text
stringlengths
37
1.41M
# Enter your code here. Read input from STDIN. Print output to STDOUT if __name__ == '__main__': N = int(input()) X = list(map(int, input().split())) W = list(map(int, input().split())) weighted_mean = round(float(sum([x * w for x, w in zip(X, W)])) / sum(W), 1) print(weighted_mean)
def add(a,b): print "ADDING %d + %d" % (a,b) return a+b def substract(a,b): print "SUBSTRACTING %d - %d" % (a,b) return a-b def divide(a,b): print "DIVIDING %d / %d" % (a,b) return a/b def multiply(a,b): print "MULTUPLYING %d * %d" % (a,b) return a*b result = add(24, substract(divide(34,100),1023)) print result
import tkinter window = tkinter.Tk() window.title('My first gui program') window.minsize(width=500, height=300) # label my_label = tkinter.Label(text='I am a label', font=('Arial', 24, "bold")) my_label.pack() # places it on the screen, centered # button def button_clicked(): print('I got clicked.') if len(input.get()) > 0: my_label.config(text = input.get()) button = tkinter.Button(text = 'click me', command = button_clicked) button.pack() #Entry input = tkinter.Entry(width = 10) input.pack() window.mainloop() # end of the program
from turtle import Turtle, Screen import random race = False screen = Screen() screen.setup(width = 500, height = 400) bet = screen.textinput("Make your bet", 'Which turtle will win the race? Enter a color: ') colors = ['red','orange','yellow','green','blue','purple'] turtles = [] for num, color in enumerate(colors): turtle = Turtle(shape = 'turtle') turtle.color(color) turtle.penup() turtle.goto(x = -230, y = (120 - num * 40)) turtles.append(turtle) if bet: race = True while race: for turtle in turtles: distance = random.randint(0,10) turtle.forward(distance) if turtle.xcor() > 230: race = False winning_color = turtle.pencolor() if winning_color == bet: print(f"You've won! The winning color is {winning_color}.") else: print(f"You've lost! The winning color is {winning_color}") screen.listen() screen.exitonclick()
from turtle import Screen, Turtle import pandas as pd from map import Map from map_game import Game df = pd.read_csv('50_states.csv') df['state'] = df['state'].apply(lambda x: x.lower()) map = Map() game = True while game: answer_state = map.user_input() if answer_state in df['state'].values: map.update_score() state = Game(df, answer_state) elif answer_state == 'quit': break else: pass map.screen.exitonclick() missing_states = df[~df['state'].isin(map.states_chosen)] missing_states['state'].to_csv('wrong_answer.csv')
##################### Extra Hard Starting Project ######################] import smtplib import datetime as dt import pandas as pd import random # 1. Update the birthdays.csv now = dt.datetime.now() month = now.month day = now.day df = pd.read_csv('birthdays.csv') # 2. Check if today matches a birthday in the birthdays.csv if day in list(df['day']): birthday_person = df[df['day'] == day] if month in list(birthday_person['month']): name = birthday_person['name'].values[0] email = birthday_person['email'].values[0] # 3. If step 2 is true, pick a random letter from letter templates and replace the [NAME] with the person's actual # name from birthdays.csv birthday_letters = ['letter_1.txt', 'letter_2.txt', 'letter_3.txt'] with open(random.choice(birthday_letters)) as f: letter = f.read().replace('[NAME]', name) # 4. Send the letter generated in step 3 to that person's email address. my_email = '' password = '' def send_email(from_email, to_email, password, msg): with smtplib.SMTP("smtp.gmail.com", port=587) as connection: connection.starttls() connection.login(user=from_email, password=password) connection.sendmail(from_addr=my_email, to_addrs=to_email, msg=f"Subject:Your special day.\n\n{msg}") send_email(my_email, email, password, letter)
# 🚨 Don't change the code below 👇 print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") # 🚨 Don't change the code above 👆 #First *fork* your copy. Then copy-paste your code below this line 👇 #Finally click "Run" to execute the tests true = ['t','r','u','e'] love = ['l', 'o','v','e'] name_combined = (name1 + name2).lower() true_count = [] love_count = [] for c in true: true_count.append(name_combined.count(c)) for c in love: love_count.append(name_combined.count(c)) score = str(sum(true_count)) + str(sum(love_count)) if int(score) >= 40 and int(score) <= 50: print(f'Your score is {score}, you are alright together.') elif int(score) < 10 or int(score) > 90: print(f'Your score is {score}, you go together like coke and mentos.') else: print(f'Your score is {score}.')
inicio=0 while(inicio<=100): if(inicio%3==0): print("Numeros Divisibles por 3") inicio+=1
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None ''' Sum of Left Leaves 題目: 加總整棵樹左邊的子葉 想法: - 沒有樹回傳0 - 判斷是不是葉 - 左葉回傳原本的值,右葉回傳零 - 並在方入葉的時,紀錄是不是左邊 - 遞迴 Time: O(n) Space: O() ''' class Solution(object): def sumOfLeftLeaves(self, root): """ :type root: TreeNode :rtype: int """ def sumOfLeftLeavesTool(root, is_left): if not root: return 0 if not root.left and not root.right: return root.val if is_left else 0 return sumOfLeftLeavesTool(root.left, True) + sumOfLeftLeavesTool(root.right, False) return sumOfLeftLeavesTool(root, False)
''' Kth Largest Element in an Array 題目: 找出第 k 個最大的元素 想法: - 利用 Heap 回傳最小並且不改變父類別最小的特性 - 每個數變負數後,原本最大的數,會被先返回 - 跑 k 次迴圈取出,最後一個取出的就是第 k 個最大的元素 - 還原成正數 Time: O() Space: O() ''' import heapq class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ heap = [] for num in nums: heapq.heappush(heap, -num) for _ in range(k): res = heapq.heappop(heap) return res * -1
''' 513. Find Bottom Left Tree Value [題目] 在樹中找最深且最左邊的值 [思考] 最深優先權最高,依樣深選最左邊 DFS 我要記住目前最深的,還要知道我是該層最左邊的 BFS 由右至左,一層一層下去,最後一個值就是我們的答案 ''' from Queue import Queue class Solution(object): def findBottomLeftValue(self, root): """ :type root: TreeNode :rtype int """ queue = Queue() queue.put(root) node = None while not queue.empty(): node = queue.get() if node.right: queue.put(node.right) if node.left: queue.put(node.left) return node.val
def bruter(lis, maximum, num_max): err = 0 shouldpass = 0 while len(lis) <= maximum: try: bruterhand(lis) except NameError: print("[!]you should define a func called bruterhand() to use the output of this func[!]") err = 1 if err == 1: break for i in range(len(lis)): if i == 0: lis[i] += 1 if lis[i - 1] > num_max: lis[i] += 1 lis[i - 1] = 0 if lis[i] > num_max: lis[i + 1] += 1 lis[i] = 0 if lis[len(lis) - 2] & lis[len(lis) - 1] == num_max: shouldpass = 0 for s in range(len(lis)): if lis[s] == num_max: shouldpass += 1 else: shouldpass = 0 if shouldpass == len(lis): bruterhand(lis) lis.append(0) for D in range(len(lis)): lis[D] = 0
""" These are the unit tests for the calculator library """ import calculator class TestCalculator: def test_addition(self): assert 40 == calculator.addition(20, 20) def test_subtraction(self): assert 2 == calculator.subtraction(4, 2) def test_multiplication(self): assert 16 == calculator.multiplication(4, 4) def test_division(self): assert 25.0 == calculator.division(125, 5) def test_sqrt(self): assert 4 == calculator.sqrt(16) def test_crt(self): assert 2 == calculator.crt(8) def test_factorial(self): assert 120 == calculator.factorial(5) def test_power(self): assert 729 == calculator.power(9, 3) def test_modulus(self): assert 1 == calculator.modulus(4, 3) def test_vector_Length(self): assert 4.47 == calculator.vector_Length(4, 2) def test_cos(self): assert 0 == calculator.cos("degrees", 90) def test_sin(self): assert 1 == calculator.sin("degrees", 90) def test_tan(self): assert 1 == calculator.tan("degrees", 45) def test_acos(self): assert 1.05 == calculator.acos(0.5) def test_asin(self): assert 0.52 == calculator.asin(0.5) def test_atan(self): assert 0.46 == calculator.atan(0.5) def test_log(self): assert 1.58 == calculator.log(3, 2)
def main(): x = eval(input("Unesite 1: ")) y = eval(input("Unesite 2: ")) c = x+y print(c) main() # Programi # Programi
"""Importamos la libreria math, para poder llevar a cabo operaciones matematicas""" import math """Valor al que sacaremos su raiz cuadrada, se ha identificado con una x""" x = 100 """Se ocupa la funcion math.sqrt, la cual nos permite obtener la raiz cuadrada de un numero""" print(math.sqrt(x)) """Definimos el objeto raiz cuadrada, en el cual se hara el calculo de la raiz cuadrada en forma de objeto""" def raiz_cuadrada(n): x = 0 while x * x <= n: x += 0.001 return x print (raiz_cuadrada(x))
class node: def __init__(self,power,prefix): self.power=power self.prefix=prefix self.nextNode=None class linked: def __init__(self): self.head=None def printer(self): search=self.head while(True): if search==None: break data=str(search.prefix)+"x^"+str(search.power) print(data,end='+') search=search.nextNode print('0') def add(self,power,prefix): nodeVal=node(power,prefix) nodeVal.nextNode=self.head self.head=nodeVal def main(): polynomial=linked() while True: choice=int(input('Enter the operation you would like to perform:\n1.Add\n2.Print and exit')) if choice==1: prefix=int(input('Enter the prefix: ')) power=int(input('Enter the power: ')) polynomial.add(prefix,power) elif choice==2: polynomial.printer() break if __name__=="__main__": main()
counter = 0 sum = 0 while True: inputNumber = input() # Integer input try: number = int(inputNumber) isPrime = True canDivideby10 = False if number%10 == 0: canDivideby10 = True else: if number < 2: isPrime = False else: if number/2 >= 2: for i in range (2,int(number/2+1)): if number%i == 0: isPrime = False break if canDivideby10 == False and isPrime == False: sum += number**2 counter += 1 # print("number:", number, " counter:", counter, " sum:", sum) # Integer disinda birsey yazilinca loop durdur except ValueError: break print(counter,sum)
#Write a function to print "hello_USERNAME!" USERNAME is the input of the function. #The first line of the code has been defined as below. def hello_username (username): return username=str(input("enter username : ")) print(f"Hello " + str(username))
# -*- coding: utf-8 -*- """ Created on Mon Nov 30 22:52:19 2020 @author: convi """ #11.Crie um programa para ler uma string fornecida pelo usuário. Informe se essa stringforma um palíndromo. palavra = input("") for i in range(int(len(palavra)/2)): if(palavra[i] != palavra[-i - 1]): print("não é palindromo") print("é palindromo") #12 Crie um programa para ler duas strings fornecidas pelo usuário. Verifique se elasforam um anagrama. a = input('digite uma palavra:') b = input('digite outra palavra:') x = list(a) x.sort() print(x) y = list(b) y.sort() print(y) if x == y: print('é um anagrama') else: print('não é um anagrama') #13.Faça um programa para multiplicar matrizes 3x3. m1 = [[1, 1, 1], [2, 2, 2], [3, 3, 3]] m2 = [[0, 0, 0], [1, 1, 1], [2, 2, 5]] resultado = [] for i in range(len(m1)): linha = [] for j in range(len(m2[0])): linha.append(m1[i][j] * m2[i][j]) resultado.append(linha) print(resultado) """ #14.Faça um programa para calcular a soma , a subtração e a multiplicação de matrizes. Você pode fornecer a matriz no código, em vez de ler o que o usuário digitar, mas suasfunções que fazem os cálculos devem ser úteis para qualquer tamanho de matriz desde que aspropriedades matemáticas sejam respeitadas. """ m1 = [[1, 1, 1], [2, 2, 2], [3, 3, 3]] m2 = [[0, 0, 0], [1, 1, 1], [2, 2, 5]] def calcula(operacao): resultado = [] for i in range(len(m1)): linha = [] for j in range(len(m2[0])): if(operacao == "soma"): linha.append(m1[i][j] + m2[i][j]) elif(operacao == "mult"): linha.append(m1[i][j] * m2[i][j]) elif(operacao == "sub"): linha.append(m1[i][j] - m2[i][j]) resultado.append(linha) return resultado print(calcula("soma")) print(calcula("mult")) print(calcula("sub")) """ 15.Crie um programa que verifica todos os números perfeitos em um intervalo fornecidopelo usuário. Ou seja, o usuário fornece dois valores (inicial e final) e o programa verifica seexiste e quais são os números perfeitos nesse intervalo. Para saber o que são númerosperfeitos, busque na wikipedia. """ inicial = int(input("")) final = int(input("")) if(inicial <= 0): inicial = 1 for i in range(inicial, final + 1): soma_divisores = 0 for j in range(1, i): if(i % j == 0): soma_divisores += j if(soma_divisores == i): print(i, " é um numero perfeito")
import networkx as nx import matplotlib.pyplot as plt U=nx.Graph() #undirected graph G=nx.DiGraph() #Directed graph print(G.nodes()) G.add_nodes_from([i for i in range(10)]) print(G.edges()) #by default show outgoing edges G.add_edge(1,2) G.add_edge(0,2) G.add_edge(1,3) G.add_edge(3,1) G.add_edge(3,5) print(G.out_edges()) print(G.in_edges()) nx.draw(G,with_labels=True) plt.show()
#输入三角形的三个变长,求三角形的周长和面积 #注意两边之和大于第三边,两边之差小于第三边 #注意三角形三边的面积公式 def is_angle(a,b,c): if a + b > c and a + c >b and b + c > a and a - b< c and a - c < b and b - c < a: return True else: return False def perm_angle(a,b,c): if is_angle(a,b,c): return a + b + c else: return 0 def aera_angle(a,b,c): if is_angle(a,b,c): p = perm_angle(a,b,c) return (p*(p-a)*(p-b)*(p-c)) ** 0.5 else: return 0 a = float(input('a = ')) b = float(input('b = ')) c = float(input('c = ')) print('the perim is %.2f , the aera is %.2f'%(perm_angle(a,b,c),aera_angle(a,b,c)))
#将输入的话是温度转换成摄氏温度 #公式是:c = (f - 32) / 1.8 # # f = float(input("请输入华氏温度:")) c = (f -32) / 1.8 print('%.1f 华氏度 = %1.f 摄氏度'%(f,c))
# 使用变量保存数据,并进行算术运算 # a = 123 b = 321 print(a + b) print(a * b) print(a - b) print(a / b) #取整数运算 print(a // b) #取模运算 print(a % b) #指数运算 print(a ** 2) print('*'*20) # 使用type() 检查变量类型 # a = 123 b = 12.345 # 1 + 5j 和 1 + 5J 是一样的 c = 1 + 5J d = 'hello world' e = True #注意首字母大小写的问题 print (type(a)) print (type(b)) print (type(c)) print (type(d)) print (type(e)) print('*'*20) # 1、input 函数的使用 # 2、int()函数,办参数转换成整数 # 3、print() 函数输出带占位符的字符串 # a = int(input('a = ')) b = int(input('b = ')) print('%d + %d = %d'%(a,b,a+b)) print('%d - %d = %d'%(a,b,a-b)) print('%d * %d = %d'%(a,b,a*b))
#使用while循环 #while 循环使用时候,可以不用知道循环次数,while True: #可以使用break,终止循环 #可以使用continue,结束本次循环,进入下一次循环 # #猜数游戏 # import random answer = random.randint(1,100) count = 0 while True: value = float(input('请输入结果:')) if value > answer: print('答案偏大,需要小一点') count += 1 elif value < answer: print('答案偏小,需要大一点') count += 1 else: if count > 7: print('次数偏多,加油补智商') else: print('回答正确') break
class Node: def __init__(self, value): self.value = value self.next = None class Slist: def __init__(self, value): node = Node(value) self.head = node def addNode(self, value): node = Node(value) runner = self.head while (runner.next != None): runner = runner.next runner.next = node return self def printAllValues(self, msg=""): runner = self.head print('Head is', id(runner), msg) while(runner.next != None): print(runner.value) runner = runner.next print(runner.value) return self def removeNode(self, value): # node you want to remove is head if self.head.value == value: if self.head.next == None: self.head = None else: self.head = self.head.next # node you want to remove is in middle elif self.head.next != None: prev = self.head runner = prev.next while(runner.next != None): if runner.value == value: prev.next = runner.next break prev = runner runner = prev.next # remove last element if runner.next == None: prev.next = None def insertNode(self, value, index): runner = self.head node = Node(value) counter = 0 # first node if index == counter: self.head = node self.head.next = runner else: prev = self.head runner = prev.next count = 1 # middle while (runner.next and index != counter): prev = runner runner = prev.next counter += 1 prev.next = node node.next = runner list = Slist(5) list.addNode(3) list.addNode(1) list.insertNode(7, 0) list.printAllValues("Attempt 1")
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ p = t = ListNode(0) carry = 0 while l1 or l2 or carry: val = (l1 and l1.val or 0) + (l2 and l2.val or 0) + carry carry, val= divmod(val, 10) p.next = ListNode(val) l1 = l1 and l1.next l2 = l2 and l2.next p = p.next return t.next l1 = ListNode(7) l1.next = ListNode(8) l1.next.next = ListNode(5) l2 = ListNode(3) l2.next = ListNode(2) l2.next.next = ListNode(5) s = Solution() l3 = s.addTwoNumbers(l1, l2) while l3: if l3.next: print(l3.val, end = ',') else: print(l3.val) l3 = l3.next
import turtle import random kucha = random.randint(5, 25) #kucha = 10 radius = 15 win = turtle.Screen() alex = turtle.Turtle() alex.speed("fastest") row_count = 1 max_in_kucha = 1 while kucha > max_in_kucha: row_count = row_count + 1 max_in_kucha = max_in_kucha + row_count alex.write(str(kucha)) alex.penup() alex.fillcolor("green") alex.right(90) alex.fd(row_count * radius * 2) alex.right(90) alex.fd(row_count * radius) alex.left(180) alex.pendown() output_count = 0 while output_count < kucha: output_in_row = 0 while output_in_row < row_count and output_count < kucha: alex.pendown() alex.begin_fill() alex.circle(radius) alex.end_fill() alex.penup() alex.fd(radius * 2) output_in_row += 1 output_count += 1 row_count -= 1 alex.left(90) alex.fd(radius * 2) alex.left(90) alex.fd(radius) alex.fd(radius * 2 * row_count) alex.left(180) alex.pendown() win.exitonclick()
n = int(input()) cub = 3 ** n fact = 1 for i in range(1, n + 1): fact = fact * i print(cub, fact)
# Dynamic Function def get_func_mult_by_num(num): def mult_by(value): return num * value return mult_by generated_func = get_func_mult_by_num(5) print("5 * 10 = ", generated_func(10)) def testing_function(number1): def inner_func(number2): return number1, number2 return inner_func tester = testing_function(32) print("This should print out two numbers: ", tester(64)) def mult_by_2(num): return num * 2 times_two = mult_by_2 # List of functions listOfFuncs[0] would call times_two listOfFuncs = [times_two, generated_func] print("5 * 9 =", listOfFuncs[1](9))
# -*- coding: utf-8 -*- """ Created on Mon Jun 25 19:51:43 2018 @author: joshu """ import math import random # Recursive Factorial def factorial(num): if num <= 1: return 1 else: result = num * factorial(num - 1) return result print(factorial(4)) def recursive_factorial(num): if num <= 1: return 1 else: return (recursive_factorial(num - 1) * num) print(recursive_factorial(4))
# -*- coding: utf-8 -*- """ Created on Mon Jun 25 09:38:48 2018 @author: joshu """ import random def bubble_sort(unsorted_list): i = len(unsorted_list) - 1 while i > 1: j = 0 while j < i: #print("\nIs {} > {}".format(unsorted_list[j], unsorted_list[j + 1])) if unsorted_list[j] > unsorted_list[j + 1]: #print("Swap") temp = unsorted_list[j] unsorted_list[j] = unsorted_list[j + 1] unsorted_list[j + 1] = temp else: j += 1 #for k in unsorted_list: #print(k, end=', ') #print() #print("END OF ROUND") i -= 1 return unsorted_list random_list = [random.randrange(1,100) for i in range(10)] print(random_list) print(bubble_sort(random_list))
# -*- coding: utf-8 -*- """ Created on Sun Jun 24 11:27:53 2018 @author: joshu """ # Will provide different outputs based on age # 1-18 -> Important # 21, 50, or > 65 -> Important # All others -> Not Important # age = eval(input("Please enter your age: ")) if ((age >= 1) and (age <= 18)): print("IMPORTANT") elif ((age == 21) or (age == 50) or (age > 65)): print("IMPORTANT") else: print("NOT IMPORTANT")
# -*- coding: utf-8 -*- """ Created on Sun Jun 24 20:31:22 2018 @author: joshu """ import random import math # 1. An outer loop decreases in size each time # 2. The goal is to have the largest number at the end of the list # when the outer loop completes 1 cycle # 3. The inner loop starts comparing indexes at the beginning of the loop # 4. Check if list[Index] > list[Index + 1] # 5. If so swap the index values # 6. When the inner loop completes the largest number is at the end # of the list # 7. Decrement the outer loop by 1 numList = [] for i in range(5): numList.append(random.randrange(1,10)) for i in numList: print(i) # Using List Comprehensions testList = [random.randrange(1,10) for i in range(5)] print(testList) def bubble_sort(unsorted_list): # Setting i equal to the lenth of the unsorted_list - 1 because if the list # has 5 elements the indexes are 0,1,2,3,4 and that is 5 elements i = len(unsorted_list) - 1 while i > 1: k = 0 while k < i: if unsorted_list[k] > unsorted_list[k + 1]: # Swap temp = unsorted_list[k] unsorted_list[k] = unsorted_list[k + 1] unsorted_list[k + 1] = temp else: k += 1 i -= 1 return unsorted_list random_list = [random.randrange(1,101) for i in range(10)] print(random_list) print(bubble_sort(random_list))
# Prime number generator def isPrime(num): for i in range(2, num): if (num % i == 0): return False return True def gen_Primes(max_number): for num1 in range(2, max_number): if isPrime(num1): yield num1 prime = gen_Primes(50) print("Prime :", next(prime)) print("Prime :", next(prime)) print("Prime :", next(prime)) print("Prime :", next(prime)) print("Prime :", next(prime))
import random try: aList = [1,2,3] print(aList[3]) except (IndexError,NameError): print("Sorry that index doesnt exist") except: print("An unknown error occurred") class DogNameError(Exception): def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) try: dogName = input("What is your dogs name : ") if any(char.isdigit() for char in dogName): raise DogNameError except DogNameError: print("Your dogs name can't contain a number") num1, num2 = input("Enter two values to divide ").split() try: quotient = int(num1) / int(num2) print("{} / {} = {}".format(num1, num2, quotient)) except ZeroDivisionError: print("You can't divide by zero") else: print("You didn't raise an exception") finally: print("I execute no matter what")
# -*- coding: utf-8 -*- """ Created on Sun Jun 24 12:10:26 2018 @author: joshu """ # Have the user enter their investment amount and expected interest # Each year their investment will increase by their investment + their # investment * interest rate # Print out the earnings after a 10 year period money, interest_rate = input("Please enter your investment amount and \ your expected interest: ").split(" ") money = float(money) interest_rate = float(interest_rate) for i in range(1,11): money = money + (money * interest_rate) print("For year {}, your investment amount was {:.2f}: ".format(i, money))
# -*- coding: utf-8 -*- """ Created on Sun Jun 24 15:18:15 2018 @author: joshu """ from decimal import Decimal as D sum = D(0) sum += D("0.1") sum += D("0.1") sum += D("0.1") sum -= D("0.3") print("Sum = ", sum) print("0.1 + 0.1 + 0.1 - 0.3 = ", (0.1 + 0.1 + 0.1 - 0.3))
# Given list of ints, return True if any two nums in list sum to 0. # Given the wording of our problem, a zero in the list will always make this true, # since “any two numbers” could include that same zero for both numbers, and they sum to zero # This function isn’t implemented, though, so when we run addtozero.py, we have test failures. def add_to_zero(nums): """Given list of ints, return True if any two nums sum to 0."""
import datetime # 1) Write me Python code that generates all prime numbers between 0 and 100 for num in range(1,101): count = 0 for i in range (2, num//2+1): if num % i == 0: count=+1 break if count == 0 and num != 1: print('%d' %num, end = ' ',) # 2) take a list of strings [‘banana’ , ‘apple’ , ‘zebra’, ‘raspberry’] and order it in alphabetical order words = ['banana', 'apple', 'zebra', 'raspberry'] print(sorted(words)) # 3) generate (you will need to look up how to generate) two sets of numbers - A and B. # Then determine which numbers are common to both sets. list_A = [1,3,24,5,6,32,1,2,3,45] list_B = [2,3,4,5,21,54,65,2,4,5] set_A = set(list_A) set_B = set(list_B) print(set_A.intersection(set_B)) # 4) make a dictionary of people you know: record their names and birthdays. # Then write a function which takes as input the names of any two people in your # dictionary and tells me the difference in minutes between their birthdays. # You MUST define a function to do this. people = {'Joe': '1988/1/1', 'Tom':'1987/1/1'} def difference_in_birthdays(name_one, name_two): date_one = people[name_one] date_two = people[name_two] format_date = '%Y/%m/%d' datetime_obj_one = datetime.datetime.strptime(date_one, format_date) datetime_obj_two = datetime.datetime.strptime(date_two, format_date) difference = datetime_obj_one - datetime_obj_two difference_min = difference.total_seconds()/60 return difference_min print(difference_in_birthdays('Joe','Tom')) # 5) make a .txt file in your computer, this file should have at least a paragraph of text, import that into Python, # make every odd numbered sentence in uppercase and every even sentence lowercase. Save this via Python as a new text file # in the same directory as the old file. DO NOT overwrite the old file (hint: check out the nltk library) # import nltk.data # import nltk.tokenize # nltk.download('punkt') # # f = open('text_file.txt', 'x') #creates the file # text_file = open('text_file.txt', 'r') # # print(text_file.read()) # sentence_count = nltk.sent_tokenize(text_file) # print(sentence_count) # 6) Look at the numpy library, import this into your Python session and # construct 2 numpy arrays, multiple then together, what happened? import numpy as np # when arrays are same shapes arr_one = np.array([1, 2, 3, 4, 5]) arr_two = np.array([6,7,8,9,10]) print(np.multiply(arr_one, arr_two)) #when arrays are in diff shapes and need to be resized #arange() is a function to specify the range and index starts with zero and doesnt include the last number x2 = np.arange(9).reshape((3,3)) print(x2) x3 = np.arange(3) print(x3) print(np.multiply(x2, x3)) # 7) given a list of numbers [38, 42, 53, 94, 1, 3, 4, 79] # return me a list of ones and zeroes where a 1 signifies # If the number in the element is divisible by 2 with no remainder. # So your answer should be [1, 1, 0, 1, 0, 0, 1, 0] list_of_numbers = [38, 42, 53, 94, 1, 3, 4, 79] new_list = [] for i in list_of_numbers: if i % 2 == 0: new_list.append(1) else: new_list.append(0) print(new_list) # 8) Count words in a string. # E.g. “This is a string and you must count words in this” # 9) count how many times each value is in a list # (use base Python for this, don’t import Counter) # 10) given a list, # return a deduped list while maintaining its order
#! python3 # Chapter 10 Project - Use Transposition Ecryption and Decryption on files import time, os, sys, TranspositionDecrypt, TranspositionEncrypt def main(): #inputFilename = 'frankenstein.txt' inputFilename = 'frankenstein_encrypted.txt' outputFilename = 'frankenstein_decrypted.txt' key = 10 mode = 'decrypt' # Set to 'encrypt' or 'decrypt' # If the input file does not exist, the program terminates early if not os.path.exists(inputFilename): print("The file %s does not exist. Quitting..." % inputFilename) sys.exit() # If the output file already exists, give the user a chance to exit # (Otherwise the file will be overwritten) if os.path.exists(outputFilename): print("This will overwrite the file %s. (C)ontinue or (Q)uit?" % outputFilename) response = input(">") if not response.lower().startswith("c"): sys.exit() # Read the message from the input file fileObj = open(inputFilename) content = fileObj.read() fileObj.close() print("%sing..." % mode.title()) # Measure how long the encryption/decryption takes startTime = time.time() if mode == 'encrypt': translated = TranspositionEncrypt.encryptMessage(key, content) elif mode == 'decrypt': translated = TranspositionDecrypt.decryptMessage(key, content) totalTime = round(time.time() - startTime, 2) print("%sion time: %s seconds" % (mode.title(), totalTime)) # Write out the translated message to the output file outputFileObj = open(outputFilename, 'w') outputFileObj.write(translated) outputFileObj.close() print("Done %sing %s (%s characters)." % (mode, inputFilename, len(content))) print("%sed file is %s." % (mode.title(), outputFilename)) # If TranspositionFileCipher.py is run (instead of imported as a module) # call the main() function: if __name__ == '__main__': main()
''' 1. 按照经验将不同的变量储存为不同类型的数据 2. 验证这些数据是何种类型 ''' # int--整型 a = 1 print(type(a)) # float--浮点型 b = 1.1 print(type(b)) # str--字符型 c = 'trash' print(type(c)) # bool--布尔型(逻辑判断--True&False) d = False print(type(d)) # list--列表 e = [10,20,30] print(type(e)) # tuple--元组 f = (10,20,30) print(type(f)) # set--集合 g = {10,20,30} print(type(g)) # dict--字典 h = {'name':'sheldon','age':19} print(type(h))
a = 10 a += 1 # a = a + 1 print(a) a = 10 a = a + 1 print(a) b = 9 b -= 1 # b = b - 1 print(b) # 相似的,还有*=, /=, //=, %=, **= 等等 c=8 c /= 4 print(c) c **= 5 print(c) # 扩展 d = 10 d += 1 + 2 # 是先算1+2=3,然后是d += 3? 还是先算d += 1 再加2? print(d) e = 10 e *= 2 + 3 print(e) # 注意:从加法没法看出来,但从乘法赋值可以看出来是先算的等号右边的表达式
from math import trunc n = float(input('Digite um número:')) int = trunc(n) print('O número {} tem a parte inteira {}'.format(n, int))
print('DESCONTO') p = int(input('Qual o preço do produto?')) d = int(input('Quanto de desconto será dado?')) de = (d*p)/100 f = p-de print('O preço do produto com {}% de desconto fica por {} reais.'.format(d, f))
# apis_tb.py # Creator: Alejandro Balseiro # Last review: 22/01/2021 by Javier Olcoz import pandas as pd import numpy as np import json import requests class Apis: def checker(self, url_complete): """ @Alex Function that helps us to make the call to the server to recieve the appropiate data: Inputs: url_complete : url to check Output: r : response of the call, if the request, have succeded, it returns "True", if found an error, returns "False" """ try: r = requests.get(url=url_complete) r.raise_for_status() # Raises a HTTPError if the status is 4xx, 5xxx, or timeout except (requests.exceptions.ConnectionError, requests.exceptions.Timeout, requests.exceptions.HTTPError): return False else: return True def conection_error(self): """ @Alex Function that checks the so and return the last json given data: Output: resp_json : Json file with the information requested """ print("error in the response, proceed to open the newest copy of the file given") import os path = os.path.dirname(os.path.dirname(os.path.dirname( __file__ ))) camino = path + os.sep + "data" + os.sep + "jsonpaalexjaviyantonio.json" with open(camino, 'r+') as outfile: resp_json = json.load(outfile) return resp_json def requester (self, url_b, url_add, psw ): """ @Alex Function that helps us to make the call to the server to recieve the appropiate data: Inputs: url_b : Basic url to do the request url_add : Dictionary with the additional to the bassic url to perform the addecuate request psw : String withe the required password to get the data Output: resp_json : Json file with the information requested """ url_complete = url_b+url_add["group_id"]+psw["group_id"] token = self.checker(url_complete) if token == True: token = requests.get(url=url_complete) token = token.json() url_complete = url_b+url_add["token"]+token["token"] resp_json = self.checker(url_complete) if resp_json == True: resp_json = requests.get(url=url_complete) resp_json = resp_json.json() else: resp_json = self.conection_error() else: resp_json = self.conection_error() return resp_json
import guiatv import guiatv guiatv.opciones() numero = input('') print('elegiste la opción',numero) if numero == '1': print('¿cuantos canales deseas listar?') cantidad = input('') aenterocantidad = int(cantidadentero) guiatv.listar((cantidadentero+1)) elif numero == '2': guiatv.agregar() elif numero == '3': guiatv.buscar() else: guiatv.supererror() #THE-END
def check(a, b, c): if (a + b <= c) or (b + c <= a) or (c + a <= b): return False else: return True n = int(input("Enter number of test cases: ")) for i in range(n): a, b, r = [int(x) for x in input("Enter a, b, r: ").split()] num = int(input("Enter number of chopsticks in jar: ")) leng = list(map(int, input("Enter lengths of chopsticks in jar: ").split())) cnt = 0 for l in leng: if check(a, b, l): cnt += 1 print("\nNumber of triangles possible: ", cnt) if cnt > r: print("Winner: Natsu") else: print("Winner: Grey")
from turtle import right, left, forward, shape, exitonclick a = int(input("napis hodnotu:")) for d in range(a): for i in range(1): for j in range(2): forward(50) left(60) forward(50) left(60) forward(50) right(60) forward(50) right(60) forward(50) right(60) forward(50) right(60) forward(50) left(60) forward(50) left(60) forward(50) right(60) forward(50) right(60) forward(50) right(60) forward(50) left(60) for im in range(1): for jm in range(2): forward(50) right(60) forward(50) right(60) forward(50) right(60) forward(50) left(60) forward(50) left(60) forward(50) right(60) forward(50) right(60) forward(50) right(60) forward(50) right(60) forward(50) left(60) forward(50) left(60) forward(50) right(60) exitonclick()
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ # print(pd. __version__) print(np. __version__) print('Hello! Let\'s explore some US bikeshare data!') # Get input for city to explore while True: city = input("which city will you like to explore \n") city = city.lower() if city in ['chicago', 'washington', 'new york city']: break else: print('please enter a valid city \n') # get input for month to explore while True: month = input("Please enter month the month you desire within the first 6 months or enter 'all' \n") month = month.lower() if month in ['january', 'february', 'march', 'april', 'may', 'june', 'all']: break else: print('please enter a valid input \n') # get input for day of week to explore while True: day = input("Please enter the desired day or enter 'all' \n") day = day.lower() if day in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday','all']: break else: print('please enter a valid input \n') print('-'*40) return city, month, day def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ pd.set_option('display.max_colwidth', None) df = pd.read_csv(CITY_DATA[city]) df['Start Time'] = pd.to_datetime(df['Start Time']) df['month'] =df['Start Time'].dt.month df['day_of_week'] = df['Start Time'].dt.day_name() if month != 'all': months = ['january', 'february', 'march', 'april', 'may', 'june'] month = months.index(month) + 1 df = df[df['month'] == month] if day != 'all': df = df[df['day_of_week'] == day.title()] return df def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() common_month = df['month'].mode()[0] print("Most common month is ", common_month, " \n") common_week = df['day_of_week'].mode()[0] print("Most common day of week is ", common_week, " \n") # display for the most common start hour df['hour'] = df['Start Time'].dt.hour common_start_hour = df['hour'].mode()[0] print("Most common start hour is ", common_start_hour, " \n") print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() common_start_station = df['Start Station'].mode()[0] print("Most common used start station is ", common_start_station, " \n") common_end_station = df['End Station'].mode()[0] print("Most common used End station is ", common_end_station, " \n") df['trip'] = df['Start Station'] + " " + df['End Station'] frequent_combination = df['trip'].mode()[0] print("Most frequent combination of start station and end station trip is ", frequent_combination, " \n") print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() total_trip_duration = df['Trip Duration'].sum() print("Total travel time is ", total_trip_duration, " \n") avg_travel_time = df['Trip Duration'].mean() print("Mean travel time is ", avg_travel_time, " \n") print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() user_type_counts = df.groupby(['User Type'])['User Type'].count() print(user_type_counts, "\n") if 'Gender' in df.columns: df['Gender'].replace(np.nan, 'not available', inplace =True) print(df['Gender'].value_counts(dropna=False)) if 'Birth Year' in df.columns: print('Earliest Birth is', int(df['Birth Year'].min())) print('Most Recent Birth is', int(df['Birth Year'].max())) print('Most Common Birth is', int(df['Birth Year'].mode())) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) x = 1 while True: raw = input('\nWould you like to see some raw data? Enter yes or no.\n') if raw.lower() == 'yes': print(df[x:x+5]) x = x+5 else: break def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break if __name__ == "__main__": main()
#To check whether the string contains all 26 letters. s='Quick zephyrs blow, vexing daft Jim' temp=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] s=s.lower() flag=0 for i in temp: if i not in s: flag=1 break if flag==0: print("Pangram"); else: print('Not a Pangram');
def sum(num): if num!=0: return num+sum(num-1) else: return num num=10 print(sum(num))
# Numbers which have repeating Aliquot sequence of length 1 are called Perfect Numbers. For example 6, sum of its proper divisors is 6. # Numbers which have repeating Aliquot sequence of length 2 are called Amicable numbers. For example 220 is a Amicable Number. # Numbers which have repeating Aliquot sequence of length 3 are called sociable number. # Aliquot Sequence of a number starts with itself, # remaining terms of the sequence are sum of proper divisors of immediate previous term. from math import sqrt def getSum(n): summ = 0 for i in range(1, int(sqrt(n)) + 1): if n % i == 0: if n // i == i: summ += i else: summ += i summ += n // i return summ - n def printAliquot(n): print(n, end=" ") s = set() s.add(n) nextt = 0 while n > 0: n = getSum(n) if n in s: print("Further Repeats") break print(n, end=" ") s.add(n) if __name__ == "__main__": printAliquot(12)
#Given three positive numbers a, b and m. Compute a/b under modulo m. #The task is basically to find a number c such that (b * c) % m = a % m. import math def modinverse(b,m): temp=math.gcd(b,m); if temp!=1: return -1 else: return b**(m-2)%m def modular_division(a,b,m): a=a%m inverse=modinverse(b,m) if inverse==-1: print("Division not defined") else: print((inverse*a)%m) modular_division(8,3,5)
def root(arr,i): while i!=arr[i] : i=arr[i] return arr[i] def find(arr,u,v): if root(arr,u)==root(arr,v): return 1 else: return 0 def weight_union(arr,size,u,v): rootu=root(arr,u) rootv=root(arr,v) if(size[rootu]<size[rootv]): arr[rootu]=arr[rootv] size[rootv]+=size[rootu] else: arr[rootv]=arr[rootu] size[rootu]+=size[rootv] return arr,size arr=[0,1,2,3,4,5] size=[1,1,1,1,1,1] arr,size=weight_union(arr,size,0,1) print(arr) arr,size=weight_union(arr,size,1,2) print(arr) arr,size=weight_union(arr,size,3,2) print(arr)
def noOfdigits(num): count=0 while num: num=int(num/10) count+=1 return count num=34545 temp=num revnum=0 digits=noOfdigits(num)-1 while(temp): revnum+=(temp%10)*(10**digits) temp=int(temp/10) digits-=1 print(revnum)
class Empresa: ventas = {0, 0, 0, 0, 0, 0, 0} def __init__(self, name, id): self.name = name self.id = id self.ventas = {} def ventas_totales(self): ventasTotales = 0 for i in self.ventas: ventasTotales += int(i) return ventasTotales def __str__(self): return "Empresa: " + str(self.id) + " " + self.name + "\tVentas totales: " + str(self.ventas_totales()) def read_first_line(data): i = 0; empresas = [] while i < len(data): emp = Empresa(data[(i)], data[(i + 1)]) empresas.append(emp) i = i + 2 return empresas def read_last_lines(lineas, empresas): for i in range(1, len(lineas) - 1): linea = lineas[i].split(", ") for emp in empresas: if emp.id == linea[0]: emp.fecha_ventas = linea[1] emp.ventas = [linea[2], linea[3], linea[4], linea[5], linea[6], linea[7], linea[8]] return empresas f = open("datos.txt") lineas = f.read().split("\n") empresas = read_first_line(lineas[0].split(", ")) empresas = read_last_lines(lineas, empresas) for i in empresas: print(i)
class Pieza: pass class Tuberia(Pieza): def __init__(self, longitud): self.longitud = longitud def __str__(self): return "Tuberia " + str(self.longitud) + "mm" class Tuerca(Pieza): def __init__(self, diametro): self.diametro = diametro def __str__(self): return "Tuerca " + str(self.diametro) + "mm" class Codo(Pieza): def __init__(self, angulo): self.angulo = angulo def __str__(self): return "Codo " + str(self.angulo) + "º" class Inventario: def __init__(self): self.piezas = list() def alta(self, pieza): self.piezas += [pieza] def baja(self, indice): pass def modificacion(self): pass def __getitem__(self, item): return self.piezas[item] def __len__(self): return len(self.piezas) inventario = Inventario() inventario.alta(Codo(90)) inventario.alta(Tuerca(90)) inventario.alta(Tuberia(90)) print(len(inventario))
# -*- coding: utf-8 -*- """ Created on Sat Aug 1 17:38:24 2020 @author: stuar """ import random class Card(object): ''' Creates the class card, which contains the suit (either Spade, Heart, Club or Diamond) and a value (J,Q,K and A are represented as 11, 12, 13 and 14). ''' def __init__(self, suit, value): self.suit = suit self.value = value def get_suit(self): return self.suit def get_value(self): return self.value def set_suit(self, suit): self.suit = suit def set_value(self, value): self.value = value def compare_value(self, other_card): if self.value == other_card.value: if self.suit != other_card.suit: return True else: return False def __str__(self): if self.value == 11: return "The Jack of " + str(self.suit) + 's' elif self.value == 12: return "The Queen of " + str(self.suit) + 's' elif self.value == 13: return "The King of " + str(self.suit) + 's' elif self.value == 14: return "The Ace of " + str(self.suit) + 's' else: return "The " + str(self.value) + " of " + str(self.suit) + 's' def gen_deck(): '''Generates a standard 52 deck without jokers. Returns an ordered list of card objects''' suits = ["Diamond", "Heart", "Club", "Spade"] #13 values = [2,3,4,5,6,7,8,9,10,11,12,13,14] deck_of_cards = [] for i in range(4): for n in range(13): deck_of_cards.append(Card(suits[i],values[n])) return(deck_of_cards) def deal(deck): '''One parameter (card deck) and returns a single card chosen at random. This modifies the deck passed in. ''' card_dealt = deck.pop(random.randint(0, (len(deck)-1))) return(card_dealt) def deal_hand(num_players, deck, holdem= True): ''' takes in two arguments, the number of players and a generated deck, and returns a list of lists. Each sublist is a hand containing two cards (if holdem is true) or five cards (if holdem is false). ''' all_hands = [] for n in range(num_players): if holdem == True: hand = deal(deck), deal(deck) else: hand = deal(deck),deal(deck),deal(deck),deal(deck),deal(deck) all_hands.append(hand) return all_hands def deal_flop(deck): burn_card = deck.pop(random.randint(0, (len(deck)-1))) flop = deal(deck),deal(deck),deal(deck) return flop def deal_turn(deck): burn_card = deck.pop(random.randint(0, (len(deck)-1))) turn = deal(deck) return turn def deal_river(deck): burn_card = deck.pop(random.randint(0, (len(deck)-1))) river = deal(deck) return river def pair_toak_foak(hand): ''' Takes in a hand as argument. Returns strings pair, three of a kind, four of a kind, and high card. ''' numbers = [[],[],[],[],[],[],[],[],[],[],[],[],[]] pair = [] foak = [] toak = [] high_card_score = 2 for card in hand: numbers[(card.get_value()-2)].append(card) if card.get_value() > high_card_score: high_card_score = card.get_value() high_card = card for number in numbers: if 1 < len(number) < 3: for card in number: pair.append(card) if 2 < len(number) < 4: for card in number: toak.append(card) if 3 < len(number) < 5: for card in number: foak.append(card) if len(foak) > 0: return 'Four of a kind' elif len(toak) > 0: if len(pair) > 0: fh = toak + pair return 'Full house' else: return 'Three of a kind' elif len(pair) > 2: return 'Two pair' elif len(pair) > 0: return 'Pair' else: return 'High card' def flush(hand): ''' Takes in a hand as argument. Returns string flush if there is a flush. ''' flush = False suit = hand[0].get_suit() for card in hand: if card.get_suit() != suit: return flush return 'Flush' def straight(hand): ''' Takes in a hand as argument. Returns string straight if there is a straight. ''' straight = False values = [] for card in hand: values.append(card.get_value()) values.sort() try: for i in range(5): if values[i] + 1 != (values[i +1]): return straight except IndexError: return 'Straight' def score_hand(hand): if straight(hand) == 'Straight' and flush(hand) == 'Flush': return 'Straight flush' elif pair_toak_foak(hand) == 'Four of a Kind': return 'Four of a kind' elif pair_toak_foak(hand) == 'Full House': return 'Full house' elif flush(hand) == 'Flush': return 'Flush' elif straight(hand) == 'Straight': return 'Straight' else: return pair_toak_foak(hand) def play_a_round(num_players): deck = gen_deck() all_hands = deal_hand(num_players, deck) player_hand = all_hands[0] flop = deal_flop(deck) turn = deal_turn(deck) river = deal_river(deck) total_hand = [] total_hand.append(turn) total_hand.append(river) for card in player_hand: total_hand.append(card) for card in flop: total_hand.append(card) return(score_hand(total_hand)) def benson_poker(num_rounds): pairs = 0 twopairs = 0 trips = 0 straights = 0 flushes = 0 fullhouses=0 quads=0 straightflushes=0 high_card = 0 for i in range(num_rounds): outcome = play_a_round(4) if outcome == 'Pair': pairs += 1 elif outcome == 'Two pair': twopairs += 1 elif outcome == 'Three of a kind': trips += 1 elif outcome == 'Straight': straights += 1 elif outcome == 'Flush': flushes += 1 elif outcome == 'Full house': fullhouses += 1 elif outcome== 'Four of a kind': quads += 1 elif outcome == 'Straight flush': straightflushes += 1 else: high_card += 1 print("In " + str(num_rounds) + " hands, there were:\n -------------") print(str(high_card) + ' High Cards.') pairscent = (pairs * 100)/num_rounds print(str(pairscent) + ' %') print(str(pairs) + ' Pairs.') pairscent = (pairs * 100)/num_rounds print(str(pairscent) + ' %') print(str(twopairs)+ ' Two pairs.') pairscent = (twopairs * 100)/num_rounds print(str(pairscent) + ' %') print(str(trips)+ ' Three of a kind.') pairscent = (trips * 100)/num_rounds print(str(pairscent) + ' %') print(str(straights)+ ' Straights') pairscent = (straights * 100)/num_rounds print(str(pairscent) + ' %') print(str(flushes)+ ' Flushes') pairscent = (flushes * 100)/num_rounds print(str(pairscent) + ' %') print(str(fullhouses) + ' Full Houses') pairscent = (fullhouses * 100)/num_rounds print(str(pairscent) + ' %') print(str(quads) + ' Four of a kind') pairscent = (quads * 100)/num_rounds print(str(pairscent) + ' %') print(str(straightflushes) + ' Straight Flushes') pairscent = (straightflushes * 100)/num_rounds print(str(pairscent) + ' %') benson_poker(1000)
# understandiing cryptography problem 2.l import string alphabet = string.ascii_lowercase # ALPHABET_LIST = [alphabet[i] for i in range(len(alphabet))] def create_alphabet_dict(alphabet_list=ALPHABET_LIST): # alphabetを数値かする output_dict = {} for i in range(len(alphabet_list)): output_dict[alphabet_list[i]] = i return output_dict ALPHABET_DICT = create_alphabet_dict() def encryptt(plain_letter,key_alphabet,alphabet_dict=ALPHABET_DICT): num_letter = alphabet_dict[plain_letter] num_key = alphabet_dict[key_alphabet] remainder = (num_letter+num_key) % 26 return ALPHABET_LIST[remainder] def decrypt(plain_letter, key_alphabet, alphabet_dict=ALPHABET_DICT): # this can also be used for decrypt num_letter = alphabet_dict[plain_letter] num_key = alphabet_dict[key_alphabet] remainder = (num_letter-num_key) % 26 return ALPHABET_LIST[remainder] if __name__ == "__main__": plain = "bsaspp" key = "rsidpy" # print(encrypt("a","b")) for i in range(len(plain)): tmp = decrypt(plain[i], key[i]) print(tmp)
a=int(input('Enter the first value')) print(a) b=int(input('Enter the second value')) print(b) temp=a a=b b=temp print("After swapping Your first value is",a,"and Your second value is",b)
# example of program that calculates the total number of times each word has been tweeted. import numpy as np # read text file file = open('tweet_input/tweets.txt','r') #print(file) allWords = np.empty(shape=(0,0)) #print(allWords) # write words in a text file to single array for line in file: # read words in each line words = line.split(); # append words from each line into one array allWords = np.append(allWords, words); file.close() # find unique words in a text file, unique also sorts so need to sort uniqueWords = np.unique(allWords) #print('Number of words in a text file',len(allWords)) #print('Number of unique words in a text file',len(uniqueWords)) # find the total number of number of times each words has been tweeted # create an array with length of uniquewords to save number of times each word has been tweeted wordCount = np.zeros((len(uniqueWords),), dtype= np.int) for x in range(0, len(uniqueWords)): wordCount[x] = list(allWords).count(uniqueWords[x]) # stack unique words and number of times they were tweeted wordsAndCount = np.column_stack([uniqueWords, wordCount]) # save data into a text file np.savetxt('tweet_output/ft1.txt', wordsAndCount, fmt='%+s', delimiter='\t')
# non-web GUI's (YAY!) # remember, with WSL you need to launch xming import tkinter # GUI development mainWindow = tkinter.Tk() mainWindow.title("Hello World") # screen resolution # offsets (Where window appears on screen) represented by +/- mainWindow.geometry('640x480+8+400') # GUI design label = tkinter.Label(mainWindow, text="Hello World") # side = orientation on the window label.pack(side='top') # frames can be used as containers for geometry objects (widget) leftFrame = tkinter.Frame(mainWindow) leftFrame.pack(side='left', anchor='n', fill=tkinter.Y, expand=False) canvas = tkinter.Canvas(leftFrame, relief="raised", borderwidth=1) # fill = the area that the widget will cover # tkinter.Y and tkinter.X are both fill options # fill is based on side (orientation); if orientation is left/right, # the expand option must be used for X, and if orientation is top/bottom, # the expand option must be used for Y # canvas.pack(side='left', fill=tkinter.X, expand=True) # widgets will share the same side in the order that they are packed # to adjust this, you can pass the anchor option to .pack(); # Note that this position IS STILL based on the order with pack canvas.pack(side='left', anchor='n') rightFrame = tkinter.Frame(mainWindow) rightFrame.pack(side='right', anchor='n', expand='true') button1 = tkinter.Button(rightFrame, text="button1") button2 = tkinter.Button(rightFrame, text="button2") button3 = tkinter.Button(rightFrame, text="button3") button1.pack(side='top') button2.pack(side='top') button3.pack(side='top') # passes control from console to tk (runs the program in the GUI) mainWindow.mainloop()
# Time Basics # import time # # prints start of epoch as tuple # print(time.gmtime(0)) # # produces current locatime as a tuple # time_here = time.localtime() # print(time_here) # # two ways of outputting the data (via tuple index, or through built in # # methods) # print("Year:", time_here[0], time_here.tm_year) # print("Month:", time_here[1], time_here.tm_mon) # print("Day:", time_here[2], time_here.tm_mday) # Time manipulation import time from time import perf_counter as my_timer import random input("Press enter to start ") # records time between start and stop wait_time = random.randint(1, 6) time.sleep(wait_time) start_time = my_timer() input("Press enter to stop ") end_time = my_timer() # prints and formats time data from start/end print("Started at " + time.strftime("%X", time.localtime(start_time))) print("Ended at " + time.strftime("%X", time.localtime(end_time))) # prints time to hit button print("Your reaction time was {} seconds".format(end_time - start_time))
val=int(input("enter a value") if(val%400==0): print(val,"is leap year") else print(val,"is not a leap year")
"""Pixelflut is a TCP server screen inspired by the pixelflut project of the CCC Göttingen (https://cccgoe.de/wiki/Pixelflut). It uses the core python libraries and will not rely on other libraries. There is a server and a client component in this package. The server listens for packets with commands as content. The following commands are recognized: SIZE - will respond with the actual size of the screen in the format WIDTHxHEIGHT PX x y on_off - will draw (on_off=1) or clear (on_off=0) the pixel at (x|y). """ import tkinter import socket import threading class Pixelflut: """A canvas that shows the screen which can be used by clients to print or clear pixels on. """ def __init__(self, ip="127.0.0.1", port=1234): fenster = tkinter.Tk() # TODO add event to kill server thread when closing window self.ip = ip self.port = port self.coord2rectangle = dict() self.canvas = tkinter.Canvas(fenster, background="white") self.canvas.pack(fill=tkinter.BOTH, expand=1) self.__init_canvas() # start pixel server in a separate thread th = threading.Thread(target=self.__run_pixel_server) th.start() fenster.mainloop() def __run_pixel_server(self): server = PixelServer(self, self.ip, self.port) server.start() def get_canvas_size(self): """Return size of the current canvas in form of (width, height).""" return (self.canvas.winfo_width(), self.canvas.winfo_height()) def draw_pixel(self, x, y): """Draw a black pixel at (x|y).""" # TODO Support for colors if (x, y) not in self.coord2rectangle: r = self.canvas.create_rectangle(x, y, x+1, y+1, fill="black") self.coord2rectangle[(x, y)] = r def clear_pixel(self, x, y): """Remove the pixel at (x|y) from the screen.""" if (x, y) in self.coord2rectangle: self.canvas.delete(self.coord2rectangle[(x, y)]) del(self.coord2rectangle[(x, y)]) def __init_canvas(self): t = "Pixelflutserver" t += "@" + self.ip + ":" + str(self.port) self.canvas.create_text(10, 0, anchor="nw", text=t) class PixelServer: def __init__(self, pixelflut, ip="127.0.0.1", port=1234): self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.bind((ip, port)) self.client_sock = self.server.listen(100) self.pixelflut = pixelflut def start(self): """Start server. This method does not return.""" while True: sock, _address = self.server.accept() # TODO only call handle if window is visible - call for window state # th = threading.Thread(target=self.__handle, args=(sock,)) # th.start() self.__handle(sock) def __handle(self, client_sock): bytes_request = client_sock.recv(1024) command = str(bytes_request, "utf-8") print("Command:", command) if command.lower().startswith("px"): try: _px, x, y, on_off = command.split(' ') if on_off == "1": self.pixelflut.draw_pixel(int(x), int(y)) elif on_off == "0": self.pixelflut.clear_pixel(int(x), int(y)) except Exception as e: print("Command Error", command, e) elif command.lower() == "size": w, h = self.pixelflut.get_canvas_size() client_sock.send(bytes(str(w) + "x" + str(h), "utf-8")) client_sock.close() class PixelClient: def __init__(self, ip="127.0.0.1", port=1234): self.ip = ip self.port = port def px(self, x, y, on_off): """Send the PX-Command to the server. This will draw or clear the pixel at (x|y).""" cmd = "PX {x} {y} {on_off}".format(x=x, y=y, on_off=on_off) cmd = bytes(cmd, "utf-8") client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((self.ip, self.port)) client.send(cmd) client.close() def __run_client(ip, port): print("Connecting to {ip}:{po}.".format(ip=ip, po=port)) user_input = "" cl = PixelClient(ip=ip, port=port) while user_input != "n": x = int(input("x=")) y = int(input("y=")) on_off = int(input("on_off (1,0)=")) cl.px(x, y, on_off) user_input = input("Again? (y/n)") def __main(): d = """ Pixelflut - A Server, that listens for TCP packets that allow for drawing on the screen. Valid content of the packets is \"PX x y on_off\" where x and y are coordinates on the screen and on_off is either 1 or 0. A pixel will be drawn there if on_off is 1 - otherwise it will be cleared. If the packet contains \"SIZE\" you will receive the size of the screen in the format WIDTHxHEIGHT. There is a simple client that can be used as well. """ parser = argparse.ArgumentParser(description=d) parser.add_argument("-s", "--server", action="store_const", const=True, help="Start server.") parser.add_argument("-c", "--client", action="store_const", const=True, help="Start client.") parser.add_argument("-i", "--ip", help="An IP address or hostname the client or server " "should be bound to.", dest="ip", default="127.0.0.1") parser.add_argument("-p", "--port", help="The port number to listen or to connect to.", type=int, dest="port", default=1234) args = parser.parse_args() if args.client: __run_client(args.ip, args.port) elif args.server: Pixelflut(ip=args.ip, port=args.port) if __name__ == "__main__": import argparse __main()
import pprint from collections import defaultdict from google.cloud import translate def statement_request(): entry = input("Enter a phrase for us to deconstruct:\n").lower() return entry def deconstruct(entry): """ Function to create a deconstructed list of the statement letters :param entry: The string input from user :return: sorted list of letters used in statement """ chart = defaultdict(list) for letter in entry: if letter.isalpha(): chart[letter].append(letter) return sorted(chart.items()) if __name__ == '__main__': translate_client = translate.Client() text = u"Hello World!" target = "ru" translation = translate_client.translate( text, target_language=target) print(u'Text: {}'.format(text)) print(u'Translation: {}'.format(translation['translatedText'])) # print("Hello, welcome to our statement analyzer. Input a statement and we will break it down into how many letters" # "it has.") # print("Enter 'stop' to quit.") # # # Loop to keep asking for more statements # while True: # statement = statement_request() # if statement == "stop": # print("Thank you for using our services. Have a nice day.") # break # else: # pp = pprint.PrettyPrinter(width=110) # pp.pprint(deconstruct(statement))
#The python program String to MD5 hash method #Ajith R B import hashlib; string=input ("Enter the String to MD5 hash:") result = hashlib.md5(string.encode()) print("The hexadecimal equivalent of hash is : ", result.hexdigest())
a=int(input("enter the 1st num")) b=int(input("enter the 2nd num")) c=input("enter operation") if(c=="add"): print(a,"+",b,"=",a+b) elif(c=="sub"): print(a,"-",b,"=",a-b) elif(c=="mul"): print(a,"*",b,"=",a*b) elif(c=="div"): print(a,"/",b,"=",a/b) else: print("enter any operators like add,sub,mul,div")
def checkio(text): text=text.lower() y=0 for i in text: if ord(i)>=97 and ord(i)<=122: if text.count(i)>y: y=text.count(i) z=i if text.count(i)==y: if ord(z)>ord(i): z=i return z print checkio("aAaAaFfFfFfEeEeEe")
from abc import abstractmethod, ABC class Beverage(ABC): description: str = "Unknown beverage" def get_description(self): return self.description @abstractmethod def cost(self): pass
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right numbers = [] class Solution: def recoverTree(self, root: TreeNode) -> None: """ Do not return anything, modify root in-place instead. """ def traverse(root): global numbers if root.left: traverse(root.left) numbers.append(root.val) if root.right: traverse(root.right) global numbers numbers = [] traverse(root) x = [] numbers2 = sorted(numbers) for i in range(len(numbers2)): if numbers2[i]!=numbers[i]: x+=[numbers[i]] def traverse1(root, x): if root.left: traverse1(root.left, x) if root.val==x[0]: root.val = x[1] elif root.val == x[1]: root.val = x[0] if root.right: traverse1(root.right, x) traverse1(root, x) return root
import sqlite3 def connect(): conn = sqlite3.connect("bookstore.db") cur = conn.cursor() cur.execute( "CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, title text, author text, year integer, isbn integer)") conn.commit() conn.close() connect() def insert(title, author, year, isbn): conn = sqlite3.connect("bookstore.db") cur = conn.cursor() cur.execute("INSERT INTO books VALUES (NULL,?,?,?,?)", (title, author, year, isbn)) conn.commit() conn.close() def delete(id): conn = sqlite3.connect("bookstore.db") cur = conn.cursor() cur.execute("DELETE FROM books WHERE id=?", (id,)) conn.commit() conn.close() def view(): conn = sqlite3.connect("bookstore.db") cur = conn.cursor() cur.execute("SELECT * FROM books") rows = cur.fetchall() # cursor.fetchall() fetches all the rows of a query result. It returns all the rows as a # list of tuples. An empty list is returned if there is no record to fetch. conn.close() return rows def search(title="", author="", year="", isbn=""): conn = sqlite3.connect("bookstore.db") cur = conn.cursor() cur.execute("SELECT * FROM books WHERE title=? OR author=? OR year=? OR isbn=? ", (title, author, year, isbn)) rows = cur.fetchall() # cursor.fetchall() fetches all the rows of a query result. It returns all the rows as a # list of tuples. An empty list is returned if there is no record to fetch. conn.close() return rows def update(id, title, author, year, isbn): conn = sqlite3.connect("bookstore.db") cur = conn.cursor() cur.execute("UPDATE books SET title=?, author=?, year=?, isbn=? WHERE id=?", (title, author, year, isbn, id)) conn.commit() conn.close()
# https://leetcode.com/problems/power-of-three def isPowerOfThree(n): """ :type n: int :rtype: bool """ if n < 1: return False while n % 3 == 0: n /= 3 return n == 1
# -*- coding: utf-8 -*- """ Created on Wed Apr 12 15:32:09 2017 @author: Artem Los """ nums = {} # REMOVE LATER def popWithSquares(a, b, p): for x in range(p): #y2 =( x*x*x+a*x+b )% p if x**2%p in nums: nums[x**2 % p].append(x) else: nums[x**2 % p] = [x]
class Assignments: def __init__(self, name, max_score, grade): self.name = name self.max_score = max_score self.grade = grade def Assignment(self, name, max_score): self.name = name self.max_score = max_score self.grade = None def assign_grade(self, grade): if self.max_score < grade: self.grade = None else: self.grade = grade class students(Assignments): def __init__ (self, id, first_name, last_name, assignments): self.id = id self.first_name = first_name self.last_name = last_name self.assignments = assignments def __Student__ (self, id, first_name, last_name): self.id = id self.first_name = first_name self.last_name = last_name assignments = [] print("New student created") def get_full_name(self): return(str(self.id) + ': ' + str(self.first_name) + ' ' + str(self.last_name)) def get_assignments(self): return(self.assignments) def get_assignment(self, assignment_name): if any(assignment_name in s for s, j in self.assignments): return_grade = [j for i,j in self.assignments if i == assignment_name] return(('Assignment = ' + assignment_name, 'Grade = '+ str(return_grade[0]))) else: None def get_average(self): numofAssignment = len(self.assignments) totalPoints = sum(j for i, j in self.assignments) average = totalPoints / numofAssignment return(average) def submit_assignment(self, Assignment): self.assignments.append((Assignment.name, Assignment.grade)) def remove_assignment(self, assignment_name): self.assignments = [i for i in self.assignments if i[0] != assignment_name]
def is_isogram(string: str) -> bool: """Checks if a given string is an Isogram (ie. no repeated chars) Parameters: string the given string Retunrs: ======== True, if string is an isogram False, otherwise """ # Controls whether a char has already appeared or not char_has_appeared = set() # Cleans the input cleaned = string cleaned = cleaned.replace(" ", "") cleaned = cleaned.replace("-", "") cleaned = cleaned.lower() for char in cleaned: # We have found a repeated lchar if char in char_has_appeared: return False # We mark the char as already visited char_has_appeared.add(char) return True
### Chapter 6: Python 101 :Jimmy Moore ### # Ex. 6.1 fruit = 'banana' index = len(fruit)-1 while index >=0: letter = fruit[index] print letter, index = index-1 # Ex. 6.2 # fruit[:] is a slice of the full string. full slice? # Ex. 6.3 def counter(string,index): count =0 for letter in string: if letter == index: count = count+1 print count counter('banana', 'a') # Ex. 6.4 word = 'banana' print word.count('a') # Ex. 6.5 str = 'X-DSPAM-Confidence: 0.8475' extract = str[str.find(':')+1:] print float(extract) # Ex. 6.6 string = 'hello, world!' print string.capitalize() #returns Hello, world! print string.find('lo') #returns 3 print string.isalnum() #returns false print string.isalpha() #returns false (! is not alphanumeric) print string.replace('hello', 'goodbye') #returns goodbye, world! print string.strip('h!') #returns ello, world print string.title() #returns Hello, World!
produto1 = int(input('digite o preço de um produto: ')) produto2 = int(input('digite o preço de um produto: ')) produto3 = int(input('digite o preço de um produto: ')) menor = min(produto1, produto2, produto3) print('compre o de R$' + str(menor) + ' por que é mais barato ')
import math h = input("Podaj wysokosc do uderzenia(m): ") a = 9.8 l = input("Podaj odleglosc do upadku(m): ") tx = math.sqrt(2*l/a) vz = math.sqrt(l*a/2) if vz**2 - 2*a*h < 0 : print "Wprowadzono bledne dane!" else : vo = math.sqrt(vz**2 - 2*a*h); print "Predkosc poczatkowa:",\ vo,\ "m/s"
import random want_more = 'хочу' while want_more == 'хочу': answer = random.randint(1, 10) guess = -1 while answer != guess: guess = input('Введите число: ') try: guess = int(guess) except ValueError: print('Где у вас башка? Я вам сказала введите ЧИСЛО! Вы слышите, ЧИСЛО!!!!!!!') continue if answer < guess: print('Загаданое число меньше') elif answer > guess: print('Загаданое число больше') else: print('Бинго!!!!') want_more = input('Хотите сыграть ещё? "хочу" или "не хочу": ') print() print('До свиданья(не в том смысле!), приходите ещё!') print()
#!/usr/bin/python def split_numal(val): """Split, for example, '1a' into (1, 'a') >>> split_numal("11a") (11, 'a') >>> split_numal("99") (99, '') >>> split_numal("a") (0, 'a') >>> split_numal("") (0, '') """ if not val: return 0, '' for i in range(len(val)): if not val[i].isdigit(): return int(val[0:i] or '0'), val[i:] return int(val), '' def numal_sort(a, b): """Sort a list numeric-alphabetically >>> vals = "1a 1 10 10a 10b 11 2 2a z".split(" "); \\ ... vals.sort(numal_sort); \\ ... " ".join(vals) 'z 1 1a 2 2a 10 10a 10b 11' """ anum, astr = split_numal(a) bnum, bstr = split_numal(b) cmpnum = cmp(anum, bnum) if(cmpnum == 0): return cmp(astr, bstr) return cmpnum def calc_alignment(string): l = 2 + len(string.strip()) // 6 if l <= 4: return 4 if l <= 7: return 7 if l < 10: return 10 return l if __name__ == "__main__": import doctest doctest.testmod()
# DDP LAB-4 # Nama: Evry Nazyli Ciptanto # NIM: 0110220045 # SOAL 1 - Mencetak nama # Tuliskan program untuk Soal 1 di bawah ini print("SOAL 1 - Mencetak nama") nama = input("Masukkan nama: ") # mendapatkan input pengguna i = 0 # set awalan variabel i ke 0 while i < len(nama): # melakukan perulangan sebanyak panjang string i +=1 # Agar dimulai indeks ke 1 print(nama[0:i]) # tampilkan teks sesuai index awal 0 dan index akhir sesuai nilai i # SOAL 2 - Validasi teks # Tuliskan program untuk Soal 2 di bawah ini print("\nSOAL 2 - Validasi teks") isTeks = True # set awalan variabel ke true # melakukan perulangan selama kondisi benar while(isTeks): # mendapatkan input pengguna b = input("Masukkan sebuah teks: "); # kondisi Panjang teks minimal 8 if(len(b)<8): print("Teks",b,"tidak valid karena panjang teks kurang dari 8") # kondisi teks mengandung frasa nf elif("nf" not in b.lower()): print("Teks",b,"tidak valid karena tidak mengandung frase NF") # kondisi teks terakhir yyy elif(not b.lower().endswith('yyy')): print("Teks",b,"tidak valid karena tidak diakhiri dengan 'YYY' atau 'yyy'") # kondisi teks mengandung angka -> catatan ada di bawah elif(b.isalpha()): print("Teks",b,"tidak valid karena tidak mengandung angka") # jika teks sudah tervalidasi, hentikan perulangan dengan mengatur variable isTeks ke false else: isTeks=False print() print("Teks valid. Program berhenti.") # b.isalpha() -> Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. # https://docs.python.org/2/library/stdtypes.html#str.isalpha # isdigit() -> Return true if all characters in the string are digits and there is at least one character, false otherwise. # kata ="asfasfasfasf@#asnfyyy" # print(any(char.isdigit() for char in kata))
#! /usr/local/bin/python # -*- coding: utf-8 -*- # 关于字符和字符串的用法几乎都在这里了 print "Hello World!" print 'Hello Again' print "I'd much rather you 'not', or \"not\"" print 'I "said" do not touch this, notice the word \'said\'' print "They are John", "Jack", "Philip" print "What is 3 + 2?", 3 + 2 print "This is first line.", print "This should be second line, but the end of upper line there is a comma, so" print "." * 20 # what did this do? my_name = 'Zed A. Shaw' my_height = '6\'2' my_weight = 180 # lbs print "He's", my_height, "inches tall and ", my_weight, "pounds." print "He's name is %s" % my_name print "He's %s inches tall and %d pounds." % (my_height, my_weight) str1 = "He's name is %s" str2 = "He's %s inches tall and %d pounds." print (str1 + str2) % (my_name, my_height, my_weight) print str1 % my_name + "\n" + str2 % (my_height, my_weight) print "." * 20 # gap line formatter = "%r %r" print formatter % (1,2) print formatter % ("one", "two") print formatter % ( "I got this,", "I mean it." ) print "." * 20 # gap line print """ There's something going on here. With the three double-quotes. """
# We are going to create a program where the user is able to enter a magic number however if they pick the number then they win def magic_number(): user_value = input("Enter your magic number beteen 0 - 10: ") if user_value < "10": print ("this is your magic number {} ".format(int(user_value))) elif user_value == "10": print("try again") else: if user_value >"0": print("try again") magic_number() magic_number
# draw regular polygons with the sparki # # written by Jeremy Eglen # Created: September 13, 2012 (originally for the Scribbler 2 / Fluke) # Last Modified: July 19, 2016 from __future__ import division,print_function from sparki_learning import * def getInteriorAngle(numSides): """ Calculates the interior angle of an equilateral polygon argument: numSides -- integer number of sides returns: float -- number of degrees in each interior angle """ numSides = int(numSides) # ensure that numSides is an integer return ( (numSides - 2.0) * 180.0 / numSides ) def getExteriorAngle(numSides): """ Calculates the exterior angle of an equilateral polygon argument: numSides -- integer number of sides returns: float -- number of degrees in each exterior angle """ numSides = int(numSides) # ensure that numSides is an integer return ( 180 - getInteriorAngle(numSides) ) def drawFigure(numSides, sideLength=1): """ Draws an equilateral polygon of numSides arguments: numSides -- integer number of sides sideLength -- float number of seconds to spend drawing each side (defaults to 1) returns: nothing """ angle = getExteriorAngle(numSides) for x in range(0, numSides): forward(1, sideLength) turnBy(angle) def drawFigurecm(numSides, sideLength=10): """ Draws an equilateral polygon of numSides arguments: numSides -- integer number of sides sideLength -- float length of side in cm returns: nothing """ angle = getExteriorAngle(numSides) for x in range(0, numSides): moveForwardcm(sideLength) turnBy(angle) def main(): myCom = None while not myCom: myCom = ask("What COM port is the Sparki on? ") init(myCom) numSides = int( ask("How many sides does the figure have? ") ) sideLength = float( ask("How long should I make each side (in cm)? ") ) while numSides > 2 and sideLength > 0: print("I am going to draw a figure with " + str(numSides) + " sides") print("If you'd like to draw, please insert a pen or marker") ask("Press okay once you have placed a pen or marker in me") drawFigurecm(numSides, sideLength) print("Please remove the marker") ask("Press okay once you have removed the marker from me") # move a little so that figures don't overlap turnBy( -90 ) forward( 1, 2 ) turnBy( 90 ) numSides = int( ask("How many sides does the figure have? (<=2 to quit) ") ) sideLength = float( ask("How long should I make each side? (<= 0 to quit) ") ) if __name__ == "__main__": main()
"""A class representing a car, with a dependency on an engine""" class Car: """A car that can be turned off and can be inspected""" def __init__(self, engine): self.engine = engine def is_on(self): return self.engine.on def turn_off(self): return self.engine.turn_off()
from Book import Book from BookStore import BookStore case =0 test_case = int(input()) ## 테스트케이스를 받는다. while case<test_case: ## 테스크케이스만큼 반복한다 book = input() ##책의 수와 서점 수를 입력받는다 book_number = int(book[0]) book_store_number = int(book[2]) Book_Store = [0]*book_store_number ## 서점 수만큼의 배열을 만든다 for i in range(0,book_store_number): ## 만든 배열에 서점 클래스(객체)를 넣어준다 Book_Store[i] = BookStore() i = 0 ##반복변수 while i<book_number: # 책 수만큼 반복 in_put = input() ## 책 가격과 포인트 입력 in_put= in_put.strip() ## 양끝 공백제거 in_put=in_put.split(" ") ## 문자열 사이에 공백제거 for j in range(0, book_store_number*2, 2): ##책의 가격과 포인트를 각각 서점에 넣어줄 for문 price = int(in_put[j]) ## price에는 책의 가격 j는 0,2,4 가격이 0,2,4줄에 있기때 point = int(in_put[j+1]) ## point에는 책의 포인트가 들어간다 j+1는 1,3,5 포인트가 1,3,5줄에 있기때 price_point = Book(price, point) ## 위에 break가 발동안됬을시 가격과 포인트로 Book 객체를 만든다 Book_Store[int(j/2)].add(price_point) ## while문 위에 만든 서점 배열에 차곡차곡 책을 더해 넣는다 i= i +1 ## 반복변수 +1 pay = Book_Store[0].min_price() ## pay 변수에 첫번쨰 서점의 가장 싼 가격 넣기 for i in range(1, book_store_number): ## 나머지 서점가격 게산을 위한 for문 if pay>Book_Store[i].min_price(): ## 만약 pay보다 다른 서점의 값이 더 싸다면 pay에 그 값을 넣어줌 pay = Book_Store[i].min_price() print(pay) ## 가격 출력
__author__ = 'yihanjiang' import numpy import scipy.optimize as opt def sigmoid(X): return 1 / (1 + numpy.exp(- X)) def cost(theta, X, y): p_1 = sigmoid(numpy.dot(X, theta)) # predicted probability of label 1 log_l = (-y)*numpy.log(p_1) - (1-y)*numpy.log(1-p_1) # log-likelihood vector return log_l.mean() def grad(theta, X, y): p_1 = sigmoid(numpy.dot(X, theta)) error = p_1 - y # difference between label and prediction grad = numpy.dot(error, X_1) / y.size # gradient vector return grad # prefix an extra column of ones to the feature matrix (for intercept term) y = [1 for _ in xrange(100)] X = y theta = 0.1* numpy.random.randn(3) X_1 = numpy.append( numpy.ones((X.shape[0], 1)), X, axis=1) theta_1 = opt.fmin_bfgs(cost, theta, fprime=grad, args=(X_1, y))
from datetime import timedelta from block_core.blocked import Blocked class DataCache: """ This class represents a time-limited cache of blocked traffic data. By default, it stores the last 10 seconds of data. This cache is approximate, in that each time new data is added, all data older than 10 seconds is removed. When data is added, if the timestamp equals the previous timestamp, 1 ms is added to ensure monotone increasing values. Users can obtain all data since a stated timestamp, which will return all available data strictly *after* the given timestamp. """ def __init__(self, cache_length_in_seconds=10): self.cache = [] self.cache_length_in_seconds = cache_length_in_seconds def get_all_since(self, timestamp): """ Gets all blocked instances where the timestamp is strictly greater than the timestamp parameter :param timestamp: timestamp of the last data recieved (to ms accuracy) :return: all blocked instances with timestamp strictly greater than the timestamp parameter """ return [item for item in self.cache if item.timestamp > timestamp] def add(self, blocked): """ Add the instance to the cache :param blocked: :return: None """ if len(self.cache) > 0 and blocked.timestamp <= self.cache[-1].timestamp: blocked = Blocked(self.cache[-1].timestamp + timedelta(microseconds=1), blocked.ip, blocked.protocol) self.cache.append(blocked) cutoff = blocked.timestamp - timedelta(seconds=self.cache_length_in_seconds) while self.cache[0].timestamp <= cutoff: del self.cache[0]
import string def format(text, limit, justify): separator = ' ' slice_start = 0 formatted_text = str() #substitui os caracteres que quebra de linha para que o algoritmo possa identificá-los como palavras separadas text_without_line_break = text.replace('\n', ' \n ') #separa o texto inserido usando espaço como separador das palavras words = text_without_line_break.split(separator) #percorre as itens do array de palavras do texto inserido para poder cortá-lo em partes de tamanho menor que o limite inserido for x in range(1,len(words)): line = '' #se o texto possui palavras com quantidade de caracteres maior que o limite inserido, é acionado uma exceção if len(words[x]) > limit: raise ValueError('The text has words bigger than the limit!') #se o item selecionado é uma quebra de linha, junta as palavras do intervalo percorrido até a quebra e gera a linha elif words[x] =='\n': line = LineFormatter(words[slice_start:x], limit, justify, separator) + '\n' slice_start = x+1 #se o intervalo percorrido possui tamanho maior que o limite, junta as palavras do intervalo e gera a linha elif len(separator.join(words[slice_start:x+1])) > limit: line = LineFormatter(words[slice_start:x], limit, justify, separator) + '\n' slice_start = x #se o item percorrido é a última palavra do array, gera a linha do intervalo percorrido elif x == len(words) -1: line = LineFormatter(words[slice_start:], limit, justify, separator) #verifica se a linha gerada está dentro dos limites definidos para texto normal (tamanho menor que limite) ou justificado (tamanho igual ao limite) if line != '' and line != '\n': if justify == True and x < len(words) -1: assert len(line) == limit + 1 else: assert len(line) <= limit + 1 #concatena a linha gerada no resultado final formatted_text += line #retorna a string formatada return formatted_text #Função para justificar linhas #Padrão: percorre as palavras da esquerda para a direita e insere um espaço a cada duas palavras. Depois o inverso pela outra direção. #Exemplos: (caractere '_' representa o espaço adicionado) #|and the earth. Now the earth was | #|and _the earth. Now the earth was | #|and the earth._ Now the earth was | #|and the earth. Now the_ earth was | #|and the earth. Now the earth _was | #|and the earth. Now _the earth was | #|and the _earth. Now the earth was | #|and_ the earth. Now the earth was | #|and the earth._ Now the earth was| #|and the earth. Now the earth was| #|formless and empty darkness was over | #|formless_ and empty darkness was over | #|formless and empty_ darkness was over | #|formless and empty darkness was_ over | #|formless and empty darkness _was over| #|formless and empty darkness was over| def LineFormatter(words, limit, justify, separator): word_count = len(words) - 1 line = '' #percorre o array de palavras para acrescentar espaços para justificar a linha if justify == True and word_count > 0: index = 0 increment = 2 while limit > len(separator.join(words)): #sentido: esquerda para direita if increment == 2: if index < word_count: words[index] = words[index] + separator index += increment else: #chegou ao fim da linha increment = -2 if index > word_count: index = word_count -1 #sentido: direita para esquerda else: if index > 0: words[index] = separator + words[index] index += increment else: #chegou ao início da linha increment = 2 if index < 0: index = 1 return separator.join(words)
""" Simple text based progress indicator """ from __future__ import print_function class TextProgress: def track(self, name, at, end, points): print("Fetching track {:s} [{:d}/{:d}] with {:d} points".format(name, at, end, points)) def point(self, at, end): if at % 100 == 0: print("{:.0f}%".format(100.*at/end))
''' Problem:Remove Nth Node From End of List Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: 1.Given n will always be valid. 2.Try to do this in one pass. ''' # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ if head is None or head.next is None: return None pre = dummy = ListNode(0) pre.next = head p = head q = head i = 0 for i in range(n-1): q = q.next while q.next: pre = p p = p.next q = q.next pre.next = p.next return dummy.next ''' Test Case: ''' if __name__ == '__main__':
''' Problem:Single Number II Given an array of integers, every element appears three times except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? ''' class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ arr = sorted(nums) length = len(nums) result = [] i = 0 if length==1: return nums[0] while i<length-1: if arr[i]==arr[i+1]: i+=3 else: result.append(arr[i]) break if i==length-1: result.append(arr[i]) return result ''' Test Case: ''' if __name__ == '__main__': s = Solution() array = [2,2,3,2] r = s.singleNumber(array) print r
""" Þú átt að útfæra clasann DiceThrower í honum á að vera Constructor sem skilgreinir hversu marga tenginga notandinn hefur, breytu sem kallar í Dice classan throw fall sem kastar öllum teningunum í lista rethow fall kastar völdum tenginum aftur Einnig áttu að búa til 2 föll Main_menu sem býr prentar út upphafið á leiknum og tekur inn input frá notenda hvað hann vill gera Print_sheet sem prentar út stigatöflu notenda Dæmi: 1: New game 2: Quit Enter your choice(1/2)please: 1 [4, 5, 4, 2, 2] Do you want to Rethrow? (Y/N): y Enter the dices you want to rethrow (0 - 4) space between please: 1 [4, 3, 4, 2, 2] Do you want to Rethrow? (Y/N): y Enter the dices you want to rethrow (0 - 4) space between please: 1 [4, 1, 4, 2, 2] 0: Small Row 0 1: Big Row 0 2: Full House 0 3: Chance 0 4: Yatzy 0 Enter your choice(0 - 4)please: 4 0: Small Row 0 1: Big Row 0 2: Full House 0 3: Chance 0 4: Yatzy 13 [1, 4, 3, 5, 5] Do you want to Rethrow? (Y/N): y Enter the dices you want to rethrow (0 - 4) space between please: 0 1 2 [5, 1, 3, 5, 5] Do you want to Rethrow? (Y/N): y Enter the dices you want to rethrow (0 - 4) space between please: 0 1 [6, 3, 3, 5, 5] 0: Small Row 0 1: Big Row 0 2: Full House 0 3: Chance 0 4: Yatzy 13 Enter your choice(0 - 4)please: 0 0: Small Row 22 1: Big Row 0 2: Full House 0 3: Chance 0 4: Yatzy 13 [1, 4, 4, 5, 6] Do you want to Rethrow? (Y/N): n 0: Small Row 22 1: Big Row 0 2: Full House 0 3: Chance 0 4: Yatzy 13 Enter your choice(0 - 4)please: 2 0: Small Row 22 1: Big Row 0 2: Full House 20 3: Chance 0 4: Yatzy 13 [2, 3, 3, 4, 6] Do you want to Rethrow? (Y/N): n 0: Small Row 22 1: Big Row 0 2: Full House 20 3: Chance 0 4: Yatzy 13 Enter your choice(0 - 4)please: 2 0: Small Row 22 1: Big Row 0 2: Full House 18 3: Chance 0 4: Yatzy 13 [4, 1, 2, 3, 4] Do you want to Rethrow? (Y/N): n 0: Small Row 22 1: Big Row 0 2: Full House 18 3: Chance 0 4: Yatzy 13 Enter your choice(0 - 4)please: 2 0: Small Row 22 1: Big Row 0 2: Full House 14 3: Chance 0 4: Yatzy 13 Final Score 49 1: New game 2: Quit Enter your choice(1/2)please: 2 Process finished with exit code 0 """ import random class Dice: def __init__(self): self.number = 0 def throw(self): self.number = random.randint(1, 6) return self.number class DiceThrower: def __init__(self, how_many=5): self.dice_list = [-1 for i in range(self.number_of_dice)] def throw(self): def rethrow(self, rethrow_list=[]): def main_menu(): def print_sheet(yatzy_sheet): def dice_menu(dice_thrower): still_throwing = True number_of_throws = 0 while still_throwing: user_dice = dice_thrower.throw() number_of_throws += 1 rethrowing_allowed = True print(user_dice) while rethrowing_allowed: rethrow = input('Do you want to Rethrow? (Y/N): ').upper() if rethrow == 'Y': s = input("Enter the dices you want to rethrow (0 - 4) space between please: ") dice = s.split() rethrow_dice = [eval(x) for x in dice] user_dice = dice_thrower.rethrow(rethrow_dice) number_of_throws += 1 print(user_dice) else: rethrowing_allowed = False if number_of_throws == 3: rethrowing_allowed = False still_throwing = False return user_dice def sheet_menu(dice, yatzy_sheet): print_sheet(yatzy_sheet) user_input = int(input('Enter your choice(0 - 4)please: ')) yatzy_sheet[user_input] = sum(dice) print_sheet(yatzy_sheet) def main(): # Do not change this code dt = DiceThrower() sheet = [0, 0, 0, 0, 0] game_is_on = main_menu() while game_is_on: for i in range(0, 5): dice = dice_menu(dt) sheet_menu(dice, sheet) print('Final Score', sum(sheet)) game_is_on = main_menu() main()
lower = int(input("lower: ")) higer = int(input("higher: ")) between = 0 while True: between = int(input("enter number between " + str(lower) + " and " + str(higer) + ":")) if(lower <= between <= higer): print("Gotham city is safe … for now") break
size = int(input("Input size: ")) arr = [] for i in range(size): arr.append(int(input("Enter value {}:".format(i + 1)))) target = int(input("Input target")) # Demo 1 if target in arr: print("{} is in the list.".format(target)) else: print("{} is not in the list.".format(target)) # Demo 2 found = 0 for a in arr: if target == a: found += 1 if found: print("{} is {} in the list.".format(target, found)) else: print("{} is {} in the list.".format(target, found))
def get_file(file_name): try: with open(file_name, "r", encoding="utf-8") as data_file: data_list = [] # start with an empty list for line_str in data_file: data_list.append(line_str.strip().split()) return sorted(data_list) except FileNotFoundError: print("Cannot find file", file_name) def list_to_dic(a_dict): dic = {} for x in a_dict: if x[0] not in dic.keys(): dic[x[0]] = x[1] else: dic[x[0]] += " " + x[1] return dic def print_people(a_dict): john = -1 mary = -1 phil = -1 for x in a_dict.keys(): print(x + ": ") countries = a_dict[x].split() arr = [] count = [] for y in countries: if y not in arr: arr.append(y) print("\t", y) count.append(y) if x == "John": john += len(count) elif x == "Mary": mary += len(count) elif x == "Phil": phil += len(count) if john >= mary > phil: print("John has been to {} countries".format(john)) elif mary > john > phil: print("Mary has been to {} countries".format(mary)) elif phil > john > mary: print("Phil has been to {} countries".format(phil)) file_name = "flights.txt" file = get_file(file_name) dic = list_to_dic(file) print_people(dic)
def lowest_value(nums): return min(nums) def check(length, l): return len(length) == l def main(): for x in range(2, 5): i = [int(ss) for ss in input("Enter " + str(x) + " numbers: ").split(',')] if x == 4: print(lowest_value(i)) else: if check(i, x): print(lowest_value(i)) else: print("What the fuck?!?!?") main()
def get_value(): val = int(input("Input table size: ")) if 0 < val > 8: print("Invalid size!") exit(0) return val def main(val): for x in range(1, val + 1): print("{}|".format(x), end="") for y in range(1, val + 1): print("{}".format("\t" + str((x*y))), end="") print("") def header(val): for x in range(1, val + 1): print("{}".format("\t" + str(x)), end="") print("") print("\t" + ("-" * (4*val))) value = get_value() header(value) main(value)
a = int(input("Integer one: ")) b = int(input("Integer two: ")) print(a + b)