blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
f0dbc3f098e17c3aa179370e0dc13a092759c6ce
hcl14/cpp_problems_for_position1
/task1.py
2,744
4
4
# -*- coding: utf-8 -*- # The problem is to count numbers from 1 to N and factorize each one. # It means, that numbers aren't supposed to be big and usage of some advanced prime factorization algorithms # like Pollard’s Rho is not beneficial. Trial division is used here: # function that factorizes one positive integer (size_t is unsigned type) # result is written to std::vector container import numpy as np # we need an object array that contains lists of different length divisors=np.empty((1,),dtype=object) #array of lists containing database of divisors for each number # unfortunately, we lose numpy speedup this way, another memory-costy variant is to initialize big matrix Nx(N/2) and have zeros there # function that factorizes one number by division and database search def factorize_to_primes( number ): #add factorized number to the database # np.append(divisors,[], axis=0) # does not work current_entry = np.empty((1,),dtype=object) global divisors divisors = np.concatenate((divisors,current_entry)) divisors[divisors.shape[0]-1] = [] half = number/2 #prime divisors of N are located in between 1..N/2; (NOT 1..sqrt(N) : see 6 or 10 for example) #note, that we have already passed all the numbers 1..N/2 for their divisors #check for divisors in the database, starting from the biggest for i in range(half,0,-1): # if i is a divisor if number % i == 0: # if it does not have any divisors recorded in the database, except 1 and itself if len(divisors[i-1]) == 1: #record it as prime divisor divisors[number-1].append(i) # proposed function to factorize numbers from 1 to N def factorize_sequence(number): if number==0: return 1 # adding 1 as prime number, just to leave less code in the function body divisors[0] = [] divisors[0].append(1) #if we have more to do if number>1: # main loop, from 2 up to number requested for i in range(2,number+1): factorize_to_primes(i) #one more pass to make results neat (include actual number) #we cannot do that in function above, because checking for 2 (instead of 1) divisors in the database #can be errorneous: for example 4 will have two: 2,1. #So let's do one more pass instead of extra checks for i in range(2,number+1): if len(divisors[i-1]) == 1: divisors[i-1].append(i) return 0; def print_results(): for i in range(0,divisors.shape[0]): print i+1, ": ", divisors[i] if __name__ == "__main__": factorize_sequence(12) print_results()
df97aa2ef46b3ab6d5f623604e64222d232214d3
dhbandler/unit6
/hw6.py
929
3.671875
4
#Daniel Bandler #5/14/18 #hw6.py """ #Program 1 wordlist = ["dog", "cat", "hamburguesa"] wordguess = input("Guess a word") if wordguess in wordlist: print("yes") else: print("no") file = open("engmix.txt") word = input("guess a word ") for line in file: line = line.strip() if word == line: print("in dictionary") inD = True break if not inD: print("no") """ """ file = open("engmix.txt") numLines = 0 for line in file: numLines += 1 if numLines == 888: print(line.strip()) """ """ file = open("warmup16.py") for line in file: print(line.strip(), "!") """ file = open("engmix.txt") letter = input("Type a letter here. ") mostLetters = [] letterCount = 0 for line in file: lineLetter = line.count(letter) if lineLetter > letterCount: letterCount = lineLetter mostLetters = line.strip() print(mostLetters)
2408c31f6598155bcf9248554378c2d479cda617
rzngnam/giangnamdeptrai
/20.8.1.py
291
3.515625
4
s = input("Enter string ? ").lower() # lệnh xóa whitespaces nhưng e ko chạy được ¿ # s.replace(' ', '') table = dict() for i in range(len(s)): if s[i] in table: table[s[i]] += 1 else: table[s[i]] = 1 for k, v in sorted(table.items()): print(k, v)
c76cfc05bdcf2ef4b9beff7cb13a4cbd2c61b0dd
rosswilsonmedia/functionsBasicI
/functionBasicI.py
2,239
3.765625
4
#1 def number_of_food_groups(): return 5 print(number_of_food_groups()) # print 5 #2 def number_of_military_branches(): return 5 # print(number_of_days_in_a_week_silicon_or_triangle_sides() + number_of_military_branches()) # Error: invalid arguments for number_of_days_in_a_week_silicon_or_triangle_sides() #3 def number_of_books_on_hold(): return 5 return 10 print(number_of_books_on_hold()) # print 5 #4 def number_of_fingers(): return 5 print(10) print(number_of_fingers()) # print 5 #5 def number_of_great_lakes(): print(5) x = number_of_great_lakes() print(x) # print 5, print None #6 def add(b,c): print(b+c) # print(add(1,2) + add(2,3)) # print 3, print 5, TypeError: can't add NoneType #7 def concatenate(b,c): return str(b)+str(c) print(concatenate(2,5)) # print '25' #8 def number_of_oceans_or_fingers_or_continents(): b = 100 print(b) if b < 10: return 5 else: return 10 return 7 print(number_of_oceans_or_fingers_or_continents()) # print 100, print 10 #9 def number_of_days_in_a_week_silicon_or_triangle_sides(b,c): if b<c: return 7 else: return 14 return 3 print(number_of_days_in_a_week_silicon_or_triangle_sides(2,3)) print(number_of_days_in_a_week_silicon_or_triangle_sides(5,3)) print(number_of_days_in_a_week_silicon_or_triangle_sides(2,3) + number_of_days_in_a_week_silicon_or_triangle_sides(5,3)) # print 7, print 14, print 21 #10 def addition(b,c): return b+c return 10 print(addition(3,5)) # print 8 #11 b = 500 print(b) def foobar(): b = 300 print(b) print(b) foobar() print(b) # print 500, print 500, print 300, print 500 #12 b = 500 print(b) def foobar(): b = 300 print(b) return b print(b) foobar() print(b) # print 500, print 500, print 300, print 500 #13 b = 500 print(b) def foobar(): b = 300 print(b) return b print(b) b=foobar() print(b) # print 500, print 500, print 300, print 300 #14 def foo(): print(1) bar() print(2) def bar(): print(3) foo() # print 1, print 3, print 2 #15 def foo(): print(1) x = bar() print(x) return 10 def bar(): print(3) return 5 y = foo() print(y) # print 1, print 3, print 5, print 10
f7772bec2e3bf98d5f23a9965319133b8c622b1b
joaothomaz23/Basic_Python_Journey
/num_max.py
371
4.125
4
print("Este programa lê três numeros e dia qual deles é o maior: ") num1 = int(input("Entre com o primeiro numero: ")) num2 = int(input("Entre com o segundo numero: ")) num3 = int(input("Entre com o terceiro numero: ")) num_max = max(num1, num2, num3) num_min = min(num1, num2, num3) print("O maior numero e: ",num_max) print("O menor numero e: ",num_min)
1dfced69c33ae3ebc077b92ca0d117b7ff8dca78
alammahbub/py_begin_oct
/13. exception handling.py
319
4.125
4
# if try block produce an error then except block will catch that error and response as required try: value = 5/0 number = int(input("Enter a number")) print(number) except ZeroDivisionError as err: print("Input number other than zero: "+str(err)) except ValueError: print("Invalid Input")
bab85bf4b1bb2f31959e5c15607e28a08b76f19f
PatrickJameson/Kursovaya
/2 часть курсовой/10.py
339
3.5625
4
import numpy as np N = 4 M = 5 K = np.random.randint(1, 3) A = np.random.randint(low=-9, high=10, size=(N, M)) print("Матрица:\r\n{}\n".format(A)) K_arr = np.array(A[:, K-1]) K_arr = K_arr[: , np.newaxis] print("K-ый столбец: \r\n{}\n".format(K_arr)) A = A * K_arr print("Новая матрица:\r\n{}\n".format(A))
736c689d915761887dc2a782ed0fbb6cb03c72c0
johni-yoods/session-10-assignment-johni-yoods
/polygon.py
2,484
4.3125
4
import math class Polygon: """ Polygon class to generate polygon of desired vertex and circumradius. """ def __init__(self,no_of_edges:int,circumradius:int): """ no_of_edges: Number of vertices of the plygon circumradius: circumradius of the polygon. """ self.no_of_edges = no_of_edges self.circumradius = circumradius def __repr__(self)->str: """ function to display the output of the class object. """ return (f"Polygon with {self.no_of_edges} vertices and {self.circumradius} as Circumradius") def __eq__(self, obj)->bool: """ check the self.no_of_edges and self.circumradius with the the obj passed as an argument returns : bool - True if equal else False """ if not isinstance(obj,Polygon): raise TypeError('expected polygon class but given is not a polygon class') return ((self.no_of_edges == obj.no_of_edges) and (self.circumradius == obj.circumradius)) def __gt__(self, obj)->bool: """ This class is to check greater than. It checks the self.no_of_edges and self.circumradius with the ones of the other passed in as argument returns: bool - True if equal else False """ if not isinstance(obj,Polygon): raise TypeError('expected polygon class but given is not a polygon class') return self.no_of_edges > obj.no_of_edges def interior_angle(self)->float: """ This function calculates the interior angle (n-2)*180/n """ return ((self.no_of_edges-2)*180)/self.no_of_edges def edge_length(self)->float: """ This function calculates the edge length s=2*R*sin(pi/n) """ return 2*self.circumradius*math.sin(math.pi/self.no_of_edges) def apothem(self)->float: """ This function calculates the apothem a=R*cos(pi/n) """ return self.circumradius*math.cos(math.pi/self.no_of_edges) def area(self)->float: """ This function calculates the area, area=1/2*n*s*a """ return 0.5*self.apothem()*self.edge_length() * self.no_of_edges def perimeter(self)->float: """ This function calculates the perimeter, perimeter = n*s """ return self.no_of_edges * self.edge_length()
f5f1a1deaef231feb288d35fd17ba8f0b6b96432
dkspringer/build-a-blog
/hashutil.py
534
3.515625
4
import hashlib import random import string def make_salt(): return ''.join([random.choice(string.ascii_letters) for x in range(5)]) def make_hash_with_salt(password, salt=None): if not salt: salt = make_salt() hash = get_hash(password+salt) return '{},{}'.format(hash, salt) def get_hash(text): return hashlib.sha256(str.encode(text)).hexdigest() def verify_hash(password, hash): salt = hash.split(',')[1] if make_hash_with_salt(password, salt) == hash: return True return False
3a6e3d85968a2aea22d17713f8fbdbdcf1f9971c
TaehoLi/DL-Tensorflow
/RBM_AutoE/.ipynb_checkpoints/예제3-1-checkpoint.py
3,981
3.5625
4
""" 예제 3-1: 이진 입력 RBM을 MNIST 데이터에 적용 """ # 필요한 라이브러리를 불러들임 import numpy as np import pandas as pd import tensorflow as tf import matplotlib.pyplot as plt %matplotlib inline # MNIST 파일 읽어들임 from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data", one_hot=True) # 학습관련 매개변수 설정 n_input = 784 n_hidden = 500 display_step = 1 num_epochs = 10 batch_size = 256 lr = tf.constant(0.001, tf.float32) # 입력, 가중치 및 편향을 정의함 x = tf.placeholder(tf.float32, [None, n_input], name="x") W = tf.Variable(tf.random_normal([n_input, n_hidden], 0.01), name="W") b_h = tf.Variable(tf.zeros([1, n_hidden], tf.float32, name="b_h")) b_i = tf.Variable(tf.zeros([1, n_input], tf.float32, name="b_i")) # 확률을 이산 상태, 즉 0과 1로 변환함 def binary(probs): return tf.floor(probs + tf.random_uniform(tf.shape(probs), 0, 1)) # Gibbs 표본추출 단계 def cd_step(x_k): h_k = binary(tf.sigmoid(tf.matmul(x_k, W) + b_h)) x_k = binary(tf.sigmoid(tf.matmul(h_k, tf.transpose(W)) + b_i)) return x_k # 표본추출 단계 실행 def cd_gibbs(k,x_k): for i in range(k): x_out = cd_step(x_k) # k 반복 후에 깁스 표본을 반환함 return x_out # CD-2 알고리즘 # 1. 현재 입력값을 기반으로 깁스 표본추출을 통해 새로운 입력값 x_s를 구함 # 2. 새로운 x_s를 기반으로 새로운 은닉노드 값 act_h_s를 구함 x_s = cd_gibbs(2,x) act_h_s = tf.sigmoid(tf.matmul(x_s, W) + b_h) # 입력값이 주어질 때 은닉노드 값 act_h를 구함 act_h = tf.sigmoid(tf.matmul(x, W) + b_h) # 은닉노드 값이 주어질 때 입력값을 추출함 _x = binary(tf.sigmoid(tf.matmul(act_h, tf.transpose(W)) + b_i)) # 경사 하강법을 이용한 가중치 및 편향 업데이트 W_add = tf.multiply(lr/batch_size, tf.subtract(tf.matmul(tf.transpose(x), act_h), \ tf.matmul(tf.transpose(x_s), act_h_s))) bi_add = tf.multiply(lr/batch_size, tf.reduce_sum(tf.subtract(x, x_s), 0, True)) bh_add = tf.multiply(lr/batch_size, tf.reduce_sum(tf.subtract(act_h, act_h_s), 0, True)) updt = [W.assign_add(W_add), b_i.assign_add(bi_add), b_h.assign_add(bh_add)] # 텐서플로 그래프 실행 with tf.Session() as sess: # 모형의 변수들을 초기화하기 init = tf.global_variables_initializer() sess.run(init) total_batch = int(mnist.train.num_examples/batch_size) # 훈련용 이미지 데이터를 사용하여 학습 시작 for epoch in range(num_epochs): # 모든 미니배치에 대해 반복함 for i in range(total_batch): batch_xs, batch_ys = mnist.train.next_batch(batch_size) # 가중치 업데이터 실행 batch_xs = (batch_xs > 0)*1 _ = sess.run([updt], feed_dict={x:batch_xs}) # 실행 단계 보여주기 if epoch % display_step == 0: print("Epoch:", '%04d' % (epoch+1)) print("RBM training Completed !") # 20개의 검정용 이미지에 대해 은닉노드의 값을 계산 out = sess.run(act_h,feed_dict={x:(mnist.test.images[:20]> 0)*1}) label = mnist.test.labels[:20] # 20개의 실제 검정용 이미지 그리기 plt.figure(1) for k in range(20): plt.subplot(4, 5, k+1) image = (mnist.test.images[k]> 0)*1 image = np.reshape(image,(28,28)) plt.imshow(image,cmap='gray') # 20개의 생성된 검정용 이미지 그리기 plt.figure(2) for k in range(20): plt.subplot(4, 5, k+1) image = sess.run(_x,feed_dict={act_h:np.reshape(out[k],(-1,n_hidden))}) image = np.reshape(image,(28,28)) plt.imshow(image,cmap='gray') print(np.argmax(label[k])) W_out = sess.run(W) sess.close()
5f0bbd7ca72275903f3e359857f7f9814d7f1709
binkesi/leetcode_easy
/python/n559_NTreeDepth.py
1,152
3.875
4
# https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/ # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children class Solution: def __init__(self): self.depth = 0 self.queue = [] def maxDepth(self, root: 'Node') -> int: if root is None: return 0 tmp_queue = [] tmp_queue.append(root) self.queue.append(tmp_queue) while len(self.queue[0]) != 0: tmp_queue = [] for node in self.queue[0]: if node is None or len(node.children) == 0: continue for i in node.children: tmp_queue.append(i) self.queue.append(tmp_queue) self.queue.pop(0) self.depth += 1 return self.depth def maxDepth_a(self, root: 'Node'): if root is None: return 0 if root.children == []: return 1 height = [self.maxDepth_a(node) for node in root.children] return max(height) + 1 if __name__ == "__main__": pass
911027e4239d73e94229f9f70c2315243db70db9
AdamZhouSE/pythonHomework
/Code/CodeRecords/2314/60787/305323.py
71
3.625
4
n=int(input()) for i in range(0,n): a=input() print(str(i)+" ")
03ad6b78e2f5a4de8980dfd64469162a3d70be03
makurek/leetcode
/1323-maximum-69-number.py
729
4.1875
4
''' Given a positive integer num consisting only of digits 6 and 9. Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6). Example 1: Input: num = 9669 Output: 9969 Explanation: Changing the first digit results in 6669. Changing the second digit results in 9969. Changing the third digit results in 9699. Changing the fourth digit results in 9666. The maximum number is 9969. ''' def maximum69Number(num:int) -> int: s = str(num) result = "" done = False for element in s: if element is "6" and not done: result += "9" done = True else: result += element return int(result) print(maximum69Number(9669))
55d1ef94ec89dc76ca90a0da58df7a0bf9b0201c
AdamsGeeky/basics
/04 - Classes-inheritance-oops/10-classes-inheritance.py
831
4.59375
5
# HEAD # Classes - Inheritance # DESCRIPTION # Describes how to create a class inheritance using two classes # RESOURCES # # Creating Parent class class Parent(): par_cent = "parent" def p_method(self): print("Parent Method invoked with par_cent", self.par_cent) return self.par_cent # Inheriting all Parent attributes # and methods into Child class Child(Parent): chi_cent = "child" def c_method(self): print("Child Method invoked with chi_cent", self.chi_cent) # Accessing Parent methods return self.p_method() obj = Child() # Access Parent and Child Attributes print("obj.par_cent ", obj.par_cent) print("obj.chi_cent ", obj.chi_cent) # Invoke Parent and Child Methods print("p_method ", obj.p_method()) print("c_method ", obj.c_method())
6437d3b6dab4ae399a6d513471d602ee305e0ff4
kwonseongjae/p1_201611055
/w7main_3.py
937
3.5
4
def saveTracks(): import turtle wn=turtle.Screen() t1=turtle.Turtle() t1.speed(1) t1.pu() mytracks=list() t1.goto(-370,370) t1.rt(90) t1.pd() mytracks.append(t1.pos()) t1.pencolor("Red") t1.fd(300) t1.lt(90) mytracks.append(t1.pos()) t1.fd(400) t1.lt(90) mytracks.append(t1.pos()) t1.fd(150) t1.rt(90) mytracks.append(t1.pos()) t1.fd(200) t1.rt(90) mytracks.append(t1.pos()) t1.fd(300) t1.fd(100) t1.lt(90) mytracks.append(t1.pos()) t1.fd(200) mytracks.append(t1.pos()) return mytracks for i in range(0,len(mytracks)): t1.goto(mytracks[i]) def replayTracks(mytracks): for i in range(0,len(mytracks)): print(mytracks[i]) def lab7(): mytracks=saveTracks() replayTracks(mytracks) def main(): lab7() main() if __name__=="main": main() wn.exitonclick()
f195f65f74f3aa4c7ff84858cff39b66dc466d84
AmitAps/advance-python
/intermediate_python/tuples.py
478
3.78125
4
#Tuples: ordered, immutable, allows duplicate elements mytuple = ("Amit", 28, "chhapra") print(mytuple) singletuple = ("Amit",) print(type(singletuple)) for x in mytuple: print(x) mytuple1 = ('a', 'p', 's', 'd', 'k', 'p') print(mytuple1.count('p')) print(mytuple1.index('p')) # mytuple2 = "amitpratapsingh sahadi chhapra" # # print(mytuple2.count('sahadi')) import timeit print(timeit.timeit(stmt="[0,1,2,3,4,5]", number=1000)) print(timeit.timeit(stmt="(0,1,2,3,4,5)", number=1000))
e1f10b5e9def0b70243e4f280ca5a7996408c51e
dawnarc/util_scripts
/string/batch_replace_string.py
560
3.640625
4
#batch replace string in a directory recursively import os import glob import io dir = 'D:/test' dic = { "src": "dest", "aaa": "bbb"} def replace_all(text, dic): for i, j in dic.items(): text = text.replace(i, j) return text for file in glob.iglob(dir + '/**/*.txt', recursive=True): print(file) new_text = '' with io.open(file,'r',encoding='utf8') as f: text = f.read() new_text = replace_all(text, dic); with io.open(file,'w',encoding='utf8') as f: f.write(new_text)
eb7f284265f24594d9e564118abf5304f197d54c
Ethnrk/Comp_Mthds_HW1
/Percentile.py
3,473
4.03125
4
# -*- coding: utf-8 -*- """ Created on Wed Feb 22 16:35:53 2017 @author: Ethan """ #test list for checking if code is right listy = [2,14,67,44,67,34,56,78,12,3,3,98,77,88,43,25,46,76,54,36,73,56,23,87,12,67,34,56,23,98,23,65,33,24,26,97,104,45,67,8,81,98,212] ## lets make this a bit more realistic for diameters shall we?? for i in range(0,len(listy)): listy[i] = listy[i]/1000.0 ##Initialization of code and input of values print 'Welcome to the river properties calculator!' print 'You will be given a variety of parameters to enter in.' print 'For the parameter you wish to solve for, please enter 0 for the value' r_slope = input('Enter river slope: ') r_height = input('Enter flow height: ') ## Important!! program does not function with lists of less than three values. As the program is intended to work with longer lists ##(5+ values) this should be ok. If you want to do it with less do the math yourself. It is good mental excercise. r_diameter = input('Enter a list of grain diameters: ') sediment_size = {} sediment_size['set1'] = r_diameter ## defining class for river class River: def __init__(self, slope, height, density , tau): self.slope = slope self.height = height self.density = density self.tau = tau #set up of custom river class my_river = River (r_slope,r_height,2650.0,0.06) # preparation for funciton used to caluclate percentile. # had issues with getting funciton to accept a direct list, dictionary result was much better def percentile(data,num): Percentile = float(num) datum = data['set1']; listy1 = sorted(datum) per_calc = len(listy1) a = (Percentile/100.0) ## calculating percentile based on simple statisticla method #percentile if list has even number of values if per_calc%2 == 0.0: count = int(a * per_calc) x_percentile = (listy1[count] + listy1[count+1])/2.0 # percentile if it has odd number of values else: count = int(a * per_calc) + (a%per_calc >0) x_percentile = listy1[count] return x_percentile if r_diameter == 0: diam_50 = 0 else: diam_50 = (percentile(sediment_size,50.0)) #set density factor dens = (1000.0/(my_river.density - 1000)) ##solving for variables/ calling you out for doing something you are not supposed to ## uses equation of tau = density difference * height * slope / 50th percentile diameter if my_river.slope == 0 and my_river.height == 0: print("I'm sorry, you appear to be trying to solve for one too many variables, please try again") elif my_river.slope == 0 and r_diameter == 0: print("I'm sorry, you appear to be trying to solve for one too many variables, please try again") elif my_river.height == 0 and r_diameter == 0: print("I'm sorry, you appear to be trying to solve for one too many variables, please try again") elif my_river.slope ==0: slope = (my_river.tau*diam_50)/(dens*my_river.height) print 'Slope is:', slope elif my_river.height == 0: height = ((my_river.tau*diam_50)/(dens*my_river.slope)) print 'Height is: ', height elif diam_50 == 0: diam_50 = (dens*my_river.height*my_river.slope)/my_river.tau print '50th percentile diameter is :', diam_50 else: print 'Hey man, you already got all the vlaues you need, what are you doing??'
6a979b5b35a901ce6028d9f9e09ea9f33520f144
alegorecki2405/Coding-challanges
/7.py
774
3.875
4
# Good morning! Here's your coding interview problem for today. # This problem was asked by Facebook. # Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. # For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. # You can assume that the messages are decodable. For example, '001' is not allowed. lst = [1,2,3,4,5] dl = len(lst) def ile_mozliwosci(dl): if dl == 1: return 1 elif dl == 2: return 2 return ile_mozliwosci(dl-1) + ile_mozliwosci(dl-2) def poprawki(lst,dl): ileod = 0 for i in range(0,dl-1): if lst[i]*10 + lst[i+1] > 26: ileod+=1 return ileod print(ile_mozliwosci(dl)-poprawki(lst,dl))
1569633d00fdf216fc2c8e3c1e3171ea36b31a19
kswr/Python_Mega_Course
/S_6_File_handling/L_58_opening_and_writing_to_a_txt_file/open_and_wrt_to_txt_file.py
219
3.578125
4
file = open('example.txt','w') file.write("Line 1\n") file.write("Line 2\n") file.close() file = open('example1.txt','w') list = ["Line 1", "Line 2", "Line 3"] for item in list: file.write(item+"\n") file.close()
fa2fcb21f4e2bb3d76e299d20544c41ce2bfb4b9
brunofonsousa/python
/pythonbrasil/exercicios/repeticao/ER resp 26.py
1,104
4.125
4
''' Numa eleição existem três candidatos. Faça um programa que peça o número total de eleitores. Peça para cada eleitor votar e ao final mostrar o número de votos de cada candidato. ''' cand1, cand2, cand3 = 0,0,0 print('******************************************************') print('********************** ELEIÇÕES **********************') print('******************************************************') print('\n') eleitores = int(input('\tDigite o número total de eleitores: ')) print('') for i in range(eleitores): voto = int(input('\t Vote nos candidatos(1,2,3):')) if voto == 1: cand1 += 1 if voto == 2: cand2 += 1 if voto == 3: cand3 += 1 print('\n') print('\t\t TOTAL DE VOTOS:') print('\t\t Candidato 1: ',cand1) print('\t\t Candidato 2: ',cand2) print('\t\t Candidato 3: ',cand3) print('\n') print('******************************************************') print('******************************************************') print('******************************************************')
d1080a8f9ea6001db38246da9722c34682fe841a
eyoung8/weathersite
/src/weather/weather.py
5,199
3.796875
4
#/usr/bin/env python """Script that accesses and prints weather information on a city retrieved from yahoo's weather api. On command line specify city (lowercase, no spaces), state (lowercase, abbreviation, eg. ny) to select the location Display options include: temp condition windchill high low humidity date location Example call: python weather.py newyork ny temp condition windchill high low humidity date location""" #API info: #https://developer.yahoo.com/yql/console/#h=select+*+from+weather.forecast+where+woeid+in+(select+woeid+from+geo.places(1)+where+text%3D'dasdas%2C+asdafaf') #https://developer.yahoo.com/weather/ import urllib.parse, urllib.request, json, sys from .utils import is_zip def get_temp(data): """Returns temperature string""" return data['query']['results']['channel']['item']['condition']['temp'] def get_windchill_temp(data): """Returns feels like temperature string""" return data['query']['results']['channel']['wind']['chill'] def get_date(data): """Returns date/time of most recent weather update string""" return data['query']['results']['channel']['lastBuildDate'] def get_condition(data): """Returns weather condition string""" return data['query']['results']['channel']['item']['condition']['text'] def get_city(data): """Returns city string""" return data['query']['results']['channel']['location']['city'] def get_state(data): """Returns state (or region) string""" return data['query']['results']['channel']['location']['region'] def get_humidity(data): """Returns humidity string""" return data['query']['results']['channel']['atmosphere']['humidity'] def get_sunrise(data): """Returns sunrise string""" return data['query']['results']['channel']['astronomy']['sunrise'] def get_sunset(data): """Returns sunset string""" return data['query']['results']['channel']['astronomy']['sunset'] def get_high(data): """Returns high temperature string""" return data['query']['results']['channel']['item']['forecast'][0]['high'] def get_low(data): """Returns low temperature string""" return data['query']['results']['channel']['item']['forecast'][0]['low'] def get_location(data): """Returns formatted location as City, STATE""" return get_city(data) + ", " + get_state(data) def get_yahoo_weather_json(query): """Returns a json file. Designed for accessing yahoo weather api.""" base_url = "https://query.yahooapis.com/v1/public/yql?" format = "&format=json" final_url = base_url + urllib.parse.urlencode({'q':query}) + format req = urllib.request.urlopen(final_url).read().decode('utf-8') data = json.loads(req) return data displayDict = { "temp" : ["Temperature: ", get_temp, " F"], "condition" : ["Condition: ", get_condition, ""], "date" : ["Accessed: ", get_date, ""], "windchill" : ["Feels like: ", get_windchill_temp, " F"], "high" : ["High: ", get_high, " F"], "low" : ["Low: ", get_low, " F"], "sunrise" : ["Sunrise: ", get_sunrise, ""], "sunset" : ["Sunset: ", get_sunset, ""], "humidity" : ["Humidity: ", get_humidity, "%"], "location" : ["", get_location, ""] } #displayDict["temp"] def get_query(city, state): loc = city + ", " + state query = "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='"+ loc + "')" return query def get_query_by_zip(loc): query = "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='"+ loc + "')" return query def get_std_weather_results(data, settings=['location', 'temp', 'condition', 'high', 'low', 'humidity', 'date']): results = {} for word in settings: try: results[word] = ('{}{}'.format(displayDict[word][1](data), displayDict[word][2])) except KeyError as err: pass return results def get_weather(location): query = None if (len(location.split())== 1): query = get_query_by_zip(location) else: city, state = location.split() query = get_query(city, state) data = get_yahoo_weather_json(query) if(data['query']['results']): results = get_std_weather_results(data) else: results = None return results def main(): try: city = sys.argv[1] state = sys.argv[2] loc = city + ", " + state query = "select * from weather.forecast where woeid in (select woeid from geo.places(1) where text='"+ loc + "')" data = get_yahoo_weather_json(query) settings = sys.argv[3:] for word in settings: try: print('{0}{1}{2}'.format(displayDict[word][0], displayDict[word][1](data), displayDict[word][2])) except KeyError as err: print ("Not an option: {}".format(err)) except IndexError as err: print ("Index Error: {}".format(err)) except urllib.error.URLError: print("Weather Gods could not be reached",) if __name__ == "__main__": main()
6a312d80c034ef0808bae6d8ae63ecd28e1b4111
CSC525AI-Project1/CSC525AI-Project1
/EightPuzzleGame_InformedSearch.py
18,822
3.828125
4
import numpy as np from EightPuzzleGame_State import State ''' This class implement the Best-First-Search (BFS) algorithm along with the Heuristic search strategies In this algorithm, an OPEN list is used to store the unexplored states and a CLOSE list is used to store the visited state. OPEN list is a priority queue. The priority is insured through sorting the OPEN list each time after new states are generated and added into the list. The heuristics are used as sorting criteria. In this informed search, reducing the state space search complexity is the main criterion. We define heuristic evaluations to reduce the states that need to be checked every iteration. Evaluation function is used to express the quality of informedness of a heuristic algorithm. ''' class InformedSearchSolver: current = State() goal = State() openlist = [] closed = [] depth = 0 def __init__(self, current, goal): self.current = current self.goal = goal self.openlist.append(current) def sortFun(self, e): return e.weight """ * check if the generated state is in open or closed * the purpose is to avoid a circle * @param s * @return """ def check_inclusive(self, s): in_open = 0 in_closed = 0 ret = [-1, -1] for item in self.openlist: if item.equals(s): in_open = 1 ret[1] = self.openlist.index(item) break for item in self.closed: if item.equals(s): in_closed = 1 ret[1] = self.closed.index(item) break if in_open == 0 and in_closed == 0: ret[0] = 1 # the child is not in open or closed elif in_open == 1 and in_closed == 0: ret[0] = 2 # the child is already in open elif in_open == 0 and in_closed == 1: ret[0] = 3 # the child is already in closed return ret """ * four types of walks * best first search * ↑ ↓ ← → (move up, move down, move left, move right) * the blank tile is represent by '0' """ def state_walk(self): # add closed state self.closed.append(self.current) self.openlist.remove(self.current) # move to the next heuristic state walk_state = self.current.tile_seq row = 0 col = 0 for i in range(len(walk_state)): for j in range(len(walk_state[i])): if walk_state[i, j] == 0: row = i col = j break self.depth += 1 ''' The following program is used to do the state space walk ''' # ↑ move up if (row - 1) >= 0: # TODO your code start here """ *get the 2d array of current *define a temp 2d array and loop over current.tile_seq *pass the value from current.tile_seq to temp array """ tempArray = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) for i in range(len(self.current.tile_seq)): for j in range(len(self.current.tile_seq[i])): tempArray[i, j] = self.current.tile_seq[i, j] """ *↑ is correspond to (row, col) and (row-1, col) *exchange these two tiles of temp """ tempHolder = tempArray[row, col] tempArray[row, col] = tempArray[row-1, col] tempArray[row-1, col] = tempHolder #print("temp up \n", tempArray) """ *call check_inclusive(temp state) *define a new temp state via temp array """ tempState = State() tempState.tile_seq = tempArray tempState.depth = self.depth flag = self.check_inclusive(tempState) #print("TempState \n", tempState.tile_seq) """ *do the next steps according to flag *if flag = 1 //not in open and closed *begin *assign the child a heuristic value via heuristic_test(temp state); *add the child to open *end; """ if flag[0] == 1: self.heuristic_test(tempState) self.openlist.append(tempState) #print("open list \n", self.openlist) """ *if flag = 2 //in the open list *if the child was reached by a shorter path *then give the state on open the shorter path """ if flag[0] == 2: if self.openlist[flag[1]].depth > tempState.depth: self.openlist[flag[1]].depth = tempState.depth #print("depth", tempState.depth) """ *if flag = 3 //in the closed list *if the child was reached by a shorter path then *begin *remove the state from closed; *add the child to open *end; """ if flag[0] == 3: if self.closed[flag[1]].depth > tempState.depth: self.closed.remove(self.closed[flag[1]]) self.openlist.append(tempState) # TODO your code end here # ↓ move down if (row + 1) < len(walk_state): # TODO your code start here """ *get the 2d array of current *define a temp 2d array and loop over current.tile_seq *pass the value from current.tile_seq to temp array """ tempArray = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) for i in range(len(self.current.tile_seq)): for j in range(len(self.current.tile_seq[i])): tempArray[i, j] = self.current.tile_seq[i, j] """ *↓ is correspond to (row, col) and (row+1, col) *exchange these two tiles of temp """ tempHolder = tempArray[row, col] tempArray[row, col] = tempArray[row+1, col] tempArray[row+1, col] = tempHolder #print("temp down \n", tempArray) """ *call check_inclusive(temp state) *define a new temp state via temp array """ tempState = State() tempState.tile_seq = tempArray tempState.depth = self.depth flag = self.check_inclusive(tempState) # print("TempState \n", tempState.tile_seq) """ *do the next steps according to flag *if flag = 1 //not in open and closed *begin *assign the child a heuristic value via heuristic_test(temp state); *add the child to open *end; """ if flag[0] == 1: self.heuristic_test(tempState) self.openlist.append(tempState) # print("open list \n", self.openlist) """ *if flag = 2 //in the open list *if the child was reached by a shorter path *then give the state on open the shorter path """ if flag[0] == 2: if self.openlist[flag[1]].depth > tempState.depth: self.openlist[flag[1]].depth = tempState.depth # print("depth", tempState.depth) """ *if flag = 3 //in the closed list *if the child was reached by a shorter path then *begin *remove the state from closed; *add the child to open *end; """ if flag[0] == 3: if self.closed[flag[1]].depth > tempState.depth: self.closed.remove(self.closed[flag[1]]) self.openlist.append(tempState) # TODO your code end here # ← move left if (col - 1) >= 0: # TODO your code start here """ *get the 2d array of current *define a temp 2d array and loop over current.tile_seq *pass the value from current.tile_seq to temp array """ tempArray = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) for i in range(len(self.current.tile_seq)): for j in range(len(self.current.tile_seq[i])): tempArray[i, j] = self.current.tile_seq[i, j] """ *↑ is correspond to (row, col) and (row, col-1) *exchange these two tiles of temp """ tempHolder = tempArray[row, col] tempArray[row, col] = tempArray[row, col-1] tempArray[row, col-1] = tempHolder #print("temp left \n", tempArray) """ *call check_inclusive(temp state) *define a new temp state via temp array """ tempState = State() tempState.tile_seq = tempArray tempState.depth = self.depth flag = self.check_inclusive(tempState) # print("TempState \n", tempState.tile_seq) """ *do the next steps according to flag *if flag = 1 //not in open and closed *begin *assign the child a heuristic value via heuristic_test(temp state); *add the child to open *end; """ if flag[0] == 1: self.heuristic_test(tempState) self.openlist.append(tempState) # print("open list \n", self.openlist) """ *if flag = 2 //in the open list *if the child was reached by a shorter path *then give the state on open the shorter path """ if flag[0] == 2: if self.openlist[flag[1]].depth > tempState.depth: self.openlist[flag[1]].depth = tempState.depth # print("depth", tempState.depth) """ *if flag = 3 //in the closed list *if the child was reached by a shorter path then *begin *remove the state from closed; *add the child to open *end; """ if flag[0] == 3: if self.closed[flag[1]].depth > tempState.depth: self.closed.remove(self.closed[flag[1]]) self.openlist.append(tempState) # TODO your code end here # → move right if (col + 1) < len(walk_state): # TODO your code start here """ *get the 2d array of current *define a temp 2d array and loop over current.tile_seq *pass the value from current.tile_seq to temp array """ tempArray = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) for i in range(len(self.current.tile_seq)): for j in range(len(self.current.tile_seq[i])): tempArray[i, j] = self.current.tile_seq[i, j] """ *↑ is correspond to (row, col) and (row, col+1) *exchange these two tiles of temp """ tempHolder = tempArray[row, col] tempArray[row, col] = tempArray[row, col+1] tempArray[row, col+1] = tempHolder #print("temp right \n", tempArray) """ *call check_inclusive(temp state) *define a new temp state via temp array """ tempState = State() tempState.tile_seq = tempArray tempState.depth = self.depth flag = self.check_inclusive(tempState) # print("TempState \n", tempState.tile_seq) """ *do the next steps according to flag *if flag = 1 //not in open and closed *begin *assign the child a heuristic value via heuristic_test(temp state); *add the child to open *end; """ if flag[0] == 1: self.heuristic_test(tempState) self.openlist.append(tempState) # print("open list \n", self.openlist) """ *if flag = 2 //in the open list *if the child was reached by a shorter path *then give the state on open the shorter path """ if flag[0] == 2: if self.openlist[flag[1]].depth > tempState.depth: self.openlist[flag[1]].depth = tempState.depth # print("depth", tempState.depth) """ *if flag = 3 //in the closed list *if the child was reached by a shorter path then *begin *remove the state from closed; *add the child to open *end; """ if flag[0] == 3: if self.closed[flag[1]].depth > tempState.depth: self.closed.remove(self.closed[flag[1]]) self.openlist.append(tempState) # TODO your code end here # sort the open list first by h(n) then g(n) self.openlist.sort(key=self.sortFun) self.current = self.openlist[0] """ * Solve the game using heuristic search strategies * There are three types of heuristic rules: * (1) Tiles out of place * (2) Sum of distances out of place * (3) 2 x the number of direct tile reversals * evaluation function * f(n) = g(n) + h(n) * g(n) = depth of path length to start state * h(n) = (1) + (2) + (3) """ def heuristic_test(self, current): curr_seq = current.tile_seq goal_seq = self.goal.tile_seq # (1) Tiles out of place h1 = 0 # TODO your code start here """ *loop over the curr_seq *check the every entry in curr_seq with goal_seq """ for i in range(len(curr_seq)): for j in range(len(curr_seq[i])): if curr_seq[i, j] != goal_seq[i, j]: h1 += 1 # TODO your code end here # (2) Sum of distances out of place h2 = 0 # TODO your code start here """Code to find the out of place tiles by iterating through the current list and comparing it to the goal state. If a tile is out of place, enter the next set of loops to fine where the tile should be, and then add the absolute value of the difference in the x coordinates plus the absolute value of the difference in the y coordinates""" """outer loop to find out of place tiles""" for i in range(len(curr_seq)): for j in range(len(curr_seq[i])): if curr_seq[i, j] != goal_seq[i, j]: """if the tile is out of place, start next loops to find correct place""" for k in range(len(goal_seq)): for m in range(len(goal_seq[k])): """once correct place is found, find the absolute value of the differences in the x and y coordinates""" if curr_seq[i, j] == goal_seq[k, m]: h2 += abs(i-k) + abs(j-m) #print("H2 is", h2) """ *loop over the goal_seq and curr_seq in nested way *locate the entry which has the same value in *curr_seq and goal_seq then calculate the offset *through the absolute value of two differences *of curr_row-goal_row and curr_col-goal_col *absoulte value can be calculated by abs(...) """ # TODO your code end here # (3) 2 x the number of direct tile reversals h3 = 0 # TODO your code start here for row in range(len(curr_seq)): for col in range(len(curr_seq[row])): if row + 1 < len(curr_seq): if curr_seq[row + 1, col] != 0 and curr_seq[row, col] != 0: if curr_seq[row + 1, col] == goal_seq[row, col] and curr_seq[row, col] == goal_seq[row + 1, col]: h3 += 1 #print("Tile reversal detected: ", curr_seq[row+1, col], " and ", curr_seq[row, col]) #print("Current \n", current.tile_seq, "\n vs goal \n ", goal_seq) if col + 1 < len(curr_seq[row]): if curr_seq[row, col + 1] != 0 and curr_seq[row, col] != 0: if curr_seq[row, col + 1] == goal_seq[row, col] and curr_seq[row, col] == goal_seq[row, col + 1]: h3 += 1 #print("Tile reversal detected:", curr_seq[row, col+1], " and ", curr_seq[row, col]) #print("Current \n", current.tile_seq, "\n vs goal \n", goal_seq) """ *loop over the curr_seq *use a Γ(gamma)shap slider to walk throught curr_seq and goal_seq *rule out the entry with value 0 *set the boundry restriction *don't forget to time 2 at last *for example *goal_seq 1 2 3 curr_seq 2 1 3 the Γ shape starts * 4 5 6 4 5 6 * 7 8 0 7 8 0 *with 1 2 in goal_seq and 2 1 in curr_seq thus the * 4 4 *reversal is 1 2 and 2 1 """ # TODO your code end here h3 *= 2 # set the heuristic value for current state current.weight = current.depth + h1 + h2 + h3 # You can choose to print all the states on the search path, or just the start and goal state def run(self): # output the start state print("start state !!!!!") print(self.current.tile_seq) path = 0 while not self.current.equals(self.goal): self.state_walk() #print("decision \n", self.current.tile_seq) path += 1 print("It took ", path, " iterations") print("The length of the path is: ", self.current.depth) # output the goal state target = self.goal.tile_seq print(target) print("goal state !!!!!")
fcda751ab005d41d08bfa8790a1edfdcb013d7e5
sakurasakura1996/Leetcode
/leetcode_二刷hot100/problem538_把二叉搜索树转换为累加树.py
948
3.625
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # 想了一个比较蠢的思路,就是我先递归算出每个节点包含自身和所有子节点的和,然后再递归一次,减去左节点当前的值 # 突然发现想漏了,如果不是根节点的话,最终节点的值应该是其父节点的值加上自己的值,再加上右子树的节点值啊。 class Solution: ans = 0 def convertBST(self, root: TreeNode) -> TreeNode: # 突然想到一个,中序遍历搜索数是有序的,从小到大,那么中序遍历倒序是不是从大到小,那不是正好,舒服啊 if not root: return if root.right: self.convertBST(root.right) root.val += self.ans self.ans = root.val if root.left: self.convertBST(root.left) return root
b0a3c58c9a4de66e32b9c126ea88e530a448ced1
SamuelHealion/Sandbox
/week_9/person.py
1,106
4.21875
4
""" CP1404 Week 9 Lecture notes - Do this now Define the class Person """ class Person: """Represents a Person object.""" def __init__(self, first_name='', last_name='', age=0): """Initialise the Person instance.""" self.first_name = first_name self.last_name = last_name self.age = age def __str__(self): """Return a string representation of a Person object.""" return "{} {}, {} years old".format(self.first_name, self.last_name, self.age) def __lt__(self, other): """Less than, used to sort people by age, from youngest to oldest.""" return self.age < other.age def __eq__(self, other): if self.first_name == other.first_name and self.last_name == other.last_name and self.age == other.age: return True def run_tests(): first_person = Person('Sam', 'Healion', 28) print(first_person) second_person = Person('Sam', 'Healion', 28) print(second_person) if first_person == second_person: print('They are the same person') if __name__ == '__main__': run_tests()
3051a73fcf10161dc79127be71ce283a5ebe5969
lim1202/LeetCode
/Tree/populating_next_right_pointers_in_each_node.py
1,363
4.34375
4
# What if the given tree could be any binary tree? Would your previous solution still work? # Note: # You may only use constant extra space. For example, Given the following binary tree, # 1 # / \ # 2 3 # / \ \ # 4 5 7 # After calling your function, the tree should look like: # 1 -> NULL # / \ # 2 -> 3 -> NULL # / \ \ # 4-> 5 -> 7 -> NULL from binarytree import tree def connect(root): nexts = {} if root is None: return nexts p = root first = None last = None while p is not None: if first is None: if p.left is not None: first = p.left elif p.right is not None: first = p.right if p.left is not None: if last is not None: nexts[last.value] = p.left last = p.left if p.right is not None: if last is not None: nexts[last.value] = p.right last = p.right if nexts.get(p.value): p = nexts[p.value] else: p = first last = None first = None return nexts if __name__ == "__main__": my_tree = tree() print(my_tree) print(connect(my_tree))
9aa2d8376555689b7efff7287c7e5b46fb427fc4
venkateshvadlamudi/Pythontesting
/pythonPractice/Distionary.py
1,519
3.984375
4
# Creating Distionary friends= {'tom': '123-123-1234' , 'jerry' : '456-789-7854'} print(friends) # retrieving friends= {'tom': '123-123-1234' , 'jerry' : '456-789-7854'} print(friends) #Retrieving element from the distionary print(friends['tom']) #Adding elements into the distionary friends['bob']='888-999-666' print(friends) #Modify elements into the distionary friends['bob']='888-999-777' print(friends) # delete element from the distionary del friends['bob'] print(friends) # Looping items in the distionary friends={'a': '100', 'b' : '200', 'c': '300', 'd': '400' } for x in friends: print(x ,":" , friends[x]) ## Find the lenth of the distionary print(len(friends)) ## Equality Tests in distionary --> < ,> <=,<= can not use equality d1={"miske" : 41 , "bob" : 3 } d2={"bob" : 3 ,"miske" : 41 } print(d1==d2) print(d1 != d2) friends= {'tom': '123-123-1234' , 'bob':'888-999-666', 'jerry' : '456-789-7854'} #popitem() --> Returns randomly select item from distionary and also remove the selected item print(friends.popitem()) #Clear () Delete everything from distionary print(friends.clear()) friends= {'tom': '123-123-1234' , 'bob':'888-999-666', 'jerry' : '456-789-7854'} #keys() Return keys in distionary as tuple print(friends.keys()) # Values() print(friends.values()) #get(key) print(friends.get('tom')) #pop(key) print(friends.pop('bob')) print(friends)
89b802dca88049ee4fb7f5637ba74fdb81bb4dfb
DariaBe/isapy9
/Zadanie_2.py
2,696
3.71875
4
# 1) Stwórz program który przyjmie w parametrze dowolną listę np ['col1', 'col2', 'col3'] i wyświetli: # +------+------+------+ # | col1 | col2 | col3 | # +------+------+------+ # Dodatkowym atutem będzie gdy szerokość kolumn będzie zawsze równa bez względów na zawartość, tekst wyrównany do lewej. # Maksymalna szerokość kolumny np 30znaków jesli tekst będzie za długi niech zawartość przycina się i kończy trzema kropkami. # A jeszcze większym atutem będzie gdy będzie można podać liste zagnieżdżoną i narysuje się tabela z odpowiednią ilością wierszy i kolumn :) lista = ['col1', 'col2', 'col3', 'col4'] ilosc_argumentow = len(lista) max_ilosc_liter = max(lista, key = len) max_ilosc_liter = len(max_ilosc_liter) print(('+' + '-' * (max_ilosc_liter + 2)) * ilosc_argumentow + '+') for i in lista: print(('| ' + i), end=' ') print('|') print(('+' + '-' * (max_ilosc_liter + 2)) * ilosc_argumentow + '+') def rysowanie_tabeli(lista=[]): """Ta fukncja przyjmuje listę w parametrze i rysuje tabelę""" ilosc_kolumn = input('Podaj ilość kolumn: ') ilosc_kolumn = int(ilosc_kolumn) for i in ilosc_kolumn: ilosc_argumentow = len(lista) max_ilosc_liter = max(lista, key=len) max_ilosc_liter = len(max_ilosc_liter) print(('+' + '-' * (max_ilosc_liter + 2)) * ilosc_argumentow + '+') for i in lista: print(('| ' + i), end=' ') print('|') print(('+' + '-' * (max_ilosc_liter + 2)) * ilosc_argumentow + '+') rysowanie_tabeli(['col1', 'col2', 'col3']) # 2) Program przyjmuje kwotę w parametrze i wylicza jak rozmienić to na monety: 5, 2, 1, 0.5, 0.2, 0.1 wydając ich jak najmniej. kwota = input("Podaj kwotę: ") kwota = float(kwota) monety = [5, 2, 1, 0.5, 0.2, 0.1] for num in monety: if kwota // num > 0: print("Otrzymasz {} monety {} złotowe".format(kwota // num, num)) kwota = kwota - (kwota // num * num) kwota = (round(kwota, 1)) else: continue # 3) Program rysujący piramidę o określonej wysokości, np dla 3 # # # ### # ##### wysokosc = input("Podaj wysokość piramidy: ") wysokosc = int(wysokosc) for i in range(1, wysokosc * 2, 2): print(' ' * (wysokosc - 1) + '#' * i) wysokosc = wysokosc - 1 # 4) Kalkulator do wyliczania wieku psa. # Przez pierwsze dwa lata, każdy psi rok to 10,5 ludzkiego roku, przez reszte lat psi rok to 4 ludzkie lata # Np: 15 ludzkich lat to 73 psie lata wiek_psa = (input("Podaj wiek psa: ")) wiek_psa = float(wiek_psa) if(wiek_psa <= 2): print(wiek_psa * 10.5) elif(wiek_psa >= 2): print((wiek_psa - 2) * 4 + 21) else: print("Chyba nie masz psa")
6a4317b3078984ead44b8bdb77eedf0351ba040b
tx58/origin
/lab02/dice.py
272
4.03125
4
""" A simple die roller Author: Tianli Xia Date: Sep 6th, 2018 """ import random first=1 last=6 print('Choosing two numbers between '+str(first)+ ' and '+ str(last) +'.') a=random.randint(first,last) b=random.randint(first,last) roll=a+b print("The sum is "+ str(roll) +'.')
919aec0ed45511239a23c00de6878b5f42228810
MCLeitao/Python-Exercises
/download-package/PythonExercises/ex088.py
883
3.984375
4
# Make a program that helps a PowerBall player to make guesses. The program will ask how many games will be generated # and will raffle 6 numbers between 1 and 60 for each game, registering everything in a composite list. from random import randint from time import sleep print('-' * 35) print(f'{"PLAY ON POWERBALL":^35}') print('-' * 35) amount = int(input('How many games do you want me to draw? ')) game = list() guesses = list() print(f'{" SORTING THE GAMES ":-^35}') for cont in range(0, amount): unity = 0 while True: number = randint(1, 60) if number not in game: game.append(number) unity += 1 if unity == 6: break game.sort() guesses.append(game[:]) game.clear() for index, game in enumerate(guesses): print(f'Game {index + 1}: {game}') sleep(1) print(f'{" < GOOD LUCK! > ":-^35}')
15cf7defa338dc596efdb1ffc9d71424fbad427a
Maaz-Mehtab/Python
/Assignment4/Question4.py
416
3.671875
4
# Question4 Write a function called favorite_book() that accepts one parameter, title. The function should print a # message, such as One of my favorite books is Alice in Wonderland. Call the function, making sure to # include a book title as an argument in the function call. def favorite_book(title): print(title + " is one of my favorite book.") favorite_book('Dead Until Dark (Sookie Stackhouse, #1)')
f53058f09a2e75b095ec3eda26b49963923431df
qmnguyenw/python_py4e
/geeksforgeeks/python/easy/26_3.py
5,175
4.09375
4
MongoDB Python – Insert and Replace Operations **Prerequisites :**MongoDB Python Basics This article focus on how to replace document or entry inside a collection. We can only replace the data already inserted in the database. **Method used :** replace_one() and replace_many() Aim: Replace entire data of old document with new document **Insertion In MongoDB** We would first insert data in MongoDB. __ __ __ __ __ __ __ # Python code to illustrate # Insert in MongoDB from pymongo import MongoClient try: conn = MongoClient() print("Connected successfully!!!") except: print("Could not connect to MongoDB") # database db = conn.database # Created or Switched to collection names: my_gfg_collection collection = db.my_gfg_collection emp_rec1 = { "name":"Mr.Geek", "eid":24, "location":"delhi" } emp_rec2 = { "name":"Mr.Shaurya", "eid":14, "location":"delhi" } emp_rec3 = { "name":"Mr.Coder", "eid":14, "location":"gurugram" } # Insert Data rec_id1 = collection.insert_one(emp_rec1) rec_id2 = collection.insert_one(emp_rec2) rec_id3 = collection.insert_one(emp_rec3) print("Data inserted with record ids",rec_id1," ",rec_id2,rec_id3) # Printing the data inserted cursor = collection.find() for record in cursor: print(record) --- __ __ Output: Connected successfully!!! Data inserted with record ids {'_id': ObjectId('5a02227b37b8552becf5ed2a'), 'name': 'Mr.Geek', 'eid': 24, 'location': 'delhi'} {'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name': 'Mr.Shaurya', 'eid': 14, 'location': 'delhi'} {'_id': ObjectId('5a02227c37b8552becf5ed2c'), 'name': 'Mr.Coder', 'eid': 14, 'location': 'gurugram'} **Replace_one()** After inserting the data let’s replace the Data of employee whose name : Mr.Shaurya __ __ __ __ __ __ __ # Python code to illustrate # Replace_one() in MongoDB from pymongo import MongoClient try: conn = MongoClient() print("Connected successfully!!!") except: print("Could not connect to MongoDB") # database db = conn.database # Created or Switched to collection names: my_gfg_collection collection = db.my_gfg_collection # replace one of the employee data whose name is Mr.Shaurya result = collection.replace_one( {"name":"Mr.Shaurya"}, { "name":"Mr.GfG", "eid":45, "location":"noida" } ) print("Data replaced with id",result) # Print the new record cursor = collection.find() for record in cursor: print(record) --- __ __ Connected successfully!!! Data replaced with id {'_id': ObjectId('5a02227b37b8552becf5ed2a'), 'name': 'Mr.Geek', 'eid': 24, 'location': 'delhi'} {'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name': 'Mr.GfG', 'eid': 45, 'location': 'noida'} {'_id': ObjectId('5a02227c37b8552becf5ed2c'), 'name': 'Mr.Coder', 'eid': 14, 'location': 'gurugram'} We have successfully replaced the document of employee name:’Mr.Shaurya’ and replaced the entire document with new one, name:’Mr.GfG’ (present). **Replace_many()** _Considering the data is same as inserted._ Replace all the data entries with eid:14. __ __ __ __ __ __ __ # Python code to illustrate # Replace_many() in MongoDB from pymongo import MongoClient try: conn = MongoClient() print("Connected successfully!!!") except: print("Could not connect to MongoDB") # database db = conn.database # Created or Switched to collection names: my_gfg_collection collection = db.my_gfg_collection # replace one of the employee data whose name is Mr.Shaurya result = collection.replace_many( {"eid":14}, { "name":"Mr.GfG", "eid":45, "location":"noida" } ) print("Data replaced with id",result) # Print the new record cursor = collection.find() for record in cursor: print(record) --- __ __ Output would have been: Connected successfully!!! Data replaced with id {'_id': ObjectId('5a02227b37b8552becf5ed2a'), 'name': 'Mr.Geek', 'eid': 24, 'location': 'delhi'} {'_id': ObjectId('5a02227c37b8552becf5ed2b'), 'name': 'Mr.GfG', 'eid': 45, 'location': 'noida'} {'_id': ObjectId('5a02227c37b8552becf5ed2c'), 'name': 'Mr.GfG', 'eid': 45, 'location': 'noida'} Here we can see both entries with eid:14 got replace with new data. (ObjectId will be different even if data is same). Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
7c1b3fbe6554c3d0216bad7c69765349615b71a4
fonoempresa/deep-learning-with-python
/forward_propagation.py
815
3.953125
4
import numpy as np print("Enter the two values for input layers") print('a = ') a = int(input()) # 2 print('b = ') b = int(input()) # 3 input_data = np.array([a, b]) # How are the weights created? # The model training process sets them to optimize predictive accuracy. weights = { 'node_0': np.array([1, 1]), 'node_1': np.array([-1, 1]), 'output_node': np.array([2, -1]) } node_0_value = (input_data * weights['node_0']).sum() # 2 * 1 +3 * 1 = 5 print('node 0_hidden: {}'.format(node_0_value)) node_1_value = (input_data * weights['node_1']).sum() # 2 * -1 + 3 * 1 = 1 print('node_1_hidden: {}'.format(node_1_value)) hidden_layer_values = np.array([node_0_value, node_1_value]) output_layer = (hidden_layer_values * weights['output_node']).sum() print("output layer : {}".format(output_layer))
0ebeb4427016605f51ccd68a03009b5cd7924bab
unclebae/python3-data-analysis
/ch02/columnStack2D.py
366
3.671875
4
# _*_ coding: utf-8 _*_ import numpy as num a = num.arange(9).reshape(3, 3) print ("num.arange(9).reshape(3, 3) : ", a) b = 2 * a print ("b = 2 * a : ", b) # column_stack print ("column_stack of 2D : column_stack( (a, b) ) : ", num.column_stack( (a, b) ) ) print ("compare column_stack of 2D and hstack : ", num.column_stack( (a, b) ) == num.hstack( (a, b) ) )
2caadd54e0ef3cf234fb5553ebc280d2b3a961dd
davidburdelak/exercises-studies
/python/task_5_1.py
1,455
4.375
4
""" Task: Sergeant Thomson decided to censor the letters his soldiers receive. This censorship involves removing every third line from the letter. Help the sergeant: write a program that receives a text file with a letter and creates its censored version - task_5_1_letter_censor.txt. The task_5_1_letter.txt file exists before, and the task_5_1_letter_censor.txt file is created by the program. """ file_write = open('task_5_1_letter_censor.txt','w') file_read = open('task_5_1_letter.txt','r') i=1 all_lines = file_read.readlines() for line in all_lines: #Reading all lines from a text file if i==1: file_write.write(line) i+=1 elif i==2: file_write.write(line) i+=1 elif i==3: i+=1 elif i==4: file_write.write(line) i+=1 elif i==5: file_write.write(line) i+=1 elif i==6: i+=1 elif i==7: file_write.write(line) i+=1 elif i==8: file_write.write(line) i+=1 elif i==9: i+=1 elif i==10: file_write.write(line) i+=1 elif i==11: file_write.write(line) i+=1 elif i==12: i+=1 elif i==13: file_write.write(line) i+=1 elif i==14: file_write.write(line) i+=1 elif i==15: i=1 file_write.close() file_read.close()
26a1f7779b40770d425f104fb7ec64accfcb3d2d
aaronbernal02/backup
/practice2.py
383
4.0625
4
# Aaron, Bernal # 9/27/19 Block 1 print("Input two numbers") num1 = int(input("Enter 1st digit ")) num2 = int(input("Enter 2nd digit ")) print (str(num1) + "+" + str(num2) + "=" + str(num1 + num2)) print (str(num1) + "*" + str(num2) + "=" + str(num1 * num2)) print (str(num1) + "/" + str(num2) + "=" + str(num1 / num2)) print (str(num1) + "-" + str(num2) + "=" + str(num1 - num2))
a04bac771101cee12134afd993d25cda0b09b01b
duckha/python_labs
/Lab3/Lab_1/Main.py
267
3.6875
4
class Square: def __init__(self, side): self.side = side def getP(self): return self.side * 4 def getS(self): return self.side ** 2 s = Square(5) s1 = Square(10) print("hello") print(s.getP()) print(s1.getP()) print(s1.getS())
0ff51c02eb3ef57e380b97ad10984b0a67d04d2b
liangel02/ccc2013
/q2.py
868
3.609375
4
totalWeight = int(input()) cars = int(input()) weightList = [] num = 0 for i in range(cars): weight = int(input()) weightList.append(weight) for i in range(len(weightList)): if i == 0: if weightList[i] > totalWeight: break else: weightOfOne = weightList[i] num = i + 1 elif i == 1: weightOfTwo = sum(weightList[i-1:i+1]) if weightOfTwo <= totalWeight: num = i + 1 else: break elif i == 2: weightOfThree = sum(weightList[i-2:i+1]) if weightOfThree <= totalWeight: num = i + 1 else: break elif i >= 3: weightOfFour = sum(weightList[i-3:i+1]) if weightOfFour <= totalWeight: num = i + 1 else: break print(num)
7a703fa6224c3c0aded4262764f25cafe00af146
kentronnes/python_crash_course
/python_work/Python Crash Course Chapter 4/4-11 my pizzas, your pizzas.py
423
4
4
pizzas = ['salami and olive', 'peperoni', 'supreme', 'bbq chicken'] for pizza in pizzas: print(pizza.title()) print("I like " + pizza.title() + " Pizza." + "\n") friend_pizzas = pizzas[:] pizzas.append('mushroom') friend_pizzas.append('sausage') print("\nMy favorite pizzas are:") for pizza in pizzas: print("\t" + pizza) print("\nMy friend's favorite pizzas are:") for pizza in friend_pizzas: print("\t" + pizza)
7e714fe4767d9d6553c8c01666582506d4a85fa1
OlehHnyp/Home_Work_10
/Home_Work_10_task_1.py
387
4.0625
4
age = input("Enter your age:") def even_odd(inf): try: inf = int(inf) if inf < 1: raise IndexError status = "odd" if inf%2 == 0: status = 'even' print(f"Your age is {status}") except ValueError: print("It's not a number") except IndexError: print("Age should be positive number") even_odd(age)
6a821fdccfb3ad277185cae15a15415cbe69ad35
alexaustin456/Preliminary-Code-for-Extended-Project
/is_prime.py
195
4.0625
4
def is_prime(): a = 2 num = int(input("Number:")) while num > a: if num % a == 0 & a != num: return False a += 1 else: return True is_prime()
fea242174ebccf75fbcceecee3ef4f636a485374
bomminisivaprasad/python-for-everybody-coursera-
/Course 3 - Using Python to access web data/ex12/scraping.py
848
3.9375
4
# This program scrapes a website for numbers and returns their count and sum. # Importing from urllib.request import urlopen from bs4 import BeautifulSoup import ssl # Initialising the count and total count = 0 total = 0 # Ignoring SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE # Asking user to input the URL url = input('Enter URL: ') html = urlopen(url, context=ctx).read() # Creating an organised string (soup) with BeautifulSoup soup = BeautifulSoup(html, "html.parser") # Retrieve all of the span tags tags = soup('span') for tag in tags: # Trying to convert the tag's content into integer try: total = total + int(tag.contents[0]) count = count + 1 except: continue # Printing the results print('Count',count) print('Sum',total)
de90606a0dc79fae1ed4eee5a67522827f403d7f
odremaer/some-exercises
/AAABBBCCC.py
215
3.5625
4
def f(s): res = s[0] cur = s[0] for i in range(1, len(s)): if cur == s[i]: pass else: cur = s[i] res += s[i] return res print(f("ABBBBCCCCDDF"))
5a6f61b22a3945ffbf225bb6d8620b574bbe48c0
MrHamdulay/csc3-capstone
/examples/data/Assignment_7/grgvic001/question1.py
377
3.953125
4
#enter values and return all unique values #victor gueorguiev #27 April 2014 def main(): xinput = input('Enter strings (end with DONE):\n') strlist = [] while xinput != 'DONE': if not xinput in strlist: strlist.append(xinput) xinput = input() print() print('Unique list:') for item in strlist: print(item) main()
4ff9cbeb10f734170e2923956d5bf4646f3bcd1f
TaylenH/learningProjects
/Zenva/Python/VariablesAndOperators/PurchasingReceipt.py
1,256
3.828125
4
#Project printing out a receipt for store purchases made by a customer. #Showcases knowledge of variable assigning and mathmatic operators. #descripton and price of store items lovely_loveseat_description = ''' Lovely Loveseat. Tufted polyester blend on wood. 32 inches high x 40 inches wide x 30 inches deep. Red or white.''' lovely_loveseat_price = 254.00 stylish_settee_description = ''' Stylish Settee. Faux leather on birch. 29.50 inches high x 54.75 inches wide x 28 inches deep. Black.''' stylish_settee_price = 180.50 luxurious_lamp_description = ''' Luxurious Lamp. Glass and iron. 36 inches tall. Brown with cream shade.''' luxurious_lamp_price = 52.15 sales_tax = .088 #customer one customer_one_total = 0 customer_one_itemization = "" #customer one purchases customer_one_total += lovely_loveseat_price customer_one_itemization += lovely_loveseat_description #customer one also buys Luxurious lamp customer_one_total += luxurious_lamp_price customer_one_itemization += luxurious_lamp_description #calculate tax customer_one_tax = customer_one_total * sales_tax customer_one_total += customer_one_tax #begin printing receipt print("Customer One Items:") print(customer_one_itemization) print("Customer One Total:") print(customer_one_total)
55c76712787458bc7a94eb768b20b3c288ae6f44
jasemabeed114/Python-work
/11.47.py
3,099
3.640625
4
from tkinter import * import random class largeBlock: def __init__(self): window = Tk() window.title("Find Largest Block") frame = Frame(window) frame.pack() frame2 = Frame(window) frame2.pack() self.v = [] for i in range(10): self.v.append([]) for j in range(10): self.v[i].append(IntVar()) self.e = [] for r in range(10): self.e.append([]) for c in range(10): x = random.randint(0,1) self.v[r][c].set(x) self.e[r].append(Entry(frame, width = 2, justify = RIGHT, textvariable = self.v[r][c])) self.e[r][c].grid(row = r, column = c) Button(frame2, text = "Refresh", command = self.refresh).pack(side = LEFT) Button(frame2, text = "Find Largest Block", command = self.large).pack(side = LEFT) window.mainloop() def refresh(self): self.v = [] for i in range(10): self.v.append([]) for j in range(10): self.v[i].append(IntVar()) self.v[i][j].set(random.randint(0,1)) for r in range(10): for c in range(10): self.e[r][c].configure(bg = "white") self.e[r][c].delete(0, END) self.e[r][c].insert(0, self.v[r][c].get()) def large(self): counter = 10 while counter > 0:#this will count down in block size finding the largest one its first and ending the loop for i in range(10 - counter +1): for j in range(10 - counter + 1): num = 0 numb = 0 for k in range(0, counter): if self.v[i][j+k].get() == 0: num +=1 elif self.v[i][j+k].get() == 1: numb += 1 if num == counter: print(i) print(j) for x in range(1, counter): for y in range(0, counter): if self.v[i+x][j+y].get() == 0: num +=1 if num == counter * counter : self.show(i, j, counter) return elif numb == counter: for x in range(1, counter): for y in range(0, counter): if self.v[i+x][j+y].get() == 1: numb +=1 if numb == counter * counter : self.show(i, j, counter) return counter -= 1 def show(self, i, j, counter): for r in range(counter): for c in range(counter): self.e[i+r][j+c].configure(bg = "red") self.e[i+r][j+c].update() largeBlock()
6ecfc2518badf9f84645211c6e61f12a0b69c798
f981113587/Python
/Aula 07/Desafios/010.py
276
3.84375
4
# Crie um programa que leia quanto dinheiro # uma pessoa tem na carteira e mostre quantos # dólares ela pode comprar. Consirede U$$ 1,00 = R$ 3,27 reais = float(input('Quantos R$ você tem ? ')) dolares = reais / 3.27 print('Você pode comprar US$ {:.2f}.'.format(dolares))
49a75e97c67535b1c7964bf2d2b3de41259acc2d
estherjulien/HybridML
/train_data_gen.py
4,201
3.734375
4
from NetworkGen.NetworkToTree import * from NetworkGen.LGT_network import * from datetime import datetime import pandas as pd import numpy as np import pickle import time import sys ''' Code used for generating train data. make_train_data: - Make a network and get data points by calling the function net_to_reduced_trees net_to_reduced_trees: - 1. Take all displayed trees from network, and set this as a tree set - 2. While stopping criterion not met: - reduce a (reticulated) cherry in the tree set and the network - make/update features for each cherry - label all cherries in tree set as: 0: if cherry (x, y) nor (y, x) is a cherry in the network 1: (x, y) is a cherry in the network 2: (x, y) is a reticulated cherry in the network 3: (y, x) is a reticulated cherry in the network - 3: Store all labelled data RUN in terminal: python train_data_gen.py <number of networks> <maxL> maxL: maximum number of leaves per network EXAMPLE: python train_data_gen.py 10 20 ''' def make_train_data(net_num=0, num_red=100, max_l=100, save_network=False): # 1. Make a network # params of LGT generator beta = 1 distances = True ret_num_max = 9 now = datetime.now().time() st = time.time() # choose n max_ret = 9 max_n = max_l - 2 + max_ret n = np.random.randint(1, max_n) tree_info = f"_maxL{max_l}_random" if n < 30: alpha = 0.3 elif n > 50: alpha = 0.1 else: alpha = 0.2 # make network network_gen_st = time.time() trial = 1 print(f"JOB {net_num} ({now}): Start creating NETWORK (maxL = {max_l}, n = {n})") while True: np.random.seed(0) net, ret_num = simulation(n, alpha, 1, beta, max_ret) num_leaves = len(leaves(net)) if ret_num < ret_num_max+1 and num_leaves <= max_l: break if time.time() - network_gen_st > 30*trial: print(f"JOB {net_num} ({now}): Start creating NEW NETWORK (maxL = {max_l}, n = {n})") n = np.random.randint(0, max_n) trial += 1 if save_network: with open(f"test_network_{net_num}.pickle", "wb") as handle: pickle.dump(net, handle) net_nodes = int(len(net.nodes)) now = datetime.now().time() print(f"JOB {net_num} ({now}): Start creating TREE SET (maxL = {max_l}, L = {num_leaves}, R = {ret_num})") num_rets = len(reticulations(net)) now = datetime.now().time() num_trees = 2 ** num_rets metadata_index = ["rets", "reductions", "tree_child", "nodes", "net_leaves", "chers", "ret_chers", "trees", "n", "alpha", "beta", "runtime"] print(f"JOB {net_num} ({now}): Start creating DATA SET (maxL = {max_l}, L = {num_leaves}, R = {ret_num}, T = {num_trees})") X, Y, num_cher, num_ret_cher, tree_set_num, tree_child = net_to_reduced_trees(net, num_red, num_rets, distances=distances, net_lvs=num_leaves) print(f"JOB {net_num} ({now}): DATA GENERATION NETWORK FINISHED in {np.round(time.time() - st, 3)}s " f"(maxL = {max_l}, L = {num_leaves}, TC = {tree_child}, R = {ret_num}, T = {num_trees}, X = {len(X)})") metadata = pd.Series([num_rets, num_red, tree_child, net_nodes, num_leaves, np.mean(num_cher), np.mean(num_ret_cher), np.mean(num_ret_cher), n, alpha, beta, time.time() - st], index=metadata_index, dtype=float) output = {"net": net, "X": X, "Y": Y, "metadata": metadata} with open( f"Data/Train/inst_results/ML_tree_data{tree_info}_{net_num}.pickle", "wb") as handle: pickle.dump(output, handle) if __name__ == "__main__": net_num = int(sys.argv[1]) max_l = int(sys.argv[2]) make_train_data(net_num=net_num, max_l=max_l)
96ce66dac074380f8745904a37802b1338a9fed3
DurdenTyler2008/Tasks_Python
/9.py
809
3.859375
4
#матрица,закрутить против часовой стрелки(надо сделать так): # 1 8 7 1 2 3 # 2 9 6 из 4 5 6 # 3 4 5 7 8 9 m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for i in range (len(m)): for j in range(len(m)): if i == 2: if j==0: print('1:',m[j][0],m[i][1],m[i][0]) for i in range (len(m)): for j in range(len(m)): for k in range(len(m)): if i == 0: if j == 1: if k == 2: print('2:',m[i][1],m[k][2],m[j][2]) for i in range (len(m)): for j in range(len(m)): if i == 0: if j == 1: print('3:',m[i][2],m[j][0],m[j][1]) #rezult: 1: 1 8 7 #rezult: 2: 2 9 6 #rezult: 3: 3 4 5
e18776b85243ba60d81ab04d3addc17c70207992
19990423whs/AIDVN2005
/dir/demo.py
614
3.640625
4
""" python 操作 mysql 流程演示 """ import pymysql # 1. 创建数据库连接对象 --> 关键字参数 db= pymysql.connect( host='localhost', port=3306, user='root', passwd='123456', database='student', charset='utf8' ) # 2. 生成游标对象 (游标对象用于执行sql语句,获取执行结果) cur = db.cursor() # 3. 执行sql 语句 # 写操作 --> 增删改 sql = "insert into class_1 values (7,'Tom',13,'w',93);" cur.execute(sql) db.commit() # 4. 关闭游标和数据库对象 cur.close() db.close()
0ce81e87585e72570e101fd960272c12dd11983b
imranzahid81/Python
/8 loops.py
3,068
4.84375
5
# http://www.learnpython.org/en/Loops # Loops # "for" loop # For loops iterate over a given sequence. Here is an example: primes = [2, 3, 5, 7] for prime in primes: print(prime) """ # FOR PYTHON 3 in order to get list from string use syntax : list(range(1,100)) # For loops can iterate over a sequence of numbers using the "range" and "xrange" functions. The difference between range and xrange is that the range function returns a new list with numbers of that specified range, whereas xrange returns an iterator, which is more efficient. # Prints out the numbers 0,1,2,3,4 for x in xrange(5): # or range(5) ##### FOR PYTHON 2 ONLY ##### print(x) # Prints out 3,4,5 for x in xrange(3, 6): # or range(3, 6) print(x) # Prints out 3,5,7 for x in xrange(3, 8, 2): # or range(3, 8, 2) print(x) """ # FOR PYTHON 3 in order to get list use syntax : list(range(1,100)) # Prints out the numbers 0,1,2,3,4 for x in range(1, 5): # or range(5) ##### FOR PYTHON 2 ONLY ##### print("Prints out the numbers 0,1,2,3,4 : " + str(x)) # Prints out 3,4,5 for x in range(3, 4, 5): # or range(3, 6) print("Prints out 3,4,5 : " + str(x)) # Prints out 3,5,7 for x in range(4, 25, 7): # or range(3, 8, 2) print("Prints out 3,5,7 : " + str(x)) # Converting python range() to list print("Converting python range() to list") even_list = list(range(2, 10, 2)) print("Printing List", even_list) # "while" loops ################################## # Prints out 0,1,2,3,4 count = 0 while count < 5: print('"while" loops Prints out increment with += : ' + str(count)) count += 1 # This is the same as count = count + 1 # "break" and "continue" statements # break is used to exit a for loop or a while loop, whereas continue is used to skip the current block, and return to the "for" or "while" statement. A few examples: # Prints out 0,1,2,3,4 count = 0 while True: print('"while" loops Prints out increment with Bolean : ' + str(count)) count += 1 if count >= 5: break # Prints out only odd numbers - 1,3,5,7,9 for x in range(10): # Check if x is even if x % 2 == 0: continue print("Prints out only odd numbers 1 to 9 : " + str(x)) # can we use "else" clause for loops? # unlike languages like C,CPP.. we can use else for loops. When the loop condition of "for" or "while" statement fails then code part in "else" is executed. If break statement is executed inside for loop then the "else" part is skipped. Note that "else" part is executed even if there is a continue statement. # Here are a few examples: # Prints out 0,1,2,3,4 and then it prints "count value reached 5" count = 0 while (count < 5): print('"while" loops Prints out increment with += along else condition : ' + str(count)) count +=1 else: print("else condition : count value reached %d" % (count)) # Prints out 1,2,3,4 for i in range(1, 5): if (i % 5 == 0): break print(i) else: print("this is not printed because for loop is terminated because of break but not due to fail in condition")
97e1b1224388f4a0a848dcaf9b663e1ce76f2410
Duologic/python-deployer
/deployer/console.py
16,693
3.9375
4
""" The ``console`` object is an interface for user interaction from within a ``Node``. Among the input methods are choice lists, plain text input and password input. It has output methods that take the terminal size into account, like pagination and multi-column display. It takes care of the pseudo terminal underneat. Example: :: class MyNode(Node): def do_something(self): if self.console.confirm('Should we really do this?', default=True): # Do it... pass .. note:: When the script runs in a shell that was started with the ``--non-interactive`` option, the default options will always be chosen automatically. """ from deployer import std from termcolor import colored from datetime import datetime import random __all__ = ('Console', 'NoInput', 'ProgressBarSteps', 'ProgressBar', ) class NoInput(Exception): pass class Console(object): """ Interface for user interaction from within a ``Node``. :param pty: :class:`deployer.pseudo_terminal.Pty` instance. """ def __init__(self, pty): self._pty = pty @property def pty(self): """ The :class:`deployer.pseudo_terminal.Pty` of this console. """ return self._pty @property def is_interactive(self): """ When ``False`` don't ask for input and choose the default options when possible. """ return self._pty.interactive def input(self, label, is_password=False, answers=None, default=None): """ Ask for plain text input. (Similar to raw_input.) :param is_password: Show stars instead of the actual user input. :type is_password: bool :param answers: A list of the accepted answers or None. :param default: Default answer. """ stdin = self._pty.stdin stdout = self._pty.stdout def print_question(): answers_str = (' [%s]' % (','.join(answers)) if answers else '') default_str = (' (default=%s)' % default if default is not None else '') stdout.write(colored(' %s%s%s: ' % (label, answers_str, default_str), 'cyan')) stdout.flush() def read_answer(): value = '' print_question() while True: c = stdin.read(1) # Enter pressed if c in ('\r', '\n') and (value or default): stdout.write('\r\n') break # Backspace pressed elif c == '\x7f' and value: stdout.write('\b \b') value = value[:-1] # Valid character elif ord(c) in range(32, 127): stdout.write(colored('*' if is_password else c, attrs=['bold'])) value += c elif c == '\x03': # Ctrl-C raise NoInput stdout.flush() # Return result if not value and default is not None: return default else: return value with std.raw_mode(stdin): while True: if self._pty.interactive: value = read_answer() elif default is not None: print_question() stdout.write('[non interactive] %r\r\n' % default) stdout.flush() value = default else: # XXX: Asking for input in non-interactive session value = read_answer() # Return if valid anwer if not answers or value in answers: return value # Otherwise, ask again. else: stdout.write('Invalid answer.\r\n') stdout.flush() def choice(self, question, options, allow_random=False, default=None): """ :param options: List of (name, value) tuples. :type options: list :param allow_random: If ``True``, the default option becomes 'choose random'. :type allow_random: bool """ if len(options) == 0: raise NoInput('No options given.') if allow_random and default is not None: raise Exception("Please don't provide allow_random and default parameter at the same time.") # Order options alphabetically options = sorted(options, key=lambda i:i[0]) # Ask for valid input while True: self._pty.stdout.write(colored(' %s\n' % question, 'cyan')) # Print options self.lesspipe(('%10i %s' % (i+1, tuple_[0]) for i, tuple_ in enumerate(options))) if allow_random: default = 'random' elif default is not None: try: default = [o[1] for o in options ].index(default) + 1 except ValueError: raise Exception('The default value does not appear in the options list.') result = self.input(question, default=('random' if allow_random else default)) if allow_random and result == 'random': return random.choice(options)[1] else: try: result = int(result) if 1 <= result <= len(options): return options[result - 1][1] except ValueError: pass self.warning('Invalid input') def confirm(self, question, default=None): """ Print this yes/no question, and return ``True`` when the user answers 'Yes'. """ answer = 'invalid' if default is not None: assert isinstance(default, bool) default = 'y' if default else 'n' while answer not in ('yes', 'no', 'y', 'n'): answer = self.input(question + ' [y/n]', default=default) return answer in ('yes', 'y') # # Node selector # def select_node(self, root_node, prompt='Select a node', filter=None): """ Show autocompletion for node selection. """ from deployer.cli import ExitCLILoop, Handler, HandlerType, CLInterface class NodeHandler(Handler): def __init__(self, node): self.node = node @property def is_leaf(self): return not filter or filter(self.node) @property def handler_type(self): class NodeType(HandlerType): color = self.node.get_group().color return NodeType() def complete_subhandlers(self, part): for name, subnode in self.node.get_subnodes(): if name.startswith(part): yield name, NodeHandler(subnode) def get_subhandler(self, name): if self.node.has_subnode(name): subnode = self.node.get_subnode(name) return NodeHandler(subnode) def __call__(self, context): raise ExitCLILoop(self.node) root_handler = NodeHandler(root_node) class Shell(CLInterface): @property def prompt(self): return colored('\n%s > ' % prompt, 'cyan') not_found_message = 'Node not found...' not_a_leaf_message = 'Not a valid node...' node_result = Shell(self._pty, root_handler).cmdloop() if not node_result: raise NoInput return self.select_node_isolation(node_result) def select_node_isolation(self, node): """ Ask for a host, from a list of hosts. """ from deployer.inspection import Inspector from deployer.node import IsolationIdentifierType # List isolations first. (This is a list of index/node tuples.) options = [ (' '.join([ '%s (%s)' % (h.slug, h.address) for h in hosts ]), node) for hosts, node in Inspector(node).iter_isolations(identifier_type=IsolationIdentifierType.HOST_TUPLES) ] if len(options) > 1: return self.choice('Choose a host', options, allow_random=True) else: return options[0][1] def lesspipe(self, line_iterator): """ Paginator for output. This will print one page at a time. When the user presses a key, the next page is printed. ``Ctrl-c`` or ``q`` will quit the paginator. :param line_iterator: A generator function that yields lines (without trailing newline) """ stdin = self._pty.stdin stdout = self._pty.stdout height = self._pty.get_size()[0] - 1 with std.raw_mode(stdin): lines = 0 for l in line_iterator: # Print next line stdout.write(l) stdout.write('\r\n') lines += 1 # When we are at the bottom of the terminal if lines == height: # Wait for the user to press enter. stdout.write(colored(' Press enter to continue...', 'cyan')) stdout.flush() try: c = stdin.read(1) # Control-C or 'q' will quit pager. if c in ('\x03', 'q'): stdout.write('\r\n') stdout.flush() return except IOError: # Interupted system call. pass # Move backwards and erase until the end of the line. stdout.write('\x1b[40D\x1b[K') lines = 0 stdout.flush() def in_columns(self, item_iterator, margin_left=0): """ :param item_iterator: An iterable, which yields either ``basestring`` instances, or (colored_item, length) tuples. """ # Helper functions for extracting items from the iterator def get_length(item): return len(item) if isinstance(item, basestring) else item[1] def get_text(item): return item if isinstance(item, basestring) else item[0] # First, fetch all items all_items = list(item_iterator) if not all_items: return # Calculate the longest. max_length = max(map(get_length, all_items)) + 1 # World per line? term_width = self._pty.get_size()[1] - margin_left words_per_line = max(term_width / max_length, 1) # Iterate through items. margin = ' ' * margin_left line = [ margin ] for i, j in enumerate(all_items): # Print command and spaces line.append(get_text(j)) # When we reached the max items on this line, yield line. if (i+1) % words_per_line == 0: yield ''.join(line) line = [ margin ] else: # Pad with whitespace line.append(' ' * (max_length - get_length(j))) yield ''.join(line) def warning(self, text): """ Print a warning. """ stdout = self._pty.stdout stdout.write(colored('*** ', 'yellow')) stdout.write(colored('WARNING: ' , 'red')) stdout.write(colored(text, 'red', attrs=['bold'])) stdout.write(colored(' ***\n', 'yellow')) stdout.flush() def progress_bar(self, message, expected=None, clear_on_finish=False, format_str=None): """ Display a progress bar. This returns a Python context manager. Call the next() method to increase the counter. :: with console.progress_bar('Looking for nodes') as p: for i in range(0, 1000): p.next() ... :returns: :class:`ProgressBar` instance. :param message: Text label of the progress bar. """ return ProgressBar(self._pty, message, expected=expected, clear_on_finish=clear_on_finish, format_str=format_str) def progress_bar_with_steps(self, message, steps, format_str=None): """ Display a progress bar with steps. :: steps = ProgressBarSteps({ 1: "Resolving address", 2: "Create transport", 3: "Get remote key", 4: "Authenticating" }) with console.progress_bar_with_steps('Connecting to SSH server', steps=steps) as p: ... p.set_progress(1) ... p.set_progress(2) ... :param steps: :class:`ProgressBarSteps` instance. :param message: Text label of the progress bar. """ return ProgressBar(self._pty, message, steps=steps, format_str=format_str) class ProgressBarSteps(object): # TODO: unittest this class. def __init__(self, steps): # Validate for k,v in steps.items(): assert isinstance(k, int) assert isinstance(v, basestring) self._steps = steps def get_step_description(self, step): return self._steps.get(step, '') def get_steps_count(self): return max(self._steps.keys()) class ProgressBar(object): interval = .1 # Refresh interval def __init__(self, pty, message, expected=None, steps=None, clear_on_finish=False, format_str=None): if expected and steps: raise Exception("Don't give expected and steps parameter at the same time.") self._pty = pty self.message = message self.counter = 0 self.expected = expected self.clear_on_finish = clear_on_finish self.done = False self._last_print = datetime.now() # Duration self.start_time = datetime.now() self.end_time = None # In case of steps if steps is not None: assert isinstance(steps, ProgressBarSteps) self.expected = steps.get_steps_count() self.steps = steps # Formatting if format_str: self.format_str = format_str elif self.expected: self.format_str = '%(message)s: %(counter)s/%(expected)s [%(percentage)s completed] [%(duration)s] [%(status)s]' else: self.format_str = '%(message)s: %(counter)s [%(duration)s] [%(status)s]' def __enter__(self): self._print() return self def _print(self): # Calculate percentage percentage = '??' if self.expected and self.expected > 0: percentage = '%s%%' % (self.counter * 100 / self.expected) # Calculate duration duration = (self.end_time or datetime.now()) - self.start_time duration = str(duration).split('.')[0] # Don't show decimals. status = colored(( 'DONE' if self.done else self.steps.get_step_description(self.counter) if self.steps else ''), 'green') format_str = '\r\x1b[K' + self.format_str + '\r' # '\x1b[K' clears the line. self._pty.stdout.write(format_str % { 'message': self.message, 'counter': self.counter, 'duration': duration, 'counter': self.counter, 'expected': self.expected, 'percentage': percentage, 'status': status , }) def next(self): """ Increment progress bar counter. """ self.set_progress(self.counter + 1, rewrite=False) def set_progress(self, value, rewrite=True): """ Set counter to this value. :param rewrite: Always redraw the progress bar. :type rewrite: bool """ self.counter = value # Only print when the last print was .3sec ago delta = (datetime.now() - self._last_print).microseconds / 1000 / 1000. if rewrite or delta > self.interval: self._print() self._last_print = datetime.now() def __exit__(self, *a): self.done = True self.end_time = datetime.now() if self.clear_on_finish: # Clear the line. self._pty.stdout.write('\x1b[K') else: # Redraw and keep progress bar self._print() self._pty.stdout.write('\n')
e47b48cecb443ebaf6dd71b3bc40cb3d7ae1c4da
G-Jarvey/base-python
/列表元素个数的加权和(1).py
226
3.59375
4
lst = eval(input()) def f(lst,level): sum = 0 for i in lst: if type(i) == int: sum = sum + level else: sum = sum + f(i,level+1) return sum sum = f(lst,1) print(sum)
08e0f11ec04dda78c02d3954cdfa85c35ace9066
brendanmarko/Pygame
/Race/Code/Position.py
741
3.734375
4
# Position.py # Serves as storage for a position (or any data type with two fields!) class Position(object): 'serves as storage for a position (or any structure with two points)' def __init__(self, x, y): # Debug info self.DEBUG=1 self.DEBUG_TAG="[Position]" if (self.DEBUG == 1): print(self.DEBUG_TAG + ":init") self.curr_pos=[x,y] def getX(self): return self.curr_pos[0] def getY(self): return self.curr_pos[1] def updateStorage(self, new_x, new_y): self.curr_pos[0]=new_x self.curr_pos[1]=new_y def getStorage(self): return self.curr_pos def printPos(self): if (self.DEBUG == 1): print(self.DEBUG_TAG + ":X=" + str(self.getX()) + ", Y=" + str(self.getY()))
695d3fb99dfe0af1ba3d93e2a91ac1f7cb7b4aee
KirillGukov/edu_epam
/hw3/tasks/task_1.py
1,488
4.0625
4
"""In previous homework task 4, you wrote a cache function that remembers other function output value. Modify it to be a parametrized decorator, so that the following code: @cache(times=3) def some_function(): pass Would give out cached value up to times number only. """ from typing import Callable def cache(times=None) -> Callable: """ take 1 function and cache result with count = times :arg: func: any callable :return: decorated func: callable """ def cached_func(func): cached_value_dict = {} if times: cache_counter = times def some_func(*args, **kwargs): # if func had already called with this args return cache if (args, tuple(kwargs.items())) in cached_value_dict: # takes counter from outside function nonlocal cache_counter if cache_counter > 1: cache_counter -= 1 return cached_value_dict[(args, tuple(kwargs.items()))] else: # return value last time and delete if from dict return cached_value_dict.pop((args, tuple(kwargs.items()))) else: # add value to cache if it isn't in it cached_value_dict[(args, tuple(kwargs.items()))] = func(*args, **kwargs) return cached_value_dict[(args, tuple(kwargs.items()))] return some_func return cached_func
d137b70e471898c1aedc82368663b79afb310f44
YouriTjang/INFDEV02-2
/Code samples from the lectures/Lecture01/Player_class.py
1,019
3.890625
4
class player: def __init__(self, name, posX, posY): self.name = name self.positionX = posX self.positionY = posY # Met de __str__-methode kan je aangeven hoe je deze class wil printen def __str__(self): return "Player {} is at position ({}, {})".format(self.name, self.positionX, self.positionY) class stukje: def __init__(self, grootte, icoon, locatie): self.grootte = grootte self.icoon = icoon self.locatie = locatie def __str__(self): return "{} - {} - {}".format(self.grootte, self.icoon, self.locatie) # Maak een concrete instance van de stukje-class stukje1 = stukje(3, "zwaard", 10) # Maak een paar concrete instances van de player-class playerOne = player("P1", 0.0, 10) playerTwo = player("P2", 5.0, 0.0) playerThree = player("P3", 10.0, 0.0) # Hiermee wordt de __str__-methode aangeroepen print playerOne # Zo kun je variabelen van een class aanroepen en printen print playerOne.name print playerOne.positionX
99d75561ca5d66aa65a0d4c7383b4bc353b3f8e6
kuchunbk/PythonBasic
/7_Conditional Statements and loops/Sample/conditional_ex40.py
893
4.0625
4
'''Question: Write a Python program to find the median of three values. ''' # Python code: a = float(input("Input first number: ")) b = float(input("Input second number: ")) c = float(input("Input third number: ")) if a > b: if a < c: median = a elif b > c: median = b else: median = c else: if a > c: median = a elif b < c: median = b else: median = c print("The median is", median) '''Output sample: Input first number: 25 Input second number: 55 Input third number: 65 The median is 55.0 '''
67a23e86d468db1d29cd83333cba27a17c181ddc
andrewyager/python-asterisk-dialplan
/asterisk_dialplan/ranges.py
2,710
3.671875
4
from .util import common_start import math def split_range(low, high): """ Take a range of telephone numbers in E.164 format between low and high and return the "safe" chunks for the pattern matching script to use :param low: telephone number in E164 format :type low: integer :param high: telephoen number in E164 format :type high: integer :returns: list of integer tuples for pattern chunking :rtype: list """ from .dialplan_exceptions import DialplanException # start by ensuring our arguments are integers low = int(low) high = int(high) # get string representations of numbers fn_string = str(low) ln_string = str(high) if len(fn_string) != len(ln_string): # the pattern to match is not valid raise DialplanException("First and last numbers are not of equal length") if low > high: raise DialplanException("Last number is smaller than the first number") if low == high: return [(low, high)] patterns = [] # lets work out the number of significant digits pattern = common_start(low, high) digit_start = int(len(pattern)) digits = len(str(low)) - len(pattern) strip_digits = int(digits * -1) remaining_fn = fn_string[strip_digits:] remaining_ln = ln_string[strip_digits:] remaining_fn_int = int(remaining_fn) remaining_ln_int = int(remaining_ln) last_of_first_range = int( math.ceil(float(remaining_fn_int / math.pow(10, digits - 1))) * math.pow(10, digits - 1) ) first_of_last_range = int( math.floor(float((remaining_ln_int + 1) / math.pow(10, digits - 1))) * math.pow(10, digits - 1) ) if remaining_fn_int != last_of_first_range: low = pattern + str(remaining_fn_int).zfill(int(digits)) high = pattern + str(last_of_first_range - 1).zfill(int(digits)) if strip_digits == 1: patterns.append((int(low), int(high))) else: patterns.extend(split_range(int(low), int(high))) if last_of_first_range != first_of_last_range: # we have a range in the middle low = pattern + str(last_of_first_range).zfill(int(digits)) high = pattern + str(first_of_last_range - 1).zfill(int(digits)) patterns.append((int(low), int(high))) if (first_of_last_range - 1) != remaining_ln_int: low = pattern + str(first_of_last_range).zfill(int(digits)) high = pattern + str(remaining_ln_int).zfill(int(digits)) if strip_digits == 1 or low == high: patterns.append((int(low), int(high))) else: patterns.extend(split_range(int(low), int(high))) return patterns
684cfb0e95213ea794c7168edc53aa4dd0b2284d
puccash/py_projects
/basic/p2.py
4,165
3.578125
4
# 단일 데이터(단일 타입) # 문자열(연속이지만, 이쪽으로도 분류한다) # 표기법 # '....' , "....." , '''.....''' , """.......""" # '''....''' , """.....""" 용도 : 여러줄 표현, 구조유지, 여러줄 주석용 a = 'hi' print(a) a = "hi" print(a) # 혼용 표현 a = 'abcd"KKK"efg' print(a) # 이스케이프 문자로 동일 기호를 내부에서 사용 가능 a = 'abcd\kkk\efg' print(a) # 여러줄 사용 a = ''' asdfs safwwd erw2fs2 4r32ed ''' print(a) """ 여러줄 주석 """ # 문자열 더하기 (이어 붙이기) <--> 문자열 안의 문자열(포멧팅) a = 'hello' b = 'mint' print(a+b) # 문자열 반복 print('1'*10) # 인덱싱 : Indexing : 문자열에서 특정 문자를 획득하는 방식 >> 차원 축소 # 문법 : 변수명[인덱스(정방향 or 역방향)] >> 방향의 기준은 가까운 쪽에서 시작 a = '0123456789' # a에서 2를 출력하기 print(a[2]) print(a[-8]) # : 뒷쪽에서부터는 멀기 때문에 가까운쪽에서 해결할 것 # 슬라이싱 : 데이터에서 범위에 해당되는 데이터를 획득 >> 차원 유지 # 문법 : 변수[ 시작인덱스:끝인덱스:step ] >> step : cut 간격, 생략시 defalut 값 1 # a를 카피한다 print(a[:]) # 1 부터 8 까지 출력하기 # 뒷쪽의 경계값은 포함되지 않는다. print(a[-1],a[1]) # a <= < b print(a[1:-1]) print(a[1:-1:3]) url = 'https://cdn.clien.net/web/api/file/F01/2475133/20067898062c482492e.JPG' # 위의 이러한 문자열의 파일명 추출, 도메인 추출 등등 사용가능 print(a[:2],a[-2:]) # 멤버함수 (문자열) a = '0123456789' # 문자열 내의 특정 문자 갯수 파악하기 print('a라는 문자열의 3의 갯수', a.count('3')) print('a라는 문자열의 -1의 갯수', a.count('-1')) # 값이 없으면 0 이 나타난다 print('a라는 문자열의 A의 갯수', a.count('A')) # a라는 문자열에 "A"라는 문자가 존재하는가? print(a.count('A')>0) print(a.index('2')) # 에러 및 없는 문자는 예외처리가 필요하다. # print(a.index('A')) print(a.find('2')) print(a.find('A')) # 문자열 내에서 문자열 찾기는 count(), find()를 사용할 것. b = ',' # 조인 print(b.join(a)) # 분해 print(b.join(a).split(b)) # 공백제거 a = ' sdsd ' print('[%s]'%a.rstrip()) print('[%s]'%a.lstrip()) print('[%s]'%a.strip()) # 가운데 공백 제거 >> 정규식 # 대소문자 a = 'asdasASDF가나다라1234!@#$' print(a.upper()) print(a.lower()) # 조합 사용 url = 'https://cdn.clien.net/web/api/file/F01/2475133/20067898062c482492e.JPG' # >> image.png (or jpg) 라는 문자열을 획득. 리스트 인덱싱 사용 # 단 상수값은 사용하지 않는다. # 이미지 값을 구해가는 과정 tmp = url.split('/') print(url.split('/')) print(url.split('/')[-1] ) print(tmp) print(len(tmp)) print(tmp[-1]) print(tmp[len(tmp)-1]) print(url.count('/')) print(url.split('/')[url.count('/')]) # 포멧팅 a=1 b=2 # x+y=z 형식으로 출력하기 print('%d+%d=%d' % (a,b,a+b) ) # %s를 사용하는 경우 : 데이터가 문자열일떼, 데이터의 타입을 모를 때. print('%s+%s=%s' % (a,b,a+b) ) print('%d/%d=%f' % (a,b,a/b) ) print('%d/%d=%s' % (a,b,a/b) ) # .format() 처리 print( '{}+{}={}'.format(a, b, a+b) ) print( '{0}+{1}={2}'.format(a,b,a+b)) print( '{1}+{0}={2}'.format(a, b, a+b) ) # format 의 파라미터를 모두 다 쓸 필요는 없다. print( '{1}+{1}={1}'.format(a, b, a+b) ) print( '{0}+{1}={result}'.format(a, b, result=a+b) ) # print(result) >>> Error # 포멧팅, 자리수 체크 print('[%s]'%'12345') # 20칸에 배치 시, print('[%20s]'%'12345') # 앞 쪽 정렬 print('[%-20s]'%'12345') # 뒷 쪽 정렬 print('[%0.2f]'%3.145625) # 반올림 >> 수치 변경 print('[%10.2f]'%3.145625) print('[%10.2f]'%3.145625) # 뒷쪽 정렬 print('[%10s]'%'12345') # 치환식 a = 'abc()efg'.format('k') print(a) # 자릿수 10개 a = 'abc{0:<10}efg'.format('k') print(a) a = 'abc{0:>10}efg'.format('k') print(a) # 짝수칸일 경우, 앞쪽으로 센터 위치 a = 'abc{0:^10}efg'.format('k') print(a) # *로 빈칸 채우기 a = 'abc{0:*^10}efg'.format('K') print( a )
a39d4cc47fe0f706797e14380f0a62892fd7120e
nicolasgonzalez98/Ejercicios-Python-de-Informatica-UBA-
/TP 7/ej7.py
350
3.625
4
def elim_cadenas(a): a=a.split(" ") b=list(a) print(b) cad=input("Ingrese una cadena a eliminar: ") for i in range(len(b)-1): if b[i]==cad: b.pop(i) for i in range(len(b)): if b[i]==cad: b.pop(i) b=" ".join(b) return b texto="Danilo se fue a Paris" print(elim_cadenas(texto))
4f14c34cb64ef7daf0cb7f0e68376142392d61e6
cifpfbmoll/practica-5-python-fperi90
/P5ej1.py
295
3.921875
4
for i in range(10): print(i+1,end=" ") print ("\n") for i in range(10): print((i+1)*2,end=" ") print("\n") for i in range(10): print(20+(i*2),end=" ") print("\n") for i in range(6): print(10+(i*4),end=" ") print("\n") for i in range(9): print(40-(i*5),end=" ")
d53fc8e0c349d1553535b7b502692e7585ff1225
arara90/AlgorithmAndDataStructure
/Practice_python/Graph/서로소집합자료구조.py
1,767
3.71875
4
# 특정원소가 속한 집합 찾기 (x는 노드번호) def find_parent(parent, x): # 루트 노드 찾을 때까지 재귀 if parent[x] != x: return find_parent(parent, parent[x]) return x # 두 원소가 속한 집합 합치기 def union_parent(parent, a, b): a = find_parent(parent, a) b = find_parent(parent, b) if a < b: parent[b] = a else: parent[a] = b # 노드의 개수와 간선(Union연산)의 개수 입력받기 v, e = map(int, input().split()) parent = [0] * (v+1) # 부모테이블 초기화 # 부모 테이블 상에서 부모를 자기 자신으로 초기화 for i in range(1, v+1): parent[i] = i # Union연산을 각각 수행 for i in range(e): a, b = map(int, input().split()) union_parent(parent, a, b) print('각 원소가 속한 집합: ', end='') for i in range(1, v+1): print(find_parent(parent, i), end='') print() # 부모테이블내용 출력 print('부모테이블 : ', end='') for i in range(1, v+1): print(parent[i], end='') # #문제점 # 합집합(union)연산 # 이 편향되게 이루어지는 경우 찾기(Find)함수가 비효율적으로 동작 # 최악의 경우에는 찾기(Find)함수가 모든 노드를 다 확인하게 되어 시간 복잡도 O(V) # union(4,5),union(3,4),union(2,3),union(1,2) # 1<-2<-3<-4<-5 의경우 # 1,2,3,4,5 # 1,1,2,3,4 # 경로압축기법 # -> 찾기 함수를 재귀함수로 호출한 뒤에 부모 테이블 값을 바로 갱신 def find_parent2(parent, x): # 루트 노드가 아니라면, 루트 노드를 찾을 때까지 재귀적으로 호출 if parent[x] != x: parent[x] = find_parent(parent, parent[x]) return parent[x] # 1,2,3,4,5 # 1,1,1,1,1 <=요런식으로 된다.
3aff6aa43c7c40b447419fa01c6e7589eb5ca2e4
Cleber-Woheriton/Python-Mundo-1---2-
/desafioAula029.py
543
3.734375
4
#(Desafio 29) Escreva um programa que leia a velovidade de um carro. # se ultrapassar 80km. Mostre uma msg dizendo que ele foi multado. # A multa irá custar R$ 7.00 por cada km acima do limite. print('*-'*15, 'Programa de Velocidade', '*-'*15) vel = int(input('Informe a velocidade: ')) # if verificando se a velocidade é maior que 80Km if vel > 80: acm = vel - 80# acm recebendo os Km acima dos 80Km print(f'\033[31m{vel} Km. Você foi multado o valor a pagar R$\033[33m {7 * acm}') else: print('\033[32mVelocidade permitida!')
d9444af2df03c1c731834223d41472842321f617
iajalil/tkinter-demo
/#TASK 2.py
2,050
4.03125
4
#importing tkinter for our interface design import tkinter as tk #using the alias tk instead of the normal tkinter from tkinter import ttk from tkinter.ttk import * #create an instance of tk win = tk.Tk() #Giving the window a title win.title(' App title') ttk.Label(win).grid( column=3 , row = 0) #creating an empty space ttk.Label(win).grid( row=0) #Setting our FNAME labels and input boxes lblFNAME = ttk.Label (win, text = "FNAME:") lblFNAME.grid(column=1 , row= 1) #creating an empty space ttk.Label(win).grid (row=2) #setting or FNAME textbox FName=tk.StringVar() txtFNAME = ttk.Entry(win, width= 16, textvariable=FName) txtFNAME.grid(column =3, row =1) #setting our LNAME labels and input boxes lblLNAME = ttk.Label(win,text = "LNAME: ") lblLNAME.grid(column=1, row=3) #creating an empty space ttk.Label(win).grid (row=4) #setting our LNAME textbox Lname = tk.StringVar() txtLNAME = ttk.Entry(win, width=16, textvariable= Lname) txtLNAME.grid(column=3, row=3) #setting our EMAIL labels and input boxes lblEMAIL = ttk.Label(win,text = "EMAIL: ") lblEMAIL.grid(column=1, row=5) #creating an empty space ttk.Label(win).grid (row=6) #setting our EMAIL textbox Email = tk.StringVar() txtEMAIL = ttk.Entry(win, width=16, textvariable= Email) txtEMAIL.grid(column=3, row=5) #setting our PASSD labels and input boxes lblPASSD = tk.Label(win, text ="PASSD:") lblPASSD.grid(column=1, row=7) #creating an empty space ttk.Label(win).grid (row=8) #setting our PASSD text box Passd = tk.StringVar() txtPASSD =ttk.Entry(win, width=16, textvariable=Passd) txtPASSD.grid(column=3, row=7) #Creating an empty space tk.Label(win).grid(row=9) #setting up our SUBMIT button btnSUBMIT =ttk.Button(win, width= 10, text="SUBMIT" ) btnSUBMIT.grid(column=1, row=10) #btnSUBMIT.configure(background="#00FFF00") #btnSUBMIT.pack() #setting up our RESET button btnRESET =ttk.Button(win, width= 15, text="RESET") btnRESET.grid(column=3, row=10) #btnRESET.configure(background="#FF0000") #btnRESET.pack() #Invoking our GUI loop win.mainloop()
30505f751cb1ef2e768681d2ba5832229c014085
GUSTAVOPERALTA1/poo
/semana_8/temp.py
3,037
4.03125
4
repeticiones= 0 #Variable que almacena el numero de repeticiones class Temperaturas: #Clase principal promedio_cent= 0 #Alamacenamos el promedio de °C prmedio_fahr= 0 #aAlmacenamos el promedio de °F fecha= [] #Almacenamos las fechas cent= [] #Almacenamos los °C fahr= [] #Almacena los °F def __init__(self): #Metodo constructor pass def datos(self): #Metodo para pedir datos dia= input("Deme una fecha: ") #Pedimos la fecha self.fecha.append(dia)#Almacenamos en la variable fecha temperatura= int(input("Deme la temperatura en °C: "))#Pedimos la temperatura self.cent.append(temperatura) #Almacenamos en cent convertir= (temperatura * 9 / 5) + 32 #Convertimos a °F self.fahr.append(convertir)#Almacenamos los datos en Fahr def mayor(self):#Metodo para encontrar al mayor info= dict(zip(self.fahr,self.fecha))#Convertimos los datos a diccionario mas= max(info.items(), key=lambda x: x[1] ) #Buscamos el mayor elemento, items regresa los datos conjuntos, clave y valor. #Key regresa una lista de elementos que seran las claves. #lambada convierte la funciona a anonima. abrir = open("temperaturas.txt","a")#Abre el archivo para añadir abrir.write("Su informacion es la siguiente: " + str(info) + "\n")#Escribe los datos de diccionario abrir.write("La temperatura mayor es: " + str(mas) + "\n") #Escribe la temperatura mayor abrir.close()#Cierra el archivo print("Temperatura mayor " +str(mas))#Imprime la temperatura y la fecha def promedio(self): #Metodo para el promedio self.promedio_cent= sum(self.cent)/repeticiones#sacaremos el promedio, primero sumando todos los datos numericos de una tupla self.promedio_fahr= sum(self.fahr) /repeticiones #Calculamos el promedio en °f print("Promedio fahrenheit: " + str( self.promedio_fahr) + "\n") #Imprimimos print("Promedio centigrados: " + str( self.promedio_cent) + "\n") #imprime el pormedio de °f def escribir(self):#Metodo para trasladar la informacion abrir = open("temperaturas.txt", "a") #Abrimos el archivo abrir.write("Promedio centigrados:" + str(self.promedio_cent) + "\n") #agrega el promedio de °c abrir.write("Promedio fahrenheit: " + str( self.promedio_fahr) + "\n") #agrega el promedio de °f abrir.close() #cierra el archivo objeto = Temperaturas() #Declaramos el objeto repetir = "s"#Variable para repetir while repetir == "S" or repetir == "s":#Mientras repetir sea s, se ejecutaran los metodos repeticiones+= 1 #Sumamos uno a las repeticiones objeto.datos() #Llamamos al metodo para pedir datos respuesta = input("¿Desea agregar otro dato? s/n ") #Preguntamos si se desea agregar mas datos if respuesta == "N" or respuesta == "n":#Si la respuesta es n, se cierra la primera parte y continuamos objeto = Temperaturas()#Se declara un objeto objeto.promedio()#Llamamos al metodo para el promedio objeto.mayor()#Llamamos al metodo para buscar el mayor objeto.escribir()#Llamamos al metodo para escribir en el archivo break #termina el programa
6abe87daa2cbc1da5a445f74997c7f8947c58e21
joydeepnandi/Algo
/Recursion/Interweaving Strings/InterweavingStrings1.py
644
3.96875
4
# O(2^(n + m)) time | O(n + m) space - where n is the lengt # of the first string and m is the length of the second string def interweavingStrings(one, two, three): if len(three) != len(one) + len(two): return False return areInterwoven(one, two, three, 0, 0) def areInterwoven(one, two, three, i, j): k = i + j if k == len(three): return True if i < len(one) and one[i] == three[k]: if areInterwoven(one, two, three, i + 1, j): return True if j < len(two) and two[j] == three[k]: return areInterwoven(one, two, three, i, j + 1) return False
5341f8c8e3d9fac4d0e9675ac00ee1bebf4e911f
rrlins/python3-exercicios
/python_exercicios/ex051.py
369
3.96875
4
# Desafio 051 - Desenvolva um programa que leia o primeiro termo e a razão de uma # PA. No final, mostre os 10 primeiros termos dessa progressão. n = int(input('Digite o primeiro termo da progresão aritimética: ')) r = int(input('Digite a razão da progresão aritimética: ')) for c in range(0,10): print('{}o termo: {}'.format(c+1,n)) n+=r
7c2e248869c9527207f54eab080b647f2836427d
MohammedAlewi/competitive-programming
/leetcode/modulus calculation/prime_subraction.py
253
3.609375
4
def subPrimes(a,b): if abs(a-b)==1: print("No") return print("YES") def runner(): val=input() for i in range(int(val)): ans=input() ans=ans.split(" ") subPrimes(int(ans[0]),int(ans[1])) runner()
1b0e58c8f769399f293594ab01b79d43560eada6
mikaelbeat/Modern_Python3_Bootcamp
/Modern_Python3_Bootcamp/List_comprehension/Preview.py
543
4.03125
4
print("\n********** Demo 1 **********\n") numbers = [1, 2, 3, 4, 5] doubled_numbers = [] for num in numbers: doubled_number = num * 2 doubled_numbers.append(doubled_number) print(doubled_numbers) print("\n********** Demo 2 **********\n") name = "Colt" print([char.upper() for char in name]) print("\n********** Demo 3 **********\n") print([bool(value) for value in [0, [], ""]]) print("\n********** Demo 4 **********\n") string_list = [str(value) for value in numbers] print(string_list)
473e0182cb98ec7a71a7e9f386fc17c181f27087
Jack-Attack3000/RPG-Game-Final
/g_map.py
2,465
3.6875
4
# Course: CS 30 # Period: 1 # Date Created: 21/02/28 # Date Last Modified: 21/02/28 # Name: Jack Anderson # Description: Classes for the map and location class Location: def __init__(self, name, description, inv_item, chara, exits): self.name = name self.description = description self.chara = chara self.inv_item = inv_item self.exits = exits def print_loc(self): """Prints out location and info""" print(f"You are now in the {self.name}") print(f"{self.description}.") print(f"{self.chara} is here") print(f"There's a {self.inv_item} in here.") print(f"There are exits {self.exits}.") class GMap: def __init__(self, loc_list): self.loc_list = loc_list self.game_map = [] self.player_start = '' self.restart() def restart(self): """Restarts the game map""" row = 0 column = 0 row_vals = [] col_vals = [] for location in self.loc_list: if location.chara == 'player': self.player_start = location col_vals.append(location) column = column + 1 if column > 2: row_vals.append(col_vals) col_vals = [] row = row + 1 column = 0 self.game_map = row_vals def move_direction(self, player_loc, direction): """Moves player around""" exit_found = False for exit in player_loc.exits: if exit == direction: exit_found = True break if exit_found is False: print("You run into a wall. Maybe try a different direction") else: print(f"You move {direction}") found_row = 0 found_col = 0 for row in range(3): for col in range(3): if self.game_map[row][col].name == player_loc.name: found_row = row found_col = col break; if direction == "up": found_row = found_row - 1 elif direction == "down": found_row = found_row + 1 elif direction == "right": found_col = found_col + 1 elif direction == "left": found_col == found_col - 1 else: print(f"{direction} is not a direction") return self.game_map[found_row][found_col]
3f3df53a1f7bd4f678b07cb90112ac1e5db8cd4b
FernandoKGA/DesafiosDeProgramacao1
/Lista2/H - Maximum Sum of Digits/maximumSumOfDigits.py
702
3.78125
4
import math def findLargestSum(n): digits = digitsFromNumber(n) if len(digits) == 1: print(n) else: size = len(digits) numberWithNines = 0 i = 0 while i < size-1: numberWithNines += 9 * math.pow(10,i) i += 1 firstDigit = int(digits[0])-1 numberWithNines += firstDigit * math.pow(10,size-1) numberWithNines = int(numberWithNines) rest = n - numberWithNines print(sum(digitsFromNumber(numberWithNines)) + sum(digitsFromNumber(rest))) def digitsFromNumber(number): listOfDigitsFromN = list(map(int,list(str(number)))) return listOfDigitsFromN n = int(input()) findLargestSum(n)
63b0f5bca58e5d5eb66fcc2823c3baad5750a3cb
ebatsell/geo-api
/cities.py
3,894
3.65625
4
import heapq import math import random class City(object): def __init__(self, cityid, name, population, alt_names_str, latitude, longitude, country_code, segment): self.id = cityid self.primary_name = name self.population = population self.country_segment = segment self.latitude = float(latitude) self.longitude = float(longitude) self.alt_names = alt_names_str.split(',') self.country_code = country_code self._temp_distance = None def matches_word(self, word): return word in self.name def set_distance(self, distance): self._temp_distance = distance @property def distance(self): return self._temp_distance def distance_to(self, city): ''' Uses Haversine method for calculating distance from current objects lat & long to another City's lat & lon Ported from javascript code from https://www.movable-type.co.uk/scripts/latlong.html ''' EARTH_RADIUS = 6371000 # meters lat1 = math.radians(self.latitude) lat2 = math.radians(city.latitude) delta_lat = math.radians(city.latitude - self.latitude) delta_lon = math.radians(city.longitude - self.longitude) a = math.sin(delta_lat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * (math.sin(delta_lon / 2) ** 2) c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)) return EARTH_RADIUS * c def find_k_closest(self, k, city_list): for city in city_list: city.set_distance(self.distance_to(city)) # heap is faster than sorting entire list for small values of k return heapq.nsmallest( k, city_list, key=lambda city: city.distance ) def find_k_closest_in_country(self, k, city_list): country_cities = list(filter(lambda city: self.country_code == city.country_code, city_list)) for city in country_cities: city.set_distance(self.distance_to(city)) return heapq.nsmallest( k, country_cities, key=lambda city: city.distance ) def to_json(self): return { 'id': self.id, 'name': self.primary_name, 'country': self.country_code, 'latitude': self.latitude, 'longitude': self.longitude, 'segment': self.country_segment, 'population': self.population } # for debugging def __repr__(self): return "City: {}\nId: {}\nLoc ({},{})\nCountry: {}\n------".format( self.primary_name, self.id, self.latitude, self.longitude, self.country_code ) class CityHandler(object): def __init__(self): self.cities = {} self._load_cities() def _load_cities(self): with open('cities1000.txt') as dataset_file: for line in dataset_file.readlines(): city_data = line.split('\t') (city_id, city_name, ascii_name, alternate_names, latitude, longitude, _, _, country_code, _, country_segment, _, _, _, population) = city_data[0:15] self.cities[city_id]= City( city_id, city_name, population, alternate_names, latitude, longitude, country_code, country_segment ) # Lower Population limit (filter by min-population to avoid BS cities) def proximal_query(self, city_id, num_cities, country_limit=False): if country_limit: return self.cities[city_id].find_k_closest_in_country(num_cities, self.cities.values()) return self.cities[city_id].find_k_closest(num_cities, self.cities.values()) # Sort by certain things: # population # id # proximity to current location (distance function + browser location - interesting proposition) def lexical_query(self, text): matching_cities = [] words = text.split(' ') for city in self.cities.values(): matches = True for word in words: # Change the way this is implemented to get the alternate names word_matches = False if word in city.primary_name: word_matches = True for name in city.alt_names: if word in name: word_matches = True matches = matches and word_matches if matches: matching_cities.append(city) return matching_cities
87b00d8065f044647e6fac2d9030d92453331251
dujiaojingyu/Personal-programming-exercises
/编程/8月/8.15/链表成对调换.py
1,290
3.921875
4
__author__ = "Narwhale" class ListNode: def __init__(self,elem): self.elem = elem self.next = None class Solution(object): def __init__(self,node=None): self.__head = node def is_empty(self): return self.__head == None def append(self,item): node = ListNode(item) if self.is_empty(): self.__head = node else: cur = self.__head while cur.next is not None: cur = cur.next cur.next = node def travel(self): """遍历整个链表""" cur = self.__head while cur != None: print(cur.elem,end=" ") cur = cur.next def swapPairs(self): if self.__head == None or self.__head.next == None: return self.__head node = self.__head result = node.next while node and node.next: temp = node.next node.next = temp.next temp.next.next = temp.next temp.next = None self.__head = temp return self.__head if __name__ == "__main__": ll = Solution() ll.append(1) ll.append(2) ll.append(3) ll.append(4) ll.travel() print('\n') print(ll.swapPairs()) ll.travel()
c459af8f6d522d43db7da0c213bcd8ff290ee591
paianish62/Anish-s-Calculators
/Square_Cube_and_Pie.py
630
4
4
def cust(a,b): c = 0 ans = a while c < (b-1) : ans = ans*a c += 1 print(ans) while True : x = int(input("Enter No. ")) y = str(input("Function performed on the no. (square, cube, pie or custom) ")) if y == "square": print(x*x) break elif y == "cube": print(x*x*x) break elif y == "pie": print(x*3.14) break elif y == "custom" : z = int(input("Enter custom power ")) cust(x,z) break else: print("please enter pie, square or custom")
8d24122d84b9695f10de2fe5406b2635d9d563aa
RayNakagami/Atcoder
/2706/2706.py
733
3.609375
4
prime = [2] def check(x): for i in prime: if x % i ==0: return False elif x < i * i: break return True def set(): for i in range(3,10**5,2): if check(i): prime.append(i) set() #print('ok') #print(prime) p,q = [int(i) for i in input().split(' ')] if q % p == 0: q = q //p p = 1 for i in prime: while True: if p % i ==0 and q % i == 0: p = p // i q = q // i #print(p,q,i) else: break ans = 1 #print(p,q) for i in prime: if q % i == 0: # print(q,i) q = q // i ans *= i while q % i ==0: q = q // i ans *= q print(ans)
3d142f2d4f8c3828d33643e1c0a601464414e97b
simplynaive/LeetCode
/706. Design HashMap.py
2,022
3.859375
4
class ListNode: def __init__(self, key, val): self.key = key self.val = val self.next = None class MyHashMap(object): def __init__(self): """ Initialize your data structure here. """ self.size = 1000 self.map = [None] * self.size def put(self, key, value): """ value will always be non-negative. :type key: int :type value: int :rtype: None """ index = key % self.size if not self.map[index]: self.map[index] = ListNode(key, value) else: cur = self.map[index] while cur.next: if cur.key == key: cur.val = value return cur = cur.next cur.next = ListNode(key, value) def get(self, key): """ Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key :type key: int :rtype: int """ index = key % self.size cur = self.map[index] while cur: if cur.key == key: return cur.val else: cur = cur.next return -1 def remove(self, key): """ Removes the mapping of the specified value key if this map contains a mapping for the key :type key: int :rtype: None """ index = key % self.size cur = pre = self.map[index] if not cur: return if cur.key == key: self.map[index] = cur.next else: cur = cur.next while cur: if cur.key == key: pre.next = cur.next break else: pre = cur cur = cur.next # Your MyHashMap object will be instantiated and called as such: # obj = MyHashMap() # obj.put(key,value) # param_2 = obj.get(key) # obj.remove(key)
c41097cb6c0b6c8319cff5a983171c36d1ed1a45
prince-prakash/practice_session
/pp_multiplicationtable.py
109
3.71875
4
num = int(input('Enter the number for table evaluation: ')) for i in range(10): w = i * num print(w)
c1d938a7b63d27b94cb66c2271feb8674f3fb7a6
anoyo-lin/algorithm
/pre-algorithm/binary_search.py
588
3.921875
4
#!/usr/bin/python3 sample_lst = [ 1, 3, 6, 10, 12 ] target = 22 def binary_search( sorted_lst, target ): low = 0 high = len(sorted_lst) - 1 while low <= high: mid = (low + high)//2 if sorted_lst[mid] > target: high = mid - 1 elif sorted_lst[mid] < target: low = mid + 1 else: if sorted_lst[mid] == target: print ("find {0} at index {1}".format(target, mid)) return True print ("can't find {0}".format(target)) return False print (binary_search(sample_lst, target))
8921e94e9c2391c2939bdfc27128ee9dd764891e
Asap7772/shpPython
/Class5/ImageManipulation/Color.py
257
3.734375
4
class Color(object): r = 0; g = 0; b = 0; def __init__(self, red = 0, green=0, blue=0): self.r = red; self.g = green; self.b = blue; def __str__(self): return "{} {} {} ".format(self.r, self.g, self.b);
e588e28a48d18c71e9f27965375e2253ba671b4e
mirko-m/restricted_boltzmann_machine
/src/binary_rbm_numpy.py
10,260
3.609375
4
import numpy as np import matplotlib.pyplot as plt import mnist def sigm(x): return 1.0/(1.0 + np.exp(-x)) class RestrictedBoltzmannMachine: '''Implementation of binary Restricted Boltzmann Machine (RBM) using numpy. Both the visible and the hidden units are binary. The weights are initialized using Gauusian ranom numbers and the biases are initialized to zero. Parameters ---------- n_v: (Integer) Number of visible units n_h: (Integer) Number of hidden units. Attributes ---------- n_v: (Integer) Number of visible units n_h: (Integer) Number of hidden units. weights: (Float) Array with shape (n_h, n_v). The weights connecting the visible and hidden units. bias_v: (Float) Array of length n_v with the biases for the visible units. bias_h: (Float) Array of length n_h with the biases for the hidden units. Methods ------- sample_h_from_v sample_v_from_h gibbs_step fit calc_squared_reconstruction_error ''' def __init__(self,n_v,n_h): self.n_v = n_v self.n_h = n_h self.weights = np.random.randn(n_h,n_v)/100.0 self.bias_v = np.zeros(n_v) self.bias_h = np.zeros(n_h) def sample_h_from_v(self,v): '''Sample the hidden units from the visible units. Parameters ---------- v: Binary array of shape (n_samples, n_v) representing n_samples different configurations of the visible units Returns ------- prob_h: (Float) Array of shape (n_samples, n_h) with the probability for the hidden units to be turned on. h: Binary Array of shape (n_samples, n_h) representing a sample of the hidden units drawn from v. Note ---- when a single vector v is passed it is important that the shape is (1, n_v). ''' dim = v.shape[0] prob_h = sigm(np.dot(v,self.weights.T) + self.bias_h) # dimension dim x n_h h = (np.random.rand(dim,self.n_h) < prob_h).astype(float) return prob_h, h def sample_v_from_h(self,h): '''Sample the visible units from the visible units. Parameters ---------- h: Binary array of shape (n_samples, n_h) representing n_samples different configurations of the hidden units Returns ------- prob_v: (Float) Array of shape (n_samples, n_v) with the probability for the visible units to be turned on. v: Binary Array of shape (n_samples, n_v) representing a sample of the visible units drawn from h. Note ---- when a single vector h is passed it is important that the shape is (1, n_v). ''' dim = h.shape[0] prob_v = sigm(np.dot(h,self.weights) + self.bias_v) # dimension dim x n_v v = (np.random.rand(dim,self.n_v) < prob_v).astype(float) return prob_v, v def gibbs_step(self,X): '''Perform a single Gibbs step which updates first the hidden units and then the visible units. Can be used for reconstruction of a sample. Parameters ---------- X: Binary array of shape (n_samples, n_v) Returns ------- prob_h: (Float) Array of shape (n_samples, n_h) with the probability for the hidden units to be turned on. h: Binary Array of shape (n_samples, n_h) representing a sample of the hidden units drawn from X. prob_v: (Float) Array of shape (n_samples, n_v) with the probability for the visible units to be turned on given h. v: Binary Array of shape (n_samples, n_v) representing a sample of the visible units drawn from h, i.e. the reconstruction of X. Note ---- when a single vector h is passed it is important that the shape is (1, n_h). ''' prob_h, h = self.sample_h_from_v(X) prob_v, v = self.sample_v_from_h(h) return prob_h, h, prob_v, v def fit(self,X,lr,decay=0.0,k=1,n_iter=10,batch_size=100,\ persistent=True, verbose=True): '''Fit the RBM to the data X using k-contrastive divergence (k-CD) or k-persistent contrastive divergence (k-PCD). For k-CD the Markov chain is reset after each iteration using the training data. For k-CPD on the other hand the Markov chain is initialized once using the training data, but not reset. Parameters ---------- X: Binary array of shape (n_samples, n_v) containing the training data lr: the learning rate decay: (default = 0) parameter for weight decay to encourage sparsity. k: (default = 1) number of samples that are drawn from the Markov-chain in each step. n_iter: (default = 10) number of iterations. In each iteration every sample contained in X is visited once. batch_size: (default = 100) the size of the mini_batches used for the fitting procedure. After each mini_batch the gradient is updated. persistent: (default = True) Use k-PCD or k-CD. verbose: (default=True) print iteraton number and squared reconstruction error to stdout. Note ---- 1. The k-CD algorithm implemented here is taken from Algorithm 1 of A. Fischer and C. Igel, "Training restricted Boltzmann machines: An Introduction", Pattern Recognition 47, 25 (2014). The k-CPD algorithm is a slight variation of this algorithm descibed in the same reference. 2. The squared reconstruction error is not necessarily a good indicator of whether the algorithm is truly optimizing the log-likelihood. This needs to be kept in mind. ''' n_samples = X.shape[0] n_batch = n_samples/batch_size n_rest = n_samples % batch_size if persistent: # Initialize Markov-chain with first batch of training data v_k = np.copy(X[:batch_size,:]) for step in xrange(0,n_iter): # If n_samples is not a multiple of n_batch, the final batch has a # smaller size. Instead of running the algorithm on the smaller # batch I choose to reshuffle the data so that eventually all of # the data will be used for fitting. shuffled = np.random.permutation(X) for j in xrange(0,n_batch): X_batch = shuffled[j*batch_size:(j+1)*batch_size,:] if persistent: v_k = self._pcd_step(X_batch,v_k,lr,decay=decay,k=k) else: self._cd_step(X_batch,lr,k=k) if verbose: print 'iteration\t{:d}\tsquared_reconstruction_error\t{:.6f}\t'.\ format(step, self.calc_squared_reconstruction_error(X)) def _pcd_step(self,X,v,lr,decay=0.0,k=1): '''Helper function which performs a simgle step of k-PCD. Parameters ---------- v: Binary array of shape (n_samples, n_v) representing the current state of the visible units in the Markov chain. For all other parameters see docstring of fit Returns ------- v_k: Binary array of shape (n_samples, n_v) representing the visible units after updating the Markov chain k times. This is passed back into _pcd_step in the next iteration. ''' n_samples = X.shape[0] prob_h_0, h_0 = self.sample_h_from_v(X) prob_h_k, h_k, prob_v_k , v_k = self.gibbs_step(v) # loop below is entered when k>1 for t in range(1,k): prob_h_k, h_k, prob_v_k , v_k = self.gibbs_step(v) prob_h_k = sigm(np.dot(v_k,self.weights.T) + self.bias_h) # The update rules below were taken from A. Fisher and C. Igel # Pattern Recognition 47, 25, (2014) self.weights += lr*(np.dot(prob_h_0.T,X) -\ np.dot(prob_h_k.T,v_k))/n_samples\ - decay*self.weights self.bias_h += lr*np.sum(prob_h_0 - prob_h_k,axis=0)/n_samples self.bias_v += lr*np.sum(X - v_k,axis=0)/n_samples return v_k def _cd_step(self,X,lr,decay=0.0,k=1): '''Helper function which performs a simgle step of k-CD. Parameters ---------- See docstring of fit ''' n_samples = X.shape[0] prob_h_0, h_0, prob_v_k , v_k = self.gibbs_step(X) # loop below is entered when k>1 for t in range(1,k): prob_h_k, h_k, prob_v_k , v_k = self.gibbs_step(v_k) prob_h = sigm(np.dot(v_k,self.weights.T) + self.bias_h) # The update rules below were taken from A. Fisher and C. Igel # Pattern Recognition 47, 25, (2014) self.weights += lr*(np.dot(prob_h_0.T,X) -\ np.dot(prob_h_k.T,v_k))/n_samples\ - decay*self.weights self.bias_h += lr*np.sum(prob_h_0 - prob_h_k,axis=0)/n_samples self.bias_v += lr*np.sum(X - v_k,axis=0)/n_samples def calc_squared_reconstruction_error(self,X): '''Calculate the squared reconstruction error Parameters ---------- X: Binary array of shape (n_samples, n_v) containing the data to be reconstructed Returns ------- squared reconstruction error (Float) ''' _, _, _, X_rec = self.gibbs_step(X) return np.mean(np.square(X-X_rec)) def save_state_to_file(self,fname): '''Save the current state (weights and biases) of the RBM to a file. Parameters ---------- fmname: (string) name of the file ''' f = open(fname,'w') np.savez(f,weights=self.weights,bias_v=self.bias_v,bias_h=self.bias_h) def load_saved_state(self,fname): '''Load a saved state (weights and biases) from a file Parameters ---------- fmname: (string) name of the file ''' data = np.load(fname) self.weights = data['weights'] self.bias_v = data['bias_v'] self.bias_h = data['bias_h']
a823b5329a617fa19cdbee490c096ffc5e88755b
LemmiwinksNO/Udacity101
/Units 1-2 PS 1-2/Lesson 3.py
1,155
4.125
4
def find_element(p,t): i = 0 while i < len(p): if p[i] == t: return i i = i + 1 return -1 def find_element(p,t): i = 0 for e in p: if e == t: return i i += 1 return -1 # index method <list>.index(<value>) p = [0, 1, 2] print p.index(3) # in -> <value> in <list> 3 in p #=> is 3 in list p? # Define a procedure, find_element, # using index that takes as its # inputs a list and a value of any # type, and returns the index of # the first element in the input # list that matches the value. # If there is no matching element, # return -1. def find_element(values, value): if value in values: return values.index(value) return -1 # Define a procedure, union, # that takes as inputs two lists. # It should modify the first input # list to be the set union of the two # lists. You may assume the first list # is a set, that is, it contains no # repeated elements. def union(list1, list2): for e in list2: if e not in list1: list1.append(e) # Test a = [1,2,3] b = [2,4,6] union(a,b) print a #>>> [1,2,3,4,6] print b #>>> [2,4,6]
03ec85aff434b394a505abf6b052779062fd68f4
dackour/python
/Chapter_24/04_Quiz.py
2,775
3.890625
4
# 1. What is the purpose of an __init__.py file in a module package directory? # # The __init__.py file serves to declare and initialize a regular module package; # Python automatically runs its code the first time you import through a directory # in a process. Its assigned variables become the attributes of the module object # created in memory to correspond to that directory. It is also not optional until 3.3 # and later—you can’t import through a directory with package syntax unless it # contains this file. # # 2. How can you avoid repeating the full package path every time you reference a # package’s content? # # Use the from statement with a package to copy names out of the package directly, # or use the as extension with the import statement to rename the path to a shorter # synonym. In both cases, the path is listed in only one place, in the from or import # statement. # # 3. Which directories require __init__.py files? # # In Python 3.2 and earlier, each directory listed in an executed import or from statement # must contain an __init__.py file. Other directories, including the directory # that contains the leftmost component of a package path, do not need to include # this file. # # 4. When must you use import instead of from with packages? # # You must use import instead of from with packages only if you need to access the # same name defined in more than one path.With import, the path makes the references # unique, but from allows only one version of any given name (unless you also use # the as extension to rename). # # 5. What is the difference between from mypkg import spam and from . import spam? # # In Python 3.X, from mypkg import spam is an absolute import—the search for # mypkg skips the package directory and the module is located in an absolute directory # in sys.path. A statement from . import spam, on the other hand, is a relative import # —spam is looked up relative to the package in which this statement is contained # only. In Python 2.X, the absolute import searches the package directory first before # proceeding to sys.path; relative imports work as described. # # 6. What is a namespace package? # # A namespace package is an extension to the import model, available in Python 3.3 # and later, that corresponds to one or more directories that do not have # __init__.py files. When Python finds these during an import search, and does not # find a simple module or regular package first, it creates a namespace package that # is the virtual concatenation of all found directories having the requested module # name. Further nested components are looked up in all the namespace package’s # directories. The effect is similar to a regular package, but content may be split across # multiple directories.
2c41a0ca20c589b1fa3fc66cbdc401c220f8ec03
sphars/python-learning-playground
/python-crash-course/chap11/test_name_function.py
568
3.59375
4
import unittest from name_function import get_formatted_name class NamesTestCase(unittest.TestCase): """Tests for 'name_function.py'.""" def test_first_last_name(self): """Do names like 'Ned Flanders' work?""" formatted_name = get_formatted_name('ned', 'flanders') self.assertEqual(formatted_name, 'Ned Flanders') def test_first_last_middle_name(self): """Do names like 'Charles Montgomery Burns' work?""" formatted_name = get_formatted_name('charles', 'burns', 'montgomery') self.assertEqual(formatted_name, 'Charles Montgomery Burns') unittest.main()
9f9c1c6c83d53c11a25bd2540dc6f943e61674ae
CristianeNaves/rsa
/funcoes_auxiliares.py
1,013
4.09375
4
""" Recebe um numero grande e simplifica ele em fatores menores de 8,4,2 e 1. num: 23 retorno: [8,8,4,2,1] """ def fatorar_numero(num): resultado = [] quantidade_15 = int(num/15) mod_15 = num % 15 num = num - (15 * quantidade_15) resultado.append(8) if int(num/8) else None num = num % 8 resultado.append(4) if int(num/4) else None num = num % 4 resultado.append(2) if int(num/2) else None num = num % 2 resultado.append(1) if int(num/1) else None for i in range(0, quantidade_15): resultado.append(1) resultado.append(2) resultado.append(4) resultado.append(8) return resultado """ Recebe uma string e retorna uma lista dos codigos ascii do texto """ def string_to_ascii(texto): return list(map(lambda s: ord(s), list(texto))) """ Recebe uma lista de códigos ascii e retorna uma string """ def ascii_to_string(simbolos_ascii): resultado = list(map(lambda s: chr(s), simbolos_ascii)) return "".join(resultado)
4b5fb414b9f19fec12d42f7997ede49a34ca26e6
yadnyesh/AllPythonYouTube
/durga/section7/printPattern.py
93
3.6875
4
n = int(input('Enter number of rows: ')) for i in range(n): print((str(i + 1) + ' ') * n)
e9b3ead9247d6eb91b18c7d70f59e67d1debed35
nikosninosg/Multi-dimensional-Data-Structures
/Kd_Trees/Mds_Main_Solution.py
643
3.5625
4
import pandas as pd from sklearn.neighbors import KDTree import matplotlib.pyplot as plt df = pd.read_csv("train_x_y_10K.csv") # Num of Rows = 29.118.021 points print("Num of Rows: ", len(df.index)) # print(df.y[0:3]) plt.scatter(df.x[0:99], df.y[0:99]) plt.show() X = df.to_numpy() print(X) print(type(X)) tree = KDTree(X) print(tree) nearest_dist, nearest_ind = tree.query(X, k=2) # k=2 nearest neighbors # Each entry gives the list of distances to the neighbors of the corresponding point. print(nearest_dist[:, 1]) # Each entry gives the list of indices of neighbors of the corresponding point. print(nearest_ind[:, 1]) # drop id
3e533579d9dd97b78444c4a43e7fd7b5549141ea
rainishadass/127
/code/exam1/answers.py
1,444
3.890625
4
import math ############### question 1 ####################### # def f(n,k): numerator = (1+n)**k denomiator = math.sqrt(k+1) return numerator / denomiator ############### question 2 ####################### # def remove_e(sentence): result = "" for letter in sentence: if letter != 'e': result = result + letter return result ############### question 3 ####################### # def box(length,height): result = "" if height % 2 != 0: height = height - 1; xs = "X"*length os = "O"*length for row in range(height // 2): result = result + os+'\n' result = result + xs+'\n' return result ############### question 4 ####################### # def makeacronym(w): acronym = "" w = w.lower() for word in w.split(): acronym = acronym + word[0] return acronym print("-------------- Question 1 -----------------") ans = f(5,6) print("n=5, k=6",ans) print() print("-------------- Question 2 -----------------") s = "The letter E will be removed" print("original: ",s) print("result: ",remove_e(s)) print() print("-------------- Question 3 -----------------") print("l=5,h=5") print(box(5,5)) print() print("l=10,h=6") print(box(10,6)) print("-------------- Question 4 -----------------") s = "Laugh out loud" print(s," : ", makeacronym(s)) print() s = "In my humble opinion" print(s," : ", makeacronym(s)) print()
cc0eb4cfdc53d06dd09726006c2c626fd4876488
LeighGriffith/python-projects
/code-studio/s1level63.py
801
3.703125
4
'''s1level63 // draw_a_square for (var count = 0; count < 4; count++) { moveForward((50)); turnRight(90); } // draw_a_square for (var count2 = 0; count2 < 4; count2++) { moveForward((60)); turnRight(90); } // draw_a_square for (var count3 = 0; count3 < 4; count3++) { moveForward((70)); // draw_a_square for (var count = 0; count < 4; count++) { moveForward((80)); turnRight(90); } // draw_a_square } for (var count2 = 0; count2 < 4; count2++) { moveForward((90)); turnRight(90); } ''' import turtle artist = turtle.Turtle() artist.pensize(7) artist.pencolor('red') def draw_a_square(length): for count in range(4): artist.forward(length) artist.right(90) draw_a_square(50) draw_a_square(60) draw_a_square(70) draw_a_square(80) draw_a_square(90)
12236e1f2f6e474eebd79c9534f8e8bdf54384c3
Code-Law/Ex
/MaxNumber.py
176
4.03125
4
#Input 6 integer.Output the biggest one. m=0 number=[] for i in range(6): num=int(input("number:")) number.append(num) if number[i]>m: m=number[i] print(m)
6dc7db393e69cbf702bb56e4cc280d73c49f2d4b
asanjeevkumar/throw-ball
/scripts/max_touches.py
2,265
3.765625
4
"""Script prints the maximum number of players that can touch a single ball. This script takes csv file location as argument and process csv file to identify the maximum count of players touch a single ball. `python throw_ball/scripts/max_touches.py [file_location]` """ from os import path as osp import csv import click def get_players_length(player, visibility_matrix): """Gets number of players who have visibility between each other. :param str player: Name of player who has ball :param visibility_matrix: Array of player matrix. :return int: number of players visibility is both ways """ counter = 0 for pass_to in visibility_matrix[player]: # Checking if player is in others visibility list if player in visibility_matrix[pass_to]: counter = +1 return counter def clean_data(file_location): """Returns array of data by processing csv file. :param file_location: :return: dictionary with items as list """ ball_mat = {} with open(file_location) as csvfile: reader = csv.reader(csvfile) for row in reader: ball_mat[row[0]] = [i.strip() for i in row[1:]] return ball_mat def get_max_touches_by_single_ball(file_location): """Process the csv file and converts data into dictionary of containing list items. :param str file_location: :return : max players can touch single ball. """ processed_data = clean_data(file_location) print(processed_data) player_pass_length = 0 for player, _ in processed_data.items(): player_pass_length += get_players_length(player, processed_data) return player_pass_length @click.command() @click.argument('file_location', type=click.Path(exists=True, resolve_path=True)) def main(file_location): """main function is trigger point :param file_location: location of file :return: """ # Validating for csv file. if osp.basename(file_location).split('.')[1] != 'csv': raise ValueError("File does not exist or not csv" " %s" % file_location) print(get_max_touches_by_single_ball(file_location)) if __name__ == "__main__": main() # pylint: disable=no-value-for-parameter
fe7fa911738b41994f63d04e33d361c73b580e97
mibra41/UVA
/TEST1/madlib.py
1,447
3.71875
4
#Muhammad Ibrahim (mi2ye) #Nathan Tumperi (nlt4xp) name = input('Female name: ') noun1 = input('Plural object: ') person = input('Dangerous people: ') mean_animal = input('Mean animal: ') verb1 = input('past tense verb: ') verb2 = input('Malicious past tense verb: ') household_object = input('Household object: ') bodypart1 = input('Body part: ') verb3 = input('Action verb: ') bodypart2 = input('Different body part: ') verb4 = input('Aggressive eating technique: ') def par1(): print('Once upon a time, there was a girl named ' + name + '. ') print('One day, ' + name + '\'s mother told ' + name + ' to deliver ' + noun1) print(' to grandma, \"but don\'t talk to ' + person + '\'s on the way!\" she said.') def par2(): print('The Big Bad ' + mean_animal + ' then ' + verb1 + ' to Grandma\'s house,') print('knocked on the door, and ' + verb2 + ' her. The Big Bad ' + mean_animal) print('put on Grandma\'s clothes and waited in her ' + household_object + '. ') print('When', name, 'got to her granda\'s house, she entered and went to the', household_object + '.',) def par3(): print('"My, what big', bodypart1, 'you have, grandma! She said in surprise". "All the better to', verb3, 'my dear."') print('"My, what big', bodypart2, 'you have, grandma!" "All the better to', verb4, 'you, my dear.') print('The', mean_animal, 'ate', name + '.') print() par1() print() par2() print() par3()
00fec2a4b6053f9982beb005035606a134107957
CarlosAmorim94/Python
/Exercícios Python/ex065_Maior e menor valor.py
796
3.96875
4
""" EXERCÍCIO 065: Maior e Menor Valores Crie um programa que leia vários números inteiros pelo teclado. No final da execução, mostre a média entre todos os valores e qual foi o maior e o menor valores lidos. O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores. """ continuar = 's' soma = quant = media = maior = menor = 0 while continuar in 'Ss': n = int(input('Digite um número: ')) continuar = str(input('Quer continuar? [S/N]: ')).strip()[0] soma += n quant += 1 if quant == 1: maior = menor = n else: if n > maior: maior = n if n < menor: menor = n media = soma / quant print('O maior número é {} o menor é {} e a média entre eles é {}'.format(maior, menor, media))
ff41e00b993e374b1e5e776f4cfd733d184c669e
lygeneral/LeetCode
/Python/Array/middle/73_set-matrix-zeroes.py
1,606
3.546875
4
''' 73. 矩阵置零 给定一个 m x n 的矩阵,如果一个元素为 0,则将其所在行和列的所有元素都设为 0。请使用原地算法。 示例 1: 输入: [ [1,1,1], [1,0,1], [1,1,1] ] 输出: [ [1,0,1], [0,0,0], [1,0,1] ] 示例 2: 输入: [ [0,1,2,0], [3,4,5,2], [1,3,1,5] ] 输出: [ [0,0,0,0], [0,4,5,0], [0,3,1,0] ] 进阶: 一个直接的解决方案是使用 O(mn) 的额外空间,但这并不是一个好的解决方案。 一个简单的改进方案是使用 O(m + n) 的额外空间,但这仍然不是最好的解决方案。 你能想出一个常数空间的解决方案吗? ''' class Solution: def setZeroes(self, matrix): ''' @describe: 在原矩阵上处理,为0的元素所在的行列上的元素置为-inf(不为0的情况下),然后遍历找出-inf的元素置为0 @param matrix: 矩阵 @return: NULL ''' m = len(matrix) n = len(matrix[0]) for i in range(m): for j in range(n): if matrix[i][j] == 0: for k in range(m): matrix[k][j] = -float('inf') if matrix[k][j] != 0 else 0 for k in range(n): matrix[i][k] = -float('inf') if matrix[i][k] != 0 else 0 for i in range(m): for j in range(n): if matrix[i][j] == -float('inf'): matrix[i][j] = 0 if __name__ == '__main__': matrix = [[1,1,1],[1,0,1],[1,1,1]] s = Solution() s.setZeroes(matrix) print(matrix)
082dac836fd2a2c5ac7f2c3a15f4130049f2e0e9
ThouArtToFiddy/Past-Projects
/csci1133/TakehomeTest1/wheeloffortune.py
9,080
3.75
4
import random def randomphrase(): #Returns a random phrase from phrasebak.txt and its category number x x = random.randint(0,4) y = random.randint(0,19) phrases = getphrase() return [phrases[x][y].upper(),x] def getcategory(x): #Returns the category of the phrase if x == 0: return "Before and After" elif x == 1: return "Song Lyrics" elif x == 2: return "Around the House" elif x == 3: return "Food and Drink" elif x == 4: return "Same Name" else: return "ERROR Incorrect Category Input" def getphrase(): #Puts phrases in a 2d array, with 5 rows of 20 p = open("phrasebank.txt").read().splitlines() PhraseBank = [["" for phrase in range(20)]for category in range(5)] for category in range(len(PhraseBank)): for phrase in range(len(PhraseBank[0])): PhraseBank[category][phrase] = p[(category)*20+phrase] return PhraseBank def action(input,phrase,blocked,earnings,guesses): x = input.upper() if x == "SPIN": return spinthewheel(phrase,blocked,earnings,guesses) elif x == "VOWEL": return buyAVowel(phrase,blocked,earnings,guesses) elif x == "SOLVE": return solve(phrase,earnings) elif x == "QUIT": return ("",-2,"") else: print("Your Action: \"",input,"\" was not a valid Action") return ("",-1,"") def solve(phrase,earnings): #Checks if the user's guess is correct guess = input("Enter your Guess with single spaces\n").upper() for i in range(len(guess)): if phrase[i]!=guess[i]: #If any charcter does not match print("Your Guess was incorrect!\nCurrent Winnings reset to $0") return (False,0) print("Your guess was correct!") return (True,earnings) def buyAVowel(phrase,blocked,earnings,guesses): #Function for when the user buys a vowel if earnings<250: #Checks to make sure user has more than $250 print("You don't have enough money to buy a vowel! You need $250!\nYour current Winnings are: $",earnings) return (blocked,earnings,"") earnings -= 250 done = False while not done: #Loop to ensure the user enters a valid vowel guess = input("$250 deducted from your winnings. Which vowel would you like to buy? (A , E , I , O , U)\n").upper() if guess not in "AEIOU": #If their guess was not AEIOU print("Your Guess: \"",guess,"\" is not a valid vowel.") else: if guess not in guesses: #Checks to make sure their guess was not already guessed before if phrase.count(guess)>0: #Correctly guesses the vowel print("Congratulations! Your Guess \"",guess,"\" appeared in the Phrase ",phrase.count(guess)," times!") for i in range(len(phrase)): if phrase[i] == guess: blocked[i] = guess return (blocked,earnings,guess) else: #Incorrectly guesses the vowel print("Oh no! Your Guess\"",guess,"\" did not appear in the Phrase.") return (blocked,earnings,guess) else: #If their guess was already in the list of guesses print("Your Guess: \"",guess,"\" has already been guessed.") def spinthewheel(phrase,blocked,earnings,guesses): #Function for the consonant guess spint the wheel values = [50,100,100,100,100,100,100,200,200,200,200,250,250,250,500,500,750,750,1000,2000,5000,10000,"Bankrupt"] x = random.randint(0,22) if values[x] != "Bankrupt": #If the user did not roll bankrupt print("You spun a",values[x]) done = False while not done: #Loops to make sure the user completes a valid action guess = input("Guess a valid consonant \n").upper() if guess not in "QWRTYPSDFGHJKLZXCVBNM": #Makes sure the user's input was a valid consonant print("Your guess: ",guess," is not a valid consonant.") elif guess not in guesses: #Makes sure the user did not guess one that was already guessed if phrase.count(guess)>0: #Correctly guesses the consonant earnings += values[x]*phrase.count(guess) print("Congratulations! Your Guess \"",guess,"\" appeared in the phrase ",phrase.count(guess)," times! \nYou've won $ ",values[x]*phrase.count(guess)) for i in range(len(phrase)): if phrase[i] == guess: blocked[i] = guess return (blocked,earnings,guess) else: #Incorrectly guesses the consonant earnings -= values[x] print("Oh no! your Guess \"",guess,"\" did not appear in the phrase\nYou've lost $ ",values[x],".") return (blocked,earnings,guess) else: #If the user tries to guess a consonant that was already guessed print("Your Guess: \"",guess,"\" has already been guessed.","\nTry again.") else: #If the user did roll a bankrupt print("You spun a Bankrupt and lost all your Winnings!\nYou lost your turn!") if earnings > 0: earnings = 0 return (blocked,earnings,"") def blankphrases(phrase): #Returns blanks for every single character in the phrase newphrase = phrase[0] newphrase = newphrase.upper() for i in "QWERTYUIOPASDFGHJKLZXCVBNM": newphrase = newphrase.replace(i,"_") return list(newphrase) def printblocked(blocked): #Prints a phrase character by character onn the same line for x in range(len(blocked)): print(blocked[x],end ="") print("") def allletters(guesses): #Checks if the user has guessed all 26 letters for i in "QWERTYUIOPASDFGHJKLZXCVBNM": if i not in guesses: return False return True def main(): guesses = "" #Tracker variable for all the valid guesses the user makes earnings = 0 #Tracker for the winnings of the user print("Welcome to the Wheel of Fortune!\nThe Phrase is:") phrase = randomphrase() #print(phrase[0]) #Remove comment infront of print line to show the random phrase blocked = blankphrases(phrase) print("Your Category Is: ",getcategory(phrase[1])) print("Your current Winnings are: $",earnings) printblocked(blocked) done = False while not done: #Keeps on looping until the game is finished userinput = input("Would you like to Spin the Wheel (type 'spin'), Buy a Vowel (type 'vowel'), Solve the Puzzle (type 'solve'), or Quit (type 'quit')?\n") result = action(userinput,phrase[0],blocked,earnings,guesses) if result[1]==-1: #If the user input was invalid, skip this iteration and ask for input again continue elif result[1]==-2: #If the user inputs 'quit' print("Too hard for you?\nGood luck next time!\nYou have Won: $0") done = True continue elif result[0]==True: #If the user chose solve and gets it right! if earnings > 0: print("Congratulations! You Win! \nYour total Winnings: $",result[1],"!") else: print("Congratulations! You Win! \nYour total Winnings is somehow $0!") done = True continue elif result[0]==False: #If the user chose solve and got it wrong earnings = result[1] else: #Spins, Vowels, boring earnings = result[1] blocked = result[0] guesses += result[2] print("Your Category is: ",getcategory(phrase[1])) printblocked(blocked) print("Consonants Guessed: ", end = "") for i in guesses: #Lists out the consonants that were guesses if i not in "AEIOU": print(i, end = " ") print("\nVowels Guessed: ", end = "") for i in guesses: #Lists out the vowels that were guessed if i in "AEIOU": print(i,end = " ") print("\nYour current Winnings are: $", earnings) if allletters(guesses): #The losing condtion that all 26 letters were guessed done = True print("You Lost! (You have guessed all the letters and still didn't get it?)","\nYou have Won: $0\nHave a nice day! :D") if __name__ == '__main__': main()
7fadeb96acd394e4ee0084a9a5285af8192e6a17
djdavis1420/gilded_rose
/src/models/item.py
322
3.515625
4
class Item: def __init__(self, name, sell_in, quality): self.name = name self.sell_in = sell_in self.quality = quality def update_item(self): if self.sell_in <= 0: self.quality -= 2 elif self.quality > 0: self.quality -= 1 self.sell_in -= 1
f4a7d24840218e5a7513da24164b41d129f4de87
dantru7/PY110-november-2018
/Tasks/train_second.py
710
3.78125
4
""" 2. Считалочка Дано N человек, считалка из K слогов. Считалка начинает считать с первого человека. Когда считалка досчитывает до k-го слогка, человек, на котором она остановилась, вылетает. Игра происходит до тех пор, пока не останется последний человек. Для данных N и К дать номер последнего оставшегося человека. """ N = 5 K = 4 arr = list(range(N)) while N > 1: c = K % N if c == 0: c = N del arr[c-1] N -= 1 print(arr[0] + 1)
2b253ca3ac1b3a0384d44b900026ae1d2d646fdd
phvv-me/python-switch-if-tree
/src/switch.py
1,663
3.671875
4
# simple switch key = "preposition" default = "..." switch = { "noun": "dog", "verb": "to bark", "adjective": "big", "adverb": "loudly", "preposition": "of", }.get(key, default) assert switch == "of" # functional switch def fibonacci_switch(key): def loop(n): ... def recurrent(n): ... def memoization(n): ... # you could refactor this as a loop return { loop.__name__: loop, recurrent.__name__: recurrent, memoization.__name__: memoization, }.get(key, lambda: NotImplemented) memoization_fibonacci = fibonacci_switch("memoization") assert ( memoization_fibonacci(10) is None ), f"Try implementing the {memoization_fibonacci.__name__} function" # switch with reduce switch = { "noun": { "animal": {"mammal": "rabbit", "reptile": "tortoise"}, "human": "Napoleon Bonaparte", }, "verb": { "witchcraft": {"summon", "enchant", "dispel"}, "sports": { "basketball": 5, "soccer": 11, "volleyball": 7, "sumo": 2, "darts": 1, }, }, "adjective": { "good": {"excellent": 10, "very good": 8, "okay": 6}, "bad": {"unbearable": 0, "terrible": 2, "awful": 4,}, }, "adverb": ..., } path = ("verb", "sports", "sumo") default = "not found" item = switch for key in path: try: item = item.get(key, default) except AttributeError: break # isinstance(item, dict) is False assert item == 2 from functools import reduce result = reduce(lambda item, key: item.get(key, default), path, switch) assert result == item
505773eadb095ad2fb79c6b12eecccf96383f4b5
luisdomal/Python
/S8/ejemplos/test_operaciones.py
635
3.578125
4
from operaciones import * def test_suma_cero(): resultado = suma(0, 0) # Espero que resultado sea 0 assert resultado == 0 # Para correr el test tenemos que escibir en consola lo siguiente: "py -m pytest" # Para tener mas detalle podemos escribir al final -v def test_suma_numeros_iguales(): assert suma (2, 2) == 2 * 2 assert suma (8, 8) == 8 * 2 def test_suma_cadenas(): resultado = suma("Hello ", "World") assert len(resultado) > 0 assert type(resultado) == str assert resultado == "Hello World" # Agregando -x en la consola podemos hacer que el test se detenga hasta donde las pruebas pasan
1f01960ee7ee3d5772e57fc474531ece31c0e950
SANJAY072000/PythonInterviewChallenges
/LevelOne/forLoop.py
150
3.71875
4
# print(list(range(0, 20, 5))) # for i in list(range(0, 20, 2)): # print(i, end=' ') for i in ["Sanjay", "Singh", "Bisht"]: print(i, end=' ')
43f30982521c64019f25c41b01b77cccb2cdb92c
Jeffreygrimmie/dice
/roshambo.py
1,121
3.890625
4
###Jeffrey Grimmie 2/17/2019 ###To do: fix bug, if more then one player rolls the same number and the rolls are highest in rolls. ### tap roll the dice game rolls dice on each input for player then returns what player wins. import os import roll_dice def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') def same_number_roll_checker(rolls): none = none #place holder for future code ###To do: fix bug, if more then one player rolls the same number and the rolls are highest in rolls. ###here def roshambo(): roll = [] rolls = [] player_position = 1 clear_screen() print("Welcome to Roshambo play at your own risk!!!") print("The player that rolls the highest number first wins!") players = int(input('How many players are there: ')) for i in range(players): input('Press any key to roll player %s' % player_position) roll = roll_dice.roll_dice(6, 6) #print(roll[-1]) rolls.insert(player_position - 1, roll[-1]) roll[:] = [] player_position += 1 winner = rolls.index(max(rolls)) + 1 #print(rolls) print('Player %s has won the roll!' % winner) roshambo()