text
stringlengths
37
1.41M
''' Name: Terence Tong Section: 202 - 9 ''' class StackArray: """Implements an efficient last-in first-out Abstract Data Type using a Python List""" def __init__(self, capacity): """Creates and empty stack with a capacity""" self.capacity = capacity # this is example for list implementation self.items = [None]*capacity # this is example for list implementation self.num_items = 0 # this is example for list implementation def is_empty(self): """Returns true if the stack self is empty and false otherwise""" if self.num_items == 0: return True return False def is_full(self): """Returns true if the stack self is full and false otherwise""" if self.num_items == self.capacity: return True return False def push(self, item): if(self.is_full()): raise IndexError else: self.items[self.num_items] = item self.num_items += 1 def pop(self): if (self.is_empty()): raise IndexError("there is nothing left to pop") else: self.num_items -= 1 temp = self.items[self.num_items] self.items[self.num_items] = None return temp def peek(self): if self.is_empty(): return None else: return self.items[self.num_items-1] def size(self): """Returns the number of elements currently in the stack, not the capacity""" return self.num_items def __repr__(self): return ('StackArray({}), Capacity: {}').format(self.items, self.capacity) def __eq__(self, other): return self.items == other.items class Node: def __init__(self, data): self.data = data self.next = None def getNext(self): return self.next def getData(self): return self.data def setNext(self, next): self.next = next def setData(self, data): self.data = data def __repr__(self): return self.getData() ''' def __eq__(self,other): if other == None: return False return self.data == other.data ''' class StackLinked: """Implements an efficient last-in first-out Abstract Data Type using a Python List""" def __init__(self, capacity): """Creates and empty stack with a capacity""" self.capacity = capacity # this is example for list implementation self.items = None# this is example for list implementation self.num_items = 0 # this is example for list implementation def is_empty(self): """Returns true if the stack self is empty and false otherwise""" if self.num_items == 0: return True return False def is_full(self): """Returns true if the stack self is full and false otherwise""" if self.num_items == self.capacity: return True return False def push(self, item): numOfItem = 1 node = Node(item) if self.is_full(): raise IndexError ''' if not lastItem.getNext() == None: #check if the node has other nodes attached to it while(not lastItem.getNext() == None): #runs a loop to see how many nodes are connected numOfItem += 1 #adds numOfItem for each additional node attatched lastItem = lastItem.getNext() #changes the conditional of the while loop to keep looping if numOfItem + self.num_items > self.capacity: # checks to see the chain of nodes is not larger than the capacity raise IndexError ''' self.num_items += 1 #numOfItem if self.items == None: #so we dont have the initial empty node initially self.items = node else: temp = self.items self.items = node node.setNext(temp) # accounts for mutiple nodes added def pop(self): if self.is_empty(): raise IndexError else: self.num_items -= 1 temp = self.items self.items = self.items.getNext() return temp.getData() def peek(self): return self.items.getData() def size(self): """Returns the number of elements currently in the stack, not the capacity""" return self.num_items def __repr__(self): return ('StackLinked(Nodes: {}, Capacity: {}), ').format(self.items, self.capacity) def __eq__(self, other): return self.items == other.items and self.capacity == other.capacity and self.num_items == other.num_items ''' stacklink = StackLinked(5) stacklink1 = StackLinked(5) node1 = Node(1) node2 = Node(2) node3 = Node(3) node4 = Node(4) node5 = Node(5) stacklink.push(node1) stacklink.push(node2) print(node3.getNext()) stacklink.push(node3) stacklink.push(node4) stacklink.push(node5) stacklink1.push(node1) stacklink1.push(node2) stacklink1.push(node3) print(stacklink == stacklink1) print(stacklink1.capacity) '''
# Name: Terence Tong # Class: CSC 202 - 9 # key things about the MaxHeap class, # index[0] is empty, # index[1] is the parent node, # index[even] are left nodes # index[odd] are right nodes # ask about what the heap contents is supposed to return class MaxHeap: def __init__(self, capacity=50): self.heapList = [0] self.currentSize = 0 self.capacity = capacity # inserts “item” into the heap, returns true if successful, false if there is no room in the heap # item -> boolean def insert(self, item): if self.currentSize == self.capacity: return False self.currentSize += 1 self.heapList.append(item) self.perc_up(self.currentSize) return True # returns max without changing the heap and return None if not found # None -> item or None def find_max(self): return None if self.is_empty() else self.heapList[1] # returns max and removes it from the heap and restores the heap property and return None if heap is empty # None -> None or int def del_max(self): #print('deleting') if self.is_empty(): return None tmp = self.heapList[1] self.heapList[1] = self.heapList[self.currentSize] self.currentSize -= 1 self.heapList.pop() self.perc_down(1) return tmp # returns a list of contents of the heap in the order it is stored internal to the heap. # (This may be useful for in testing your implementation.) # None -> String def heap_contents(self): return self.heapList[1:] # Method buildHeap that has a single explicit argument “list of int” and builds a heap using the bottom up method # discussed in class. It should return True if the build was successful and False if the capacity of the MaxHeap # object is not large enough to hold the “array of int” argument. # list of int -> list of int def build_heap(self, alist): if len(alist) > self.capacity: return False i = len(alist) // 2 self.currentSize = len(alist) self.heapList = [0] + alist[:] while i > 0: self.perc_down(i) i = i - 1 return True # returns True if the heap is empty, false otherwise # None -> boolean def is_empty(self): return self.currentSize == 0 # returns True if the heap is full, false otherwise # None -> boolean def is_full(self): return self.currentSize == self.capacity # this is the maximum number of a entries the heap can hold - 1 less than the number of entries that the array # allocated to hold the heap can hold. # None -> int def get_heap_cap(self): return self.capacity # the actual number of elements in the heap, not the capacity # None -> boolean def get_heap_size(self): return self.currentSize # where the parameter i is an index in the heap and perc_down moves the element stored at that location to its # proper place in the heap rearranging elements as it goes. Since this is an internal method we will assume that # the element is either in the correct position or the correct position is below the current position. # index -> None def perc_down(self, i): while (i * 2) <= self.currentSize: mc = self.maxChild(i) if self.heapList[i] < self.heapList[mc]: tmp = self.heapList[i] self.heapList[i] = self.heapList[mc] self.heapList[mc] = tmp i = mc # helper for perc_down # index -> index def maxChild(self, i): if i * 2 + 1 > self.currentSize: return i * 2 else: #print('maxChild', self.heapList) if self.heapList[i * 2] > self.heapList[i * 2 + 1]: return i * 2 else: return i * 2 + 1 # similar specification as perc_down, see class notes Normally these would be private but make them public # for testing purposes. # index -> index def perc_up(self, i): while i // 2 > 0: if self.heapList[i] > self.heapList[i // 2]: tmp = self.heapList[i // 2] self.heapList[i // 2] = self.heapList[i] self.heapList[i] = tmp i = i // 2 def __repr__(self): return 'Capacity: {}, Current Size: {}, List: {}'.format(self.capacity, self.currentSize, self.heapList) # takes a list of integers and returns a list containing the integers in non-decreasing order using the Heap Sort # algorithm as described in class. Since your MaxHeap class is a max heap using the list internal to the heap to # store the sorted elements will result in them being sorted in increasing order. This enables the reuse of the # space but will destroy the heap order property. However, then you can just return the appropriate part of the # internal list since you will not be using the heap anymore. def heap_sort_increase(alist): h = MaxHeap(len(alist)) h.build_heap(alist) sortedList = [] while h.currentSize > 0: tmp = h.del_max() sortedList = [tmp] + sortedList return sortedList
""" Name: Rohan Ramani, Terence Tong Section: 202 - 9 """ import random # creates and prints a random list of numbers def listGenerator(): alist = [] for i in range(100000): # integer random numbers between 10 and 70 n = random.randint(10, 70) alist.append(n) print(alist) return alist ''' Terence Tong write a insert sort algorithm list of integers -> list of integers ''' def insert_sort(alist): ind = 1 comp = 0 while ind < len(alist): j = ind while j > 0 and alist[j-1] > alist[j]: comp += 1 temp = alist[j] alist[j] = alist[j-1] alist[j-1] = temp j -= 1 ind += 1 print('Insert Sort Comparisons:', comp) return alist l1 = listGenerator() l2 = l1.copy() l2 = sorted(l2) print(insert_sort(l1)) print(insert_sort(l2)) """ Terence Tong write an selection algorithm list of integers -> list of integers selection sort finds the smallest number and puts it in the front """ def select_sort(alist): comparisons = 0 for i in range(len(alist)): minimum = alist[i] index = i for j in range(i, len(alist)): comparisons += 1 if alist[j] < minimum: minimum = alist[j] index = j alist[index] = alist[i] alist[i] = minimum print('Select Sort Comparisons: ', comparisons) return alist #print(select_sort(l1)) #print(select_sort(l2)) """ Rohan Ramani write a merge sort algorithm list of integers -> list of integers """ def merge_sort(alist): pass
#This script runs a simple "Hang Man" game through the Windows command window #This is a good starter assignment that includes looping, conditionals, simple built-in functions, and work with lists #Author: Daniel Kuhman #Contact: danielkuhman@gmail.com #Date created: 1/27/2020 import random import re file_handle = open('hangman_words.txt','r') #This file contains words that will be selected randomly print('Welcome to Hang Man!') #Compile the words in the imported file list_of_words = list() for line in file_handle: list_of_words.append(line.rstrip()) #Start new game game_status = 1 while game_status == 1: #Select a random word from the list game_word = random.choice(list_of_words) #Show the user the number of letters in the game word display_word = list() for i in range(len(game_word)): display_word.append('_ ') print('Your word:',''.join(display_word)) #Start the game list_of_guesses = list() misses = 0 #The user gets 6 misses before the game ends while misses < 6: user_guess = input('Guess a letter:') user_guess = user_guess.lower() if len(user_guess) > 1: print('Your guess must be a single letter!') else: if user_guess in list_of_guesses: #See if the letter was already guessed print('You already guessed that letter!') elif user_guess.isalpha() == False: #Ensure input is alphabetical print('Your guess must be a letter!') else: list_of_guesses.append(user_guess) if user_guess not in game_word: misses = misses + 1 print('Oh no! That letter is not in this word!') print('You have', 6 - misses, 'left!') if misses == 6: print('Oh no! You lost!') print('The game word was', game_word) break else: print('Nice guess!') #correct_list = list() for match in re.finditer(user_guess,game_word): #Needed to see if the letter appears more than once display_word[match.start()] = user_guess print('Your word:',''.join(display_word)) if ''.join(display_word) == game_word: print('Congratulations! You won!') break play_again = input('Would you like to keep playing? (y/n): ') play_again = play_again.lower() if play_again == 'y': game_status = 1 else: game_status = 0 break
# # program that asks the user to enter a list of integer print("????????????????? Question1 ////////////////\n") lis = [] n = int(input("Enter number of elements you want to save in list : ")) for id in range(n): num = int(input("enter numbers: ")) lis.append(num) # Print the total number of items in the list. print("list: ",lis) # Print the last item in the list print("Last digit of List: ",lis[-1]) #Print the list in reverse order. print("using slicing reverse List: ",lis[::-1]) #start:end:step print("using for loop with built in reversed function") for item in reversed(lis): print(item) #Print Yes if the list contains a 5 and No otherwise print("search 5 yes else no: \n") if 5 in lis: print("\tyes 5 appear ") else: print("\tno 5 not appear") #Print the number of fives in the list. c = lis.count(5) print("Number of 5 in list: ",c) # Print how many integers in the list are less than 5 k = 5 count = 0 for i in lis: if i < k: count = count + 1 print("The numbers less than 5 : " + str(count)) # Remove the first and last items from the list, sort the remaining items, and print the result using pop(0) to perform removal lis.pop(0) lis.pop(-1) print("sorted list by removing first or last element: ",sorted(lis))
import unittest from WordFrequency import pre_process, count_words, sort_words_by_count class Test(unittest.TestCase): def test_pre_process(self): test_string = "This [is] a (sample) 100 @$string's, where we will test-string preprocessing ." expected_output = "this is a sample string s where we will test string preprocessing" result = pre_process(test_string) self.assertEqual(str(result), expected_output) def test_count_words(self): test_string = "this is a sample string of word frequency this string count word count or frequency of each string" expected_output = {'this': 2, 'sample': 1, 'string': 3, 'word': 2, 'frequency': 2, 'count': 2, 'each': 1} result = count_words(test_string) self.assertEqual(result, expected_output) def test_sort_words_by_count(self): test_word_count_dict = {'this': 2, 'sample': 1, 'string': 3, 'word': 2, 'frequency': 2, 'count': 2, 'each': 1} expected_output = [('string', 3), ('this', 2), ('word', 2), ('frequency', 2), ('count', 2), ('sample', 1), ('each', 1)] result = sort_words_by_count(test_word_count_dict) self.assertEqual(result, expected_output) if __name__ == '__main__': unittest.main()
Min_equal_Max=[] MinMax=[] def find_max_min(fruits): if (min(fruits))==(max(fruits)): Min_equal_Max.append(len(fruits)) print(Min_equal_Max) return Min_equal_Max elif(min(fruits))<(max(fruits)): MinMax.append(min(fruits)) MinMax.append(max(fruits)) print (MinMax) return MinMax (find_max_min([1,1,1,1])) (find_max_min([7,2,1,9,3,0,3,2,]))
phone_number = { "james": "945-394-2356", "miranda": "648-384-2345" } result = phone_number["james"] print ("This is James phone number",result) result = phone_number["miranda"] print ("This is Miranda's phone number",result)
print("-----------задание 1---------") print("Hello, World!") print("Маша + Петя = Любовь") x=3+4 print("x=3+4") print("x=",x) print("------------задание 2--------") x='Hello, World!' print(type(x)) x=3+4 print(type(x)) x=3/4 print(type(x)) x=[1,2,5,10,100] print(type(x)) print("------------задание 3--------") x=3 y=(x**2)**0.5/(x**3+3/x)*(4*x**7-x**5)+80*((27*x**4+12*x**3-5*x**2+10)**0.5) print(y) x=3 y=(3%2+(16.7*4.32)//1)/(14.5+31%12-(x**3.4)//1) print(y) print("------------задание 4--------") a=[1,5,'Good','Bad'] b=[9,'Blue','Red',11] print(a[1]+b[3]) print(a[2]+b[2]) print(a[0]+b[0]) print(a[1]**b[3]) print(a+b)
import random import os import time clearConsole = lambda: os.system('cls' if os.name in ('nt', 'dos') else 'clear') # Score is going to be a global variable user_score = 0 # Define few constant values score_for_correct_guess = 10 score_for_wrong_guess = -3 range_dict = dict({'A': [1,10], 'B': [1,20], 'C': [1,50], 'D': [1,100]}) def displayRangesToUser(): print("Available number ranges are ->") print(" \ 1-10 : enter 'A' \n \ 1-20 : enter 'B' \n \ 1-50 : enter 'C' \n \ 1-100 : enter 'D' \n \ ") def generateNumberEachRun(user_selection): if (user_selection not in ['A','B','C','D']): print("WARN: Please enter your choice as - A/B/C/D") else: minIndex = range_dict.get(user_selection)[0] maxIndex = range_dict.get(user_selection)[1] var_number_generated = random.randint(minIndex, maxIndex) return var_number_generated def shuffleSequence(aList): random.shuffle(aList) return aList def scoreCard(machine_generates, human_guess): global user_score if (human_guess == machine_generates): user_score += score_for_correct_guess print("Yayy...You WON!!!") else: user_score += score_for_wrong_guess if user_score < 0: user_score = 0 print("Better luck next time!!!") def numberGuessingGame(): while(True): clearConsole() print("Enter the Game...") user_play_on = input("Press N to exit or, any other key to continue -> ").upper() if ('N' == user_play_on): print("Your final Score =",user_score,", See you next time!!!") break print("------------") displayRangesToUser() print("------------") var_number_generated = 0 while(var_number_generated == 0): selection_number_range = input("Choose the range for your practice? - ").upper() var_number_generated = generateNumberEachRun(selection_number_range) print("------------") user_display_list = shuffleSequence([var_number_generated,(var_number_generated - random.randint(1,10)),(var_number_generated + random.randint(1,10))]) print("The hints for you, are -> ", user_display_list) print("------------") while(True): try: user_answer = int(input("Your answer is -> ")) scoreCard(user_answer, var_number_generated) print ("Your current score is = ", user_score) break except ValueError: print("ERROR: Please enter a number from the choices") continue time.sleep(2) print("-/-/-/-/-/-/-/-/") numberGuessingGame()
#!/usr/bin/env python # @author FAN Kai (fankai@net.pku.edu.cn), Peking University # @date May 25 06:09:25 PM CST 2009 def foo(s): m = 1 ms = s for i in range(1, len(s)): s = s[1:] + s[0] #print 'ms=',ms, 's=', s if s < ms: ms = s m = i+1 #print 'ms=', ms, 'm=', m return m def test(): assert foo('helloworld')==10 assert foo('amandamanda')==11 assert foo('aaabaaa')==5 assert foo('dontcallmebfu')==6 test() n = input() while n > 0: n -= 1 print foo(raw_input())
import math import numpy as np def user_input() -> list: ''' Пользовательский ввод для заполнения списка ''' n = int(input("Введите n(размер массива): ")) arr = [] for i in range(0, n): x = float(input("Введите число: ")) arr.append(x) return arr def o136(a): """ Формула из 136 о """ sum = 0 for k in a: sum += math.sqrt(10 + k ** 2) return sum def v178(a): """ Определяет количество членов являющихся квадратами четных чисел; """ count = 0 for k in a: buf = math.sqrt(k) int_part = buf // 1 real_part = buf % 1 if (real_part == 0) and (int_part % 2 == 0): count += 1 return count def b334(n1, n2): """ Формула из 334 б """ sum_buf = 0 for i in range(0, n1): for j in range(0, n2): sum_buf += math.sin(i ** 3 + j ** 4) return sum_buf def a675(arr): """ Вставляет столбец а в квадратную матрицу arr перед последним столбцом """ n = len(arr) a = np.zeros((n, 1)) a[0:n, 0:1] = 1 b = arr[0:n, 0:n-1] c = arr[0:n, n-1:n] return np.hstack((b, a, c))
from time import time def print_board(arr, width=5): """Print a 2-demension array prettily Args: arr: the 2-demension array """ size = len(arr) def g(x): return f'{x}'.rjust(width, ' ') for i in range(size): for j in range(size): print(g(arr[i][j]), end='') print('') def time_costing(func): """Calculate the running time of a function""" def _wrapper_(*args, **kwargs): start = time() result = func(*args, **kwargs) print('time costing:', time() - start) return result return _wrapper_
# coding=utf-8 import tensorflow as tf import numpy as np # Placeholders are used to feed values from python to TensorFlow ops. We define # two placeholders, one for input feature x, and one for output y. x = tf.placeholder(dtype=tf.float32, shape=None, name='x') y = tf.placeholder(dtype=tf.float32, shape=None, name='y') # Assuming we know that the desired function is a polynomial of 2nd degree, we # allocate a vector of size 3 to hold the coefficients. The variable will be # automatically initialized with random noise. w = tf.get_variable('w', shape=[3,1]) # We define yhat to be our estimate of y. f= tf.stack([tf.square(x), x, tf.ones_like(x)],1 ) yhat = tf.squeeze(tf.matmul(f,w),1 ) # The loss is defined to be the l2 distance between our estimate of y and its # true value. + a shrinkage term, to ensure the resulting weights # would be small. loss = tf.nn.l2_loss(yhat - y) + 0.1 * tf.nn.l2_loss(w) # We use the Adam optimizer with learning rate set to 0.1 to minimize the loss. train_op= tf.train.AdamOptimizer(0.1).minimize(loss) def generate_data(): x_val=np.random.uniform(-10.0, 10, size=100) y_val =5* np.square(x_val)+3 return x_val,y_val sess=tf.Session() sess.run(tf.global_variables_initializer()) for _ in range (1000): x_val, y_val= generate_data() _, loss_val=sess.run([train_op, loss],{x:x_val, y: y_val} ) print(loss_val) print(sess.run([w]))
score = input("Enter Score: ") fscore = float(score) if fscore>1.0: print('error') elif fscore<0.0: print('error') elif fscore>=0.9: print('A') elif fscore>=0.8: print('B') elif fscore>=0.7: print('C') elif fscore>=0.6: print('D') elif fscore<0.6: print('F')
f = open("input.txt", "r") values = f.read().split() passwords = values[2::3] letters = [i[:-1] for i in values[1::3]] mins_maxes = values[::3] mins = [i[0:i.index("-")] for i in mins_maxes] maxes = [i[i.index("-")+1:] for i in mins_maxes] def pw_check(pw, letter, min, max): count = 0 for char in pw: if char == letter: count += 1 if count > max: return False return count >= min def pw_check_all(passwords, letters, mins, maxes): count = 0 for i in range(len(passwords)): pw = passwords[i] letter = letters[i] min = int(mins[i]) max = int(maxes[i]) if pw_check(pw, letter, min, max): count += 1 return count print("Part 1: ", pw_check_all(passwords, letters, mins, maxes))
def max_index(numbers): return numbers.index(max(numbers)) def magician_and_chocolates_easy(box, taken_time): chocolates = 0 while taken_time != 0: large_box = max_index(box) chocolates = chocolates + box[large_box] if boxes[large_box] == 0: break box[large_box] = float(box[large_box]/2) taken_time = taken_time - 1 return chocolates if __name__ == "__main__": box_number = int(input("Enter the total box number : ")) # 2 print("Enter the chocolates number of ", box_number, " boxes : ") boxes = list(int(num) for num in input().strip().split())[:box_number] # [6, 5] total_taken = int(input("Enter the taken number : ")) # 3 ans = magician_and_chocolates_easy(boxes, total_taken) # 14 print("Ans : ", int(ans))
visited = [] ans = [] def dfs(graph, node, visited): if node not in visited: visited.append(node) ans.append(node) for neighbour in graph[node]: dfs(graph, neighbour, visited) return ans if __name__ == "__main__": graph = { 'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': [] } start_node = 'A' ans = dfs(graph, start_node, visited) print("DFS : ", ans, "\n")
nome = input('Digite o seu nome: ') idade = int(input('Digite o seu nome: ')) print('Seu nome é', nome) print('Você tem', idade, 'anos')
from abc import ABC, abstractmethod class Robot(ABC): """Abstract base class to control mobile robots.""" def __init__(self, client_id: int, track: float, wheel_radius: float): """Robot class initializer. Args: client_id: CoppeliaSim connection handle. track: Distance between the centerline of two wheels on the same axle [m]. wheel_radius: Radius of the wheels [m]. """ self._client_id = client_id self._track = track self._wheel_radius = wheel_radius @abstractmethod def move(self, v: float, w: float): """Solve inverse kinematics and send commands to the motors. Args: v: Linear velocity of the robot center [m/s]. w: Angular velocity of the robot center [rad/s]. """ pass @abstractmethod def sense(self): """Acquire sensor readings.""" pass
n = int(input("Please input a number:")) test = (n % 2) if test == 1: print("odd number") elif test == 0: print("even number") if n < 0: print("negative number")
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import scipy.stats as stats # crea un data set ficticio centrado alrededor de los 27000 # con distribucion normal y desviacion estandar de 15000 con 10000 data points incomes = np.random.normal(27000, 15000, 10000) print "Mean: ",np.mean(incomes) print "Median: ",np.median(incomes) # Moda: creamos un data set de 500 edades entre los 19 y 99 years ages = np.random.randint(18, 99, 500) print "Mode: ", stats.mode(ages) plt.hist(incomes, 50) plt.show()
# 1 - Restrição entre diferença de Datas de Nascimento entre Pai e Filho def dataNascimento_pai_filho(pai,filho): if filho["nome"] in pai["ePai"]: return int(filho["dataNasc"].split('-')[2]) > int(pai["dataNasc"].split('-')[2]) + 13 else: return False def dataNascimento_avo_m_filho(avo,pai,mae): if pai["nome"] in avo["ePai"]: return int(pai["dataNasc"].split('-')[2]) > int(avo["dataNasc"].split('-')[2]) + 13 else: if mae["nome"] in avo["ePai"]: return int(mae["dataNasc"].split('-')[2]) > int(avo["dataNasc"].split('-')[2]) + 13 else: return False # 2 - Restrição entre diferença de Datas de Nascimento entre Mae e Filho def dataNascimento_mae_filho(mae,filho): if filho["nome"] in mae["eMae"]: return int(mae["dataNasc"].split('-')[2])+12 <= int(filho["dataNasc"].split('-')[2]) and int(filho["dataNasc"].split('-')[2]) <= int(mae["dataNasc"].split('-')[2])+50 else: return False def dataNascimento_avo_f_filho(avo,pai,mae): if pai["nome"] in avo["eMae"]: return int(avo["dataNasc"].split('-')[2])+12 <= int(pai["dataNasc"].split('-')[2]) and int(pai["dataNasc"].split('-')[2]) <= int(avo["dataNasc"].split('-')[2])+50 else: if mae["nome"] in avo["eMae"]: return int(avo["dataNasc"].split('-')[2])+12 <= int(mae["dataNasc"].split('-')[2]) and int(mae["dataNasc"].split('-')[2]) <= int(avo["dataNasc"].split('-')[2])+50 else: return False # 3 - Não pode estar morto quando o filho nasce def dataMorte_pai_filho(pai,filho): if filho["nome"] in pai["ePai"]: return int(pai["dataMorte"].split('-')[2]) > int(filho["dataNasc"].split('-')[2]) else: return False def dataMorte_mae_filho(mae,filho): if filho["nome"] in mae["eMae"]: return int(mae["dataMorte"].split('-')[2]) > int(filho["dataNasc"].split('-')[2]) else: return False def dataMorte_avo_m_filho(avo,pai,mae): if pai["nome"] in avo["ePai"]: return int(avo["dataMorte"].split('-')[2]) > int(pai["dataNasc"].split('-')[2]) else: if mae["nome"] in avo["ePai"]: return int(avo["dataMorte"].split('-')[2]) > int(mae["dataNasc"].split('-')[2]) else: return False def dataMorte_avo_f_filho(avo,pai,mae): if pai["nome"] in avo["eMae"]: return int(avo["dataMorte"].split('-')[2]) > int(pai["dataNasc"].split('-')[2]) else: if mae["nome"] in avo["eMae"]: return int(avo["dataMorte"].split('-')[2]) > int(mae["dataNasc"].split('-')[2]) else: return False # 5 - Avo-Neto def avo_neto(avo_m,avo_f,filho): if filho["nome"] in avo_m["eAvo"]: if filho["nome"] in avo_f["eAvo"]: return True else: return False else: return False # 6 - Pai - Filho def pai_filho(pai,filho): if filho["nome"] in pai["ePai"]: return True else: return False def avo_m_filho(avo,pai,mae): if pai["nome"] in avo["ePai"]: return True else: if mae["nome"] in avo["ePai"]: return True else: return False # 7 - Mae - Filho def mae_filho(mae,filho): if filho["nome"] in mae["eMae"]: return True else: return False def avo_f_filho(avo,pai,mae): if pai["nome"] in avo["eMae"]: return True else: if mae["nome"] in avo["eMae"]: return True else: return False # 8 - Casado Pai - Mae def casado_pai_mae(pai,mae): if pai["ePai"] == mae["eMae"]: return True else: return False def casado_avo_m_avo_f(avo_m,avo_f): if avo_m["ePai"] == avo_f["eMae"]: return True else: return False
from tkinter import * global scvalue def click(event): text = event.widget.cget("text") print(text) if text == "=": if scvalue.get().isdigit(): value = eval(screen.get()) else: value = eval(screen.get()) scvalue.set(value) screen.update() elif text =="c": scvalue.set("") screen.update() else: scvalue.set(scvalue.get()+text) screen.update() root =Tk() root.geometry("600x800") root.title("calculater by shivam using Tkinter") scvalue = StringVar() scvalue.set("") screen = Entry(root,textvar=scvalue,font = "lucida 40 bold") screen.pack(fill= X,ipadx=8,pady=10, padx=10) f = Frame(root,bg = "red") b = Button(f,text = "9",padx = 10 , pady = 5,font= "licida 35 bold") b.pack(side=LEFT, padx=15,pady=5) b.bind("<Button-1>",click) b = Button(f,text = "8",padx = 10 , pady = 5,font= "licida 35 bold") b.pack(side=LEFT, padx=15,pady=5) b.bind("<Button-1>",click) b = Button(f,text = "7",padx = 10, pady = 5,font= "licida 35 bold") b.pack(side=LEFT ,padx=15,pady=5) b.bind("<Button-1>",click) f.pack() f = Frame(root,bg = "blue") b = Button(f,text = "6",padx = 10 , pady = 5,font= "licida 35 bold") b.pack(side=LEFT, padx=15,pady=5) b.bind("<Button-1>",click) b = Button(f,text = "5",padx = 10 , pady = 5,font= "licida 35 bold") b.pack(side=LEFT, padx=15,pady=5) b.bind("<Button-1>",click) b = Button(f,text = "4",padx = 10, pady = 5,font= "licida 35 bold") b.pack(side=LEFT ,padx=15,pady=5) b.bind("<Button-1>",click) f.pack() f = Frame(root,bg = "purple") b = Button(f,text = "3",padx = 10 , pady = 5,font= "licida 35 bold") b.pack(side=LEFT, padx=15,pady=5) b.bind("<Button-1>",click) b = Button(f,text = "2",padx = 10 , pady = 5,font= "licida 35 bold") b.pack(side=LEFT, padx=15,pady=5) b.bind("<Button-1>",click) b = Button(f,text = "1",padx = 10, pady = 5,font= "licida 35 bold") b.pack(side=LEFT ,padx=15,pady=5) b.bind("<Button-1>",click) f.pack() f = Frame(root,bg = "red") b = Button(f,text = "0",padx = 10 , pady = 5,font= "licida 35 bold") b.pack(side=LEFT, padx=17,pady=5) b.bind("<Button-1>",click) b = Button(f,text = "+",padx = 10 , pady = 5,font= "licida 35 bold") b.pack(side=LEFT, padx=16,pady=5) b.bind("<Button-1>",click) b = Button(f,text = "-",padx = 10, pady = 5,font= "licida 35 bold") b.pack(side=LEFT ,padx=16.5,pady=5) b.bind("<Button-1>",click) f.pack() f = Frame(root,bg = "yellow") b = Button(f,text = "*",padx = 10 , pady = 5,font= "licida 35 bold") b.pack(side=LEFT, padx=16,pady=5) b.bind("<Button-1>",click) b = Button(f,text = "/",padx = 10 , pady = 5,font= "licida 35 bold") b.pack(side=LEFT, padx=15,pady=5) b.bind("<Button-1>",click) b = Button(f,text = "%",padx = 10, pady = 5,font= "licida 35 bold") b.pack(side=LEFT ,padx=16,pady=5) b.bind("<Button-1>",click) f.pack() f = Frame(root,bg = "blue") b = Button(f,text = ".",padx = 10 , pady = 5,font= "licida 35 bold") b.pack(side=LEFT, padx=16.5,pady=5) b.bind("<Button-1>",click) b = Button(f,text = "c",padx = 10 , pady = 5,font= "licida 35 bold") b.pack(side=LEFT, padx=16,pady=5) b.bind("<Button-1>",click) b = Button(f,text = "=",padx = 10, pady = 5,font= "licida 35 bold") b.pack(side=LEFT ,padx=16,pady=5) b.bind("<Button-1>",click) f.pack() root.mainloop()
# Project Euler # Problem 19: Counting Sundays # You are given the following information, but you may prefer # to do some research yourself. # * 1 Jan 1900 was a Monday. # * Thirty days has September, # April, June and November. # All the rest have thirty-one, # Saving February alone, # which has twenty-eight, rain or shine. # And on leap years, twenty-nine # * A leap year occurs on any year divisible by 4, # but not on a century unless it is divisible by 400. # # How many Sundays fell on the first of the month during the # twentieth Century? (1 Jan 1901 to 31 Dec 2000) # Jeffrey Spahn # Created for Python 3.x ''' Notes: 1900: Jan starts Mon (1) Feb starts 1 + 31%7 ''' import time start_time = time.time() month_length = { 1 : 31, # January 2 : 28, # February - Non Leap Year 3 : 31, # March 4 : 30, # April 5 : 31, # May 6 : 30, # June 7 : 31, # July 8 : 31, # August 9 : 30, # September 10: 31, # October 11: 30, # November 12: 31 # December } def is_leap_year(n): """returns True if the year is a leap year""" if n % 400 == 0: return True elif n % 100 == 0: return False elif n % 4 == 0: return True else: return False # ------------------------------------------------------------ # Main # ------------------------------------------------------------ if __name__ == "__main__": start_time = time.time() sunday_count = 0 day_index = 1 # Sunday = 0 , Monday = 1, ... Saturday = 6 for year in range(0,101): for month in range(1,13): if not (year == 100 and month == 12): day_index = day_index + month_length[month] if month == 2 and is_leap_year(1900 + year): day_index = day_index + 1 day_index = day_index % 7 if day_index == 0 and year > 0: sunday_count += 1 print("The total number of months in the 20th Century that started on a Sunday are {}".format(sunday_count)) print("Completion time: {}".format(time.time()-start_time)) # Output # The total number of months in the 20th Century that started on a Sunday are 171 # Completion time: 0.001010894775390625
# Project Euler # Problem 18: Maximum Sum Path 1 # By starting at the top of the triangle below and moving to adjacent # numbers on the row below, the maximum total from the top to bottom # is 23. # 3 # 7 4 # 2 4 6 # 8 5 9 3 # # That is, 3 + 7 + 4 + 9 = 23 # Find the maximum total from top to bottom of the triangle below: # 75 # 95 64 # 17 47 82 # 18 35 87 10 # 20 04 82 47 65 # 19 01 23 75 03 34 # 88 02 77 73 07 63 67 # 99 65 04 28 06 16 70 92 # 41 41 26 56 83 40 80 70 33 # 41 48 72 33 47 32 37 16 94 29 # 53 71 44 65 25 43 91 52 97 51 14 # 70 11 33 28 77 73 17 78 39 68 17 57 # 91 71 52 38 17 14 91 43 58 50 27 29 48 # 63 66 04 68 89 53 67 30 73 16 69 87 40 31 # 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23 # Note: As there are only 16384 routes, it is possible to solve this # problem by trying every route. However, Problem 67, is the same # challenge with a triangle containing one-hundred rows; it cannot # be solved by brute force, and requires a clever method! ;o) # Jeffrey Spahn # Created for Python 3.x import time startTime = time.time() s_triangle = '''75 95 64 17 47 82 18 35 87 10 20 04 82 47 65 19 01 23 75 03 34 88 02 77 73 07 63 67 99 65 04 28 06 16 70 92 41 41 26 56 83 40 80 70 33 41 48 72 33 47 32 37 16 94 29 53 71 44 65 25 43 91 52 97 51 14 70 11 33 28 77 73 17 78 39 68 17 57 91 71 52 38 17 14 91 43 58 50 27 29 48 63 66 04 68 89 53 67 30 73 16 69 87 40 31 04 62 98 27 23 09 70 98 73 93 38 53 60 04 23''' def to_int_triangle(args_triangle): """returns the triangle array in integer form""" args_triangle = args_triangle.split("\n") n_triangle = [] for s in args_triangle: s_level = s.split(" ") n_level = [] for value in s_level: n_level.append(int(value)) n_triangle.append(n_level) return n_triangle def calculate_max_sum(int_triangle, triangle_height): """ Start at the line second from the bottom (n -1). For each number there, add the largest number it could go to. These is now the new last line. repeat until you reach the top example: 63 becomes 63 + 62 = 125 66 becomes 66 + 98 = 164 04 becomes 04 + 98 = 102 68 becomes 68 + 27 = 95 """ for i in range(triangle_height - 2, -1, -1): for j in range(i + 1): if int_triangle[i + 1][j] > int_triangle[i + 1][j + 1]: int_triangle[i][j] = int_triangle[i][j] + int_triangle[i + 1][j] else: int_triangle[i][j] = int_triangle[i][j] + int_triangle[i + 1][j + 1] return int_triangle[0][0] #------------------------------------------------------------ # Main #------------------------------------------------------------ if __name__ == "__main__": start_time = time.time() int_triangle = to_int_triangle(s_triangle) triangle_height = len(int_triangle) # Height of Triangle max_sum = calculate_max_sum(int_triangle,triangle_height) print("The Maximum total from the top to the bottom is: {}".format(max_sum)) print(" Completion time: {}".format(time.time() - start_time)) # Output: # The Maximum total from the top to the bottom is: 1074 # Completion time: 0.00012183189392089844
# Project Euler # Problem 1: Multiples of 3 and 5 # Problem Details: # If we list all the natural numbers below 10 that are multiples of 3 or 5, we get # 3, 5, 6, and 9. The sum of these multiples is 23. # Find the sum of all the multiples fof 3 and 5 below 1000. # # Jeffrey Spahn # created for Python 3.x import time def sum_of_multiples(n, divisors): """Returns the sum of all natural numbers below n that are divisible by divisors""" result = 0 for x in range(1, n): if any([x % div == 0 for div in divisors]): result += x return result #------------------------------------------------------------ # Main #------------------------------------------------------------ if __name__ == "__main__": start_time = time.time() print("The sum of all multiples of 3 or 5 below 1000 is {}".format(sum_of_multiples(1000,[3,5]))) print("Completion time: {}".format(time.time() - start_time)) # Output: # The sum of all multiples of 3 or 5 below 1000 is 233168 # Completion time: 0.0006198883056640625
# Project Euler # Problem 2: Even Fibonacci Numbers # Problem Details: # Each new term in the Fibonacci sequence is generated by # adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: # 1, 2, 3, 5, 8 , 13, 21, 34, 55, 89 # By considering the terms in the Fibonacci sequence whose values do not exceed four # million, find the sum of the even- valued terms. # Jeffrey Spahn # created for Python 3.x import time def even_fib_sum(n): """Finds the sum of all even numbered Fibonacci numbers below the value of n""" sum_of_evens = 2 a1 = 1 a2 = 2 a3 = a1 + a2 while a3 < n: a1 = a2 a2 = a3 a3 = a1 + a2 if a3 % 2 == 0: sum_of_evens += a3 return sum_of_evens #------------------------------------------------------------ # Main #------------------------------------------------------------ if __name__ == "__main__": start_time = time.time() n = 4000000 # The upper limit on the value of Fibonacci Numbers we will consider solution = even_fib_sum(n) print("The Sum of all Even Fibonacci Numbers below {0} is: {1}".format(n,solution)) print("Completion time: {}".format(time.time() - start_time)) # Output: # The Sum of all Even Fibonacci Numbers below 4000000 is: 4613732 # Completion time: 2.2172927856445312e-05
# Project Euler # Problem 26: Reciprocal cycles # A unit fraction contains 1 in the numerator. The decimal representation # of the unit fractions with denominators 2 to 10 are given: # # 1/2 = 0.5 # 1/3 = 0.(3) # 1/4 = 0.25 # 1/5 = 0.2 # 1/6 = 0.1(6) # 1/7 = 0.(142857) # 1/8 = 0.125 # 1/9 = 0.(1) # 1/10 = 0.1 # # Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. # It can be seen that 1/7 has a 6-digit recurring cycle. # # Find the value of d < 1000 for which 1/d contains the longest # recurring cycle in its decimal fraction part. # Jeffrey Spahn # Created for Python 3.x import time def is_recurring(d): """Looks at the fraction 1/d and returns True if its decimal representation is a recurring cycle""" if d % 2 == 0 or d % 5 == 0: return False else: return True def recurring_length(d): """Looks at the fraction 1/d and returns the length of the recurring cycle. Every Fraction of the form 1/d that has a recurring cycle can be made into the form: X/(10^i - 1) where X is the recurring digits and i is the number of digits that recurs. Example: 1/3 = 0.(3) = 3/9 1/7 = 0.(142857) = 142857/999999 To reverse this process, we simply find the value for i such that (10^i - 1) mod d == 0 """ if is_recurring(d): b_found = False i = 1 while True: if (10**i-1) % d == 0: return i else: i = i+1 else: return 0 pass # ------------------------------------------------------------ # Main # ------------------------------------------------------------ if __name__ == "__main__": start_time = time.time() largest_recurring_length = 0 largest_d = 0 for d in range(2,1000): r_length = recurring_length(d) if r_length > largest_recurring_length: largest_recurring_length = r_length largest_d = d print("The fraction 1/{} has the largest recurring cycle of {} repeating digits.".format(largest_d,largest_recurring_length)) print("Completion time: {}".format(time.time()-start_time)) # Output: # The fraction 1/983 has the largest recurring cycle of 982 repeating digits. # Completion time: 0.10865998268127441
__copyright__ = '' __author__ = 'Son-Huy TRAN' __email__ = "sonhuytran@gmail.com" __doc__ = '' __version__ = '1.0' def generate(A, C, M, X0, N) -> int: for _ in range(N): X0 = (A * X0 + C) % M return X0 def main() -> int: n = int(input()) results = [''] * n for i in range(n): (A, C, M, X0, N) = map(int, input().split()) results[i] = str(generate(A, C, M, X0, N)) print(' '.join(results)) return 0 if __name__ == '__main__': exit(main())
__copyright__ = '' __author__ = 'Son-Huy TRAN' __email__ = "sonhuytran@gmail.com" __doc__ = 'http://codeforces.com/problemset/problem/384/A' __version__ = '1.0' def print_chessboard(size: int) -> None: n_coders = size * size // 2 line = ['C.' * (size // 2), '.C' * (size // 2)] if size % 2 != 0: n_coders += 1 line[0] += 'C' line[1] += '.' print(n_coders) for i in range(size): print(line[i % 2]) return def main() -> int: n = int(input()) print_chessboard(n) return 0 if __name__ == '__main__': main()
__copyright__ = '' __author__ = 'Son-Huy TRAN' __email__ = "sonhuytran@gmail.com" __doc__ = '' __version__ = '1.0' def main() -> int: n = int(input()) exercises = [int(word) for word in input().split()] total = [0] * 3 for i in range(3): total[i] = sum(exercises[i::3]) max_index = total.index(max(total)) exercise_names = ['chest', 'biceps', 'back'] print(exercise_names[max_index]) return 0 if __name__ == '__main__': main()
__copyright__ = '' __author__ = 'Son-Huy TRAN' __email__ = "sonhuytran@gmail.com" __spec__ = 'http://codeforces.com/problemset/problem/282/A' __version__ = '1.0' n = int(input()) result = 0 for _ in range(n): statement = input() if ('++' in statement): result += 1 elif ('--' in statement): result -= 1 print(result)
__copyright__ = '' __author__ = 'Son-Huy TRAN' __email__ = "sonhuytran@gmail.com" __doc__ = '' __version__ = '1.0' def find_point(n: int, k: int, squares: list) -> int: if k > n: return -1 squares = sorted(squares, reverse=True) return squares[k - 1] def main() -> int: (n, k) = map(int, input().split()) squares = [int(word) for word in input().split()] result = find_point(n, k, squares) if result < 0: print(result) else: print(result, result) return 0 if __name__ == '__main__': exit(main())
__copyright__ = '' __author__ = 'Son-Huy TRAN' __email__ = "sonhuytran@gmail.com" __doc__ = 'http://codeforces.com/problemset/problem/379/A' __version__ = '1.0' def calculate_hour(candles: int, pieces: int) -> int: hour = 0 went_outs = 0 while candles > 0: hour += candles went_outs += candles candles = went_outs // pieces went_outs %= pieces return hour (a, b) = map(int, input().split()) print(calculate_hour(a, b))
__copyright__ = '' __author__ = 'Son-Huy TRAN' __email__ = "sonhuytran@gmail.com" __doc__ = '' __version__ = '1.0' def sum_digit(string: str) -> int: return sum(int(char) for char in string) def is_lucky_ticket(n: int, ticket: str) -> bool: if (ticket.count('4') + ticket.count('7')) != n: return False return sum_digit(ticket[:n // 2]) == sum_digit(ticket[n // 2:]) def main() -> int: n = int(input()) ticket = input() print('YES' if is_lucky_ticket(n, ticket) else 'NO') return 0 if __name__ == '__main__': exit(main())
__copyright__ = '' __author__ = 'Son-Huy TRAN' __email__ = "sonhuytran@gmail.com" __doc__ = '' __version__ = '1.0' def findab(x1: int, y1: int, x2: int, y2: int) -> tuple: a = (y1 - y2) // (x1 - x2) b = y1 - a * x1 return (a, b) def main() -> int: n = int(input()) results = [''] * n for i in range(n): (x1, y1, x2, y2) = map(int, input().split()) results[i] = '(%d %d)' % findab(x1, y1, x2, y2) print(' '.join(results)) return 0 if __name__ == '__main__': exit(main())
__copyright__ = '' __author__ = 'Son-Huy TRAN' __email__ = "sonhuytran@gmail.com" __doc__ = '' __version__ = '1.0' def count_stealing_ways(n: int, cookie_bags: list) -> int: sum_cookies = sum(cookie_bags) temp = sum_cookies % 2 return sum(1 for bag in cookie_bags if bag % 2 == temp) def main() -> int: n = int(input()) cookie_bags = [int(word) for word in input().split()] print(count_stealing_ways(n, cookie_bags)) return 0 if __name__ == '__main__': exit(main())
__copyright__ = '' __author__ = 'Son-Huy TRAN' __email__ = "sonhuytran@gmail.com" __spec__ = '' __version__ = '1.0' print([x * x for x in range(10)]) print([x * x for x in range(10) if x % 3 == 0]) print([(x, 2 * x) for x in range(10)]) print([(x, y) for x in range(3) for y in range(2)])
__copyright__ = '' __author__ = 'Son-Huy TRAN' __email__ = "sonhuytran@gmail.com" __doc__ = '' __version__ = '1.0' def collatz(number: int) -> int: count = 0 while number != 1: number = number // 2 if number % 2 == 0 else number * 3 + 1 count += 1 return count def main() -> int: input() numbers = [int(word) for word in input().split()] results = [str(collatz(i)) for i in numbers] print(' '.join(results)) return 0 if __name__ == '__main__': exit(main())
#!/usr/bin/python import random import tkinter as tk from tkinter import messagebox from PIL import ImageTk ,Image import tkinter.font as font from tkinter.simpledialog import askstring def home(): game() # Code to add widgets will go here... window = tk.Tk() window.rowconfigure([1,2,3,4,5,6,7,8],minsize=50) window.columnconfigure([2, 4, 6],minsize=50) lbl_wel = tk.Label(master=window,text="Welcome to the Vote App") lbl_wel.grid(row=2,column=4) btn = tk.Button(master=window,text="Home",command=home) btn.grid(row=2,column=4) window.geometry("300x300+120+120") def result_values(): lbl_score_com['fg']='blue' lbl_score_com['bg']='#49A' lbl_score_you['fg']='blue' lbl_score_you['bg']='#49A' lbl_user = lbl_value_r["text"] lbl_computer = lbl_random_r["text"] lbl_dec=int(lbl_decrese["text"]) if(lbl_user=="Rock" and lbl_computer=="Paper"): lbl_score_com["text"]=increase_com() lbl_won['text']='Computer win' elif(lbl_user=="Rock" and lbl_computer=="Scissor"): lbl_score_you["text"]=increase_you() lbl_won['text']='You wins' elif(lbl_user=="Paper" and lbl_computer=="Rock"): lbl_score_you["text"]=increase_you() lbl_won['text']='You win' elif(lbl_user=="Paper" and lbl_computer=="Scissor"): lbl_score_com["text"]=increase_com() lbl_won['text']='Computer win' elif(lbl_user=="Scissor" and lbl_computer=="Rock"): lbl_score_com["text"]=increase_com() lbl_won['text']='Computer win' elif(lbl_user=="Scissor" and lbl_computer=="Paper"): lbl_score_you["text"]=increase_you() lbl_won['text']='You win' else: #messagebox.showinfo("top","You are in tie") lbl_won['text']='You are in Tie with Computer' #if(lbl_dec==10): #lbl_won['text']='winner is {}'.format(winner()) def increase_you(): value = int(lbl_score_you["text"]) lbl_score_you["text"] = f"{value + 1}" def increase_com(): value = int(lbl_score_com["text"]) lbl_score_com["text"] = f"{value + 1}" def random_values(): val=random.choice(["Rock","Paper","Scissor"]) #filename = ImageTk.PhotoImage(file = random.choice(val)) #img2=Image.open (val) #image2 = img2.resize((50, 50), Image.ANTIALIAS) #val_random=random.choice(val) #img2=Image.open (val_random) #image2 = img2.resize((50, 50)) #my_img2 = ImageTk.PhotoImage(img2) #filechoices = ["rock.jpg","paper.jpg","scissor.jpg"] #filename = ImageTk.PhotoImage(file = random.choice(val)) #lbl_random_r.configure(image=filename,width=50,height=50) lbl_random_r['text']=val lbl_random_r['font']=myFont def handlePress_rock(): random_values() '''img2=Image.open ("rock.jpg") image2 = img2.resize((100, 100), Image.ANTIALIAS) my_img2 = ImageTk.PhotoImage(image2) lbl_value_r.configure(image=my_img2)''' lbl_value_r["text"]='Rock' #lbl_value_r["text"]=image=photo1 result_values() def handlePress_paper(): random_values() '''img2=Image.open ("paper.jpg") image2 = img2.resize((100, 100), Image.ANTIALIAS) my_img2 = ImageTk.PhotoImage(image2) lbl_value_r.configure(image=my_img2)''' lbl_value_r["text"]='Paper' result_values() def handlePress_scissor(): random_values() '''img2=Image.open ("scissor.jpg") image2 = img2.resize((100, 100), Image.ANTIALIAS) my_img2 = ImageTk.PhotoImage(image2) lbl_value_r.configure(image=my_img2)''' lbl_value_r["text"]='Scissor' #lbl_value_r["text"]=my_img2 result_values() def decrese(event): value = int(lbl_decrese["text"]) if(value==10): lbl_won['text']='winner is {}'.format(winner()) messagebox.showinfo("top","winner is {}".format(winner())) msg=messagebox.askquestion('"Yes/No"','Do You want to Play again') print(msg) if(msg=='yes'): lbl_decrese['text']='0' lbl_score_you['text']='0' lbl_score_com['text']='0' lbl_won['text']='' lbl_value_r['text']='' lbl_random_r['text']='' if(msg=='no'): exit() else: lbl_decrese["text"] = f"{value + 1}" def winner(): you=int(lbl_score_you["text"]) com=int(lbl_score_com["text"]) if(you > com): return "You" elif(you==com): return "Both,Scores Are In Tie" else: return "Computer" def game(): top = tk.Tk() #top.geometry("300x300+120+120") top['bg'] ='#49A' myFont = font.Font(family='Helvetica', size=15, weight='bold') top.geometry("30000x30000+12000+12000") top.rowconfigure([1,2,3,4,5,6,7,8],minsize=50) top.columnconfigure([2, 4, 6],minsize=50) greeting = tk.Label(text="Welcome To Rock Paper Scissor Game",foreground="yellow",background="blue") greeting.grid(row=1,column=4,padx=5,pady=25) greeting['font']=myFont lbl_won=tk.Label(text='',bg="#49A") lbl_won.grid(row=2,column=4) lbl_won['font']=myFont lb_chance=tk.Label(text="Round") lb_chance.grid(row=3,column=4,padx=10) lb_chance['font']=myFont lbl_decrese=tk.Label(text="0",bg='#49A') lbl_decrese.grid(row=3,column=5) lbl_decrese['font']=myFont img2=Image.open ("paper.jpg") image2 = img2.resize((150, 150), Image.ANTIALIAS) my_img2 = ImageTk.PhotoImage(image2) img3=Image.open ("scissor.jpg") image3 = img3.resize((150, 150), Image.ANTIALIAS) my_img3 = ImageTk.PhotoImage(image3) img1=Image.open ("rock.jpg") image1 = img1.resize((150, 150), Image.ANTIALIAS) my_img1 = ImageTk.PhotoImage(image1) button_rock = tk.Button(text="Rock", image=my_img1, command=handlePress_rock) button_paper = tk.Button(text="Paper", image=my_img2, command=handlePress_paper) button_scissor = tk.Button(text="Scissor",image=my_img3, command=handlePress_scissor) button_rock.grid(row=4, column=2,padx=150,pady=100) button_rock.bind("<Button-1>", decrese) button_paper.grid(row=4, column=4,padx=150,pady=100 ) button_paper.bind("<Button-1>", decrese) button_scissor.grid(row=4, column=6,padx=150,pady=100) button_scissor.bind("<Button-1>", decrese) lbl_value=tk.Label(top,text="You Choose ") lbl_value.grid(row=5,column=2) lbl_value['font']=myFont lbl_value_r=tk.Label(top,text="",bg="#49A") lbl_value_r.grid(row=5,column=4) lbl_value_r['font']=myFont lbl_random=tk.Label(top,text="Computer Choose") lbl_random.grid(row=7,column=2) lbl_random['font']=myFont lbl_random_r=tk.Label(top,text="",bg="#49A") lbl_random_r.grid(row=7,column=4) lbl_score_you=tk.Label(top,text="0",bg='#49A',fg='#49A') lbl_score_you.grid(row=5,column=6) lbl_score_you['font']=myFont lbl_score_com=tk.Label(top,text="0",bg='#49A',fg='#49A') lbl_score_com.grid(row=7,column=6) lbl_score_com['font']=myFont lbl_tie=tk.Label(text='') lbl_tie.grid(row=8,column=5) lbl_tie['font']=myFont #top.mainloop() top.mainloop() window.mainloop()
times = int(input()) result = [] for _ in range(times): x = int(input()) if x % 7 == 0: result.append(x * x) for y in result: print(y)
def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ value=collections.Counter(s) value1=collections.Counter(t) if len(value)!=len(value1): return False else: for i in value.keys(): if i not in value1.keys(): return False else: if value[i]!=value1[i]: return False return True
"""A Queue with a capacity limit.""" CAPACITY = 3 class EmptyQueue(Exception): """Exception to throw for empty queue.""" class Queue: def __init__(self): self.capacity = CAPACITY self.queue = [] def isEmpty(self): if len(self.queue): return False else: return True def enqueue(self, ele): if len(self.queue) < self.capacity: self.queue.append(ele) else: del self.queue[0] self.queue.append(ele) def dequeue(self): if self.isEmpty(): raise EmptyQueue else: ele = self.queue.pop() return ele if __name__ == "__main__": q = Queue() q.enqueue(1) q.enqueue(2) q.enqueue(3) q.enqueue(4) print q.queue
""" The item class and it's children """ class Item: """ Parent class for all items """ # All the important variables for a consumable item. # The constructor that sets the. # name, description, StackCap, Stack, and affect. def __init__(self, name, desc, stack_cap, stack, drop_rate): self.itemName = name self.itemDescription = desc self.itemStackCap = stack_cap self.itemStack = stack self.itemDropRate = drop_rate # The setter and Getter for itemName def set_item_name(self, name): """ Sets the name of the item, although this seems quite stupid. :param name: the name """ self.itemName = name def get_item_name(self): """ Returns the name of the item :return: the name of the item """ return self.itemName # The setter and Getter for itemDescription def set_item_description(self, desc): """ sets the description of the item :param desc: the item description """ self.itemDescription = desc def get_item_description(self): """ Gets the item description :return: item description """ return self.itemDescription # Setters and Getters for itemStackCap and itemStack def set_item_stack_cap(self, cap): """ Sets the max amount of items the player can hold. :param cap: The max amount of item. """ self.itemStackCap = cap def set_item_stack(self, amount): """ Sets the amount of the item :param amount: stack amount """ self.itemStack = amount def get_item_stack_cap(self): """ Gets the max item stack :return: the max item stak """ return self.itemStackCap def get_item_stack(self): """ Gets the item stack :return: Gets the item stack """ return self.itemStack # Most important function, setter and getter for drop rate. def set_item_drop_rate(self, rate): """ Sets the drop rates of the items just in case. :param rate: the drop rate """ self.itemDropRate = float(rate) def get_item_drop_rate(self): """ Gets the drop rate of the item :return: The drop rate """ return self.itemDropRate class EquippableItem(Item): """ This type of item is equippable by the player, like a sword, ring, or helmet. """ def __init__(self, name, desc, level_req, damage, stack_cap, stack, drop_rate): Item.__init__(self, name, desc, stack_cap, stack, drop_rate) self.level_req = level_req self.damage = damage def set_level_req(self, level): """ Sets the level requirement, not necessary as it's in the constructor. :param level: the item's level """ self.level_req = level def get_level_req(self): """ Returns the item's level :return: The item's level """ return self.level_req def set_damage(self, damage): """ Sets the damage of the item :param damage: item damage """ self.damage = damage def get_damage(self): """ Returns the damage of the item :return: item damage """ return self.damage
# Describe the given number in terms of parity and being the prime number def numberDesc(): nb = input('Podaj liczbe:') if nb % 2 == 0: print ("Liczba jest parzysta") else: if nb == 1: print ("Liczba jest nieparzysta") else: check = 0; for x in list(range(2,nb/2)): if nb % x == 0: print ("Liczba jest nieparzysta") check = 1 break else: continue if check == 0: print ("Liczba jest pierwsza") numberDesc()
#!/usr/bin/env python # -*- coding:utf-8 -*- import xlrd import os class read_Excel(): def read_excel(xls_name,sheet_name): cls=[] #获取excel路径 xlspath=os.path.join('D:\\',xls_name) file=xlrd.open_workbook(xlspath) sheet = file.sheet_by_name(sheet_name)#获取excel的sheet nrows = sheet.nrows#行数 ncols = sheet.ncols keys=sheet.row_values(0) #print('keys:',keys) cell=sheet.cell_value(0,0) #第一行第一列 #print('cell:',cell) for i in range(nrows): a=sheet.row_values(i) cls.append(a) return cls if __name__=='__main__': print(read_Excel.read_excel('1.xlsx','Sheet1')) print('用户名:',read_Excel.read_excel('1.xlsx', 'Sheet1')[1][0]) print('密码:', read_Excel.read_excel('1.xlsx', 'Sheet1')[1][1])
def romb(letter): # not hardcoded all_letters = 'abcdegfxyz' # test cases assert # check type # check is alfa find =all_letters.find(letter) all_letters = all_letters[:find+1] for char in all_letters: distance = find - all_letters.find(char) external = [' ' for _ in range(distance)] external = ''.join(external) internal = ['_' for _ in range(all_letters.find(char)*2 - 1)] internal = ''.join(internal) if all_letters.find(char) == 0: print(external+char+internal+external) else: print(external+char+internal+char+external) for char in all_letters[-2::-1] : distance = find - all_letters.find(char) external = [' ' for _ in range(distance)] external = ''.join(external) internal = ['_' for _ in range(all_letters.find(char)*2 - 1)] internal = ''.join(internal) if all_letters.find(char) == 0: print(external+char+internal+external) else: print(external+char+internal+char+external) romb("d")
# Copyright(c) 2011 Cuong Ngo # Print the most character used in a sentence list1 = [] spaces = " " # Get the sentence SENTENCE = input("sentence: ") print(SENTENCE) # Lowercase sentence = SENTENCE.lower() # Get rid of the space in a sentence sentence = sentence.replace(" ", "") # Convert sentence to integer number and put it in a list for letter in sentence: number = ord(letter) list1.append(number) # Find the mode mode = max([list1.count(y),y] for y in list1) [1] print("2", chr(mode)) # Exit the program input("\n\nPress the enter key to exit.")
# Copyright (c) 2011 Cuong Ngo # Guessing game print("\tThink of a number between 1 and 10, but don't tell me what it is.\n") print("\tThen hit enter.\n\n\n") number = 5 answer = "" while answer != "y": answer = input("\nIs it " + str(number) + "? [y/n]") if answer == "n": answer = input("\nIs your number higher or lower than " + str(number) + "? [h/l]") if answer == "l": number -= 1 if number < 0: break elif answer == "h": number += 1 if number > 10: break else: print("\nI win!") input("\n\nPress enter key to exit.")
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt # 导入 MNIST 数据集 from tensorflow.examples.tutorials.mnist import input_data mnist=input_data.read_data_sets("MNIST_data", one_hot=True) x = tf.placeholder(tf.float32, [None, 784]) # 输入的数据占位符:存放待识别的图片 y_actual = tf.placeholder(tf.float32, shape=[None, 10]) # 输入的标签占位符:放0~9 这10个数字 # 定义一个函数,用于初始化所有的权值 W def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) # 从截断的正态分布中输出随机值 return tf.Variable(initial) # 定义一个函数,用于初始化所有的偏置项 b def bias_variable(shape): initial = tf.constant(0.1, shape=shape) # 创建一个常量tensor return tf.Variable(initial) # 定义一个函数,用于构建[卷积层] def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') #x是图片的所有参数,W是此卷积层的权重,然后定义步长strides=[1,1,1,1]值,strides[0]和strides[3]的两个1是默认值,中间两个1代表padding时在x方向运动一步,y方向运动一步,padding采用的方式是SAME。 # 定义一个函数,用于构建[池化层] def max_pool(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')# 为了得到更多的图片信息,padding时我们选的是一次一步,也就是strides[1]=strides[2]=1,这样得到的图片尺寸没有变化,而我们希望压缩一下图片也就是参数能少一些从而减小系统的复杂度,因此我们采用pooling来稀疏化参数,也就是卷积神经网络中所谓的下采样层。pooling 有两种,一种是最大值池化,一种是平均值池化,本例采用的是最大值池化tf.max_pool()。池化的核函数大小为2x2,因此ksize=[1,2,2,1],步长为2,因此strides=[1,2,2,1]: # 构建网络 x_image = tf.reshape(x, [-1, 28, 28, 1]) # 转换输入数据shape,以便于用于网络中 W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # 第一个卷积层 h_pool1 = max_pool(h_conv1) # 第一个池化层 W_conv2 = weight_variable([5, 5, 32, 64]) # 接着呢,同样的形式我们定义第二层卷积,本层我们的输入就是上一层的输出,本层我们的卷积核patch的大小是5x5,有32个featuremap所以输入就是32,输出呢我们定为64 b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # 第二个卷积层 h_pool2 = max_pool(h_conv2) # 第二个池化层:输出大小为7x7x64 # 建立全连接层 W_fc1 = weight_variable([7 * 7 * 64, 1024]) #weight_variable的shape输入就是第二个卷积层展平了的输出大小: 7x7x64,后面的输出size我们继续扩大,定为1024 b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64]) # 通过tf.reshape()将h_pool2的输出值从一个三维的变为一维的数据, -1表示先不考虑输入图片例子维度, 将上一个输出结果展平. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # 将展平后的h_pool2_flat与本层的W_fc1相乘(注意这个时候不是卷积了) keep_prob = tf.placeholder("float") h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) # dropout层 W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) y_predict = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) # softmax层 cross_entropy = -tf.reduce_sum(y_actual * tf.log(y_predict)) # 利用交叉熵损失函数来定义我们的cost function train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy) # 梯度下降法 correct_prediction = tf.equal(tf.argmax(y_predict, 1), tf.argmax(y_actual, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) # 精确度计算 sess = tf.InteractiveSession() sess.run(tf.initialize_all_variables()) for i in range(20000): batch = mnist.train.next_batch(50) if i % 100 == 0: # 训练100次,验证一次 train_acc = accuracy.eval(feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 1.0}) print('step', i, 'training accuracy', train_acc) train_step.run(feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 0.5}) #由于我自己的电脑显存不够,所以把数据集分10次喂给训练器,最后取平均的正确率 test_acc = 0 for i in range(10): test_acc += accuracy.eval(feed_dict={x: mnist.test.images[1000*i:1000*(i+1)], y_actual: mnist.test.labels[1000*i:1000*(i+1)], keep_prob: 1.0}) test_acc /= 10 #test_acc = accuracy.eval(feed_dict={x: mnist.test.images, y_actual: mnist.test.labels, keep_prob: 1.0}) print("测试准确度是:", test_acc)
def maxProfit(prices): lowest = float('inf') profit = 0 prices.append(-float('inf')) for i in range(0,len(prices)-1): if prices[i] < lowest: lowest = prices[i] elif prices[i]>=prices[i-1] and prices[i] >= prices[i+1]: profit += prices[i] - lowest print(prices[i]-lowest) lowest = float('inf') return profit prices = [5,2,3,2,6,6,2,9,1,0,7,4,5,0] print(maxProfit(prices))
from typing import TextIO, Any f: TextIO with open('third.txt', 'r', encoding='utf-8') as f: zp: list[Any] = [] for line in f: worker, salary = line.split() zp.append(salary) if 20000 > float(salary): print(f'{worker}: зарплата меньше 20 000') print(f'Средняя величина дохода сотрудников равна: {sum(map(float, zp)) / len(zp)}')
beg=int(input("enter the first number:")) end=int(input("enter the last number :")) print("the even numbers are ") for n in range(beg,end+1): if(n%2)==0: print(n)
num=input("enter number:") for i in range(0,5+1): mul=num*i print("the first five multiples of a number :",num,mul)
from util import advent_input from collections import Counter, defaultdict def valid(passphrase): words = passphrase.split(' ') c = Counter(words) # check that the phrase has at most 1 of any word return c.most_common(1)[0][1] == 1 def anagrams(words): """finds all sets of anagrams in words""" def key(word): return ''.join(sorted(word)) anagram_registry = defaultdict(list) for word in words: anagram_registry[key(word)].append(word) return anagram_registry.values() def valid2(passphrase): words = passphrase.split(' ') return len(max(anagrams(words), key=len)) == 1 def part1(): total = 0 with advent_input(4) as f: for line in f: line = line.strip() if valid(line): total += 1 print(total) def part2(): total = 0 with advent_input(4) as f: for line in f: line = line.strip() if valid2(line): total += 1 print(total) if __name__ == '__main__': part1() part2()
def spin_and_insert(nums, pos, to_insert, steps): steps = steps % len(nums) new_pos = (steps + pos) % len(nums) nums.insert(new_pos + 1, to_insert) return nums, new_pos + 1 def spin_state(current_pos, length, num_after_0, steps): steps = steps % length new_pos = (current_pos + steps) % length if new_pos == 0: num_after_0 = length length += 1 return new_pos + 1, length, num_after_0 def part1(): nums = [0] pos = 0 steps = 335 for i in range(2017): nums, pos = spin_and_insert(nums, pos, i + 1, steps) print(nums[(pos + 1) % len(nums)]) def part2(): pos = 0 length = 1 num_after_0 = 0 steps = 335 for _ in range(50_000_000): pos, length, num_after_0 = spin_state(pos, length, num_after_0, steps) print(num_after_0) def test(): nums = [0] pos = 0 steps = 335 for i in range(10): nums, pos = spin_and_insert(nums, pos, i + 1, steps) print(pos, len(nums), nums[1]) def test2(): pos = 0 length = 1 num_after_0 = 0 steps = 335 for i in range(10): pos, length, num_after_0 = spin_state(pos, length, num_after_0, steps) print(pos, length, num_after_0) if __name__ == '__main__': part1() part2()
n=int(input("enter a number")) fact=1 i=1 for i in range(1,n+1): fact=fact*i i=i+1 print("factorial of",n,"is",fact)
n=int(input("enter a number")) temp=n reverse=0 while(n>0): d=n%10 reverse=(reverse*10)+d n=n//10 if(temp==reverse): print("given number is palindrome")
n=int(input("enter a number")) count=0 sum=0 while(n>0): count=count+1 d=n%10 sum=sum+d n=n//10 print("sum of number of digit of entered number is",sum) print("the number of digit in the number are",count)
# The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was unaffected by these events. # открыть файл file = open('madlibs.txt', 'r') key_words = ['ADJECTIVE', 'NOUN', 'VERB'] words_found = [] file_obj = file.read() file.close() # сформировать список словарей ключевых слов с пустыми значениями for word in file_obj.split(): if word.strip(',.') in key_words: words_found.append({word.strip(',.'): ''}) # получить замены от пользователя в внести их в список словарей # вместо пустых значений for word in words_found: for k in word.keys(): word[k] = input('Enter {}: '.format(k)) # заменить ключевые слова значениями от пользователя lst = file_obj.split() for l in range(len(lst)): for n in range(len(words_found)): for word in words_found: for key in word.keys(): if lst[l].strip(',.') == key: if lst[l].endswith('.'): lst[l] = word[key] + '.' elif lst[l].endswith(','): lst[l] = word[key] + ',' else: lst[l] = word[key] del words_found[n] # записать полученный текст в файл file = open('madlibs.txt', 'w', encoding='UTF-8') file.write(' '.join(lst)) file.close()
import sys from common import readArrayFromLine def maxHeapify(arr, i, length): left = (2 * i) + 1 right = (2 * i) + 2 largest = i if left < length and arr[left] > arr[largest]: largest = left if right < length and arr[right] > arr[largest]: largest = right if largest != i: t = arr[largest] arr[largest] = arr[i] arr[i] = t maxHeapify(arr, largest, length) def heapBuild(arr): length = len(arr) for i in range(length/2,-1,-1): maxHeapify(arr, i, length) def heapSort(arr): heapBuild(arr) for i in range(len(arr)-1,-1,-1): t = arr[0] arr[0] = arr[i] arr[i] = t maxHeapify(arr, 0, i) if __name__ == '__main__': fp = open(sys.argv[1], 'r') n = int(fp.readline()) arr = readArrayFromLine(fp) fp.close() heapSort(arr) for a in arr: print a, print
import sys def func(a, b): sum = 0 for num in range(a,b+1): if num % 2 == 1: sum += num return sum if __name__ == '__main__': a = int(sys.argv[1]) b = int(sys.argv[2]) print func(a, b)
import sys from common import readArrayFromLine def binSearch(arr, val, start, end): if start > end: return -1 num = end - start mid = start + (num / 2) if arr[mid] == val: return mid + 1 if num <= 1: return -1 if arr[mid] < val: return binSearch(arr, val, mid+1, end) if arr[mid] > val: return binSearch(arr, val, start, mid) def func(arr, k): for number in k: pos = binSearch(arr, number, 0, len(arr)) s = str(pos) print s, print def readParams(inFile): f = open(inFile, 'r') f.readline() # n f.readline() # m arr = readArrayFromLine(f) k = readArrayFromLine(f) f.close() return (arr, k) if __name__ == '__main__': (arr, k) = readParams(sys.argv[1]) func(arr, k)
def code_generator(code1, code2): code1_list= code1.split('-') code2_list = code2.split('-') code1_list = [int(item) for item in code1_list] code2_list = [int(item) for item in code2_list] while not code1_list == code2_list: if code1_list[1] < 999: code1_list[1] += 1 if code1_list[1] < 10: print("{}-00{}".format(code1_list[0], code1_list[1])) elif code1_list[1] < 100: print("{}-0{}".format(code1_list[0], code1_list[1])) else: print("{}-{}".format(code1_list[0], code1_list[1])) else: code1_list[0] += 1 code1_list[1] = 0 print("{}-00{}".format(code1_list[0], code1_list[1])) code_generator('79-900', '80-155')
def reverse(i): y = i.split() return" ".join(y[::-1]) i = (input("ENTER A SENTENCE\n")) print(reverse(i))
def inventory_list(items_list, cmd): cmd = cmd.split(' - ') action = cmd[0] item = cmd[1] if action == 'Collect': if item not in items_list: items_list.append(item) elif action == 'Drop': if item in items_list: items_list.remove(item) elif action == 'Combine Items': old_item, new_item = item.split(':')[0], item.split(':')[1] if old_item in items_list: items_position_check = items_list for ind, it in enumerate(items_position_check): if old_item == it: old_item_index = ind items_list.insert((old_item_index + 1), new_item) break elif action == 'Renew': if item in items_list: items_position_check = items_list for it in items_position_check: if item == it: items_list.remove(item) items_list.append(item) break return items_list items_list = input().split(', ') cmd = input() while cmd != 'Craft!': inventory_list(items_list, cmd) cmd = input() items_list = ', '.join(items_list) print(items_list)
num_str = input() num_list = num_str.split() inverted_list = [] for i in range(len(num_list)): num_list[i] = int(num_list[i]) inverted_list.append(num_list[i] * -1) print(inverted_list)
def calculator(action, num1, num2): if action == 'multiply': return num1 * num2 elif action == 'divide': return num1 // num2 elif action == 'add': return num1 + num2 elif action == 'subtract': return num1 - num2 operator = input() number1 = int(input()) number2 = int(input()) print(calculator(operator, number1, number2))
n = int(input()) word = input() my_list = [] filtered_list = [] for _ in range(n): sentence = input() my_list.append(sentence) if word in sentence: filtered_list.append(sentence) print(my_list) print(filtered_list)
line = input() contests_dict = {} individual_standings = {} while line != 'no more time': user_retake_same_contest = False username = line.split(' -> ')[0] contest = line.split(' -> ')[1] points = int(line.split(' -> ')[2]) if contest not in contests_dict: contests_dict[contest] = [] for i in range(len(contests_dict[contest])): if contests_dict[contest][i][0] == username: if contests_dict[contest][i][1] < points: contests_dict[contest][i][1] = points individual_standings[username] = points user_retake_same_contest = True if not user_retake_same_contest: contests_dict[contest].append([username, points]) if username not in individual_standings: individual_standings[username] = 0 individual_standings[username] += points line = input() for contest_name, participants in contests_dict.items(): participants_count = len(participants) print(f'{contest_name}: {participants_count} participants') position = 1 for participant in sorted(participants, key=lambda x: (-x[1])): user = participant[0] user_points = participant[1] print(f'{position}. {user} <::> {user_points}') position += 1 print("Individual standings:") position_counter = 1 for user, points in sorted(individual_standings.items(), key=lambda kvp: (-kvp[1], kvp[0])): print(f"{position_counter}. {user} -> {points}") position_counter += 1
def order_sum(item, amount): if item == 'coffee': sum = amount * 1.50 return sum elif item == 'water': sum = amount * 1 return sum elif item == 'coke': sum = amount * 1.40 return sum elif item == 'snacks': sum = amount * 2 return sum ordered_item = input() ordered_amount = int(input()) total_sum = order_sum(ordered_item, ordered_amount) print(f'{total_sum:.2f}')
snowballs_number = int(input()) import sys snowball_value_max = -sys.maxsize for snowball in range(1, snowballs_number + 1): snowball_snow = int(input()) snowball_time = int(input()) snowball_quality = int(input()) snowball_value = (snowball_snow / snowball_time) ** snowball_quality if snowball_value > snowball_value_max: snowball_value_max = int(snowball_value) snowball_snow_best = snowball_snow snowball_time_best = snowball_time snowball_quality_best = snowball_quality print(f'{snowball_snow_best} : {snowball_time_best} = {snowball_value_max} ({snowball_quality_best})')
old_favorite = input().split(' | ') command = input() new_favorite = [] while not command == 'Stop!': if 'Join' in command: action, genre = command.split() if genre not in old_favorite: old_favorite.append(genre) elif 'Drop' in command: action, genre = command.split() if genre in old_favorite: old_favorite.remove(genre) elif 'Replace' in command: action, old_genre, new_genre = command.split() if old_genre in old_favorite: if new_genre not in old_favorite: for index, item in enumerate(old_favorite): if item == old_genre: old_favorite[index] = new_genre command = input() new_favs = ' '.join(old_favorite) print(new_favs)
nums_list = [int(num) for num in input().split(', ')] even_indexes_list = [] for num in nums_list: if num % 2 == 0: even_indexes_list.append(nums_list.index(num)) print(even_indexes_list)
n = int(input()) register_dict = {} for _ in range(n): command = input().split() action = command[0] name = command[1] if action == 'register': car_reg = command[2] if name in register_dict: print(f'ERROR: already registered with plate number {car_reg}') else: register_dict[name] = car_reg print(f'{name} registered {car_reg} successfully') if action == 'unregister': if name not in register_dict: print(f'ERROR: user {name} not found') else: register_dict.pop(name) print(f'{name} unregistered successfully') for name, car_reg in register_dict.items(): print(f'{name} => {car_reg}')
def factorial_division(num_1, num_2): num_1_fact = num_1 num_2_fact = num_2 for num in range(num_1 - 1, num_2, -1): num_1_fact *= num return f'{num_1_fact:.2f}' n_1 = int(input()) n_2 = int(input()) print(factorial_division(n_1, n_2))
command = input() chat = [] while command != 'end': if 'Chat' in command: action, message = command.split() chat.insert(len(chat), message) elif 'Delete' in command: action, message = command.split() if message in chat: chat.remove(message) elif 'Edit' in command: action, msg_to_edit, edited_msg = command.split() if msg_to_edit in chat: for index, item in enumerate(chat): if item == msg_to_edit: chat[index] = edited_msg elif 'Pin' in command: action, message = command.split() if message in chat: for index, item in enumerate(chat): if item == message: chat.pop(index) chat.insert(len(chat), message) elif 'Spam' in command: spam_message = command.split() spam_message = spam_message[1:] chat.extend(spam_message) command = input() for text in chat: print(text)
mylist=[] def mean(myList): result_mean=sum(myList)/len(myList) return result_mean n=int(input("Enter the number of elements in the list")) for i in range(n): num=int(input("Enter list elements")) mylist.append(num) print("mean= ",mean(mylist))
import sys def compute(filename): f = open(filename,'r') n = int(f.readline()[:-1]) for i in range(n): temp = f.readline()[:-1].split(" ") if int(temp[0])&1: print "Case #"+str(i+1)+":",bottomTop(int(temp[1])) else: print "Case #"+str(i+1)+":",topBottom(int(temp[1]),int(temp[2])) f.close() def topBottom(p,q): n =1 while p!=1 and q!=1: if p>q: return n def bottomTop(n): return 0 compute(sys.argv[1])
def my_cube(y): """ takes a value and returns the value cubed uses the ** operator """ return(y ** 3) print(my_cube(13))
# -*- coding: utf-8 -*- """ date: 07/26/17 author: stamaimer source: https://leetcode.com/problems/merge-two-binary-trees/#/discuss difficulty: easy """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def pre_order_traverse(self, tree1, tree2, tree3): x = tree1.val if tree1 else 0 y = tree2.val if tree2 else 0 tree3.val = x + y tree1_left = tree1.left if tree1 and tree1.left else None tree2_left = tree2.left if tree2 and tree2.left else None if tree1_left or tree2_left: left = TreeNode(0) tree3.left = left self.pre_order_traverse(tree1_left, tree2_left, left) tree1_right = tree1.right if tree1 and tree1.right else None tree2_right = tree2.right if tree2 and tree2.right else None if tree1_right or tree2_right: right = TreeNode(0) tree3.right = right self.pre_order_traverse(tree1_right, tree2_right, right) def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ if t1 or t2: t3 = TreeNode(0) self.pre_order_traverse(t1, t2, t3) return t3 else: return None def mergeTreesV2(self, t1, t2): if (t1 is None) and (t2 is None): return None if t1 is None: return t2 if t2 is None: return t1 t1.val += t2.val t1.left = self.mergeTreesV2(t1.left, t2.left) t1.right = self.mergeTreesV2(t1.right, t2.right) return t1 if __name__ == '__main__': node_11 = TreeNode(1) node_12 = TreeNode(2) node_13 = TreeNode(3) node_15 = TreeNode(5) node_11.left = node_13 node_11.right = node_12 node_13.left = node_15 node_21 = TreeNode(1) node_22 = TreeNode(2) node_23 = TreeNode(3) node_24 = TreeNode(4) node_27 = TreeNode(7) node_22.left = node_21 node_22.right = node_23 node_21.right = node_24 node_23.right = node_27 # Solution().mergeTrees(node_11, node_22) Solution().mergeTreesV2(node_11, node_22)
""" Date: 12/09/2020 Name: Rio Weil Title: day10.py Decription: 2020 AoC D10 - Count number of valid paths in a list of integers """ import numpy as np ## Functions: def plusminusn_counter(loi, n): # Counts the number of neighbouring elements that are n different in loi # CONSTRAINT: loi must be sorted counter = 0 for i in range(1, len(loi)): if (loi[i] - loi[i-1]) == n: counter = counter + 1 return counter def split_list(loi, n): # Splits lists into sublists, with cutoffs where neighbours have a gap of n # CONSTRAINT: loi must be sorted sublists = [] current_sublist = [0] for i in range(1, len(loi)): if (loi[i] - loi[i-1]) >= n: sublists.append(current_sublist) current_sublist = [] current_sublist.append(loi[i]) return sublists def how_many_paths(n): # Count how many paths there are for lists of length n # Paths are valid where "jumps" between successive elements are 3 or shorter if n == 1 or n == 2: return 1 if n == 3: return 2 else: return how_many_paths(n-1) + how_many_paths(n-2) + how_many_paths(n-3) ## Solution strlist = open('input.txt', "r").read().splitlines() intlist = [int(i) for i in strlist] intlist.append(0) # The 0 volt outlet intlist.append(max(intlist)+3) # The joltage of the device intlist.sort() onev_diffs = plusminusn_counter(intlist, 1) threev_diffs = plusminusn_counter(intlist, 3) s1 = onev_diffs*threev_diffs sublists = split_list(intlist, 3) s2 = 1 for sl in sublists: s2 = s2 * how_many_paths(len(sl))
def rearrange_digits(input_list=None): """ Rearrange Array Elements so as to form two number such that their sum is maximum. Args: input_list(list): Input List Returns: (int),(int): Two maximum sums """ if type(input_list) is not list or input_list is None or len(input_list) == 0: print("Please check input") return sorted_list = heapsort(input_list) max_sum_1 = 0 max_sum_2 = 0 for i in range(0, len(sorted_list), 2): if i < len(sorted_list): max_sum_1 += sorted_list[i] * pow(10, i // 2) if i + 1 < len(sorted_list): max_sum_2 += sorted_list[i + 1] * pow(10, (i + 1) // 2) return max_sum_1, max_sum_2 def heapify(arr, n, i): largest_index = i left_node = 2 * i + 1 right_node = 2 * i + 2 if left_node < n and arr[i] < arr[left_node]: largest_index = left_node if right_node < n and arr[largest_index] < arr[right_node]: largest_index = right_node if largest_index != i: arr[i], arr[largest_index] = arr[largest_index], arr[i] heapify(arr, n, largest_index) def heapsort(arr): n = len(arr) for i in range(n, -1, -1): heapify(arr, n, i) for i in range(n - 1, 0, -1): arr[i], arr[0] = arr[0], arr[i] heapify(arr, i, 0) return arr def test_function(test_case): output = rearrange_digits(test_case[0]) solution = test_case[1] if sum(output) == sum(solution): print("Pass") else: print("Fail") test_function([[1, 2, 3, 4, 5], [542, 31]]) test_case = [[4, 6, 2, 5, 9, 8], [964, 852]] test_function(test_case) # Edge case test_case = [[9, 9, 9, 9, 9], [999, 99]] test_function(test_case) test_case = [[1, 0, 0, 0, 0], [100, 0]] test_function(test_case) test_case = [[0, 0, 0, 0, 0], [0, 0]] test_function(test_case) # Check "input_list" rearrange_digits() # "input_list" missing, should return "Please check input" rearrange_digits([]) # "input_list" is null, should return"Please check input"
""" @package steg A program for embedding character data into a greyscale image and extracting data so embedded. ### Embedding text into an image To embed a text file into the least-significant bits of an 8-bit greyscale image execute the command $ python steg.py embed in_img_file out_img_file data_file where * \c in_img_file is the name of some image file; \c data_file will be embedded in the least significant bits of the pixels of the image in \c in_img_file. * \c out_img_file is the name of the image file to create with the embedded text. * \c data_file is the name of the text file to embed. \c in_img_file must be an 8-bit greyscale image. \c in_img_file and \c out_img_file can be of any image format (the format will be detected by the filename extension), but \c out_img_file must be a lossless format such as PNG or TIFF. Furthermore, it must be the case that \f$32 + 8n \leq w\cdot h\f$, where \f$n\f$ is the number of characters in \c data_file , \f$w\f$ is the width of \c in_img_file , and \f$h\f$ is the height of \c in_img_file . ### Extracting text from an image To extract a text file that has been embedded into an image with the above command, execute the command $ python steg.py extract img_file where \c img_file is the file created by an invocation as above. The extracted text will be printed to the terminal. @author N. Danner """ # Python standard library modules. import sys # Python Image Library modules. from PIL import Image # Local modules import hw1_steg def _main(argv): command = argv[0] if command == 'embed': # python steg.py embed in_img out_img data in_img_filename = argv[1] out_img_filename = argv[2] data_filename = argv[3] # Read in the input image, quit if it is not 8-bit greyscale. in_img = Image.open(in_img_filename) if in_img.mode != 'L': print("Input image must be greyscale.") sys.exit(1) width, height = in_img.size pixels = list(in_img.getdata()) # Read in the data file. data_file = open(data_filename, 'r') data = data_file.read() data_file.close() # Embed the data into the image, getting the resulting image # returned to us. hw1_steg.str_into_pixels(data, pixels) # Save the resulting image (the Python Image Library looks at # the filename extension and automatically writes the appropriate # image format). out_img = Image.new("L", (width, height)) out_img.putdata(pixels) out_img.save(out_img_filename) elif command == 'extract': # python steg.py extract img in_img_filename = argv[1] # Read in the input image, quit if it is not 8-bit greyscale. in_img = Image.open(in_img_filename) if in_img.mode != 'L': print("Input image must be greyscale.") sys.exit(1) in_pixels = list(in_img.getdata()) # Get the data and print it out. data = hw1_steg.str_from_pixels(in_pixels) print(data) elif command == 'cr': # python steg.py cr img in_img_filename = argv[1] # Open the image and make sure it is type 'L'. img = Image.open(in_img_filename) if img.mode != 'L': print("Input image must be greyscale.") sys.exit(1) pixels = img.getdata() cr = hw1_steg.cr(pixels) # print("Compression ratio for " + in_img_filename + ": " + str(cr)) print("Compression ratio for %s: %1.4f" % (in_img_filename, cr)) else: print('Illegal command: %s' % command) sys.exit(2) if __name__ == '__main__': _main(sys.argv[1:])
""" @package duo_disp A program for displaying two images side-by-side. To run this program execute the following command: python duo_disp.py You can then select an image to display on either side by pressing the "Choose" button. The image must be 8-bit greyscale. Once an image is loaded, you can view a representation of the least-significant bits of the image by selecting the "Low bits" button. When you do so, each pixel of the displayed image will be colored black if the lsb of the corresponding pixel of the loaded image is 0 and white if it is 1. """ import tkinter.filedialog import tkinter from PIL import Image from PIL import ImageTk _IMG_WIDTH = 600 _IMG_HEIGHT = 450 def _do_resize(img, width, height): """ Resize an image to the given width and height, maintaining the aspect ratio of the original image. @type img: Image.Image @param img: the image to resize @type width: int @param width: the (maximum) width of the resized image. @type height: int @param height: the (maximum) height of the resized image. @rtype: Image.Image @returns: a new C{Image.Image} obtained by resizing C{img}. The aspect ratio of C{img} is preserved, and the returned image has width C{width} and/or height C{height}, depending on how the aspect ratios of the original image and the new size compare. """ img_width, img_height = img.size img_aspect_ratio = float(img_width)/img_height aspect_ratio = float(width)/height """ if img_aspect_ratio >= aspect_ratio: return img.resize((width, int(height*(aspect_ratio/img_aspect_ratio)))) else: return img.resize((int(width*(aspect_ratio/img_aspect_ratio)), height)) """ return img.resize((width, height)) class _image_frame(tkinter.Frame): """ @internal A widget that displays an image in a label, along with buttons for selecting the image and toggling whether the image or just the least-significant bits are displayed. This widget can only display 8-bit greyscale images (PIL type 'L'). """ def __init__(self, master): tkinter.Frame.__init__(self, master) self.configure(relief='raised', borderwidth=1) empty_image = Image.new("1", (_IMG_WIDTH, _IMG_HEIGHT)) img_tk = ImageTk.BitmapImage(empty_image) buttons = tkinter.Frame(self) choose_button = tkinter.Button(buttons, text='Choose', command=self._load_image) self.toggle_v = tkinter.IntVar() self.toggle_cb = tkinter.Checkbutton(buttons, text='Low bits', variable=self.toggle_v, command=self._toggle_low_bits) self.img_lbl = tkinter.Label(self, image=img_tk, bg="black") choose_button.pack(side='left') self.toggle_cb.pack(side='left') buttons.pack(side='top', anchor='w') self.img_lbl.pack(side='top') self.pack() def _toggle_low_bits(self): """ Switch between the image and low-order bits for the image in the given label, as per the value of C{self.toggle_v}; if C{self.toogle_v.get() == 0} display the image itself, otherwise display just the least-significant bits. """ img = self.img_tk if self.toggle_v.get() == 0 else self.img_tk_low_bits self.img_lbl.configure(image=img) def _load_image(self): img_filename = \ tkinter.filedialog.askopenfilename(title='Select an image file') if img_filename != '': # We'll save a reference to the resized image as part of the label # so that we have easy access to it if the user just wants to see # the low-order bits. img = _do_resize(Image.open(img_filename), _IMG_WIDTH, _IMG_HEIGHT) self.img_tk = ImageTk.PhotoImage(img) # Now compute the least-significant bits. low_img = Image.new('1', (_IMG_WIDTH, _IMG_HEIGHT)) pixels = img.getdata() low_bits = tuple(p%2 for p in pixels) low_img.putdata(low_bits) self.img_tk_low_bits = ImageTk.BitmapImage(low_img, foreground='white') self.toggle_v.set(0) self._toggle_low_bits() return def _main(): root = tkinter.Tk() left_f = _image_frame(root) right_f = _image_frame(root) left_f.pack(side='left') right_f.pack(side='right') root.mainloop() if __name__ == '__main__': _main()
def main(): num = eval(input("숫자를 입력하세요")) if num % 2 == 0: if num % 3 == 0: print("2의 배수 이면서 3의 배수 입니다") else: print("NO") else: print("NO") if num % 2 == 0 and num % 3 == 0: print("2의 배수 이면서 3의 배수 입니다") else: pass print("NO") main()
class WordFilter(object): def __init__(self, words): """ :type words: List[str] """ from collections import defaultdict dict = defaultdict(list) for i in range(0, len(words)): tmpwords = words[i] for j in range(0,len(tmpwords)+1): for k in range(0, len(tmpwords)+1): tmpwords2 = tmpwords[:j] + '#' + tmpwords[k:len(tmpwords)] dict[tmpwords2] = i + 1 self.dict = dict self.words = words def f(self, prefix, suffix): """ :type prefix: str :type suffix: str :rtype: int """ if not prefix and not suffix: return len(self.words)-1 tmpword = prefix + '#' + suffix if self.dict[tmpword]: return self.dict[tmpword] - 1 else: return -1 words = ["a","b"] prefix = "p" suffix = "pop" # Your WordFilter object will be instantiated and called as such: obj = WordFilter(words) param_1 = obj.f(prefix,suffix) print(param_1)
def longestPalindrome(s): """ :type s: str :rtype: str """ n = len(s) maxl = 0 start = 0 for i in range(0, n): if i - maxl >= 1 and s[i - maxl - 1:i + 1] == s[i - maxl - 1: i + 1][::-1]: start = i - maxl - 1 maxl += 2 continue if i - maxl >= 0 and s[i - maxl:i + 1] == s[i - maxl:i + 1][::-1]: start = i - maxl maxl += 1 return s[start: start + maxl] s = "ababsbsbs" ans = longestPalindrome(s) print(ans)
class Solution(object): def sortColors(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ for i in range(0, len(nums) - 1): for j in range(i, len(nums)): if nums[i] > nums[j]: nums[i], nums[j] = nums[j], nums[i] nums = [2,0,2,1,1,0] obj = Solution() ans = obj.sortColors(nums) print(ans)
class NumArray(object): def __init__(self, nums): """ :type nums: List[int] """ if nums: self.sumofnums = [0 for i in range(0, len(nums) + 1)] self.sumofnums[0] = 0 for i in range(1, len(nums)+1): self.sumofnums[i] = self.sumofnums[i - 1] + nums[i-1] def sumRange(self, i, j): """ :type i: int :type j: int :rtype: int """ return (self.sumofnums[j + 1] - self.sumofnums[i]) nums = [-2,0,3,-5,2,-1] i = 0 j = 5 obj = NumArray(nums) param_1 = obj.sumRange(i,j) print(param_1)
class Solution(object): def computeArea(self, A, B, C, D, E, F, G, H): """ :type A: int :type B: int :type C: int :type D: int :type E: int :type F: int :type G: int :type H: int :rtype: int """ area = (C - A) * (D - B) + (G - E) * (H - F) # 判断两矩形左边的关系, 取靠右的边: if A < E: A = E else: E = A # 如果不重叠: if A >= C or E >= G: return area # 判断两矩形右边的关系,取靠左的边: if G > C: G = C else: C = G # 如果不重叠: if A >= C or E >= G: return area # 判断两矩形下边的关系,取靠上的边: if B < F: B = F else: F = B # 如果不重叠: if B >= D or F >= H: return area # 判断两矩形上边的关系,取靠下的边: if H < D: D = H else: H = D # 如果不重叠: if B >= D or F >= H: return area return area - (C - A) * (D - B)
a=float(input("Enter 1st number: ")) b=float(input("Enter 2nd number: ")) if a%b==0: print(a,"is divisible by",b) else: print(a,"is not divisible by",b)
a=float(input("Enter 1st multiple: ")) b=float(input("Enter 2nd multiple: ")) c=float(input("Enter 3rd multiple: ")) d=float(input("Enter 4th multiple: ")) e=float(input("Enter 5th multiple: ")) div=float(input("Enter value of divisor: ")) count=0 if a%div==0: count+=1 if b%div==0: count+=1 if c%div==0: count+=1 if d%div==0: count+=1 if e%div==0: count+=1 print("Number of multiples of divisor from the given number:",count)
print("For Quadratic equation of general form ax^2+bx+c=0") print("Enter values of a,b and c") import math a=float(input("Enter value of a: ")) b=float(input("Enter value of b: ")) c=float(input("Enter value of c: ")) d=b**2-4*a*c x1=0 x2=0 if d>0: x1=(-b+math.sqrt(d))/(2*a) x2=(-b-math.sqrt(d))/(2*a) print("Roots of quadractic equation are (Real and distinct)",x1,x2) elif d==0: x1=(-b)/2*a print("Roots of quadractic equation are (Real and equal)",x1,x1) else: print("Roots are complex/Imaginary(As D<0)")
import numpy as np class GamblersRuin(object): """ Three fair coins tossed. Heads gets +1, tails -1, pay-offs are added and net pay-off added to equity. The 3 tosses are repeated 1000 times. Initial equity is 10 dollars p: probability that gambler is successful/ wins at each round. i: gambler's initial amount of money/reserves """ def __init__(self, p, init_bal): self.p = p self.init_bal = init_bal self.bal = init_bal self.q = 1 - self.p self.realizations = np.array(self.init_bal) self.simulation_results = [] def coin_toss(self): """ One coin flip with payoff (1, -1) with probability (p,q) """ outcome = np.random.uniform(0, 1) if outcome < self.p: result = 1 else: result = -1 return result def play_one_round(self): """ Three coin tosses in one round round """ result_round = 0 for i in range(0,3): result_round += self.coin_toss() return result_round def gamble(self, no_rounds): """ One round is played until ruin or no_rounds times """ self.realizations = np.array(self.init_bal) self.bal = self.init_bal round = 1 while round < no_rounds: round_result = self.play_one_round() if (self.bal + round_result) >= 0: self.bal += round_result else: break self.realizations = np.append(self.realizations, self.bal) round += 1 def simulate(self, no_simulations, no_rounds): # Gamble multiple times and store realization paths self.simulation_results = [] for game in range(1,no_simulations+1): self.gamble(no_rounds=no_rounds) self.simulation_results.append(self.realizations) def probability_ruin(self): # Analytical solution for calculating probability of ruin if you play infinite games if self.p > 0.5: prob_ruin_analytical = 1 - ((self.q/self.p) ** self.init_bal) else: prob_ruin_analytical = 1 # Probability of ruin in simulation # number of ruin / number of still in the game no_ruin = self.simulation_results return prob_ruin_analytical if __name__ == "__main__": # probability of success p = 0.5 # initial amount init_bal = 10 # number of rounds no_rounds = 100 # number of simulations no_simulations = 100 gr = GamblersRuin(p=float(p), init_bal=int(init_bal)) #result = gr.coin_toss() #result = gr.play_one_round() #print(result) #gr.gamble(no_rounds=no_rounds) #print(gr.realizations) gr.simulate(no_simulations=no_simulations, no_rounds=no_rounds) print(gr.simulation_results)
import math import operator """ create user similarity matrix w[u][v] 对称矩阵 """ def UserSimilarity(train): # build inverse table for item_users item_users = dict() for u, items in train.items():# user - items for i in items.keys(): item_users.setdefault(i, set()) item_users[i].add(u) # calculate co-rated items between users C = dict() # C represents common set N = dict() # N represents user u's items set for i, users in item_users.items():# item - users for u in users: N.setdefault(u, 0) N[u] += 1 C.setdefault(u, {}) for v in users: if u == v: continue C[u].setdefault(v, 0) C[u][v] += 1 #create similirity matrix, content represents weight W = C.copy() for u, related_users in C.items(): for v, cuv in related_users.items(): W[u][v] = cuv / math.sqrt(N[u] * N[v]) #calculate cos similirity return W """ sort the W[u], find the most similiar user v sort the items user u may need """ def Recommend(user, train, W, K=3): rank = dict() interacted_items = train[user] #given the user, sort the top K similiar users for v, wuv in sorted(W[user].items(), key=operator.itemgetter(1), reverse=True)[0:K]: for i, rvi in train[v].items(): # we should filter items user interacted before if i in interacted_items: continue rank.setdefault(i, 0) #calculate the score of items that were not known by user(u) but they #were bought by user(v) rank[i] += wuv * rvi[0] #wuv = similiar user; rvi = user r 对 item(i) 的兴趣 rank = sorted(rank.items(), key=operator.itemgetter(1), reverse=True) return rank """ calculate all users may need items """ def Recommendation(users, train, W, K=3): result = dict() for user in users: rank = Recommend(user, train, W, K) result[user] = rank return result
import matplotlib.pyplot as plt import numpy as np def transform(sample,j,operator): ''' Transforms a given sample based on specified set of raising and lowering operators. Transformed state can be used to obtain corresponding amplitude coefficient in local estimator. :param sample: Sample for which value of observable is being determined. :type sample: str :param j: Subscript of first spin observable. :type j: int :param operator: The observable to be measured. One of "S+S-" "S-S+". :type operator: str :returns: Transformed sample after applying two spin observable. :rtype: str ''' newSample = list(sample) if operator == "S+S-": newSample[j] = "1" newSample[j+1] = "0" elif operator == "S-S+": newSample[j] = "0" newSample[j+1] = "1" return "".join(newSample) def convert(operator,sample,amplitudes): ''' Calculates the value of an observable corresponding to a given spin configuration. :param operator: The observable to be measured. One of "S2S3" "SzSz" "S+S-" "S-S+". :type operator: str :param sample: Sample for which value of observable is being determined. :type sample: str :param amplitudes: List of amplitudes corresponding to quantum state. :type amplitudes: listof float :returns: Value of the observable corresponding to the given sample. :rtype: float ''' total = 0 org = amplitudes[int(sample,2)] if operator == "S2S3": for i in range(len(sample)-1): if i == 1: if sample[i:i+2] == "00" or sample[i:i+2] == "11": total += 0.25 else: total += -0.25 elif operator == "SzSz": for i in range(len(sample)-1): if sample[i:i+2] == "00" or sample[i:i+2] == "11": total += 0.25 else: total += -0.25 elif operator == "S+S-": for i in range(len(sample)-1): if sample[i:i+2] == "01": total += amplitudes[int(transform(sample,i,"S+S-"),2)]/org elif operator == "S-S+": for i in range(len(sample)-1): if sample[i:i+2] == "10": total += amplitudes[int(transform(sample,i,"S-S+"),2)]/org return total def operatorCheck(operator, listofMs, amplitudeFilename, samplesFilename, observablesFilename, textBox = False): ''' Compares average value of observable from samples with expected value from tensor contractions. Creates a plot of error versus number of samples. This will verify that the simulator is working and will give us an idea of the minimum number of samples to use. :param operator: The observable to be measured. One of "S2S3" and "H". :type operator: str :param listofMs: List of number of samples to try. :type listofMs: listof int :param amplitudeFilename: Name of file containing amplitudes :type amplitudeFilename: str :param samplesFilename: Name of file containing samples :type samplesFilename: str :param observablesFilename: Name of file containing exact expectation values of observables :type observablesFilename: str :param textBox: If True then will display textbox showing exact expectation value of observable. Default is False. :type textBox: bool :returns: Final relative error between expected value of observable and measured value of observable :rtype: float ''' # Read and store samples from sample file samples = [] sampleFile = open(samplesFilename) lines = sampleFile.readlines() numQubits = len(lines[0].split(" ")) - 1 for line in lines: samples.append(line.replace(" ","").strip("\n")) sampleFile.close() # Read and store amplitudes from amplitudes file amplitudes = [] amplitudeFile = open(amplitudeFilename) lines = amplitudeFile.readlines() for line in lines: amplitudes.append(float(line.split(" ")[0])) amplitudeFile.close() # Read and store amplitudes from amplitudes file observablesFile = open(observablesFilename) lines = observablesFile.readlines() S2S3 = lines[0].strip("\n").split(" ")[1] H = lines[1].strip("\n").split(" ")[1] observablesFile.close() if operator == "S2S3": expectedValue = float(S2S3) opStr = r"S_{2}^{z}S_{3}^{z}" elif operator == "H": expectedValue = float(H) opStr = "H" total = 0 values = [] for i in range(len(samples)): if operator == "S2S3": total += convert("S2S3",samples[i],amplitudes) elif operator == "H": total += -convert("SzSz",samples[i],amplitudes) total += -0.5 * convert("S+S-",samples[i],amplitudes) total += -0.5 * convert("S-S+",samples[i],amplitudes) if i in listofMs: values.append(abs(expectedValue - total/(i+1))/abs(expectedValue)) fig, ax = plt.subplots() plt.plot(listofMs,values,"o") plt.xlabel("Number of Samples") plt.ylabel("Relative Error") plt.title(r"Accuracy Plot of $\left \langle \psi \left" + r" | {0} \right".format(opStr) + r" |\psi \right \rangle$ for " + "N = {0}".format(numQubits)) props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) if textBox: plt.text(0.65, 0.12, r"$\left \langle \psi \left" + r" | {0} \right".format(opStr) + r" |\psi \right \rangle$ = " + str(round(expectedValue,4)), transform = ax.transAxes,fontsize = 14, verticalalignment = "top",bbox = props) plt.ticklabel_format(style = "sci", axis = "y", scilimits = (0,0)) plt.tight_layout() plt.savefig("{0}".format(operator),dpi = 200) finalError = abs(expectedValue - total/(i+1))/abs(expectedValue) return finalError
age=int(input("你的年龄:")) if age >= 18: print("你的年龄: %d 岁,你可以进网吧!" % age) else: print("未成年禁止入内!")
def print_line(char, times): """ 打印出单行分隔线 :param char: 分隔字符 :param times: 每行分隔符个数 """ print(char * times) def print_lines(char, times, row): """ 打印多行分隔线 :param char: 分隔符 :param times: 每行分隔符个数 :param row: 行数 """ col = 0 while col < row: print_line(char, times) col += 1 name = "我是一个模块"