text
stringlengths
37
1.41M
# This is a list pets = ["doggo", "cat", "iguana"] # We access list variables by their index, which starts at 0 dog = pets[0] # If you give a negative INDEX, you access the end of the list demonSpawn = pets[-1] # If you want to access a range of values in a list, # you use a number and a colon : and then end of the range you want # to access myFavoriteTwoAnimals = pets[0:2] demonSpawns = pets[] # If you start your index range with negative,it starts at end of list
# store dictionaries in a list + # make dictionary(ies) + # delete something on a list + # add something to a list + # view everything on the list + # have a way to quit + # can't stop won't stop until Q :check + # MAKE THEM IN FUNCTIONS check in progress + toDoList = [] def welcomeMessage(): message = """\n ()()()()()()()()()(()()) Welcome to my To Do App! Press 1 to Add Task Press 2 to Delete Task Press 3 to View All Tasks Press q to Quit Program ()()()()()()()()()()()() \n""" return print(message) # I understand, question: how does the toDoDictionary know to put together the "title":"priority" key:value pair? def addFunction(): toDoDictionary = {} addTask = input("Enter task: ") priorityOfTask = input("Assign priority: ") toDoDictionary["title"] = addTask toDoDictionary["priority"] = priorityOfTask toDoList.append(toDoDictionary) return print("I added * %s * to your list of things to do" % addTask) # I understand def viewFunction(): count = 1 print("Your tasks") for task in toDoList: print("%d. %s = %s" % (count, task["title"], task["priority"])) count += 1 return print("Your tasks") # I understand def delFunction(): print("Here are your tasks") viewFunction() delTask = int(input( "What task would you like to delete (choose the index)\n")) taskToDeleteIndex = delTask - 1 taskThatIsGettingDeleted = toDoList[taskToDeleteIndex] del toDoList[taskToDeleteIndex] return print("I deleted %s off your list" % taskThatIsGettingDeleted) # I understand def determineTask(userChoice): whatTheyChose = "" if(userChoice == "1"): whatTheyChose = addFunction() elif(userChoice == "2"): whatTheyChose = delFunction() elif(userChoice == "3"): whatTheyChose = viewFunction() # elif(userChoice == "q"): else: print("Bad key ") whatTheyChose = choice return whatTheyChose choice = "" while(choice != "q"): welcomeMessage() userChoices = input("What would you like to do?") outcome = determineTask(userChoices) choice = outcome
""" Remove reactions with a given stoichiometry from a table, writing a new table. """ import argparse from ast import literal_eval from table_utilities import read_reaction_table, read_component_table, write_reaction_table parser = argparse.ArgumentParser( description='Remove reactions with a given stoichiometry from a table, writing a new table.' ) parser.add_argument('stoichiometry_file', help='file of stoichiometries to exclude') parser.add_argument('input_file', help='input reaction table') parser.add_argument('output_file', help='clean reaction table file to write') args = parser.parse_args() stoichiometries, parents, reversibilities = read_reaction_table(args.input_file) bad_stoichiometries = map(literal_eval,read_component_table(args.stoichiometry_file)) to_remove = [] for reaction, stoichiometry in stoichiometries.iteritems(): if stoichiometry in bad_stoichiometries: to_remove.append(reaction) print 'Removing %s:\t%s' % (reaction, stoichiometry) for reaction in to_remove: stoichiometries.pop(reaction) write_reaction_table(args.output_file, stoichiometries, parents, reversibilities)
""" Remove reactions from a table that involve given species, writing a new table. """ import argparse from table_utilities import read_reaction_table, read_component_table, write_reaction_table parser = argparse.ArgumentParser( description='Remove reactions from a table that involve certain species, writing a new table.' ) parser.add_argument('species_file', help='file of species names to exclude') parser.add_argument('input_file', help='input reaction table') parser.add_argument('output_file', help='clean reaction table file to write') args = parser.parse_args() stoichiometries, parents, reversibilities = read_reaction_table(args.input_file) bad_species = set(read_component_table(args.species_file)) to_remove = [] for reaction, stoichiometry in stoichiometries.iteritems(): if bad_species.intersection(stoichiometry): to_remove.append(reaction) print 'Removing %s:\t%s' % (reaction, stoichiometry) for reaction in to_remove: stoichiometries.pop(reaction) write_reaction_table(args.output_file, stoichiometries, parents, reversibilities)
""" Tic Tac Toe Player """ import math import sys import copy X = "X" O = "O" EMPTY = None def initial_state(): """ Returns starting state of the board. """ return [[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]] def player(board): """ Returns player who has the next turn on a board. """ return X if sum([sum(1 for slot in row if slot == None) for row in board])%2==1 else O def actions(board): """ Returns set of all possible actions (i, j) available on the board. """ moves = set() for i in range(3): for j in range(3): if board[i][j] == None: moves.add((i, j)) return moves if len(moves) > 0 else None def result(board, action): """ Returns the board that results from making move (i, j) on the board. """ i, j = action tempBoard = copy.deepcopy(board) #prevent board container to be permanently changed tempBoard[i][j] = player(board) return tempBoard def winner(board): """ Returns the winner of the game, if there is one. """ def findwinner(board, p): for row in board: if all(tile==p for tile in row): return p for i in range(3): if all([row[i]==p for row in board]): return p if all([board[i][i]==p for i in range(3)]): return p if all([board[::-1][i][i]==p for i in range(3)]): return p if findwinner(board, "O") == "O": return "O" elif findwinner(board, "X") == "X": return "X" return None def terminal(board): """ Returns True if game is over, False otherwise. """ if not any([True for row in board if EMPTY in row]) or winner(board) or not actions(board): return True return False def utility(board): """ Returns 1 if X has won the game, -1 if O has won, 0 otherwise. """ if winner(board) == X: return 1 elif winner(board) == O: return -1 return 0 def minimax(board): if terminal(board): return None if player(board) == X: next_move = None if terminal(board): return next_move best = -999999 for action in actions(board): move_value = minimize(result(board, action)) if move_value > best: next_move = action return next_move else: next_move = None if terminal(board): return next_move best = 999999 for action in actions(board): move_value = maximize(result(board, action)) if move_value < best: next_move = action return next_move def minimize(board): if terminal(board): return utility(board) val = 999 for action in actions(board): val = min(val, maximize(result(board, action))) if val == -1: break #it will not get better than -1 return val def maximize(board): if terminal(board): return utility(board) val = -999 for action in actions(board): val = max(val, minimize(result(board, action))) if val == 1: break #it will not get better than 1 return val
# Python Program to find sum of array # Given an array of integers, find sum of its elements. arr = [2, 3, 4] print(sum(arr))
import curses import sys import time from pynput import keyboard from ._widget import Widget class Button(Widget): """ A simple widget to get a input button. For eg, if the key esc is asigned to it and a appstate, it will change the appstate to it when the esc key is pressed """ def __init__(self, y, x, toggled=False, key=keyboard.Key.space, go_to=None): super().__init__("button") self.window = curses.newwin(3, 3, y, x) self.toggled = toggled self.toggle_count = 0 self.key = key self.go_to = go_to def refresh(self): self.window.border(0) self.window.addch(1, 1, "o" if self.toggled else "x") self.window.noutrefresh() if self.toggle_count >= 1: if self.go_to is not None: return self.go_to def press_on(self, key): if key == self.key or key.char == self.key: self.toggle_count += 1 self.toggled = not self.toggled
list1 = [] list2 = [] list3 = [] def merger_list(first_list, second_list): mydict = {word:1 for word in first_list} mydict.update({word:1 for word in second_list}) List = [] for word in mydict: List.append(word) return List while 1: print("Введите количество строк в 1 списке ") try: n = int(input()) except: print("Некорректный ввод") wait = input() continue for i in range(n): list1.append(input()) break while 1: print("Введите количество строк во 2 списке ") try: n = int(input()) except: print("Некорректный ввод") wait = input() continue for i in range(n): list2.append(input()) break print(merger_list(list1, list2)) wait = input()
f = open('text.txt', 'r') mydict = {} for line in f: words = line.split() for word in words: mydict[word] = 1 for word in mydict: print(word) wait = input()
print ("Hello You!, ik ben Ties Hogenboom") print ("Wie ben jij?") naam = input () print("Hello, " + naam) print("Hier zijn wat vragen over mij:") ans = input ("In welk jaar ben ik geboren? A 2002 B 2003 C 2004") if ans == "B": print("Dat is correct ik kom uit 2003!") else : print("dit is niet juist") ans = input ("Welk van deze anime is mijn favoriet? A One Piece B Naruto C God of Highschool") if ans == "B": print("Dat klopt Naruto is mijn favoriet!") else : print("dit is niet juist") ans = input ("Wat drink ik liever? A Redbull B IceTea C Appelsap") if ans == "A": print("Jup Redbull is erg lekker") ans = input("Vind ik de normale RedBull beter dan de andere RedBull smaken? A Ja! B Nee C Even goed") if ans == "A": print("Natuurlijk!") else : print("dit is niet juist") elif ans == "B": print("Jup IceTea is erg lekker") ans = input("Vind ik IceTea beter dan normale thee? A Ja! B Nee C Even goed") if ans == "A": print("Natuurlijk!") else : print("dit is niet juist") else : print("dit is niet juist")
import math from scipy import stats import numpy sample_data = [11, 15, 17, 27, 20, 17, 13, 22, 17] mean = numpy.mean(sample_data) median = numpy.median(sample_data) mode = stats.mode(sample_data) data_range = numpy.ptp(sample_data, axis=0) sum_squared = sum(sample_data)**2 sum_of_squares = sum([i**2 for i in sample_data]) stdev = numpy.std(sample_data) n = 12.0 sum_of_y = 305.0 sum_of_x = 112.0 sum_of_ysq = 9988.0 sum_of_xsq = 1424.0 sum_of_xy = 3452.0 x_bar = sum_of_x/n y_bar = sum_of_y/n b1 = sum_of_xy/sum_of_xsq b0 = y_bar - x_bar * b1 corrcoef = ((n * sum_of_xy) - (sum_of_x * sum_of_y))/(math.sqrt((n * sum_of_xsq - (sum_of_x**2))*(n * sum_of_ysq - (sum_of_y**2)))) print("The average X value is: " + str(x_bar)) print("The average Y value is: " + str(y_bar)) print("The regression model intercept is: " + str(b0)) print("The slope of the regression model is: " + str(b1)) print("The correlation coefficient is: "+str(corrcoef)) x_input = float(input("Enter X Value: ")) regression = x_input * b1 + b0 print("The best predicted value of Y given an X of " + str(x_input) +" is: "+str(regression)) # given with a normal distribution import math bicycle_price_mean = 140.00 bicycle_price_variance = 324.00 bicycle_price_stdev = math.sqrt(bicycle_price_variance) print("The standard deviation is: " + str(bicycle_price_stdev)) lower_bound = 115.00 upper_bound = 135.00 zlower = (lower_bound - bicycle_price_mean)/bicycle_price_stdev zupper = (upper_bound - bicycle_price_mean)/bicycle_price_stdev print(zlower, zupper) probability = round((100 * (stats.norm.cdf(zlower) - stats.norm.cdf(zupper))), 4) print("The probability of attaining a bicycle between " + str(lower_bound) + " and " + str(upper_bound) + " is: "+str(probability) + "%") z_new = (150.00 - bicycle_price_mean)/bicycle_price_stdev prob2 = round((100 * (1-stats.norm.cdf(z_new))), 4) print("The probability that the mean of bicycle prices will be over 150 is: " + str(prob2) + "%") x = numpy.array([3.0, 5.0, 7.0, 9.0, 11.0], dtype=float) P_of_X = numpy.array([0.5, 0.1, 0.2, 0.1, 0.1], dtype=float) expected_x = x * P_of_X mean = sum(expected_x) variance = sum(x**2 * P_of_X) - mean**2 stdev = variance**0.5 print(mean, variance, stdev) import scipy invoices_paid = 0.85 invoices_not_paid = 0.15 n = 9 chosen7 = 7 combinations7 = scipy.special.comb(n, chosen7) prb_of_7 = round(100 * combinations7 * (invoices_paid**chosen7) * (invoices_not_paid**(n-chosen7)), 4) print("The probability of exactly 7 invoices being paid with a random sample of 9 is " + str(prb_of_7) + "%") prb_of_fewer_than_2 = sum(numpy.array([100 * scipy.special.comb(n, x) * (invoices_paid**x) * (invoices_not_paid**(n-x)) for x in range(2)])) print("The probability of fewer than 2 invoices being paid with a random sample of 9 is " + str(prb_of_fewer_than_2) + "%") mean = 55.0 stdev = 4.2 problem1 = 50.0 problem2 = 52.0 problem3 = 65.0 zpa = (problem1-mean)/stdev zpb = (problem2-mean)/stdev zpc = (problem3-mean)/stdev prb_a = round(100*(0.5-stats.norm.cdf(zpa)), 4) prb_b = round(100*(0.5+stats.norm.cdf(zpb)), 4) prb_c = round(100*(stats.norm.cdf(zpc)), 4) print("With a mean of " + str(mean) + " and a standard deviation of " + str(stdev) + ":\n") print("The probability of a mean less than " + str(problem1) + " is: " + str(prb_a) + "%\n") print("The probability of a mean greater than " + str(problem2) + " is: " + str(prb_b) + "%\n") print("The probability of a mean less than " + str(problem3) + " is: " + str(prb_c) + "%\n") import math from scipy import stats n = 81.0 mean = 88.0 stdev = 12.2 confidence_interval = 0.924 alpha = (1-confidence_interval)/2. print(stats.norm.interval(confidence_interval,loc=mean,scale=stdev/math.sqrt(n))) import math from scipy import stats import numpy small_sample = numpy.array([8.2, 10.4, 7.8, 7.5, 8.1, 6.8, 7.2]) confidence_interval = 0.9 mean = sum(small_sample)/len(small_sample) stdev = numpy.std(small_sample) print(stats.norm.interval(confidence_interval,loc=mean,scale=stdev/math.sqrt(len(small_sample)))) import random def rollDie(number): counts = [0] * 6 for i in range(number): roll = random.randint(1,6) counts[roll - 1] += 1 return counts print(rollDie(6)) odd_total = 0 five_or_eight = 0 less_than_8 = 0 for i in range(100): d1, d2 = rollDie(1) if (d1 + d2) % 2 == 0: odd_total += 1 if d1 + d2 == 5 or d1 + d2 == 8: five_or_eight += 1 if d1 + d2 < 8: less_than_8 += 1 print(odd_total,five_or_eight,less_than_8)
import os import random def menu(): print("1. one player") print("2. two players") selection = input() if selection == "1": os.system('clear') oneplayer() elif selection == "2": os.system('clear') twoplayers() else: exit() def twoplayers(): p1_score = 0 p2_score = 0 while p1_score != 3 and p2_score != 3: print("Player 1 score:", p1_score, "- Player 2 score:", p2_score) print("Choose Rock Paper or Scissors.\n") player1 = input("Player 1: ") os.system('clear') player2 = input("Player 2: ") os.system('clear') print("Player 1 choice:", player1, "- Player 2 choice:", player2) # p1 wins scenarios if player1 == 'rock' and player2 == 'scissors': print("Player 1 wins.") p1_score += 1 elif player1 == 'paper' and player2 == 'rock': print("Player 1 wins.") p1_score += 1 elif player1 == 'scissors' and player2 == 'paper': print("Player 1 wins.") p1_score += 1 # p2 wins scenarios elif player1 == 'rock' and player2 == 'paper': print("Player 2 wins.") p2_score += 1 elif player1 == 'paper' and player2 == 'scissors': print("Player 2 wins.") p2_score += 1 elif player1 == 'scissors' and player2 == 'rock': print("Player 2 wins.") p2_score += 1 # ties scenario elif player1 == 'rock' and player2 == 'rock': print("It's a tie") elif player2 == 'scissors' and player2 == 'scissors': print("It's a tie") elif player1 == 'paper' and player2 == 'paper': print("It's a tie") def oneplayer(): p1_score = 0 p2_score = 0 choices = {'rock': '1', 'paper': '2', 'scissors': '3'} while p1_score != 3 and p2_score != 3: print("Player 1 score:", p1_score, "- Computer score:", p2_score) print("Choose Rock Paper or Scissors.\n") player1 = input("Player 1: ") player2 = random.choice(list(choices.keys())) os.system('clear') print("Player 1 choice:", player1, "- Computer choice:", player2) # p1 wins scenarios if player1 == 'rock' and player2 == 'scissors': print("Player 1 wins.") p1_score += 1 elif player1 == 'paper' and player2 == 'rock': print("Player 1 wins.") p1_score += 1 elif player1 == 'scissors' and player2 == 'paper': print("Player 1 wins.") p1_score += 1 # IA wins scenarios elif player1 == 'rock' and player2 == 'paper': print("Computer wins.") p2_score += 1 elif player1 == 'paper' and player2 == 'scissors': print("Computer wins.") p2_score += 1 elif player1 == 'scissors' and player2 == 'rock': print("Computer wins.") p2_score += 1 # ties scenario elif player1 == 'rock' and player2 == 'rock': print("It's a tie") elif player2 == 'scissors' and player2 == 'scissors': print("It's a tie") elif player1 == 'paper' and player2 == 'paper': print("It's a tie") menu()
class eseleccion(): def __init__(): pass # Ejercicio4 Construir un algoritmo def ejer4(self): nota=float(input("Ingrese su nota o calificación: ")) if nota>=7: print(" Su calificacion es:{} APROBADO ".format(nota) ) #Ejercicio5 Calificación de un alumno en su examen def ejer5(self): notaexa=float(input("Ingrese la nota de su examen: ")) if notaexa>=7 : print(" Su calificación es:{} APROBADO " .format(notaexa)) else: print("sucalificación es:{} REPROBADO" .format(notaexa)) # Ejercicio6 Sueldo de un empleado def ejer6(self): sueldo=float(input("Ingrese el sueldo: ")) if sueldo <600: print("Usted recibira un aumento en el sueldo por lo tanto ganara:{} $".format((sueldo*0.10)+sueldo)) else: print("Su sueldo total es:{}".format(sueldo)) # Ejercicio7 Horas extras def ejer7(self): htrabajads=int(input("Ingrese las horas trabajadas ")) valorhora=float(input("Ingrese el valor por hora ")) if htrabajads>40: hextras=htrabajads-40 if hextras > 8: hextrast=hextras-8 paghorasextra=(valorhora*2*8)+(valorhora*3*hextrast) else: paghorasextra=valorhora*2*hextras total=valorhora*40+paghorasextra else: total=valorhora*htrabajads print ("El pago total por las horas trabajadas es {}".format(total)) # Ejercicio8 Leer 3 numeros enteros def ejer8(self): num1,num2,num3=0,0,0 num1=int(input("Ingrese el numero1: ")) num2=int(input("Ingrese el numero2: ")) num3=int(input("Ingrese el numero3: ")) if (num1>num2>num3): print(num1) elif (num2>num1>num3): print(num2) else: print(num3) # Ejercicio9 Diseñar un algoritmo (2variables tipo entero) def ejer9(self): numer, v = 0, 0 numer = int(input("Ingrese un número como opción: ")) v = float(input("Ingrese cualquier número que desee: ")) if (numer == 1): resp = 100 * v elif (numer == 2): resp = 100 ** v elif (numer == 3): resp = 100 / v else: resp = 0 print('Resultado:', resp) # Ejercicio10 Operador lógico AND def ejer10(self): nota1= int(input("Ingrese su primera calificación: ")) nota2= int(input("Ingrese su segunda calificación: ")) if nota1>=80 and nota2>=80: print("La calificacion 1: {},la calificación 2:{} es ACEPTADO" .format(nota1,nota2)) else: print("La calificacion 1: {},la calificación 2:{} es RECHAZADO" .format(nota1,nota2)) sel=eseleccion() sel.ejer4() sel.ejer5() sel.ejer6() sel.ejer7() sel.ejer8() sel.ejer9() sel.ejer10()
def romb(n): for i in range(n+1): for _ in range(n-i): print(' ', end='') for _ in range(i*2+1): print('#', end='') print() for i in range(n): for _ in range(i+1): print(' ', end='') for _ in range(2*(n-i)-1): print('#', end='') print() romb(4) print() romb(6) print()
# Uses python3 import sys def lcm_naive(a, b): for l in range(1, a*b + 1): if l % a == 0 and l % b == 0: return l return a*b def primes(n): result = [] # Print the number of two's that divide n while n % 2 == 0: result.append(2) n = int(n / 2) # n must be odd now, so a skip of 2 ( i = i + 2) can be used for i in range(3, int(n**(1/2.0)) + 1, 2): # while i divides n , print i and divide n while n % i == 0: result.append(i) n = int(n / i) # Condition if n is a prime number greater than 2 if n > 2: result.append(n) return result def count_elements(arr): result = {} for elem in arr: elem_str = str(elem) if elem_str in result: result[elem_str] += 1 else: result[elem_str] = 1 return result def find_max_element_count(counts_a, counts_b): result = [] for k, v in counts_a.items(): b_count = counts_b.get(k, 0) max_count = max(v, b_count) result.append((int(k), max_count)) if k in counts_b: del counts_b[k] for k, v in counts_b.items(): result.append((int(k), v)) return result def calculate_result(max_counts): result = 1 for elem in max_counts: elem_result = elem[0] ** elem[1] result *= elem_result return result def lcm_fast(a, b): primes_a = primes(a) primes_b = primes(b) counts_a = count_elements(primes_a) counts_b = count_elements(primes_b) max_counts = find_max_element_count(counts_a, counts_b) return calculate_result(max_counts) if __name__ == '__main__': input_data = sys.stdin.read() a, b = map(int, input_data.split()) print(lcm_fast(a, b))
# В школе решили набрать три новых математических класса. # Так как занятия по математике у них проходят в одно и то же время, # было решено выделить кабинет для каждого класса и купить в них новые парты. # За каждой партой может сидеть не больше двух учеников. # Известно количество учащихся в каждом из трёх классов. # Сколько всего нужно закупить парт чтобы их хватило на всех учеников? # Программа получает на вход три натуральных числа: # количество учащихся в каждом из трех классов. # The school decided to recruit three new math class. # Since the classes in mathematics they are at the same time, # it was decided to allocate the office for each class and to buy them new desks. # Behind each desk can sit no more than two students. # Know the number of students in each of the three classes. # How much to buy desks to enough for all students? # The program receives the input of three integers: # the number of students in each of the three classes. print('В школе решили набрать три новых математических класса.') print('Так как занятия по математике у них проходят в одно и то же время,') print('было решено выделить кабинет для каждого класса и купить в них новые парты.') print('За каждой партой может сидеть не больше двух учеников.') print('Известно количество учащихся в каждом из трёх классов.') print('Сколько всего нужно закупить парт чтобы их хватило на всех учеников?') print('Программа получает на вход три натуральных числа:') print('количество учащихся в каждом из трех классов.') print() ans = 'y' while ans == 'y': a = int(input('Количество учеников в первом классе: ')) b = int(input('Количество учеников во втором классе: ')) c = int(input('Количество учеников в третьем классе: ')) a1 = a // 2 + a % 2 b1 = b // 2 + b % 2 c1 = c // 2 + c % 2 print(str('Надо купить ' + str(a1 + b1 + c1) + ' парт')) ans = input('Еще раз? y/n ')
# По данному натуральному числу N найдите наибольшую целую степень двойки, # не превосходящую N. Выведите показатель степени и саму степень. # Операцией возведения в степень пользоваться нельзя! # For a given natural number N find the greatest integer power of two, # not superior to N. Output the exponent and the degree. # Operation of exponentiation can not be used! print('По данному натуральному числу N найти наибольшую целую степень двойки,') print('не превосходящую N. Вывести показатель степени и саму степень.') print() ans = 'y' while ans == 'y': n = int(input('N = ')) i = 0 s = 1 while s <= n: s *= 2 i += 1 print(i - 1, s // 2) ans = input('Еще раз? y/n ')
# Пирожок в столовой стоит A рублей и B копеек. # Определите, сколько рублей и копеек нужно заплатить за N пирожков. # Программа получает на вход три числа: A, B, N, # и должна вывести два числа: стоимость покупки в рублях и копейках. # Pie in the dining room is A rubles and B kopecks. # Determine how many rubles and kopecks to pay for N pies. # The program takes on input three integers: a, b, n, # and should print two numbers: the purchase price in roubles and kopecks. print('Пирожок в столовой стоит a рублей и b копеек.') print('Определите, сколько рублей и копеек нужно заплатить за n пирожков.') print('Программа получает на вход три числа: a, b, n,') print('и должна вывести два числа: стоимость покупки в рублях и копейках.') print() ans = 'y' while ans == 'y': a = int(input('a = ')) b = int(input('b = ')) n = int(input('n = ')) print(str(a * n + (b * n) // 100) + ' руб ' + str((b * n) % 100) + ' коп') ans = input('Еще раз? y/n ')
# Дана последовательность натуральных чисел, завершающаяся числом 0. # Определите, какое наибольшее число подряд идущих элементов # этой последовательности равны друг другу. # Given a sequence of natural numbers ending with the number 0. # Determine what is the largest number of consecutive elements # of this sequence are equal to each other. print('Дана последовательность натуральных чисел, завершающаяся числом 0.') print('Определите, какое наибольшее число подряд идущих элементов') print('этой последовательности равны друг другу.') print() ans = 'y' while ans == 'y': max = i = 1 a = int(input('a1 = ')) j = 1 while a != 0: j += 1 b = int(input('a' + str(j) + ' = ')) if a == b: i += 1 else: i = 1 if max < i: max = i a = b print(max) ans = input('Еще раз? y/n ')
# С начала суток часовая стрелка повернулась на угол в α градусов. # Определите на какой угол повернулась минутная стрелка с начала последнего часа. # Входные и выходные данные — действительные числа. # Since the beginning of the day, the hour hand turned at an angle of α degrees. # Determine the angle turned the minute-hand since the beginning of the last hour. # Input and output real numbers. print('С начала суток часовая стрелка повернулась на угол в α градусов.') print('Определить, на какой угол повернулась минутная стрелка с начала последнего часа.') print('Входные и выходные данные — действительные числа.') print() import math ans = 'y' while ans == 'y': a = float(input('a = ')) print('Минутная стрелка повернулась на ' + str((a % 30) * 12) + ' градусов') ans = input('Еще раз? y/n ')
# Дано положительное действительное число X. # Выведите его первую цифру после десятичной точки. # Given a positive real number X. # Outputting the first digit after the decimal point. print('Дано положительное действительное число X.') print('Вывести его первую цифру после десятичной точки.') print() ans = 'y' while ans == 'y': a = float(input('a = ')) print('Первая цифра после точки ' + str(int(a * 10) % 10)) ans = input('Еще раз? y/n ')
# Последовательность состоит из различных натуральных чисел # и завершается числом 0. Определите значение второго # по величине элемента в этой последовательности. # Гарантируется, что в последовательности есть хотя бы два элемента. # The sequence consists of distinct natural numbers # and ends with the number 0. Determine the value of the second # largest element in this sequence. # It is guaranteed that the sequence has at least two elements. print('Последовательность состоит из различных натуральных чисел') print('и завершается числом 0. Определить значение второго') print('по величине элемента в этой последовательности.') print('Гарантируется, что в последовательности есть хотя бы два элемента.') print() ans = 'y' while ans == 'y': max1 = int(input('a1 = ')) max2 = n = int(input('a2 = ')) i = 2 if max2 > max1: max1, max2 = max2, max1 while n != 0: i += 1 n = int(input('a' + str(i) + ' = ')) if n > max1: max2 = max1 max1 = n elif n > max2: max2 = n print('Второй максимум = ' + str(max2)) ans = input('Еще раз? y/n ')
# С начала суток часовая стрелка повернулась на угол в α градусов. # Определите сколько полных часов, минут и секунд прошло с начала суток, # то есть решите задачу, обратную задаче «Часы - 1». # Запишите ответ в три переменные и выведите их на экран. # Since the beginning of the day, the hour hand turned at an angle of α degrees. # Determine how many total hours, minutes and seconds have passed since the beginning # of the day, that is, solve the problem, the inverse problem of "Watch - 1". # Write down the answer in three variables and print them to the screen. print('С начала суток часовая стрелка повернулась на угол в α градусов.') print('Определить сколько полных часов, минут и секунд прошло с начала суток,') print('то есть решить задачу, обратную задаче «Часы - 1».') print('Записать ответ в три переменные и вывести их на экран.') print() import math ans = 'y' while ans == 'y': a = float(input('a = ')) h = a // 30 m = (a % 30) * 12 // 6 s = ((a % 30) * 12 % 6) * 10 print('С начала суток прошло ' + str(int(h)) + ' часов '\ + str(int(m)) + ' минут ' + str(int(s)) + ' секунд') ans = input('Еще раз? y/n ')
# By using list comprehension, please write a program to print the list after removing delete numbers which are # divisible by 5 and 7 in [12,24,35,70,88,120,155]. target = [12, 24, 35, 70, 88, 120, 155] new_list = [x for x in target if x % 5 != 0 and x % 7 != 0] print(new_list)
# Write a program that computes the net amount of a bank account based a transaction log from console input. # The transaction log format is shown as following: # D 100 # W 200 # ?? # D means deposit while W means withdrawal. # Suppose the following input is supplied to the program: # D 300 # D 300 # W 200 # D 100 # Then, the output should be: # 500 cash = 0 while True: user_input = input() if not user_input: break operation, amount = user_input.split() if(not operation or not amount): break if operation == 'D': cash += int(amount) if operation == 'W': cash -= int(amount) print(cash)
# A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT # with a given steps. The trace of robot movement is shown as the following: # UP 5 # DOWN 3 # LEFT 3 # RIGHT 2 # ?? # The numbers after the direction are steps. Please write a program to compute the distance from current position after # a sequence of movement and original point. If the distance is a float, then just print the nearest integer. # Example: # If the following tuples are given as input to the program: # UP 5 # DOWN 3 # LEFT 3 # RIGHT 2 # Then, the output of the program should be: # 2 import math # [x, y] position = [0, 0] while True: line = input() if line: steps = int(line.split()[1]) if line.find('UP'): position[1] += steps if line.find('DOWN'): position[1] -= steps if line.find('LEFT'): position[0] -= steps if line.find('RIGHT'): position[0] += steps else: break distance = int(math.sqrt(math.pow(position[0], 2) + math.pow(position[1], 2))) print(distance)
# Define a function that can accept an integer number as input and print the "It is an even number" # if the number is even, otherwise print "It is an odd number". def print_parity(num): print("Is is an even number") if num % 2 == 0 else print("It is an odd number") print_parity(2) print_parity(4) print_parity(5)
# Write a method which can calculate square value of number def square(x): return x**2
# Please write a binary search function which searches an item in a sorted list. The function should return the index # of element to be searched in the list. def binary_search(list, item): left = 0 right = len(list) - 1 index = -1 while right >= left and index == -1: middle = int((left + right) / 2) element = list[middle] if element < item: left = middle + 1 elif element > item: right = middle - 1 else: index = middle return index
# Define a class, which have a class parameter and have a same instance parameter. class Car: def __init__(self, model): self.model = model audi = Car('audi') print(audi.model)
# Write a program which takes 2 digits, X,Y as input and generates a 2-dimensional array. The element value in the i-th # row and j-th column of the array should be i*j. # Note: i=0,1.., X-1; j=0,1,??Y-1. # Example # Suppose the following inputs are given to the program: # 3,5 # Then, the output of the program should be: # [[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]] dimensions = [int(x) for x in input().split(',')] rows, columns = dimensions array = [[0 for column in range(columns)] for row in range(rows)] for row in range(rows): for column in range(columns): array[row][column] = row * column print(array)
sumofFactors = 0 def findFactors(number): factors = [1] for i in range(2, number//2 + 1): if (number % i == 0): factors.append(i) return factors def sumFactors(factors): sumofFactors = 0 for i in range(0, len(factors)): sumofFactors += factors[i] return sumofFactors def checkNumber(sumofFactors, number): if (sumofFactors == number): print(number) for i in range(2, 10001): factors = findFactors(i) sumofFactors = sumFactors(factors) checkNumber(sumofFactors, i) print("finished")
#!/usr/bin/env python2.7 # DONT READ COMMENTS import RPi.GPIO as GPIO from time import sleep import sys board_type = sys.argv[-1] GPIO.setmode(GPIO.BCM) # initialise RPi.GPIO GPIO.setup(25, GPIO.OUT) # 22 normal input no pullup if board_type == "m": print "It's-a- me, Mario!" else: print "It's-a- me, Mario!" raw_input("When ready hit enter.\n") button_press = 0 # set intial values for variables previous_status = '' try: GPIO.output(25, 1) sleep(5) GPIO.output(25, 0) sleep(5) for i in range(10): if (i % 2): GPIO.output(25, 1) sleep(1) else: GPIO.output(25, 0) sleep(1) except KeyboardInterrupt: # trap a CTRL+C keyboard interrupt GPIO.cleanup() # resets all GPIO ports GPIO.cleanup() # on exit, reset GPIO ports used by program
num1=int(raw_input("Dime un numero: ")) num2=int(raw_input("Dime otro numero: ")) suma=num1+num2 resta=num1-num2 print "La suma es:", suma print "La resta es:", resta
#!/usr/bin/python3 '''THIS IS MY FUNCTION THAT WILL ADD TWO NUMBERS IT WILL TAKE TWO INTEGER ARGS a, b it's name is simple function''' def add_integer(a, b=98): ''' add_integer simple function args a, b''' try: if isinstance(a, float): raise TypeError except TypeError: a = int(a) try: if isinstance(b, float): raise TypeError except TypeError: b = int(b) try: if not(isinstance(a, int)): raise TypeError except: raise TypeError('a must be an integer') try: if not(isinstance(b, int)): raise TypeError except: raise TypeError('b must be an integer') return(a + b)
#!/usr/bin/python3 def replace_in_list(my_list, idx, element): z = len(my_list) for i in range(0, z): if idx == i: my_list[i] = element return (my_list) elif idx < 0: return (my_list) elif idx > z - 1: return (my_list)
#!/usr/bin/python3 """ Module that contains function """ def read_file(filename=""): """function read_file Args: filename """ with open(filename, 'r') as f: data = f.read() print(data, end='')
# def getMissingNo(A): # n = len(A) # total = (n+1)*(n+2)/2 # sum_of_A = sum(A) # return total - sum_of_A # def getmissingno(array): # arraylength = len(array) # total = (arraylength+1)*(arraylength+2)/2 # sumarray = sum(array) # return total - sumarray def getmissingno(anarray): for index in range(0,len(anarray)-1): element = anarray[index] if (element + 1 != anarray[index+1]): print(element+1) anarray = [1,2,3,4,5,6,7,9] getmissingno(anarray)
import translators as ts import tkinter from tkinter import filedialog def choose_files(): root = tkinter.Tk() root.withdraw() root.attributes('-topmost', True) root.title("Choose Text Files") files = filedialog.askopenfilename(title='Choose Text File', filetypes=(('Plain Text', '*.txt'), ('List Files', '*.lst'), ('All Files', '*.*'))) return files def translate_the_string(text, to, from_what, server): try: if server == 'b': return ts.bing(text, from_what, to) else: return ts.google(text, from_what, to) except Exception as e: return 'Sorry, Following Error Occured\n{}'.format(e) if '__main__'==__name__: ask = input("From File(F) or From User-Input(U): ").lower() if ask == 'f': print("Chooose File") filename = choose_files() file = open(filename, 'r') filename = "translated_{}".format(str(filename).split('/')[-1]) print(filename) text = "".join(file.readlines()) else: filename = "translated_{}.txt".format(input("Ouput Filename: ")) print('Please Enter your Text') text = '' while True: gets = input() if gets == '': break else: text += "{}\n".format(gets) to_lang = input("Which language you wanna translate to?\n").lower() if len(to_lang) > 3: print('Sorry, Literal is incorrect\nPlease Open LITERALS.md for LITERALS') print('Defaulting to English: EN') to_lang = 'en' elif to_lang == '': print("Defaulting to English: EN") to_lang = 'en' print("""Choose Engine 1. Is Accurate but has less Translation Language 2. Might be Inaccurate but has large variety of Translation Lang. """) ask = input(": ").lower() if ask == '1': ask = 'b' else: ask = 'g' translated = translate_the_string(text, to_lang, 'auto', ask) getfl = open(filename, 'w') getfl.write(translated) getfl.close() print("File is Outputted to {}".format(filename))
# 코딩테스트 연습 - 스택/큐 - 주식가격 prices = [1, 2, 3, 2, 3] def solution(prices): answer = [] # prices 배열의 현재값을 위한 변수 i for i in range(len(prices)): sec = 0 # i와 미래를 비교하기 위한 v for v in range(i+1,len(prices)+1): if v == len(prices): # 총 시간과 반복이 일치할 경우 answer.append(sec) break elif prices[i] > prices[v]: # 현재 가격이 미래보다 클 경우 초를 추가 후 어팬드 sec += 1 answer.append(sec) break elif prices[i] <= prices[v]: # 미래보다 현재 가치가 더 낮으면 초 추가 후 다음 반복 수행 sec += 1 return answer print(solution(prices)) # 방법 2. 코드 간소화 def solution2(prices): rep = len(prices) answer = [0] * rep for v in range(rep): for i in range(v+1,rep): answer[v] += 1 if prices[i] < prices[v]: # 미래가 현재보다 작은 경우 break return answer print(solution2(prices)) """ - 코딩테스트 연습 - 스택/큐 - 기능개발 - URL: https://programmers.co.kr/learn/courses/30/lessons/42586 - 문제해석 기능별 개발 속도가 다르고, 뒤에 기능이 먼저 개발되도 앞에 기능이 배포될 때 같이 배포되기 때문에 QUEUE 접근 """ pro1 = [93, 30, 55] spd1 = [1, 30, 5] pro2 = [95, 90, 99, 99, 80, 99] spd2 = [1, 1, 1, 1, 1, 1] def solution3(progresses, speeds): answer = [] # 결과값 리스트 선언 while progresses: cnt = 0 # 카운트 변수 선언 progresses = [x+y for x,y in zip(progresses, speeds)] # 진행상황에 속도 더함 while progresses: if progresses[0] >= 100: # 첫 idx가 진행상황 100 넘길때 cnt += 1 # 갯수를 더하고 progresses.pop(0) # pop으로 추출 speeds.pop(0) elif cnt > 0: # idx 0이 100이 안넘고 갯수가 있는 경우 append answer.append(cnt) break else: # idx 0이 100을 안넘고 갯수도 없는 경우 loop문 나옴 break answer.append(cnt) # loop문 종료 후, 마지막 cnt는 진행중인 프로그램이 없어서 # 하지못한 append를 마지막으로 실행 return answer print(solution3(pro1,spd1)) # [2,1] print(solution3(pro2,spd2)) # [1,3,2]
""" - 백준 - 동적계획법 - 계단오르기 - URL : https://www.acmicpc.net/problem/2579 - 문제 풀이 과정 : 한 번에 한 계단, 혹은 두 계단씩 오를 수 있으므로 매번 계단수 마다의 최대값을 answer list에 저장. for 문으로 전전 최댓값 + 현재 계단점수 와 전 최댓값을 비교하여 더 큰 값을 저장 마지막 계단은 무조건 밟아야 하므로, input list를 reverse시켜 무조건 밟고 시작하기 """ def solution(floor): answer = [] # 시작점 점수 floor.reverse() # 마지막 도착 계단을 무조건 밟아야 하므로 뒤에서부터 내려오기 answer.append(floor[0]) # 도착 지점의 계단값으로 sum의 최댓값 미리 넣어주기 answer.append(floor[0]+floor[1]) answer.append(max(floor[0]+floor[2],floor[1]+floor[2])) print(answer) for i in range(3,len(floor)): answer.append(max(answer[i-2]+floor[i],answer[i-3]+floor[i-1]+floor[i])) print(answer) print(floor) return answer[-1] print(solution([6,10,20,15,25,10,20])) # 76
def getkey(): list1=[] while True: a=input("请输入键:") if a == "" : break list1.append(a) return list1 def getvalue(list0): i=len(list0) list1=[] for k in range(i): a=input("请输入值:") list1.append(a) return list1 def makedic(list1,list2): dic={} for i,j in zip(list1,list2): dic[i]=j return dic def showdit(a): print(a) if __name__ == "__main__": a=getkey() b=getvalue(a) c=makedic(a,b) showdit(c)
#Case 7: Please write a program which count and print the numbers of each character in a string input by console. # Example: If the following string is given as input to the program: # abcdefgabc # Then, the output of the program should be: # a,2 # c,2 # b,2 # e,1 # d,1 # g,1 # f,1 dic = {} s='abcdefgabc' for s in s: dic[s]=dic.get(s,0)+1 print('\n'.join(['%s,%s' % (k, v) for k, v in dic.items()]))
# Case: Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0) # Example: # If the following n is given as input to the program: # 5 # Then, the output of the program should be: # 3.55 n=int(input("Enter a number: ")) sum=0.0 for i in range (1,n+1): sum+=float(float(i)/(i+1)) print(sum)
# Write a code which accepts a sequence of words as input and prints the words in a sequence after sorting them alphabetically. # Hint: In case of input data being supplied to the question, it should be assumed to be a console input. my_str=input("Enter your word: ") words=my_str.split() words.sort() for word in words: print(word) print("\nGood Bye")
""" A Singleton that controls the image and sound files. Uses python csv. """ import csv # The FileManager's job is to handle all file input class FileManager(): # Inner class - This is where the implementation goes! class __FileManager: def __init__(self): # Two separate dictionaries for the images # tracks file paths and file values self._image_paths = {} self._image_values = {} with open('images/images.csv', newline = '') as input: reader = csv.reader(input) for row in reader: k = row[0] path = row[1] value = row[2] self._image_paths[k] = path self._image_values[k] = value #Another dictionary for the sounds self._sound_paths = {} with open('sounds/sounds.csv', newline = '') as input: sound_reader = csv.reader(input) for row in sound_reader: s_k = row[0] s_path = row[1] self._sound_paths[s_k] = s_path def get_path(self, key): return self._image_paths[key] def get_value(self, key): return self._image_values[key] def get_sound_path(self, key): return self._sound_paths[key] # Instance variable! instance = None def __init__(self): # Create an object if one does not exist # Note that if two constructors are called, only one object is created! if not FileManager.instance: FileManager.instance = FileManager.__FileManager() # Pass attribute retrieval to the instance def __getattr__(self, name): return getattr(self.instance, name)
def odd_even(): for x in range(1, 2001): iteration = "Number is " + str(x) + ". " if (x % 2 == 0): even_num = iteration + "This is an even number." print even_num else: odd_num = iteration + "This is an odd number." print odd_num odd_even() def multiply(lst, num): new_lst = [] for x in lst: new_lst.append(x * num) print new_lst return new_lst multiply([2,10,20], 5) def layered_multiples(arr): new_arr = [] b = len(arr) counter = 0 list_num = 0 for y in arr: counter = 0 new_arr.append([]) while (counter < y): new_arr[list_num].append(1) counter +=1 list_num +=1 return new_arr x = layered_multiples(multiply([2,4,5],3)) print x
def multiples(): for count in range(5, 1000): if (count % 2 != 0): print count else: passdef find_characters(arr, character): multiples() def multiples_five(): for count in range(5, 1000005): if (count % 5 == 0): print count else: pass multiples_five() ## Sum List a = [1, 2, 5, 10, 255, 3] def sum_list(): count = 0 for count in a: print count count +=1 sum_list() ## Average List def average_list(array): average = 0 for count in array: average += count average /= len(array) print average average_list(a)
__author__ = 'edfeng' def sum_of_multiples(n): return sum([i for i in xrange(1, n) if i % 3 == 0 or i % 5 == 0])
#!/usr/bin/env python # -*- coding: utf-8 -*- #Program de Criptografia Cifra de Vigenère def val_cod(key_val, char_val): val_final = (key_val + char_val) if (val_final > 255): return (val_final%255) return val_final def input_file(nome_arq): with open(nome_arq, "rb") as f: byte = f.read() info = [byte[i:i+1] for i in range(0, len(byte), 1)] return info def output_file(out_info, out_name): nome_cypt = str(out_name[0:-3]) + "cry" arq_out = open(nome_cypt, "wb+") arq_out.write(out_info) arq_out.close() nome = raw_input("Digite um arquivo a ser cryptografado\n") list_clean = input_file(nome) list_cypt = list_clean key = list(raw_input("Digite a Chave de Codificação\n")) #print(key) key_index = 0 #print(key_index) for x in range(0, len(list_cypt), 1): if (key_index < len(key)): val_key = ord(key[key_index]) list_cypt[x] = chr(val_cod(val_key, ord(list_clean[x]))) key_index = key_index + 1 else: key_index = 0 val_key = ord(key[key_index]) list_cypt[x] = chr(val_cod(val_key, ord(list_clean[x]))) #print(list_cypt) #print(''.join(list_cypt)) output_file(''.join(list_cypt), (str(nome[:-3]+"cry")))
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ if not l1: return l2 if not l2: return l1 carry = 0 res = None res_end = None while l1 and l2: tsum = l1.val + l2.val + carry digit = tsum % 10 carry = tsum / 10 if not res: res = ListNode(digit) res_end = res else: res_end.next = ListNode(digit) res_end = res_end.next l1 = l1.next l2 = l2.next rem = None if l1: rem = l1 if l2: rem = l2 if rem: while rem: tsum = rem.val + carry digit = tsum % 10 carry = tsum / 10 res_end.next = ListNode(digit) res_end = res_end.next rem.next = rem if carry == 1: res_end.next = ListNode(1) return res class Solution2(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ carry = 0 res = None res_end = None while l1 or l2 or carry == 1: tmp = 0 if l1: tmp += l1.val l1 = l1.next if l2: tmp += l2.val l2 = l2.next tmp += carry digit = tmp % 10 carry = tmp / 10 if not res: res = ListNode(digit) res_end = res else: res_end.next = ListNode(digit) res_end = res_end.next return res
class Stack(object): def __init__(self): self.items = [] def is_empty(self): return len(self.items) == 0 def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] class Solution(object): def isValid(self, s): """ :type s: str :rtype: bool """ left_p = {'(': 1, '[': 2, '{': 3} right_p = {')': 1, ']': 2, '}': 3} if not s: return True stc = Stack() for ch in s: if ch in left_p.keys(): stc.push(ch) else: if stc.is_empty(): return False if right_p[ch] != left_p[stc.pop()]: return False return stc.is_empty()
class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ if not s: return 0 arrays = s.split() if not arrays: return 0 last = s.split()[-1] return len(last) s = Solution() print s.lengthOfLastWord(' ')
# Step 1: Make all the "turtle" commands available to us. import turtle # Step 2: create a new turtle, we'll call him bob and make him look like a turtle bob = turtle.Turtle() bob.shape("turtle") # Step 3: lets make Bob use a blue pen bob.color("blue") # Lets draw a star! for i in range(3): bob.forward(200) bob.left(120)
# 最大・最小ヒープ # http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_9_B&lang=jp import sys def max_heapify(array, root_index): left_index = root_index * 2 right_index = left_index + 1 max_index = root_index # 検索対象となっている節において最も大きい値をルートとする if left_index < len(array) and array[left_index] > array[root_index]: max_index = left_index # なのでrightと比較するのはleftとrootのうち大きい方と比較する # そうしないとleft > right > rootの場合にrightがrootにきてしまい、最大ヒープの条件を満たさない # (新たなrootとなるものよりleftの方が大きいので条件を満たさなくなる) if right_index < len(array) and array[right_index] > array[max_index]: max_index = right_index if max_index != root_index: array[0] = array[root_index] array[root_index] = array[max_index] array[max_index] = array[0] max_heapify(array, max_index) def main(): n = int(input()) array = [int(s) for s in input().split(" ")] heap = [0, *array] for i in range((n + 1) // 2, 0, -1): max_heapify(heap, i) sys.stdout.write(" ") print(" ".join(map(str, heap[1:]))) if __name__ == '__main__': main()
# https://atcoder.jp/contests/abc158/tasks/abc158_a def main(): s = input() if s.__contains__("A") and s.__contains__("B"): print("Yes") else: print("No") if __name__ == '__main__': main()
import re import sys def main(): s = input() p = re.compile(r'([A-Z][a-z]*[A-Z])+?') words = p.findall(s) words = list(map(lambda x: x.lower(), words)) words.sort() out = sys.stdout for w in words: out.write("%s%s%s" % (w[0].upper(), w[1:-1], w[-1].upper())) out.flush() if __name__ == '__main__': main()
# 二分探索木: 挿入 # http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_8_A&lang=jp import sys class Node(object): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def insert(root, v): if root is None: root = Node(v) else: if root.value > v: # insert into left if root.left is None: root.left = Node(v) else: insert(root.left, v) else: if root.right is None: root.right = Node(v) else: insert(root.right, v) return root def print_node(root_node): t = root_node stack = [] preorder = [] inorder = [] while t is not None or len(stack) > 0: while t is not None: stack.append(t) preorder.append(t.value) t = t.left t = stack.pop() inorder.append(t.value) t = t.right sys.stdout.write(" ") print(" ".join(map(str, inorder))) sys.stdout.write(" ") print(" ".join(map(str, preorder))) def main(): num = int(sys.stdin.readline()) root_node = None for _ in range(num): command = sys.stdin.readline().split(" ") if command[0] == "insert": root_node = insert(root_node, int(command[1])) else: print_node(root_node) if __name__ == '__main__': main()
# https://atcoder.jp/contests/abc148/tasks/abc148_d def main(): num = int(input()) origin = [int(i) for i in input().split(" ")] break_count = 0 want = 1 satisfy = False for b in origin: if b == want: want += 1 satisfy = True continue else: break_count += 1 print("-1" if not satisfy else break_count) if __name__ == '__main__': main()
from textblob import TextBlob a = input("Masukkan kata : ") print("Kata inputan " + str(a)) b = TextBlob(a) print("Kata perbaikan :" + str(b.correct()))
from tkinter import* root =Tk() label1= Label(root,text = "Label 1") label2= Label(root,text = "Label 2") label3= Label(root,text = "Label 3") label1.grid(row = 0,column = 0) label2.grid(row = 0,column = 1) label3.grid(row = 1,column = 0) root.mainloop()
from tkinter import* import random root = Tk() canvas= Canvas(root,width = 300, height = 300) canvas.pack() def randomRects(num): for i in range(0,num): x1 = random.randrange(150) y1 = random.randrange(150) x2 = x1 + random.randrange(150) y2 = y1 + random.randrange(150) canvas.create_rectangle(x1,y1,x2,y2) randomRects(150) root.mainloop()
a = int(input()) for i in range(a): b=int(input()) q=0 for j in range(b): q+=0.5 q=int(q*2) print(q)
import math a=[int(a) for a in input().split()] for q in range(a[0]): if int(input())<=math.sqrt(a[1]**2+a[2]**2): print("DA") else: print("NE")
from typing import List, Union Number = Union[int, float] """ 1) Termine os métodos calcula_juros() e saque(valor) da classe ContaPoupanca 2) Termine o método calcula_juros() da classe ContaCorrente 3) Adicione um atributo à classe Conta chamado _operacoes: self._operacoes = [] Ele servirá para guardar um extrato de todos as operações realizadas como saque, depósito, cobrança de juros, depósito de juros, etc. Você poderá registrar as operações assim: def saque(self, valor): self._saldo -= valor self._operacoes.append({'saque': valor}) """ class Cliente: ''' Classe Cliente do Módulo do Banco ''' def __init__(self, nome: str, telefone: int, email: str) -> None: self._nome = nome self._tel = telefone self._email = email def get_nome(self) -> str: ''' Acessor do atributo Nome ''' return self._nome def get_telefone(self) -> int: ''' Acessor do atributo Telefone ''' return self._tel def set_telefone(self, novo_telefone: int) -> None: ''' Mutador do atributo Telefone ''' if not type(novo_telefone) == int: raise TypeError else: self._tel = novo_telefone def get_email(self) -> str: ''' Acessor do atributo E-mail ''' return self._email def set_email(self, novo_email) -> None: ''' Mutador do atributo E-mail ''' if '@' not in novo_email: raise ValueError self._email = novo_email class Conta: ''' Conta básica ''' def __init__(self, clientes: List[Cliente], numero_conta: int, saldo_inicial: Number): self._clientes = clientes self._numero = numero_conta if saldo_inicial < 0: raise ValueError self._saldo = saldo_inicial def get_clientes(self) -> List[Cliente]: ''' Acessor Clientes ''' return self._clientes def get_numero_conta(self) -> int: ''' Acessor Número da Conta ''' return self._numero def get_saldo(self) -> Number: ''' Acessor Saldo ''' return self._saldo def set_saldo(self, novo_saldo: Number) -> None: self._saldo = novo_saldo def deposito(self, valor: Number) -> None: self._saldo += valor def saque(self, valor: Number) -> None: self._saldo -= valor class ContaPoupanca(Conta): ''' Conta Poupança ''' def __init__(self, clientes: List[Cliente], numero_conta: int, saldo_inicial: Number, taxa_juros: float): super().__init__(clientes, numero_conta, saldo_inicial) self._juros = taxa_juros def calcula_juros(self) -> None: # calcule os juros recebidos e atualize o saldo pass def saque(self, valor): # caso o saldo não seja suficiente, lance uma # exceção ValueError, senão chame o método saque # da classe pai if valor > saldo_inicial: raise ValueError else: super.saque(valor) class ContaCorrente(Conta): ''' classe conta corrente ''' def __init__(self, clientes, numero_conta, saldo_inicial, juros, limite): super().__init__(clientes, numero_conta, saldo_inicial) self._juros = juros self._limite = limite def calcula_juros(self): # caso minha conta esteja negativa, calcule os # juros devidos e atualize o saldo pass class Banco: def __init__(self, nome): self.nome = nome self._contas = [] def abre_cc(self, clientes, saldo_inicial): cc = ContaCorrente(clientes, len(self._contas) + 1, saldo_inicial, 0.1, 100) self._contas.append(cc) def abre_cp(self, clientes, saldo_inicial): cp = ContaPoupanca(clientes, len(self._contas) + 1, saldo_inicial, 0.01) self._contas.append(cp) def calcula_juros(self): for conta in self._contas: conta.calcula_juros() def mostra_saldos(self): for conta in self._contas: print(f'{conta.get_numero_conta()}: {conta.get_saldo()}') ''' fulano = Cliente('fulano', 9999999, '[email protected]') bb = Banco('Meu Banco') bb.abre_cc([fulano], 100) bb.abre_cp([fulano], 300) bb.abre_cc([fulano], 0) bb._contas[2].saque(50) bb.mostra_saldos() bb.calcula_juros() bb.mostra_saldos() '''
''' Douglas Byfield ''' def hello(): print("ECSE3038 - Engineering IoT Systems") hello() def validatePassword(psword): alnum, num = 0, 0 if len(psword) >= 8 and psword.isalnum(): for val in psword: try: if isinstance(int(val), int): num += 1 except: pass if num >= 2: return True return False def sumUpToN(num): digit = 0 if num > 1: for i in range(1, num+1): digit += i else: digit = -1 return digit
class Program: def __init__(self, numsList): self.nums = {i: v for i, v in enumerate(numsList)} self.relBase = 0 def getNum(self, index, mode=1): """ :param index: index to read at :param mode: 0 for position mode, 1 for immediate mode, 2 for relative mode :return: the value to use when operation operated on specified index """ if mode == 0: return self.getNum(self.getNum(index)) elif mode == 1: # this is also the base case, use 0 for default return self.nums.get(index, 0) elif mode == 2: return self.getNum(self.relBase + self.getNum(index)) else: raise Exception('uknown mode', mode) def setNum(self, index, value, mode): if mode == 0: self.nums[index] = value elif mode == 2: self.nums[index + self.relBase] = value else: raise Exception('uknown mode', mode) def run(self, input): nums = self.nums getNum = self.getNum setNum = self.setNum outputs = [] i = 0 while i < len(nums): num = nums[i] opcode = num % 100 num //= 100 mode1 = num % 10 num //= 10 mode2 = num % 10 num //= 10 mode3 = num % 10 modes = [mode1, mode2, mode3] if opcode == 1: val1 = getNum(i + 1, mode1) val2 = getNum(i + 2, mode2) val3 = getNum(i + 3) total = val1 + val2 setNum(val3, total, mode3) i += 4 elif opcode == 2: val1 = getNum(i + 1, mode1) val2 = getNum(i + 2, mode2) val3 = getNum(i + 3) product = val1 * val2 setNum(val3, product, mode3) i += 4 elif opcode == 3: val1 = getNum(i + 1) setNum(val1, input, mode1) i += 2 elif opcode == 4: val1 = getNum(i + 1, mode1) outputs.append(val1) i += 2 elif opcode == 5: val1 = getNum(i + 1, mode1) val2 = getNum(i + 2, mode2) if val1 != 0: i = val2 else: i += 3 elif opcode == 6: val1 = getNum(i + 1, mode1) val2 = getNum(i + 2, mode2) if val1 == 0: i = val2 else: i += 3 elif opcode == 7: val1 = getNum(i + 1, mode1) val2 = getNum(i + 2, mode2) val3 = getNum(i + 3) if val1 < val2: setNum(val3, 1, mode3) else: setNum(val3, 0, mode3) i += 4 elif opcode == 8: val1 = getNum(i + 1, mode1) val2 = getNum(i + 2, mode2) val3 = getNum(i + 3) if val1 == val2: setNum(val3, 1, mode3) else: setNum(val3, 0, mode3) i += 4 elif opcode == 9: val1 = getNum(i + 1, mode1) self.relBase += val1 i += 2 elif opcode == 99: break else: raise Exception('uknown op: ' + str(opcode)) return outputs def getNums(): with open('./inputs/input9.txt', 'r') as fp: data = fp.read() strNums = data.split(',') nums = [int(s) for s in strNums] return nums def solve1(): nums = getNums() program = Program(nums) try: outputs = program.run(1) return outputs except IndexError: print('index ERROR..........') print('part 1 solution:', solve1()) def solve2(): nums = getNums() program = Program(nums) try: outputs = program.run(2) return outputs except IndexError: print('index ERROR..........') print('part 2: solution',solve2())
""" filename : dashboard.py Page : Dashboard This script is responsible for generating plots on dashboard page. """ import streamlit as st import pandas as pd import plotly.graph_objects as go from app.controller.envelope_info import list_envelopes from app.utils.utilities import page_title def display_stats(): """ Function for Dashboard page, fetches envelopes information and generates plots input :: output :: donut plot of envelope status and bar plot of day wise sent envelopes """ page_title("Dashboard") with st.spinner('Did you know.. The 20 billion sheets of paper Docusign and its customers have saved? And its just the beginning.'): envelopes_df = list_envelopes() # code for donut plot labels = envelopes_df['status'].value_counts().index.tolist() values = envelopes_df['status'].value_counts().values.tolist() l = [0] * len(values) maxpos = values.index(max(values)) l[maxpos] = 0.1 fig = go.Figure(data=[go.Pie(labels=labels, values=values, pull=l, hole=.3)]) fig.update_layout(title_text='Envelope status') st.plotly_chart(fig, use_container_width=True) # code for bar plot dates = envelopes_df['created_date_time'] dates = dates.apply(lambda x : x.split("T")[0]) labels = dates.value_counts().index.tolist() values = dates.value_counts().values.tolist() # green bar with max value highlighting colors = ['cornflowerblue'] * len(labels) maxval = max(values) ind = [i for i, v in enumerate(values) if v == maxval] for i in ind: colors[i] = 'green' layout = dict( xaxis=dict(title='Date', ticklen=5, zeroline=False), yaxis=dict(title='No. of envelopes', ticklen=5, zeroline=False) ) fig = go.Figure(data=[go.Bar( x=labels, y=values, marker_color=colors )], layout=layout) fig.update_layout(title_text='Sent Envelopes') st.plotly_chart(fig, use_container_width=True)
__author__ = 'Dave Sizer <[email protected]>' while 1==1: try: WIDTH = int(raw_input('Width?')) except ValueError: print 'Not a number!' continue CHAR = raw_input('Draw character?') for i in range(1,WIDTH-1): for j in range(1, WIDTH-i): print(''), for k in range(1,i): print (CHAR), print '' for i in reversed(range(1,WIDTH)): for j in range(1, WIDTH-i): print(''), for k in range(1,i): print (CHAR), print ''
class SchoolAdmission: def __init__(self, file): self.capacity = int(input()) self.applicants = [line.split() for line in file.read().split('\n')] self.departments = dict(Biotech=[], Chemistry=[], Engineering=[], Mathematics=[], Physics=[]) self.registered = [] self.place_applicants() def place_applicants(self): for priority in range(7, 10): for choice in self.departments: applicants = self.sort_applicants(choice, priority) for applicant in applicants: if applicant[:2] not in self.registered and len(self.departments[choice]) < self.capacity: student = f'{applicant[0]} {applicant[1]} {float(applicant[2])}' self.departments[choice].append(student) self.registered.append(applicant[:2]) else: pass self.display_departments() self.save_results() def sort_applicants(self, choice, priority): applicants = [] for student in self.applicants: if student[priority] == choice: index = self.review_exam(choice) grade = (int(student[index[0]]) + int(student[index[1]])) / 2 applicants.append(student[:2] + [max(grade, int(student[6]))]) applicants.sort(key=lambda x: (-float(x[2]), x[0])) return applicants @staticmethod def review_exam(choice): if choice == 'Physics': return [2, 4] elif choice == 'Mathematics': return [4, 4] elif choice == 'Engineering': return [5, 4] elif choice == 'Chemistry': return [3, 3] else: return [3, 2] def display_departments(self): for department in self.departments: self.departments[department].sort(key=lambda x: (-float(x.split()[2]), x.split()[0])) print(department, *self.departments[department], sep='\n', end='\n\n') def save_results(self): for department in self.departments: self.departments[department].sort(key=lambda x: (-float(x.split()[2]), x.split()[0])) with open(f'{department.lower()}.txt', 'w') as file: for applicant in self.departments[department]: file.write(applicant + '\n') if __name__ == '__main__': file = open('applicants.txt', 'r') SchoolAdmission(file) file.close()
#!/usr/bin/env python from datetime import datetime, timedelta import sys import dateparser import dateutil.tz # 0: Monday # 6: Sunday START_OF_WEEK = 6 class DateRange(object): def __init__(self, start=None, end=None): now = datetime.now(dateutil.tz.tzlocal()) self.week = start == "week" if self.week: start = self.first_of_week(now, end) end = start + timedelta(days=6) else: if start is None: start = now end = start else: start = self.parse_date(start) end = start if end is None else self.parse_date(end) start = start.replace(hour=0, minute=0, second=0, microsecond=0) end = end.replace(hour=0, minute=0, second=0, microsecond=0) self.one_day = start == end if self.one_day: self.dates = "{:%Y-%m-%d}".format(start) else: self.dates = "{:%Y-%m-%d} - {:%Y-%m-%d}".format(start, end) self.start = start self.end = end + timedelta(days=1) def days(self): if self.one_day: yield self.tuple() else: curr = self.start while curr < self.end: next = curr + timedelta(days=1) yield curr, next curr = next def decrement_week(self): if self.week: self.start -= timedelta(weeks=1) self.end -= timedelta(weeks=1) self.dates = "{:%Y-%m-%d} - {:%Y-%m-%d}".format(self.start, self.end - timedelta(days=1)) def decrement_day(self): if self.one_day: self.start -= timedelta(days=1) self.end -= timedelta(days=1) self.dates = "{:%Y-%m-%d}".format(self.start) @staticmethod def first_of_week(date, offset): if offset is None: offset = 0 else: try: offset = int(offset) except ValueError: raise WeeksParseError(offset) days = (date.weekday() - START_OF_WEEK) % 7 - (7 * offset) date -= timedelta(days=days) return date @staticmethod def parse_date(date): now = datetime.now(dateutil.tz.tzlocal()) settings = {'TIMEZONE': now.tzname(), 'RETURN_AS_TIMEZONE_AWARE': True} result = dateparser.parse(date, settings=settings) if result is None: raise DateParseError(date) result -= result.utcoffset() # last = now corrected = result.replace(tzinfo=dateutil.tz.tzlocal()) while result.utcoffset() != corrected.utcoffset(): settings['TIMEZONE'] = corrected.tzname() # last = result result = dateparser.parse(date, settings=settings) if result is None: raise DateParseError(date) result -= result.utcoffset() corrected = result.replace(tzinfo=dateutil.tz.tzlocal()) return result.replace(tzinfo=dateutil.tz.tzlocal()) def tuple(self): return self.start, self.end class DateParseError(ValueError): def __init__(self, date): super(DateParseError, self).__init__("date format not supported: '{}'".format(date)) class WeeksParseError(ValueError): def __init__(self, weeks): super(WeeksParseError, self).__init__("invalid number of weeks: '{}'".format(weeks)) def process_entries(entries): days = {} for entry in entries: desc, dur = entry['description'], entry['duration'] date = entry['start'][:len('YYYY-MM-DD')] if date not in days: days[date] = {} if desc not in days[date]: days[date][desc] = 0 days[date][desc] += dur rows = [] for date, work in sorted(days.items()): rows.append([]) rows.append([date]) work_rt = 0 work_ct = timedelta() for name, dur in sorted(work.items()): record = hmi(dur) clock = timedelta(seconds=dur) rows.append([name, str(clock), hm(record)]) work_rt += record work_ct += clock rows.append(["TOTAL", hms_td(work_ct), hm(work_rt)]) return rows def hms_td(td): hours, rem = divmod(td.seconds, 3600) minutes, seconds = divmod(rem, 60) hours += td.days * 24 #result = '{:02d}'.format(seconds) result = [] if hours > 0: result.append('{:d}'.format(hours)) if result or minutes > 0: result.append('{:02d}'.format(minutes)) result.append('{:02d}'.format(seconds)) return ':'.join(result) def hmi(s, round=15*60): return ((s + round/2) // round) * round def hm(s): td = timedelta(seconds=s) h = td.days * 24 + td.seconds // 3600 m = (td.seconds//60)%60 result = '{}m'.format(m) if h > 0: result = '{}h {}'.format(h, result) return result
import pandas as pd from fbprophet import Prophet import matplotlib.pyplot as plt # --------------------------- # load and inspect data, which needs to be in a very specific format # ------ df = pd.read_csv('data/BeerWineLiquor.csv') # df.rename(columns={'date':'ds', 'beer':'y'}, inplace=True) df.columns = ['ds','y'] df['ds'] = pd.to_datetime(df['ds']) # df.index.freq='MS' # print(df.head()) # create and fit the model # ------ # Prophet has many possible options to go inside the parenthesis, check docs m = Prophet() # first example ever here, so we will not split the databse in two parts (yet) m.fit(df) # predict the future # ------ future = m.make_future_dataframe(periods=24, freq = 'MS') # future is the new dataframe including the forecasted future dates # print('--------_> df tail') # print(df.tail()) # print('--------_> future tail') # print(future.tail()) # -- now predict the values and add them to the future dataframe forecast = m.predict(future) # print(forecast.head()) # -- grab specific model columns # print(forecast.colums) forecast[['ds', 'yhat_lower', 'yhat_upper', 'yhat']].tail() # plot the forecast via prophet plotting # ------ m.plot(forecast) plt.show() # -- we can plot components directly m.plot_components(forecast) # evaluate prophet precision # ------ # (see file 2)
import numpy as np import pandas as pd import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.layers import LSTM from tensorflow.keras.preprocessing.sequence import TimeseriesGenerator #data preprocessing # enconding from sklearn.preprocessing import LabelEncoder from sklearn.compose import ColumnTransformer from sklearn.preprocessing import OneHotEncoder from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import confusion_matrix, accuracy_score # --------------------------- # deep learning - ANN for classification # *** # we have data showing which clients with which characteristics remained customers of a bank or not # we train the model on such data and try to see if we can learn and how can we predict # *** # [1] load and pre-process data # ------ dataset = pd.read_csv('../data/Churn_Modelling.csv') X = dataset.iloc[:, 3:-1].values #this includes all rows, but we do not need the first three columns (raw number, customer id, surname) as they will not impact the classification decision; we also remove the last column, which we report as y y = dataset.iloc[:, -1].values # this is the dependent variable => customer with certain features stays or leaves # print(dataset.head()) # print(X) # print(y) # [2] encode categorical data (sex via label enconding, then Geography column via hot encoding) # ------ # - first, label enconding (0/1) for female/male column le = LabelEncoder() X[:, 2] = le.fit_transform(X[:, 2]) # X[:, 2] this indicates that we take all row of second column, the one indicating sex, for normal 0/1 label encoding # print(X) # - second, hot econding for geography column ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [1])], remainder='passthrough') # the code [1] will indicate that we have to transform the second column of the updated dataframe X = np.array(ct.fit_transform(X)) # transform all data into an np array with different information # print(X) # [3] split dataset # ------ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # [4] scale/normalize data for the ANN (only on training data here) # ------ sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # [5] define the model, according to new keras instructions # https://www.tensorflow.org/guide/keras/rnn # ------ model = keras.Sequential() # - add network layers # how many neurons (i.e. hyperparameters in general)? experiment model.add(layers.Dense(units=6, activation='relu')) # input layer model.add(layers.Dense(units=6, activation='relu')) # hidden layer model.add(layers.Dense(units=1, activation='sigmoid')) # output layer (only 1 neuron, as we need a 0/1 answer) # [6] fit (and run) the model # ------ model.compile(optimizer='adam', loss='binary_crossentropy', metrics = ['accuracy']) # adam is a way to perform the stochastic gradient descent model.fit(X_train, y_train, batch_size = 50, epochs = 50) print(model.summary()) # [7] run the model as experiment to predict one value # ------ # -- now we can run the prediction; in this example, we take the previous 12 datapoints to predict the first point in the future, so putput is going to be 1 array/value # *** # example - Predict if a customer (with certain characteristics) will leave the bank: YES/NO # Geography: France # Credit Score: 600 # Gender: Male # Age: 40 years old # Tenure: 3 years # Balance: $ 60000 # Number of Products: 2 # Credit card? Yes # Active Member: Yes # Estimated Salary: $ 50000 # *** # the client sample variable below is an array into an array, bringing it to a 2D array as required by the predict method client_sample = [[1, 0, 0, 600, 1, 40, 3, 60000, 2, 1, 1, 50000]] # 1,0,0 is France via hot encoding and all the orher variables describe the model client normalised_client_sample = sc.transform(client_sample) first_prediction = model.predict(normalised_client_sample) # this prediction returns a probability (of the client leaving) between 0 and 1 print('first prediction: ') print('False = client stays; True = client leaves') print(first_prediction > 0.5) # we print and filter here if the predicted probability of a client leaving is above 50%: if True, client is predicted to leave print('----------------') # [8] we are ready to run rolling predictions against the test dataset # ------ y_pred = model.predict(X_test) y_pred = (y_pred > 0.5) # again, here we interpret the predicted probability as above (line 115) # -- show here the prediction against the real test result to find out accuracy predictions = np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1) print(predictions) # [9] measure model accuracy # ------ cm = confusion_matrix(y_test, y_pred) # print(cm) accuracy = accuracy_score(y_test, y_pred) print(accuracy) # # invert scaling to understand values in the original form # # ------ # real_predictions = scaler.inverse_transform(test_predictions) # print(real_predictions) # # plot the findings # # ------ # # -- first, conveniently amend the test dataframe (with test dataset already) to add RNN predictions (to compare to test dataset) as new column # expanded_test_set = test.copy() # expanded_test_set['Predictions'] = real_predictions # expanded_test_set.plot() # plt.show() # # save model (to avoid long re-training next time) # # ------ # model.save('second_RNN.h5') # # to re-load, copy/paste and then run code below: # # from tensorflow.keras.models import load_model # # new model = load_model('first_RNN.h5') # # -- we can also load anything from a different path by adding the abolute path into parenthesis # # full forecasting into the future # # ------ # # -- same process as 'rolling predictions against the test dataset' # # -- just make sure to change the variable 'values_to_predict'
import numpy as np import pandas as pd import matplotlib.pyplot as plt import math # for squared root calculation # ------------------------- # REINFORCEMENT LEARNING # UCB - upper confidence bound # example: advertising team sends many different ads to promote an SUV; we need to register if a specific user will clikc on the ad (via 0/1) # we assume 1 is a reward when a user clicks, while 0 is no reward # we have to monitor 10.000 users to see which ad has the best click-through # load data # ------------ dataset = pd.read_csv('../data/Ads_CTR_Optimisation.csv') # run the model # ------------ N = 10000 # N is total users we monitor (or rounds in general) d = 10 # d is the total variables (=ads) to monitor ads_selected = [] # numbers_of_selections = [0] * d # initialize a list with counters => how many times each ad has been selected sums_of_rewards = [0] * d # sum the rewards for each click at each ad (one click makes the ad get one reward) total_reward = 0 # iterate through all N customers/rounds to sum up the rewards for n in range(0, N): ad = 0 # starting point: monitor from ad 0 (to reach the tenth ad => see second for loop to go through the 10 ads) max_upper_bound = 0 # confidence level: initialized at zero, but can grow # loop through the 10 different ad types for i in range(0, d): # check if an ad has been selected by a user if (numbers_of_selections[i] > 0): average_reward = sums_of_rewards[i] / numbers_of_selections[i] # avg reward is nothing else than the mean reward in the distribution # get the confidence interval according to UCB formula (see notes) delta_i = math.sqrt(3/2 * math.log(n + 1) / numbers_of_selections[i]) upper_bound = average_reward + delta_i # define the upper tail range in the reward distribution, as we will have to select the ad with the max UCB else: upper_bound = 1e400 # upper bound for the ad not selected it yet => we make it an incredibly high value = 1 with 400 zeros # let's check if the upper_bound is larger than max, make the max equal to the largest value if upper_bound > max_upper_bound: max_upper_bound = upper_bound ad = i # i is the index selected in the loop, so we make an ad the selected ad ads_selected.append(ad) # add the selected ad to the list of se;ected ads numbers_of_selections[ad] = numbers_of_selections[ad] + 1 # increment the selected ad to go through one by one reward = dataset.values[n, ad] # access a specific dataset value (either 0 or 1) to see if the ad was cliocked, and thus which reward is granted sums_of_rewards[ad] = sums_of_rewards[ad] + reward # incrementing the reward per each ad total_reward = total_reward + reward # incrementing the total reward # visualizing results # ------------ plt.hist(ads_selected) plt.title('Histogram of ads selections') plt.xlabel('Ads') plt.ylabel('Number of times each ad was selected') # plt.show()
class Node(): #Node definition for use in Doubly Linked List implementation def __init__(self, data, prev=None, next=None): self.data = data self.prev = None self.next = None #https://www.tutorialspoint.com/python_data_structure/python_advanced_linked_list.htm class DoublyLinkedList(): #Will use Double linked list for this project to be able to traverse the elements using a left and right function def __init__(self): self.head = None def append(self, data): node = Node(data) node.next = None if self.head is None: node.prev = None self.head = node return last = self.head while (last.next is not None): last = last.next last.next = node node.prev = last return class TwoWayAccepter(): #Defining a Two Way Accepter Machine that will use the Double Linked List as its input def __init__(self, case):# Accepts Double Linked List object self.original = case.head self.current = case.head def left(self): self.current = self.current.prev def right(self): self.current = self.current.next def data(self): return self.current.data def write(self, char): self.current.data = char # print(self.chars()) def chars(self): node = self.original chars = "" while node is not None: chars = chars + node.data node = node.next return chars def accept(self): """ Raise exception if accepted to terminate the entire function body for this case """ raise Exception("ACCEPTED") def reject(self): """ Raise exception if rejected to terminate the entire function body for this case """ raise Exception("REJECTED") def create_case(string): """ Creates a case of DoubleLinkedList objects from a string input """ input_string = DoublyLinkedList() for each_char in string: input_string.append(each_char) return input_string def simulator(cases, program): """ Defines the simulator that accepts cases and a program object """ for each_case in cases: try: twa = TwoWayAccepter(each_case) current_state = 1 if twa.data() == "#": twa.right() transition_set = program[str(current_state)] instruction = transition_set[twa.data()] while True: if type(instruction) == int: instruction = transition_set[twa.data()] transition_set = program[str(instruction)] if transition_set['dir'] == 'left': twa.left() elif transition_set['dir'] == 'right': twa.right() elif instruction == 'accept': twa.accept() elif instruction == 'reject': twa.reject() except Exception as e: print(e) pass
my_favorite_toy = "Giffy" guess= " " guess_count = 0 guess_limit = 5 out_of_guesses = False print("Welcome to My Favorite Toy Guessing Game!") while guess != my_favorite_toy and not(out_of_guesses): if guess_count < guess_limit: guess = input("Enter your guess: ") guess_count +=1 else: out_of_guesses = True if out_of_guesses: print("Oops sorry! You are out of guesses") else: print('Yay! Congratulations! You Win!')
#!/usr/bin/env python #-*- coding: utf-8 -*- p1 = 6000 p2 = 3000 p3 = 1000 total = p1+p2+p3 iva = .16 # respuestasi = {'si'} R= input(" Desea Iva desglosado ( Si/No) ") print("-"*79) print("{:40} | {:6}".format("Productos", "Precio")) print("-"*79) print("{:40} | {:>10.2f}".format("Lap", p1,)) print("{:40} | {:10.2f}".format("pantalla", p2)) print("{:40} | {:10.2f}".format("pila", p3)) print("-"*79) if "" in R: print("Este no es un caracter valido") if "no" in R: print("{:>40} | {:10.2f}".format("Total =", total )) elif "n" in R: print("{:>40} | {:10.2f}".format("Total =", total )) elif "NO" in R: print("{:>40} | {:10.2f}".format("Total =", total )) elif "N" in R: print("{:>40} | {:10.2f}".format("Total =", total )) if "si" in R: print("{:>40} | {:10.2f}".format("Subtotal =", total )) print("{:>40} | {:10.2f}".format("Iva =", total*iva )) print("{:>40} | {:10.2f}".format("Total =", total*iva +total )) elif "s" in R: print("{:>40} | {:10.2f}".format("Subtotal =", total )) print("{:>40} | {:10.2f}".format("Iva =", total*iva )) print("{:>40} | {:10.2f}".format("Total =", total*iva +total )) elif "SI" in R: print("{:>40} | {:10.2f}".format("Subtotal =", total )) print("{:>40} | {:10.2f}".format("Iva =", total*iva )) print("{:>40} | {:10.2f}".format("Total =", total*iva +total )) elif "S" in R: print("{:>40} | {:10.2f}".format("Subtotal =", total )) print("{:>40} | {:10.2f}".format("Iva =", total*iva )) print("{:>40} | {:10.2f}".format("Total =", total*iva +total ))
import argparse # construct the argument parse and parse the arguments ap = argparse.ArgumentParser() #We must specify both shorthand ( -n) and longhand versions ( --name) ap.add_argument("-n", "--name", required=True, help="Enter user name") ap.add_argument("-c", "--country", required=True, help="Enter country name") #call vars on the object to turn the parsed command line arguments into a Python dictionary args = vars(ap.parse_args()) print(args) # display a message to the user print("Hi Everyone, This is {}, and I am from {}.".format(args["name"],args["country"])) # To run --> python sample.py -n "anji" -c "India" # Output # {'name': 'anji', 'country': 'India'} # Hi Everyone, This is anji, and I am from India.
class Credentials: ''' This is class that stores all the credentils of each user and hence allows the user to access the information once they are logged in ''' def __init__ (self,user_name, credential_name , credential__password): self.user_name = user_name self.credential_name =credential_name self.credential_password =credential__password list_of_credentials = [] #this is an empty list that will hold all the information for each user def save_credentials(self): ''' This functions appends each new credential to the list of credetials ''' self.list_of_credentials.append(self) def delete_credentials(self): ''' this method deletes the selected credential from the list of credentials ''' Credentials.list_of_credentials.remove(self) @classmethod def find_credentials_by_name(cls,name): for credential in cls.list_of_credentials: if credential.user_name == name: return credential @classmethod def credential_exists(cls,name): for credential in cls.list_of_credentials: if credential.user_name == name: return True @classmethod def display_all_credentials(cls): ''' Function that displays all the saved credentials in the list of credentials ''' return cls.list_of_credentials
#Problem Link - https://leetcode.com/problems/friend-circles/ class Solution: def findCircleNum(self, M): N = len(M) visited = [0] * N circle = 0 queue = [] for index in range(N): if not visited[index]: queue.append(index) circle += 1 while queue: student = queue.pop(0) visited[student] = 1 for friend in range(N): if M[student][friend] and not visited[friend]: queue.append(friend) return circle if __name__ == '__main__': input = [[1,1,0],[1,1,0],[0,0,1]] s = Solution() result = s.findCircleNum(input) print(result)
""" Полиморфизм - возможность объектов с одинаковой спецификацией иметь различную реализацию. Все объекты имеют один и тот же метод в классе, но вычисляется он по-разному. И теперь можно проходить по всем этим объектам в цикле и выполнять для каждого объекта свое действие, вызывая лишь один метод. !!!А что если метод evaluate_are оформить как property?! """ class Rectangle: def __init__(self, side_1: (int, float), side_2: (int, float)) -> None: self.side_1 = side_1 self.side_2 = side_2 super().__init__() def evaluate_area(self): return self.side_1 * self.side_2 def __repr__(self) -> str: return f'Rectangle with {self.side_1} * {self.side_2} :' class Square: def __init__(self, side: (int, float)) -> None: self.side = side super().__init__() def evaluate_area(self): return self.side ** 2 def __repr__(self) -> str: return f'Square with {self.side} :' class Circle: def __init__(self, radius: (int, float)) -> None: self.radius = radius super().__init__() def evaluate_area(self): return 3.14 * self.radius ** 2 def __repr__(self) -> str: return f'Circle with {self.radius} :' rec_1 = Rectangle(1, 2) rec_2 = Rectangle(2, 5) # print(rec_1.evaluate_area(), rec_2.evaluate_area()) # print(40 * "#") sq_1 = Square(2) sq_2 = Square(10) # print(sq_1.evaluate_area(), sq_2.evaluate_area()) # print(40 * "#") crl_1 = Circle(5) crl_2 = Circle(8) # print(rec_1.evaluate_area(), rec_2.evaluate_area()) # print(40 * "#") figures = [rec_1, rec_1, sq_1, sq_2, crl_2, crl_1] # А можно решить данную данную проблемы через цикл for figure in figures: print(figure.__repr__(), figure.evaluate_area(), end='\n###############\n')
""" Любой экземпляр класса без переопределения метода __bool__ возвращает True. Любое число отличное от нуля - возвращает True. 0 - возвращает False. Строки, кортежи, списки - если они пустые, то они возвращают False. Если они что-то в себе содержат, то - True. Чтобы экземпляр класса возвращал нам при необходимости нужное значение - нужно переопределить метод __bool__ в классе. Если метод __bool__ не переопределен, но переопределен метод __len__, то Python возвращает результат работы метода __len__. """ class Point: def __init__(self, coord_x1: (int, float), coord_x2: (int, float)): self.coord_x1 = coord_x1 self.coord_x2 = coord_x2 def __len__(self): # Работает вместо функции __bool__, если она не переопределена. print("Call __len__") return abs(self.coord_x1 - self.coord_x2) def __bool__(self): print("Call __bool__") return self.coord_x1 != 0 or self.coord_x2 != 0 # Запомнить, что возвращает True, если выражение правда """ При and - Python проверил бы первое выражение и далее не пошел бы, т.е. должны соблюстись оба условия для возвращеня True При or - Python проверяет """ p1 = Point(2, 2) p2 = Point(3, 4) p3 = Point(0, 0) p4 = Point(0, 4) p5 = Point(4, 0) print(bool(p1)) print(10 * "#") print(bool(p2)) print(10 * "#") print(bool(p3)) print(10 * "#") print(bool(p4)) print(10 * "#") print(bool(p5))
# This code is for fully educational purposes and it implements the simulated annealing AI algorithm # for more information please visit: https://en.wikipedia.org/wiki/Simulated_annealing import numpy import time import random NEIGHBORHOOD_MAX = 40 NEIGHBORHOOD_MIN = 0 T_MAX = 100 T_MIN = 0.01 def f(x): assert NEIGHBORHOOD_MIN <= x <= NEIGHBORHOOD_MAX return numpy.sin(0.15 * x) + numpy.cos(x) def acceptance(s, new_s, temperature): return numpy.exp(-1 * float(new_s - s) / float(temperature)) def next_neighbor(sol, alpha, T, T_max): move = alpha * NEIGHBORHOOD_MAX if sol - move <= NEIGHBORHOOD_MIN: return sol + move elif sol + move >= NEIGHBORHOOD_MAX: return sol - move else: return sol + move * random.uniform(-1, 1) def SA(sol): s = sol T = T_MAX alpha = 0.4 beta = 0.9 while T > T_MIN: print 'S: %s | T: %s' % (str(s), str(T)) for _ in range(200): new_s = next_neighbor(s, alpha, T, T_MAX) if f(new_s) > f(s) or acceptance(s, new_s, T) > random.uniform(0, 1): s = new_s alpha *= beta T *= beta return s, f(s), f(12.6025895306) if __name__ == '__main__': print 'SOL: %s | RESULT: %s | TARGET: %s' % SA(15.0)
s = input("Input a string: ") digits = "" for i in s: if i.isdigit(): digits += i print(digits)
cost = float(input("Input the loan amount: ")) month = 0 payment = 50.0 remainder = cost if cost <= 1000: irate = 0.015 else: irate = 0.02 while True: month += 1 interest = remainder * irate remainder += interest -payment if remainder > 0: print("Month:", month, "Payment:", round(payment, 2), "Interest paid: ", round(interest, 2), "Remaining debt: ", round(remainder, 2)) else: payment += remainder remainder = 0 print("Month:", month, "Payment: ", round(payment, 2), "Interest paid: ", round(interest, 2), "Remaining debt: ", round(remainder, 2)) break if cost < 0: print("error") elif cost > 1000: irate = 0.02 month += 1
# palindrome function definition goes here def palindrome(mystr): mystr = mystr.lower() newstr = "" for i in mystr: if i.isalpha(): newstr += i if newstr == newstr[::-1]: return True else: return False in_str = input("Enter a string: ") # call the function and print out the appropriate message pal = palindrome(in_str) if pal == True: print(f'"{in_str}" is a palindrome.') else: print(f'"{in_str}" is not a palindrome.')
top_num = int(input("Upper number for the range: ")) # Do not change this line for i in range (1,top_num+1): summa=0 for j in range(1,i): if (i % j) == 0: summa += j if i == summa: print(i)
num1 = int(input("Input a number: ")) num2 = int(input("Input a number: ")) if num1 > num2: print(num1, "is greater") elif num2 > num1: print(num2, "is greater") else: print("The numbers are equal")
celsius = int(input("Input temperature in celsius: ")) farenheit = int(celsius * 9/5 + 32) print(celsius,"°C is", farenheit, "°F")
num = int(input("Input an int: ")) # Do not change this line summa = 0 for i in range(1, num+1): summa += i print(summa)
# _*_coding:utf-8_*_ # 创建用户 :chenzhengwei # 创建日期 :2019/7/12 上午10:39 """ 以升序的形式维护已排列的可变序列 """ import bisect list1 = [] bisect.insort(list1, 2) bisect.insort(list1, 1) bisect.insort(list1, 8) bisect.insort(list1, 5) print(list1) print(bisect.bisect_right(list1, 2)) # print(list1) print(bisect.bisect_left(list1, 2)) print(list1)
# _*_coding:utf-8_*_ # 创建用户 :chenzhengwei # 创建日期 :2019/7/10 下午2:42 """ python自省 在运行时能够获得对象的类型。 type(),判断对象类型 dir(), 带参数时获得该对象的所有属性和方法;不带参数时,返回当前范围内的变量、方法和定义的类型列表 isinstance(),判断对象是否是已知类型 hasattr(),判断对象是否包含对应属性 getattr(),获取对象属性 setattr(), 设置对象属性 """ # type print(type(123)) # <class 'int'> print(type('123')) # <class 'str'> print(type(None)) # <class 'NoneType'> # dir print(dir(123)) # dir(123) <==> dir(int),dir('123') <==> dir(str) print(dir()) # isinstance a = 123 b = '123' print(isinstance(a, int)) # True print(isinstance(b, str)) # True # hasattr class Obj(object): def __init__(self, x): self.x = x obj = Obj(1) print(hasattr(obj, 'x')) # True print(hasattr(obj, 'y')) # False # getattr print(getattr(obj, 'x', 123)) # 1 print(getattr(obj, 'y', 123)) # 123 # setattr setattr(obj, 'y', 123) print(getattr(obj, 'y', None)) # 123
# open the input file and read the contents text_file = open('curiosity_shop.txt') text = text_file.read() # find the position of the period which separates the sentences period_position = text.find('.') # extract the first sentence and write it to an output file first_sentence = text[0:period_position+1] first_sentence_file = open('first_sentence.txt', 'w') first_sentence_file.write(first_sentence) first_sentence_file.close() # extract the second sentence and write it to an output file second_sentence = text[period_position+1:] second_sentence_file = open('second_sentence.txt', 'w') second_sentence_file.write(second_sentence) second_sentence_file.close()
year = int(input("Enter Year: ")) if year % 4 == 0 & year % 100 != 0: print(year, "yes") elif year % 100 == 0: print(year, "no") elif year % 400 ==0: print(year, "yes") else: print(year, "no")
import unittest from oop import * class oopTest(unittest.TestCase): def test_person_instance(self): tenant1 = Tenant('Sue', 'Jackson', 10000) owner1 = Property_owner('Ian', 'Smith', [tenant1]) self.assertIsInstance(owner1, Person, msg='The object should be an instance of the `Person` class') def test_object_type(self): tenant1 = Tenant('Sue', 'Jackson', 10000) self.assertTrue((type(tenant1) is Tenant), msg='The object should be a type of `Tenant`') if __name__ == '__main__': unittest.main()
class Order: """ Initiated a new order for the store """ def __init__(self, order_number, product_id, item_type, name, product_details, factory, quantity, holiday): """ Construct a new order :param order_number: str :param product_id: str :param item_type: str :param name: str :param product_details: str :param factory: Factory :param quantity: int :param holiday: str """ self._order_number = order_number self._product_id = product_id self._item_type = item_type self._name = name self._product_details = product_details self._factory = factory self._quantity = quantity self._holiday = holiday self._is_valid = True self._invalid_notes = "" @property def quantity(self): """ Return quantity of the order. :return: int """ return self._quantity @property def order_num(self): """ Return order num of the order. :return: str """ return self._order_number @property def product_id(self): """ Return product id of the order. :return: str """ return self._product_id @property def item_type(self): """ Return item type of the order. :return: str """ return self._item_type @property def name(self): """ Return item name of the order. :return: str """ return self._name @property def product_details(self): """ Return other details of the item of the order. :return: str """ return self._product_details @property def factory(self): """ Return the factory that can generate the item. :return: Factory """ return self._factory @property def holiday(self): """ Return the holiday that the item for. :return: str """ return self._holiday @property def invalid_notes(self): """ Return the invalid notes if the item is invalid. :return: str """ return self._invalid_notes @property def is_valid(self): """ Return the valid status. :return: str """ return self._is_valid def is_invalid(self): """ Set the status to invalid. """ self._is_valid = False def set_invalid_notes(self, error): """ Set the invalid notes. :param error: str """ self._invalid_notes = error def __str__(self): """ String method of the class. """ return f"Order Number: {self._order_number} " \ f"Product ID: {self._product_id} " \ f"Item: {self._item_type} " \ f"Name: {self._name} " \ f"Quantity: {self._quantity} " \ f"Product details: {self._product_details} "
from enum import Enum class Fabric(Enum): """ The Fabric of the stuffed animal, can either be Linen, Cotton or Acrylic. """ LINEN = "Linen" COTTON = "Cotton" ACRYLIC = "Acrylic" def __str__(self): """ String method of the class. :return: str """ return str(self.value)
""" Implements the observer pattern and simulates a simple auction. """ import random class Auctioneer: """ The auctioneer acts as the "core". This class is responsible for tracking the highest bid and notifying the bidders if it changes. """ def __init__(self): """ Initialize an Auctioneer. """ self.bidders = [] self._highest_bid = 0 self._highest_bidder = None def register_bidder(self, bidder): """ Adds a bidder to the list of tracked bidders. :param bidder: object with __call__(auctioneer) interface. """ self.bidders.append(bidder) def reset_auctioneer(self): """ Resets the auctioneer. Removes all the bidders and resets the highest bid to 0. """ self._highest_bidder = None self.bidders.clear() self._highest_bid = 0 def _notify_bidders(self): """ Executes all the bidder callbacks. Should only be called if the highest bid has changed. """ for bidder in self.bidders: if self._highest_bidder is not bidder: bidder(self) def accept_bid(self, bid, bidder): """ Accepts a new bid and updates the highest bid. This notifies all the bidders via their callbacks. :param bid: a float. :precondition bid: should be higher than the existing bid. :param bidder: The object with __call__(auctioneer) that placed the bid. """ if bid > self._highest_bid: if self._highest_bidder is not None: print(f"{bidder.name} bidded {bid} in response to " f"{self._highest_bidder.name}'s bid of {self._highest_bid}") else: print(f"{bidder.name} bidded {bid} in response to " f"Starting bid's bid of {self._highest_bid}") self._highest_bidder = bidder self._highest_bid = bid self._notify_bidders() def start_bidding(self, start_price): """ Start bidding with the start price :param start_price: a float """ self._highest_bid = start_price self._notify_bidders() def check_if_fail_auction(self): """ Check if the auction failed. :return: a boolean """ return self._highest_bidder is None @property def highest_bid(self): """ Return the highest bid. :return: a float """ return self._highest_bid @property def highest_bidder_name(self): """ Return the name of the highest bid bidder. :return: a string """ return self._highest_bidder.name class Bidder: def __init__(self, name, budget=100, bid_probability=0.35, bid_increase_perc=1.1): """ Initialize a bidder that requires several bidder info. :param name: a string :param budget: a float :param bid_probability: a float :param bid_increase_perc: a float """ self.name = name self.bid_probability = bid_probability self.budget = budget self.bid_increase_perc = bid_increase_perc self.highest_bid = 0 def __call__(self, auctioneer): """ Callable function of the Bidder. :param auctioneer: an Auctioneer """ bid_or_not = random.random() if bid_or_not < self.bid_probability: bid_price = auctioneer.highest_bid * self.bid_increase_perc if bid_price <= self.budget: self.highest_bid = bid_price auctioneer.accept_bid(bid_price, self) def get_highest_bid(self): """ Return the highest bid of the bidder. :return: a float """ return self.highest_bid def get_budget(self): """ Return the budget of the bidder. :return: a float """ return self.budget def get_bid_prob(self): """ Return the bid probability of the bidder. :return: a float """ return self.bid_probability def get_increase_perc(self): """ Return the percentage of increasing bid. :return: a float """ return self.bid_increase_perc def __str__(self): """ String method of the bidder. :return: a string """ return self.name class Auction: """ Simulates an auction. Is responsible for driving the auctioneer and the bidders. """ def __init__(self, bidders): """ Initialize an auction. Requires a list of bidders that are attending the auction and can bid. :param bidders: sequence type of objects of type Bidder """ self.auctioneer = Auctioneer() for bidder in bidders: self.auctioneer.register_bidder(bidder) def simulate_auction(self, item, start_price): """ Starts the auction for the given item at the given starting price. Drives the auction till completion and prints the results. :param item: string, name of item. :param start_price: float """ print(f"\nAuctioning {item} starting at {start_price}") self.auctioneer.start_bidding(start_price) if self.auctioneer.check_if_fail_auction(): print("The auction failed! No one throw a bid.") return print(f"\nThe winner of the auction is: {self.auctioneer.highest_bidder_name}" f" at ${self.auctioneer.highest_bid}\n") print("Highest Bids Per Bidder") highest_bids = {bidder: bidder.highest_bid for bidder in self.auctioneer.bidders} for name, bid in highest_bids.items(): print(f"Bidder: {name} Highest Bid: {bid}") def main(): """ Driver function of the program. """ bidders = [] while True: print("Welcome!\nWould you like to use hardcoded bidders or new custom bidders?\n" "1. Hardcoded bidders\n2. Add Custom Bidders") menu_input = input("please enter the number: ") if menu_input == "1": # Hardcoding the bidders. bidders.append(Bidder("Jojo", 3000, random.random(), 1.2)) bidders.append(Bidder("Melissa", 7000, random.random(), 1.5)) bidders.append(Bidder("Priya", 15000, random.random(), 1.1)) bidders.append(Bidder("Kewei", 800, random.random(), 1.9)) bidders.append(Bidder("Scott", 4000, random.random(), 2)) break elif menu_input == "2": custom_bidders_num = input("How many bidders do you want to add?: ") try: for i in range(int(custom_bidders_num)): bidder_name = input(f"The name of the bidder{i}: ") bidder_budget = int(input(f"The budget of the bidder{i}: ")) bidders.append(Bidder(bidder_name, bidder_budget, random.random(), random.random() + 1)) break except Exception as e: print(e) else: print("Invalid Input. Please try again") print("-" * 20, "The list of bidders") for bidder in bidders: print(f"Name: {bidder}, Budget: {bidder.get_budget()}, Probability of bid: {bidder.get_bid_prob()}" f", Percentage of increase: {bidder.get_increase_perc()}") while True: try: bid_item_name = input("Please enter the name of the bid item: ") bid_item_start_price = float(input("Please set the start price of the item: ")) print("\n\nStarting Auction!!") print("------------------") my_auction = Auction(bidders) my_auction.simulate_auction(bid_item_name, bid_item_start_price) break except Exception as e: print(e) if __name__ == '__main__': main()
#!/usr/bin/env python from pleeplee.geometry import (Point, Triangle, rotateAngle, rotateVector, angleBetween2Vects, PRECISION) from pleeplee.utils import Color from math import sqrt # Test the Point class def test_point_distance(): point1 = Point(2.0, 4.5) point2 = Point(3.4, 6.7) assert point1.distance(point2) == point2.distance(point1) assert point1.distance(point2) == round(sqrt(6.8), PRECISION) def test_point_eq(): point1 = Point(2.05, 4.3) x = point1.X + point1._threshold - 0.01 point2 = Point(x, 4.3) assert point1 == point2 def test_point_not_eq(): point1 = Point(2.05, 4.3) x = point1.X + point1._threshold + 0.01 point2 = Point(x, 4.3) assert not point1 == point2 def test_point_minus(): point1 = Point(2.0, 4.5) point2 = Point(3.4, 6.7) assert point1.minus(point2) == (-1.4, -2.2) # Test the Triangle class def test_triangle_corner(): point = Point(2.0, 4.5) angle = 24.56 triangle = Triangle(angle, point, Color.RED) # The triangle must be rectangle. Sum of the angles of triangle = 180 degree assert triangle.angleP + triangle.cornerAngle() + 90 == 180 def test_rotate_angle(): assert rotateAngle(34.89) == 34.89 + 45 assert rotateAngle(-179.34) == -179.34 + 45 assert rotateAngle(169.28) == 169.28 - 360 + 45 def test_rotate_vector_simple(): assert rotateVector((10.0, 0.0), -90) == (0, 10) val = round(5 * sqrt(2), PRECISION) assert rotateVector((10.0, 0.0), -45) == (val, val) assert rotateVector((10.0, 0.0), 45) == (val, -val) def test_angle_two_vects(): assert angleBetween2Vects((10, 0), (0, 10)) == 90 val = round(5 * sqrt(2), PRECISION) assert angleBetween2Vects((10, 0), (val, -val)) == -45
''' in terminal: python spheres.py ''' import random import math import scipy from scipy import stats #return radius (in angstroms) of a sphere representing a protein # of randomly generated chain length betwen 80-500 residues def return_sphere(): l = random.randint(80, 500) w = l*110 r = 10*(0.066*(w**(1./3))) return l,r #generate a set of cartesian coordinates for a random point on the #surface of a sphere of radius r pi = math.pi def return_coords(r): u = random.random() v = random.random() theta = math.acos(2*v-1) phi = 2*pi*u x = r*((math.sin(theta))*(math.cos(phi))) y = r*((math.sin(theta))*(math.sin(phi))) z = r*(math.cos(theta)) coordinates = (x,y,z) return coordinates #set of functions to get the distance between 2 points (norm of #displacement vector) def displace(p1,p2): x = p1[0] - p2[0] y = p1[1] - p2[1] z = p1[2] - p2[2] return (x,y,z) def norm(x): return math.sqrt(sum(i**2 for i in x)) def dist(p1,p2): v = displace(p1,p2) return norm(v) #check distances between a given point and list of points to ensure #they are all greater than 2.5 angstroms def check_dists(p, list): dists = [] try: for i in list: d = dist(p,i) dists.append(d) except: pass clash = [x for x in dists if x < 2.50] if len(clash)>0: return False else: return True #take a list of coordinates and assign each point as negative or #positive based on an input probability #for selecting a negative point (R =1.212 meso, 1.130 thermo; #P = 0.5479 meso, 0.5305 thermo) def assign_q(list, P_neg): neg = [] pos = [] for p in list: x = random.random() if x <= P_neg: neg.append(p) else: pos.append(p) return neg, pos #function to mimic analysis of charge distributions in proteins #identifies 'attractive' and 'repulsive' interactions between points #using input cutoff distance (5 and 7 A) and reports the #number of interaxns, branching, ratio of rep to atr, #and the fraction of isolated points def properties(coords, neg, pos, d_cut): pairs = [] anti_pairs = [] for n in neg: for p in pos: if dist(n,p) <= d_cut: pairs.append((n,p)) for i in neg: if 0 < dist(n,i) <= d_cut: anti_pairs.append((n,p)) n_ip = len(pairs) n_ap = float(len(anti_pairs)) try: ratio_rep_atr = n_ap/n_ip except: ratio_rep_atr = 0.0 n_points = float(len(coords)) branched = [] for i in coords: count = [] for n,p in pairs: if i == n: count.append(n) elif i == p: count.append(p) n_interaxns = len(count) if n_interaxns > 1: branched.append(i) n_branched = float(len(branched)) ip_points = [] for a,b in pairs: if a not in ip_points: ip_points.append(a) if b not in ip_points: ip_points.append(b) n_ip_points = len(ip_points) try: frac_branched = n_branched/n_ip_points except: frac_branched = 0.0 n_iso = float(n_points - n_ip_points) frac_iso = n_iso/n_points return n_points,n_ip, ratio_rep_atr, frac_iso, frac_branched ####################################### meso_nq = []; thermo_nq = [] meso_nips = []; thermo_nips = [] meso_ratios = []; thermo_ratios = [] meso_isos = []; thermo_isos = [] meso_branches = []; thermo_branches = [] for x in range(10000): coords = [] l,r = return_sphere() nqm_nres = random.gauss(0.234, 0.034) nqm = int(round(nqm_nres*l)) while len(coords) < nqm: p = return_coords(r) if check_dists(p,coords) == True: coords.append(p) else: continue neg,pos = assign_q(coords, 0.5) np, n_ip, ratio_rep_atr, frac_iso, frac_branched = properties(coords, neg, pos, 5.0) norm_nq = np/float(l) norm_nip = n_ip/float(l) meso_nq.append(norm_nq) meso_nips.append(norm_nip);meso_ratios.append(ratio_rep_atr) meso_isos.append(frac_iso);meso_branches.append(frac_branched) coords = [] ##########now repeat for therm dist on same sphere nqt_nres = random.gauss(0.279, 0.033) nqt = int(round(nqt_nres*l)) while len(coords) < nqt: p = return_coords(r) if check_dists(p,coords) == True: coords.append(p) else: continue neg,pos = assign_q(coords, 0.5) np, n_ip, ratio_rep_atr, frac_iso, frac_branched = properties(coords, neg, pos, 5.0) norm_nip = n_ip/float(l) norm_nq = np/float(l) thermo_nq.append(norm_nq) thermo_nips.append(norm_nip);thermo_ratios.append(ratio_rep_atr) thermo_isos.append(frac_iso);thermo_branches.append(frac_branched) ####function to get stats on lists of values def stats(meso_list,thermo_list): meso_array = scipy.array(meso_list) thermo_array = scipy.array(thermo_list) meso_mean = scipy.mean(meso_array) meso_std = scipy.std(meso_array) thermo_mean = scipy.mean(thermo_array) thermo_std = scipy.std(thermo_array) p_val = scipy.stats.ttest_ind(thermo_array,meso_array)[1] s = '\nMm: ' + str(meso_mean) + '\nSTDm: ' + str(meso_std) + '\nMt: ' + str(thermo_mean) + '\nSTDt: ' + str(thermo_std) + '\nP: ' + str(p_val) return s ######get the stats and write to outfile ofile = open('results5A-10k-P5050-thesisnorm-wnq.txt','w') nip_stats = stats(meso_nips, thermo_nips) s1 = 'Normalized N_ip: ' + nip_stats + '\n' ofile.write(s1) ratio_stats = stats(meso_ratios, thermo_ratios) s2 = '\nRatio rep atr: ' + ratio_stats + '\n' ofile.write(s2) iso_stats = stats(meso_isos, thermo_isos) s3 = '\nFraction isolated: ' + iso_stats + '\n' ofile.write(s3) branched_stats = stats(meso_branches, thermo_branches) s4 = '\nFraction branched: ' + branched_stats + '\n' ofile.write(s4) meso_nip_data = str(meso_nips);thermo_nip_data = str(thermo_nips) meso_ratio_data = str(meso_ratios);thermo_ratio_data = str(thermo_ratios) meso_iso_data = str(meso_isos);thermo_iso_data = str(thermo_isos) meso_branched_data = str(meso_branches);thermo_branched_data = str(thermo_branches) s5 = '\nN_ip data: ' + '\nMESO: ' + meso_nip_data + '\nTHERMO: ' + thermo_nip_data s6 = '\nRatio data: ' + '\nMESO: ' + meso_ratio_data + '\nTHERMO: ' + thermo_ratio_data s7 = '\niso data: ' + '\nMESO: ' + meso_iso_data + '\nTHERMO: ' + thermo_iso_data s8 = '\nbranched data: ' + '\nMESO: ' + meso_branched_data + '\nTHERMO: ' + thermo_branched_data ofile.write(s5) ofile.write(s6) ofile.write(s7) ofile.write(s8) nq_stats = stats(meso_nq,thermo_nq) s9 = '\nq over nres: ' + nq_stats + '\n' ofile.write(s9) ofile.close() ''' to make a 3d scatter plot of the points: from matplotlib import pyplot from mpl_toolkits.mplot3d import Axes3D l,r = return_sphere() coords = [] for i in range(1000): coords.append(return_coords(r)) xs = [] ys =[] zs = [] for x,y,z in coords: xs.append(x) ys.append(y) zs.append(z) fig = pyplot.figure() ax = Axes3D(fig) ax.scatter(xs,ys,zs) pyplot.show() fig.savefig('plot.png') '''