示例#1
0
def create_player():
    global player
    player = Character(input("What is your name, Mr/Ms Would-be Hero?: "))
    if player.name == "Mr. Would-be Hero" or player.name == "Ms. Would-be Hero":
        print("Wow, just TOO unoriginal, I'm sorry - try again.")
        player = Character(input("What is your name, Mr/Ms Would-be Hero?: "))
    print("OK " + player.name + "! Let's go on a totally radical adventure!")
def get_number(lower, upper):
    number = input("Enter a number between ({} - {}):")

    if number < lower or number > upper or number.isdecimal():
        print("Invalid number!")
        number = input("Enter a number between ({} - {}):")
    return int(number)
示例#3
0
文件: cli.py 项目: jmsdvl/gist3.py
 def auth_dialog(self):
     try:
         with open(CONF_FILE) as conf:
             token = json.load(conf)
     except (OSError, json.JSONDecodeError, KeyError):
         print("Your token file doesn't exist or is malformed.")
         print("If you WANT to proceed anonymously, pass"
               "`-a/--anonymous` on the command line.")
         print("Or you can create a new token now. "
               "Create token? [y/n] ", end='')
         if input().lower() in ('y', 'yes'):
             username = input('Username: '******'gist3_{}'.format(id_gen())
             resp = req.post(API_BASE + '/authorizations',
                             auth=(username, password),
                             json={'scopes': ['gist'],
                                   'note': note})
             if resp.status_code == req.codes.created:
                 token = resp.json()['token']
                 with open(CONF_FILE, 'w') as conf:
                     json.dump(token, conf)
                 print('Token created & saved to {}'.format(CONF_FILE))
             else:
                 print('There was an error from github: ')
                 print(json.dumps(resp.json(), sort_keys=True, indent=4))
                 sys.exit(2)
         else:
             print('Aborting...')
             sys.exit(0)
     return AccessTokenAuth(token)
    def __init__(self):
        ##analyze frequencies
        piglatinObject = Piglatin.PigLatinTranslate()
        #print(__name__)
        if __name__ == "__main__":
            #print("from commandline")
            piglatinObject.piglatinTranslate(_("hello"))
            print(_("testing with hello == "), piglatintext)

            print(_("sentence translation"))
            piglatinObject.piglatinTranslateSentence(_("i am gowri and you are you"))

            print(_("frequency analysis"))
            print("%s" %(piglatinObject.frquencyAnalysis()))
        elif __name__ == "Piglatin_UI":
            #print("from module - testingPiglatin_commandline being the name of the module in this case")

            #Internationalization
            t = gettext.translation('English', '/locale')
            _ = t.ugettext
            
            texttotranslate = input(_("Enter text - a word: "))
            print("translated = ", piglatinObject.piglatinTranslate(texttotranslate))
            
            sentencetotranslate = input(_("Enter text - a sentence: "))
            print(_("translated text = "), piglatinObject.piglatinTranslateSentence(sentencetotranslate))

            print(_("frequency analysis"))
            print(piglatinObject.frquencyAnalysis())
示例#5
0
def testcalculator():
#Simple test average calculator that you can exit by not inputting a number or by typing 0.
    total = 0
    count = 0
    average = 0
    data = 1


    while data != 0:
        try:
            data = int(input("Enter a number or press 0 to quit: "))
            if data == 0:
                break
            else:

                try:
                
                    count += 1
                    number = data
                    total += int(number)
                    average = total / count
                    data = int(input("Enter a number or press 0 to quit: "))
                
                except ValueError:
                    break
        except ValueError:
            break

    print("The sum is {0}. The average is {1}.".format(total, average))
示例#6
0
 def chosePlayerOrServant(self, enemy, choice = True):
     print("\nVoulez vous attaquer le joueur ennemie ou ses serviteurs ?")
     while True :
         if choice == True :
             target = input("Joueur ou serviteur ?\n").lower()
             if target == "joueur" :
                 #choiceTarget = True
                 return enemy
             elif target == "serviteur" :
                 #choiceTarget = True
                 print("\nQuel serviteur ennemie voulez vous attaquer ?")
                 nameServantTarget = ""
                 while True:
                     nameServantTarget = input("Choisisez le nom du serviteur a attaquer\n").lower()
                     for cardEnemy in enemy.field :
                         if nameServantTarget == cardEnemy.name.lower() and cardEnemy not in enemy.camoField :
                             return cardEnemy
         else :
             print("\nQuel serviteur ennemie voulez vous attaquer ?")
             nameServantTarget = ""
             while True:
                 nameServantTarget = input("Choisisez le nom du serviteur a attaquer\n").lower()
                 for cardEnemy in enemy.field :
                     if nameServantTarget == cardEnemy.name.lower() and cardEnemy not in enemy.camoField :
                         return cardEnemy
示例#7
0
def add_entry():
    """Adds an entry to the diary"""
    title_string = "Title (press %s when finished)" % finish_key
    # print(title_string)
    puts(colored.yellow(title_string))
    puts(colored.green("="*len(title_string)))
    title = sys.stdin.read().strip()
    if title:
        entry_string = "\nEnter your entry: (press %s when finished)" % finish_key
        puts(colored.yellow(entry_string))
        puts(colored.green("="*len(entry_string)))
        # reads all the data entered from the user
        data = sys.stdin.read().strip()
        if data:    # if something was actually entered
            puts(colored.yellow(
                "\nEnter comma separated tags(if any!): (press %s when finished) : " % finish_key))
            puts(colored.green("="*(len(title_string)+33)))
            tags = sys.stdin.read().strip()
            tags = processTags(tags)
            puts(colored.green("\n"+"="*len(entry_string)))
            # anything other than 'n'
            if input("\nSave entry (y/n) : ").lower() != 'n':
                DiaryEntry.create(content=data, tags=tags, title=title)
                puts(colored.green("Saved successfully"))
    else:
        puts(
            colored.red("No title entered! Press Enter to return to main menu"))
        input()
        clear()
        return
示例#8
0
文件: main.py 项目: SSS135/OP_test
def work():
  power2 = lambda x: x*x
  try:
    acts = input("выход - 0, квадрат - 1, таблица - 2: ")
    act = int(acts)
    if act == 0:
      return
    #Проверка на ошибки
    if act < 0 or act > 2:
      raise Exception()
    #Ввод числа
    s = input("введите число: ")
    f = float(s)
    #Вывод квадрата
    if act == 1:
      print("квадрат: {}", power2(f))
    #Вывод таблицы
    elif act == 2:
      clen = 15
      for y in range(5):
        s = ""
        for x in range(5):
          s += str(f*x*y) + (" " * (clen-len(str(f*x*y))+1))
        print(s)
  except:
    print("ошибка ввода")
示例#9
0
def write_func():            ###Get input from user and append to table file
    
    dbase = []

    dealer = raw_input("Dealer:  ")
    hirer = raw_input("Hirer's Name:  ")
    ###     acNum to test for duplicate number
    acNum = raw_input("Loan Number:   ")
    with open('/Users/Michael/Documents/GitHub/Int-Projection/projection.csv', 'r') as compare:
        reader = csv.reader(compare)
        for row in reader:
            if str(row) == str(acNum):
                acNum = raw_input("Duplicate Loan No! Recheck and try again!")
                    
    details = raw_input("Loan Details:  ")
    agg_date = str(raw_input("Agreement Date (yyyymmdd):"))
    ###     While loop to ensure correct date format for ease of processing
    while len(agg_date) != 8:
        agg_date = str(raw_input("Invalid Date Format! Try again (yyyymmdd):"))
        
    format_date = agg_date[6:8] + '-' + agg_date[4:6] + '-' + agg_date[0:4]  #format for human eye
    amount = input("Loan Amount:   ")
    interest = input("Loan Interest:  %")
    tenure = input("No of Months: ")


    dbase = [dealer, acNum, hirer, details, amount, interest, format_date, tenure]

    with open('/Users/Michael/Documents/GitHub/Int-Projection/projection.csv', 'a') as b:
        writer = csv.writer(b)
        writer.writerow(dbase)
示例#10
0
def Dish_get_info() -> Dish:
    """ Prompt user for fields of Dish; create and return.
    """
    return Dish(
        input("Please enter the name of the dish:  "),
        float(input("Please enter the price of that dish:  ")),
        float(input("Please enter the number of calories in the dish:  ")))
示例#11
0
def escribir():
    print("Has elegido añadir un registro a la agenda")
    nombre = input("Introduce el nombre de contacto: ")
    telefono = input("Introduce su teléfono: ")

    agenda = open("agendatelefonica.csv")
    for n in range(1,40):
        linea = agenda.readline()
        lineapartida = linea.split(",")
##        print(lineapartida[0])
        if lineapartida[0] != "":
            memoria = lineapartida[0]
##    print("El numero máximo es",memoria)
    agenda.close()
    memonum = int(memoria)
    posicion = 0
    posicion = memonum + 1
    postr = str(posicion)
    print("Se ha guardado en la agenda el contacto: ",nombre,"con el número de teléfono",telefono)
    agenda = open("agendatelefonica.csv",'a')
    agenda.write(postr)
    agenda.write(",")
    agenda.write(nombre)
    agenda.write(",")
    agenda.write(telefono)
    agenda.write(",")
    agenda.write("\n")
    agenda.close()
示例#12
0
def main():
    filename = time.strftime('%A-%Y%m%d-%H-%M-%S') + '.txt'  # filename with system date time format
    f = open(filename , 'w') # opening the file with write 'w' permission
    
    f.write('+++++++++++++++++++++++++++++++++\n') # decoration with +++
    print('+++++++++++++++++++++++++++++++++')
            #To add the characters/decorating output
    days = int(input("Please enter number of days: ") )   #Asking user input
    f.write('days:  %s'%days)                             # Writing the user input 'days' to the text file
    if ( days > 0 and days <= 366 ):                      #condition to check valid days in a year
        n = math.pow(2, days-1)                           #power function ...2^n-1
        m = n / 100                                       #Converting cents to dollars
        f.write('\n+++++++++++++++++++++++++++++++++\n')
        print('+++++++++++++++++++++++++++++++++')
        f.write(' Day   Today\'s Salary \n------  -----------------\n %s    $%s'%(days,m))   #%s-substitution %(days,m) using variable to display output
        print(' Day   Today\'s Salary \n------  -----------------\n %s    $%s'%(days,m))    #%s-substitution %(days,m) using variable to display output 
    else:
        while True:                                                    #looping to check whether user has entered valid data
            f.write("\nInvalid number of days\n")               # Writing invalid number of days to text file
            print("Invalid number of days\n")
            f.write('+++++++++++++++++++++++++++++++++\n')      # decoration with +++ in the text file
            print('+++++++++++++++++++++++++++++++++\n')
            days = int(input("Please enter number of days: ") ) #Asking user input
            f.write('days:  %s'%days)
            #print ('------------------------------')  
            if ( days > 0 and days <= 366 ):
                n = int(math.pow(2, days-1))
                m = n / 100
                print ('+++++++++++++++++++++++++++++++++\n')
                f.write('\n+++++++++++++++++++++++++++++++++\n')
                f.write(' Day   Today\'s Salary\n------  -------------------\n %s    $%s'%(days,m))
                print(' Day   Today\'s Salary\n------  -------------------\n %s    $%s'%(days,m))
                break                                                      #breaking the loop
示例#13
0
def display(spectrum):
	template = np.ones(len(spectrum))

	#Get the plot ready and label the axes
	pyp.plot(spectrum)
	max_range = int(math.ceil(np.amax(spectrum) / standard_deviation))
	for i in range(0, max_range):
		pyp.plot(template * (mean + i * standard_deviation))
	pyp.xlabel('Units?')
	pyp.ylabel('Amps Squared')    
	pyp.title('Mean Normalized Power Spectrum')
	if 'V' in Options:
		pyp.show()
	if 'v' in Options:
		tokens = sys.argv[-1].split('.')
		filename = tokens[0] + ".png"
		input = ''
		if os.path.isfile(filename):
			input = input("Error: Plot file already exists! Overwrite? (y/n)\n")
			while input != 'y' and input != 'n':
				input = input("Please enter either \'y\' or \'n\'.\n")
			if input == 'y':
				pyp.savefig(filename) 
			else:
				print("Plot not written.")
		else:
			pyp.savefig(filename) 
示例#14
0
def pickchar():
	exampleprimes= [1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103,
	                1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231,
	                1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367,
	                1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487,
	                1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607,
	                1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
	                1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873,
	                1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999]
	while 1:
		try:
			char= int(input('What should be the characteristic of the ring? ')) # should input 0 or a prime number
			if char== 0 or char in exampleprimes:
				return char
			elif char< 0:
				print('That was not a valid entry. Please try again.')
				continue
			elif char< 1000 or char> 2000:
				conf= str(input('Caution: This program does not check to ensure a characteristic is prime unless it is between 1000 and 2000. Are you sure you want to use this number? Y/N: '))
				if conf in ['Y', 'Yes', 'y', 'yes']:
					return char
				else:
					continue
			else:
				print('The number you entered is not prime. Plese try again.')
				continue
		except ValueError:
			print('That was not a valid entry. Please try again.')
示例#15
0
def get_input(choices: List[Tuple]):
    all_tiles = set()
    all_commands = set()
    all_lines = set()
    for command, lines, tiles in choices:
        all_lines |= set(lines)
        all_commands.add(command)
        all_tiles |= set(tiles)
        # tile_list = ', '.join([f'{t.var} ({t.id})' for t in tiles])
        #
        # print(f"{command} ({command.id})")
        #       f"    lines: {str(lines)[1:-1]}\n"
        #       f"    tiles: {tile_list}")

    print(str(all_lines)[1:-1])
    print(', '.join([f"{c[0]} ({c[0].id})" for c in choices]))
    print(', '.join([f'{t.var} ({t.id})' for t in all_tiles]))

    while True:
        line = int(input('line: '))
        cmd_id = int(input('command: '))
        tile_id = int(input('tile: '))

        try:
            command = [c for c in all_commands if c.id == cmd_id][0]
            tile = [t for t in all_tiles if t.id == tile_id][0]
            break
        except (IndexError, ValueError):
            pass

    return line, command, tile
示例#16
0
def main():
    file = input("Enter a filename here: ");
    if os.path.exists(file):
        loadfile = open(file, "r");
        fc = loadfile.readlines();
        loadfile.close();
        newfc = [];
        for line in fc:
            line = line.replace("<female>","&#9792;");
            line = line.replace("<female/>","&#9792;");
            line = line.replace("<male>","&#9794;");
            line = line.replace("<male/>","&#9794;");
            line = line.replace("<+->","&#177;");
            line = line.replace("<+-/>","&#177;");
            line = line.replace("<plusminus>","&#177;");
            line = line.replace("<plusminus/>","&#177;");
            line = line.replace("<plusminus/>","&#177;");
            line = line.replace("<copyright>","&#169;");
            line = line.replace("<copyright/>","&#169;");
            newfc.append(line);
        loadfile = open(file, "w");
        loadfile.write("");
        loadfile.close();
        loadfile = open(file, "a");
        for line in newfc:
            loadfile.write(line);
        loadfile.close();
            
    else:
        input("Fail.");
def playPerformance(selection, performance, expression, segmentation, name='ExpressivePerformance'):
    # Store?
    # Play again?
    # View first x notes?
    while True:
        choice = util.menu('What do you want to do?', ['Play performance', 'Store expression', 'Store midi', 'View first notes of performance', 'Plot performance', 'Save plot', 'View segmentation', 'Make segmentation audible', 'Quit'])
        if choice == 0:
            seq = Sequencer()
            seq.play(performance)
        elif choice == 1:
            n = input("Enter a name for saving this performance. [{0}]\n".format(name))
            if not n == '': name = n
            tools.savePerformance(selection, expression, name)
        elif choice == 2:
            n = input("Enter a name for saving this performance. [{0}.mid]\n".format(name))
            if not n == '': name = n
            performance.exportMidi('output/{0}.mid'.format(name))
        elif choice == 3:
            for note in performance[:30]:
                print(note)
        elif choice == 4: # Plot
            visualize(segmentation, expression)
        elif choice == 5: # Save plot
            n = input("Enter a name for saving this performance. [{0}.mid]\n".format(name))
            if not n == '': name = n
            visualize(segmentation, expression, store=name)
        elif choice == 6: # View segments
            pass
        elif choice == 7: # Play segments
            pass
        elif choice == 8: # Quit
            break
示例#18
0
def main():
    try:
        
        #Change min_time HERE!!
        min_time = 4
        
        schedule_csv = input("Enter the name of the Schedule file: ") +".csv"
        transaction_csv = input("Enter the name of the Transaction file: ") +".csv"
        save_file_name = input("Enter the name of the file to which we should save: ")+".csv"
        schedule_list = create_list_from_csv(schedule_csv)
        transaction_list = create_list_from_csv(transaction_csv)

        
        #schedule_list = create_list_from_csv("Raw-Schedule-Adherance-347.csv")
        #transaction_list = create_list_from_csv("Boardings and Tag-offs by Stop.csv")
        bus_list = create_bus_list(schedule_list)
        bus_dict = create_bus_dict_from_list(bus_list)
        route_dict = generate_bus_route_dict(bus_dict, schedule_list)
        #stop_list = create_stop_list(schedule_list)
        #print(transaction_list)
        stop_dict = create_stop_dict(schedule_list)
        add_stops_to_bus_dict_from_dict(bus_dict, stop_dict, route_dict)
        add_start_leave_times(bus_dict, schedule_list)
        add_transaction_times_to_bus_dict(bus_dict, transaction_list, min_time)
        #print(time_comparison("7:17:59", "7:18:01", "7:19:15", 4, "2/03/2015", "2/03/2015"))
        
        #save_summary_to_file("347 Route Summary.txt", bus_dict, route_dict, stop_dict)
        
        save_summary_to_file(save_file_name, bus_dict, route_dict, stop_dict)
    except:
        print(traceback.format_exc())
        input("Something went bad, get Richard")
def if_not_stuff():
    x = input("Please enter some text")
    if x:
        print("You entered '{}'". format(x))
    else:
        print("You did not enter anything")

    # doesn't work in terminal
    print(not False)
    print(not True)

    age = int(input("How old are you?"))
    if not(age < 18):
        print("""You are old enough to vote.
            Please put an X in the box""")
    else:
        print("Please come back in {0} years". format(18 - age))

    parrot_type = "Norwegian Blue"
    letter = input("Enter a character: ")
    if letter in parrot_type:
        print("Give me a {}, Bob". format(letter))
    else:
        print("I don't need that letter")
    return "Just more thins with if, else and not"
示例#20
0
def main():
    # We load the spector dataset as a pandas dataframe
    # Of course, you can load your own datasets 
    data = sm.datasets.spector.load_pandas()
    
    # We define y as the endogenous variable, and x as the 
    # exogenous variable.
    # Note that if you load your own data, the methods endog 
    # and exog will not be available and you will have to 
    # explicitly define the endogenous and exogenous variables
    y, x = data.endog, data.exog
    
    # We do the regression
    reg = sm.OLS(y, x).fit()
    
    # And here we can see the results in a very nice looking table
    print('SUMMARY -------------------------------------------')
    print((reg.summary()))
    
    # We can only take a look at the parameter values though
    print('PARAMETERS ----------------------------------------')
    print((reg.params))
    
    # We can also extract the residuals
    print('RESIDUALS -----------------------------------------')
    print((reg.resid))
    
    # This line is just to prevent the output from vanishing when you
    # run the program by double-clicking
    input('Done - Hit any key to finish.')
示例#21
0
文件: user.py 项目: Raphux/passhport
def prompt_create():
    """Prompt user to obtain data for request"""
    name = input("Name: ")
    sshkey = input("SSH Key: ")
    comment = input("Comment: ")

    return {"<name>": name, "<sshkey>": sshkey, "--comment": comment}
示例#22
0
    def liquidateAssets(self, player, other, amount):
        """Prompts player to liquidate his assets until given cash amount is
        reached."""
        print("{}'s Properties".format(player))
        print('=' * (len(player) + 13))

        player = self.view.getPlayer(player)
        for tile in player.properties:
            print(tile)

        while player.cash < amount:
            print("Amount needed: {}{}".format(self.view.currency['symbol'],
                                               amount - player.cash))
            if not player.properties:
                print("Looks like you're out of properties to mortgage. Bankrupt!")
                self.view.playerBankrupt(player.name, other)
                break
            else:
                print("\nEnter the names of properties you wish to mortgage.\n"
                      "Type DONE when you're done.")
                mortgageList = []
                prop = input(prompt)

                while prop != 'DONE':
                    mortgageList.append(prop)
                    prop = input(prompt)

                for tile in mortgageList:
                    self.view.controller.playerMortgage(player.name, tile)

                print("You now have {}{}.".format(self.view.currency['symbol'],
                                                  player.cash))
def imc_creds():
    ''' This function prompts user for IMC server information and credentuials and stores
    values in url and auth global variables'''
    global url, auth, r
    imc_protocol = input(
        "What protocol would you like to use to connect to the IMC server: \n Press 1 for HTTP: \n Press 2 for HTTPS:")
    if imc_protocol == "1":
        h_url = 'http://'
    else:
        h_url = 'https://'
    imc_server = input("What is the ip address of the IMC server?")
    imc_port = input("What is the port number of the IMC server?")
    imc_user = input("What is the username of the IMC eAPI user?")
    imc_pw = input('''What is the password of the IMC eAPI user?''')
    url = h_url + imc_server + ":" + imc_port
    auth = requests.auth.HTTPDigestAuth(imc_user, imc_pw)
    test_url = '/imcrs'
    f_url = url + test_url
    try:
        r = requests.get(f_url, auth=auth, headers=headers)
    # checks for requests exceptions
    except requests.exceptions.RequestException as e:
        print("Error:\n" + str(e))
        print("\n\nThe IMC server address is invalid. Please try again\n\n")
        imc_creds()
    if r.status_code != 200:  # checks for valid IMC credentials
        print("Error: \n You're credentials are invalid. Please try again\n\n")
        imc_creds()
    else:
        print("You've successfully access the IMC eAPI")
示例#24
0
def mentre3(): #Definim la funcio mentre3, que es una funcio secundaria de mentre
    suma = 0 #La variable "suma" tindra aquest valor"
    n = input("Sumarem tots els nombres que introduiu fins que poseu 999: ") #Definim la variable "n" com un input. Sera interpretat com un nombre.
    while n != 999: #Mentre es compleixi aquesta condicio
            suma = suma + n #La variable suma augmentara en funcio de "n"
            n = input("Fins que no introdueixis 999 seguirem sumant nombres: ") #Tornem a definir la variable "n" com un input. Sera interpretat com un nombre.
    print "\nLa suma dels nombres es: ", suma #Quan les condicions del while no es compleixin, imprimirem el resultat
示例#25
0
def vending_machine():
    deposit = 0 
    #get the cost of the item(s) purchased
    cost = eval(input('Enter the cost (in cents):\n'))
    #ask for money to pay when cost is greater than 0 and ask for more deposit when not enough
    while deposit < cost:
        deposit += eval(input('Deposit a coin or note (in cents):\n'))
    change = deposit - cost
    #Give change when due
    if change > 0:
        print('Your change is:')
        
        for i in (100, 25, 10, 5, 1):
            #check decreasingly if one of the possible coin is part of the change
            if change >= i:
                #specify for change more than or equal to $1 as in dollar               
                if i == 100:
                    print(change//i, ' x ', '$1',sep = '')
                else:
                    print(change//i, ' x ', i,'c',sep = '')
                change -= (change//i)*i
                #check until chanege is 0 then break loop
                if change == 0:
                    break
            else:
                continue
示例#26
0
def main():
    T = int(input())
    
    for _ in range(T):
        n = int(input())
        side_lengths = list(map(int, input().split()))
        print('Yes' if is_valid(side_lengths) else 'No')
示例#27
0
def main():
	board = chess.Board()
	move_selector = MoveSelector(MAX_ITER_MTD, MAX_DEPTH, config.MAX_SCORE)

	color_choice = input("Do you want to play as black or white? [W/B]: ")
	while color_choice is not "W" and color_choice is not "B":
		color_choice = input("Invalid choice, please enter W for white or B for black: ")

	print(pp_board(board))

	if color_choice == "W":
		while True:
			if board.is_game_over():
				break

			handle_human_move(board)

			if board.is_game_over():
				break

			handle_ai_move(board, move_selector)
	else:
		while True:
			if board.is_game_over():
				break

			handle_ai_move(board, move_selector)

			if board.is_game_over():
				break

			handle_human_move(board)

	print(board.result())
示例#28
0
def kullanici_adini_guncelle():
    """Kullanıcıdan isim alıp ayarlara yazdırmaya gönderir"""
    veri = ayar_oku()
    veri["son_kullanan"] = input("Kullanıcı Adınız: ")
    while not veri["son_kullanan"] or len(veri["son_kullanan"]) > 9:
        veri["son_kullanan"] = input("1 ile 9 karakter uzunluğunda yazın: ")
    ayar_yaz(veri)
示例#29
0
def main():
    n = int(input())
    xs = [int(i) for i in input().strip().split()]
    assert len(xs) == n

    result = solve(xs)
    print(result)
示例#30
0
    def preloop(self):
        print("You are playing Monopoly!\n"
              "Style: {}\n"
              "Begin game?".format(self.view.style))

        if not self.confirmAction():
            raise SystemExit

        print("Enter the number of players (> 1).")
        while True:
            num = input(self.prompt)
            try:
                num = int(num)
                if num <= 1:
                    raise ValueError

                self.view.numPlayers = num
            except ValueError:
                print("Try again.")
                continue

            break

        for i in range(self.view.numPlayers):
            print("Player #{}".format(i + 1))
            print("What is your name?")
            name = input(self.prompt)
            print("What piece will you use?")
            piece = input(self.prompt)
            self.view.playerAdd(PlayerRep(name, piece, 0, self.view.currency['defaultAmount']))

        print("\nIt's {}'s turn.".format(self.view.players[self.turn].name))
示例#31
0
# code for matrix input from user

R = int(input("Enter the number of rows:"))#sıra
C = int(input("Enter the number of columns:"))#sütun

# Initialize matrix
matrix = []
print("Enter the entries rowwise:")

# For user input
for i in range(R):  # A 'for loop' for row entries
    a = []
    for j in range(C):  # A 'for loop' for column entries
        a.append(int(input()))
    matrix.append(a)

# For printing the matrix
for i in range(R):
    for j in range(C):
        print(matrix[i][j], end=" ")
    print()
示例#32
0
def dis(n, l):
    flag = 0
    c = []
    for i in range(n):
        if (l[i] == 1):
            c.append(i)
    for j in range(1, len(c)):
        if c[j] - c[j - 1] < 6:
            return ("NO")
            flag = 1
            break
    if flag == 0:
        return ("YES")


for _ in range(int(input())):
    n = int(input())
    l = list(map(int, input().split()))
    print(dis(n, l))
示例#33
0
n = int(input('Put length of pyramid '))

print((n - 2) * ' ', 1)
d = n - 2
for i in range(1, n + 1):
    print(d * ' ', end='')
    for s in range(1, i + 1):
        print(s, sep='', end='')
    for j in reversed(range(1, i + 2)):
        print(j, sep='', end='')
    print()
    d -= 1
    if d == -1:
        break
示例#34
0
a = int(input())
b = int(input())
c = int(input())

# определим гипотинузу
if (a >= b) and (a >= c):
    g = a
    k1 = b
    k2 = c
elif (b >= a) and (b >= c):
    g = b
    k1 = a
    k2 = c
elif (c >= a) and (c >= b):
    g = c
    k1 = a
    k2 = b

if k1**2 + k2**2 == g**2:
    print('rectangular')
elif g**2 - k1**2 - k2**2 - 2 * k1 * k2 > 0:
    print('impossible')
elif k1**2 + k2**2 - g**2 > 0:  # cos > 0 - острый
    print('acute')
else:
    print('obtuse')
示例#35
0
# -*- coding: utf-8 -*-
"""
Created on Fri May 18 17:31:57 2018

@author: evan9
"""

#Digits in Fibonacci Sequence
k = int(input('Digits in Fibonacci Sequence: '))

list1 = [1, 1]
for i in range(k - 2):
    list1.append(list1[i] + list1[i + 1])
for j in list1:
    print(j)
new_list = list(map(int, input().split()))
new_one = new_list[-1]
new_list.insert(0, new_one)
new_list.pop(-1)
print(*new_list)
示例#37
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
s = input()
t = input()
print (t.upper()) if s == "Y" else print (t)
from os import spawnl
import sys
sys.stdin = open("/Users/hyojinjeong/Algorithm/greedy/warehouse_cleanup.txt",
                 "r")
n = int(input())
box = list(map(int, input().split()))
m = int(input())
box.sort()
for i in range(m):
    box[0] += 1
    box[n - 1] -= 1
    box.sort()
print(box[n - 1] - box[0])
示例#39
0
menuList = []
priceList = []

def showBill():
    print("My food".center(20,"-"))
    for number in range(len(menuList)):
        print(menuList[number],priceList[number])

def total():
    total = 0
    for price in priceList:
        total = total + int(price)
    print("total Price = %d THB"%(total))


while True:
    menuName = input("Please Enter menu:")
    if(menuName.lower() == "exit"):
        break
    else:
        menuPrice = input("Price :")
        menuList.append(menuName)
        priceList.append(menuPrice)
showBill()
total()
示例#40
0
import sys

input = sys.stdin.readline
n = int(input())

wine = [0]
for i in range(n):
    wine.append(int(input()))

dp = [0]
dp.append(wine[1])
if n > 1:
    dp.append(wine[1] + wine[2])

for i in range(3, n + 1):
    dp.append(
        max(dp[i - 1], dp[i - 2] + wine[i], dp[i - 3] + wine[i - 1] + wine[i]))
    #이번에 안마시는 경우, 세번전 두번전에 마시고 이번에 마시는 경우, 세번전 한번전에 마시고 이번에 마시는 경우

print(dp[n])
示例#41
0
                p5score = p5score + base_score + p5result
            elif p5result < p5bid:
                p5score = p5score - (p5bid - p5result)
            else:
                p5score = p5score - (p5result - p5bid)
    except NameError:
        pass
    try:
        print('Score after round ' + str(p))
        print(playerlist[0] + ": " + str(p1score))
        print(playerlist[1] + ": " + str(p2score))
        print(playerlist[2] + ": " + str(p3score))
        print(playerlist[3] + ": " + str(p4score))
        print(playerlist[4] + ": " + str(p5score))
        print(playerlist[5] + ": " + str(p6score))
    except IndexError:
        pass


## starting the game
howManyPlayers()
howManyRounds()

while p != k:
    increaseRounds()
    roundNumberThree()
    scoring()
    wait = input("PRESS ENTER TO CONTINUE.")
else:
    print('Game Over')
示例#42
0
height = input("How tall are you, in inches? ")
height = int(height)
if height >= 36:
    print("yes")
else:
    print("No")
示例#43
0
import re

pattern = input("Enter a regular expression:")
fhand = open('mbox.txt')

count = 0
for line in fhand:
    if re.search(pattern, line):
        count += 1

print("mbox.txt had %d lines that matched %s" % (count, pattern))
示例#44
0
def scoring():
    global p1score, p2score, p3score, p4score, p5score, p6score
    print('Round ' + str(p) + '. Insert results.')
    while True:
        try:
            p1result = int(input(playerlist[0] + ': '))
        except ValueError:
            print("Insert a number.")
            continue
        if p1result > z:
            print("You couldn't bid more than " + str(z))
            continue
        else:
            break
    while True:
        if p1result == z:
            p2result = 0
            p3result = 0
            p4result = 0
            p5result = 0
            p6result = 0
            break
        try:
            p2result = int(input(playerlist[1] + ': '))
        except ValueError:
            print("Insert a number.")
            continue
        if p2result > z:
            print("You couldn't bid more than" + str(z))
            continue
        else:
            break
    while True:
        if p1result or p2result == z:
            p3result = 0
            p4result = 0
            p5result = 0
            p6result = 0
            break
        try:
            p3result = int(input(playerlist[2] + ': '))
        except ValueError:
            print("Insert a number.")
            continue
        if p3result > z:
            print("You couldn't bid more than" + str(z))
            continue
        else:
            break
    while True:
        if p1result or p2result or p3result == z:
            p4result = 0
            p5result = 0
            p6result = 0
            break
        try:
            p4result = int(input(playerlist[3] + ': '))
        except ValueError:
            print("Insert a number.")
            continue
        if p4result > z:
            print("You couldn't bid more than" + str(z))
            continue
        else:
            break
    while True:
        if p1result or p2result or p3result or p4result == z:
            p5result = 0
            p6result = 0
            break
        try:
            p5result = int(input(playerlist[4] + ': '))
        except ValueError:
            print("Insert a number.")
            continue
        if p5result > z:
            print("You couldn't bid more than" + str(z))
            continue
        else:
            break
    while True:
        if p1result or p2result or p3result or p4result or p5result == z:
            p6result = 0
            break
        try:
            p5result = int(input(playerlist[4] + ': '))
        except ValueError:
            print("Insert a number.")
            continue
        if p5result > z:
            print("You couldn't bid more than" + str(z))
            continue
        else:
            break
    try:
        if p == 1:
            if p1result == p1bid:
                p1score = base_score + p1result
            else:
                p1score = start_score - p1bid
            if p2result == p2bid:
                p2score = base_score + p2result
            else:
                p2score = start_score - p2bid
            if p3result == p3bid:
                p3score = base_score + p3result
            else:
                p3score = start_score - p3bid
            if p4result == p4bid:
                p4score = base_score + p4result
            else:
                p4score = start_score - p4bid
            if p5result == p5bid:
                p5score = base_score + p5result
            else:
                p5score = start_score - p5bid
            if p6result == p6bid:
                p6score = base_score + p6result
            else:
                p6score = start_score - p6bid
        else:
            if p1result == p1bid:
                p1score = p1score + base_score + p1result
            elif p1result < p1bid:
                p1score = p1score - (p1bid - p1result)
            else:
                p1score = p1score - (p1result - p1bid)
            if p2result == p2bid:
                p2score = p2score + base_score + p2result
            elif p2result < p2bid:
                p2score = p2score - (p2bid - p2result)
            else:
                p2score = p2score - (p2result - p2bid)
            if p3result == p3bid:
                p3score = p3score + base_score + p3result
            elif p3result < p3bid:
                p3score = p3score - (p3bid - p3result)
            else:
                p3score = p3score - (p3result - p3bid)
            if p4result == p4bid:
                p4score = p4score + base_score + p4result
            elif p4result < p4bid:
                p4score = p4score - (p4bid - p4result)
            else:
                p4score = p4score - (p4result - p4bid)
            if p5result == p5bid:
                p5score = p5score + base_score + p5result
            elif p5result < p5bid:
                p5score = p5score - (p5bid - p5result)
            else:
                p5score = p5score - (p5result - p5bid)
    except NameError:
        pass
    try:
        print('Score after round ' + str(p))
        print(playerlist[0] + ": " + str(p1score))
        print(playerlist[1] + ": " + str(p2score))
        print(playerlist[2] + ": " + str(p3score))
        print(playerlist[3] + ": " + str(p4score))
        print(playerlist[4] + ": " + str(p5score))
        print(playerlist[5] + ": " + str(p6score))
    except IndexError:
        pass
import socket
import os
import time
import sys

TCP_IP = sys.argv[2]
FILE_PORT = int(sys.argv[3])
DATA_PORT = int(sys.argv[3]) + 1
buf = 1024
directory = sys.argv[1]
while True:
    info = input("TCP Client" + "\n")
    if info == "q":
        break
    if info == "l":
        print(os.listdir(directory))
    if info[0] == "e":
        start = time.time()
        try:
            file_name = info[1:]
            file_name = file_name.replace(" ", "")
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((TCP_IP, FILE_PORT))
            sock.send(bytearray(file_name, "utf-8"))
            sock.close()
            print("Sending %s ..." % file_name)
            f = open(directory + file_name, "rb")
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((TCP_IP, DATA_PORT))
            data = f.read(buf)
            while (data):
def detection_crateres(moon_original):
    """
    Lance l'interface graphique
    Entrée : image de Lune (MxNx1)
    Sortie :
        - Liste des codes UAI des cratères identifiés
        - Liste des informations utiles sur les cratères (centre_y, centre_x, b, a, inclinaison) (pxl)
        - Centre du disque lunaire en y (pxl)
        - Centre du disque lunaire en x (pxl)
        - Rayon du disque lunaire (pxl)
    """
    # moon de taille [MxNx1]
    # renvoie une liste de cratères avec leur centre en pixel + centre-rayon du disque

    moon = moon_original.copy()
    moon_light = rgb2hsv(moon)[:, :, 2]
    moon_light = exposure.rescale_intensity(moon_light, in_range=(0.4, 1))

    # On trouve d'abord le disque lunaire
    print("--- Détection du disque lunaire ---")
    t0 = time()
    xc, yc, R = detection_disque(moon_light)
    resolution = 1730 / R  # en km/px
    print("Centre du disque, rayon (pxl) : ", xc, yc, R)
    # print("Détection disque : ", time()-t0)
    t0 = time()

    part_surface = 0.9

    mask_r, mask_c = draw.circle(
        yc, xc, R * part_surface, shape=moon.shape
    )  # le masque est un peu plus petit que le disque (0.8*R)
    mask = np.zeros_like(moon_light, dtype="bool")
    mask[mask_r, mask_c] = True
    # print("Création d'un masque : ", time()-t0)

    # On estime la proportion des contours des cratères par rapport à la surface totale de la Lune
    ratio = (
        72 * part_surface * part_surface
    )  # estimation de : longueur périmètres cratères (km) / diamètre Lune (km)
    perimetre_tot = ratio * (R * 2)  # estimation perimetre tot de cratère
    surface = np.pi * R * R
    frac = perimetre_tot / surface
    frac_cible = frac * 0.3
    # print("Fraction de pixels à considérer : ", frac_cible)

    # Détecte des contours (on pourra modifier les parametres)
    print("--- Détection des contours ---")
    t0 = time()
    edges = feature.canny(
        moon_light,
        sigma=R / 1000,
        low_threshold=1 - frac_cible,
        high_threshold=1 - frac_cible / 4,
        use_quantiles=True,
        mask=mask,
    )
    print("Application du filtre de canny (s) : ", time() - t0)
    plt.show()

    # Décompose les contours par composantes connexes
    # labels est une liste de contours qui sont séparés, num est le nombre de contours différents qu'on a détecté
    t0 = time()
    labels, num = measure.label(edges, return_num=True, connectivity=2)
    # print("Décomposition en composantes connexes : ", time()-t0)

    S0 = 0
    S1, i = 0, 0
    S2, j = 0, 0

    keys = []
    crat_infos = []
    liste_crateres = list(range(1, num))

    # Début de la détection semi-automatique des cratères
    print(
        "--- Début de la détection semi-automatique des cratères ---\nMode 1 : les cratères sont affichés un par un. (long)\nMode 2 : les cratères sont affichés en même temps\n Mode 2 conseillé"
    )
    mode = None
    while mode != "1" and mode != "2":
        mode = input("Mode ? (1/2) ")
        if mode == "1":
            shuffle(liste_crateres)
        elif mode == "2":
            pass
        else:
            print("rep must be 1 or 2")
    moon3 = moon_original.copy()
    num_crat = 1
    for l in liste_crateres:
        # print('----------')
        print(l, "/", num)
        t0 = time()
        y, x = np.nonzero(labels == l)
        S0 += time() - t0
        t0 = time()
        res, b, theta = regression_elliptique3(x, y, xc, yc, R)
        if res is not None:
            c_x, c_y, a = res.x[:3]
            # res = regression_elliptique2(x,y)
            # c_x, c_y, a, b, theta = [res.x[i] for i in range(5)]
            ecart_type = np.sqrt(res.cost / len(x))

            S1 += time() - t0
            i += 1
            if (ecart_type * resolution < 1 and a * resolution <
                    20):  # l'écart type est de moins de 100 km
                print("Cratère détecté, diamètre du cratère : ",
                      a * resolution)
                t0 = time()
                if mode == "1":
                    ax = plt.subplot()
                    moon3 = moon_original.copy()
                    ax.text(int(c_x), int(c_y), "Ici")
                else:
                    plt.text(int(c_x), int(c_y), num_crat)
                    num_crat += 1
                ell_y, ell_x = draw.ellipse_perimeter(
                    int(c_y),
                    int(c_x),
                    int(b),
                    int(a),
                    orientation=theta,
                    shape=moon.shape,
                )
                moon3[ell_y, ell_x] = [0, 255, 0]
                if 0 <= int(c_y) < moon3.shape[0] and 0 <= int(
                        c_x) < moon3.shape[1]:
                    moon3[int(c_y), int(c_x)] = [0, 255, 0]

                if mode == "1":
                    io.imshow(moon3)
                    plt.show()

                S2 += time() - t0
                j += 1

                if mode == "1":
                    rep = input(
                        "Voulez-vous garder ce cratère (o/n ou q pour quitter) ? "
                    )
                    if rep == "o":
                        pattern = re.compile(
                            "[A-Z]{2,2}[0-9]{4,4}[A-Z][0-9]{5,5}[A-Z]")
                        res = None
                        while res is None:
                            code = input(
                                "code L.U.N du cratère ? ").upper().strip()
                            res = pattern.search(code)
                        code = res[0]
                        print(code)
                        keys.append(code)
                        crat_infos.append((c_y, c_x, b, a, theta))
                        print("Cratère ajouté !")
                    elif rep == "q":
                        break
                else:
                    crat_infos.append((c_y, c_x, b, a, theta))

    if mode == "2":
        rep = None
        crat_infos2 = []
        while rep != "Q":
            io.imshow(moon3)
            num_crat = 1
            for crat in crat_infos:
                c_y, c_x, _, _, _ = crat
                plt.text(int(c_x), int(c_y), num_crat)
                num_crat += 1
            plt.show()
            rep = (input(
                "Entrez le numéro du cratère suivi de son code LUN (numéro,code) ou q pour terminer\n"
            ).upper().split(","))
            pattern_code = re.compile(
                "[A-Z]{2,2}[0-9]{4,4}[A-Z][0-9]{5,5}[A-Z]")
            pattern_num = re.compile("[0-9]*")
            if len(rep) > 1:
                num = pattern_num.search(rep[0])
                code = pattern_code.search(rep[1])
                if num is None or code is None:
                    print("Pattern not found")
                else:
                    num = num[0]
                    code = code[0]
                    num = int(num) - 1
                    if num >= 0 and num < len(crat_infos):
                        keys.append(code)
                        crat_infos2.append(crat_infos[num])
                        print("Cratère ajouté ! ", len(keys),
                              " cratère(s) enregistré(s).")
                    else:
                        print("Numéro incorrect")
            elif rep[0] != "Q":
                print("Pas compris, réessayez")
            elif rep[0] == "Q":
                rep = rep[0]
        crat_infos = list(crat_infos2)

    print("Terminé !\n")

    crat_infos = np.array(crat_infos)
    return keys, crat_infos, yc, xc, R
row = int(input("Enter the number of rows: "))
column = int(input("Enter the number of columns: "))
temp_list = []
final_list = []
for count in range(row * column):
    value = int(input("Enter the value: "))
    temp_list.append(value)
    if not (count + 1) % column:
        # final_list.append(temp_list) # This will append a pointer to the temp_list (shallow copy)
        final_list.append(temp_list.copy())
        temp_list.clear()

print(final_list)
示例#48
0
print('Ingrese dos numeros')
num1 = int(input('Digite el primer numero: '))
num2 = int(input('Digite el segundo numero: '))
print('El producto de ',num1,' por ',num2,' es: ',num1*num2)
示例#49
0
madeBeasu = lambda end: list(
    range(5, end + 1, 5
          ))  # 컴프리핸션 == [num for num in range(1, end+1) if num % 5 == 0]
# 람다함수를 사용함으로서 우항은 더이상 변수x 함수명! range에서 end+1 주의!!
# lambda 매개변수 : return 값

endNum = int(input("입력 받은 수 까지의 5의 배수를 만듭니다, 어디까지 : "))
numList = madeBeasu(endNum)
print(numList)
addNum = int(input("위 리스트의 모든 원소에 더할 값은 : "))
print(list(map(lambda num: num + addNum, numList)))
# WORKS BUT IT'S TOO SLOW

num_cases = int(input())

for i in range(num_cases):
    if i > 0:
        print()
    rows, cols, days = [int(x) for x in input().split()]
    grid = []
    for j in range(rows):
        grid.append(list(input()))

    for d in range(days):
        new_grid = [['' for _ in range(cols)] for _ in range(rows)]
        for r in range(rows):
            for c in range(cols):
                for o in range(4):
                    check = {0:[0,1], 1:[1,0], 2:[0,-1], 3:[-1,0]}[o]
                    check_r = r + check[0]
                    check_c = c + check[1]
                    if check_r < 0 or check_r > rows - 1 or check_c < 0 or check_c > cols - 1:
                        continue
                    
                    if {"R": "S", "S": "P", "P": "R"}[grid[check_r][check_c]] == grid[r][c]:
                        new_grid[r][c] = grid[check_r][check_c]
                        break

                if new_grid[r][c] == '':
                    new_grid[r][c] = grid[r][c]
        
        grid = [[col for col in row] for row in new_grid]
# Output:
# Print appropriate text for each photo in a new line.

def profilePictureOp(length, width, minimumLength = 0):
    """Returns "Accepted , "UPLOAD ANOTHER" or ""CROP IT" after checking aginst minimumLength"""

    if length < minimumLength or width < minimumLength:
        return "UPLOAD ANOTHER"
    else:
        if length == width:
            return "ACCEPTED"
        else:
            return "CROP IT"


l = int(input())
n = int(input())

photoList = []

# print(l , n)

for _ in range(n):
    photoList.append(list(map(int, input().split(' '))))

# print (photoList)

for i in range(len(photoList)):
    print(profilePictureOp(photoList[i][0], photoList[i][1], l))

示例#52
0
t = int(input())
for i in range(0, t):
    x = [int(y) for y in input().strip().split(' ')]
    n, m = x[0], x[1]
    lr, p = {}, []
    for j in range(0, n):
        x = [int(y) for y in input().strip().split(' ')]
        lr[x[0]] = x[1]
    for k in range(0, m):
        val = int(input())
        p.append(val)

    output = []
    for m in p:
        wtime = -1
        for key in sorted(lr.keys()):
            if m >= key and m < lr[key]:
                wtime = 0
                break
            if m < key:
                wt = key - m
                if wtime == -1 or wt < wtime:
                    wtime = wt
        output.append(wtime)
    print(output)

dc = {1: 'a', 2: 'b', 0: 'c'}
import random
nilaimax = input("Masukkan nilai minimum yang ingin di input : ")
banyakdata = input("Masukkan banyaknya data yang diinginkan : ")
i = 0
jumlah = 0

while i < banyakdata:
    data_n = random.randrange(1, nilaimax, 1)
    jumlah = jumlah + data_n
    i = i + 1
    print("data ke %s adalah %s") % (i, data_n)
rerata = jumlah / banyakdata
print("\nrerata dari %s data random adalah %s") % (banyakdata, rerata)
line = input().split()
line = list(map(int, line))

l = line[0]
r = line[1]

if l==0 and r==0:
	print("Not a moose")
elif l==r:
	print("Even ",l*2)
else:
	print("Odd ",max(line)*2)
示例#55
0
str1 = input("enter the string")

str2 = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

str3 = '1234567890'

alpha = 0

digit = 0

for i in str1:
    if i in str2:
        alpha = alpha + 1

for j in str1:
    if j in str3:
        digit = digit + 1

print(alpha)
print(digit)
示例#56
0
import math

class Solver:
    def __init__(self):
        pass

    def calculate(self, a, b, c):
            d = b ** 2 - 4 * a * c
            if d >= 0:
                disc = math.sqrt(d)
                root1 = (-b + disc) / (2 * a)
                root2 = (-b - disc) / (2 * a)
                print (root1, root2)
            else:
                print ("invalid quadratic equation")

while True:
    a = int(input("a "))
    b = int(input("b "))
    c = int(input("c "))

    Solver().calculate(a, b, c)
示例#57
0
from collections import deque
import copy
'''
      아래의 구문은 input.txt 를 read only 형식으로 연 후,
      앞으로 표준 입력(키보드) 대신 input.txt 파일로부터 읽어오겠다는 의미의 코드입니다.
      여러분이 작성한 코드를 테스트 할 때, 편의를 위해서 input.txt에 입력을 저장한 후,
      아래 구문을 이용하면 이후 입력을 수행할 때 표준 입력 대신 파일로부터 입력을 받아올 수 있습니다.

      따라서 테스트를 수행할 때에는 아래 주석을 지우고 이 구문을 사용하셔도 좋습니다.
      아래 구문을 사용하기 위해서는 import sys가 필요합니다.

      단, 채점을 위해 코드를 제출하실 때에는 반드시 아래 구문을 지우거나 주석 처리 하셔야 합니다.
'''
#sys.stdin = open("input.txt", "r")

T = int(input())
# 여러개의 테스트 케이스가 주어지므로, 각각을 처리합니다.
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]


def dfs(x, y, kk, cnt):
    global result
    if result < cnt + 1:
        result = cnt + 1
    visited[x][y] = 1
    for dir in range(4):
        nx = x + dx[dir]
        ny = y + dy[dir]
        if not (0 <= nx < n and 0 <= ny < n):
            continue
示例#58
0

def add_to_list(item):
    shopping_list.append(item)
    print("Added! List has {} items".format(len(shopping_list)))


def show_list():
    print("Here is your list")
    for item in shopping_list:
        print(item)


show_help()
while True:
    new_item = input("> ")

    if new_item == 'DONE':
        break
    elif new_item == 'HELP':
        show_help()
        continue
    elif new_item == 'SHOW':
        show_list()
        continue

    add_to_list(new_item)

show_list()

# Code Challenge of Looping and Join
示例#59
0
y = int(input())
b = "X++"
c = "--X"
x = 0
i = 1
for i in range(y):
    
    a = input()
    
    if b in a:
        x=x+1
    
    elif c in a:
        x=x-1
print("answer : ")
print(x)
    
    
示例#60
0
@author: JS
"""


#Imports our required modules
import os
import sys
import time
from datetime import datetime
import bs4 
import requests
from bs4 import BeautifulSoup


#User input to request stock prices
stock = input("Please type in a stock ticker symbol to query:\n")


#Fetching the name for use later in the application
def getStockName():
    r=requests.get(f'https://finance.yahoo.com/quote/{stock}')
    soup=bs4.BeautifulSoup(r.text, "html.parser")
    name=soup.find_all('div',{'class':'My(6px) Pos(r) smartphone_Mt(6px)'})[0].find('span').text 
    name = soup.text
    sep = 'Quote'
    name = name.split(sep, 1)[0]
    return name


#Definining our function getPrice that will go and look for a specific element on the below URL
#The input from the user is now converted into a literal sting with the 'f' at the start of the string.