blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
6f30a7de181e48b349b3d1a15e71036df3a5bb17
zhangxinzhou/PythonLearn
/helloworld/chapter03/demo03.09.py
239
3.59375
4
total = 99 for number in range(1, 100): if number % 7 == 0: continue else: string = str(number) if string.endswith('7'): continue total -= 1 print("从1数到99共拍腿", total, "次.")
5b12efb2c92e09c14d3aad497a27916df4e82eb0
zhangxinzhou/PythonLearn
/helloworld/chapter07/demo02.04.py
804
3.75
4
class Fruit: def __init__(self, color='绿色'): Fruit.color = color def harvest(self, color): print("水果是:", color, "的!") print("水果已经收获......") print("水果原来是:", Fruit.color, '的!') class Apple(Fruit): color = '红色' def __init__(self): print("窝是苹果") super().__init__() class Aapodilla(Fruit): def __init__(self, color): print("\n窝是人参果") super().__init__(color) def harvest(self, color): print("人参果是:", color, "的!") print("人参果已经收获......") print("人参果原来是:", Fruit.color, '的!') apple = Apple() apple.harvest(apple.color) sapodilla = Aapodilla('白色') sapodilla.harvest('金黄色带紫色条纹')
85ab73b618134d29af120bf7789b4f8ae38e6537
zhangxinzhou/PythonLearn
/helloworld/chapter05/demo01.08.py
94
3.65625
4
str = 'abc_ABC' lower = str.lower() upper = str.upper() print(str) print(lower) print(upper)
224160811a676654cbfe88c9d0ba15d89620450f
zhangxinzhou/PythonLearn
/helloworld/chapter04/demo03.02.py
235
4.1875
4
coffeename = ('蓝山', '卡布奇诺', '慢的宁') for name in coffeename: print(name, end=" ") print() tuple1 = coffeename print("原元组:", tuple1) tuple1 = tuple1 + ("哥伦比亚", "麝香猫") print("新元组:", tuple1)
ca8e6fd680ab452e8389b9d2391f1fbd1396ade1
zhangxinzhou/PythonLearn
/helloworld/chapter04/demo04.01.py
111
3.796875
4
dictionary = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'} print(dictionary) print(dictionary['key1'])
f152dfa3ca559ba75e1941d5f20ddc62ec2c4af0
zhangxinzhou/PythonLearn
/helloworld/chapter06/demo01.05.py
891
3.828125
4
def fun_bmi(height, weight, person='路人甲'): '''功能: 根据身高和体重计算BMI指数 person:姓名 height:身高,单位:米 weight:体重,单位:千克 ''' print(person + '的身高:' + str(height) + "米 \t 体重: " + str(weight) + "千克") bmi = weight / (height ** 2) print(person + "的BMI指数为:" + str(bmi)) # 判断身材是否合理 if bmi < 18.5: print("你的体重过轻\n") if bmi >= 18.5 and bmi < 24.9: print("正常范围,注意保持\n") if bmi >= 24.9 and bmi < 29.9: print("您的体重过重\n") if bmi >= 29.9: print("肥胖\n") # *******************************调用函数************************************* # fun_bmi(1.83, 60) # *******************************查看默认值参数************************************* # temp = fun_bmi.__defaults__ print(temp)
683c50bc6524b5ecb5d03617cf25b1d0039773dd
pedrodeoliveira/raspberrypi
/leds_buttons/reaction_game.py
563
3.5625
4
from gpiozero import Button, LED from time import sleep from random import uniform from os import _exit led = LED(4) right_button = Button(14) left_button = Button(15) left_name = input('Left player name is: ') right_name = input('Right player name is: ') led.on() sleep(uniform(5, 10)) led.off() def pressed(button): if button.pin.number == 14: print('here') print(f'{right_name} won the game!') else: print(f'{left_name} won the game!') _exit(0) right_button.when_pressed = pressed left_button.when_pressed = pressed
75d0d8250eabe212a2756b555505e49669ec49a2
ChristosVlachos2000/ErgasiesPython
/maxsequence.py
791
3.5
4
from sys import maxsize # Function to find the maximum contiguous subarray # and print its starting and telos index def maxSequence(a,size): max_mexri_stigmhs = -maxsize - 1 max_teliko = 0 arxi = 0 telos = 0 s = 0 for i in range(0,size): max_teliko += a[i] if max_mexri_stigmhs < max_teliko: max_mexri_stigmhs = max_teliko arxi = s telos = i if max_teliko < 0: max_teliko = 0 s = i+1 print (max_mexri_stigmhs) j = arxi while j <= telos: print ("[", a[j], telos='' "]" ) j = j + 1
fba702b99cbf2056eb30c1547771153a966cb5a6
Dowfree/learning
/6_try.py
521
3.875
4
class Car: def infor(self): print("This is a car") car = Car() car.infor() isinstance(car, Car) isinstance(car, str) if 5 > 3: pass class A: def __init__(self, value1=0, value2=0): self._value1 = value1 self.__value2 = value2 def setValue(self, value1, value2): self._value1 = value1 self.__value2 = value2 def show(self): print(self._value1) print(self.__value2) a = A() print(a._value1) print(a._A__value2)
62d0d299b8a4d069b60c39fa2f756e72d3f89fe9
cramer4/Python-Class
/Chapter_10/Homework_10-4.py
272
3.515625
4
def get_names(): with open("guest_list.txt", "a") as file_object: while True: name = input('What is your name? ("q" to quit): ') if name != "q": file_object.write(f"{name}\n") else: break get_names()
b0660d6dd630bb4d176784e020cf835899cb5f2b
cramer4/Python-Class
/Chapter_09/Homework_9-5.py
887
3.578125
4
class User: def __init__(self, first_name, last_name, age): self.f_name = first_name self.l_name = last_name self.age = age self.login_attempts = 0 def describe_user(self): print(f"\nUser info:\nFirst name: {self.f_name}\n" f"Last name: {self.l_name}\n" f"Age: {self.age}") def greet_user(self): print(f"\nHello {self.f_name} {self.l_name}!") def increment_login_attempts(self): self.login_attempts += 1 print(f"Login attempts: {self.login_attempts}") def reset_login_attempts(self): self.login_attempts = 0 print("Login attempts reset.") user = User("generic", "user", "") user.increment_login_attempts() user.increment_login_attempts() user.increment_login_attempts() user.reset_login_attempts() print(user.login_attempts)
e20be04e20b2bf15f303b4d1242f19a67d204290
cramer4/Python-Class
/Chapter_09/Homework_9-2.py
706
3.96875
4
class Restaurant: def __init__(self, name, cuisine): self.name = name self.cusine = cuisine self.open = True def describe_restaurant(self): print(f"{self.name} is a {self.cusine} restaurant.") def open_restaurant(self): if self.open == True: print(f"{self.name} is open!") else: print(f"{self.name} is closed.") jimmys_bbq = Restaurant("Jimmy's barbecue", "barbecue") le_crave = Restaurant("Le Crave", "French") franciscos = Restaurant("Francisco's Mexican Restaurant", "Mexican") restaurants = [jimmys_bbq, le_crave, franciscos] for restaurant in restaurants: restaurant.describe_restaurant()
d4a14dc2e7d3c0291e7cedc39e26d28b9a0b4c7b
cramer4/Python-Class
/Chapter_10/Homework_10-1.py
623
3.90625
4
########################################################### with open("learning_python.txt") as file: contents = file.read() print(contents.strip()) ########################################################### file = "learning_python.txt" with open("learning_python.txt") as file: for line in file: print(line.rstrip()) print("") ########################################################### with open("learning_python.txt") as f: for l in f: lines = f.readlines() for line in lines: print(line.rstrip()) ###########################################################
cc768b15d6b6c1670ad7af181ee00a662f67c3b2
cramer4/Python-Class
/Chapter_09/Homework_9-8.py
906
3.734375
4
class User: def __init__(self, first_name, last_name, age): self.f_name = first_name self.l_name = last_name self.age = age def describe_user(self): print(f"\nUser info:\nFirst name: {self.f_name}\n" f"Last name: {self.l_name}\n" f"Age: {self.age}") def greet_user(self): print(f"\nHello {self.f_name} {self.l_name}!") class Privileges: def __init__(self): self.privileges_list = ["can add post", "can delete post", "can ban user"] def show_privileges(self): for privilege in self.privileges_list: print(privilege.title()) class Admin(User): def __init__(self, first_name, last_name, age): super().__init__(first_name, last_name, age) self.privileges = Privileges() admin = Admin("admin", "admin", 35) admin.privileges.show_privileges()
404b6fb3b7e237e15fed1c24416226fc66fd9db5
cramer4/Python-Class
/Chapter_06/Homework_6-6.py
688
3.75
4
taken_poll = ["bill", "george", "john", "fred", "kieth"] favorite_numbers = {taken_poll[0]: 10, taken_poll[1]: 7, taken_poll[2]: 55, taken_poll[3]: 30, taken_poll[4]: 100} index = 0 for friend in taken_poll: print(f"{friend.title()}'s favorite number is {favorite_numbers[taken_poll[index]]}") index = index + 1 print("\n") poll = ["bill", "george", "john", "fred", "kieth", "bob", "tim"] for person in poll: if person in taken_poll: print(f"Thank you {person.title()} for taking our poll!") else: print(f"Would you like to take our poll {person.title()}?")
f43db38bbefb2552689ee6670952866672f9b074
cramer4/Python-Class
/Chapter_09/Homework_9-6.py
802
3.96875
4
class Restaurant: def __init__(self, name, cuisine): self.name = name self.cusine = cuisine self.open = True def describe_restaurant(self): print(f"{self.name} is a {self.cusine} restaurant.") def open_restaurant(self): if self.open == True: print(f"{self.name} is open!") else: print(f"{self.name} is closed.") class Ice_cream_stand(Restaurant): def __init__(self, name, cuisine): super().__init__(name, cuisine) self.flavors = ["vanilla", "chocolate", "strawberry"] def display_flavors(self): for flavor in self.flavors: print(flavor.title()) ice_cream_stand = Ice_cream_stand("Ice cream stand", "Ice cream") ice_cream_stand.display_flavors()
bba3a41dc0fa8e14843c0618c33c54873f76c9fb
cramer4/Python-Class
/Chapter_08/Homework_8-3.py
157
3.5625
4
def make_shirt(size, color): print(f"Made shirt that is {color} and size {size.upper()}.") make_shirt('m', 'red') make_shirt(color='blue', size='l')
9b0bbfbf98829d0315af9a743ddf0a533aba7434
miles0197/edabit_challanges
/HackerRank_practices.py
2,580
3.765625
4
#Question1 #get the input of 2 numbers from the user for each a and b, #Perform a product of a X b import itertools a = [int(x) for x in input().split(',')] b = [int(x) for x in input().split(',')] print(' , '.join(str(t) for t in itertools.product(a,b))) #Question2 #get the input for 2 numbers, try integer division, else raise error lines = int(input()) for _ in range(lines): a,b = input().split() try: print(int(a) // int(b)) except (ZeroDivisionError, ValueError) as e: print("Error Code: ", e) #Question 3 #Task #You have a non-empty set , and you have to execute commands given in lines. #The commands will be pop, remove and discard. #Input Format #The first line contains integer , the number of elements in the set . #The second line contains space separated elements of set . All of the elements are non-negative integers, less than or equal to 9. #The third line contains integer , the number of commands. #The next lines contains either pop, remove and/or discard commands followed by their associated value. #Constraints #Output Format #Print the sum of the elements of set on a single line. #Sample Input #9 #1 2 3 4 5 6 7 8 9 #10 #pop #remove 9 #discard 9 #discard 8 #remove 7 #pop #discard 6 #remove 5 #pop #discard 5 #Sample Output #4 n = int(input()) s = set(map(int, input().split())) print(s) N = int(input()) for i in range(N): choice = input().split() if choice[0] == "pop": s.pop() elif choice[0] == "discard": s.discard(int(choice[1])) elif choice[0] == "remove": s.remove(int(choice[1])) print(sum(s)) #Question #You are given n words. Some words may repeat. For each word, output its number of occurrences. #The output order should correspond with the input order of appearance of the word. #The first line contains the integer. #The next n lines each contain a word. #Output lines. #On the first line, output the number of distinct words from the input. #On the second line, output the number of occurrences for each distinct word according to their appearance in the input. #4 #bcdef #abcdefg #bcde #bcdef #Sample Output #3 #2 1 1 #Explanation #There are distinct words. Here, "bcdef" appears twice in the input at the first and last positions. #The other words appear once each. The order of the first appearances are "bcdef", "abcdefg" and "bcde" which corresponds to the output. import collections n = int(input()) words = [input().strip() for _ in range(n)] counter_words = collections.Counter(words) print(len(counter_words)) print(*counter_words.values())
ccfbbf92235fd2a7d5e181ca94e002e10bbaaaeb
miles0197/edabit_challanges
/display_next_prime_number.py
364
4.09375
4
# If the number is not prime, print the next number that is prime def is_prime(num): for i in range(2,num): if num % i ==0: return False return True def next_prime(num): if not is_prime(num): n = num + 1 while not is_prime(n): n += 1 return n else: return num print(next_prime(6))
a6949e9ec7aa2ff84e9b478aed8cd95033f5eabc
SanFranciscoSunrise/easyASCII
/easyASCII.py
8,068
4.34375
4
#!/usr/bin/python3 # # A simple python program to demonstrate writing numbers to the console # in BIG ASCII style. # import sys import os import collections import re #import getopt import argparse def setup_ascii_dictionary(dictionary_file): # Open our acii character reprentation database. # translate it into a dictionary describing which position # each symbol/letter occurs at in our list that holds a set of # lists each holding 1 of 7 rows describing the ascii representation # of each symbol try: asciiCharacterDB = open(dictionary_file,"r") # The first line in our database is always a string of the letters that are being # represented. So we get our "alphabet" that will be used to create our # dictionary later {letter(key), drawingAs7RowList(value)} alphabet = asciiCharacterDB.readline() alphabet = re.findall("\S",alphabet) # The original DB had an extra line in between the characters and their # representation for readability. So we move the pointer ahead one line asciiCharacterDB.readline() # File each row of each character into a list pixel_map = asciiCharacterDB.readlines() except: print("Error reading database file (check format)!") clean_pixel_map = [] for i in pixel_map: clean_pixel_map.append(re.findall("(?<=\" \")[^\"]+",i)) # Setup the dictionary using a dictinoary comprehension alphabet_dictionary = {character: number for number, character in enumerate(alphabet)} return alphabet_dictionary, clean_pixel_map def write_ascii(phrase_to_translate, alphabet_dictionary, clean_pixel_map, output_file): # Main program, write ascii to screen :-) try: for row in range(7): # iterate through every row of the screen line = "" # iterate through user input grabbing # each character and adding it's ascii representation # of the current row to the line we are on for column in range(len(phrase_to_translate)): keyValue = 0 if phrase_to_translate[column] == ' ': line += ' ' else: character = phrase_to_translate[column] # grab user input # lookup the position of # character in our dictionary # this should also match the position # of the character in the character database keyValue = alphabet_dictionary.get(character) symbols = clean_pixel_map[row] # grab current row of every character from # our database line += symbols[keyValue] # add the row of ascii for the current # character/column of our users input # to the line we are on # print current line to the screen for the row we are on print(line) if output_file: output_to_file(output_file, line) except IndexError: print("Index Error!") except ValueError as err: print(err, "in", digit, " unacceptable value") except TypeError as err: print("Error: attempt to translate symbol not defined in current font file.") def output_to_file(output_file, current_line): with open(output_file,'a') as outPut: outPut.write(current_line) outPut.write('\n') def main(): global dictionary_file global output_file global phrase_to_translate # The new way to parse command line using argparse if __name__ == "__main__": # Create argument parser from commandline parser = argparse.ArgumentParser(description='[*] writeASCII: \ Text to ASCII conversion tool', formatter_class=\ argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('Words', metavar='Words', nargs='+', help='Phrase to be converted to ASCII') parser.add_argument('-f', '--font', action='store', default='asciiCharacters.ezfnt', help='Db/Font used for translation', dest='character_db') parser.add_argument('-o', '--output', action='store', help='Output results to output_file', dest='output_file') parser.add_argument('-l', '--lengthwise', action='store_true', help='Force phrase to run horizontal. Often good \ for writing output to a file. Usually not so \ good for console output') parser.add_argument('-v', '--vertical', action='store_true', help='Force phrase to run fully vertical. Often good \ for console output and/or grabing individual \ characters one after another') args = parser.parse_args() # Setup our variables based on the arguments if os.path.exists(args.character_db): dictionary_file = args.character_db print('Using:', dictionary_file, ' as font for translation') else: parser.print_usage() print('File:', args.character_db, ' does not exist!') return(0) #if args.output_file and os.path.exists(args.output_file): # print('Are you sure you want to overwrite ', args.output_file,' ?') output_file = args.output_file # Setup the pixelmap and dictionary to lookup correct position in pixelmap alphabet_dictionary, clean_pixel_map = setup_ascii_dictionary(dictionary_file) # Easy way to call the main part that outputs def heart_beat(): write_ascii(word, alphabet_dictionary, clean_pixel_map, output_file) # We either output verticle, horizontal, or each word on # it's own verticle line if args.vertical: phrase_to_translate = ''.join(args.Words) for word in phrase_to_translate: heart_beat() elif args.lengthwise: word = ' '.join(args.Words) heart_beat() else: phrase_to_translate = args.Words for word in phrase_to_translate: heart_beat() main() # The old way of seting up the dictionary, now replaced with a concise # dictionary comprehension # # count = 0 # for character in alphabet: # alphabet_dictionary[character] = count # count += 1 # --The old way to parse command line using getopts-- (Depreciated) # usage() comes from old way..although I still like the visual look of my usage # better so until I figure out how to re-formate argparse help I'm keeping this # def usage(): # print("[*] writeASCII: Text to ASCII conversion tool") # print("Usage: writeASCII.py -d dictionary -o output_file -p phrase") # print() # print("-h --help - This usage message") # print("-d --dictionary - Use dictionary as DB for translation") # print("-o --output - Output results to output_file") # print("-p --phrase - Phrase to translate (not optional)") # print(" phrase must be...") # print() # print("-d and -o are optional.") # print("-d = asciiCharacters.db by default") # print("-o = stdout by default") # print() # print("Examples:") # print("writeASCII.py -d myAsciiCharacters.db -p \"Translate me\"") # print("writeASCII.py -d myAsciiCharacters.db -o myBigAscii.txt -p \"Transl$ # print("writeASCII.py -p \"Translate me\"") # sys.exit(0) # --The old way to parse command line using getopts-- (Depreciated) # # if not len(sys.argv[1:]): # usage() # # try: # opts, args = getopt.getopt(sys.argv[1:], "hd:o:p:", # ["dictionary", "output", "phrase"]) # # except getopt.GetoptError as err: # print(str(err)) # usage() # # for o,a in opts: # if o in ("-h", "--help"): # usage() # elif o in ("-d", "--dictionary"): # dictionaryFile = a # elif o in ("-o", "--output"): # outputFile = a # elif o in ("-p", "--phrase"): # phraseToTranslate = a # else: # assert False, "Unhandled Option"
a3d3afa4be2a23ad703070380efa5c45a853bee3
lichenga2404/intro-to-computer-vision-with-python-opencv
/00 Archived Scripts/00_reading_and_showing_images.py
4,745
3.859375
4
############################################################################### # BASICS 0.0: Reading, Showing & Saving Images with OpenCV and Matplotlib # # by: Todd Farr # ############################################################################### # imports import numpy as np import cv2 ################################################################# READING IMAGES print 'Loading Images: \n' # load an image # NOTE: OpenCV will import all images (grayscale or color) as having 3 channels, # to read an image only as a single channel pass the arg 0 after the image location img = cv2.imread('images/dolphin.png') img_single_channel = cv2.imread('images/dolphin.png', 0) print 'The shape of img without second arg is: {}'.format(img.shape) print 'The shape of img_single_channel is: {}\n'.format(img_single_channel.shape) ################################################################# DISPLAY IMAGES print 'Display Images using OpenCV imshow(): \n' # display the image with OpenCV imshow() #### 1st ARGUMENT --> the window name #### 2nd ARGUMENT --> the image to show # You can show as many images as you want at once, they just have to have #different window names cv2.imshow('OpenCV imshow()', img) # OpenCV waitKey() is a required keyboard binding function after imwshow() # Its argument is the time in milliseconds. The function waits for specified # milliseconds for any keyboard event. If you press any key in that time, # the program continues. If 0 is passed, it waits indefinitely for a key stroke. # It can also be set to detect specific key strokes like if key a is pressed etc. cv2.waitKey(0) # NOTE: Besides binding keyboard events this waitKey() also processes many # other GUI events, so you MUST use it to actually display the image. # destroy all windows command # simply destroys all the windows we created. If you want to destroy any specific # window, use the function cv2.destroyWindow() where you pass the exact window # name as the argument. cv2.destroyAllWindows() # NOTE: There is a special case where you can already create a window and load # image to it later. In that case, you can specify whether window is resizable # or not. It is done with the function cv2.namedWindow(). By default, the flag # is cv2.WINDOW_AUTOSIZE. But if you specify flag to be cv2.WINDOW_NORMAL, # you can resize window. It will be helpful when image is too large in dimension # and adding track bar to windows. cv2.namedWindow('Named-Empty Resizable Window', cv2.WINDOW_NORMAL) cv2.imshow('Dolphins are awesome!',img) cv2.waitKey(0) cv2.destroyAllWindows() ################################################################## SAVING IMAGES print 'Saving Images using OpenCV imwrite():' # write an image with imwrite # first argument is the file name # second argument is the image you want to save cv2.imwrite('images/dolphin_2.png', img) # summing it up all together, saving on 's' img = cv2.imread('images/dolphin.png') cv2.imshow('Option to Save image', img) print "press 's' to save the image as dolphin_3.png\n" key = cv2.waitKey(0) # NOTE: if you are using a 64-bit machine see below. # The above line needs to be: key = cv2.waitKey(0) & 0xFF if key == 27: # wait for the ESC key to exit cv2.destroyAllWindows() elif key == ord('s'): # wait for 's' key to save and exit cv2.imwrite('images/dolphin_3.png', img) cv2.destroyAllWindows() ################################################# DISPLAY IMAGES WITH MATPLOTLIB print 'Display Images using Matplotlib: \n' # display a B+W Image import matplotlib.pyplot as plt img = cv2.imread('images/dolphin.png') plt.title('Monochormatic Images in Matplotlib') plt.imshow(img, cmap='gray', interpolation='bicubic') plt.xticks([]), plt.yticks([]) # hide x and y tick values plt.show() # get the image size height, width = img.shape[:2] print 'Image Width: {}px, Image Height: {}px'.format(width, height) print 'Image Type: {}'.format(type(img)) # openCV stores images as np.ndarray # *WARNING*: Color images loaded by OpenCV is in BGR mode. But Matplotlib # displays in RGB mode. So color images will not be displayed correctly in # Matplotlib if image is read with OpenCV. # *WRONG* # Example of how matplotlib displays color images from OpenCV incorrectly img_color = cv2.imread('images/fruit.png') plt.title('How OpenCV images (BGR) display in Matplotlib (RGB)') plt.imshow(img_color), plt.xticks([]), plt.yticks([]) plt.show() # *CORRECT* # Option #1 convert the color using cv2.COLOR_BGR2RGB img_rgb = cv2.cvtColor(img_color, cv2.COLOR_BGR2RGB) plt.title('Correct Display after converting with cv2.COLOR_BGR2RGB') plt.imshow(img_rgb), plt.xticks([]), plt.yticks([]) plt.show()
3353d43c6abc42eead880c624da5bc26c1a812f8
balckwoo/pycode2
/pybasic/编码解码.py
309
3.84375
4
# 第一个是字符串 strvar = 'admin' print(strvar) # 字节码 bytevar2 = b'admin' print(bytevar2) bytevar = b'hello' print(bytevar) # 解码(把bytes类型转换utf-8类型) decode print(bytevar.decode()) strvar = 'hello' # 编码 (把utf-8类型转化bytes类型)encode print(strvar.encode())
c4f7f9151ce3b2b86a1c4282f62f9377daddf22c
balckwoo/pycode2
/pybasic/异常处理.py
1,331
3.5
4
# var = 'gaf' # # 正常语法,代码没有错误 # try: # # 可能出错的代码 # var1 = int(var) # # 捕获我错误代码的异常并输出(如果代码的语法是没有问题的是不会走到except里面) # except BaseException as msg: # print(msg) # BaseException 是万能的错误异常类型 # try: # print(hello) # except BaseException as msg: # print('错误的异常是',msg) # else: # print('nihao') # else 语法当我的try代码块里面没有问题的话就会去执行 # try: # print('hello') # except BaseException as msg: # print('错误的异常是', msg) # else: # print('nihao') # finally的代码,不管我try 里面的代码块是否正确,它都会执行 # try: # print('hello') # except BaseException as msg: # print('错误的异常是',msg) # finally: # print('nihao') # # 综合场景 # try: # print(这是一个没有错的代码块) # except BaseException as msg: # print(msg) # else: # print('try代码没有问题的话就会执行这里') # finally: # print('不管try代码块里面有没有问题他都会执行') a = None try: if a == None: # 主动抛出异常 raise EOFError print('出错了之后代码就不会走到这里') except BaseException as msg: print('代码出错了')
b3f03122b27774e57f02e65eab863d713c55f11d
sqeezy/project_euler
/problem003.py
642
4.09375
4
import sys def prim_factors(n): result = [] if n<0: n = -n if n<2: return [n] while n%2 == 0: result.append(2) n/=2 for candidate in range(3,int(n**0.5+1),2): while(n%candidate==0): result.append(candidate) n/=candidate if n>2: result.append(n) return result if __name__ == '__main__': try: number = int(raw_input("Enter a number to evaluate prime factors from...\n"))#600851475143 except ValueError: exit("Not a integer!") factors = prim_factors(number) print "The prime factors are {}.".format(factors)
540a2bce95b7d3f74ea2c9314024eee32cdf6240
sqeezy/project_euler
/problem014.py
371
3.59375
4
def next(n): if n%2==0: return n/2 else: return 3*n+1 def sequence(n): seq = [n] while n!=1: n = next(n) seq.append(n) return seq maxLen = 0 maxNum = 0 for i in range(1,10**6): curLen = len(sequence(i)) if curLen>maxLen: maxLen=curLen maxNum = i print maxLen print maxLen print maxNum
a46122503fed9b81fe6d6b28d6d701d77b45f11e
sqeezy/project_euler
/problem005.py
1,180
3.59375
4
def prim_factors(n): result = [] if n<0: n = -n if n<2: return [n] while n%2 == 0: result.append(2) n/=2 for candidate in range(3,int(n**0.5+1),2): while(n%candidate==0): result.append(candidate) n/=candidate if n>2: result.append(n) return result def lcm(numbers): if type(numbers)!=list: raise ValueError("numbers is not of type 'list'") for num in numbers: try: int(num) except ValueError: raise ValueError("Not all members of numbers are of type 'int'.") resultFactorExponents = dict() for number in numbers: factors = prim_factors(number) for fac in factors: if fac not in resultFactorExponents: resultFactorExponents[fac] = factors.count(fac) else: if factors.count(fac)>resultFactorExponents[fac]: resultFactorExponents[fac] = factors.count(fac) result = 1 for key in resultFactorExponents.keys(): result *= key**resultFactorExponents[key] return result divs = range(1,21) print lcm(divs)
3f74b15f1f12c2ca70772ef22540eebf2598a12c
krinj/logkit
/logkit/utils/truncate.py
707
3.6875
4
# -*- coding: utf-8 -*- """ Truncates string or JSON data so that it fits a specific number of characters. """ __author__ = "Jakrin Juangbhanich" __email__ = "juangbhanich.k@gmail.com" def truncate(message: str, max_length: int=128, split_ratio: float=0.8) -> str: """ Truncates the message if it is longer than max_length. It will be split at the 'split_ratio' point, where the remaining last half is added on. """ if max_length == 0 or len(message) <= max_length: return message split_index_start = int(max_length * split_ratio) split_index_end = max_length - split_index_start message_segments = [message[:split_index_start], message[-split_index_end:]] return " ... ".join(message_segments)
e8463008f9b373d322264bbaadb0afddaba1978a
Twice22/VQA
/utils.py
10,254
3.5
4
import operator import numpy as np import collections from collections import Counter import csv def fillup(my_set, my_list, K): """ Args: my_set (set of strings): set of unique most used words to fill up my_list (list of strings): list of words in descending order of frequency of apparation K (int): number of words of my_list to add to my_set Returns: my_set (set of strings): set of words + K most frequent words from my_list """ length = len(my_set) + K i = 0 while len(my_set) != length: my_set[my_list[i]] = 0 i += 1 return my_set def bow(data_question, data_q, K=1000): """ Args: data_question (json): json of all the questions of the Visual Question Answering (VQA) task from the training set data_q (json): json of all the questions of the Visual Question Answering (VQA) task from the validation set K (int): number of most frequent words from the question dataset to keep Returns: unique_words (list): list containing the K most frequent words from the question dataset """ questions = data_question['questions'] ques_val = data_q['questions'] d = dict() q_array = [questions, ques_val] for data in q_array: for q in data: question = q['question'][:-1].lower().split() for w in question: d[w] = 1 if w not in d else d[w] + 1 KmostFreqWords = np.array(sorted(d.items(), key=operator.itemgetter(1), reverse=True))[:K, 0] return list(KmostFreqWords) def bow_q123(data_question, data_q, K=10): """ Args: data_question (json): json of all the questions of the Visual Question Answering (VQA) task from the training set data_q (json): json of all the questions of the Visual Question Answering (VQA) task from the validation set K (int): number of top first, second and third words to keep from the questions to construct the bag-of-word Returns: unique_words (list): list containing the K top first, second, third most commons words from the set of questions """ questions = data_question['questions'] ques_val = data_q['questions'] firstWords = dict() secondWords = dict() thirdWords = dict() q_array = [questions, ques_val] for data in q_array: for q in data: question = q['question'][:-1].lower().split() if len(question) >= 1: firstWords[question[0]] = 1 if question[0] not in firstWords else firstWords[question[0]] + 1 if len(question) >= 2: secondWords[question[1]] = 1 if question[1] not in secondWords else secondWords[question[1]] + 1 if len(question) >= 3: thirdWords[question[2]] = 1 if question[2] not in thirdWords else thirdWords[question[2]] + 1 top10_1w = np.array(sorted(firstWords.items(), key=operator.itemgetter(1), reverse=True))[:, 0] top10_2w = np.array(sorted(secondWords.items(), key=operator.itemgetter(1), reverse=True))[:, 0] top10_3w = np.array(sorted(thirdWords.items(), key=operator.itemgetter(1), reverse=True))[:, 0] # set doesn't keep order so I've used OrderedDict() instead unique_words = collections.OrderedDict() # fill up the bag of words with UNIQUE words unique_words = fillup(unique_words, top10_1w, K) unique_words = fillup(unique_words, top10_2w, K) unique_words = fillup(unique_words, top10_3w, K) return list(unique_words) def preprocess_data(data_question, data_answer, data_qval, data_aval): """ Args: data_question (json): json of all the questions of the Visual Question Answering (VQA) task from the training set data_answer (json): json of all the answers of the Visual Question Answering (VQA) task from the training set data_qval (json): json of all the questions of the Visual Question Answering (VQA) task from the validation set data_aval (json): json of all the answers of the Visual Question Answering (VQA) task from the validation set Returns: training_dict (dict): training dictionary with keys in ['images_id', 'questions_id', 'questions', 'questions_len', 'answers'] validation_dict (dict): validation dictionary with keys in ['images_id', 'questions_id', 'questions', 'questions_len', 'answers'] answers (list): list of all the answers (string) in the training and validation sets Example: data_q = json.load(open('Questions/v2_OpenEnded_mscoco_train2014_questions.json')) data_a = json.load(open('Annotations/v2_mscoco_train2014_annotations.json')) data_qval = json.load(open('Questions/v2_OpenEnded_mscoco_val2014_questions.json')) data_aval = json.load(open('Annotations/v2_mscoco_val2014_annotations.json')) training_dict, validation_dict, answers = preprocess_data(data_q, data_a, data_qval, data_aval) """ keys = ['images_id', 'questions_id', 'questions', 'questions_len', 'answers'] training_dict = dict((k, []) for k in keys) validation_dict = dict((k, []) for k in keys) answers = [] data_ans = data_answer['annotations'] data_ques = data_question['questions'] data_ans_val = data_aval['annotations'] data_ques_val = data_qval['questions'] ques = [data_ques, data_ques_val] ans = [data_ans, data_ans_val] d = collections.defaultdict(dict) for qu in ques: for i in range(len(qu)): q_id = qu[i]['question_id'] img_id = qu[i]['image_id'] question = qu[i]['question'] d[img_id][q_id] = [question,len(question.split()) + 1] # add one for the interrogation point for idx, an in enumerate(ans): for i in range(len(an)): if idx == 0: img_id = an[i]['image_id'] q_id = an[i]['question_id'] training_dict['questions_id'].append(q_id) training_dict['images_id'].append(img_id) training_dict['answers'].append(an[i]['multiple_choice_answer']) answers.append(an[i]['multiple_choice_answer']) training_dict['questions'].append(d[img_id][q_id][0]) training_dict['questions_len'].append(d[img_id][q_id][1]) else: img_id = an[i]['image_id'] q_id = an[i]['question_id'] validation_dict['questions_id'].append(q_id) validation_dict['images_id'].append(img_id) validation_dict['answers'].append(an[i]['multiple_choice_answer']) answers.append(an[i]['multiple_choice_answer']) validation_dict['questions'].append(d[img_id][q_id][0]) validation_dict['questions_len'].append(d[img_id][q_id][1]) return training_dict, validation_dict, answers def topKFrequentAnswer(data_q, data_a, data_qval, data_aval, K=1000): """ Args: data_q (json): json file of all the questions of the Visual Question Answering (VQA) task from the training set data_a (json): json file of all the questions of the Visual Question Answering (VQA) task from the training set data_qval (json): json of all the questions of the Visual Question Answering (VQA) task from the validation set data_aval (json): json of all the answers of the Visual Question Answering (VQA) task from the validation set K (int): number of most frequent answers to keep (it will keep only the questions, questions id, images id, ...) associated to the K msot frequent answers.(default: K=1000) Returns: training_dict (dict): training dictionary whose answers are in the top K answers with keys in ['images_id', 'questions_id', 'questions', 'questions_len', 'answers'] validation_dict (dict): validation dictionary whose answers are in the top K answers with keys in ['images_id', 'questions_id', 'questions', 'questions_len', 'answers'] topKAnswers (list): top K answers recover from training+validation sets Example: data_q = json.load(open('Questions/v2_OpenEnded_mscoco_train2014_questions.json')) data_a = json.load(open('Annotations/v2_mscoco_train2014_annotations.json')) data_qval = json.load(open('Questions/v2_OpenEnded_mscoco_val2014_questions.json')) data_aval = json.load(open('Annotations/v2_mscoco_val2014_annotations.json')) K_training_dict, K_validation_dict, topKAnswers = topKFrequentAnswer(data_q, data_a, data_qval, data_aval) """ training_dict, validation_dict, answers = preprocess_data(data_q, data_a, data_qval, data_aval) d = dict() # retrieve the top K answers for answer in answers: d[answer] = 1 if answer not in d else d[answer] + 1 topKAnswers = np.array(sorted(d.items(), key=lambda x: (x[1], x[0]), reverse=True)[:K])[:, 0] # keep only question_id, image_id, questions, questions_len associated with the topKAnswers keys = ['images_id', 'questions_id', 'questions', 'questions_len', 'answers'] K_training_dict = dict((k, []) for k in keys) K_validation_dict = dict((k, []) for k in keys) dicts = [training_dict, validation_dict] K_dicts = [K_training_dict, K_validation_dict] for di, K_di in zip(dicts, K_dicts): for idx, ans in enumerate(di['answers']): if ans in topKAnswers: K_di['images_id'].append(di['images_id'][idx]) K_di['questions_id'].append(di['questions_id'][idx]) K_di['questions'].append(di['questions'][idx]) K_di['questions_len'].append(di['questions_len'][idx]) K_di['answers'].append(di['answers'][idx]) return K_training_dict, K_validation_dict, topKAnswers def getVoc(training_questions, validation_questions): """ Args: training_questions (list of strings): list of training questions validation_questions (list of strings): list of validation questions Returns: voc (dict): dictionary of all unique words that appears in all questions associated with there index in the embedding matrix """ voc = collections.OrderedDict() for q in training_questions: words = q[:-1].lower().split() # -1 to trim '?' for w in words: voc[w] = 0 for q in validation_questions: words = q[:-1].lower().split() # -1 to trim '?' for w in words: voc[w] = 0 return {v: i for i, (v, k) in enumerate(voc.items())} def ltocsv(l, filename): """ Args: l (list): input list filename (string): name of the csv file to create Returns: create a csv file containing the values of the input list """ with open(filename, 'w') as f: wr = csv.writer(f, quoting=csv.QUOTE_NONE) wr.writerow(l) def csvtol(filename): """ Args: filename (string): name of the csv file containing the list on one row Returns: l (list): create a list containing the values of the csv file """ l = [] with open(filename, 'r') as f: wr = csv.reader(f, quoting=csv.QUOTE_NONE) for row in wr: for r in row: l.append(r) return l
bd3ed4a8b2ecd34850ed439dc7a52892cf782ba7
pintotomas/simulacion
/TP1/ejercicios/TPEj6.py
601
3.96875
4
#/usr/bin/env/ python # -*- coding: utf-8 -*- import matplotlib.pyplot as plt import random #Generador de números aleatorios que provee PYTHON def aleatorio(): return random.uniform(-1,1) listaDeValores1=[] listaDeValores2=[] #Genero 1000 valores(por ejemplo) for i in range(0,10000): x = aleatorio() y = aleatorio() if ( x**2 + y**2) < 1: listaDeValores1.append(x) listaDeValores2.append(y) #Gráfico plt.title('Grafico utilizando una distribucion uniforme') plt.plot(listaDeValores1,listaDeValores2,'o',markersize=1) plt.xlabel('Valores de X') plt.ylabel('Valores de Y') plt.show()
b3aea64f494ef54d7b165eca3aa50dd463ce8e88
Takayama2258/AI-Pacman-Project_Search
/multiagent/multiAgents.py
11,651
4.125
4
from util import manhattanDistance from game import Directions import random, util from game import Agent class ReflexAgent(Agent): """ A reflex agent chooses an action at each choice point by examining its alternatives via a state evaluation function. The code below is provided as a guide. You are welcome to change it in any way you see fit, so long as you don't touch our method headers. """ def getAction(self, gameState): """ You do not need to change this method, but you're welcome to. getAction chooses among the best options according to the evaluation function. Just like in the previous project, getAction takes a GameState and returns some Directions.X for some X in the set {North, South, West, East, Stop} """ # Collect legal moves and successor states legalMoves = gameState.getLegalActions() # Choose one of the best actions scores = [self.evaluationFunction(gameState, action) for action in legalMoves] bestScore = max(scores) bestIndices = [index for index in range(len(scores)) if scores[index] == bestScore] chosenIndex = random.choice(bestIndices) # Pick randomly among the best "Add more of your code here if you want to" return legalMoves[chosenIndex] def evaluationFunction(self, currentGameState, action): """ Design a better evaluation function here. The evaluation function takes in the current and proposed successor GameStates (pacman.py) and returns a number, where higher numbers are better. The code below extracts some useful information from the state, like the remaining food (newFood) and Pacman position after moving (newPos). newScaredTimes holds the number of moves that each ghost will remain scared because of Pacman having eaten a power pellet. Print out these variables to see what you're getting, then combine them to create a masterful evaluation function. """ # Useful information you can extract from a GameState (pacman.py) prevFood = currentGameState.getFood() successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood() newGhostStates = successorGameState.getGhostStates() newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates] "*** YOUR CODE HERE ***" score=0 foods = newFood.asList() if len(foods)!=0: food_dist = [manhattanDistance(newPos, food) for food in foods] minFood = min(food_dist) score-=2*minFood score-=1000*len(foods) ghost_dist = [manhattanDistance(newPos, ghost.getPosition()) for ghost in newGhostStates] minGhost = min(ghost_dist) score+=minGhost return score def scoreEvaluationFunction(currentGameState): """ This default evaluation function just returns the score of the state. The score is the same one displayed in the Pacman GUI. This evaluation function is meant for use with adversarial search agents (not reflex agents). """ return currentGameState.getScore() class MultiAgentSearchAgent(Agent): """ This class provides some common elements to all of your multi-agent searchers. Any methods defined here will be available to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent. You *do not* need to make any changes here, but you can if you want to add functionality to all your adversarial search agents. Please do not remove anything, however. Note: this is an abstract class: one that should not be instantiated. It's only partially specified, and designed to be extended. Agent (game.py) is another abstract class. """ def __init__(self, evalFn = 'scoreEvaluationFunction', depth = '2'): self.index = 0 # Pacman is always agent index 0 self.evaluationFunction = util.lookup(evalFn, globals()) self.depth = int(depth) class MinimaxAgent(MultiAgentSearchAgent): """ Your minimax agent (question 2) """ def getAction(self, gameState): """ Returns the minimax action from the current gameState using self.depth and self.evaluationFunction. Here are some method calls that might be useful when implementing minimax. gameState.getLegalActions(agentIndex): Returns a list of legal actions for an agent agentIndex=0 means Pacman, ghosts are >= 1 gameState.generateSuccessor(agentIndex, action): Returns the successor game state after an agent takes an action gameState.getNumAgents(): Returns the total number of agents in the game gameState.isWin(): Returns whether or not the game state is a winning state gameState.isLose(): Returns whether or not the game state is a losing state """ "*** YOUR CODE HERE ***" def minimax(state, agent, depth): result=[] if not state.getLegalActions(agent) or depth == self.depth: return (self.evaluationFunction(state),0) if agent == self.index: #Pacman result=[-1e10,''] for a in state.getLegalActions(agent): s = state.generateSuccessor(agent,a) newResult=minimax(s,agent+1,depth) oldResult = result[0] if newResult[0] > oldResult: result[0]=newResult[0] result[1]=a return result else: #Ghost result=[1e10,''] for a in state.getLegalActions(agent): s = state.generateSuccessor(agent,a) if agent == (state.getNumAgents()-1): #last ghost newResult=minimax(s,self.index,depth+1) else: newResult=minimax(s,agent+1,depth) oldResult = result[0] if newResult[0] < oldResult: result[0]=newResult[0] result[1]=a return result return minimax(gameState, self.index, 0)[1] class AlphaBetaAgent(MultiAgentSearchAgent): """ Your minimax agent with alpha-beta pruning (question 3) """ def getAction(self, gameState): """ Returns the minimax action using self.depth and self.evaluationFunction """ "*** YOUR CODE HERE ***" def purn(state, agent, depth, a, b): result=[] if depth == self.depth or (not state.getLegalActions(agent)): return (self.evaluationFunction(state),0) if agent == self.index: #Pacman result=[-1e10,''] for action in state.getLegalActions(agent): s = state.generateSuccessor(agent,action) if result[0] > a: return result oldResult = result[0] newResult=purn(s,agent+1,depth,a,b) if newResult[0] > oldResult: result[0]=newResult[0] result[1]=action b = max(b,result[0]) if b > a: return result if agent != self.index: #Ghost result=[1e10,''] for action in state.getLegalActions(agent): s = state.generateSuccessor(agent,action) oldResult = result[0] if result[0] < b: return result if agent == (state.getNumAgents()-1): #last ghost newResult=purn(s,self.index,depth+1,a,b) else: newResult=purn(s,agent+1,depth,a,b) if newResult[0] < oldResult: result[0]=newResult[0] result[1]=action a = min(a,result[0]) if b > a: return result return result return purn(gameState, self.index, 0, 1e11, -1e11)[1] class ExpectimaxAgent(MultiAgentSearchAgent): """ Your expectimax agent (question 4) """ def getAction(self, gameState): """ Returns the expectimax action using self.depth and self.evaluationFunction All ghosts should be modeled as choosing uniformly at random from their legal moves. """ "*** YOUR CODE HERE ***" def exp(state, agent, depth): result=[] if not state.getLegalActions(agent) or depth == self.depth: return (self.evaluationFunction(state),0) if agent == self.index: #Pacman result=[-1e10,''] for a in state.getLegalActions(agent): s = state.generateSuccessor(agent,a) newResult=exp(s,agent+1,depth) oldResult = result[0] if newResult[0] > oldResult: result[0]=newResult[0] result[1]=a return result else: #Ghost result=[0,''] for a in state.getLegalActions(agent): s = state.generateSuccessor(agent,a) if agent == (state.getNumAgents()-1): #last ghost newResult=exp(s,self.index,depth+1) else: newResult=exp(s,agent+1,depth) oldResult = result[0] p = len(state.getLegalActions(agent)) result[0]=result[0]+(float(newResult[0])/p) result[1]=a return result return exp(gameState, self.index, 0)[1] def betterEvaluationFunction(currentGameState): """ Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable evaluation function (question 5). DESCRIPTION: <score the foods, capsules, ghost and scared ghosts seperately. For food, capsules and scared ghost, the smaller the total number is the better. I weight the capsule more than the food as eat one capsule will gain more points. Closer food, capsules or scared ghost will weight more. For the ghost Pacman should avoid it especially when it is very close, Pacman should try to never be caught by ghost thus when a ghost is very close the state is assigned to a very low score.> """ "*** YOUR CODE HERE ***" score = currentGameState.getScore() position = currentGameState.getPacmanPosition() ghosts = currentGameState.getGhostStates() capsules = currentGameState.getCapsules() foods = currentGameState.getFood().asList() score -= len(foods)*10 foodDist = [manhattanDistance(position, food) for food in foods] if foodDist: score -= min(foodDist) for food in foodDist: score+= 5.0/food capDist = [manhattanDistance(position, cap) for cap in capsules] score -= len(capsules)*40 if capDist: score -= min(capDist)*10 scareDist = [] ghostDist = [] for ghost in ghosts: distance = manhattanDistance(position, ghost.getPosition()) if ghost.scaredTimer: scareDist.append(distance) else: ghostDist.append(distance) score -= len(scareDist)*10 if scareDist: score += 50.0/min(scareDist) if ghostDist: if min(ghostDist)<2: score += min(ghostDist)*50 for dist in ghostDist: if dist >0 and dist<7: score -= pow(3.0/dist,2) return score # Abbreviation better = betterEvaluationFunction
87be5bedc854bdd1d17fa548d74e6e19fcecc970
LauraRio12/coding_exercises
/Subject 5/ex13_and.py
260
4.0625
4
number_1= input ("Enter a first number") number_2= input ("Enter a second number") if float(number_1)> 10 and float(number_2)>10: print("Both numbers are greater than 10.") else: print("At least one of the numbers you entered is not greater than 10")
bc26f90037a7d05108a8fa5421803d9b40f886aa
LauraRio12/coding_exercises
/Subject 5/ex10_elif.py
399
4.03125
4
first_number= input("Enter a first number") second_number= input("Enter a second number") result= float(second_number)-float(first_number) if result>10: print("The result is greater than 10.") elif result>0: print("The result is greater than 0 but not than 10.") elif result==0: print("The result is zero.") else: print("The result is a negative number.") print("You can try again!")
dc4cfcc11c9b26f1e27874d1b9ac84291664b33c
susanbruce707/hexatrigesimal-to-decimal-calculator
/dec_to_base36_2.py
696
4.34375
4
# -*- coding: utf-8 -*- """ Created on Fri Dec 21 23:38:34 2018 Decimal to hexatrigesimal calculator. convert decimal number to base 36 encoding; use of letters with digits. @author: susan """ def dec_to_base36(dec): """ converts decimal dec to base36 number. returns ------- sign+result """ chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' sign = '-' if dec < 0 else '' dec = abs(dec) result = '' while dec > 0: dec, remainder = divmod(dec, 36) result = chars[remainder]+result return sign+result dec = int(input("please enter a Decimal number, e.g. 683248722 :> ")) A = dec_to_base36(dec) print(A)
49272cf6c1b0a8d1c5f14e87174fd6b02ba7f184
sagarch1234/snowflake
/system_users/utilities.py
2,291
3.78125
4
''' Python imports. ''' import random import string import re from rest_framework import status def capitalize_name(input_name): """ Method to capitalize first character of name. If '.' is present in string then first character of every list element after splitting input string by '.' is capitalized. This method should be called iff is_valid_name() returns True. Input : name (allowed) Output : Capitalized name """ splitted_name = input_name.split('.') word_list = [] for word in splitted_name: word_list.append(word[0].upper() + word[1:]) return ('.'.join(word_list)) def generate_password(): ''' This method is to generate password which has at least one lowercase, uppercase, digit and special character. ''' randomSource = string.ascii_letters + string.digits + string.punctuation password = random.choice(string.ascii_lowercase) password += random.choice(string.ascii_uppercase) password += random.choice(string.digits) password += random.choice(string.punctuation) for i in range(3): password += random.choice(randomSource) passwordList = list(password) random.SystemRandom().shuffle(passwordList) password = ''.join(passwordList) return password def generate_otp(): ''' This method will generate 4 digit random number. ''' otp = random.randint(1111, 9999) return otp def verify_otp_exist(user_id): from .models import EmailVerificationOtp try: generated_otp = EmailVerificationOtp.objects.get(user=user_id) return { "message" : "OTP exist.", "otp" : generated_otp.otp, "user": generated_otp.user.id, "status" : status.HTTP_302_FOUND } except EmailVerificationOtp.DoesNotExist: return { "message" : "OTP was not generated for the provided user.", "status" : status.HTTP_404_NOT_FOUND } def store_otp(otp, user_instance): from .models import EmailVerificationOtp, User otp = generate_otp() store_otp = EmailVerificationOtp(user=user_instance, otp=otp) otp_instance = store_otp.save() return otp
d1ef77588354c2667f2e31b089a9b04dd71bae55
somnath1077/statistical_rethinking
/code/ch02/s03_normal_approx.py
1,987
3.5625
4
# We first generate the posterior as in s02_grid_compute.py and then # approximate a normal distribution to the data import matplotlib.pyplot as plt import numpy as np from scipy.stats import binom, norm, beta NUM_PTS = 20 p_grid = np.linspace(start=0, stop=1, num=NUM_PTS) # Uniform prior is a special case of the Beta distribution prior = [1] * NUM_PTS # The likelihood is Binomial(n, p). Note that the Beta-Binomial is a conjugate pair. likelihood = binom.pmf(k=6, n=9, p=p_grid) # Compute the un-normalized posterior unnormalized_posterior = likelihood * prior # Normalized posterior posterior = unnormalized_posterior / sum(unnormalized_posterior) # Normal approximation # the mean of the posterior distribution is mu = np.sum(p_grid * posterior) # The variance = E[X**2] - (E[X])**2 exp_x_squared = np.sum(np.square(p_grid) * posterior) std = np.sqrt(exp_x_squared - mu ** 2) print(f'posterior mean = {mu}, posterior standard deviation = {std}') norm_approx_posterior = norm.pdf(p_grid, loc=mu, scale=std) # The Beta dist. is a conjugate pair of the binomial dist # More specifically, if X_1, ..., X_n are iid random variables from a Binomial dist. # with parameter p, and p ~ Beta(a, b), then the posterior distribution of p # given X_1 = x_1, ..., X_n = x_n is Beta(a + sum(x_1, ..., x_n), b + n - sum(x_1, ..., x_n)) # Since Uniform(0, 1) = Beta(1, 1), the hyper-parameter update rule after observing water W times # and land L times is a = W + 1 and b = L + 1 W = 6 L = 3 beta_data = beta.pdf(p_grid, W + 1, L + 1) beta_mu = beta.mean(W + 1, L + 1) beta_std = beta.std(W + 1, L + 1) norm_approx = norm.pdf(p_grid, beta_mu, beta_std) # Plot both the analytically obtained posterior and the normal approximation plt.plot(p_grid, beta_data, 'bo-', label='beta') plt.plot(p_grid, norm_approx, 'ro-', label='normal') plt.xlabel('Fraction of water') plt.ylabel('Beta(W=6, L=3)') plt.title(f'Sample= WLWWWLWLW; number of grid points = {NUM_PTS}') plt.legend() plt.show()
bd491b4e19652cf54254c0f170c7e4e954b5927b
vedantgoyal/unary_modular_simulator
/basic_blocks.py
2,503
3.59375
4
from connector import * class LC: # Logic Circuits have names and an evaluation function defined in child # classes. They will also contain a set of inputs and outputs. def __init__(self, name): self.name = name def evaluate(self): return class Not(LC): # Inverter. Input A. Output B. def __init__(self, name): LC.__init__(self, name) self.A = Connector(self, 'A', activates=1) self.Out = Connector(self, 'Out') def evaluate(self): self.Out.set(not self.A.value) class Gate2(LC): # two input gates. Inputs A and B. Output C. def __init__(self, name): LC.__init__(self, name) self.A = Connector(self, 'A', activates=1) self.B = Connector(self, 'B', activates=1) self.Out = Connector(self, 'Out') class And(Gate2): # two input AND Gate def __init__(self, name): Gate2.__init__(self, name) def evaluate(self): self.Out.set(self.A.value and self.B.value) class Or(Gate2): # two input OR gate. def __init__(self, name): Gate2.__init__(self, name) def evaluate(self): self.Out.set(self.A.value or self.B.value) class Xor(Gate2): def __init__(self, name): Gate2.__init__(self, name) self.A1 = And("A1") # See circuit drawing to follow connections self.A2 = And("A2") self.I1 = Not("I1") self.I2 = Not("I2") self.O1 = Or("O1") self.A.connect([self.A1.A, self.I2.A]) self.B.connect([self.I1.A, self.A2.A]) self.I1.B.connect([self.A1.B]) self.I2.B.connect([self.A2.B]) self.A1.Out.connect([self.O1.A]) self.A2.Out.connect([self.O1.B]) self.O1.Out.connect([self.Out]) class Multiplexer(LC): def __init__(self,name): LC.__init__(self, name) self.A = Connector(self, 'A', activates=1) self.B = Connector(self, 'B', activates=1) self.C = Connector(self, 'C', activates=1) self.Out = Connector(self, 'Out') def evaluate(self): if self.C.value == 0: self.Out.set(self.A.value) elif self.C.value ==1: self.Out.set(self.B.value) else: self.Out.set(None) class Dmem(LC): def __init__(self,name): LC.__init__(self, name) self.D = Connector(self, 'D') self.Clk = Connector(self, 'Clk', activates=1) self.Q = Connector(self, 'Q') self.Q_bar = Connector(self, 'Q_bar') def evaluate(self): self.Q.set(self.D.value) self.Q_bar.set(not self.D.value)
29adf683e283b094c85b51926e760405a9d9bc46
nkarg/Funciones
/funcioni.py
529
3.75
4
# -*- coding: utf-8 -*- def tipoNum(n): if n <= 0: print "Error ", n, " no es un numero natural" else: cant = 0 resp = "" print "El numero ", n, " tiene como divisores a: " for i in range(1, n+1): if n % i == 0: resp = resp + str(i) + "-" cant = cant + i print resp if cant == n: print " La suma es:", cant, "El numero es Perfecto" return elif cant < n: print " La suma es:", cant, "El numero es Deficiente" return else: print "La suma es:", cant, "El numero es abundante" return
197b5b82c6797daaa77fef699dae630124a05b9d
abdullahmamunv2/Futoshiki
/Node.py
2,740
3.53125
4
#import queue as Q class node(object): def __init__(self,domain,parent,row,col,value=0): self.domain=domain self.value=value self.row=row self.col=col self.unassigned=True self.parent=parent def deletFromDomain(self,item): self.domain.remove(item) def addItem(self,item): self.domain.append(item) def __str__(self): return str(self.value) ########### least-constraining value (LCV) ############ def orderingValue(self,board): neighbourPosition=self.__getneighbourPosition(board) maxeliminate=100 eliminate=[] for val in self.domain: eli_count=0 for nei in neighbourPosition: row,col=nei try: i = board[row][col].domain.index(val) eli_count+=1 except ValueError: pass eliminate.append((eli_count,val)) eliminate.sort() new_domain=[] for i in eliminate: new_domain.append(i[1]) self.domain=new_domain def orderingVariable(self,board): neighbourPosition=self.__getneighbourPosition(board) domainSize=[] orderedVariable=[] for nei in neighbourPosition: row,col=nei domainSize.append((len(board[row][col].domain),nei)) domainSize.sort() ##### compare two value equal or not if equal than apply degree heuristic for i in range(0,len(domainSize)): row,col=domainSize[i][1] if i < len(domainSize)-1: rowC,colC=domainSize[i+1][1] if len(board[row][col].domain) == len(board[rowC][colC].domain): length=self.__getneighbourPosition(board,Row=row,Col=col) lengthC=self.__getneighbourPosition(board,Row=rowC,Col=colC) if length > lengthC : domainSize[i+1],domainSize[i]=domainSize[i],domainSize[i+1] for i in domainSize: orderedVariable.append(i[1]) return orderedVariable def deleteFromNeiDomain(self,board,value): neighbourPosition=self.__getneighbourPosition(board) for nei in neighbourPosition: row,col=nei try: board[row][col].domain.remove(value) except ValueError: pass def AppendToNeiDomain(self,board,value): neighbourPosition=self.__getneighbourPosition(board) for nei in neighbourPosition: row,col=nei board[row][col].domain.append(value) def __getneighbourPosition(self,board,Row=-1,Col=-1): row_update=[0,0,1,-1] col_update=[1,-1,0,0] neighbour=[] for i in range(0,4): row=None col=None parent=None if Row==-1: row=self.row+row_update[i] col=self.col+col_update[i] else: row=Row+row_update[i] col=Col+col_update[i] ############## check grid cell position valid or not ############ if row >=0 and row < len(board) and col>=0 and col<len(board[0]): ############## make sure that parent is not neighbour ############ if board[row][col].value==0: neighbour.append((row,col)) return neighbour
a8f8f449bc8d300428207c1507e87c636856d824
007hakan/Hackerrank-Problem-Solving-Solutions
/ElectronicsShop.py
445
3.609375
4
def getMoneySpent(keyboards, drives, b): keyboards.sort() drives.sort() result=[] for i in range(len(keyboards)): for j in range(len(drives)): if keyboards[i]+drives[j]<=b: result.append(keyboards[i]+drives[j]) elif keyboards[i]+drives[j]>b: pass if len(result)>=1: print(max(result)) else: print("-1") getMoneySpent([4],[5],5)
4c66b2b74aa4f16497118e44d44bfbf980000007
liux1711/myFirstPythonTest
/pythonProject/test1.py
446
3.953125
4
if True : print("执行!") if False : print("不执行!") print("不执行") print("不执行") age=30 if age> 28 : print("老大不小了") else: print("还小,还能浪") age= input("请输入年龄\n") if int(age)<18 : print(f"你年龄在{age},属于未成年不能上网") elif int(age)>30 and int(age)<60: print(f"输入年龄{age}") elif int(age)>60: print("可以啊,还有心情上网")
802a4136628ba08dab237ea8dbedb9b4f2d192f7
CKnight7663/college
/hw3.py
12,380
4.375
4
#!/usr/bin/env python # coding: utf-8 # Assignment 3 # ============== # # This programme will be taking some function f(x), and through various methods, calculate the Integral between a, b. We will start off with the traditional method, the same one to which integration is often introduced as a concept with the rectangular box method. We will then import a module to perform the integral for us, in order to check the accuracy of our Numerical Method. Finally we will use whats called the Monte Carlo Method, and do some analysis to its accuracy. # # For this case we will be using an intgral from Quantum Mechanics, that will give the probability of finding of finding a particale in a unit wide well, in the left third side of the well. The integral is: # # $$ P = \int_0^{1/3}2sin^2{\pi x}$$ # # From now we will call the inside function the wavefunction, and the evaluation as the integral, area etc.. # # # # For the first Task, we will only need to def the function of the wavefunction in python, along with a numerical integral function that will perform our rectangular box method for estimating the integral. # # For the second Task, we just use the scipy import to find an accurate value for the integral. # # For the third Task, we will use: # $$ \eta = \frac{\lvert measured - expected\rvert}{expected}$$ # To find the relative accuracy of our estimation. To find the order $N$, whcih goes by $\eta = \alpha n^{-N}$ of our method with alpha a constant, we can take 2 values of $\eta _i$ and number of iterations $n_i$, to find: # $$ \alpha = \eta _1 n_1^{N} $$ # $$ N = log_{\frac{n_1}{n_2}}(\frac{\eta _2}{\eta_1}) $$ $$ N = \frac{ln(\frac{\eta _2}{\eta_1})}{ln(\frac{n_1}{n_2})}$$ # Now we this we can find multiple values for the order, and averge them together. We will also start to use some kwargs, this is simply to add custimability to the programme, rather than it be a requirment to finish the task. Specifically we will use it for passing in boolian values so the function only performs an action (plotting) when asked, and to provide strings of names not always needed. # # # For the forth Task, we will be defining the Monte Carlo Method, and analysing it. This method of estimation revolves around the concept that if we pick a random point on a plot and decide if its under the curve (success) and repeat for a large number of trys, the ratio of success to total trials, will be the same as the ratio of area under the graph and the total area of the plot. # ### Task 1 ### # 1. As always we import numpy and matplotlib.pyplot, but now we are also importing scipy.integrate, in order to get an accurate value of the integral in Task 2, and also random for part 4 with the Monte Carlo method. # 2. Next we set our programme constants. These are specifically numbers that stay contsant throughout one run of the programme, and are clumped here at the start to allow for easy access in order to change them when twicking the outputs. # 3. Now we begin defining our functions. First up is the numerical integration. We need to take in 4 variables, the function fx, the min and max values, the number of boxs we want to use, i.e. the number of steps. We create an interval along between the min and max, of n+1 steps, and then find f(x) for the left hand side of each interval. We add the area of this new box to our running sum, and repeat throughout the inteval. Return the total area found. Second we define the wavefunction, which is just a simply mathimatical statement. # 4. We print our Results. # In[1]: import numpy as np import matplotlib.pyplot as plt import scipy.integrate as scig import random as rdm #Programme constants x_initial = 0 x_final = 1/3 num_n = 10000 #The number of boxs in our Numerical Integral monte_n = 10000 #Number of random guess' in the Monte Carlo Method eta_iter = 4 #The number of variations of iterations (10, 100, 1000 ...) for the accuracy test lin_min = 100 #Min in the linear array lin_max = 10000 #Max in the linear array #Function Definitions def numerical_integral(fx, xmin, xmax, n, **kwargs): #Uses the rectangle rule to find an estimate for the area under a curve f(x) interval = np.linspace(xmin, xmax, int(n) + 1) Area = 0 for i in range(1, int(n)): h = fx(interval[i-1]) Area += (interval[i] - interval[i-1]) * h return Area def wavefunction(x): f_x = 2 * ((np.sin(x * np.pi)) ** 2) return f_x num_est = numerical_integral(wavefunction, x_initial, x_final, num_n) print('The estimate for the Integral using the rectangle rule with {0} segments, is: {1:.4}'.format(num_n, num_est)) # ### Task 2 ### # 1. We evaluate the integral using scipy and print the value plus or minus its uncertainty, which is very very low. # In[2]: scipy_integral, scipy_uncertainty = scig.quad(wavefunction, x_initial, x_final) print('Using Scipy, we get the integral to be : {0:.4} +- {1:.4}'.format(scipy_integral, scipy_uncertainty)) # ### Task 3 #### # 1. First we want to build our function that will find the eta for a number of different iterations. We take in our function f(x), the method we are finding the accuracy for, along with min, max, and array of values for iterations. We can loop through these finding their corresponding $\eta$ value, and then we check for kwargs. If we have eta_plot and its True, we plot the iterations vs the $\eta$ and then check for x_scale, if its there we use its value for the scale, otherwords we assign linear to its value. We also check for a name, so that we can add a title to the plot. # 2. Next we want to find the order, but again we check if its specified and then we loop through all pairs of values of $\eta _1 , \eta _2$ find the order and then the average. # 3. Finally we define two arrays, one a linear increase from lin_min to lin max, and the other the powers of ten starting at 100. # In[3]: def Eta_Accuracy(fx, function_estimate, xmin, xmax, iterations=[1], *, eta_plot=False, order=False, **kwargs): #Finds the value of Relative Accuracy for a given function and Integral with the expected result, returns an array of the iterations, the eta values for each iteration iter_len = len(iterations) #In the arguments, we have a * as one. This designates that anything after it is a eta = np.zeros(iter_len) #kwarg, so we set the boolian kwargs intitally as false function_actual, scipy_uncertainty = scig.quad(fx, xmin, xmax) #Performs the scipy function for this f(x) for i in range(iter_len): eta[i] = abs(function_estimate(fx, xmin, xmax, iterations[i]) - function_actual) / function_actual if eta_plot: #Checks if set to True plt.plot(iterations, eta) if 'x_scale' in kwargs: #Same as above plt.xscale(kwargs.get('x_scale')) else: kwargs['x_scale'] = 'linear' #Couldn't set a default value for this kwarg, so this does it for you, if necessary if 'name' in kwargs: plt.title('Relative accuracy of {}'.format(kwargs.get('name'))) plt.xlabel('Numer of Iterations ({})'.format(kwargs.get('x_scale'))) plt.ylabel('Relative Accuracy') plt.show() #All just formating, the same as most other code if order: function_order = 0 #We want to find N for each i, j pair, but for i in range(iter_len): #as ii is not allowed and ij = ji then we for j in range (iter_len): #insit that i be less than j, grabbing each pari only once if i < j: function_order += (np.log(eta[j]/eta[i]))/(np.log(iterations[i]/iterations[j])) #See markdown for equation function_order /= ((iter_len - 1) * (iter_len / 2)) #This is just deviding by number of pairs we have if 'name' in kwargs: #which is the sum from iter_len - 1 down to 1. print('The order of the {} method was: {}'.format(kwargs.get('name'), function_order)) return iterations, eta, function_order #Only returns function order when asked for it return iterations, eta #Definging Arrays linear = np.linspace(lin_min, lin_max, (int(lin_max/lin_min) + 1)) factors_10 = np.zeros(eta_iter) for i in range(0, eta_iter): factors_10[i] = 10**(i+2) it, eta, N, = Eta_Accuracy(wavefunction, numerical_integral, x_initial, x_final, factors_10, eta_plot=True, name='Numerical Rectange', x_scale='log', order=True) it, eta = Eta_Accuracy(wavefunction, numerical_integral, x_initial, x_final, linear, eta_plot=True, name='Numerical Rectange') # We get an order of very close to 1, and when we plot the linear we can see $\eta$ and iterations goes like $\eta = n^{-1}$ # ### Task 4 ### # 1. Now we want to define the Monte Carlo method as a function. In the same format as the Numerical Integral above, we have fx then xmin, xmax and trials, this allows us to interchange these two functions at any place the other is used. We also set up our boolian kwargs as intitally False. # 2. Starting off we create an array of x,y values for fx, along with its min and max y values. We define empty lists for x, y, where all of the succesful trials go into xlist, ylist, and failed gp into x2list, y2list (this will allow us to plot a scatter plot of them. # 3. We find the total are of the plot and begin our random trials. We need to find a random x **and** y value in their ranges, and then check if the y random is below the curve. Doing this over the number of trials specified we can then (if the kwarg is set to true) plot both the success' and the failures along with f(x) on the same plot. # In[4]: def monte_carlo(fx, xmin, xmax, trials, *, monte_print=False, func_plot=False, **kwargs): #Estimating the integral using random number generations xval = np.linspace(xmin, xmax, 1000) yval = fx(xval) ymin = min(yval) ymax = max(yval) xlist= [] ylist= [] x2list=[] y2list=[] box_area = (ymax - ymin) * (xmax - xmin) success = 0 for i in range(int(trials)): xrdm = rdm.uniform(xmin, xmax) yrdm = rdm.uniform(ymin, ymax) if yrdm <= fx(xrdm): success += 1 xlist.append(xrdm) ylist.append(yrdm) else: x2list.append(xrdm) y2list.append(yrdm) if func_plot: plt.plot(xval,yval, 'r', label='f(x)') plt.title('Monte Carlo Scatter Plot') plt.scatter(xlist, ylist, s=.75, label='Successful try') plt.scatter(x2list, y2list,s=.75, label='Failed try') plt.xlabel('x') plt.ylabel('f(x)') plt.legend() plt.show() monte_estimate = (success/trials) * box_area if monte_print: print('Using the Monte Carlo Method with {0} trials, we have area: {1:.4}'.format(trials, monte_estimate)) return monte_estimate monte_est = monte_carlo(wavefunction, x_initial, x_final, monte_n, func_plot=True, monte_print=True) # Finally we are just doing 5 plots of the Monte Carlo Method, to visualize how changing the number of trials will changethe outcome. First we perform the same Eta Accuracy plot as we did for the Numerical Method above, We can see that it doesnt increase in accuracy as quickly as the Numerical did by increasing the number of trials. We see that the it is much slower. # # # Then we plot 4 of the same linearly increasing iteration numbers and we can see just how random this accuracy actually is, and even at 10000 it is not quite settled into an high accuracy (accuracy is better going to 0) # In[5]: Eta_Accuracy(wavefunction, monte_carlo, x_initial, x_final, factors_10, monte_print=True, eta_plot=True, x_scale='log', name='Monte Carlo') for i in range(4): Eta_Accuracy(wavefunction, monte_carlo, x_initial, x_final, linear, eta_plot=True, name='Monte Carlo') # In[ ]:
7051c253efff8d0669b0a126a1bbf2b06ba7de90
benaneesh/cluster
/value/sample_generator.py
3,619
3.5
4
""" ================================================= Demo of affinity propagation clustering algorithm ================================================= Reference: Brendan J. Frey and Delbert Dueck, "Clustering by Passing Messages Between Data Points", Science Feb. 2007 """ print __doc__ import numpy as np from sklearn.cluster import AffinityPropagation from sklearn import metrics from sklearn.datasets.samples_generator import make_blobs from sklearn.datasets.samples_generator import * ############################################################################## ####################################### ## Generate cluster blob sample data ####################################### centers = [[1, 1], [-1, -1], [1, -1]] X, labels_true = make_blobs(n_samples=300, centers=centers, cluster_std=0.5) """ this give us 300 points in a randon number of blobs """ ####################################### ## Generate classification sample data ####################################### Y = make_classification( n_samples=100, n_features=20, # following is the characteristic of the features n_informative=2, n_redundant=2, n_repeated=0, n_classes=2, n_clusters_per_class=2, weights=None, flip_y=0.01, class_sep=1.0, hypercube=True, shift=0.0, scale=1.0, shuffle=True, random_state=None) """ print Y print len(Y) print len(Y[0]) # 100 points vector print len(Y[1]) # 100 points label print len(Y[0][0]) # vector size is 20 -> 20 features this give us 100 points with feature vector of 20 notes: random_state: if int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. return: X : array of shape [n_samples, n_features] The generated samples. y : array of shape [n_samples] The integer labels for class membership of each sample. """ ####################################### ## Generate circles sample data ####################################### Z = make_circles(n_samples=100, shuffle=True, noise=None, random_state=None, factor=0.80000000000000004) """ Z[0] is all the data points(2D), including one big circle, one small circle z[1] is all the labels of the data print Z """ ####################################### ## Generate moon sample data ####################################### #Z = make_moons(n_samples=1500, shuffle=True, noise=0.5, random_state=None) Z = make_moons(n_samples=1500, noise=.05) ############################################################################## # Plot result import pylab as pl from itertools import cycle pl.close('all') pl.figure(1) pl.clf() # Plot All Graphs colors = 'bgrcmykbgrcmykbgrcmykbgrcmyk' for count in range(len(Z[0])): point = Z[0][count] label = Z[1] pl.plot(point[0], point[1], colors[label[count]]+'.') pl.show() """ colors = cycle('bgrcmykbgrcmykbgrcmykbgrcmyk') for k, col in zip(range(n_clusters_), colors): class_membera = laels == k cluster_center = X[cluster_centers_indices[k]] print cluster_center print class_members print len(X[class_members]) pl.plot(X[class_members, 0], X[class_members, 1], col + '.') pl.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col, markeredgecolor='k', markersize=14) for x in X[class_members]: pl.plot([cluster_center[0], x[0]], [cluster_center[1], x[1]], col) pl.title('Estimated number of clusters: %d' % n_clusters_) #pl.show() """
eda920e11595b7bc7a2a7fb686f542cdb7802443
efbatista9/Busca_Sequencial
/busca_seq.py
982
3.640625
4
class Musica: def __init__(self, titulo, interprete, compositor, ano): self.titulo = titulo self.interprete = interprete self.compositor = compositor self.ano = ano class Buscador: def busca_por_titulo(self, playlist, titulo): for i in range(len(playlist)): if playlist[i].titulo == titulo: return i return -1 def vamos_buscar(self): playlist = [Musica("Ponta de Areia", "Milton Nascimento", "Milton Nascimento", 1975), Musica("Podres Podres", "Caetano Veloso", "Caetano Veloso", 1984), Musica("Baby", "Gal Costa", "Caetano Veloso", 1969)] onde_achou = self.busca_por_titulo(playlist, "Baby") if onde_achou == -1: print("Minha musica preferida não está na playlist") else: preferida = playlist[onde_achou] print(preferida.titulo, preferida.interprete, preferida.compositor, preferida.ano, sep=', ')
3b3985673bc8b03b3dbfe8ce85499f468439cea8
nss-day-cohort-13/bangazon-group-project-ebazaon
/order_test.py
750
3.578125
4
import unittest from order import * class TestOrder(unittest.TestCase): @classmethod def setUp(self): ''' Set up class in order to test core functionality associated with orders''' self.new_order = Order( 'Test Cust_Uid', 'Test Pay_Opt_Uid', paid = False ) def test_order_creation(self): ''' Test that an order is created with the proper attributes ''' self.assertIsInstance(self.new_order, Order) self.assertEqual(self.new_order.cust_uid, 'Test Cust_Uid') self.assertEqual(self.new_order.pay_opt_uid, 'Test Pay_Opt_Uid') self.assertFalse(self.new_order.paid) if __name__ == '__main__': unittest.main()
86f8df082e714a05f09512cc87050132a2c6f59d
Tenbatsu24/Project-Euler
/divisors.py
276
3.5
4
import math def f(n): divisors = set({1, n}) for i in range(2, math.ceil(math.sqrt(n)) + 1): if (n % i) == 0: divisors.add(i) divisors.add(n // i) return divisors if __name__ == '__main__': print(f(4001)) print(f(2689))
fb7e856928aee57359f46fd022985f9413be645e
XuHangkun/BaseAlgorithm
/BaseAlgorithm/graph/edgeweighteddigraph.py
9,953
3.59375
4
# -*- coding: utf-8 -*- """ edge weighted directed graph ~~~~~~~~~~~~~~ make a edge weighted directed graph class :copyright: (c) 2020 by Xu Hangkun. :license: LICENSE, see LICENSE for more details. :ref: [美]塞奇威克(Sedgewick, R.),[美]韦恩(Wayne,K.).算法[M].北京:人民邮电出版社,2012. """ import queue from BaseAlgorithm.search.binary_search_tree import BST from BaseAlgorithm.graph.digraph import Topological,DirectedCircle class DirectedEdge: """directed edge """ def __init__(self,v:int,w:int,weight:float): self.__v = v self.__w = w self.__weight = weight def weight(self): return self.__weight def __lt__(self,edge): return self.__weight < edge.__weight def __le__(self,edge): return self.__weight <= edge.__weight def __gt__(self,edge): return self.__weight > edge.__weight def __ge__(self,edge): return self.__weight >= edge.__weight def __eq__(self,edge): return self.__weight == edge.__weight def __ne__(self,edge): return self.__weight != edge.__weight def e_from(self): return self.__v def e_to(self): return self.__w def either(self): return self.__v def other(self,vertex): if vertex == self.__v: return self.__w elif vertex == self.__w: return self.__v else: return None def __str__(self): return "%d -> %d %.2f"%(self.__v,self.__w,self.__weight) class EdgeWeightedDiGraph: """edge weighted directed graph """ def __init__(self,V=0): self.__v = V self.__e = 0 self.__adj = [] for index in range(self.__v): self.__adj.append([]) def load_graph(self,filename): """load graph from standard graph file standard graph file format line 1: 3 #number of vertex line 2: 2 #number of edge line 3: 1 2 0.1 #edge link vertex 1 and vertex 2 line 4: ... ... """ with open(filename,"r") as file: lines = file.readlines() self.__v = int(lines[0].strip('\n')) self.__e = 0 self.__adj = [] #adjacency list for index in range(0,self.__v): self.__adj.append([]) for line in lines[2:]: tmp_edge = line.split() edge = DirectedEdge(int(tmp_edge[0]),int(tmp_edge[1]),float(tmp_edge[2])) if edge: self.add_edge(edge) def add_edge(self,edge:DirectedEdge): """add a edge into the graph """ self.__adj[edge.e_from()].append(edge) self.__e += 1 def vertex_num(self): """number of vertexs """ return self.__v def edge_num(self): """number of edges """ return self.__e def adj(self,v:int): """return adjancent vertexs of vertex v """ return self.__adj[v] def edges(self): bag = [] for i in range(self.__v): for j in self.adj(i): bag.append(j) return bag def show(self): """show the graph """ print("Vertex Number: %d"%self.__v) print("Edge Number: %d"%self.__e) for index in range(self.__v): print("V %d"%index,self.adj(index)) class DijkstraSP: """generatre the smallest weighted path tree of a graph """ def __init__(self,gr:EdgeWeightedDiGraph,s:int): self.__pq = BST() self.__edgeTo = [] self.__distTo = [] for index in range(gr.vertex_num()): self.__edgeTo.append(None) self.__distTo.append(float('inf')) self.__distTo[s] = 0 self.__pq.put(s,self.__distTo[s]) while not self.__pq.size()==0: min = self.__pq.min().key self.__pq.deleteMin() self.relax_edge(gr,min) def relax_edge(self,gr:EdgeWeightedDiGraph,v:int): for edge in gr.adj(v): w = edge.e_to() if self.__distTo[w] > (self.__distTo[v] + edge.weight()): self.__distTo[w] = self.__distTo[v] + edge.weight() self.__edgeTo[w] = edge self.__pq.put(w,self.__distTo[w]) def relax_vertex(self,gr:EdgeWeightedDiGraph,v:int): for edge in gr.adj(v): w = edge.e_to() if self.__distTo[w] > (self.__distTo[v] + edge.weight()): self.__distTo[w] = self.__distTo[v] + edge.weight() self.__edgeTo[w] = edge def distTo(self,v:int): return self.__distTo[v] def hasPathTo(self,v:int): return self.__distTo[v] < float('inf') def pathTo(self,v:int): if not self.hasPathTo(v): return None path = [] edge = self.__edgeTo[v] while edge.e_to != None: path.insert(0,edge) edge = self.__edgeTo[edge.e_from()] return path def edges(self): return self.__edgeTo class AcyclicSP: """generatre the smallest weighted path tree of a acyclic graph """ def __init__(self,gr:EdgeWeightedDiGraph,s:int): self.__edgeTo = [] self.__distTo = [] for index in range(gr.vertex_num()): self.__edgeTo.append(None) self.__distTo.append(float('inf')) self.__distTo[s] = 0 top = Topological(EdgeWeightedDiGraph) for v in top.order(): self.relax_vertex(gr,v) def relax_vertex(self,gr:EdgeWeightedDiGraph,v:int): for edge in gr.adj(v): w = edge.e_to() if self.__distTo[w] > (self.__distTo[v] + edge.weight()): self.__distTo[w] = self.__distTo[v] + edge.weight() self.__edgeTo[w] = edge def distTo(self,v:int): return self.__distTo[v] def hasPathTo(self,v:int): return self.__distTo[v] < float('inf') def pathTo(self,v:int): if not self.hasPathTo(v): return None path = [] edge = self.__edgeTo[v] while edge.e_to != None: path.insert(0,edge) edge = self.__edgeTo[edge.e_from()] return path def edges(self): return self.__edgeTo class EdgeWeightedDirectedCycle: """find cycle in a edge weighted cycle """ def __init__(self,digr:EdgeWeightedDiGraph): self.__onStack = [] self.__edgeTo = [] self.__marked = [] self.__circle = [] for v in range(digr.vertex_num()): self.__onStack.append(False) self.__edgeTo.append(None) self.__marked.append(False) for v in range(digr.vertex_num()): if not self.__marked[v]: self.__dfs(digr,v) def __dfs(self,digr:EdgeWeightedDiGraph,v:int): self.__onStack[v] = True self.__marked[v] = True for w in digr.adj(v): if self.hasCircle(): return elif not self.__marked[w]: self.__edgeTo[w] = v self.__dfs(digr,w) elif self.__onStack[w]: self.__circle = [] x = v while x != w: self.__circle.insert(0,x) x = self.__edgeTo[x] self.__circle.insert(0,w) self.__circle.insert(0,v) return self.__onStack[v] = False def hasCircle(self): if self.__circle: return True else: return False def circle(self): return self.__circle class BellmanFordSP: def __init__(self,gr:EdgeWeightedDiGraph,s:int): self.__edgeTo = [] self.__distTo = [] self.__onQ = [] self.__queue = queue.Queue(0) self.__cost = 0 self.__cycle = [] for index in range(gr.vertex_num()): self.__edgeTo.append(None) self.__distTo.append(float('inf')) self.__onQ.append(False) self.__distTo[s] = 0 self.__queue.put(s) self.__onQ[s] = True while not self.__queue.empty() and not self.hasNegativeCycle(): v = self.__queue.get() self.__onQ[v] = False self.relax(gr,v) def findNegativeCycle(self): V = len(self.__edgeTo) spt = EdgeWeightedDiGraph(V) for v in range(V): if self.__edgeTo[v] != None: spt.add_edge(self.__edgeTo[v]) cf = EdgeWeightedDirectedCycle(spt) self.__cycle = cf.circle() def hasNegativeCycle(self): self.__cycle != None def negativeCycle(self): return self.__cycle def relax(self,gr:EdgeWeightedDiGraph,v:int): for edge in gr.adj(v): w = edge.e_to() if self.__distTo[w] > (self.__distTo[v] + edge.weight()): self.__distTo[w] = self.__distTo[v] + edge.weight() self.__edgeTo[w] = edge if not self.__onQ[w]: self.__onQ[w] = True self.__cost += 1 if self.__cost % gr.vertex_num() == 0: self.findNegativeCycle() def distTo(self,v:int): return self.__distTo[v] def hasPathTo(self,v:int): return self.__distTo[v] < float('inf') def pathTo(self,v:int): if not self.hasPathTo(v): return None path = [] edge = self.__edgeTo[v] while edge.e_to != None: path.insert(0,edge) edge = self.__edgeTo[edge.e_from()] return path def edges(self): return self.__edgeTo
0a1db902e3c0ed1b6742d9324397041b8ba4bbc6
XuHangkun/BaseAlgorithm
/BaseAlgorithm/data_structure/list.py
3,395
4.40625
4
# -*- coding: utf-8 -*- """ List ~~~~~~~~~~~~~~ make a list class. (Alought python has it's built-in list, we will achieve this data structure by ourself. We will only use some basic functions of python so we can display the details of list.) :copyright: (c) 2020 by Xu Hangkun. :license: LICENSE, see LICENSE for more details. :ref: [美]塞奇威克(Sedgewick, R.),[美]韦恩(Wayne,K.).算法[M].北京:人民邮电出版社,2012. """ class Node: """Node Attributes: data : data next : quote of next Node """ def __init__(self,init_data=None): self.__data = init_data self.__next = None def getData(self): """get the data in the node """ return self.__data def getNext(self): """get the quota of next node """ return self.__next def setData(self,new_data): """set data of this new node """ self.__data = new_data def setNext(self,new_next): """set the quota of next data """ self.__next = new_next class List: """List of a object a simple demo of a list of a object Attributes: first : point to first node """ def __init__(self): self.first = Node() def AddNodeOnHead(self,new_data): """Add a node on the head of the list """ new_node = Node(new_data) new_node.setNext(self.first.getNext()) self.first.setNext(new_node) def AddNodeOnEnd(self,new_data): """Add a node on the end of the end """ node = self.first while node.getNext(): node = node.getNext() #now node is the last node new_node = Node(new_data) node.setNext(new_node) def DeleteNodeOnHead(self): """delete a node on the head """ if not self.isEmpty(): next_node = self.first.getNext() self.first.setNext(next_node.getNext()) next_node.setNext(None) del next_node def DeleteNodeOnEnd(self): """delete a node on the end """ node = self.first if not self.isEmpty(): while node.getNext().getNext(): node = node.getNext() # now, node's next is the last last_node = node.getNext() node.setNext(None) del last_node def isEmpty(self): return self.first.getNext() == None def __next__(self): if self.current_node.getNext() == None: raise StopIteration else: self.current_node = self.current_node.getNext() return self.current_node def __iter__(self): #return first node self.current_node = self.first return self if __name__ == '__main__': #this is a simple test example. [test pass] test_list = List() test_list.DeleteNodeOnHead() test_list.DeleteNodeOnEnd() for i in range(0,10): test_list.AddNodeOnEnd(i) test_list.DeleteNodeOnEnd() for i in range(0,10): test_list.AddNodeOnHead(i) test_list.DeleteNodeOnHead() for item in test_list: print(item.getData())
d2d01b2f837b19d1d93f0f9506a82ad79b9352b2
lvybupt/PyLearn
/pytest/topsort/navive_topsort.py
355
3.765625
4
''' python 算法书 朴素的拓扑排序 page 90 ''' def navie_topsort(G, S=None ): if S == None: S = set(G) if len(S) == 1 : return list(S) v = S.pop() seq = navie_topsort(G,S) min_i = 0 for i,u in enumerate(seq): if v in G[u]: min_i =i+1 seq.insert(min_i,v) return seq if __name__ == '__main__': print(1)
c10eb6c7bcf2634bbefe79a744ffae1c8b63daf0
lvybupt/PyLearn
/Intro_To_Algorithms/find_maximum_subarray.py
1,185
3.765625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ##寻找最大子数组 def find_max_crossing_subarray(a,low,mid,high): leftsum = - float("inf") sum = 0 for i in range(mid,low-1,-1): sum = sum + a[i] if sum > leftsum : leftsum = sum maxleft = i rightsum = - float("inf") sum = 0 for j in range(mid+1,high+1,1): sum = sum + a[j] if sum > rightsum : rightsum = sum maxright = j return maxleft, maxright,leftsum+rightsum def find_maximum_subarray(a,low,high): if high == low : return low, high, a[low] else : mid = int((low+high)/2) leftlow, lefthigh, leftsum = find_maximum_subarray(a, low, mid) rightlow, righthigh, rightsum = find_maximum_subarray(a, mid+1, high) crosslow, crosshigh, crosssum = find_max_crossing_subarray(a, low, mid, high) if leftsum >= rightsum and leftsum >= crosssum : return leftlow, lefthigh, leftsum elif rightsum >= leftsum and rightsum >= crosssum : return rightlow, righthigh, rightsum else : return crosslow, crosshigh, crosssum def main(): a = [1,2,3,4,5,-6,-7,8,9,-10,2,3,4,-1,-4,1] low = 0 high = len(a) - 1 print(find_maximum_subarray(a,low,high)) if __name__ == '__main__': main()
66ac2e219438d2be17b530c09092178d684ce748
bmartin5263/AlgorithmsPrep
/multiply.py
407
3.734375
4
def multiply(num1, num2): product = 0 num1_size = len(num1) num2_size = len(num2) for i in range(num1_size-1,-1,-1): zeros1 = (num1_size - 1) - i value1 = int(num1[i]) * (10**zeros1) for j in range(num2_size-1,-1,-1): zeros2 = (num2_size - 1) - j value2 = int(num2[j]) * (10**zeros2) product += (value1 * value2) return product
b9778f41add3d3d14e4a9e4670299c0c9b445733
ArgeNH/basic-Python
/practice/アルゲ.py
3,475
3.703125
4
import os import math """ n = 5 while n > 0: print(f'el valor de n: {n}') n = n-1 print('\n') m = 0 while m < 4: print(f'El valor de m: {m}') m = m + 1 """ """ age = 0 while age < 100: if (age < 18): print(f'{age} menor de edad') elif (age < 70): print(f'{age} adulto') else: print(f'{age} mayor de edad') age = age + 1 print('Fin del programa') """ os.system('cls') """ while True: tex = input('Ingrese un texto: ') if tex == 'fin': break print(f'Acaba de escribir la cadena: {tex}') print('Fin del programa') """ """ while True: num = int(input('Ingrese un numero: ')) if num < 5: continue if num > 10: break print(f'Se escribio {num}') print('Fin') """ """ R = 6372.795477598 list = [[6.691,-72.8727],[6.567,-73.120],[6.456,-72.872]] data = [ [6.632, -72.984, 285], [6.564, -73.061, 127], [6.531, -73.002, 15], [6.623, -72.978, 56]] lat_2 = list[0][0] lon_2 = list[0][1] distances = [] ct = 0 for i in data: aux = math.pow(math.sin((i[0] - lat_2)/2),2) aux_2 = math.pow(math.sin((i[1] - lon_2)/2),2) val_1 = math.cos(i[0])*math.cos(lat_2) total = int(2*R*math.asin(math.sqrt(aux+(val_1*aux_2)))) distances.append(total) count = 0 for i in distances: data[count].append(i) count+=1 print(data) x = sorted(data, key=lambda i: i[2]) print(x) print(f'La zona wifi 1: ubicada en [\'{x[0][0]}\',\'{x[0][1]}\'] a {x[0][3]} metros, tiene en promedio {x[0][2]} usuarios') print(f'La zona wifi 2: ubicada en [\'{x[1][0]}\',\'{x[1][1]}\'] a {x[1][3]} metros, tiene en promedio {x[1][2]} usuarios') opt_2 = int(input('Elija 1 o 2 para recibir indicaciones de llegada\n')) """ """ menor = 99999 pos = 0 pos_2 = 0 aux = 0 for i in data: #print(i[3]) if menor > i[3]: menor = i[3] pos += 1 else: pos_2 += 1 aux = i[3] print(f'El menor es {menor} con posición {pos} y el {aux} y pos {pos_2}') print(f'El menor es {menor} con posición {pos} y anterior {aux} y pos {pos_2}') lower = 0 pos_3 = 0 for i in data: print(i[2]) if i[2] >= i[2]: lower = i[2] print(lower) """ #x = data[pos].index(menor) # print(x) #distance = 2 * R * math.asin(math.sqrt((math.sin(v_lat/2)**2)+math.cos(lat_1)*math.cos(lat_2)*math.sin(v_lon/2)**2)) # print(distance) """ def show_list(): enum = 0 for i in list: enum += 1 print(f'coordenada [latitud, longitud] {enum} : {i}') show_list() menor = 0 pos = 0 for i in list: if i[1] < menor: pos += 1 menor = i[1] print(menor,' ', pos) """ """ notas = [] sum = 0 try: for i in range(100): nt = float(input('Ingrese sus notas: ')) notas.append(nt) sum += nt except ValueError: print('Se ha ingresado fin\n') notas.sort() print(f'La nota mas baja fue: {notas[0]}') notas.sort(reverse=True) print(f'La nota mas alta fue: {notas[0]}') promedio = round(sum/len(notas),1) print(f'El promedio final es: {promedio}') if promedio <= 3.0: print('Perdio la materia') else: print('Felicidades, Gano la materia') """ import pandas as pd import csv data = [[6.632, -72.984, 285], [6.564, -73.061, 127], [6.531, -73.002, 15], [6.623, -72.978, 56]] information = [{'actual': data[0], 'zonawifi1': data[1], 'recorrido' : data[2]+data[3]}] pd.DataFrame(information).to_csv('information.csv', index=False) s = pd.Series(information) print(s)
e9873ee3cd6e780777e63e3772369fbe87a11074
hodycan/othello
/Othello GUI.py
2,650
3.5625
4
from tkinter import * from tkinter import messagebox from settings_menu import OthelloSettingsGUI from othello_gui_board import * import othello_game_logic WINDOW_WIDTH = 500 WINDOW_HEIGHT = 500 class OthelloGUI: """ Graphical user interface for Othello game. public attributes: playagain: bool """ def __init__(self, init_width: int, init_height: int, game, inversemode: bool): """Initializes the Othello GUI given initial width and height.""" self._root = Tk() self._root.title('Othello') self._root.rowconfigure(0, weight=1) self._root.columnconfigure(0, weight=1) self._root.minsize(50, 50) self._root.protocol("WM_DELETE_WINDOW", self._on_close) self._game = game self._inversemode = inversemode self._initialize_app(init_width, init_height) self.playagain = False self._root.mainloop() def _on_close(self) -> None: """asks if the user wants to quit""" text = 'Are you sure you want to exit Othello?' answer = messagebox.askquestion('Othello', message=text) if answer == 'yes': self._root.quit() def _initialize_app(self, init_width: int, init_height: int) -> None: """initialize the app.""" self._app = OthelloApp(self._root, init_width, init_height, self._game, self._inversemode) self._app.grid(row=0, column=0, sticky='nswe') self._app.bind('<Configure>', self._on_resize) def _on_resize(self, event) -> None: """tkinter resize event handler.""" self._app.refresh_board(self._root.winfo_width(), self._root.winfo_height()) if __name__ == '__main__': while True: try: settingsgui = OthelloSettingsGUI() settings = settingsgui.get_settings() rows, columns, first_turn, top_left, inversemode = settings game = othello_game_logic.OthelloGame(rows=rows, columns=columns, firstturn=first_turn, topleftpiece=top_left) gui = OthelloGUI(WINDOW_WIDTH, WINDOW_HEIGHT, game, inversemode) playagain = gui._app.playagain gui._root.destroy() if not playagain: break except: e = sys.exc_info() print(e[0], e[1]) input() break
0352ddc6ce556f182a21e28aa3c20d31cb5e3f82
dys27/Data-Structures
/LinkedList/delete middle node of a linked list.py
2,579
3.921875
4
class Node(object): def __init__(self,data): self.data=data self.next_node=None def remove(self,data,previous_node): if self.data==data: previous_node.next_node=self.next_node del self.data del self.next_node else: if self.next_node is not None: self.next_node.remove(data,self) class LinkedList(object): def __init__(self): self.head=None self.counter=0 def add_first(self,data): self.counter+=1 new_node=Node(data) if self.head is None: self.head=new_node else: new_node.next_node=self.head self.head=new_node def add_last(self,data): if self.head is None: self.add_first(data) return self.counter+=1 new_node=Node(data) current_node=self.head while current_node.next_node is not None: current_node=current_node.next_node current_node.next_node=new_node def size(self): return self.counter def traverse(self): current_node=self.head while current_node is not None: print "%d"%current_node.data, current_node=current_node.next_node def remove(self,data): self.counter-=1 if self.head: if self.head.data==data: self.head=self.head.next_node else: self.head.remove(data,self.head) def reverse(self): current_node=self.head temp_prev=None while current_node is not None: temp_next=current_node.next_node current_node.next_node=temp_prev temp_prev=current_node current_node=temp_next self.head=current_node def middle(self): if self.counter>2: count=0 current_node=self.head prev_node=None while count!=self.counter//2: prev_node=current_node current_node=current_node.next_node count+=1 prev_node.next_node=current_node.next_node del current_node.data del current_node.next_node else: return ll=LinkedList() ll.add_first(6) ll.add_first(5) ll.add_first(4) ll.add_first(3) ll.add_first(2) ll.middle() ll.traverse()
84bc34ecd5eb5534227a9c3690ae99bb965950af
julianbjornsson/tkinter
/app.py
9,004
3.53125
4
import tkinter as tk from tkinter import * from tkinter import ttk from tkcalendar import Calendar, DateEntry from tkinter.scrolledtext import * from tkinter import messagebox # DB: import sqlite3 import csv conn = sqlite3.connect("data.db") c = conn.cursor() def crear_tabla(): c.execute('CREATE TABLE IF NOT EXISTS "pacientes" ("name" TEXT, "lastname" TEXT, "email" TEXT, "age" TEXT, "date_of_birth" TEXT, "address" TEXT, "phonenumber" REAL);') conn.commit() #def add_data(name, lastname, email, age, date_of_birth, address, phonenumber): #c.execute('INSERT INTO "pacientes" (name, lastname, email, age, date_of_birth, address, phonenumber) VALUES (?,?,?,?,?,?,?)',(name, lastname, email, age, date_of_birth, address, phonenumber)) #conn.commit() def clear_text(): entry_fname.delete('0', END) entry_lname.delete('0', END) entry_email.delete('0', END) entry_age.delete('0', END) entry_address.delete('0', END) entry_phone.delete('0', END) entry_cal.delete('0', END) def add_details(): name = entry_fname.get() lastname = entry_lname.get() email = entry_email.get() age = entry_age.get() date_of_birth = cal.get() address = entry_address.get() phonenumber = entry_phone.get() #add_data(name, lastname, email, age, date_of_birth, address, phonenumber) c.execute('INSERT INTO pacientes (name, lastname, email, age, date_of_birth, address, phonenumber) VALUES (?,?,?,?,?,?,?);',(name, lastname, email, age, date_of_birth, address, phonenumber)) conn.commit() result = '\nNombre(s): {}, \nApellido(s): {}, \nEmail: {}, \nEdad: {}, \nFecha de Nacimiento: {}, \nDireccion: {}, \nTelefono: {}'.format(name, lastname, email, age, date_of_birth, address, phonenumber) tab1_display.insert(tk.END, result) messagebox.showinfo(title="Paciente nuevo", message = "El paciente {} {} ha sido añadido con exito a la base de datos".format(name, lastname)) def clean_results(): tab1_display.delete('1.0', END) def ver_todo(): window.geometry("1400x400") c.execute('SELECT * FROM "pacientes";') data = c.fetchall() for row in data: tree.insert("", tk.END, values=row) def buscarPaciente(): name = inp_buscar.get() c.execute('SELECT * FROM pacientes WHERE name = "{}"'.format(name)) data = c.fetchall() dataLimpia = ''.join(str(data)) str1 = "" for ele in dataLimpia: str1 += ele str2 = str1[2:-3] if name in str2: tab2_display.insert(tk.END, str2) else: messagebox.showinfo(title = "Alerta", message = "No hay registros") def limpiarBusqueda(): tab2_display.delete('1.0', END) inp_buscar.delete('0', END) #Estructura y layout window = Tk() window.title("Registro de Pacientes") window.geometry("700x650") style = ttk.Style(window) style.configure("TNotebook", tabposition = 'n') style.configure(window, bg = 'gray') style.configure('TLabel', background='#3d424a#3d424a', foreground='white') style.configure('TFrame', background='#3d424a') #Tab layout tab_control = ttk.Notebook(window, style = 'TNotebook') tab1 = ttk.Frame(tab_control) tab2 = ttk.Frame(tab_control) tab3 = ttk.Frame(tab_control) tab4 = ttk.Frame(tab_control) tab5 = ttk.Frame(tab_control) #Añadir tabs tab_control.add(tab1,text = f'{"Inicio":^20s}') tab_control.add(tab2,text = f'{"Listar":^20s}') tab_control.add(tab3,text = f'{"Busqueda":^20s}') tab_control.add(tab4,text = f'{"Exportar":^20s}') tab_control.add(tab5,text = "Acerca de...") tab_control.pack(expand=1, fill="both") crear_tabla() label1 = Label(tab1, text = '--- Ingreso de datos de pacientes ---', pady = 5, padx = 5) label1.grid(column = 1, row = 0) label1.configure(bg = '#3d424a', foreground = "white", font=("Courier", 15, "bold")) label2 = Label(tab2, text = '--- Listado de pacientes ---', pady = 5, padx = 5) label2.grid(column = 0, row = 0) label2.configure(bg = '#3d424a', foreground = "white", font=("Courier", 15, "bold")) label3 = Label(tab3, text = '--- Busqueda de pacientes ---', pady = 5, padx = 5) label3.grid(column = 0, row = 0) label3.configure(bg = '#3d424a', foreground = "white", font=("Courier", 15, "bold")) label4 = Label(tab4, text = '--- Exportar a archivo ---', pady = 5, padx = 5) label4.grid(column = 0, row = 0) label4.configure(bg = '#3d424a', foreground = "white", font=("Courier", 15, "bold")) label5 = Label(tab5, text = '--- Acerca de... ---', pady = 5, padx = 5) label5.grid(column = 0, row = 0) label5.configure(bg = '#3d424a', foreground = "white", font=("Courier", 15, "bold")) #Inicio l1 = Label(tab1, text = "Nombre(s):", padx = 5, pady = 5) l1.grid(column = 0, row = 1) l1.configure(bg = '#3d424a', foreground = "white", font = ("bold")) fname_raw_entry = StringVar() entry_fname = Entry(tab1, textvariable=fname_raw_entry, width = 50) entry_fname.grid(column = 1, row = 1) l2 = Label(tab1, text = "Apellido(s):", padx = 5, pady = 5) l2.grid(column = 0, row = 2) l2.configure(bg = '#3d424a', foreground = "white", font = ("bold")) lname_raw_entry = StringVar() entry_lname = Entry(tab1, textvariable=lname_raw_entry, width = 50) entry_lname.grid(column = 1, row = 2) l3 = Label(tab1, text = "Correo electronico:", padx = 5, pady = 5) l3.grid(column = 0, row = 3) l3.configure(bg = '#3d424a', foreground = "white", font = ("bold")) mail_raw_entry = StringVar() entry_email = Entry(tab1, textvariable=mail_raw_entry, width = 50) entry_email.grid(column = 1, row = 3) l4 = Label(tab1, text = "Edad:", padx = 5, pady = 5) l4.grid(column = 0, row = 4) l4.configure(bg = '#3d424a', foreground = "white", font = ("bold")) age_raw_entry = StringVar() entry_age = Entry(tab1, textvariable=age_raw_entry, width = 50) entry_age.grid(column = 1, row = 4) l5 = Label(tab1, text = "Fecha de Nacimiento:", padx = 5, pady = 5) l5.grid(column = 0, row = 5) l5.configure(bg = '#3d424a', foreground = "white", font = ("bold")) dob_raw_entry = StringVar() cal = DateEntry(tab1,width = 30, textvariable=dob_raw_entry, background = 'grey', foreground='white', borderwidth = 2, year = 2019 ) cal.grid(column = 1, row = 5) l6 = Label(tab1, text = "Direccion:", padx = 5, pady = 5) l6.grid(column = 0, row = 6) l6.configure(bg = '#3d424a', foreground = "white", font = ("bold")) dire_raw_entry = StringVar() entry_address = Entry(tab1, textvariable=dire_raw_entry, width = 50) entry_address.grid(column = 1, row = 6) l7 = Label(tab1, text = "Telefono de contacto:", padx = 5, pady = 5) l7.grid(column = 0, row = 7) l7.configure(bg = '#3d424a', foreground = "white", font = ("bold")) fono_raw_entry = StringVar() entry_phone = Entry(tab1, textvariable=fono_raw_entry, width = 50) entry_phone.grid(column = 1, row = 7) #boton0 = Button(tab1, text = 'CREAR BASE', command = crear_tabla) #boton0.grid(row = 11) boton1 = Button(tab1, text = 'Añadir', width = 20, bg = '#3b547d', fg = '#FFFFFF', command = add_details) boton1.grid(row = 8, column = 0, pady = 45, padx = 45) boton2 = Button(tab1, text = 'Limpiar Campos', width = 20, bg = '#3b547d', fg = '#FFFFFF', command = clear_text ) boton2.grid(row = 8, column = 1, pady = 25, padx = 25) tab1_display = ScrolledText(tab1, height = 10) tab1_display.grid(row = 9, pady = 5, padx = 5, columnspan = 2) boton3 = Button(tab1, text = 'Limpiar Resultados', width = 20, bg = '#3b547d', fg = '#FFFFFF', command = clean_results ) boton3.grid(row = 10, column = 1, pady = 25, padx = 25) #Listado boton_ver = Button(tab2, text = 'Listar pacientes', width = 20, bg = '#3b547d', fg = '#FFFFFF', command = ver_todo) boton_ver.grid(row = 1, column = 0, padx = 10, pady = 10) #Treeview tree = ttk.Treeview(tab2, column = ("c1", "c2", "c3", "c4", "c5", "c6", "c7"), show='headings') tree.heading("#1", text = "Nombre") tree.heading("#2", text = "Apellido") tree.heading("#3", text = "eMail") tree.heading("#4", text = "Edad") tree.heading("#5", text = "Fecha de nacimiento") tree.heading("#6", text = "Direccion") tree.heading("#7", text = "Telefono") tree.grid(column = 0, row = 10, columnspan = 3, padx = 5, pady = 5) #Busqueda buscar = Label(tab3, text = "Buscar pacientes", padx = 10, pady = 10) buscar.grid(column = 0 , row = 1) buscar.configure(bg = '#3d424a', foreground = "white", font = ("bold")) search_raw_entry = StringVar() inp_buscar = Entry(tab3, textvariable= search_raw_entry, width = 30) inp_buscar.grid(row = 1, column = 1) boton4 = Button(tab3, text = "Limpiar busqueda", width = 20, bg = '#3b547d' , fg = '#FFFFFF') boton4.grid(row=2, column = 1, padx = 10, pady = 10) boton5 = Button(tab3, text = "Limpiar resultado", width = 20, bg = '#3b547d' , fg = '#FFFFFF', command = limpiarBusqueda) boton5.grid(row=2, column = 1, padx = 10, pady = 10) boton6 = Button(tab3, text = "Buscar", width = 20, bg = '#3b547d' , fg = '#FFFFFF', command = buscarPaciente) boton6.grid(row=1, column = 2, padx = 10, pady = 10) tab2_display = ScrolledText(tab3, height = 5) tab2_display.grid(row = 10, column = 0, columnspan = 3, pady = 5, padx = 6) #Exportar #Acerca de window.mainloop()
e198e6442c237fdbbfa537a9af4a26c5708f0227
sergeykoryagin/tproger
/tasks/task21.py
155
3.640625
4
def unique(lst): return len(lst) == len(set(lst)) lst1 = [1, 2, 3, 4, 5, 6, 7] lst2 = [1, 2, 3, 4, 3, 2, 1] print(unique(lst1)) print(unique(lst2))
ec2e60e41c203c6b25be9a18fbefdac1b93a8eb2
sergeykoryagin/tproger
/tasks/task18.py
132
3.796875
4
string = 'qwertyuiopasdfghjklzxcvbnm,asdfghjkqwyeqeqrqemneiwibf' letter = input('letter is :') print(string.count(letter), 'times')
58a9223e31c487b45859dd346238ee84bb2f61c8
ao-kamal/100-days-of-code
/binarytodecimalconverter.py
1,485
4.34375
4
"""Binary to Decimal and Back Converter - Develop a converter to convert a decimal number to binary or a binary number to its decimal equivalent. """ import sys print( 'This program converts a number from Binary to Decimal or from Decimal to Binary.') def binary_to_decimal(n): print(int(str(n), 2), '\n') def decimal_to_binary(n): print(format(int(n), 'b'), '\n') def convert_again(): prompt = input('Run the program again? (Y/N)\n') if prompt == 'Y': converter() elif prompt == 'N': print('Bye!') sys.exit() else: print("You typed '{0}'.'.format{0}\n") convert_again() def converter(): print('-------------------------------------------\n') choice = input( "To convert from Binary to Decimal, type 'b'.\nTo convert from Decimal to Binary, type 'd'.\n") if choice == 'b': print('---------------------------------------') print('Converting from Binary to Decimal...\n') number = input('Enter the number you want to convert: \n') binary_to_decimal(number) convert_again() elif choice == 'd': print('---------------------------------------') print('Converting from Binary to Decimal...\n') number = input('Enter the number you want to convert: \n') decimal_to_binary(number) convert_again() else: print("You typed '{0}'.".format(choice)) converter() print('\n') converter()
25ee4620b7edb315355de1448216f604fc15129b
zero-big/Python-Basic
/String/2.3.12.string_etc2.py
610
3.5
4
setup = 'a duck goes into a bar...' #양쪽에 . 시퀀스를 삭제한다. print(setup.strip('.')) # 첫번째 단어를 대문자로 print(setup.capitalize()) # 모든 단어의 첫째 문자를 대문자로 print(setup.title()) # 글자를 모두 대문자 upper 함수 # 글자를 모두 소문자 lower 함수 # 대문자 -> 소문자로, 소문자 -> 대문자로 print(setup.swapcase()) # 문자를 지정한 공간에서 중앙에 배치 print(setup.center(30)) # 왼쪽 : ljust 함수 / 오른쪽 : rjust 함수 # a 를 a famous 로 100회 바꾼다. print(setup.replace('a', 'a famous', 100))
47702521bf85a8c3408a073fa8ac98112ac5e595
zero-big/Python-Basic
/Data/3. format.py
1,998
3.765625
4
# 데이터 값을 문자열에 끼워넣기 : format # [첫번째] 파이썬 2에서 쓰던 % n = 42; f =7.03; s = 'string cheese' print('%10.4d %10.4f %10.4s' % (n, f, s)) # 출력 : 0042 7.0300 stri # 10.4d : 10자 필드 오른쪽 정렬 및 최대 문자길이 4 # 10.4f : 10자 필드 오른쪽 정렬 및 소수점 이후 숫자길이 4 # 10.4s : 10자 필드 오른쪽 정렬 및 최대 문자길이 4 # 인자로 필드 길이 지정도 가능하다. print('%*.*d %*.*f %*.*s' % (10, 4, n, 10, 4, f, 10, 4, s)) # 결과는 위와 같다. # [두번째] {} print('{} {} {}'.format(n, f, s)) print('{n} {f} {s}'.format(n=42, f=7.03, s='string cheese')) # 출력 : 42 7.03 string cheese print('{2} {0} {1}'.format(n, f, s)) # 순서 지정도 가능 # 출력 : string cheese 42 7.03 d = {'n':42, 'f':7.03, 's':'string cheese'} # 딕셔너리를 넣어보자! print('{0[n]} {0[f]} {0[s]} {1}'.format(d, 'other')) # 출력 : 42 7.03 string cheese other print('{0:d} {1:f} {2:s}'.format(n, f, s)) # 타입 지정해주기 # 출력 : 42 7.030000 string cheese print('{n:d} {f:f} {s:s}'.format(n=42, f=7.03, s='string cheese')) # 인자에 이름 지정 # 출력 : 42 7.030000 string cheese print('{0:10d} {1:10f} {2:10s}'.format(n, f, s)) # 최소 필드 길이 10, 오른쪽 정렬 print('{0:>10d} {1:>10f} {2:>10s}'.format(n, f, s)) # '>'를 통해 오른쪽 정렬을 명확히 표현 # 공통된 출력 : 42 7.030000 string cheese print('{0:<10d} {1:<10f} {2:<10s}'.format(n, f, s)) # 왼쪽 정렬 print('{0:^10d} {1:^10f} {2:^10s}'.format(n, f, s)) # 오른쪽 정렬 # 출력 : 42 7.030000 string cheese # 출력 : 42 7.030000 string cheese print('{0:>10d} {1:>10.4f} {2:>10.4s}'.format(n, f, s)) # 정수는 10.4d를 사용할 수 없다!!!! # 출력 : 42 7.0300 stri print('{0:!^20s}'.format('BIG SALE')) # 길이 지정자 이전에 채워 넣고 싶은 문자를 입력 # 출력 : !!!!!!BIG SALE!!!!!!
9b750390731edd5a1a683067240907563877df45
zero-big/Python-Basic
/Pyscience/3. numpy.py
2,391
3.890625
4
import numpy as np # 1. 배열 만들기 : array b = np.array([2, 4, 6, 8]) print(b) # [2 4 6 8] # ndim : 랭크를 반환 print(b.ndim) # 1 # size : 배열에 있는 값의 총 개수 반환 print(b.size) # 4 # shape : 각 랭크에 있는 값의 개수 반환 print(b.shape) # (4,) a = np.arange(10) print(a) # [0 1 2 3 4 5 6 7 8 9] print(a.ndim) # 1 print(a.shape) # (10,) print(a.size) # 10 a = np.arange(7, 11) print(a) # [ 7 8 9 10] f = np.arange(2.0, 9.8, 0.3) print(f) # [2. 2.3 2.6 2.9 3.2 3.5 3.8 4.1 4.4 4.7 5. 5.3 5.6 5.9 6.2 6.5 6.8 7.1 # 7.4 7.7 8. 8.3 8.6 8.9 9.2 9.5 9.8] g = np.arange(10, 4, -1.5, dtype=np.float) print(g) # [10. 8.5 7. 5.5] a = np.zeros((3,)) print(a) # [0. 0. 0.] print(a.ndim) # 1 print(a.shape) # (3,) print(a.size) # 3 b = np.zeros((2, 4)) print(b) # [[0. 0. 0. 0.] # [0. 0. 0. 0.]] print(b.ndim) # 2 print(b.shape) # (2, 4) print(b.size) # 8 k = np.ones((3, 5)) print(k) # [[1. 1. 1. 1. 1.] # [1. 1. 1. 1. 1.] # [1. 1. 1. 1. 1.]] m = np.random.random((3, 5)) print(m) # [[0.92144665 0.79460743 0.98429623 0.5172086 0.0727177 ] # [0.3467992 0.07082806 0.06713763 0.92576145 0.37867405] # [0.57972622 0.02252859 0.66872603 0.70532502 0.7316084 ]] a = np.arange(10) a = a.reshape(2, 5) print(a) # [[0 1 2 3 4] # [5 6 7 8 9]] print(a.ndim) # 2 print(a.shape) # (2, 5) print(a.size) # 10 a = a.reshape(5, 2) print(a) # [[0 1] # [2 3] # [4 5] # [6 7] # [8 9]] print(a.ndim) # 2 print(a.shape) # (5, 2) print(a.size) # 10 a.shape = (2, 5) print(a) # 배열 연산 from numpy import * a = arange(4) a *= 3 print(a) # [0 3 6 9] plain_list = list(range(4)) print(plain_list) # [0, 1, 2, 3] plain_list = [num*3 for num in plain_list] print(plain_list) # [0, 3, 6, 9] a = zeros((2, 5)) + 17.0 print(a) # [[17. 17. 17. 17. 17.] # [17. 17. 17. 17. 17.]] # @ : 행렬 곱 a = np.array([[1,2], [3,4]]) b = a @ a print(b) # [[ 7 10] # [15 22]] # 선형 대수 # 4x + 5y = 20 # x + 2y = 13 coefficients = np.array([ [4,5], [1,2]]) dependents = np.array([20, 13]) answer = np.linalg.solve(coefficients, dependents) print(answer) # [-8.33333333 10.66666667] print(4 * answer[0] + 5 * answer[1] ) # 20.0 print(1 * answer[0] + 2 * answer[1] ) # 13.0 product = np.dot(coefficients, answer) print(product) # [20. 13.] print(np.allclose(product, dependents)) # True
88c61ce7dca614082096064bb028161dd28c0207
zero-big/Python-Basic
/Tool/3. code_debugging.py
1,334
3.9375
4
''' 파이썬에서 디버깅하는 가장 간단한 방법은 문자열을 출력하는 것이다. - vars() : 함수의 인자값과 지역 변수값을 추출 ''' def func(*args, **kwargs): print(vars()) func(1, 2, 3) # {'args': (1, 2, 3), 'kwargs': {}} ''' 데커레이터(decorator)를 사용하면 함수 내의 코드를 수정하지 않고, 이전 혹은 이후에 코드를 호출할 수 있다. ''' def dump(func): "인자값과 결과값을 출력한다." def wrapped(*args, **kwargs): print("Function name: {}".format(func.__name__)) print("Input arguments: {}".format(''.join(map(str, args)))) print("Input keyword arguments: {}".format(kwargs.items())) output = func(*args, **kwargs) print("Output:", output) return output return wrapped @dump def double(*args, **kwargs): "모든 인자값을 두 배로 반환한다." output_list = [ 2 * arg for arg in args ] output_dict = { k:2*v for k,v in kwargs.items() } return output_list, output_dict if __name__ == '__main__': output = double(3, 5, first=100, next=98.6, last=-40) ''' 출력 Function name: double Input arguments: 35 Input keyword arguments: dict_items([('first', 100), ('next', 98.6), ('last', -40)]) Output: ([6, 10], {'first': 200, 'next': 197.2, 'last': -80}) '''
4b7c355bd3b395abe1537db19ceb3df7fa1ff9ec
Magdalon/Snippets
/terningkast.py
254
3.625
4
from random import randint def terningkast(): kast = int(input("Hvor mange terningkast?")) seksere = 0 for i in range(kast): if randint(1,6) == 6: seksere +=1 print("Antall seksere:") print(seksere) terningkast()
c8bc3f032fc80622faa026514638f6764988906f
moojan/Python-BEAGLE-HHM
/getShuffle.py
282
3.5625
4
import numpy as np """GETSHUFFLE provides a permutation and inverse permutation of the numbers 1:N. perm: for shuffling invPerm: for unshuffling""" def getShuffle(n): perm = np.random.permutation(n) invperm = perm[::-1] return perm #, invperm
c296dab78893f00978039d1a8edee17c8d6d6b3d
lillyfae/cse210-tc05
/puzzle.py
1,812
4.125
4
import random class Puzzle: '''The purpose of this class is to randomly select a word from the word list. Sterotyope: Game display Attributes: word_list (list): a list of words for the puzzle to choose from chosen_word (string): a random word from the word list create_spaces (list of strings): a list of characters that will initially contain spaces and be filled in with player guesses ''' def __init__(self): '''Class constructor. Declares and initializes instance attributes. Args: self (Puzzle): An instance of Puzzle. ''' self.word_list = ["teach","applied","remain","back","raise","pleasant" "organization","plenty","continued","all","seldom","store" "refer","toy","stick","by","shine","field" "load","forth","well","mine","catch","complex" "useful","camera","teacher","sit","spin","wind" "drop","coal","every","friend","throw","wool" "daughter","bound","sight","ordinary","inch","pan"] self.chosen_word = self.random_word() self.create_spaces() def random_word(self): '''Gets a random word from the word list. Args: self (Puzzle): An instance of Puzzle. Returns: the word ''' return random.choice(self.word_list) def create_spaces(self): '''Creates the list of spaces Args: self (Puzzle) ''' self.spaces = [] for i in range(len(self.chosen_word)): self.spaces.append('_') def print_spaces(self): '''Prints out the spaces Args: self (Puzzle) ''' for ch in self.spaces: print(ch + " ", end='') print('\n')
8cd9750c60e15e79b53101fe543c5a4b01f42dd2
brandon-rhodes/python-sgp4
/sgp4/conveniences.py
3,527
3.65625
4
"""Various conveniences. Higher-level libraries like Skyfield that use this one usually have their own date and time handling. But for folks using this library by itself, native Python datetime handling could be convenient. """ import datetime as dt import sgp4 from .functions import days2mdhms, jday class _UTC(dt.tzinfo): 'UTC' zero = dt.timedelta(0) def __repr__(self): return 'UTC' def dst(self, datetime): return self.zero def tzname(self, datetime): return 'UTC' def utcoffset(self, datetime): return self.zero UTC = _UTC() def jday_datetime(datetime): """Return two floats that, when added, produce the specified Julian date. The first float returned gives the date, while the second float provides an additional offset for the particular hour, minute, and second of that date. Because the second float is much smaller in magnitude it can, unlike the first float, be accurate down to very small fractions of a second. >>> jd, fr = jday(2020, 2, 11, 13, 57, 0) >>> jd 2458890.5 >>> fr 0.58125 Note that the first float, which gives the moment of midnight that commences the given calendar date, always carries the fraction ``.5`` because Julian dates begin and end at noon. This made Julian dates more convenient for astronomers in Europe, by making the whole night belong to a single Julian date. The input is a native `datetime` object. Timezone of the input is converted internally to UTC. """ u = datetime.astimezone(UTC) year = u.year mon = u.month day = u.day hr = u.hour minute = u.minute sec = u.second + u.microsecond * 1e-6 return jday(year, mon, day, hr, minute, sec) def sat_epoch_datetime(sat): """Return the epoch of the given satellite as a Python datetime.""" year = sat.epochyr year += 1900 + (year < 57) * 100 days = sat.epochdays month, day, hour, minute, second = days2mdhms(year, days) if month == 12 and day > 31: # for that time the ISS epoch was "Dec 32" year += 1 month = 1 day -= 31 second, fraction = divmod(second, 1.0) second = int(second) micro = int(fraction * 1e6) return dt.datetime(year, month, day, hour, minute, second, micro, UTC) _ATTRIBUTES = None def dump_satrec(sat, sat2=None): """Yield lines that list the attributes of one or two satellites.""" global _ATTRIBUTES if _ATTRIBUTES is None: _ATTRIBUTES = [] for line in sgp4.__doc__.splitlines(): if line.endswith('*'): title = line.strip('*') _ATTRIBUTES.append(title) elif line.startswith('| ``'): pieces = line.split('``') _ATTRIBUTES.append(pieces[1]) i = 2 while pieces[i] == ', ': _ATTRIBUTES.append(pieces[i+1]) i += 2 for item in _ATTRIBUTES: if item[0].isupper(): title = item yield '\n' yield '# -------- {0} --------\n'.format(title) else: name = item value = getattr(sat, item, '(not set)') line = '{0} = {1!r}\n'.format(item, value) if sat2 is not None: value2 = getattr(sat2, name, '(not set)') verdict = '==' if (value == value2) else '!=' line = '{0:39} {1} {2!r}\n'.format(line[:-1], verdict, value2) yield line
462a87b89e16e39b0bf1ad560eeda5c8cd53bd6e
fffFancy/myPython1
/chapter3/First.py
306
3.71875
4
import random def getAnswer(answerNum): if answerNum == 1: return 'It is certain' elif answerNum == 2: return 'It is decidedly so' elif answerNum == 3: return 'Yes' else: return 'Ask again later' r = random.randint(1,9) fortune = getAnswer(r) print(fortune)
0e948b831e8ba1f5ccb7aecb95ebd0ae4fb6cdda
fffFancy/myPython1
/chapter4/PracticeCode.py
1,406
3.828125
4
# 方法一,不完善,没有考虑列表嵌套 # def changeListToStr(alist): # para = str(alist[0]) # for i in range(1, len(alist)-1): # para = para + ', ' + str(alist[i]) # # para = para + ' and ' + str(alist[-1]) # # print(para) # # changeListToStr(['apples','bananas','tofu','cats']) # changeListToStr([1,2,3,4,5]) # changeListToStr([1,2,'4',5,'cats']) # 方法二,使用一些现成的方法,摘自网络,缺点没有处理非字符串的情况以及and前面的逗号 # 值得借鉴的是把和前面不一样的元素直接在列表中处理成一个整体 # def list2Str(alist): # alist[-1] = ' and ' + str(alist[-1]) # para = ', '.join(alist) # print(para) # # list2Str(['apples','bannas','tofu','cats']) # 方法三,考虑列表嵌套,先处理列表 def listUnfold(listBefore): listAfter = [] for value in listBefore: if type(value) == list: listMid = listUnfold(value) for item in listMid: listAfter.append(item) else: listAfter.append(value) return listAfter def list2str(alist): blist = listUnfold(alist) print(blist) blist[-1] = ' and ' + str(blist[-1]) astr = str(blist[0]) for i in range(len(blist)-1): astr = astr + ', ' + str(blist[i]) astr = astr + str(blist[-1]) print(astr) list2str([[[7,5],0],8,[8,[0,[9,7]]],3,9])
0eabd87271acc72d1a716f09afffee2c17ae5ed7
adriansctech/Python--Basic-Exercises
/Ejercicio-12/UT5_Actividad12_AdriSC.py
2,747
3.75
4
def main(): return 0 if __name__ == '__main__': main() palabras = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","v","w","x","y","z"] print "*************************************************************" print "* UT5_ACTIVIDAD12 *" print "*************************************************************" print "* AdriSC *" print "*************************************************************" print " Introduce un string :" frase = raw_input().lower() a=frase.count(palabras[0]) if a>0: print "La 'a' se ha repetido :",a,"veces." b=frase.count(palabras[1]) if b>0: print "La 'b' se ha repetido :",b,"veces." c=frase.count(palabras[2]) if c>0: print "La 'c' se ha repetido :",c,"veces." d= frase.count(palabras[3]) if d>0: print "La 'd' se ha repetido :",d,"veces." e= frase.count(palabras[4]) if e>0: print "La 'e' de ha repetido :",e,"veces." f = frase.count(palabras[5]) if f>0: print "La 'f' se ha repetido :",f,"veces" g=frase.count(palabras[6]) if g>0: print "La 'g' se ha repetido :",g,"veces" h=frase.count(palabras[7]) if h>0: print "La 'h' se ha repetido :",h,"veces" i=frase.count(palabras[8]) if i>0: print "La 'i' se ha repetido :",i,"veces" j=frase.count(palabras[9]) if j>0: print "La 'j' se ha repetido :",j,"veces" k=frase.count(palabras[10]) if k>0: print "La 'k' se ha repetido :",k,"veces" l=frase.count(palabras[11]) if l>0: print "La 'l' se ha repetido :",l,"veces" m=frase.count(palabras[12]) if m>0: print "La 'm' se ha repetido :",m,"veces" n=frase.count(palabras[13]) if n>0: print "La 'n' se ha repetido :",n,"veces" o=frase.count(palabras[14]) if o>0: print "La 'o' se ha repetido :",o,"veces" p=frase.count(palabras[15]) if p>0: print "La 'p' se ha repetido :",p,"veces" q=frase.count(palabras[16]) if q>0: print "La 'q' se ha repetido :",q,"veces" r=frase.count(palabras[17]) if r>0: print "La 'r' se ha repetido :",r,"veces" s=frase.count(palabras[18]) if s>0: print "La 's' se ha repetido :",s,"veces" t=frase.count(palabras[19]) if t>0: print "La 't' se ha repetido :",t,"veces" v=frase.count(palabras[20]) if v>0: print "La 'v' se ha repetido :",v,"veces" w=frase.count(palabras[21]) if w>0: print "La 'w' se ha repetido :",w,"veces" x=frase.count(palabras[22]) if x>0: print "La 'x' se ha repetido :",x,"veces" y=frase.count(palabras[23]) if y>0: print "La 'y' se ha repetido :",y,"veces" z=frase.count(palabras[24]) if z>0: print "La 'z' se ha repetido :",z,"veces"
187da656876fc244b6a7e8a8609b0b701da5ac34
prasertcbs/python_tutorial
/src/min_dhm.py
784
4.09375
4
def min_to_day_hour_minute(minutes): min_per_day = 24 * 60 # 1440 d = minutes // min_per_day h = (minutes - (d * min_per_day)) // 60 m = minutes - (d * min_per_day + h * 60) return (d, h, m) # tuple def min_to_day_hour_minute_dic(minutes): min_per_day = 24 * 60 # 1440 d = minutes // min_per_day h = (minutes - (d * min_per_day)) // 60 m = minutes - (d * min_per_day + h * 60) return {'day': d, 'hour': h, 'minute': m} if __name__ == "__main__": print(min_to_day_hour_minute(2441)) d, h, m = min_to_day_hour_minute(2441) print(d, h, m) total_min = d * (24 * 60) + h * 60 + m print(total_min) # print(min_to_day_hour_minute_dic(2441)) d = min_to_day_hour_minute_dic(2441) print(d['day'], d['hour'], d['minute'])
ca851a63737efa0dbef14a3d542e64797b808cce
prasertcbs/python_tutorial
/src/while_loop.py
677
4.15625
4
def demo1(): i = 1 while i <= 10: print(i) i += 1 print("bye") def demo_for(): for i in range(1, 11): print(i) print("bye") def sum_input(): n = int(input("enter number: ")) total = 0 while n != 0: total += n n = int(input("enter number: ")) print("total = ", total) def sum_input_repeat_unit(): total = 0 while True: n = int(input("enter number: ")) if n != 0: total += n else: break print("total = ", total) # repeat until # do ... while # demo1() # demo_for() # sum_input() sum_input_repeat_unit()
297f36d9f45831806c3935f60ecc4764623ac62a
prasertcbs/python_tutorial
/src/demo_debug3.py
221
3.53125
4
import random def demo(): for i in range(100): d1 = random.randint(1, 6) d2 = random.randint(1, 6) d = d1 + d2 print("{:>4}: {} + {} = {:>2}".format(i + 1, d1, d2, d)) demo()
97d063a69a1b0d07b13145cbcaf48c7ae947770f
prasertcbs/python_tutorial
/src/random_demo2.py
624
3.75
4
import random # print(random.random()) # [print(random.randint(1, 6)) for i in range(10)] # [print(random.randrange(1, 7)) for i in range(10)] # [print(random.randrange(0, 20, 2)) for i in range(10)] # [print(random.choice(["rock", "paper", "scissors"])) for i in range(5)] # [print(random.choice("HT")) for i in range(5)] # [print(random.normalvariate(160, 3.5)) for i in range(5)] flowers = ["lily", "rose", "tulip", "magnolia", "jasmine", "carnation"] b = random.sample(flowers, 3) print(b) # print(flowers) # random.shuffle(flowers) # print(flowers) # [print(random.uniform(1, 10)) for i in range(5)]
93980f525adf6752437fb6de571bb1881ada359c
prasertcbs/python_tutorial
/src/remove_whitespace_demo.py
842
3.578125
4
def read_demo1(filename): with open(filename, mode="r") as f: s = f.readlines() print(s) s2 = [line.strip() for line in s] print(s2) def read_demo2(filename): with open(filename, mode="r") as f: s = [line.strip() for line in f] print(s) def read_demo3(filename): with open(filename, mode="r") as f: s = f.read() print(s) s2=s.splitlines() print(s2) s3 = [a.strip() for a in s2] print(s3) def read_demo4(filename): with open(filename, mode="r", encoding="utf8") as f: s = f.readlines() print(s) s2 = [a.strip().split(",") for a in s] s3 = [a.split(",") for a in s] print(s2) print(s3) filename = "planet2.txt" # read_demo1(filename) # read_demo2(filename) # read_demo3(filename) read_demo4(filename)
fae074b5290fb36bc9e56b73bd74a99a615fd124
prasertcbs/python_tutorial
/src/namedtuple_demo.py
993
3.84375
4
from collections import namedtuple def demo1(): x = (4, 7, 8) print("x = ", x) Medal = namedtuple("Medal", ["gold", "silver", "bronze"]) th = Medal(4, 7, 8) print("th = ", th) print(th.gold) print(sum(th[:2])) def demo2(): Medal = namedtuple("Medal", ["country", "gold", "silver", "bronze"]) th = Medal("Thailand", 4, 7, 8) print(th.country) print(sum(th[1:])) def demo3(): Medal = namedtuple("Medal", "country gold silver bronze") th = Medal("Thailand", 4, 7, 8) print(th) kr = Medal(country = "Korea", bronze=10, gold=15, silver=7) print(kr) j = ("Japan", 30, 20, 10) jp = Medal._make(j) print(jp) od = jp._asdict() print(od) def demo4(): Area = namedtuple("RaiNganSqwa", "rai ngan sqwa") area1 = Area(3, 2, 70) print(area1) total_area = area1.rai * 400 + area1.ngan * 100 + area1.sqwa print(total_area) # demo1() # demo2() # demo3() demo4()
fc145d14d64e69b1ad72dca096a692f5354e00c0
prasertcbs/python_tutorial
/src/age_yy_mm_d.py
398
3.578125
4
from datetime import date # pip install python-dateutil from dateutil.relativedelta import relativedelta def how_old_ymd(dob): age = relativedelta(date.today(), dob) print(age) return age.years, age.months, age.days print(date.today()) # print(how_old_ymd(date(1997, 7, 10))) y, m, d = how_old_ymd(date(1997, 7, 10)) print("{} year {} month {} days".format(y, m, d))
e322ea4e9bc34545804c3683771a7c12e116e2c7
prasertcbs/python_tutorial
/src/string_method3.py
918
3.515625
4
import random def join_demo(): stations = ("HUA", "SAM", "SIL", "LUM", "KHO", "SIR", "SUK", "PET", "RAM", "CUL", "HUI", "SUT", "RAT", "LAT", "PHA", "CHA", "KAM", "BAN") print(stations) print(" -> ".join(stations)) print(" -> ".join(stations[1:4])) print(" -> ".join(stations[1:4][::-1])) def password_generator(length): # s = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") # print(s) # p = random.sample(s, length) # print(p) # return "".join(random.sample(s, length)) return "".join(random.sample(list("ABCDEFGHJKLMNPQRSTUVWXYZ23456789"), length)) def replace_demo(): s = "password" s2 = s.replace("a", "@") s3 = s.replace("a", "@").replace("o", "0") s4 = s.replace("pass", "fail") print(s, s2, s3, s4) # join_demo() # for i in range(10): # print(password_generator(8)) replace_demo()
1f35eb0f2ed224fdd8bf552ad07d8537cacdf133
prasertcbs/python_tutorial
/src/vin.py
2,021
3.765625
4
# https://en.wikibooks.org/wiki/Vehicle_Identification_Numbers_(VIN_codes)/Check_digit def vin_checkdigit(vin): weight = ( 8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2 ) t = { "A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "H": 8, "J": 1, "K": 2, "L": 3, "M": 4, "N": 5, "P": 7, "R": 9, "S": 2, "T": 3, "U": 4, "V": 5, "W": 6, "X": 7, "Y": 8, "Z": 9, "_": 0 } total = 0 for v, w in zip(vin, weight): if v.isdigit(): total += int(v) * w else: total += t[v.upper()] * w r = total % 11 return "X" if r == 10 else str(r) def vin_checkdigit2(vin): weight = ( 8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2 ) t = { "A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "H": 8, "J": 1, "K": 2, "L": 3, "M": 4, "N": 5, "P": 7, "R": 9, "S": 2, "T": 3, "U": 4, "V": 5, "W": 6, "X": 7, "Y": 8, "Z": 9, "_": 0, "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9 } total = 0 for v, w in zip(vin, weight): total += t[v.upper()] * w r = total % 11 return "X" if r == 10 else str(r) def vin_checkdigit3(vin): weight = ( 8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2 ) t = { "A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "H": 8, "J": 1, "K": 2, "L": 3, "M": 4, "N": 5, "P": 7, "R": 9, "S": 2, "T": 3, "U": 4, "V": 5, "W": 6, "X": 7, "Y": 8, "Z": 9, "_": 0, "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9 } r = sum([t[v.upper()] * w for v, w in zip(vin, weight)]) % 11 return "X" if r == 10 else str(r) # print(vin_checkdigit("1M8GDM9A_KP042788")) # print(vin_checkdigit("LJCPCBLCX11000237")) print(vin_checkdigit("JHLRD77874C026456")) print(vin_checkdigit2("JHLRD77874C026456")) print(vin_checkdigit3("JHLRD77874C026456"))
1e8090298859aaa7df4097c052e771252f1ae8a9
prasertcbs/python_tutorial
/src/zip_demo.py
1,077
3.546875
4
# zip def demo1(): weight = [70, 60, 48] height = [170, 175, 161] bmi = [] for i in range(len(weight)): bmi.append(weight[i] / (height[i] / 100) ** 2) return bmi def demo2(): weight = [70, 60, 48] height = [170, 175, 161] bmi = [] for w, h in zip(weight, height): # print(w, h) bmi.append(w / (h / 100) ** 2) return bmi def demo3(): weight = [70, 60, 48] height = [170, 175, 161] return [w / (h / 100) ** 2 for w, h in zip(weight, height)] def demo4(): weight = [70, 60, 48] height = [170, 175, 161] name = ["Leo", "Ben", "Peter"] return [{n: w / (h / 100) ** 2} for w, h, n in zip(weight, height, name)] def demo5(): weight = [70, 60, 48] height = [170, 175, 161] name = ["Leo", "Jane", "Peter"] gender = ["M", "F", "M"] return [{n: w / (h / 100) ** 2} for w, h, n, g in zip(weight, height, name, gender) if g == "M"] print(demo1()) print(demo2()) print(demo3()) print(demo4()) print(demo5())
1d542e2baaefdc942aa96047ebcf3ea021caa317
prasertcbs/python_tutorial
/src/mult_table.py
312
3.796875
4
def mtable(fromN=2, toN=6): for i in range(1, 13): for j in range(fromN, toN + 1): print("{:2} x {:2} = {:3} | ".format(j, i, j * i), end="") print() if __name__ == '__main__': # fromN = int(input("from:")) # toN = int(input("to:")) # mtable(fromN, toN) mtable()
95d5668794f9de9904748c696cb5f1d1b0736071
prasertcbs/python_tutorial
/src/string_format2.py
938
3.859375
4
def demo(): print("{}{}".format("th", "Thailand")) print("{:5}|{:15}|".format("th", "Thailand")) # align left print("{:<5}|{:<15}|".format("th", "Thailand")) # align left print("{:>5}|{:>15}|".format("th", "Thailand")) # align right print("{:*>5}|{:->15}|".format("th", "Thailand")) # align right print("{:^5}|{:^15}|".format("th", "Thailand")) # align center def mult_table(n): for i in range(1, 13): print("{} x {:2} = {:3}".format(n, i, n * i)) def ascii_table(): for i in range(65, 128): print("{0:3} {0:#08b} {0:04o} {0:#x} {0:X} {0:c}".format(i)) def demo_dict(): menu = {"name": "mocha", "price": 40, "size": "m"} print(menu["name"]) print("menu name = {} price = {}".format(menu["name"], menu["price"])) print("menu name = {name}({size}) price = {price}".format(**menu)) # demo() # demo_dict() # mult_table(12) ascii_table()
1ddf917b2b2d1d2953eb181f7c24c179aad662f7
syamaguchijp/Others
/Python/Class.py
1,588
3.578125
4
# coding: utf-8 class User: # クラス変数(Public) className = None # コンストラクタ def __init__(self, name, age): # インスタンス変数(Public) self.name = name self.age = age # インスタンス変数(Private) self.__address = None # デストラクタ def __del__(self): print("destructor") # プロパティ(ゲッター) @property def address(self): return self.__address # プロパティ(セッター) @address.setter def address(self, address): self.__address = address # インスタンスメソッド def dump(self): return ("name: %s, age: %d, address: %s" % (self.name, self.age, self.address)) # クラスメソッド @classmethod def classMethod(cls): print("class_method") # スタティックメソッド @staticmethod def staticMethod(): print("static_method") # 継承 class SpecialUser (User): # オーバーライド def dump(self): return ("SubClass name: %s, age: %d, address: %s" % (self.name, self.age, self.address)) # 生成 user1 = User("Honda", 27) str1 = user1.dump() print(str1) # プロパティへのアクセス user1.address = "Tokyo" print(user1.address) # クラス変数 User.className = "ABC" print(User.className) # クラスメソッドとスタティックメソッド User.classMethod() User.staticMethod() # サブクラス user2 = SpecialUser("Kawasaki", 33) str2 = user2.dump() print(str2)
e105386bcb9851004f3243f42f385ebc39bac8b7
KAOSAIN-AKBAR/Python-Walkthrough
/casting_Python.py
404
4.25
4
x = 7 # print the value in float print(float(x)) # print the value in string format print(str(x)) # print the value in boolean format print(bool(x)) # *** in BOOLEAN data type, anything apart from 0 is TRUE. Only 0 is considered as FALSE *** # print(bool(-2)) print(bool(0)) # type casting string to integer print(int("34")) # print(int("string")) ----> would produce error ; please donot try this
f64eb90364c4acd68aac163e8f76c04c86479393
KAOSAIN-AKBAR/Python-Walkthrough
/calendar_Python.py
831
4.40625
4
import calendar import time # printing header of the week, starting from Monday print(calendar.weekheader(9) + "\n") # printing calendar for the a particular month of a year along with spacing between each day print(calendar.month(2020, 4) + "\n") # printing a particular month in 2-D array mode print(calendar.monthcalendar(2020, 4)) print() # printing calendar for the entire year print(calendar.calendar(2020)) print() # printing a particular day of the week in a month in terms of integer print(calendar.weekday(2020, 4, 12)) # answer is 6, because according to python 6 is Sunday print() # finding whether a year is leap year or not print(calendar.isleap(2020)) print() # finding leap days within specific years, the year you put at the end is exclusive, 2000 and 2004 is leap year. print(calendar.leapdays(2000,2005))
f18161063141ca4c5ca0f71ab54e491f93c17acf
shade9795/Cursos
/python/ejercicio4.py
153
3.578125
4
precio=int(input("Ingrese el precio: ")) cantidad=int(input("ingrese cantidad")) importe=precio*cantidad print("el importe total es de:") print(importe)
ddc4112ca99f04ff02838546bd3543b03e0cf3a1
shade9795/Cursos
/python/problemas/Estructura de programación secuencial/problema2.py
245
3.984375
4
num1=int(input("num 1: ")) num2=int(input("num 2: ")) num3=int(input("num 3: ")) num4=int(input("num 4: ")) suma=num1+num2 producto=num3*num4 print("el resultado de la suma es:") print(suma) print("el resultado del producto es") print(producto)
5af9931029bef4345ffc1528219484cd363fbcfa
shade9795/Cursos
/python/problemas/Condiciones compuestas con operadores lógicos/problema5.py
257
4.125
4
x=int(input("Cordenada X: ")) y=int(input("Cordenada Y: ")) if x==0 or y==0: print("Las coordenadas deben ser diferentes a 0") else: if x>0 and y>0: print("1º Cuadrante") else: if x<0 and y>0: print("2º Cuadrante")
bdbc33109f40ea9f6d0845fcb039467bbcc09d92
shade9795/Cursos
/python/ejercicio20.py
183
3.828125
4
dia=int(input("Ingrese el dia: ")) mes=int(input("Ingrese el mes: ")) año=int(input("Ingrese el año: ")) if mes==1 or mes==2 or mes==3: print("Corresponde al primer trimestre")
1bf441f93b17207eb3055dd79f647415181e7892
logstown/project-euler
/problem22.py
608
3.609375
4
def quicksort(listie): if len(listie) <= 1: return listie pivot = [listie[len(listie)/2]] listie.remove(pivot[0]) less = [] greater = [] for x in listie: if x <= pivot[0]: less.append(x) else: greater.append(x) return quicksort(less) + pivot + quicksort(greater) f = open('names.txt', 'r') bigstring = f.read() bigstring = bigstring.replace('"',"") bigarr = bigstring.split(',') # sortedarr = quicksort(bigarr) bigarr.sort() tot = 0 for x in range(0, len(bigarr)): name = bigarr[x] val = 0 for y in range(0, len(name)): val += ord(name[y])-64 tot += val * (x+1) print tot
372b542ddb42ce5ae8e0c0064e9780dbbb1baee4
DauletY/PyCode
/PythonExample/JungleCam.py
311
3.546875
4
def Primere(): sound = str(input()) t = "Tiger" s = "Snake" l = "Lion Lion" b = "Bird" i = 1 while i <= 4: i += 1 if sound == "Grr": sound = l elif sound == "Ssss": sound = s elif sound == "Rawr": sound = t elif sound == "Chirp": sound = b print(sound) Primere()
a8f4268bd6f4a6f121deeb4a1acdfd8751ecb37f
DauletY/PyCode
/PythonExample/testpy.py
112
3.90625
4
#commint here x = int(input()) y = int(input()) if x % y == 0: print('even ',x) else: print('odd',y)
f809c940240766b014b341c8c9ed5d7fc19252ce
Qing8/Chat_system-2018-
/reversegam.py
8,973
3.796875
4
import random import sys WIDTH = 8 HEIGHT = 8 def drawBoard(board): #print the board passed to this #funtion and return NONE print(" 12345678") print(" +------+") for y in range(HEIGHT): print("{0}|".format(y+1),end = "") for x in range(WIDTH): print(board[x][y],end="") print("|{0}".format(y+1)) print(" +------+") print(" 12345678") def getNewBoard(): # create a brand-new, blank board # data structure board = [] for i in range(WIDTH): board.append([" "," "," "," "," "," "," "," "]) return board def isValidMove(board, tile, xstart, ystart): # return False if the player's # move on space xstart, ystart # is invalid # if it is a valid move, return # a list of spaces that would # become the player's if they # made a move here if board[xstart][ystart] != " " or not isOnBoard(xstart,ystart): return False if tile == "X": otherTile = "0" else: otherTile = "X" tilesToFlip = [] for xdirection, ydirection in [[0,1],[1,1],[1,0],[1,-1],[0,-1],[-1,-1],[-1,0],[-1,1]]: x, y = xstart, ystart x += xdirection y += ydirection while isOnBoard(x,y) and board[x][y] == otherTile: # keep moving in this x&y direction x += xdirection y += ydirection if isOnBoard(x, y) and board[x][y] == tile: # there are pieces to flip over, go in the reverse direction # until we reach the original space, noting all the tiles # along the way. while True: x -= xdirection y -= ydirection if x == xstart and y == ystart: break tilesToFlip.append([x,y]) if len(tilesToFlip) == 0: return False return tilesToFlip def isOnBoard(x, y): return 0 <= x <= WIDTH-1 and 0 <= y <= HEIGHT-1 def getBoardWithValidMoves(board,tile): # return a new board with periods marking the valid move the player can make boardCopy = getBoardCopy(board) for x,y in getValidMoves(boardCopy, tile): boardCopy[x][y] = "." return boardCopy def getValidMoves(board,tile): # return a list of [x,y] lists of valid moves for the given player on the given board validMoves = [] for x in range(WIDTH): for y in range(HEIGHT): if isValidMove(board,tile,x,y) != False: validMoves.append([x,y]) return validMoves def getScoreOfBoard(board): # determine the score by counting the tiles. return a dictionary with key "x"&"0" xscore = 0 oscore = 0 for x in range(WIDTH): for y in range(HEIGHT): if board[x][y] == "X": xscore += 1 if board[x][y] == "0": oscore += 1 return {"X":xscore, "0":oscore} def enterPlayerTile(): # let the player enter which tile they want to be # return a list with the player's tile as the first item and computer's tile as the second tile = "" while not (tile == "X" or tile == "0"): tile = input("Do you want to be X or 0?").upper() # the first element in the list is the player's tile, and the second is the computer's tile if tile == "X": return ["X","0"] else: return ["0","X"] def whoGoesFirst(): # randomly choose who goes first if random.randint(0,1) == 0: return "computer" else: return "player" def makeMove(board,tile,xstart,ystart): # place the tile on the board at xstart, ystart and flip any of the opponent's pieces # return False if this is an invalid move, True if it is valid tilesToFlip = isValidMove(board,tile,xstart,ystart) if tilesToFlip == False: return False board[xstart][ystart] = tile for x,y in tilesToFlip: board[x][y] = tile return True def getBoardCopy(board): # make a duplicate of the board list and return it boardCopy = getNewBoard() for x in range(WIDTH): for y in range(HEIGHT): boardCopy[x][y] = board[x][y] return boardCopy def isOnCorner(x,y): # return True if the position is in one of the four corners return (x==0 or x== WIDTH-1) and (y == 0 or y ==HEIGHT-1) def getPlayerMove(board,playerTile): # let the player enter their move # return the move as [x,y] (or return the strings 'hints' or 'quit') DIGITSIT08 = '1 2 3 4 5 6 7 8'.split() while True: print("Enter your move, 'quit' to end the game, or 'hints' to toggle hints.") move = input().lower() if move == "quit" or move == "hints": return move if len(move) == 2 and move[0] in DIGITSIT08 and move[1] in DIGITSIT08: x = int(move[0]) -1 y = int(move[1]) -1 if isValidMove(board,playerTile,x,y) == False: continue else: break else: print("This is not a valid move, enter the column (1-8) and then the row(1-8)") print("For example, 81 will move on the top-right corner.") return [x,y] def getComputerMove(board,computerTile): # given a board and the computer's tile, determine where to move and return that mvoe as an [x,y] list. possibleMoves = getValidMoves(board,computerTile) # randomize the order of the moves random.shuffle(possibleMoves) # always go for a corner if available for x,y in possibleMoves: if isOnCorner(x,y): return [x,y] # find the highest-scoring move possible bestScore = -1 for x,y in possibleMoves: boardCopy = getBoardCopy(board) makeMove(boardCopy,computerTile,x,y) score = getScoreOfBoard(boardCopy)[computerTile] if score > bestScore: bestMove = [x,y] bestScore = score return bestMove def printScore(board,playerTile,computerTile): scores = getScoreOfBoard(board) print("You: {0} points\ncomputer: {1} points.".format(scores[playerTile],scores[computerTile])) def playGame(playerTile, computerTile): showHints = False turn = whoGoesFirst() print("{0} goes first".format(turn)) board = getNewBoard() board[3][3] = "X" board[3][4] = "0" board[4][3] = "0" board[4][4] = "X" while True: playerValidMoves = getValidMoves(board,playerTile) computerValidmoves = getValidMoves(board,computerTile) if playerValidMoves == [] and computerValidmoves == []: return board elif turn == "player": if playerValidMoves != []: if showHints: validMovesBoard = getBoardWithValidMoves(board,playerTile) drawBoard(validMovesBoard) else: drawBoard(board) printScore(board,playerTile, computerTile) move = getPlayerMove(board,playerTile) if move == "quit": print("Thanks for playing!") #sys.exit() elif move == "hints": showHints = not showHints continue else: makeMove(board,playerTile,move[0],move[1]) turn = "computer" elif turn == "computer": if computerValidmoves != []: drawBoard(board) printScore(board,playerTile,computerTile) input("Press Enter to see the computer's move") move = getComputerMove(board,computerTile) makeMove(board,computerTile,move[0],move[1]) turn = "player" def start(): print("Welcome to Reversegam!") playerTile, computerTile = enterPlayerTile() while True: finalBoard = playGame(playerTile,computerTile) # display the final score drawBoard(finalBoard) scores = getScoreOfBoard(finalBoard) print("X scored {0} points, 0 scores {1} points.".format(scores['X'],scores['0'])) if scores[playerTile] > scores[computerTile]: print("You beat the computer by {0} points".format(scores[playerTile]-scores[computerTile])) # result = "You beat the computer by {0} points".format(scores[playerTile]-scores[computerTile]) elif scores[playerTile] < scores[computerTile]: print("You lost the computer by {0} points".format(-scores[playerTile]+scores[computerTile])) # result = ("You lost the computer by {0} points".format(-scores[playerTile]+scores[computerTile])) else: print("it's a tie") # result = "it's a tie" print("Do you want to play again? \n(yes or no)") if not input().lower().startwith('y'): break
f3143b4d9a4c031ea2761f6024b64e0a8c3b8fb8
Shusmoy108/LeetCode
/Easy/strmatch.py
388
3.625
4
class Solution(object): def arrayStringsAreEqual(self, word1, word2): str1="" str2="" for i in range (0,len(word1)): str1=str1+word1[i] for i in range (0,len(word2)): str2=str2+word2[i] return str1==str2 """ :type word1: List[str] :type word2: List[str] :rtype: bool """
2c7fb6ec98791f8bc08159ff2ed20af3a87187cc
KRaudla/Python_kursus_2015
/he_ja_she.py
338
3.90625
4
while True: try: isikukood = int(input("Sisesta isikukood")) except ValueError: print ("Isikukood on number!") continue else: break if str(isikukood)[0] in ("1","3","5"): print ("he") elif str(isikukood)[0] > "6": print ("See pole isikukood.") else: print ("she")
09c66056d6b3187aa8fe2dbd33cfb7b34e6c7209
JonathWesley/travelingSalesman
/City.py
741
4.03125
4
class City: def __init__(self, name): self.name = name self.connectedTo = {} def distance(self, city): distance = self.connectedTo[city.name] return distance def __repr__(self): string = str(self.name) + ": (" for key, value in self.connectedTo.items(): string += str(key) + '->' + str(value) +';' string += ')' return string # apenas para teste da classe City if __name__ == "__main__": cityA = City('A') cityA.connectedTo['B'] = 2 cityA.connectedTo['C'] = 5 cityB = City('B') cityB.connectedTo['A'] = 2 cityB.connectedTo['C'] = 5 print(cityA) print(cityA.distance(cityB))
f58222387a089bfbfb947ba2371715023e2f20f1
dennysreg/HackerRankSolutions
/funnyString.py
499
3.9375
4
# Enter your code here. Read input from STDIN. Print output to STDOUT def esPalindromo(s): n = len(s) middle = n/2 for i in range(middle): if s[i]!=s[n-i-1]: return False return True t = int(raw_input()) for _ in range(t): s = raw_input() n = len(s) ascii = [ord(x) for x in s] numbers = [abs(ascii[i+1] - ascii[i]) for i in range(0,n-1)] if esPalindromo(numbers): print "Funny" else: print "Not Funny"
3a3fe86fea46900eb431cc1492f45e4291c8e651
lindsaysteinbach/cssi-prework-python-conditionals-lab-cssi-prework-2016
/morning.py
909
3.703125
4
#1. Waking Up def wake_up(day_of_week): if ((day_of_week.lower() == "saturday") or (day_of_week.lower() == "sunday")): return "Go back to bed" else: return "Stop hitting snooze" #2. The Commute def commute(weather, mins_until_work): if ((mins_until_work<=10) or (weather.lower()=="rainy")): return "Better take the car" elif ((mins_until_work>30) and (weather.lower()=="sunny")): return "Enjoy a bike ride!" else: return "Hop on the bus" #3. Coffee Buzz def coffee(number): if (number>=100): return "Time for a triple shot espresso" elif ((number<100) and (number>=50)): return "Go for a large black coffee" elif ((number<50) and (number>0)): return "A latte will serve you well" elif (number == 0): return "You have reached the Nirvana of 21st century communication!" elif (number < 0): return "Is this a new Gmail feature?"
e5f0551b8b7a2d10da36ad6b00bd6c3ef8816930
abyingh/Algorithms-and-Data-Structures-Implementations
/Data Structures/Stack.py
771
3.953125
4
""" A stack is a linear data structure which follows a particular order in which the operations are performed. The order is last in first out(LIFO). 3 operations: push, pop, top(peak) """ class Stack: def __init__(self): self.items = [] self.head = None self.tail = None def getSize(self): return len(self.items) def isEmpty(self): return 'YES' if self.getSize() == 0 else 'NO' def push(self, item): if len(self.items) == 0: self.head = item self.tail = item else: self.head = item self.items.insert(0, item) def pop(self, idx): self.items.pop(idx) self.head = data[0] def top(self): return self.items[-1]
160c64e34c9ab49034feb19a21c23a05f11ccb93
TAdeJong/moire-lattice-generator
/latticegen/transformations.py
4,097
3.5625
4
"""Common code for geometrical transformations""" import numpy as np def rotation_matrix(angle): """Create a rotation matrix an array corresponding to the 2D transformation matrix of a rotation over `angle`. Parameters ---------- angle : float rotation angle in radians Returns ------- ndarray (2x2) 2D transformation matrix corresponding to the rotation """ return np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]]) def scaling_matrix(kappa, dims=2): """Create a scaling matrix Creates a numpy array containing the `dims`-dimensional scaling matrix scaling the first dimension by `kappa`. Parameters ---------- kappa : float scaling factor of first dimension dims : int, default: 2 number of dimensions Returns ------- ndarray (dims x dims) scaling matrix corresponding to scaling the first dimension by a factor `kappa` """ return np.diag([kappa]+[1]*(dims-1)) def strain_matrix(epsilon, delta=0.16, axis=0, diff=True): """Create a scaling matrix corresponding to uniaxial strain Only works for the 2D case. Parameters ---------- epsilon : float applied strain delta : float, default 0.16 Poisson ratio. default value corresponds to graphene axis : {0, 1} Axis along which to apply the strain. diff : bool, default True Whether to apply in diffraction or real space. Returns ------- ndarray (2 x 2) scaling matrix corresponding to `epsilon` strain along `axis` """ scaling = np.full(2, 1 - delta*epsilon) scaling[axis] = 1 + epsilon if diff: scaling = 1 / scaling return np.diag(scaling) def apply_transformation_matrix(vecs, matrix): """Apply transformation matrix to a list of vectors. Apply transformation matrix `matrix` to a list of vectors `vecs`. `vecs` can either be a list of vectors, or a NxM array, where N is the number of M-dimensional vectors. Parameters ---------- vecs : 2D array or iterable list of vectors to be transformed matrix : 2D array Array corresponding to the transformation matrix Returns ------- 2D array Transformed vectors """ avecs = np.asanyarray(vecs) return avecs @ matrix.T def rotate(vecs, angle): "Rotate 2D vectors `vecs` by `angle` radians around the origin." return apply_transformation_matrix(vecs, rotation_matrix(angle)) def wrapToPi(x): """Wrap all values of `x` to the interval [-pi,pi)""" r = (x + np.pi) % (2*np.pi) - np.pi return r def a_0_to_r_k(a_0, symmetry=6): """Transform realspace lattice constant to r_k Where $r_k = (a_0\\sin(2\\pi/symmetry))^{-1}$. i.e. r_k is 1/(2\\pi) the reciprocal lattice constant. Parameters ---------- a_0 : float realspace lattice constant symmetry : integer symmetry of the lattice Returns ------- r_k : float length of k-vector in frequency space """ crossprodnorm = np.sin(2*np.pi / symmetry) r_k = 1 / a_0 / crossprodnorm return r_k def r_k_to_a_0(r_k, symmetry=6): """Transform r_k to a realspace lattice constant a_0 Parameters ---------- r_k : float length of k-vector in frequency space as used by lattigeneration functions symmetry : integer symmetry of the lattice Returns ------- a_0 : float realspace lattice constant """ crossprodnorm = np.sin(2*np.pi / symmetry) a_0 = 1 / r_k / crossprodnorm return a_0 def epsilon_to_kappa(r_k, epsilon, delta=0.16): """Convert frequency r_k and strain epsilon to corresponding r_k and kappa as consumed by functions in `latticegeneration`. Returns ------- r_k2 : float kappa : float See also -------- latticegeneration.generate_ks """ return r_k / (1 - delta*epsilon), (1+epsilon) / (1 - delta*epsilon)
61c753b75f1bf6b1dc13b30d04f0612d62473add
florije1988/pythonlearn
/learn/learn026.py
1,307
3.953125
4
# -*- coding: utf-8 -*- __author__ = 'florije' if __name__ == '__main__': a = 1 b = 1 c = 300 d = 300 print(a == b, a is b) print(c == d, c is d) # 这种的在shell里面运行的时候就会发现是不对的。 ''' In [37]: a = 1 In [38]: b = 1 In [39]: print('a is b', bool(a is b)) ('a is b', True) In [40]: c = 999 In [41]: d = 999 In [42]: print('c is d', bool(c is d)) ('c is d', False) # 原因是python的内存管理,缓存了-5 - 256的对象 In [43]: print('256 is 257-1', 256 is 257-1) ('256 is 257-1', True) In [44]: print('257 is 258-1', 257 is 258 - 1) ('257 is 258-1', False) In [45]: print('-5 is -6+1', -5 is -6+1) ('-5 is -6+1', True) In [46]: print('-7 is -6-1', -7 is -6-1) ('-7 is -6-1', False) In [47]: a = 'hello world!' In [48]: b = 'hello world!' In [49]: print('a is b,', a is b) ('a is b,', False) # 很明显 他们没有被缓存,这是2个字段串的对象 In [50]: print('a == b,', a == b) ('a == b,', True) # 但他们的值相同 # But, 有个特例 In [51]: a = float('nan') In [52]: print('a is a,', a is a) ('a is a,', True) In [53]: print('a == a,', a == a) ('a == a,', False) # 亮瞎我眼睛了~ '''
c24e0ec3bf20e113f19e61b97721757d08a6fede
florije1988/pythonlearn
/learn/learn003.py
852
3.53125
4
# -*- coding: utf-8 -*- __author__ = 'florije' # this is the program to test the func map and reduce # map( func, seq1[, seq2...] ) if __name__ == '__main__': print range(6) print [x % 3 for x in range(6)] print map(lambda x: x % 3, range(6)) a = [1, 2, 3] b = [4, 5, 6] zipped = zip(a, b) print zipped print zip(*zipped) print map(lambda x, y: x * y, [1, 2, 3], [4, 5, 6]) print map(lambda x, y, z: (x * y + z, x + y - z), [1, 2, 3], [4, 5, 6], [1, 2, 3]) # [(4, 5), (10, 7), (18, 9)] print map(None, [1, 2, 3], [4, 5, 6]) # [(1, 4), (2, 5), (3, 6)] print zip([1, 2, 3], [4, 5, 6]) # [(1, 4), (2, 5), (3, 6)] # reduce( func, seq[, init] ) n = 5 print reduce(lambda x, y: x * y, range(1, n + 1)) # 120 m = 2 n = 5 print reduce(lambda x, y: x * y, range(1, n + 1), m)