blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
97d5d6829a0395d0e1d5c442f74d4e0cfd5522da
fxw97/NCRE2python
/第6套/简单应用题/6-45demo.py
239
3.765625
4
# 判断是否为闰年 def judge_year(year): if (year%4==0 and year%100!=0) or (year%400 ==0): print(year,'年是闰年') else: print(year,'年不是闰年') year = eval(input('请输入年份:')) judge_year(year)
ff72bda9207df9a8a0508b65e12440dfc324672a
kylerlmy/pythonpractice
/src/examine/second/topic3.py
964
4.125
4
# 输入一个字符串,考虑字符串中字符所哟可能的排列组合;按字典打印出该字符串中字符的全排列 def str_replace(str, x, y): if x == y: return str x_val = str[x:x+1] y_val = str[y:y+1] if x < y: str = str[0:x] + y_val + str[x+1:y] + x_val + str[y+1:len(str)] else: str = str[0:y] + x_val + str[y+1:x] + y_val + str[x+1:len(str)] return str def str_sort(str, x): if x == len(str): # 当x为字符串的最大长度时返回当前字符交换的结果 global str_list str_list.append(str) return for i in range(x, len(str)): str = str_replace(str, i, x) # 递归遍历第i个字符, str_sort(str, x+1) str = str_replace(str, x, i) # 恢复字符串原来的顺序,便于下次遍历 inputstring = input('请输入结果,如:‘abc’:') global str_list str_list = [] str_sort(inputstring, 0) print(str_list)
dbdc4f4568077f91f53f275da8a1e65de279ad3c
yamendrasinganjude/200244525045_ybs
/day5/binarySearch.py
705
4.15625
4
''' 3. Write a Python program for Binary search. ''' def binarySearch(lst, searchElement): start = 0 end = len(lst) - 1 while start <= end: mid = (start + end) // 2 if lst[mid] == searchElement: position = mid return position else: if searchElement < lst[mid]: end = mid - 1 else: start = mid + 1 return -1 lst = [8, 7, 6, 5, 4, 3, 2, 1, 9] lst.sort() print("Searching List :", lst) searchElement = int(input("Enter a element to search : ")) a = binarySearch(lst, searchElement) if a == -1: print("Element Not in list...") else: print("Element Found at position %d." % (a))
8d51d118d817a763fff54479d9f331ce74b5e9d0
djmejiaamador/Cipher-Maker
/CypherMaker.py
10,151
3.796875
4
# Author: Douglas Mejia # CypherMaker # # produces encyrpted files using simple ciphers import sys import click import os def caeserCypher(key, file,output): ''' Classic Caeser Cipher Encryption Referenced from: Manual of Cryptography 1911: 28-29 A substitution cypher that shirts characters around by a certain number along the ASCII table ''' readingFrom = open(file,'r') message = readingFrom.read() readingFrom.close() writingTo = open(output,'w') for letter in message: if letter == "\n": writingTo.write(letter) else: writingTo.write(chr( (ord(letter) +key) % 256 )) writingTo.close() return; def decryptCaeser(key, encyrptedFile,output): ''' Classic Caeser Cipher Encryption Referenced from: Manual of Cryptography 1911: 28-29 A decrypts messages by rotating each characters by a certain key value along the ASCII table ''' readingFrom = open(encyrptedFile,'r') message = readingFrom.read() readingFrom.close() writingTo = open(output,'w') for letter in message: if letter == "\n": writingTo.write(letter) else: writingTo.write(chr( (ord(letter) - key) % 256)) writingTo.close() return; toLeet = { "a": "4", "e":"3", "i": "1", "o": "0", "v":"u", "s":"5", "t":"7", "n":"^","l":"|", "d": ")", "h": "#", "r":"2" } fromLeet = { "4": "a", "3":"e" ,"1":"i", "0":"o", "u":"v", "5":"s", "7": "t", "^":"n" , "|":"l" , ")":"d", "#" : "h" , "2" : "r" } def toLeetSpeak(file, output): """ substitution cipher: LeetSpeak Reads in given file and substitutes certain letters into leet speak. The letter to be changed are detailed in dictionaries defined below. toLeet = { "a": "4", "e":"3", "i": "1", "o": "0", "v":"u", "s":"5", "t":"7", "n":"^","l":"|", "d": ")", "h": "#", "r":"2" } fromLeet = { "4": "a", "3":"e" ,"1":"i", "0":"o", "u":"v", "5":"s", "7": "t", "^":"n" , "|":"l" , ")":"d", "#" : "h" , "2" : "r" } referenced from: Link: Gamehouse.com/blog/leet-speak-cheat-sheet/ """ readingFrom = open(file,'r') message = readingFrom.read() readingFrom.close() writingTo = open(output,'w') for letter in message: if toLeet.has_key(letter): writingTo.write(toLeet[letter]) else: writingTo.write(letter) writingTo.close() return; def fromLeetSpeak(file, output): """ substitution cipher: LeetSpeak Reads in given file and substitutes certain letters from leet speak. The letter to be changed are detailed in dictionaries defined below. toLeet = { "a": "4", "e":"3", "i": "1", "o": "0", "v":"u", "s":"5", "t":"7", "n":"^","l":"|", "d": ")", "h": "#", "r":"2" } fromLeet = { "4": "a", "3":"e" ,"1":"i", "0":"o", "u":"v", "5":"s", "7": "t", "^":"n" , "|":"l" , ")":"d", "#" : "h" , "2" : "r" } referenced from: Link: Gamehouse.com/blog/leet-speak-cheat-sheet/ """ readingFrom = open(file,'r') message = readingFrom.read() readingFrom.close() writingTo = open(output,'w') for letter in message: if fromLeet.has_key(letter): writingTo.write(fromLeet[letter]) else: writingTo.write(letter) writingTo.close() return; """Polyalphabetic Cipher key: dream The key wraps around the the messages and cross references the each letter against the a different alphabet referenced from: Elements of Cyptanalysis pg 34 - 40 class notes wikipedia link: https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher """ alphabet = "abcdefghijklmnopqrstuvwxyz" polykey = { "d" : "asdfghjklzxcvbnmqwertyuiop", "r" : "lkjhgfdsamnbvcxzpoiuytrewq", "e" : "qwertyuiopzxcvbnmasdfghjkl", "a" : "zaqwsxcderfvbgtyhnmjuiklop", "m" : "fvredcwsxqaztgbnhyujmkilpo" } def poly(key,file, output): """Polyalphabetic Cipher key: dream The key wraps around the the messages and cross references the each letter against the a different alphabet referenced from: Elements of Cyptanalysis pg 34 - 40 class notes wikipedia link: https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher """ readingFrom = open(file,'r') message = readingFrom.read() readingFrom.close() keyIndex = 0 writingTo = open(output,'w') for letter in message: if letter.isspace(): writingTo.write(" ") elif alphabet.find(letter) == -1: writingTo.write(letter) else: #convert letter to lowercase for simplicity letterholder = letter.lower() #to cross reference reg alphabet with cipher alphabets; index of letter in reg alphabet indexOfLetter = alphabet.find(letterholder) #to iterate over key (dream) and decide which alphabet to use keyValue = key[keyIndex] letterToAdd = polykey[keyValue][indexOfLetter] writingTo.write(letterToAdd) keyIndex = keyIndex +1 if(keyIndex > len(key)-1): keyIndex = 0 writingTo.close() return; def fromPoly(key, file, output): """Polyalphabetic Cipher key: dream The key wraps around the the messages and cross references the each letter against the a different alphabet referenced from: Elements of Cyptanalysis pg 34 - 40 class notes wikipedia link: https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher """ readingFrom = open(file,'r') message = readingFrom.read() readingFrom.close() keyIndex = 0 writingTo = open(output,'w') for letter in message: if letter.isspace(): writingTo.write(" ") elif alphabet.find(letter) == -1: writingTo.write(letter) else: #find the index of the letter in appropriate alphabet keyValue = key[keyIndex] #to cross reference reg alphabet with cipher alphabets; index of letter in cipher alphabet indexOfLetter = polykey[keyValue].find(letter) letterToAdd = alphabet[indexOfLetter] writingTo.write(letterToAdd) keyIndex = keyIndex +1 if(keyIndex > len(key)-1): keyIndex = 0 writingTo.close() return; def transpositionCipher(file, output): ''' Transpositon cipher: refrenced from: Manual of Crytography 49 - 55 https://www.youtube.com/watch?v=0um-_4SvPg0 ''' readingFrom = open(file,'r') message = readingFrom.read() readingFrom.close() shiftedMessage= "" for i in range( 0, len(message)): shiftAmount = (len(message)-i ) % len(message)-1 shiftedMessage = shiftedMessage + message[shiftAmount] writeTo = open(output,'w') writeTo.write(shiftedMessage) writeTo.close() return; def decrypt_transposition(file,output): ''' Transpositon cipher: refrenced from: Manual of Crytography 49 - 55 https://www.youtube.com/watch?v=0um-_4SvPg0 ''' readingFrom = open(file,'r') message = readingFrom.read() readingFrom.close() shiftedMessage= "" writeTo = open(output,'w') for i in range(len(message),0,-1): shiftAmount = (i+len(message)) % len(message)-1 shiftedMessage = message[shiftAmount] writeTo.write(shiftedMessage) writeTo.close() return; def find_Frequecy(file): ''' Function that prints the Frequency of the message's letter, bigrams, and trigrams ''' Frequecy ={} readingFrom = open(file,'r') message = readingFrom.read() readingFrom.close() shiftedMessage= "" for i, letter in enumerate(message): #check to see if the single letter exist if " " in letter or "" in letter or '\n' in letter or '\n' in letter: pass elif letter in Frequecy: Frequecy[letter] = Frequecy[letter] + 1 else: Frequecy.update({letter:1}) bigramIndex = i+1 if(bigramIndex > len(message)): continue bigram = message[i:bigramIndex+1] if " " in bigram or '\n' in bigram or " " and '\n' in bigram: pass elif bigram in Frequecy: Frequecy[bigram] = Frequecy[bigram] + 1 else: Frequecy.update({bigram:1}) trigramIndex = i+2 if(trigramIndex >len(message)): continue trigram = message[i:trigramIndex+1] if " " in trigram or '\n' in trigram or " " and '\n' in trigram: pass elif trigram in Frequecy: Frequecy[trigram] = Frequecy[trigram] + 1 else: Frequecy.update({trigram:1}) #combinations for key in sorted(Frequecy.iterkeys()): print "{%s : %s}" % (key, Frequecy[key]) return; @click.group() @click.option("--cypher", help = "produces an encrypted file from given text file ") def cli(cypher): """ Action: encrypt to encrypt a given file using a certain encryption algorithm (see Type of Encryption) decrypt to encrypt a given file using a certain encryption algorithm (see Type of Encryption) Type of Encryption: c for caeserCipher\n l for leetSpeak\n p for polyalphabetic\n t for transpositon Input file Outputfile """ pass @cli.command() @click.argument('type_of_encryption', type = click.STRING) @click.argument('input_file', type = click.STRING) @click.argument('output', type = click.STRING) def encrypt(type_of_encryption,input_file,output): print(type_of_encryption) if ( type_of_encryption not in ["c","l","p","t"]): print("invalid input: see --help") elif os.path.isfile(input_file) == False: print("cant find that file") else: if( type_of_encryption == "c"): print("c") caeserCypher(2, input_file,output) elif(type_of_encryption == "l"): toLeetSpeak(input_file,output) elif type_of_encryption == "p": poly("dream", input_file,output) elif( type_of_encryption == "t"): print("transpo") transpositionCipher(input_file,output) @cli.command() @click.argument('type_of_decryption', type = click.STRING) @click.argument('file_to_decrypt', type = click.STRING) @click.argument('output', type = click.STRING) def decrypt(type_of_decryption,file_to_decrypt,output): if ( type_of_decryption not in ["c","l","p","t"]): print("invalid input: see --help") elif os.path.isfile(file_to_decrypt) == False: print("cant find that file") else: if(type_of_decryption == "c"): print("about to call decryptCaeser") decryptCaeser(2, file_to_decrypt,output) elif(type_of_decryption == "l"): fromLeetSpeak(file_to_decrypt,output) elif( type_of_decryption == "p"): fromPoly("dream", file_to_decrypt,output) elif( type_of_decryption == "t"): print("transpo") decrypt_transposition(file_to_decrypt,output) @cli.command() @click.argument('file_to_freq', type = click.STRING) def Freq(file_to_freq): if os.path.isfile(file_to_freq) == False: print("cant find that file") else: find_Frequecy(file_to_freq) if __name__ == '__main__': cli()
454bf21ca73d84f08dc96817408fac6dd037814c
rachelPark1/python-files
/Python/Python_Q4/count_duplicate_letter.py
1,180
3.921875
4
def count_duplicates(strAlpha): # This function takes in strAlpha which is made of lowercase alphabets and #numberic digits. #1) Cast the strAlpha into a new list and assign it listAlpha = list(strAlpha) # e.g. listAlpha is ['a', 'a', 'b', 'b'] #2) Make a new empty list that can be appended when any characters are #reapeated dupChar = [] #3) Loop until the iNum is the last index of the listAlpha for iNum in range(len(listAlpha)): # iNum is 0, 1, 2, 3 #print("iNum: " + str(iNum)) newListAlpha = listAlpha[0 : iNum] + listAlpha[(iNum + 1) : (len(listAlpha) + 1)] #print("newListAlpha: " + str(newListAlpha)) if listAlpha[iNum] in newListAlpha: # As long as there is the same character as the listAlpha[iNum] #remove listAlpha[iNum] from the listAlpha if not (listAlpha[iNum] in dupChar): dupChar.append(listAlpha[iNum]) #print("dupChar: " + str(dupChar)) newListAlpha.remove(listAlpha[iNum]) #print("dupChar: " + str(dupChar) + "\n") return len(dupChar) p = count_duplicates("investigate") print(p)
b97d22cce94fbaab5f6da11a8e7a11fa8756eaed
JayS420/Python-For-All
/2. Object Oriented Programming/4. Overloading method.py
1,177
4
4
class point(): def __init__(self, x=0, y=0): self.x = x self.y = y self.coords = (self.x, self.y) def move(self, x, y): self.x += x self.y += y def __add__(self, p): return point(self.x + p.x, self.y + p.y) def __sub__(self, p): return point(self.x - p.x, self.y - p.x) def __mul__(self, p): return self.x * p.x + self.y *p.y def length(self): import math return math.sqrt(self.x**2 + self.y**2) def __gt__(self, p): return self.length() > p.length() def __ge__(self, p): return self.length() >= p.length() def __lt__(self, p): return self.length() < p.length() def __le__(self, p): return self.length() <= p.length() def __eq__(self, p): return self.x == p.x and self.y == p.y def __str__(self): return "(" +str(self.x) + ',' + str(self.y) + ')' p1 = point(3,4) p2 = point(3,2) p3 = point(1,3) p4 = point(0,1) p5 = p1 + p2 p6 = p4 - p1 p7 = p2 * p3 print(p5, p6, p7) print(p1 == p2) print(p1 > p2) print(p4 <= p2)
b6bfd5541bc995fd5c0a7e8aaedcf99ba527c008
Aravind644/python-
/ABSTRACT CLASS.py
1,396
4.53125
5
# python9 ABSTRACT CLASS 1.Create an abstract class with abstract and non-abstract methods * Python comes with a module called abc which provides useful stuff for abstract class. We can define a class as an abstract class by abc.ABC and define a method as an abstract method by abc.abstractmethod. ABC is the abbreviation of abstract base class. from abc import ABC, abstractmethod class Animal(): @abstractmethod def move(self): pass a = Animal() 2.Create a sub class for an abstract class.Create an object in the child class for the abstract class and access the non-abstract methods * By subclassing directly from the base, we can avoid the need to register the class explicitly. In this case, the Python class management is used to recognize PluginImplementation as implementing the abstract PluginBase. import abc class parent: def geeks(self): pass class child(parent): def geeks(self): print("child class") print( issubclass(child, parent)) print( isinstance(child(), parent)) 3.Create an instance for the child class in child class and call abstract methods import abc class parent: def geeks(self): pass class child(parent): def geeks(self): print("child class") print( issubclass(child, parent)) print( isinstance(child(), parent))
7bc9bdb20e2031ad8e9919a99e765233569f696c
ngthnam/Python
/Python Basics/29_Regular_Expressions.py
1,646
4.15625
4
''' Identifiers ----------------- \d any number \D anything but number \s space \S anything but a space \w any char \W anything but char . any char, except new line \b the white space around words \. a period \\ literal backslash Modifiers ----------------- {1,3} we're expecting 1-3 + match 1 or more ? match 0 or 1 * match 0 or more $ match end of the string ^ match begining of a string | either or [] range or "variance" [1-5a-zA-O] {x} expecting "x" amount White space chars ----------------- \n new line \s space \t tab \e escape \f form feed \r return ESCAPE THEM ----------------- . + * ? [ ] $ ^ ( ) { } | \ ''' import re stringdata = ''' Prateek is 27 years old, and Mayank is 25 years old Utkarsh is 22, and their father, Rakesh is 60 year old ''' # .findall() function to get all the data ages = re.findall(r'\d{1,3}',stringdata) names = re.findall(r'[A-Z][a-z]*', stringdata) print('Ages:',ages) print('Names:', names) words = re.split(r'\s',stringdata) #.split(pattern, string) to slplit th 'string' by the 'pattern' print('Filter:',filter(lambda x: len(x)>0, words)) print('All words:',words) threeletterwords=[] # empty list for each in words: match = re.search(r'^(\w{3})$', each) # search for 3 letter words if match: threeletterwords.append(match.group(0)) # adding items that are 3 lettered to the list print('Three letter words:',threeletterwords) dictionary = {} i=0 for item in names: dictionary[item] = ages[i] i+=1 print('Name-Age dictionary:',dictionary) search = re.search(r'\d{1,2}',stringdata) print('position:', search.span()) # to find the posiyion of match
9f4a0d4c84446346ec2abfe527aec589cf1f6348
Ashish-012/Competitive-Coding
/linkedlist/insertHead.py
527
4.03125
4
''' Check if the list is empty, if it is just point the head to the new node created and return the head. Otherwise create a node `current` pointing to the head node. Now point the head node to the newly created node with the data and in the end point the next of the newly created node to the `current`. ''' def insertNodeAtHead(head, data): node = SinglyLinkedListNode(data) if not head: head = node return head current = head head = node node.next = current return head
d6cebc5811182d106c4a6391bd6fc1cc75003db3
Luksos9/LearningThroughDoing
/automateboringstuff/PatternMatchingWIthRegularExpressions/checkIfPhoneNumber.py
852
4.34375
4
# Program check if the telephone number is correct # It assumes that the phone number is made of 9 digits separated by dash "-" """using Regex module is much more efficient in this type of programs""" def isPhoneNumber(text): if len(text) != 11: return False for i in range(0, 3): if not text[i].isdecimal(): return False if text[3] != "-": return False for i in range(4,7): if not text[i].isdecimal(): return False if text[7] != "-": return False for i in range(8,11): if not text[i].isdecimal(): return False return True userNumber = input("Enter your phone number (e.g 444-444-444)\n") if isPhoneNumber(userNumber): print("Your number:", userNumber, "is a phone number") else: print("Your number isn't a phone number")
57340fe01073e3370c2168d073a3e31966202d92
RahulTechTutorials/PythonPrograms
/Lists/ListFilterReduce.py
579
4.40625
4
import functools def main(): '''This is a program to understand the functionality of Reduce and Lamba functions on List''' lst = [1,2,3,4,5,6,7,8,9,10] print ('The list is : ',lst ) cubelst = list(map(lambda x : x ** 3,lst)) print('The cube operation on lst is : ',cubelst) evencubelst = list(filter (lambda x : x%2 == 0 , cubelst)) print('The even cube lst is : ', evencubelst) sumcubeevenlst = functools.reduce(lambda x,y : x + y, evencubelst) print('The sum of the evencubelst is: ', sumcubeevenlst) if __name__ == '__main__': main()
bef034fd660213aa15870ddc47618b168391e014
harrywenhr/ShuaTi
/Array/sortColors.py
2,386
4.03125
4
# # Given an array with n objects colored red, white or blue, #sort them in-place so that objects of the same color are adjacent, #with the colors in the order red, white and blue. # Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. # Note: You are not suppose to use the library's sort function for this problem. # Just like the Lomuto partition algorithm usually used in quick sort. # We keep a loop invariant that [0,i) [i, j) [j, k) are 0s, 1s and 2s # sorted in place for [0,k). # Here ")" means exclusive. We don't need to swap because we know the values we want. class Solution: def sortColors(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ i = j = 0 for k in range(len(nums)): #get current value v = nums[k] nums[k] = 2 if v < 2: nums[j] = 1 j += 1 if v == 0: nums[i] = 0 i += 1 # Proof: Initialization: i=j=k=0. [0,0) [0,0) [0,0) don't exist [k=0,len(nums)-1] undetermined # [0,i) [i, j) [j, k) are 0s, 1s and 2s # Maintenance: Case 1:encounter 2, [0,i) [i,j) don't change [j,k)->[j,k+1) # Case 2: encounter 0, [0, i)-> [0,i+1), [i,j)->[i+1,j+1), [j, k)->[j+1,k+1) # Case 3: encounter 1: [0,i) doesn't change, [i,j)->[i,j+1), [j,k)->[j+1, k+1) # Termination: The same as "Maintenance" [0,0,0,1,1,1,2,2,2] next one is 0 we bump 0s to 0000 bump 1s to 1111 then bump 2s to 2222 i = j = 0 for k in range(len(nums)): v = nums[k] if v == 0: #we need to bump the areas of 1s and 2s #we set current k to 2 first, the set current j = 1 #then set current i to 0, #expanding the areas one by one from the end #previous positions will be over write as the 1s and 2s #area expand nums[k] = 2 nums[j] = 1 nums[i] = 0 i += 1 j += 1 elif v == 1: #we only need to bump area 1 and 2 nums[k] = 2 nums[j] = 1 j += 1 else: #only need to bump area 2 nums[k] = 2 #practiced
c32f7d2acadc139cf16e3510185bf7bf14f81943
NeilPolitum/Ejercicios-Modelos
/ciclos_32_pregunta.py
71
3.5625
4
l = "" while l=!n or l=!N: l = str(input("¿Desea continuar?"))
164740ca6bc3c0849174fa8d495fae1aa9cdec53
kareem20-meet/Meetyl1201819
/lab4.py
905
3.875
4
class Animal(object): def __init__(self,sound,name,age,favorite_color): self.sound = sound self.name = name self.age = age self.favorite_color = favorite_color def eat(self,food): print("Yummy!! " + self.name + " is eating " + food) def description(self): print(self.name + " is " + self.age + " years old and loves the color " + self.favorite_color) def make_sound(self): print(self.name + " says " + self.sound) cat = Animal("Meow!" , "Max", "3" ,"blue") cat.description() cat.make_sound() cat.eat("fish") class Person(object): def __init__(self,name,gender,color_eye): self.name = name self.gender = gender self.color_eye = color_eye def breakfast(self): print(self.name + " eat his favorite breakfast everyday! ") def sports(self): print(self.name + " loves to play his favorite sport,football") person =Person("Ali", "male", "blue") person.breakfast() person.sports()
2574146d4442c05fc775e90801b7c3f36ead1085
z47288/selfteaching-python-camp
/exercises/1901100351/1001S02E06_stats_word.py
2,778
3.78125
4
text = ''' the Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! ''' import re def stats_text_en(text): #定义函数 ''' 这是一个统计英文词频并按出现次数降序排列的函数 ''' text_1 = re.sub('\W',' ',text) #不是字符的,都转换为空格,主要去除标点符号 text_1 = text_1.lower() #转换为小写 textlist_1 = text_1.split() #将段落转换为列表 dict1 = {} #定义字典 for i in textlist_1: num= textlist_1.count(i)#统计词频 r1 = {i:num}#定义元组 dict1.update(r1)#更新词典 dict2=sorted(dict1.items(),key = lambda dict_items:dict_items[1], reverse=True)#排序 return(dict2) print(stats_text_en(text)) def stats_text_cn(text_cn):#设定函数 ''' 这是一个统计中文汉字字频并按出现次数降序排列的函数 ''' word_dict = {} #定义一个空字典,作为结果容器 cn_list = list(text_cn) #将文本直接拆分为列表 for s in cn_list: #统计中文汉字个数,并将结果返回word_dict中 if '\u4e00'<= s <= '\u9fff':#中文字符的代码区间 count=cn_list.count(s)#统计字符出现次数 r1={s:count}#定义字典中的元组 word_dict.update(r1)#更新列表 word_sorted = sorted(word_dict.items(), key=lambda items:items[1],reverse=True) #按字频降序排列输出结果 return word_sorted text_cn = ''' 人类历史纷繁芜杂,到底什么才是最重要、最核心的推力? 是精英,还是民众?是制度,还是技术?是欲望,还是道德? 很多时候,似乎是精英主导社会,但也有许多时候,民众的力量也能摧枯拉朽; 很多时候,似乎是制度塑造社会,但也有许多时候,技术的进步会带来制度的重构; 很多时候,似乎是人们的欲望推动着社会,但也有许多时候,道德的力量也能重振河山。 ''' print(stats_text_cn(text_cn))
d348dfe5002369edd3928a628685ff29173668e6
diamondnorthpole/tower-of-hanoi
/Tower.py
6,086
3.859375
4
# ----------------------------------------# # Michael Roudnitski # Tower of Hanoi # March 3, 2017 # ----------------------------------------# import time import pygame pygame.init() HEIGHT = 600 WIDTH = 1400 ground = 600 screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.RESIZABLE) #---------------------------------------------------------------------------------------------------# RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) WHITE = (255, 255, 255) BLACK = (0, 0, 0) disks = input("Enter the number of disks you would like in your tower... ") steps = 0 source = [] temp = [] dest = [] complete = False numDisks = disks #---------------------------------------------------------------------------------------------------# for i in range(disks): # appends values into source list depending on how many disks the user chose source.append(numDisks) numDisks -= 1 #---------------------------------------------------------------------------------------------------# def AB(): """ Makes a legal move between source and temp if source is not empty and then temp is empty or last value of source < last value of temp Pops last item in source and appends it to temp or if temp is not empty and then source is empty or last value of temp < last value of source Pops last item in temp and appends it to source """ if len(source) > 0 and (len(temp) == 0 or source[-1] < temp[-1]): temp.append(source.pop()) elif len(temp) > 0 and (len(source) == 0 or temp[-1] < source[-1]): source.append(temp.pop()) #---------------------------------------------------------------------------------------------------# def AC(): """ Makes a legal move between source and destination if source is not empty and then dest is empty or last value of source < last value of dest Pops last item in source and appends it to dest or if dest is not empty and then source is empty or last value of dest < last value of source Pops last item in dest and appends it to source """ if len(source) > 0 and (len(dest) == 0 or source[-1] < dest[-1]): dest.append(source.pop()) elif len(dest) > 0 and (len(source) == 0 or dest[-1] < source[-1]): source.append(dest.pop()) #---------------------------------------------------------------------------------------------------# def BC(): """ Makes a legal move between temp and destination if source is not empty and then dest is empty or last value of temp < last value of dest Pops last item in source and appends it to dest or if dest is not empty and then temp is empty or last value of dest < last value of temp Pops last item in dest and appends it to temp """ if len(temp) > 0 and (len(dest) == 0 or temp[-1] < dest[-1]): dest.append(temp.pop()) elif len(dest) > 0 and (len(temp) == 0 or dest[-1] < temp[-1]): temp.append(dest.pop()) #---------------------------------------------------------------------------------------------------# def write(): """ Prints the value of the three lists (source, temp, dest) >>> write() source [5,4,3,2] temp [1] dest [] """ print "source ", source print "temp ", temp print "dest ", dest print " " #---------------------------------------------------------------------------------------------------# def is_done(): """ Checks if the destination list is full (all values are stored in dest list) if it returns true, it breaks the loop source = [] temp = [] dest = [5,4,3,2,1] >>> is_done() All done! dest [5,4,3,2,1] """ if len(dest) != disks: pass else: print "All done! " print "That only took ", steps, " steps" print "dest ", dest return True #---------------------------------------------------------------------------------------------------# def redraw_screen(): pygame.event.clear() screen.fill(WHITE) #pegs pygame.draw.rect(screen, BLACK, ((WIDTH / 4) - 5, 200, 10, 380)) pygame.draw.rect(screen, BLACK, ((WIDTH / 2) - 5, 200, 10, 380)) pygame.draw.rect(screen, BLACK, (WIDTH - (WIDTH / 4) - 5, 200, 10, 380)) # disks for i, val in enumerate(source): pygame.draw.rect(screen, RED, ((WIDTH / 4) - (val * 10), ground - (20 * i) - 40, (val * 10) * 2, 20)) for i, val in enumerate(temp): pygame.draw.rect(screen, RED, ((WIDTH / 2) - (val * 10), ground - (20 * i) - 40, (val * 10) * 2, 20)) for i, val in enumerate(dest): pygame.draw.rect(screen, RED, (WIDTH - (WIDTH / 4) - (val * 10), ground - (20 * i) - 40, (val * 10) * 2, 20)) pygame.display.update() #time.sleep(0.1) #---------------------------------------------------------------------------------------------------# redraw_screen() if disks % 2 == 0: #check if number of disks are even or odd while complete is False: AB() # make the legal move steps += 1 #increase step counter write() # write current state of lists to console redraw_screen() # draw everything if is_done(): # break the loop if we're done break AC() steps += 1 write() redraw_screen() if is_done(): break BC() steps += 1 write() redraw_screen() if is_done(): break else: while complete is False: AC() steps += 1 write() redraw_screen() if is_done(): break AB() steps += 1 write() redraw_screen() if is_done(): break BC() steps += 1 write() redraw_screen() if is_done(): break
f8d8ca4d8150f7ab741ccd2c2d8fc50d21b36d74
196884/Python
/PE/pe0304.py
2,067
3.5
4
def powMod(a, b, m): a2k = a # a^(2^k) result = 1 while b > 0: if b % 2 == 1: result = (result * a2k) % m a2k = (a2k * a2k) % m b /= 2 return result def multModMat2(l1, l2, m): r = [[0, 0], [0, 0]] r[0][0] = (l1[0][0] * l2[0][0] + l1[0][1] * l2[1][0]) % m r[0][1] = (l1[0][0] * l2[0][1] + l1[0][1] * l2[1][1]) % m r[1][0] = (l1[1][0] * l2[0][0] + l1[1][1] * l2[1][0]) % m r[1][1] = (l1[1][0] * l2[0][1] + l1[1][1] * l2[1][1]) % m return r def powModMat2(l, n, m): # l is supposed to be a 2x2 matrix, computes l^n mod m l2k = l result = [[1, 0], [0, 1]] while n > 0: if n % 2 == 1: result = multModMat2(result, l2k, m) l2k = multModMat2(l2k, l2k, m) n /= 2 return result def iSqrt(n): """ Integral square root (by Newton iterations) """ x = 1 xOld = 1 while True: aux = ( x + ( n / x ) ) / 2 if aux == x: return x if aux == xOld: return min(x, xOld) xOld = x x = aux def getPrimes(B): primes = [] isPrime = [True for n in range(0, B+1)] for n in range(2, B+1): if isPrime[n]: p = n primes.append(p) pk = 2 * p while pk <= B: isPrime[pk] = False pk += p return primes def isPrime(n, primes): for p in primes: if n % p == 0: return n == p return True def fib(n, x): m = [[0, 1], [1, 1]] m = powModMat2(m, n, x) return m[1][0] def solve(): # Really slow in Python. Could speed up the sieving, but enough for now B = 10 ** 7 + 10 ** 4 primes = getPrimes(B) n = 10 ** 14 m = 1234567891011 r = 0 k = 0 while True: n += 1 if isPrime(n, primes): r += fib(n, m) k += 1 print k if k == 10 ** 5: return r % m if __name__ == "__main__": result = solve() print "Result: %d" % result
1398bf257910bbdcdfc6cb611da952b6e32dd283
pflun/advancedAlgorithms
/canPermutePalindrome.py
450
3.640625
4
# -*- coding: utf-8 -*- # 成对出现,至多可能中间有奇数个 class Solution(object): def canPermutePalindrome(self, s): dic = {} for char in s: dic[char] = dic.get(char, 0) + 1 for key, val in dic.items(): if val % 2 == 0: dic.pop(key) if len(dic) <= 1: return True return False test = Solution() print test.canPermutePalindrome("carerac")
83ea29370c4f4cd2f5c46e7ccf72193a2fae726a
jorabeknazarmatov/Python-dars
/14-dars.py
571
3.75
4
from random import * #son top o'yini a=randint(1,10) n=int(input('Son kiriting: ')) def top(x,y): res=[] while y==x: print(f'Tabriklaymiz siz biz o`ylagan sonni {len(res)} urunishda topdingiz') top() if y>x: print(f'{n} biz o`ylagan sondan katta.') res.append(y) n=int(input('Son kiriting: ')) top(x,n) else: print(f'{n} biz o`ylagan sondan kichik.') res.append(y) n=int(input('Son kiriting: ')) top(x,n) top(a,n) ''' 1.randint() 2.n=son kiriting 3.n a ga tekshiruv 4. '''
c4a35b1184ddc9951b0bf9e8a1ceeaccd2c708a0
Chongkai-Ma/Fundamentals-of-Python-Data-Structures
/Array/LinkedInstead.py
345
3.546875
4
#!/usr/bin/python3 from node import Node head = None for count in range(1, 10): head = Node(count, head) probe = head targetItem = 5 while probe != None and targetItem != probe.data: probe = probe.next if probe != None: probe.data = 88888 print ("The item has been changed") else: print ("The item has not been found")
85bf4c80295dcaf5f890571d71bd9387b4e7999f
jakemuncada/hexalink-solver
/point.py
1,048
4.375
4
"""Point Class""" from math import sqrt class Point: """A coordinate point class.""" def __init__(self, pt=(0, 0)): self.x = float(pt[0]) self.y = float(pt[1]) def __add__(self, other): return Point((self.x + other.x, self.y + other.y)) def __sub__(self, other): return Point((self.x - other.x, self.y - other.y)) def __mul__(self, scalar): return Point((self.x*scalar, self.y*scalar)) def __div__(self, scalar): return Point((self.x/scalar, self.y/scalar)) def __len__(self): return int(sqrt(self.x**2 + self.y**2)) def __str__(self): return "{:.2f}, {:.2f}".format(self.x, self.y) def dist(self, other): """Get distance to another point.""" xSquared = (self.x - other.x) * (self.x - other.x) ySquared = (self.y - other.y) * (self.y - other.y) return sqrt(xSquared + ySquared) def get(self): """Returns the x and y coordinate as a tuple of ints.""" return (int(self.x), int(self.y))
df4c44161f5d34ba3405c5a9bc42cdf2dff42b2e
thesmigol/python
/1050.py
561
3.859375
4
entrada = None def read_integer(): try: # read for Python 2.x return int(raw_input()) except NameError: # read for Python 3.x return int(input()) entrada = read_integer() if entrada == 61: print("Brasilia") elif entrada == 71: print("Salvador") elif entrada == 11: print("Sao Paulo") elif entrada == 21: print("Rio de Janeiro") elif entrada == 32: print("Juiz de Fora") elif entrada == 19: print("Campinas") elif entrada == 27: print("Vitoria") elif entrada == 31: print("Belo Horizonte") else: print("DDD nao cadastrado")
9020886a307f342530e0294856a9507d793c3fc6
amulmgr/practicepython
/ex34_birthdayjson.py
535
3.796875
4
# -*- coding: utf-8 -*- """ Created on Tue Mar 5 15:21:25 2019 @author: Anuj Saboo """ def add(): print("This is a prompt to add more user") name=input("Enter the name") dob=input("Enter birthday") read[name]=dob with open('info.json','w') as f: json.dump(read,f) with open('info.json','r') as f: write=json.load(f) print("Updated Dictionary is {}".format(write)) import json with open('info.json','r') as f: read=json.load(f) add()
3c69328fb00fad85cf4d20e548dc4d96133966d5
vineettanna/Algorithms-Stanford
/Part 2/Week 1/shortest_path_length.py
804
3.734375
4
from queue import Queue def bfs_shortest_path_length(graph,s,e): q = Queue() q.put(s) dist = {} if s == e: return 0 dist[s] = 0 while not q.empty(): curr = q.get() for i in graph[curr]: if i not in dist.keys(): q.put(i) dist[i] = dist[curr] + 1 if i == e: return dist[i] return -1 # graph = { # 's':['a','b'], # 'a':['s','c'], # 'b':['s','c','d'], # 'c':['a','e','b','d'], # 'd':['b','c','e'], # 'e':['c','d'] # } #print (bfs_shortest_path_length(graph,'s','e')) graph = { 1:[3,5], 3:[1,5], 5:[1,3,7,9], 7:[5], 9:[5], 2:[4], 4:[2], 6:[8,10], 8:[6,10], 10:[6,8] } print (bfs_shortest_path_length(graph,1,10))
633c54a2b2e13a5340ec91d68ae1001a388f879f
Aasthaengg/IBMdataset
/Python_codes/p03729/s322640559.py
102
3.640625
4
num = input().split() print('YES') if num[0][-1]==num[1][0] and num[1][-1]==num[2][0] else print('NO')
041277c272432e52da827d07443a8060692855e3
blakepoon/python_learning
/plot/rw_visual.py
477
3.625
4
import matplotlib.pyplot as plt from random_walk import RandomWalk """ while True: """ rw = RandomWalk(50000) rw.fill_walk() point_numbers = list(range(rw.num_points)) plt.plot(rw.x_value, rw.y_value, linewidth=1) plt.scatter(0, 0, s=10, c='green') plt.scatter(rw.x_value[-1], rw.y_value[-1], c='red', s=10) plt.axes().get_xaxis().set_visible(False) plt.axes().get_yaxis().set_visible(False) plt.show() """ kn = input('Make another walk? (y/n)') if kn == 'n': break """
0afedca9c5726a53d55155c6f4aa4ca2716bfb6b
123zrf123/python-
/practice_4.py
271
4.125
4
def hanoi(x,A,B,C): if x == 1: print('%r-->%r' %(A,C)) if x == 2: print('%r-->%r %r-->%r %r-->%r' %(A,B,A,C,B,C)) if x > 2: return hanoi(x-1,A,C,B),hanoi(1,A,B,C),hanoi(x-1,B,A,C) x = int(input('hanoi的起始个数:')) A = 1 B = 2 C = 3 hanoi(x,A,B,C)
aa31b135fe125bd3835f5311139d80d9de1272e3
bhaumiksony1995/Python
/Lists.py
4,237
4.71875
5
# Can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type. squares = [1, 4, 9, 16, 25] print ("squares[1, 4, 9, 16, 25]") print (squares) print('') #Like strings (and all other built-in sequence type), lists can be indexed and sliced: print ("squares[0]") print (squares[0]) # indexing returns the item print('') print("squares[-1]") print(squares[-1]) print('') print("squares[-3:]") # slicing returns a new list print(squares[-3:]) print('') print("squares[:]") # All slice operations return a new list containing the requested elements. The following slice returns a new (shallow) copy of the list print(squares[:]) print('') # Lists also support operations like concatenation: print("squares + [36, 49, 64, 81, 100]") print(squares + [36, 49, 64, 81, 100]) print('') # Unlike strings, which are immutable, lists are a mutable type, i.e. it is possible to change their content: cubes = [1, 8, 27, 65, 125] print("cubes = [1, 8, 27, 65, 125]") #the cube of 4 is 64 not 65, lets change that print (cubes) cubes[3] = 64 print("cubes[3] = 64") print(cubes) #The cube of 4 is now 64 not 65 print('') # You can also add new items at the end of the list, by using the append() cubes.append(216) # add the cube of 6 cubes.append(7 ** 3) # and the cube of 7 print("cubes.append(216)") print("cubes.append(7 ** 3)") print(cubes) print('') # Assignment to slices is also possible, and this can even change the size of the list or clear it entirely: letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print("letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']") letters[2:5] = ['C', 'D', 'E'] # replace some values print("letters[2:5] = ['C', 'D', 'E']") print(letters) letters[2:5] = [] # now remove them print("letters[2:5] = []") print(letters) letters[:] = [] # clear the list by replacing all the elements with an empty list print("letters[:] = []") print(letters) print('') alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] print("len(alphabet)") print(len(alphabet)) print('') # It is possible to nest lists (create lists containing other lists) a = ['a', 'b', 'c'] n = [1, 2, 3] x = [a, n] print("a = ['a', 'b', 'c']") print("n = [1, 2, 3]") print("x = [a, n]") print(x) print("x[0]") print(x[0]) print("x[0][1]") print(x[0][1]) print('') #All the methods for list #list.append(x) # Add an item to the end of the list #list.extend(iterable) # Extend the list by appending all the items from the iterable #list.insert(x) # Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the # front of the list, and a.insert(len(a), x) is equivalent to a.append(x). #list.remove(x) # Remove the first item from the list whose value is equal to x. It is an error if there is no such item. #list.pop([i]) # Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the # list. (The square brackets around the i in the method signature denote that the parameter is optional #list.clear() # Remove all items from the list #list.index(x[,start[, end]]) # Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item. #list.count(x) # Return the number of times x appears in the list. #list.sort(key=None, reverse=False) # Sort the items of the list in place #list.reverse() # Reverse the elements of the list in place. #list.copy() # Return a shallow copy of the list ###Examples of most of the list methods fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana'] print(fruits) print("apple ", fruits.count('apple')) print("tangerine ", fruits.count('tangerine')) print("banana ", fruits.index('banana')) print("next banana ", fruits.index('banana', 4)) # Find next banana starting a position 4 print(fruits.reverse()) fruits.append('grape') print(fruits) fruits.sort() print(fruits) fruits.pop() print(fruits) print('') a = [-1, 1, 66.25, 333, 333, 1234.5] print(a) del(a[0]) print("del a[0] ", a) del(a[2:4]) print("del a[2:4] ", a) del(a[:]) print("del(a[:]) ", a)
f0521b9d22d4060f747b62d102ef3ec98db35786
shahrajesh2006/RainingRobots
/Rajesh/Challenge8Bonus/Challenge8Bonus.py
3,528
3.828125
4
import random import os import time from player import Player # Using readlines() file1 = open('Rajesh/bestscore.txt', 'r') Lines = file1.readlines() # this list of all the lines from the file # Strips the newline character for line in Lines: print(line.strip()) #Before we start the game lest load the existing player scores in a list # Using readlines() file2 = open('Rajesh/players.txt', 'r') players_file = file2.readlines() # list of all lines from the file #Line 1-2 are the random number and operating system module numberofpeopleplaying = input("How many people are playing? The max is 10 players.") time.sleep(1) os.system("clear") #Here is the object with three arguments more comments #more comments please players = [] peopleplayingvalue = 0 while peopleplayingvalue < int(numberofpeopleplaying): playersname = input("Player" + str(peopleplayingvalue + 1) + " what is your name or nickname") # Now see if this player is new player or existing player existing_player="n" # assume he is not existing player for n in range(len(players_file)): # Step 1 loop through the lines y=players_file[n].split("=") # Step 2 split the line #print("splitting Name"+y[0]) if y[0]==playersname:# if name is in the file then existing player print("Welcome back "+y[0]+"your previous score was" + y[1]) existing_player="y" # If its a new player print different message if existing_player=="n": print("Welcome new player "+playersname) NewPerson = Player(playersname, random.randrange(1,101), 0) players.append(NewPerson) print ("New player created..."+players[peopleplayingvalue].name) peopleplayingvalue=peopleplayingvalue+1 # players.append(NewPerson) # peopleplayingvalue = peopleplayingvalue + 1 time.sleep(1) os.system("clear") peopleplayingvalue = 0 while peopleplayingvalue < int(numberofpeopleplaying): players[peopleplayingvalue].PlayGame() print ("after game") peopleplayingvalue = peopleplayingvalue + 1 #This ask player 2 if they are ready print("Are") time.sleep(1) print("you") time.sleep(1) print("ready") time.sleep(1) print("to see") time.sleep(1) print("who") time.sleep(1) print("won?") ready = input("Print y to continue") if ready.lower().strip() =="y": print("Then lets... see... who... wonnnnnnnnn!") time.sleep(1) os.system ("clear") #Clears screen WinningPlayer = players[0]# For now assume first player won print("For now the winning player is "+WinningPlayer.name) print(WinningPlayer) peopleplayingvalue = 0 while peopleplayingvalue < int (numberofpeopleplaying): time.sleep(1) print("looping for the player"+players[peopleplayingvalue].name) if players[peopleplayingvalue].attempts < WinningPlayer.attempts: WinningPlayer = players[peopleplayingvalue]#found a better player so switch print("Found the new winning player is "+WinningPlayer.name) else: print("Winning player is still the same "+WinningPlayer.name) peopleplayingvalue = peopleplayingvalue + 1 #With the above logic if there is tie then the first player will be the winner print("The winner is" + WinningPlayer.name) file1 = open('Rajesh/bestscore.txt', 'w') file1.writelines("Winner of the last game:"+ WinningPlayer.name+"\n") file1.writelines("Best Score for the last game:"+ str(WinningPlayer.attempts)+"\n") file1.close() #Now lets write the players.txt file2 = open('Rajesh/players.txt', 'w') for n in range(int(numberofpeopleplaying)): file2.writelines(players[n].name+"="+str(players[n].attempts)+"\n") file2.close()
4169c5e5e7356705b49dcad124e8eaa4313dadc8
AnandaMontoly/haunted-smith
/spookysmithsav2.py
26,717
3.859375
4
from graphics import * import time import random import pygame stories = [] class Story: "This an object which organizes all of the narratives that we can go through with this project. We have two test stories currently, classic and castle." def __init__(self,name,printed_name,landing_point,description): self.name = name self.landing_point = landing_point self.description = description stories.append(self) #story mode. this variable determines which story is being told classic = Story("classic","A classic adventure","house","The original adventure in the game's code") #what mode of the story and where the player starts. castle = Story("castle","An adventure in a castle","hall","A small adventure in which you can talk to Slorb") current_story = classic class Room: ###This is an environment with a series of commands ###that the player can be within and can use commands inside of def __init__(self,name,printed_name,description,commands): self.name = name self.printed_name = printed_name self.description = description self.commands = commands def printDesc(self): print(self.description) return self.description def printCommands(self): i = 0 for value in self.commands: if value[1] == True: i +=1 print(str(i)+".",value[0].name+".", value[0].description) print(str(i+1)+". Get help. Bring up short guide") print(str(i+2)+". Print your inventory.") def giveCommands(self): commands_per_room = self.commands return commands_per_room class roomCommand: ###This is a command within a room. Technically, items should be a subclass of it but I yeeted it. def __init__(self,name,description): self.name = name self.description = description def giveName(self): return self.name def giveDescription(self): return self.description class Exit(roomCommand): ###This is a room command which provides the info for the player to move from one room to the other def __init__(self,name,description,from_room,to_room): self.name = name self.description = description self.from_room = from_room self.to_room = to_room def giveToRoom(self): return self.to_room def giveFromRoom(self): return self.from_room def openDoor(self): to_room = locations[self.to_room] from_room = locations[self.from_room] print("The door to the", to_room.name,"has been opened.") for command in from_room.commands: if command[0] == self: if command[0] == self: #open these gates command[1] = True class NPC(roomCommand): ###This is a room command class which has dialogue and talks to the user. def __init__(self,name,description,dialogue,dialogue_number): self.name = name self.description = description self.dialogue = dialogue self.dialogue_number = dialogue_number self.dialogue_count = 0 def speak(self): print("\n") print(self.name.upper()) print("""################################################# """) print(self.dialogue[self.dialogue_count % self.dialogue_number]) self.dialogue_count += 1 print("""################################################# """) class fetchNPC(NPC): ###this npc is special because they will ask the player for an item in their initial dialogue ###and then will change their dialogue after an item is used to. #dialogue 1 = "I need this item" or some shit like that lol #dialogue 2 - "thank you for doing that whatever the fuck. #they will also pass in a string which will be the command #that is processed by a def __init__(self,name,description,dialogue,dialogue2,thanks_dialogue,dialogue_number,action,Exit,stage,item,item2): self.name = name self.description = description self.dialogue = dialogue self.dialogue2 = dialogue2 self.thanks_dialogue = thanks_dialogue self.dialogue_number = dialogue_number self.dialogue_count = 0 self.action = action #what the npc does upon being gifted the item self.Exit = Exit self.stage = stage # determines if the object has been given or not self.item = item #the item that the npc wants self.item2 = item2 def processAction(self,inventory): #if the task that the npc does upon having their quest being solved is opening up a location if self.action == "openDoor": self.Exit.openDoor() self.item.takeFromInventory(inventory) if self.action == "giveItem": print(self.name,"has a gift for you as thanks.") self.item2.putIntoInventoryFromNPC(inventory) self.item.takeFromInventory(inventory) print(""" """) def interact(self,inventory): if self.stage == "notFulfilled" and self.item not in inventory.contents: self.speak() elif self.stage == "notFulfilled" and self.item in inventory.contents: print(self.name.upper()) print("""################################################# """) print(self.thanks_dialogue) print("""################################################# """) self.processAction(inventory) self.stage = "Fulfilled" self.dialogue = self.dialogue2 elif self.stage == "Fulfilled": self.speak() class Look(roomCommand): ###This will later return an image of the room in a browser. Not yet tho. def __init__(self, name, description, file): self.name = name self.description = description self.file = file def showImage(self): print("Look") print("Click to close Look") win = GraphWin(self.name, 350, 350) room_pic = Image(Point(175, 175), self.file) room_pic.draw(win) win.getMouse() #time.sleep(7) win.close() class Inventory: ###This is the list that holds the items and the special methods for it yo. def __init__(self,contents, combos): self.contents = [] def printItems(self): print("\nThese are all of the items in your inventory\n") print("#"*80) i = 0 for value in self.contents: if value.shown == True: i +=1 print(str(i)+".",value.name+".",value.description) print("#"*80) if i == 0: print("There are no items in your inventory") print("\n") def alchemy(self): checkingdevicethingy = self.contents[1] #to prevent alchemy from running if there aren't two objects alchemy_info = print("Enter the numbers of two items you wish to combine separated by spaces.") combo_input = input("What would you like to combine?: ") combo_input = combo_input.split() choice1 = int(combo_input[0]) - 1 # gives the equivalent place within the list choice2 = int(combo_input[1]) - 1 if (choice1 >= choice2): # switches the order so the order of deleting doesn't get affected choice1, choice2 = choice2, choice1 inventory_list = self.contents element1 = str(inventory_list[choice1]) # turns it into a string for easy matching element2 = str(inventory_list[choice2]) print("You selected: " + element1 + ", " + element2) # these are the predecided combinations, the player can only combine the pairs in here to get something new pair_counter = 0 for pair in comboDict.keys(): pair_counter += 1 if (element1+element2) in pair: print(comboDict.values()) del inventory_list[choice1] inventory_list.insert(choice1, "placeholder") del inventory_list[choice2] del inventory_list[choice1] inventory_list.append(comboDict.get(pair)) print("you created a new item!") break else: print("you can't combine these items!") break ## if [element1, element2] in greenTrinketCombo: ## ## print("you created a new item!") ## inventory_list.append(greenTrinket) ## elif [element1, element2] in russianRockCombo: ## del inventory_list[choice1] ## inventory_list.insert(choice1, "placeholder") ## del inventory_list[choice2] ## del inventory_list[choice1] ## print("you created a new item!") ## inventory_list.append(russianRock) # creates a class of potential combinations class Combos(Inventory): def __init__(self, part1, part2): self.part1 = part1 self.part2 = part2 def comboCreator(self): return (self.part1+self.part2, self.part2+self.part1) class Item: def __init__(self,name,description,shown): self.name = name self.description = description self.shown = shown # makes the item show up as its name when printed def __str__(self): return '{self.name}'.format(self=self) def printItem(): print("Item name:",self.name+". Item description",self.description) def putIntoInventory(self,room,inventory): if type(self) == Key: self.newCommand() inventory.contents.append(self) inventory_counter = 0 for item in room.commands: inventory_counter +=1 if item[0].name == self.name: del room.commands[inventory_counter-1] if type(item) == Key: item.newCommand break print("You put the",self.name,"into your inventory.") def putIntoInventoryFromNPC(self,inventory): if type(self) == Key: self.newCommand() inventory.contents.append(self) print("You put the",self.name,"into your inventory.") def takeFromInventory(self,inventory): taking_counter = 0 for thing in inventory.contents: taking_counter +=1 if thing.name == self.name: del inventory.contents[taking_counter-1] break class Key(Item): def __init__(self,name,description,shown,room,command): self.name = name self.description = description self.shown = shown self.room = room self.command = command def useKey(self,inventory,Exit_here,room): #change command of if a location is shown from False to True #remove item from inventory #change descriptor of room. #self.command[1] = True #the command here is the command to open the next room. item_index = inventory.contents.index(self) del inventory.contents[item_index] print("You have used the",self.name,"to open a way to the",self.room.name) Exit_here.openDoor() from_room = locations[Exit_here.from_room] for action in from_room.commands: if action[0] == self: # from_room.commands.remove(action) def newCommand(self): #room is the room where it can be used. the command is for it to open the door. self.room = locations[self.room] for value in self.room.commands: if value[0] == self: value[1] = True break def returnRoom(self): self.room = locations[self.room] return self.room class Person: #This is a class with the ability to go from one place to the other. The player is one of these. Literally #all it can do is move from one room to the other, lol. def __init__(self,name,location): self.name = "Ritchie" self.location = location def giveLocation(self): return self.location def moveSelf(self,from_room,to_room): self.location = locations[to_room] return self.location #TEST CLASS #fart = Fart("a big fart","wow, it's gross. no big surprise there, sherlock.", "test file") #THIS IS LOOKING AROUND look_laboratory = Look("Look in the laboratory","There are strange beeping noises and nuclear fallout symbols everywhere.", "lab.gif") look_house = Look("Look in the house","McLoving this architecture", "house.gif") look_basement = Look("Look around the basement","It's damp and dingy.", "basement.gif") look_secret_room = Look("Look around","Actually, you should probably pass on that. It seems scary", "secretroom.gif") look_outside = Look("Look outside","I mean there's stuff here but who cares?", "outside.gif") look_garage = Look("Look in the garage","All I can see is old tools dad promised himself that he'd use.", "garage.gif") #THIS IS THE PLAYER'S INVENTORY player_inventory = Inventory([], {}) #THESE ARE EXITS stairs = Exit("Stairs","These are stairs that go downwards","house","basement") upstairs = Exit("Upstairs","Go up the stairs","basement","house") side_tunnel = Exit("A side tunnel?","Go through the side tunnel","basement","secret_room") side_tunnel_back = Exit("Go back","Time to leave the sights behind","secret_room","basement") go_outside = Exit("Is that a door outside?","leave through the door outside","house","outside") go_inside = Exit("Well, that was lame","go back inside","outside","house") enter_garage = Exit("The garage","Looks like the door to the garage","outside","garage") exit_garage = Exit("Leave the garage","Leave the garage since it was boring","garage","outside") enter_lab = Exit("Enter the lab","Looks like there's another room off the side","secret_room","laboratory") leave_lab = Exit("Leave the lab","You've seen about all there is to see","laboratory","secret_room") tunnel = Exit("Go through the tunnel","You're curious what's up this tunnel","laboratory","garage") back_tunnel = Exit("Back through tunnel","Well, you figured that out","garage","laboratory") #THIS IS A FEW ITEMS greenCube = Item("Green Cube","A 7 inch by 7 inch, lime green cube.",True) russianTrinket = Item("Russian Trinket","Some creepy doll with cyrillic writing on it",True) rock = Item("Rock","Isn't that a great rock",True) endingTest = Item("Ending Test", "end tester", True) #COMBO ITEMS greenTrinket = Item("Green Trinket", "The combo of russian trinket and green cube", True) russianRock = Item("Russian Rock", "russian trinket + rock", True) #COMBO CREATIONS GTCombo = Combos("Green Cube", "Russian Trinket") greenTrinketCombo = GTCombo.comboCreator() RRCombo = Combos("Russian Trinket", "Rock") russianRockCombo = RRCombo.comboCreator() comboDict = {greenTrinketCombo: greenTrinket, russianRockCombo: russianRock} #THESE ARE KEYS garage_key = Key("Garage Key","This is the key that will let you into dad's garage",True,"outside",enter_garage) #THESE ARE NPCS uncle_joe = NPC("Uncle Joe","Is that Uncle Joe?",["I'm busy in here.","Do zou zink I am a Russian spy"],2) mom = NPC("Mom","She's holding a platter of cookies",["Do you want some cookies?","I made them just for you"],2) dad = NPC("Dad","He's looking forelornly at the lawn mower",["Your mother told me to fix this","I don't have any idea how"],2) rat = NPC("A Rat","Looks like the mouse trap didn't work.",["Squeak!","Squeeeeak!"],2) vlad = fetchNPC("Definitely not Vlad","A man sitting in front of a computer - seems valid",["I need a green cube","I think that's absolutely valid"],["Wow, you're so nice for helping out","This is a very good cube. Not nuclear"],"Zank you for ze cube",2,"giveItem",tunnel,"notFulfilled",greenCube,rock) #THESE ARE ROOMS garage = Room("garage","The garage","Filled with all of dad's used to be projects",[[look_garage,True], [exit_garage,True], [rat,True]]) secret_room = Room("secret_room","A secret room","Huh, this is just an old, secret room",[[look_secret_room,True], [side_tunnel_back,True], [uncle_joe,True], [russianTrinket,True], [garage_key,True], [enter_lab,True]]) house = Room("house","An Upper Middle Class Travesty","This is a house",[[look_house,True], [stairs,True], [go_outside,True], [mom,True], [greenCube,True]]) basement = Room("basement","Smells like forgotten baby toys","This is a basement",[[look_basement,True], [upstairs,True], [side_tunnel,True]]) outside = Room("outside","Ew, what is this place","Is this outside???",[[look_outside,True], [go_inside,True], [dad,True], [endingTest, True], [garage_key,False], [enter_garage,False]]) laboratory = Room("laboratory","A Secret Laboratory","This place seems a little sketchy. There's Russian writing everywhere",[[look_laboratory,True], [leave_lab,True], [vlad,True], [tunnel,False]]) #THIS IS THE PLAYER Location is set with their initialization player = Person("Ritchie",house) #LOCATIONS DICTIONARY. Pre-initializes the locations for the rooms/exits locations = { "house":house, "basement":basement, "secret_room":secret_room, "outside":outside, "garage":garage, "laboratory":laboratory} #THIS IS NON CLASS BASED DEFINITIONS def getInput(): player_input = input("--> ") return player_input def help(): print(""" Dialogue, walking, and picking up items simulator Simply enter the number of the command that you want to do. Type the number as a numeral or it will not work. You can end the game simply by typing "end." """) def gameEnder(): inventory_list = player_inventory.contents ending_choices = {garage.name:"Ending Test", basement.name:"basement key test"} # garage ending for items in inventory_list: if items.name in ending_choices.values(): if player.location.name in ending_choices.keys(): if player.location.name == garage.name: print("The game has ended because you went to the Man Cave") print("A.K.A. the Garage") print("How dare you ruin the sanctity of your dad's special shrine to Manhood") print("Your dad is very, very disappointed.") win = GraphWin("Dad", 350, 350) dad_bg = Image(Point(175, 175), "disappointeddad.gif") dad_bg.draw(win) time.sleep(4) win.close() pygame.mixer.music.stop() going = False return going else: going = True return going else: going = True return going def processInput(player_input): i = 0 counter_of_written = len(locations[player.location.name].commands) try: for value in player.location.commands: #the counter of the written is how many of the commands are written to the screen if value[1] == False: counter_of_written -= 1 for value in player.location.commands: #this determines how far off the player's input will be from what they are actually asking for if (value[1] == False and (player.location.commands.index(value)<int(player_input))): #it differs from the counter of written because it only goes up to the total of the player input player_input = int(player_input)+1 #for each one that's false, the player's input will have to go one further from where it originally would have gone #the above will run a check that handles false commands try: player_choice = player.location.commands[int(player_input)-1] if player_choice[1] == True: #this section right here is where I can add in different kinds of commands if type(player_choice[0]) == Exit: #if the type of the command associated is Exit, complete an exit action player.moveSelf(player_choice[0].from_room,player_choice[0].to_room) print("You moved to "+ player.location.printed_name) elif type(player_choice[0]) == Look: player_choice[0].showImage() elif type(player_choice[0]) == NPC: player_choice[0].speak() elif type(player_choice[0]) == Item: player_choice[0].putIntoInventory(player.location,player_inventory) elif type(player_choice[0]) == Key: if player_choice[0] in player_inventory.contents: player_choice[0].useKey(player_inventory,player_choice[0].command,player_choice[0].room) else: player_choice[0].putIntoInventory(player.location,player_inventory) elif type(player_choice[0]) == fetchNPC: player_choice[0].interact(player_inventory) except IndexError: player_choice = player_input # this accounts for the increase in player_input from above without affecting the rooms that don't have falses for value in player.location.commands: #this determines how far off the player's input will be from what they are actually asking for if (value[1] == False and (player.location.commands.index(value)<int(player_input))): #it differs from the counter of written because it only goes up to the total of the player input player_input = int(player_input)-1 #for each one that's false, the player's input will have to go one less than what was adjusted above player_choice = player_input if int(player_choice) ==(counter_of_written+1): #if the number the player inputs is past the list of commands inherent to each room and so is a normal commands help() elif int(player_choice) == (int(counter_of_written) + 2): player_inventory.printItems() choose_combine = input("Do you want to create a new item? YES/NO: ") if choose_combine.upper() == "YES": try: player_inventory.alchemy() player_inventory.printItems() except IndexError: print("") else: print("") elif int(player_choice) >= (counter_of_written+3): #if it isn't one of the commands print("\nNon valid command help\n") except ValueError: print("\nPlease type in numerals unless doing an end command\n") def main(): going = True while going == True: #put ending checker here. random ending put in just for the sake of checking to see if it will work #idea - check dictionary of choices made throughout the game for different endings maybe. player.location.printDesc() player.location.printCommands() player_input = getInput() if player_input.upper() == "END": print("Thank you for playing!") pygame.mixer.music.stop() break else: processInput(player_input) going = gameEnder() time.sleep(1) #####################CODE EXECUTION################################### if __name__ == "__main__": #pass pygame.mixer.init() pygame.mixer.music.load("Happy_Ending.mp3") pygame.mixer.music.play() main() ###################################################################### #http://blog.thedigitalcatonline.com/blog/2015/01/12/accessing-attributes-in-python/ #https://codereview.stackexchange.com/questions/57438/game-inventory-system # Professor John Foley's code "Spooky Example" - ported these ideas into OOP # https://www.pythonforbeginners.com/error-handling/python-try-and-except #https://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary #https://stackoverflow.com/questions/216972/in-python-what-does-it-mean-if-an-object-is-subscriptable-or-not #https://www.tutorialspoint.com/python/list_index.htm #https://stackoverflow.com/questions/11520492/difference-between-del-remove-and-pop-on-lists/11520540 #https://www.edureka.co/community/18841/how-do-play-audio-playsound-in-background-of-python-script #https://www.pygame.org/docs/ref/mixer.html #https://www.quora.com/What-is-the-use-of-__str__-in-python #https://stackoverflow.com/questions/46058432/python-3-set-name-of-object-in-class/46058669 #https://www.pythonforbeginners.com/dictionary/how-to-use-dictionaries-in-python
f4bf9b0daee491bb39cf49dac4834e51636b46e3
MrHamdulay/csc3-capstone
/examples/data/Assignment_9/knnsad001/question1.py
1,611
4.0625
4
#program to analyse student marks read in from a file and determine which students need to see a student advisor #KNNSAD001 #Assignment 9 import math filename=input("Enter the marks filename:\n") f = open(filename,"r") lines=f.readlines() #opens file and reads data- puts each string in each line into an individual list marks=[] names=[] mean_mark=0 for i in range(len(lines)): marks.append(lines[i].split(',')[1].split("\n")[0]) names.append(lines[i].split(',')[0]) marks[i]=int(marks[i]) mean_mark+=marks[i] #to find the mean mark per student by spiliiting the individual marks in the lists and calculating mean mean_mark=mean_mark/len(marks) s_deviation=0 for i in range(len(marks)): s_deviation+=(marks[i]-mean_mark)**2 s_deviation=math.sqrt(s_deviation/len(marks)) #uses the calculated mean mark above to calculate std deviation print("The average is:","{:.2f}".format(mean_mark)) print("The std deviation is:","{:.2f}".format(s_deviation)) advsr=False for i in range(len(marks)): if(marks[i]<(mean_mark-s_deviation)): #if mark is below bthe average mark = student needs a student advisor) advsr=True if(advsr): print("List of students who need to see an advisor:") #prints students who need to see an advisor based on marks for i in range(len(marks)): if(marks[i]<(mean_mark-s_deviation)): print(names[i])
024552ace9e460ec58a18f1a710ca884c7b30a5d
harishramuk/python-handson-exercises
/388..py
277
3.828125
4
import os fname = input('enter file name:') if os.path.isfile(fname): print('file existing:',fname) f = open(fname,'r') text = f.read() print(40 * '*') print(text) print(40 * '*') f.close() else: print('file name is not exist...')
8c852d99e401ffddf700ba6e870dd586fdaf3821
sinegami301194/Python-HSE
/2 week/sumOfSquares.py
106
3.65625
4
x = int(input()) sum = 0 i = 1 while i <= x: sum = sum + i**2 i = i + 1 print(sum, end='')
b416eb369e667099dce7e4f875ca35c6d36c0b22
henriquekirchheck/Curso-em-Video-Python
/desafio/desafio037.py
1,361
3.75
4
#Peça para o usuario um numero inteiro e peça uma base de conversão num = int(input('\nDigite um numero inteiro: ')) base = int(input('Escolha entre binario(1), octal(2) e hexadecimal(3): ')) print('') hexcount = 10 done = False numalf = { 10 : 'A', 11 : 'B', 12 : 'C', 13 : 'D', 14 : 'E', 15 : 'F', } if(base == 1): binary = [] while(done == False): rest = num % 2 num = num // 2 binary.append(rest) if(num == 0): result = binary[::-1] done = True if(base == 2): octal = [] while(done == False): rest = num % 8 num = num // 8 octal.append(rest) if(num == 0): result = octal[::-1] done = True if(base == 3): hexadecimal = [] while(done == False): rest = num % 16 num = num // 16 hexadecimal.append(rest) if(num == 0): while(hexcount <= 15): count = [i for i, x in enumerate(hexadecimal) if x == hexcount] if(count != []): for x,y in zip(count, numalf[hexcount]): hexadecimal[x] = y hexcount = hexcount + 1 result = hexadecimal[::-1] done = True print(''.join(str(e) for e in result))
d1af447038c00c0ea87178b0999350c142e52792
FriggD/CursoPythonGGuanabara
/Mundo 1/Desafios/Desafio#16.py
234
3.859375
4
#Crie um programa que leia um número real qualquer pelo teclado e mostre na tela a sua porção inteira from math import trunc num = float(input('Digite um núemro fracionário: ')) print('A parte inteira é: {}'.format(trunc(num)))
f82a6ce63d3f930b27e0ce5bc2666efdf188346d
gelinas/Sorting
/src/iterative_sorting/iterative_sorting.py
1,851
4.25
4
# TO-DO: Complete the selection_sort() function below test_list = [8, 2, 5, 4, 1, 3] # print(test_list) def selection_sort( arr ): # loop through n-1 elements for i in range(0, len(arr) - 1): print("start:") print(arr) cur_index = i smallest_index = cur_index # TO-DO: find next smallest element # (hint, can do in 3 loc) for j in range(i, len(arr)): if arr[j] < arr[cur_index] and arr[j] < arr[smallest_index]: smallest_index = j # print("smallest:") # print(smallest_index) # print(arr[smallest_index]) # print("current:") # print(cur_index) # print(arr[cur_index]) # TO-DO: swap if cur_index != smallest_index: temp = arr[cur_index] arr[cur_index] = arr[smallest_index] arr[smallest_index] = temp print("end:") print(arr) return arr # TO-DO: implement the Bubble Sort function below def bubble_sort( arr ): cursor = 0 flag = True swap = False while flag == True and cursor < len(arr): start = arr.copy() print("cursor:") print(cursor) for i in range(cursor, len(arr) - 1): if arr[i + 1] < arr[i]: temp = arr[i] arr[i] = arr[i + 1] arr[i + 1] = temp swap = True print("start:") print(start) print("end:") print(arr) if swap == False and cursor < len(arr): cursor += 1 if start == arr: flag = False return arr # STRETCH: implement the Count Sort function below def count_sort( arr, maximum=-1 ): return arr # print(selection_sort(test_list)) print(bubble_sort(test_list))
603f7203c9b624d83651b3781649566a10d6acab
ongsuwannoo/PSIT
/PlanCDEFGHIJKLMNOPQRSTUVWXYZ.py
564
4
4
''' PlanCDEFGHIJKLMNOPQRSTUVWXYZ ''' def main(): ''' for sort ''' option = input() num1 = float(input()) num2 = float(input()) num3 = float(input()) much = num3 if num3 > num2 and num3 > num1 else num1 if num1 > num2 else num2 less = num3 if num3 < num2 and num3 < num1 else num1 if num1 < num2 else num2 mid = (num1 + num2 + num3) - (much + less) if option == 'Ascend': print('%.2f, %.2f, %.2f'%(less, mid, much)) # Ascend else: print('%.2f, %.2f, %.2f'%(much, mid, less)) # Descend main()
b9c1184e92ba71ac6c36a358cb15ce4c17b73136
surajshrestha-0/Python_Basic_I
/Function/Question14.py
397
4.09375
4
""" Write a Python program to sort a list of dictionaries using Lambda. """ def sortDictionaries(input_tuple): return sorted(input_tuple, key=lambda x: x['salary']) dicts = [ {"name": "Ram", "salary": 10000}, {"name": "Hari", "salary": 30000}, {"name": "Shyam", "salary": 15000}, {"name": "Gaurav", "salary": 20000} ] print(sorted(dicts, key=lambda item: item['salary']))
30124f5c9435c483264f7bc307de967579fae77f
SeungHune/Programming-Basic
/과제 6/과제 6-1.py
1,301
3.640625
4
def minsteps0(n): if n > 1: r = 1 + minsteps0(n - 1) if n % 2 == 0: r = min(r, 1 + minsteps0(n // 2)) if n % 3 == 0: r = min(r, 1 + minsteps0(n // 3)) return r else: return 0 def minsteps1(n): memo = [0] * (n + 1) def loop(n): print(memo) if n > 1: if memo[n] != 0: return memo[n] else: memo[n] = 1 + loop(n - 1) if n % 2 == 0: memo[n] = min(memo[n], 1 + loop(n // 2)) if n % 3 == 0: memo[n] = min(memo[n], 1 + loop(n // 3)) return memo[n] else: return 0 return loop(n) print(minsteps1(3)) def minsteps(n): memo = [0] * (n + 1) for i in range(len(memo)): print(memo) if (n > 1): if (memo[n] != 0): return memo[n] else: n = n -1 memo[n] = 1 + memo[n-1] if (n % 2 == 0): n = n // 2 memo[n] = min(memo[n], 1 + memo[n//2]) if (n % 3 == 0): n = n // 3 memo[n] = min(memo[n], 1 + memo[n//3]) return memo[n] print(minsteps(3))
adcb530170b637c0676535a09167249b15e787e1
OmkarGangan/Resume-Maker-
/resume maker.py
2,733
4.25
4
# declare variable and accept user input name = input('Enter your Name:') mail = input('Enter your Email Id:') num = input('Enter your Contact No.:') l = input('Enter your Location:') edu = input('Enter Latest Education:') p = input('Enter Percentage:') y = input('Enter passing year:') c = input('Enter College:') e = input('Enter Latest Experience:') org = input('Enter Name of Company:') # list to store multiple number of projects pj = [] pro = int(input('Enter Number of projects you want to add:')) for i in range(pro): pj.append(input("Enter projects:")) # empty list to store multiple number of skills sk = [] s = int(input('Enter Number of skills you want to add:')) for i in range(s): sk.append(input("Enter skills:")) a = input('Enter your Achievements') # empty list to store multiple number of hobbies ho = [] hob = int(input('Enter Number of hobbies you want to add:')) for i in range(hob): ho.append(input("Enter hobbies:")) # empty list to store multiple number of languages known lang = [] lan = int(input('Enter Number of languages you know:')) for i in range(lan): lang.append(input("Enter language:")) # print resume format print('-------------------------------------------------------------------------------------------------') print('\t\t\t\t\t{}'.format(name)) print('\t\t{}\t\t{}\t\t{}'.format(mail,num,l)) print('-------------------------------------------------------------------------------------------------') print('\t\t\t\t\tEducation') print('\t\t{}\t\t{}\t\t{}\t\t{}'.format(edu,p,y,c)) print('-------------------------------------------------------------------------------------------------') print('\t\t\t\t\tExperience') print('\t\t\t{}\t\t{}'.format(e,org)) print('-------------------------------------------------------------------------------------------------') print('\t\t\t\t\tSkills') for i in sk: print('\t\t\t\t{}'.format(i)) print('-------------------------------------------------------------------------------------------------') print('\t\t\t\t\tProjects') for i in pj: print('\t\t\t\t{}'.format(i)) print('-------------------------------------------------------------------------------------------------') print('\t\t\t\t\tAchievements') print('\t\t\t\t{}'.format(a)) print('-------------------------------------------------------------------------------------------------') print('\t\t\t\t\tHobbies') for i in ho: print('\t\t\t\t{}'.format(i)) print('-------------------------------------------------------------------------------------------------') print('\t\t\t\t\tLanguages') for i in lang: print('\t\t\t\t{}'.format(i))
0537a2a37f0d31d47902bcca611bb7901fa6347e
dkaimekin/webdev_2021
/lab9/Informatics_2/e.py
198
4.1875
4
a = int(input("Insert number a: ")) b = int(input("Insert number b: ")) def find_bigger(a, b): if a > b: return 1 elif a < b: return 2 else: return 0 print(find_bigger(a, b))
a35481b16f339c98a69d611a263d4e9eb4c7413b
anandtest27/pyrepo
/hello.py
441
3.890625
4
def main(): anand = [10, 20, 30, 40, 50] # For array # x = bytes(anand) # this is byte data type and it cant be changed # print (type(x)) # # x[3] = 100 # anand[3] = 110 # # print (x) # print (anand) x = bytearray(anand) # This is byte array data type. The items inside can be changed x[3] = 25 print (type(x) , " Value on 1st position is: " + str(x[3])) if __name__ == "__main__": main()
88647d9a725a490e763d3837a707a5dce226a919
JosephAdolf/AP-II
/EX 4 LAB 6 REVISAO.py
613
3.765625
4
def comp_palavra(palavra,letra,tamanho): if tamanho == 0: if palavra[0].upper() == letra.upper(): return 1 else: return 0 if palavra[tamanho].upper() == letra.upper(): return 1 + comp_palavra(palavra,letra,tamanho-1) else: return 0 + comp_palavra(palavra,letra,tamanho-1) letra = input("Digite a letra que você quer comparar:") palavra = input("Digite a palavra que você quer comparar:") tamanho = len(palavra)-1 print("A letra",letra,"aparece",comp_palavra(palavra,letra,tamanho),"vezes!!")
e70d8001baf358b4ddeee6d518db9c7a8dda4e57
pranavraj101/python-
/regex_1.py
162
3.6875
4
import re if(re.match(r'AV', 'AV Analytics AV')): print("MATCHED") else: print("NOT MATCHED") print(re.search(r'Analytics', 'AV Analytics AV Analytics'))
4336f7471d3b70728c8ef63ef82e409b533c4013
annguyenict172/coding-exercises
/exercises/array_and_string/license_key_formatting.py
1,447
3.5
4
""" Leet Code #482 """ import unittest def license_key_formatting(string, k): if not string: return '' string_builder = [] chars_in_group = 0 for i in range(len(string)-1, -1, -1): if string[i] != '-': string_builder.append(string[i].upper()) chars_in_group += 1 if chars_in_group == k: string_builder.append('-') chars_in_group = 0 if len(string_builder) == 0: return '' if string_builder[-1] == '-': string_builder.pop() return ''.join(list(reversed(string_builder))) class TestResult(unittest.TestCase): def test_empty_string(self): self.assertEqual(license_key_formatting('', 5), '') def test_k_larger_than_string_length(self): self.assertEqual(license_key_formatting('abcd', 5), 'ABCD') def test_single_group(self): self.assertEqual(license_key_formatting('a-bcd-efg', 7), 'ABCDEFG') def test_first_group_has_less_characters(self): self.assertEqual(license_key_formatting('a-b-cd-ef-g-h', 3), 'AB-CDE-FGH') def test_all_group_equal_characters(self): self.assertEqual(license_key_formatting('a-b-cd-ef-g-h-i', 3), 'ABC-DEF-GHI') def test_dash_only_string(self): self.assertEqual(license_key_formatting('---', 3), '') def test_multiple_dashes_in_beginning(self): self.assertEqual(license_key_formatting('---AA-AA', 2), 'AA-AA')
0fcfcc006d4497c1f6129bcf981f675195846ba3
itsolutionscorp/AutoStyle-Clustering
/assignments/python/anagram/src/422.py
405
3.6875
4
def detect_anagrams(word, anagrams): result = [] for item in anagrams: word = word.lower() if (word == item.lower()) : continue if (len(word) == len(item)): temp_word = word for letter in item.lower(): if (letter in temp_word): index = temp_word.index(letter) temp_word = temp_word[0:index] + temp_word[index+1:] if (len(temp_word) == 0): result.append(item) return result
52b2c6ac5c296ebd037196418c9166a9aa830347
sseering/AdventOfCode
/2017/aoc06.py
4,491
3.953125
4
#!/usr/bin/env python3 # --- Day 6: Memory Reallocation --- # # A debugger program here is having an issue: it is trying to repair a memory reallocation routine, but it keeps getting stuck in an infinite loop. # # In this area, there are sixteen memory banks; each memory bank can hold any number of blocks. The goal of the reallocation routine is to balance the blocks between the memory banks. # # The reallocation routine operates in cycles. In each cycle, it finds the memory bank with the most blocks (ties won by the lowest-numbered memory bank) and redistributes those blocks among the banks. To do this, it removes all of the blocks from the selected bank, then moves to the next (by index) memory bank and inserts one of the blocks. It continues doing this until it runs out of blocks; if it reaches the last memory bank, it wraps around to the first one. # # The debugger would like to know how many redistributions can be done before a blocks-in-banks configuration is produced that has been seen before. # # For example, imagine a scenario with only four memory banks: # # The banks start with 0, 2, 7, and 0 blocks. The third bank has the most blocks, so it is chosen for redistribution. # Starting with the next bank (the fourth bank) and then continuing to the first bank, the second bank, and so on, the 7 blocks are spread out over the memory banks. The fourth, first, and second banks get two blocks each, and the third bank gets one back. The final result looks like this: 2 4 1 2. # Next, the second bank is chosen because it contains the most blocks (four). Because there are four memory banks, each gets one block. The result is: 3 1 2 3. # Now, there is a tie between the first and fourth memory banks, both of which have three blocks. The first bank wins the tie, and its three blocks are distributed evenly over the other three banks, leaving it with none: 0 2 3 4. # The fourth bank is chosen, and its four blocks are distributed such that each of the four banks receives one: 1 3 4 1. # The third bank is chosen, and the same thing happens: 2 4 1 2. # # At this point, we've reached a state we've seen before: 2 4 1 2 was already seen. The infinite loop is detected after the fifth block redistribution cycle, and so the answer in this example is 5. # # Given the initial block counts in your puzzle input, how many redistribution cycles must be completed before a configuration is produced that has been seen before? # # To begin, get your puzzle input. # # The first half of this puzzle is complete! It provides one gold star: * # --- Part Two --- # # Out of curiosity, the debugger would also like to know the size of the loop: starting from a state that has already been seen, how many block redistribution cycles must be performed before that same state is seen again? # # In the example above, 2 4 1 2 is seen again after four cycles, and so the answer in that example would be 4. # # How many cycles are in the infinite loop that arises from the configuration in your puzzle input? # # Although it hasn't changed, you can still get your puzzle input. INPUT_STR = "10 3 15 10 5 15 5 15 9 2 5 8 5 2 3 6" def redistribute(memory_banks): max_ = -1 max_idx = None for (idx, val) in enumerate(memory_banks): if val > max_: max_ = val max_idx = idx len_ = len(memory_banks) memory_banks[max_idx] = 0 while max_ > 0: max_idx += 1 max_idx = max_idx % len_ memory_banks[max_idx] += 1 max_ -= 1 def part1() -> None: memory_banks = [int(_) for _ in INPUT_STR.split()] all_seen = set() all_seen.add(tuple(memory_banks)) answer = 0 while True: redistribute(memory_banks) answer += 1 mem_tuple = tuple(memory_banks) if mem_tuple in all_seen: break all_seen.add(mem_tuple) print(f'solution of part 1 is {answer}') def part2() -> None: memory_banks = [int(_) for _ in INPUT_STR.split()] all_seen = dict() answer = 0 all_seen[tuple(memory_banks)] = answer while True: redistribute(memory_banks) answer += 1 mem_tuple = tuple(memory_banks) if mem_tuple in all_seen: answer -= all_seen[mem_tuple] print(f'solution of part 2 is {answer}') break all_seen[mem_tuple] = answer def main() -> None: part1() part2() print('done') if __name__ == '__main__': main()
fdacf6f1384da7ece286d24aa0c8c056d4d96076
xiaoying909/xiaoying
/demo02.py
2,674
4.0625
4
#判断 代码块 缩进 # a = 1 # b = 2 # if a == 1: # print("hhh") # if a > b: # print("a比b大") # else: # print("a比b小") # age =int( input("请输入你的年龄:")) # if age > 60: # print("你应该退修了") # elif age > 30: # print("家庭的责任重大") # elif age > 20: # print("一定要好好规划你的未来") # else: # print("一定要好好学习") # if elif else 有区别的 #---------------------------------------------- # in的用法 # a = "你好" # if a in "你好,今天你吃了吗": # print("OK") # else: # print("NO") #---------------------------------------------- # a = input("请输入:") # if a == "": # print("不能为空!") # exit() # if a in "0123456789": # a = int(a) # else: # print("请重新输入:") # exit() # if a > 5: # print("大") # else: # print("小") #---------------------------------------------- # a = 10 # if type(a) is int: # print("是数字!") # elif type(a) is str: # print("是字符串") # else: # print("其他") #---------------------------------------------- # a = 1 # while a < 10: # print("憨憨",a) # a = a + 2 # 遍历 # a = "你好,今天你吃了吗?" # for i in a: # print(i) # a=["zhangsan"] # for i in a: # print(i) # # b = list(range(0,100,2)) # 自动生成了一个数列,步长/步进 # # print(b) # for i in range(10): # print(i) # for i in range(1,10): # for j in range(1,i+1): # print(i,"X",j,"=",i*j,end=" ") # print() # for i in range(10): # if i == 4: # continue # print(i) #方法/函数 def checkname(username): """ 自动的判断账号的长度是5-8位,并且账号是小写 """ if len(username) >=5 and len(username) <=8: if username[0] in "qazwsxedcrfvtgbyhnujmiklop": print() else: print("账号的首字母必须小写字母开头") else: print("账号不符合规范") # def 方法的声明 # checkname 方法的名字 # username 方法的参数 #""""方法的说明"""" # 方法的逻辑代码 def jiafa(a,b): """ 方法的作用是数字相加 """ if type(a) is int and type(b) is int:# typy() 查询数据类似 is 和某个数据类型一样 return a+b else: return "输入的数据类型不正确" """ 返回值,返回后我们可以对这个值进行其他操作 而,print不行 """ # try: # print(1+"a") # except Exception as e: # print("上面代码错了",e) #异常类 包>类>方法>变量 username=input("请输入:") print(checkname)
92977b03d183e0979d68b005bdc95597ea224027
kexiaojiu/python_based_programming
/chapter_04/exercise_4_10.py
304
4
4
players = ['charles', 'martina', 'michael', 'florence', 'eli'] print("The first three items in the list are: " + str(players[0:3])) print("The middle three items in the list are: " + str(players[len(players)/2 - 1 :len(players)/2 + 2])) print("The lat three items in the list are: " + str(players[-3:]))
403879b5f724cf60a9b37bd7f46d3006b40447d2
cy601/Python_basic_programming
/实训/第四章/实训题/猜数字游戏.py
462
3.65625
4
import random number = random.randint(1, 20) guess = 0 while 1: i = (input("输入你猜的数字:")) if i.isdigit(): guess += 1 i = int(i) if i > number: print("猜大了") elif i < number: print("猜小了") else: print("恭喜你,猜对了") print("一共猜了%d次" % guess) exit() else: print("必须输入数字,请重新输入")
d8a5f4768a865121415b128a394571ae56ba8460
Abdelaziz-pixel/Project-PENDU
/main.py
2,306
4.03125
4
"""call all the functions""" from fonctions import * from nom_fichier import * """these variables will start the program""" mot_a_trouver = choisir_mot() position_tout = [] essais = 0 lettres_trouvees = [] """loop when the game does not exceed 6 tries""" while essais < 6: lettre_joueur = "" lettre_joueur = input("Entrez une lettre: ").lower() """condition to check the entry of the user""" if len(lettre_joueur) > 1 or not lettre_joueur.isalpha(): print("Entrez seulement une lettre et non pas des chiffres ou des caractéres !") """if the entry of the user is identical to the first one at the level of the letters chosen""" while lettre_joueur in lettres_trouvees : lettre_joueur = input("Entrer a nouveau une lettre, vous avez déjà choisit cette lettre : ").lower() if len(lettre_joueur) > 1 or not lettre_joueur.isalpha(): print("Entrez seulement une lettre et non pas des chiffres ou des caractéres !") lettres_trouvees.append(lettre_joueur) position_actuelle = lettre_dans_mot(lettre_joueur, mot_a_trouver) """indicates the number of remaining parties if user error""" if position_actuelle == []: essais += 1 print("Attention ! vous avez utilisé {} essais sur 6 possibles.".format(essais)) position_tout += position_actuelle mot_a_aficher = affiche_lettres_trouvees(position_tout, mot_a_trouver) print(mot_a_aficher) print(PENDAISON[essais]) """if the number of errors is identical to the number of tests and tells him the right word""" if essais == 6 : print("Désoler :( vous avez perdu ! Le bon mot était {} ".format((mot_a_trouver).upper())) if mot_a_aficher == mot_a_trouver: print("Bravo! vous avez trouver le bon mot") """this loop allows the user to replay or quit the program""" while essais == 6 or mot_a_aficher == mot_a_trouver : restart = input("Voulez-vous rejouer ? oui/non ? ").lower() if restart == "oui": mot_a_trouver = choisir_mot() position_tout = [] essais = 0 lettres_trouvees = [] elif restart == "non": print("À trés bientot :) !") exit() else: print("Choisissez entre oui et non")
7600f18ac19ed1b05cdcf6e2dcf7ceda3e6d9571
deshmukhrajvardhan/DailyCodingProblem
/solutions/question2.py
911
4.21875
4
'''Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]. Follow-up: what if you can't use division? ''' import pandas def prod_i_sans(l,i): total_prod=1 for el in l: total_prod *=el for i in (range(len(l))): if i<0 or i>len(l)-1: print("illegal index") return times=0 current_prod=total_prod current_el=l[i] while times * current_el < total_prod: current_prod -= current_el times+=1 l[i]=times print("times:{},l:{}".format(times,l)) prod_i_sans([1, 2, 3, 4, 5],0)
440293e4c9fec40caa6504371bd90a85a416f566
nickli1215/Machine-learning-projects
/Seed_Classification/Seeds_Classification.py
2,915
3.65625
4
import csv import torch import torch.nn as nn import numpy as np import numpy.random as rand from pathlib import Path import matplotlib.pyplot as plt data_folder = Path("C:/Users/Nicholas/AppData/Local/Programs/Python/Python36-32/PyTorch practice") datafile = data_folder/ "Seed_Data.csv" features = 7 data = np.empty([0,0]) #reading data and formatting into 2 arrays with open(datafile) as file: seeds = csv.reader(file, delimiter = ',') next(seeds) data = np.array([[float(i) for i in next(seeds)]], dtype = float) for row in seeds: data = np.append(data,[[float(i) for i in row]], axis = 0) #shuffle and assign data. Adding bias term features to X. #Convert y into M x K sized matrix so that each row vector represents a class. #For example, a data sample of class 2 would be converted into a vector [0,0,1]. rand.shuffle(data) X = np.array(data[0:,0:features]) classes = data[0:,features] y = np.zeros ((data.shape[0],3)) for i in range(len(classes)): y[i,int(classes[i])] = 1 #feature scaling data with Z-score standardization m = X.mean(0) std = X.std(0) X = (X-m)/std X = np.hstack((np.ones((data.shape[0],1),dtype = np.float64),X)) #separating data into training and testing samples. totalSize = X.shape[0] trainingSize = totalSize*7//10 X_training = X[0:trainingSize] y_training = y[0:trainingSize] X_test = X[trainingSize:totalSize] y_test = y[trainingSize:totalSize] class Logistic_Regression: def __init__(self): self.inputSize = 8 self.outputSize = 3 epsilon = -1.0 # I use numpy.random.randint over torch.randn so that I can limit the initial size of the parameters self.W = rand.uniform(low = -epsilon,high = epsilon,size = (self.inputSize,self.outputSize)) def sigmoid(self,x): #sigmoid function return 1/(1+np.exp(x)) def costfunction (self,X,y): #cost function z = np.dot(X,self.W) h = self.sigmoid(z) m = X.shape[0] cost = sum(sum((-y*np.log(h)) - ((1-y)*np.log(1-h))))/m return cost def train (self, X,y,iterations): #Training the algorithm using a simple gradient descent algorithm. for i in range(iterations): p = self.sigmoid(np.dot(X,self.W)) d = p-y m = y.shape[0] grad = (1/m)*(np.dot(np.transpose(X),d)) alpha = 0.1 self.W = self.W + alpha*grad print(self.costfunction(X,y)) def predict (self, X): z = np.dot(X,self.W) h = self.sigmoid(z) return np.argmax(h, axis = 1) K = Logistic_Regression() print(K.costfunction(X,y)) K.train(X_training,y_training,2000) ypred = K.predict(X_test) y_ans = np.argmax(y_test,axis = 1) print(y_ans == ypred) print( "Accuracy: " + str(sum(y_ans == ypred)/len(y_ans))) print(K.W)
31fad5974cc59e6e1503bb21ed03566a137c10fe
bogdanlungu/learning-python
/shopping/cart.py
723
3.75
4
# Cart class # Adds or deletes products from the cart # it also has a __repr__ method that shows what products are in the cart class Cart: def __init__(self): self._contents = dict() def __repr__(self): return "Your shopping cart has these products: {0}".format(self._contents) def process(self, order): if order.add: if not order.item in self._contents: self._contents[order.item] = 0 self._contents[order.item] += 1 elif order.delete: if order.item in self._contents: self._contents[order.item] -= 1 if self._contents[order.item] <= 0: del self._contents[order.item]
7fdabc4ce111f0350c4f3554f1908b8870784da5
bristola/social_news_analysis
/src/project/data_collector/data_collector.py
1,058
3.765625
4
from abc import ABC, abstractmethod class Data_Collector(ABC): def __init__(self, out_file): self.output = out_file def write_to_file(self, data): """ Takes all the list of data and writes it to a new file. """ with open(self.output, 'w+', encoding="utf-8") as f: f.write("\n".join(data)) def filter_authors(self, data): """ Takes the input list of data, and removes all data that has an author that is already found in the data. """ authors = list() out_data = list() for d in data: # If it is a new author, add it to output and add author to list if not d['author'] in authors: authors.append(d['author']) out_data.append(d) return out_data @abstractmethod def search(self, topic, max=None, c=100): pass @abstractmethod def create_strings(self, data): pass @abstractmethod def run(self, topic, iterations): pass
1fee97c98d53715913a47941b19f25b29498033f
FoxTrot-dev/Photoelectric-Effect--Graph-and-Work-Function--PYTHON-CODE
/WorkFunctionPLATINUM.py
1,593
3.5
4
#!/usr/bin/env python # coding: utf-8 # In[1]: # Python #Photoelectric effect- Calculation of WorkFunction #Error Calculation from Theoretical and Calculated Value # Amrutha V-lab Simulation Result #PLATINUM #PLATINUM #PLATINUM #PLATINUM #PLATINUM #PLATINUM #Variable declaration e = 1.6e-19; # Charge on an electron, C h = 6.626e-34; # Planck's constant, Js c = 3.0e+08; # Speed of light in vacuum, m/s W_Theo = 6.35; # Theoretical Value of Work Function of Pt in eV lamb = float(input("Enter the Wavelenghth (in meter) :")); # Wavelength of incident light (meter) V_0 = float(input("Enter the Stopping potential (-ve) :" )); # Stopping potential for emitted electrons, V #Calculation f = c/lamb; # Frequency of incident radiation , Hz E = (h*f); # Energy carried by one photon from Planck's law, J K_max = (e*V_0); # Maximum kinetic energy of electrons, J # We have, WorkFunction W = E-K_max W_in_joule = ((h*f)-(e*V_0)); #Converting to eV, Dividing by e=1.6e-19 to get WorkFunction W_in_eV = (W_in_joule/e) #Result print("The work function of Pt metal (in joule) = ") print (W_in_joule , "joule") print("The work function of Pt metal (in eV) = ") print (W_in_eV,"eV") #Error Calculation print("Theoretical Value of WorkFunction of Pt:-", W_Theo ,"eV" ) print("Calculated Value of WorkFunction of Pt:-",W_in_eV,"eV") #Error=(|theoreticalValue-CalculatedValue|)/theoreticalValue Error=(W_Theo-W_in_eV)/(W_Theo) print("ErrorCalculated=",Error) #Error%=Error*100 Error_Percent = Error*100 print("ErrorPercentage=",Error_Percent,"%") # In[ ]:
0b08a573b61cbd8f111d15258be838fd2234738b
pigwejq/python
/Zadanie5zajecia2.py
457
3.59375
4
#Wydrukuj alfabet w formacie: AaBbCcDd….., a następnie w formacie: #aAbBcCdD….. import string alfabetM = string.ascii_lowercase alfabetW = string.ascii_uppercase licznik = 0 while licznik < len(alfabetW): print(alfabetM[licznik], end="") print(alfabetW[licznik], end="") licznik+=1 licznik = 0 print("\nDruga runda") while licznik < len(alfabetW): print(alfabetW[licznik], end="") print(alfabetM[licznik], end="") licznik+=1
758554f9c1334731c33db46ee9d0803ff8cdd60b
sushtend/100-days-of-ml-code
/code/Advanced Python 1/10.1 cycle.py
339
3.75
4
import itertools as it counter = it.cycle(("on", "off")) # Output # on # off # on # off # on print(next(counter)) print(next(counter)) print(next(counter)) print(next(counter)) print(next(counter)) counter = it.cycle([1, 2, 3]) print(next(counter)) print(next(counter)) print(next(counter)) print(next(counter)) print(next(counter))
4debc9c9dfa123d71a8e7b4b4e4c4d8c7998dae5
javawizard/afn
/filer/src/filer1/data/store.py
1,127
3.6875
4
from abc import ABCMeta, abstractmethod class Store(object): __metaclass__ = ABCMeta @abstractmethod def store(self, data): """ Stores the specified commit, which is a BEC object, in this store. The BEC object in question must form a valid Filer commit; in particular, the store is permitted to rely on special keys like "parents" being present, and is free to throw an exception if they're not. """ @abstractmethod def get(self, hash): """ Returns the commit with the specified hash, or throws an exceptions.NoSuchObject if the commit in question does not exist. """ @abstractmethod def has(self, hash): """ Returns true if the specified hash has been stored in this store, false if it hasn't. """ @abstractmethod def list(self): """ Returns an iterator of some sort (could be a list, or the implementation of this method could just be a generator) providing all of the hashes stored in this store at the moment. """
a8bb4495f33ac945ac4c2a38acd4fc1e4e466a74
GanLay20/The-Python-Workbook-1
/pyworkbookex009.py
502
3.921875
4
savings_account = float(input("Account Ballance:\n>>> ")) year_one_ballance = savings_account * .04 + savings_account year_two_ballance = year_one_ballance * .04 + year_one_ballance year_three_ballance = year_two_ballance * .04 + year_two_ballance print("After one full year your ballance will be :\n$ %.2f" % year_one_ballance) print("After two full years your ballance will be :\n$ %.2f" % year_two_ballance) print("After three full years your ballance will be :\n$ %.2f" % year_three_ballance)
ed9627b7e5369554d75fcee62a1519d902ec128e
Bingwen-Hu/hackaway
/books/dataScienceFromScratch/simpleLinearRegression.py
2,085
4
4
""" The simplest model: y = alpha + beta * x + error the error is uncontrolled factor affected the result. we ignore it in our model so given out ALPHA and BETA, we can compute the yi value The predict error given by: prediected_error = y - yi So we just need to minimize the predict_error # some useful numpy function np.std(array) # standard deviation np.var(array) # variance np.correlate(v1, v2) correlation(x, y) = covariance(x, y) / (std(x) * std(y)) when std(x)*std(y)!=0 covariance(x, y) = (x - avg(x)) * (y - avg{y}) / (n - 1) """ import numpy as np def predict(alpha, beta, x_i): return beta * x_i + alpha def error(alpha, beta, x_i, y_i): return y_i - predict(alpha, beta, x_i) def sum_of_squared_errors(alpha, beta, x, y): return sum(error(alpha, beta, x_i, y_i) ** 2 for x_i, y_i in zip(x, y)) # the three function do the things can be imployed as the following one: def numpy_sum_of_squared_errors(alpha, beta, x, y): error = np.array(y) - (beta * np.array(x) + alpha) squared_error = np.square(error) return np.sum(squared_error) # least squares fit need some calculus def least_squares_fit(x, y): beta = numpy_correlation(x, y) * np.std(y) / np.std(x) alpha = np.mean(y) - beta * np.mean(x) return np.double(alpha), np.double(beta) def total_sum_of_squares(y): return sum((np.array(y) - np.average(y))**2) def r_squared(alpha, beta, x, y): return 1.0 - (sum_of_squared_errors(alpha, beta, x, y) / total_sum_of_squares(y)) # some helpful function: def numpy_covariance(x, y): x_ = np.array(x) - np.average(x) y_ = np.array(y) - np.average(y) return np.dot(x_, y_) / (len(x) -1) def numpy_correlation(x, y): return numpy_covariance(x, y) / (np.std(x) * np.std(y)) # NOTE: Given the beta as # beta = correlation(x, y) * std(y) / std(x) # = covariance(x, y) / std(x) / std(y) * std(y) / std(x) # = covariance(x, y) / (std(x) * std(x)) # very strange! # reference to the multipleRegression.py
df91e62325b0c4495d80c1204ba6a33ecbcace48
Ivanor12/EjercicioPython
/holamundo.py
1,727
3.53125
4
from pathlib import Path import requests import os #direccion API publica que voy a utilizar #https://docs.thecatapi.com/ try: def menu(): os.system('cls') print("\t1 - Referencias API y codigos de ejemplo") print("\t2 - Foto de un gato al azar") opcion=int(input("Selecciona una opcion : ")) return (opcion) api_address="https://www.etnassoft.com/api/v1/get/?keyword=python&count_items=true&decode=true" resp = requests.get(api_address) if resp.status_code==200: json_data=json.loads(resp.content) print(type(json_data)) print("Referencias API y codigos de ejemplo : %s"%json_data.get('texto')) def gatos_categoria(): categoria=input ("Introduce la categoria de gatos sobre la cual quieres hacer la consulta : ") api_address="https://www.etnassoft.com/api/v1/get/?category=%s&criteria=most_viewed&decode=true"%categoria resp = requests.get(api_address) if resp.status_code==200: json_data=json.loads(resp.content) contador=1 def fotos_gato_al_azar(): api_address="https://www.etnassoft.com/api/v1/get/?keyword=python&lang=spanish&last_year&decode=true" resp = requests.get(api_address) if resp.status_code==200:#todo correcto json_data=json.loads(resp.content) print(json_data) while True: opcion=menu() if opcion==1: categoria_gatos() elif opcion==2: fotos_gatos_al_azar() elif opcion==3: break input("Pulse una tecla para terminar...") except: print("Ha ocurrido algun error")
682e7c731987b6bc48902f5c97fd3d49b6c1a393
mattster895/MD-MARRFB-Assembler
/assembler/parser.py
4,684
3.703125
4
import sys import re import code import os from assembler.instruction_patterns import INSTRUCTION_PATTERNS from assembler.error import SyntaxError class Parser(): """ The main parser Separates and parses the lines of instructions in an assembly file. Class Variables: file - A file object of the input file. outputfile - A file object of the output file. input_lines - An array of strings that contain every line of the input file instruction_lines - A tuple of every instruction and the original line index it was on. mntdw_lines - An array of strings that are compiled machine code labels - A dictionary of labels and their index in instruction_lines """ mntdw_lines = [] instruction_lines = [] labels = {} # The initial fuction that opens the file, reads it and stores it in memory. def __init__(self, inputfile): self.file = open(inputfile, "r") self.input_lines = self.file.read().split("\n") self.file.close() # A function that handles the assembly of all the code. def assemble(self): self.__remove_whitespace() self.__parse() # This function saves the assembled file to the outputfile path. It removes # the old one if it exists. def saveFile(self, outputfile): try: os.remove(outputfile) except OSError: pass self.outputfile = open(outputfile, 'w') self.outputfile.write("\n".join(self.mntdw_lines)) self.outputfile.close() # This functioin creates labels and removes white space from the input file. def __remove_whitespace(self): for index, line in enumerate(self.input_lines): # Remove white space characters new_line = re.sub(r'\s+', '', line) # REMOVEs COMMENTS from input_lines new_line = re.sub(r'(#|;).*$', '', new_line) # Check if new line is a label. # TODO: Allow labels to be on the same line as an instruction. if re.match(r'^[a-zA-Z]+\w+:+$', new_line): # store the name and index (relative to instruction_lines) of the label self.labels[new_line[:-1]] = len(self.instruction_lines) # labels aren't an instruction so we don't need to assemble them. continue # Ignore lines that are blank if new_line == "": continue # New line should be ready to do self.instruction_lines.append((new_line, index)) # This function starts the parsing process for all the input file lines. def __parse(self): for index, instruction_tuple in enumerate(self.instruction_lines): line = instruction_tuple[0] try: assembled = self.__parseLine(instruction_tuple, index) if not assembled: raise SyntaxError("Unable to parse the above line.") self.mntdw_lines.append(assembled) except SyntaxError as error: print("Syntax Error on line " + str(instruction_tuple[1] + 1) + " (Snippet shown below)") print(self.input_lines[instruction_tuple[1]]) if len(error.args) > 0: print(error) sys.exit(0) # This function parses an individual line. It is repsonsible for calling # the instruction parser associated with the line. def __parseLine(self, instruction_tuple, address): instruction = instruction_tuple[0] # go through every instruction pattern and see if it's a match. for pattern in INSTRUCTION_PATTERNS: # create a regex object and matches it with the instruction. regex = re.compile(pattern[0]) if regex.match(instruction): # remove the instruction word from the instruction. instruction_params = re.sub(regex, '', instruction) # If instruction parameters exist split them by commas. if instruction_params: instruction_params = instruction_params.split(',') else: instruction_params = [] # Call the instruction parser function and give it the # instruction object. return pattern[1]({ 'params': instruction_params, 'address': address, 'line': instruction_tuple[1], 'complete_instruction': instruction, 'labels': self.labels, }) raise SyntaxError
6604c04c1a4f0cad9d7cd35c878d195bd57cb625
nataliatymk/Exercise_checkio
/Elementary/between_markers_simplified.py
1,606
4.5
4
# You are given a string and two markers (the initial one and final). You have to find a substring enclosed between these two markers. But there are a few important conditions. # This is a simplified version of the Between Markers mission. # The initial and final markers are always different. # The initial and final markers are always 1 char size. # The initial and final markers always exist in a string and go one after another. # Input: Three arguments. All of them are strings. The second and third arguments are the initial and final markers. # Output: A string. # def between_markers(text: str, begin: str, end: str) -> str: # if text.startswith(begin): # for t in text.split(end): # if t.startswith(begin): # return t[1:] # else: # for t in text.split(begin): # if t.endswith(end): # return t[:-1] def between_markers(text: str, begin: str, end: str) -> str: return text[text.index(begin)+1:text.index(end)] if __name__ == '__main__': print('Example:') print(between_markers('What is >apple<', '>', '<')) print(between_markers("[an apple]","[","]")) print(between_markers(">Apple< is simple",">","<")) print(between_markers('>apple<', '>', '<')) # These "asserts" are used for self-checking and not for testing assert between_markers('What is >apple<', '>', '<') == "apple" assert between_markers('What is [apple]', '[', ']') == "apple" assert between_markers('What is ><', '>', '<') == "" assert between_markers('>apple<', '>', '<') == "apple" print('Done!')
b9b3bdc3c0b7673e12441a45fb29ddad8f1b1f1b
yaoxin502/Homework
/三角形/条件语句.py
714
3.859375
4
# age = int(input('输入年龄')) # if age >18: # print(f'您输入的年龄是{age}','已成年,可以上网') # else : # print(f'您输入的年龄是{age}','未成年,不能上网') # a = int(input('输入年龄')) # if a < 18: # print(f'您输入的年龄是{a}','童工,违法') # elif (a >= 18 and a <=60): # print(f'您输入的年龄是{a}','正常工作年龄,合法') # else: # print(f'您输入的年龄是{a}','退休') # print('结束') money = int(input('是否有钱')) if money == 1: print('可以上车') seat = int(input('是否有座')) if seat == 1: print('可以坐着') else: print('站着') else: print('不能上车')
403acba161f20e841cca59627dabe5001a42107d
StasOverflow/stm32_flash
/app/back/utils.py
477
3.96875
4
def get_dict_attr(obj, attr): """ Looks up attr in a given object's __dict__, and returns the associated value if its there. If attr is not a key in that __dict__, the object's MRO's __dict__s are searched. If the key is not found, an AttributeError is raised. """ for obj in [obj] + obj.__class__.mro(): # print(obj.__dict__) if attr in obj.__dict__: return obj.__dict__[attr] raise AttributeError
c0388cdcc6923088f1f7c83a7eb69890f19412c1
richardlynnchild/machine-learning
/Ensemble Learning/DecisionTree.py
6,180
3.84375
4
''' Author: Richard Child This class implements a Decision Tree learning algorithm, ID3. The function will return a Node that contains the information about how to predict labels based on features. The Predict function will follow the ID3 produced Node and make a prediction. ''' from Node import Node import operator import math import copy class DecisionTree: def __init__(self, node): self.root = node ######################################## #### Several Helper Functions #### ######################################## '''Return the most common value of the specified column index''' def __most_common__(S,index): term_set = set() term_counts = dict() for example in S: val = example[index] term_set.add(val) for term in term_set: term_counts[term] = 0 for term in term_set: for example in S: if(example[index] == term): term_counts[term] += 1 return max(term_counts,key=term_counts.get) '''Return the Attribute that best splits the data set''' def __best_split__(S,Columns,Attributes,Labels,func,D): attr_gains = dict() for attribute,a_values in Attributes.items(): attr_gains[attribute] = __gain__(S,Columns,attribute,a_values,Labels,func,D) return max(attr_gains,key=attr_gains.get) '''Calculate the information gain of splitting the dataset S by the given attribute. func is the function to use to calculate the information gain, can use: -- __entropy__ -- __gini__ -- __majority_error__ Return a float.''' def __gain__(S,Columns,attribute,a_values,Labels,func,D): gain = func(S,Labels,D) for a_value in a_values: S_v,D_v = __subset__(S,Columns,attribute,a_value,D) gain -= (len(S_v)/len(S)*func(S_v,Labels,D_v)) return gain ''' Calculate the entropy of the given dataset with given Labels''' def __entropy__(S,Labels,D): prob_dict = __probabilities__(S,Labels,D) entropy = 0.0 for prob in prob_dict.values(): if prob == 0.0: continue entropy -= (prob*math.log2(prob)) return entropy '''Calculate the Gini Index of the given dataset and given Labels''' def __gini__(S,Labels,D): prob_dict = __probabilities__(S,Labels,D) gini = 1.0 for prob in prob_dict.values(): gini -= (prob**2) return gini '''Calculate the Majority Error for the dataset given Labels''' def __majority_error__(S,Labels,D): prob_dict = __probabilities__(S,Labels,D) majority_error = 1 - max(prob_dict.values()) return majority_error '''Calculate the probability of each Label in S. Store them in a dictionary {'Label':p} where p is float.''' def __probabilities__(S,Labels,D): prob_dict = dict() for label in Labels: prob_dict[label] = 0 for label in Labels: for i,example in enumerate(S): if example[-1] == label: prob_dict[label] += D[i] for label,count in prob_dict.items(): if len(S) == 0: prob_dict[label] = 0.0 else: prob_dict[label] = count/len(S) return prob_dict '''Returns a subset of S where each example has A=attr_value''' def __subset__(S,Columns,A,attr_value,D): S_v = [] D_v = [] for i,example in enumerate(S): if example[Columns.index(A)] == attr_value: S_v.append(example) D_v.append(D[i]) return S_v,D_v '''Perform the ID3 algorithm on dataset S. Return a Node that has an attribute label with branches to other Nodes, or is a leaf node and contains only a Label. Column - list of column names in dataset (attribute names) Attributes - dictionary of attribute name -> values (i.e. Temp:['hot','cold']) Labels - set of values example can evaluate to (the prediction/result of example)''' def ID3(S,Columns,Attributes,Labels,D,func=__gini__,max_depth=1,current_depth=0): # If all examples have same label, return leaf node if(len(Labels) == 1): leaf_name = str(Labels.pop()) return Node(leaf_name) # If no more attributes to split on, return leaf with # most common label. if(len(Attributes) == 0): return Node(str(__most_common__(S,len(Columns)-1))) # If reached the max tree depth, return leaf node # with most common label. if max_depth == current_depth: return Node(str(__most_common__(S,len(Columns)-1))) A = __best_split__(S,Columns,Attributes,Labels,func,D) root = Node(str(A)) for attr_value in Attributes[A]: S_v,D_v = __subset__(S,Columns,A,attr_value,D) if len(S_v) == 0: root.branches[attr_value] = Node(str(__most_common__(S,len(Columns)-1))) else: Attributes_v = copy.deepcopy(Attributes) Attributes_v.pop(A) Labels_v = set() for example in S_v: Labels_v.add(example[len(example)-1]) root.branches[attr_value] = ID3(S_v,Columns,Attributes_v,Labels_v,D_v,func,max_depth,current_depth+1) return root '''Given a test example, use a DecisionTree to predict the test example's label. If predicted correctly, return True, otherwise return False.''' def Predict(example,tree,Columns): actual_label = example[len(example)-1] current = tree # Go until reach a leaf node while not current.isLeaf(): # Get the attribute to decide on decision_attr = current.name # Get the value of that attribute from example attr_val = example[Columns.index(decision_attr)] # Traverse tree based on example values current = current.branches[attr_val] if current.name == actual_label: return True else: return False ''' Given input example on the tree return the label predicted. ''' def predict(example,tree,Columns): current = tree # Go until reach a leaf node while not current.isLeaf(): # Get the attribute to decide on decision_attr = current.name # Get the value of that attribute from example attr_val = example[Columns.index(decision_attr)] # Traverse tree based on example values current = current.branches[attr_val] return current.name
80888c9fa57e45009338bb6cf1076bdbd5d2afcd
darr/offer_algri
/offer_algri/把数组排成最小的数/p.py
645
3.640625
4
#!/usr/bin/python # -*- coding: utf-8 -*- ##################################### # File name : p.py # Create date : 2018-07-23 08:49 # Modified date : 2018-07-23 13:04 # Author : DARREN # Describe : not set # Email : lzygzh@126.com ##################################### from functools import cmp_to_key class Solution: def PrintMinNumber(self, numbers): if numbers == None or len(numbers) <= 0: return '' strList = [] for i in numbers: strList.append(str(i)) key = cmp_to_key(lambda x, y: int(x+y)-int(y+x)) strList.sort(key=key) return ''.join(strList)
157b033e0bad665eb9ed921537c225aeb9e45828
Khalil-Zaman/HighLow-Game
/Game.py
2,893
3.6875
4
import random printplay = False cards = [] def deck(): for i in range(1, 53): cards.append(i) def print_card(i): i = i % 13 if i == 0: return 'A' elif i == 12: return 'K' elif i == 11: return 'Q' elif i == 10: return 'J' else: i = i + 1 return str(i) deck() class Player: player_cards = [] player_number = 0 cards = [] def __init__(self, player_number): self.player_cards = [] self.player_number = player_number for i in range(0, 26-len(self.player_cards)): card = random.randint(0, len(cards)-1) self.player_cards.append(cards[card]) cards.pop(card) def no_cards(self): return len(self.player_cards) def print_cards(self): print("Player " + str(self.player_number) + ". Cards: ", end="") for i in range(0, len(self.player_cards)): print(print_card(self.player_cards[i]), end=" ") print("") def set_cards(self, cs): self.player_cards.clear() for c in cs: self.player_cards.append(c) def play(self): if len(self.player_cards) > 0: c = self.player_cards[0]%13 self.player_cards.pop(0) return c else: return -1 def add(self, cs): for c in cs: self.player_cards.append(c) def play_game(iteration_number = 1000): won = [] iterations = 1 player_won = random.randint(1, 2) while ((player1.no_cards() > 0) and (player2.no_cards() > 0)) and iterations <= iteration_number: if player_won == 1: c1 = player1.play() c2 = player2.play() won.append(c1) won.append(c2) if c1 > c2: player1.add(won) won.clear() elif c2 > c1: player2.add(won) won.clear() else: c1 = player1.play() c2 = player2.play() won.append(c2) won.append(c1) if c1 > c2: player1.add(won) won.clear() elif c2 > c1: player2.add(won) won.clear() print("Iteration " + str(iterations)) player1.print_cards() player2.print_cards() iterations += 1 print("") def hack_the_game(): player1.set_cards([ 12, 11, 10, 9, 8, 7, 6, 25, 24, 23, 22, 21, 20, 21, 38, 37, 36, 35, 34, 33, 51, 50, 49, 48, 47, 46]) player2.set_cards([ 1, 2, 3, 4, 5, 13, 14, 15, 16, 17, 18, 19, 26, 27, 28, 29, 30, 31, 32, 39, 40, 41, 42, 43, 44, 45]) player1 = Player(1) player2 = Player(2) print("Initial cards: ") player1.print_cards() player2.print_cards() print("") #hack_the_game() play_game(1000)
8fe44a5e380a4b97fe13d31be83f31f3cd40487d
Sudoka/CSE-231
/Honors/03/honors03.py
4,177
3.828125
4
# Honors Project 03 # Creates a population of bitstrings and introduces variation # Algorithm ''' Create 1st Generation For 2 individuals Append individual() to population Print Crossover to make "new" individuals Crossover Print individuals Mutation Mutate both w/ default rate Print Mutate each w/ specified rate Print ''' # Imports import pdb, random # Classes class individual(object): '''Stores a 100 character bitstring and its fitness''' def __init__(self): self.bitstring = self.genBitstring() self.genFitness() def __str__(self): return '%s : %d\n'%(self.bitstring, self.fitness) def flipBit(self, index): ''' Flips a given bit in a given bitString. Arguments: Bit Algorithm: If bit = 1, make it 0 If bit = 0, make it 0 Else can't happen ''' bitList = list(self.bitstring) if bitList[index] == '1': bitList[index] = '0' if bitList[index] == '0': bitList[index] = '1' else: print 'Can\'t happen.' self.bitstring = ''.join(bitList) def genBitstring(self): ''' Creates a 100 bit string of random bits. Returns: 100 bit string Algorithm: Seed random Create bitstring For 100 chars Randomly append 1 or 0 to bitList Merge bitList ''' random.seed() bitList = [] for i in range(1,101): bitList.append(str(random.randint(0,1))) bitString = ''.join(bitList) return bitString def genFitness(self): ''' Evaluates fitness based on number of 1 bits. Arguments: Bitstring Return: Fitness float Algorithm: Initialize count For each bit in string If 1, increment count ''' count = 0 for i in self.bitstring: if i == '1': count += 1 self.fitness = count def mutate(self, rate=7): ''' Mutates an individual. Arguments: individual of individual class, rate of mutation Algorithm: For each bit if random < rate flip bit Regen fitness ''' random.seed() for i in range(0, len(self.bitstring)): if random.randint(0,100) < rate: self.flipBit(i) self.genFitness() # Functions def crossover(ind1, ind2): ''' Performs double crossover on two individuals' bitstrings. Arguments: Two individuals of individual class Algorithm: Create bitLists Divide each bitList into three sections Slice at random points Swap center sections Change bitstrings Regen fitness ''' # Bitlists bitList1 = [i for i in ind1.bitstring] bitList2 = [i for i in ind2.bitstring] # Division random.seed() index1 = random.randint(0,98) index2 = random.randint(index1,100) newList1 = bitList1[:index1] + bitList2[index1:index2] + bitList1[index2:] newList2 = bitList2[:index1] + bitList1[index1:index2] + bitList2[index2:] newStr1 = ''.join(newList1) newStr2 = ''.join(newList2) ind1.bitstring, ind2.bitstring = newStr1, newStr2 ind1.genFitness() ind2.genFitness() # 2 individuals population = [] for i in range(0,2): population.append(individual()) # Print print 'Individuals:\n' for i in population: print i # Create new generation crossover(population[0], population[1]) print '\nNew individuals after crossover:\n' for i in population: print i # Default mutation print '\nMutated individuals:\n' for i in population: i.mutate() print i # Custom mutation for i in population: rate = int(raw_input('\nEnter a mutation rate percentage (1-100): ')) i.mutate(rate) print i
2570cd39f069accb7dbc6d76b17bca1903876739
dk-sirvi/live_weather_application
/liveweather.py
1,522
3.515625
4
from tkinter import * from tkinter import messagebox import requests url = "https://api.openweathermap.org/data/2.5/weather?appid=4c22d6872257394dab6f68e9242a1470&q={}" def getweather(city): json_data = requests.get(url.format(city)).json() temp_far = json_data['main']['temp']-273.15 #tempratur temp_cel= (json_data['main']['temp']-273.15)*9/5+32 main = json_data['weather'][0]['main'] #enviourment condition cont = json_data['sys']['country'] icon = json_data['weather'][0]['icon'] name = json_data['name'] print(json_data) final=(temp_far,temp_cel,main,name,cont) return final def search(): city = city_text.get() weather = getweather(city) if weather: location_lbl['text']='{} {}'.format(weather[3],weather[4]) temprature_l['text']='{:.2f} C, {:.2f} F'.format(weather[0],weather[1]) weather_l['text']='{}'.format(weather[2]) else: messagebox.error("{} city cannnot found".format(city)) app = Tk() app.title("Weather application") app.geometry('700x350') city_text = StringVar() city_entry = Entry(app,textvariable=city_text) city_entry.pack() search_btn=Button(app,text='search weather',width=20, command=search) search_btn.pack() location_lbl = Label(app,text="",font=('bold',20)) location_lbl.pack() temprature_l = Label(app,text='') temprature_l.pack() weather_l = Label(app,text='') weather_l.pack() app.mainloop()
29bc054ba44334feaf1d465146ed7591437c8b97
Mand09/CS104-01
/test score average.py
430
4.3125
4
howManyEntered = 0 total=0 average = 0 howMany = int (input ("How many test scores would you like to average?")) while (howManyEntered < howMany): howManyEntered=howManyEntered + 1 testScores= input("Enter Test score " + str(howManyEntered)+ ": ") testScore=float(testScores) total= total+testScore average= total/howManyEntered print("The average of you test scores is: " + str(average) +"%")
4b1bf3e1079435c2bc05f09385ba90a4611151d6
Ressull250/code_practice
/part2/24.py
505
3.640625
4
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ start = head while head and head.next: tmp = head.val head.val = head.next.val head.next.val = tmp head = head.next.next return start a = ListNode(1) Solution().swapPairs(None)
afd51ca5f2d3de6f06e064436a7a55df53f7d36d
adrianocerutti/calculo_taxa_frequencia
/calculo_taxa_frequencia.py
624
3.984375
4
numero_empregados = float(input("Digite o número de empregados: ")) jornada_mensal_trabalho = float(input("Digite a jornada mensal de trabalho: ")) numero_acidentes = float(input("Digite o número de acidentes: ")) dias_perdidos = float(input("Digite o número de dias perdidos: ")) horas_homens_trabalhadas = numero_empregados * jornada_mensal_trabalho taxa_frequencia = (numero_acidentes * 1000000) / horas_homens_trabalhadas resultado = "Taxa de Frequência: {0}".format(taxa_frequencia) #Para formatar o resultado com 2 casas decimais #resultado = "Taxa de Frequência: {0:.2f}".format(taxa_frequencia) print(resultado)
cf158e8ebe6b12d5efdfb320700c675b99795b71
BravoDelta151/CircuitPython_Misc
/simon_game.py
5,937
3.75
4
# A Simon game for Circuit Playground Express # Press button A or button B to start. Button B will include number correct # after each round of play. # # A round in the game consists of the device lighting up one or more buttons # in a random order, after which the player must reproduce that order by pressing # the the touch pad by the lights. There are two pads by each of the red (A4, A5), # green (A6, A7) and blue (A2, A3) lights, but only one by the yellow light(A1). # As the game progresses, the speed and the number of buttons to be pressed increases. # # If a mistake is made, an error tone will play followed by the correct light that was # next in the sequence blinking twice. Then the game will reset automatically. # # The switch is used as an on/off. if this doesn't appear to start, try changing the # switch... # # Author: David Boyd # License: MIT License (https://opensource.org/licenses/MIT) from adafruit_circuitplayground.express import cpx import time import array import random # ID, Pixel Index, Tone, high, low RED_ID = [1, 1, 440, (125,0,0), (5,0,0)] YELLOW_ID = [2, 6, 550, (125,125,0), (5,5,0)] GREEN_ID = [3, 3, 330, (0, 125, 0),(0,5,0)] BLUE_ID = [4, 8, 660, (0,0,125),(0,0,5)] # simons sequence simon = array.array('b',) # score needed to win to_win = 35 # note_e = 330 # green # note_a = 440 # red # note_cSH = 550 # yellow # note_eH = 660 # blue note_bad = 240 def display_score(score): ''' display the score ''' print("Score: ", score) if len(simon) >= to_win: for i in range(16): play_color_tone((i % 4) + 1, .2) print("Yay! You beat the game") def reset(): ''' Reset game ''' # print('reset') cpx.pixels.fill((0,0,0)) cpx.pixels.brightness = 0.3 # this will initialize the neopixels for i in range(5): play_color_tone(i, .5 ) # seed random generator random.seed(int((cpx.temperature + cpx.light) * time.monotonic())) def play_color_tone(color_id, wait = 1.0): ''' Play selected tone and highlight color ''' if color_id == RED_ID[0]: # RED cpx.pixels[RED_ID[1]] = RED_ID[3] cpx.play_tone(RED_ID[2], wait) cpx.pixels[RED_ID[1]] = RED_ID[4] elif color_id == YELLOW_ID[0]: # YELLOW cpx.pixels[YELLOW_ID[1]] = YELLOW_ID[3] cpx.play_tone(YELLOW_ID[2], wait) cpx.pixels[YELLOW_ID[1]] = YELLOW_ID[4] elif color_id == GREEN_ID[0]: # GREEN cpx.pixels[GREEN_ID[1]] = GREEN_ID[3] cpx.play_tone(GREEN_ID[2], wait) cpx.pixels[GREEN_ID[1]] = GREEN_ID[4] elif color_id == BLUE_ID[0]: # BLUE cpx.pixels[BLUE_ID[1]] = BLUE_ID[3] cpx.play_tone(BLUE_ID[2], wait) cpx.pixels[BLUE_ID[1]] = BLUE_ID[4] else: cpx.play_tone(note_bad, wait) def play_sequence(): ''' Play simon's sequence ''' # set speed for difficulty if len(simon) > 0: speed = max(1.0 - (len(simon) * 4 / 100), .2) for i in simon: time.sleep(max(speed - 0.5, .02)) play_color_tone(i,speed) def get_touch(): ''' Get Touch pad ''' while cpx.switch: # this will handle if the switch is turned off at this stage if cpx.touch_A4 or cpx.touch_A5: return RED_ID[0] if cpx.touch_A6 or cpx.touch_A7: return GREEN_ID[0] if cpx.touch_A1: return YELLOW_ID[0] if cpx.touch_A2 or cpx.touch_A3: return BLUE_ID[0] def validate_choice(idx, touch): ''' checks if the players choice is correct and plays appropriate tone ''' if simon[idx] == touch: play_color_tone(touch, 0.7) return True else: play_color_tone(0, 1.5) # let them know what the correct color was... time.sleep(1) play_color_tone(simon[idx], 0.25) play_color_tone(simon[idx], 0.25) time.sleep(1) return False def players_guess(): ''' gets the players guess at the sequence ''' guess = array.array('b',) correct = True idx = 0 while cpx.switch and correct and idx < len(simon): correct = validate_choice(idx, get_touch()) idx += 1 return correct def add_to_sequence(): ''' adds a random number to the sequence ''' rand_num = random.randint(1,4) simon.append(rand_num) def play_game(verbose_score): ''' Main game loop ''' winning = True while cpx.switch and winning: # add to sequence add_to_sequence() # play tones play_sequence() # wait for player input cpx.red_led = True winning = players_guess() cpx.red_led = False if len(simon) >= to_win: break; if winning: if verbose_score: display_score(len(simon)) time.sleep(1) while cpx.switch: reset() if len(simon) > 0: del simon simon = array.array('b',) # (i for i in range(35))) # test score # print a blank line... print() print("Press Button A or Button B to start new game") # wait for the player to push a button to restart waiting = True verbose_score = False while waiting and cpx.switch: if cpx.button_a: waiting = False if cpx.button_b: verbose_score = True waiting = False time.sleep(0.1) play_game(verbose_score) display_score(len(simon)) if not cpx.switch: cpx.pixels.fill((0, 0, 0)) print("switch is off")
8ebc3a2dce110edfa99935bbbdd7811cab657789
adihendro/tucil1
/tucil-009-2.py
1,455
3.5625
4
# Full Vigenere Cipher import string import random # Import uppercase letters LETTERS = string.ascii_uppercase ORDINAL_A = ord('A') def createMatrix(): matrix = [0 for _ in range(26)] for i in range(26): matrix[i] = random.sample(LETTERS,26) return matrix def clearText(text): clearedText = [] for i in range (len(text)): if (text[i].isalpha()): clearedText.append(text[i]) return ''.join(clearedText) def extendKey(text, key): key = list(key) for i in range (len(text) - len(key)): key.append(key[i % len(key)]) return ''.join(key) def encVigenere(text, key): cipher = [] for i in range (len(text)): cipher.append(matrix[ord(key[i]) - ORDINAL_A][ord(text[i]) - ORDINAL_A]) return ''.join(cipher) def decVigenere(cipher, key): text = [] for i in range (len(cipher)): row = ord(key[i]) - ORDINAL_A n = matrix[row].index(cipher[i]) text.append(LETTERS[n]) return ''.join(text) def main(): # Input text text = input().upper() # Input key key = input().upper() clearedText = clearText(text) clearedKey = clearText(key) print(clearedText) print(extendKey(clearedText, clearedKey)) cipher = encVigenere(clearedText, extendKey(clearedText, clearedKey)) print(cipher) print(decVigenere(cipher, extendKey(clearedText, clearedKey))) matrix = createMatrix() # print(matrix) main()
f163b8cf179709f6609eb2344da08d313859301d
tjligang/Python3
/function/basic.py
1,108
4.125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # 内置函数的使用 x = abs(100) y = abs(-20) print(x, y) print('max(1, 2, 3) =', max(1, 2, 3)) print('min(1, 2, 3) =', min(1, 2, 3)) print('sum([1, 2, 3]) =', sum([1, 2, 3])) # 函数名其实就是指向一个函数对象的引用,完全可以把函数名赋给一个变量,相当于给这个函数起了一个“别名” a = abs # 变量a指向abs函数 print(a(-1)) # 定义函数 import math def my_abs(x): if not isinstance(x, (int, float)): raise TypeError('bad operand type') if x >= 0: return x else: return -x print(my_abs(123), my_abs(-123), my_abs('123')) # 返回多值的函数,返回的是一个tuple,可以通过序列解包进行赋值 import math def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny x, y = move(100, 100, 60, math.pi / 6) print(x, y) t = move(100, 100, 60, math.pi / 6) print(t) # 没有return或只写return的函数,返回None def func(): print('hello, world') return print(func())
b782267d11c6fa54a87a7ed6c5c880fec0e3d294
beidou9313/deeptest
/第一期/广州-Aimee/python/lesson05_iter.py
1,624
4.21875
4
# coding = utf-8 __author__ = 'Aimee' #迭代器是一个可以记住遍历的位置的对象。 #迭代器对象从集合的第一个元素开始访问,直到所有的元素被访问完结束。 # 迭代器只能往前不会后退。 # 迭代器有两个基本的方法:iter() 和 next()。 # 字符串,列表或元组对象都可用于创建迭代器 # import sys # # if __name__ == "__main__": # # tuple = (1,2,3,4,5,6) # #创建迭代器 # it = iter(tuple) # #打印第一个元素 # print("第一个元素: %s" % next(it)) # #打印第二个元素 # print("第二个元素: %s" % next(it)) # # #使用for循环来遍历迭代器对象 # it_for = iter(tuple) # print("for 循环遍历迭代器:") # for i in it_for: # print(i,end=",") # # print("\n") # # #while 结合next遍历迭代器 # print("while 循环遍历迭代器:") # it_while = iter(tuple) # while True: # try: # print(next(it_while)) # except: # sys.exit() # #s生成器返回的是一个迭代器的函数 import sys def fibonacci(n): # 初始化变量 a,b,count = 0,1,0 while True: if count > n: return yield a a,b = b,a+b print("%d,%d" %(a,b)) count = count +1 if __name__ == "__main__": f = fibonacci(10) #f是一个迭代器,由生成器返回生成 while True: try: print(next(f),end=",") except: sys.exit()
b1add498664650d3d3501fa10463ecf0af9a870f
ThallesTorres/Curso_Em_Video_Python
/Curso_Em_Video_Python/ex036.py
1,090
4.3125
4
# Ex: 036 - Escreva um progrma para aprovar o empréstimo bancário para a compra # de uma casa. O programa vai perguntar o valor da casa, o salário do comprador # e em quantos anos ele vai pagar. Calcule o valor da prestação mensal, dabendo # que eka não pode exceder 30% do salário ou então o empréstimo será negado. print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Seja bem-vindo! --Exercício 036 -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ''') print('-=-Preencha os Dados-=- ') valor_casa = int(input('Valor da Casa: R$')) salario = int(input('Salário do Comprador: R$')) anos = int(input('Em quantos Anos: ')) meses = anos * 12 prestacao = valor_casa / meses print('-=-Dados Finais-=-') print(f'Valor da Casa: R${valor_casa} \nAnos: {anos} \nMeses: {meses} \nPrestações: R${prestacao:.2f}') if prestacao >= salario * 30 / 100: print('Empréstimo Não Aprovado!!)') else: print('Empréstimo Aprovado!!') print(''' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- --Obrigado pelo uso! --Desenvolvido por Thalles Torres -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-''')
4dbbc7a8194e92b9179dd3075335b3ef0ff81c6d
wnelson01/gess
/GessGame.py
19,587
3.84375
4
# Name: Wade Nelson # Date: 6/4/2020 # Description: Gess # used for converting the algebraic notation of the external board to the row-column structure of the internal board rows = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'] cols = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't'] class GessGame: """represents a game of Gess with a board and pieces""" def __init__(self): """ initalizes the board as a 2 dimensional list with an initial configuration of stones initliazes a dictionary of every potential piece initalizes the player turn tracker initalizes the game state loads the board state into the dictionary of piece objects """ self._board = [ [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4], # 00 20 [4, 0, 2, 0, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 2, 0, 4], # 01 19 [4, 2, 2, 2, 0, 2, 0, 2, 2, 2, 2, 0, 2, 0, 2, 0, 2, 2, 2, 4], # 02 18 [4, 0, 2, 0, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 0, 2, 0, 2, 0, 4], # 03 17 [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], # 04 16 [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], # 05 15 [4, 0, 2, 0, 0, 2, 0, 0, 2, 0, 0, 2, 0, 0, 2, 0, 0, 2, 0, 4], # 06 14 [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], # 07 13 [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], # 08 12 [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], # 09 11 [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], # 10 10 [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], # 11 09 [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], # 12 08 [4, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 4], # 13 07 [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], # 14 06 [4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4], # 15 05 [4, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 4], # 16 04 [4, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 4], # 17 03 [4, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 4], # 18 02 [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4], # 19 01 # 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 # 0A 0B 0C 0D 0E 0F 0G 0H 0I 0J 0K 0L 0M 0N 0O 0P 0Q 0R 0S 0T ] self._prev_board = self._board.copy() self._piece = {} self._player_turn = 'BLACK' self._game_state = 'UNFINISHED' self.board_to_pieces() def board_to_pieces(self): """takes the layout of stones on the board and loads the configuration of the stones into piece objects""" for i in range(18, 0, -1): for j in range(1, 19): row = 18 - j col = i - 1 self._piece[cols[i] + rows[j]] = Piece( self._board[row + 1][col + 1], # middle (mi) self._board[row + 0][col + 1], # up (up) self._board[row + 2][col + 1], # down (do) self._board[row + 1][col + 0], # left (le) self._board[row + 1][col + 2], # right (ri) self._board[row + 0][col + 2], # upper right (ur) self._board[row + 2][col + 2], # lower right (lr) self._board[row + 2][col + 0], # lower left (ll) self._board[row + 0][col + 0], # upper left (ul) ) def get_game_state(self): """returns the current game state""" return self._game_state def resign_game(self): """resigns game""" if self._player_turn == 'BLACK': self._game_state = 'WHITE_WON' if self._player_turn == 'WHITE': self._game_state = 'BLACK_WON' def print_board(self): """displays the board for debug purposes""" if self._player_turn == 'BLACK': # or self._player_turn =='WHITE' row = 20 for i in self._board: line = '' for j in i: if j == 0: line += '|' + ' ' if j == 1: line += '|b' if j == 2: line += '|w' if j == 4: line += ' ' # else: # line += str(j) + ' ' if row < 10: print(str(row) + ' ' + line) else: print(str(row) + ' ' + line) row -= 1 print(' A B C D E F G H I J K L M N O P Q R S T') if self._player_turn == 'WHITE': row = 1 for i in reversed(self._board): line = '' for j in reversed(i): if j == 0: line += '|' + ' ' if j == 1: line += '|b' if j == 2: line += '|w' if j == 4: line += ' ' # else: # line += str(j) + ' ' if row < 10: print(str(row) + ' ' + line) else: print(str(row) + ' ' + line) row += 1 print(' T S R Q P O N M L K J I H G F E D C B A') def make_move(self, start, stop): """makes a move""" prev_board = [x[:] for x in self._board] row = start[1::] col = start[0] black_ring = None white_ring = None # if there are both black and white stones in the prospective piece's configuration, the piece is invalid if 1 in self._piece[start].get_cf() and 2 in self._piece[start].get_cf(): return False # The following 8 blocks look in all 8 directions and log all possible legal moves # up if self._piece[start].get_up()[1] == 1 and self._player_turn == 'BLACK' or self._piece[start].get_up()[ 1] == 2 and self._player_turn == 'WHITE': row = str(int(start[1::]) + 1) col = start[0] if self._piece[start].get_mi() == 0: moves = 2 else: moves = 18 try: while self._piece[col + row].get_up() == (0, 0, 0) and moves > 0: self._piece[start].set_mo(col + row) row = str(int(row) + 1) col = col moves -= 1 except KeyError: pass self._piece[start].set_mo(col + row) # print(self._piece[start].get_mo()) # down if self._piece[start].get_do()[1] == 1 and self._player_turn == 'BLACK' or self._piece[start].get_do()[ 1] == 2 and self._player_turn == 'WHITE': row = str(int(start[1::]) - 1) col = start[0] if self._piece[start].get_mi() == 0: moves = 2 else: moves = 18 try: while self._piece[col + row].get_do() == (0, 0, 0) and moves > 0: self._piece[start].set_mo(col + row) row = str(int(row) - 1) col = col moves -= 1 except KeyError: pass self._piece[start].set_mo(col + row) # print(self._piece[start].get_mo()) # left if self._piece[start].get_le()[1] == 1 and self._player_turn == 'BLACK' or self._piece[start].get_le()[ 1] == 2 and self._player_turn == 'WHITE': row = start[1::] col = chr((ord(start[0]) - 1)) if self._piece[start].get_mi() == 0: moves = 2 else: moves = 18 try: while self._piece[col + row].get_le() == (0, 0, 0) and moves > 0: self._piece[start].set_mo(col + row) row = row col = chr((ord(col) - 1)) moves -= 1 except KeyError: pass self._piece[start].set_mo(col + row) # print(self._piece[start].get_mo()) # right if self._piece[start].get_ri()[1] == 1 and self._player_turn == 'BLACK' or self._piece[start].get_ri()[ 1] == 2 and self._player_turn == 'WHITE': row = start[1::] col = chr((ord(start[0]) + 1)) if self._piece[start].get_mi() == 0: moves = 2 else: moves = 18 try: while self._piece[col + row].get_ri() == (0, 0, 0) and moves > 0: self._piece[start].set_mo(col + row) row = row col = chr((ord(col) + 1)) moves -= 1 except KeyError: pass self._piece[start].set_mo(col + row) # print(self._piece[start].get_mo()) # upper-right if self._piece[start].get_ur()[2] == 1 and self._player_turn == 'BLACK' or self._piece[start].get_ur()[ 2] == 2 and self._player_turn == 'WHITE': row = str(int(start[1::]) + 1) col = chr((ord(start[0]) + 1)) if self._piece[start].get_mi() == 0: moves = 2 else: moves = 18 try: while self._piece[col + row].get_ur() == (0, 0, 0, 0, 0) and moves > 0: self._piece[start].set_mo(col + row) row = str(int(row) + 1) col = chr((ord(col) + 1)) moves -= 1 except KeyError: pass self._piece[start].set_mo(col + row) # print(self._piece[start].get_mo()) # lower-right if self._piece[start].get_lr()[2] == 1 and self._player_turn == 'BLACK' or self._piece[start].get_lr()[ 2] == 2 and self._player_turn == 'WHITE': row = str(int(start[1::]) - 1) col = chr((ord(start[0]) + 1)) if self._piece[start].get_mi() == 0: moves = 2 else: moves = 18 try: while self._piece[col + row].get_lr() == (0, 0, 0, 0, 0) and moves > 0: self._piece[start].set_mo(col + row) row = str(int(row) - 1) col = chr((ord(col) + 1)) moves -= 1 except KeyError: pass self._piece[start].set_mo(col + row) # print(self._piece[start].get_mo()) # lower-left if self._piece[start].get_ll()[2] == 1 and self._player_turn == 'BLACK' or self._piece[start].get_ll()[ 2] == 2 and self._player_turn == 'WHITE': row = str(int(start[1::]) - 1) col = chr((ord(start[0]) - 1)) if self._piece[start].get_mi() == 0: moves = 2 else: moves = 18 try: while self._piece[col + row].get_ll() == (0, 0, 0, 0, 0) and moves > 0: self._piece[start].set_mo(col + row) row = str(int(row) - 1) col = chr((ord(col) - 1)) moves -= 1 except KeyError: pass self._piece[start].set_mo(col + row) # print(self._piece[start].get_mo()) # upper-left if self._piece[start].get_ul()[2] == 1 and self._player_turn == 'BLACK' or self._piece[start].get_ul()[ 2] == 2 and self._player_turn == 'WHITE': row = str(int(start[1::]) + 1) col = chr((ord(start[0]) - 1)) if self._piece[start].get_mi() == 0: moves = 2 else: moves = 18 try: while self._piece[col + row].get_ul() == (0, 0, 0, 0, 0) and moves > 0: self._piece[start].set_mo(col + row) row = str(int(row) + 1) col = chr((ord(col) - 1)) moves -= 1 except KeyError: pass self._piece[start].set_mo(col + row) # print(self._piece[start].get_mo()) # if the intended move is within the starting piece's potential legal moves if stop in self._piece[start].get_mo(): stop_col = cols.index(stop[0]) stop_row = 20 - int(stop[1::]) start_col = cols.index(start[0]) start_row = 20 - int(start[1::]) # store the start piece's initial configuration temp_mi = self._board[start_row][start_col] temp_up = self._board[start_row - 1][start_col] temp_do = self._board[start_row + 1][start_col] temp_le = self._board[start_row][start_col - 1] temp_ri = self._board[start_row][start_col + 1] temp_ur = self._board[start_row - 1][start_col + 1] temp_lr = self._board[start_row + 1][start_col + 1] temp_ll = self._board[start_row + 1][start_col - 1] temp_ul = self._board[start_row - 1][start_col - 1] # remove the starting piece self._board[start_row][start_col] = 0 self._board[start_row - 1][start_col] = 0 self._board[start_row + 1][start_col] = 0 self._board[start_row][start_col - 1] = 0 self._board[start_row][start_col + 1] = 0 self._board[start_row - 1][start_col + 1] = 0 self._board[start_row + 1][start_col + 1] = 0 self._board[start_row + 1][start_col - 1] = 0 self._board[start_row - 1][start_col - 1] = 0 # move the starting piece to the intended position self._board[stop_row][stop_col] = temp_mi self._board[stop_row - 1][stop_col] = temp_up self._board[stop_row + 1][stop_col] = temp_do self._board[stop_row][stop_col - 1] = temp_le self._board[stop_row][stop_col + 1] = temp_ri self._board[stop_row - 1][stop_col + 1] = temp_ur self._board[stop_row + 1][stop_col + 1] = temp_lr self._board[stop_row + 1][stop_col - 1] = temp_ll self._board[stop_row - 1][stop_col - 1] = temp_ul # update all pieces to represent the layout of the new board self.board_to_pieces() # remove any stones that fell into the out-of-bounds area during the move for i in range(20): self._board[0][i] = 4 self._board[i][19] = 4 self._board[19][i] = 4 self._board[i][0] = 4 # clean up any out-of-bounds squares (4's) that got moved onto the board for i in range(1, 19): for j in range(1, 19): if self._board[i][j] == 4: self._board[i][j] = 0 # look for rings for piece in self._piece: if self._piece[piece].get_cf() == [[1, 1, 1], [1, 0, 1], [1, 1, 1]]: black_ring = True if self._piece[piece].get_cf() == [[2, 2, 2], [2, 0, 2], [2, 2, 2]]: white_ring = True # if black has made a move that would result in no black ring, go back to the previous board state if black_ring is None and self._player_turn == 'BLACK': self._board = [i[:] for i in prev_board] self.board_to_pieces() # print('Cannot make a move that leaves the player with no ring') return False # if white has made a move that would result in no white ring, go back to the previous board state if white_ring is None and self._player_turn == 'WHITE': self._board = [i[:] for i in prev_board] self.board_to_pieces() # print('Cannot make a move that leaves the player with no ring') return False # if black has made a move that results in no white ring, black wins if black_ring is None and self._player_turn == 'WHITE': self._game_state = 'WHITE_WON' self._player_turn = 'NONE' # if white has made a move that results in no black ring, white wins if white_ring is None and self._player_turn == 'BLACK': self._game_state = 'BLACK_WON' self._player_turn = 'NONE' # take turns if self._player_turn == 'BLACK': self._player_turn = 'WHITE' else: self._player_turn = 'BLACK' # self.print_board() # print(self._player_turn) # print(self._game_state) return True # no legal moves else: return False class Piece: """represents a Piece with a 9 slot configuration""" def __init__(self, mi, up, do, le, ri, ur, lr, ll, ul): """middle (mi), upper (up), downward (do), left (le), right (ri), upper-right (ur), lower-right (lr), lower-left (ll), upper-left (ul), configuration (cf), and moves (mo) """ self._mi = mi # middle self._up = up # up self._do = do # down self._le = le # left self._ri = ri # right self._ur = ur # upper-right self._lr = lr #lower-right self._ll = ll #lower-left self._ul = ul #upper-left self._cf = [ [ul, up, ur], [le, mi, ri], [ll, do, lr], ] self._mo = [] def get_mi(self): """returns the middle slot's value""" return self._mi def get_up(self): """returns the upper row""" return (self._ul, self._up, self._ul) def get_do(self): """returns the downward row""" return (self._ll, self._do, self._lr) def get_le(self): """returns the left-most column""" return (self._ul, self._le, self._ll) def get_ri(self): """returns the right-most column""" return (self._ur, self._ri, self._lr) def get_ur(self): """returns the upper-right arrow""" return (self._ul, self._up, self._ur, self._ri, self._lr) def get_lr(self): """returns the lower-right arrow""" return (self._ur, self._ri, self._lr, self._do, self._ll) def get_ll(self): """returns the lower-left arrow""" return (self._lr, self._do, self._ll, self._le, self._ul) def get_ul(self): """returns the upper-left arrow""" return (self._ll, self._le, self._ul, self._up, self._ur) def get_cf(self): """returns the piece's configuration""" return self._cf def set_mo(self, mo): """appends a move to the piece's legal moves""" self._mo.append(mo) def get_mo(self): """returns the piece's legal moves""" return self._mo
be21758f44c6c2ca1e9f246bfadbcd9e2ff4df89
UmVitor/python_int
/ex092.py
986
3.9375
4
#Crie um programa que leia nome, ano de nascimento e carteira de trabalho e #cadastre-os(com idade) em um dicionario se por acaso a CTPS for diferente #de zero o funcionario receberá também o ano de contratação e o salario #Calcule e acrescente, além da idade, com quantos anos a pessoas vai se #aposentar. Considerando que a pessoas se aposente depois de 35 anos de colaboração from datetime import date ano_atual = date.today().year pessoas = dict() pessoas["nome"] = str(input('Nome: ')) pessoas["idade"] = (ano_atual - int(input("Ano de nascimento: "))) pessoas["ctps"] = (int(input("Carteira de trabalho (0 não tem): "))) if(pessoas["ctps"] > 0): pessoas["contratação"] = int(input("Ano de contratação: ")) pessoas["salário"] = float(input('Salário: ')) pessoas["Aposentadoria"] = (35 - (ano_atual - pessoas["contratação"])) + pessoas["idade"] print('-='*20) for k, v in pessoas.items(): print(f'{k} tem o valor {v}')
fc5ef64db740983f0b84a5965b911a88b1b64cc2
Neilqdddd/dsc-430
/hw3_1.py
2,131
3.703125
4
''' Yili Lin 2/19/2019 I have not given or received any unauthorized assistance on this assignment. ''' import random class SixSidedDie(): 'class of six side dice' def __init__(self,x=0): 'values of instance members' self.x=x def roll(self): 'function of roll dice' self.x = random.randrange(1, 7) return self.x def getFaceValue(self): 'return the value of the dice' return self.x def __repr__(self): 'string present the dice face' return f'SixSidedDie({self.x})' class TenSidedDie(SixSidedDie): 'class of ten side dice' def roll(self): 'function of roll dice' self.x = random.randrange(1, 11) return self.x def __repr__(self): 'string present the dice face' return f'TenSidedDie({self.x})' class TwentySidedDie(SixSidedDie): 'class of 20 side dice' def roll(self): 'function of roll dice' self.x = random.randrange(1, 21) return self.x def __repr__(self): 'string present the dice face' return f'TwentySidedDie({self.x})' class Cup(): 'class cup of hold the 6,10,20 dice' list_count = [] sum = 0 def __init__(self, sixside=1, tenside=1, twentyside=1): 'values of instance members' self.six = sixside self.ten = tenside self.twenty = twentyside def rollone(self,num,classname): 'roll one dice' for i in range(0,num): self.name=classname self.name.roll() self.list_count.append(self.name) self.sum+=classname.getFaceValue() def roll(self): 'roll all dice' self.rollone(self.six,SixSidedDie()) self.rollone(self.ten,TenSidedDie()) self.rollone(self.twenty,TwentySidedDie()) return self.sum def getSum(self): 'sum' return self.sum def __repr__(self): 'string the value of each dice' return (f'Cup({str(self.list_count)[1:-1]})')
ccbc6fa5047f9b3e7af52677332611cec7a03b83
sweavo/code-advent-2020
/day9_2.py
1,616
3.78125
4
import day9input import day9_1 """ After having some faulty insights, I am just going to brute force this. Mistakes made during design: assuming the sequence increases monotonically. It doesn't, though it does _tend_ to increase. This led to stopping the search as soon as a value greater than our target was found, which excluded possibilities. """ def pontoon( target, cards ): """ find a contiguous sequence of cards that sum to target, returning their indices >>> cards = [1, 10, 9, 2, 5] >>> target=20 >>> pontoon(target, cards) 3 >>> target 20 >>> pontoon(21, cards) >>> pontoon(21, cards[1:]) 3 >>> pontoon(21, cards[2:]) """ for index, candidate in enumerate(cards): target-=candidate if target==0: return index+1 def meta_pontoon( target, cards ): """ find a contiguous sequence of cards that sum to target, returning their indices >>> cards = [1, 10, 9, 2, 5] >>> meta_pontoon(21, cards) (1, 4) >>> cards[1:4] [10, 9, 2] >>> meta_pontoon(16, cards) (2, 5) """ for start in range(len(cards)): result = pontoon(target,cards[start:]) if result: return start, start+result def puzzle_answer( target, cards ): """ >>> puzzle_answer(127, day9_1.TEST_DATA) 62 """ start, stop = meta_pontoon( target, cards ) ordered_cards = sorted(cards[start:stop]) return ordered_cards[0] + ordered_cards[-1] def day9_2(): """ >>> day9_2() 104800569 """ return puzzle_answer( day9_1.day9_1(), day9input.DATA_STREAM )
db045ad5401ae427b6913fada237084df82dd634
luzap/intro_to_cs
/cs002/exer21.py
276
4.15625
4
"""Exercise 2.1: Bob Barker.""" phrase = "BOB! Come get Bob's bobblehead" # The original phrase name = "bob barker" # The replacement phrase # Makes matching simpler lower_phrase = phrase.lower() print("Original: ", phrase) print("Modified: ", lower_phrase.replace("bob", name))
ccb2dbfa2ba787beee00b8ca4118fc504c1c752f
pymft/py-mft1
/S06/builtin_functions/re_implement_zip.py
328
3.640625
4
def my_zip(a, b): out = [] for i in range(len(a)): out.append((a[i], b[i])) return out def my_enumeratep(a): out = [] for i in range(len(a)): out.append((i, a[i])) return out lst1 = [1, 2, 3] lst2 = [10, 20, 30] res = my_enumeratep(lst2) print(res) # [(1, 10), (2, 20), (3, 30)]
7495aa18d33410c0a1a9ab9c39106a2bb1ba0013
Maaitrayo/Python-Programming-Basics
/6_working_with_lists.py
1,584
4.6875
5
#here we will see how to print each item in a list names = ['maaitrayo', 'rohan', 'rupin', 'bangru'] print("The names are: ") for name in names: print(name) print("___________________________\n") #A pizza problem pizzas = ['plain', 'barbeque', 'pepperoni'] for pizza in pizzas: print( "I like " + pizza + " pizza !" ) print("Thank you for visting our store") print("___________________________\n") #Using in range() function for i in range(0,11): print(i) print("___________________________\n") #Creating a list using range() function numbers = list(range(1,6)) print(numbers) #here we create a list to store even numbers. first argument accepts the starting value. second argument accepts the last value. #Third argument accepts the number to be added at every iteration numbers = list(range(2,11,2)) print(numbers) #To store squared values squared = [] for value in range(1,11): square = value**2 squared.append(square) print(squared) print("OR") squares = [value**2 for value in range(1,11)] print(squares) print("___________________________\n") #min,max,sum functions digits = [1,2,5,8,9,10,14,52,14,3] print(min(digits)) print(max(digits)) print(sum(digits)) print("___________________________\n") #Slicing through list lists = ["ok", "me", "im", "in", "for", "this"] print(lists[0:4]) print(lists[:2]) print(lists[-3:]) print("___________________________\n") #Copying a list my_foods = ['grape', 'tea', 'cookie', 'orange'] friends_foods = my_foods[:] print("My foods are: ") print(my_foods) print("\nMy friends food are:") print(friends_foods)
fa20a41b9b7565e5d9c735a96fbd02911f015f8b
yuryanliang/Python-Leetcoode
/2019/0609/141_linked_list_cycle.py
452
3.859375
4
class ListNode: def __init__(self, x): self.val = x self.next = None def hasCycle(head): fast,slow=head,head while fast and fast.next: fast=fast.next.next slow=slow.next if fast is slow: return True return False if __name__ == "__main__": head = ListNode(1) head.next = ListNode(2) head.next.next = ListNode(3) head.next.next.next = head.next print hasCycle(head)
887985676dc795c9a702beaf18c7373c2cfa0255
bgruening/ngsutils
/ngsutils/bed/frombasecall.py
1,085
3.75
4
#!/usr/bin/env python ## category Conversion ## desc Converts a file in basecall format to BED3 format ''' Converts a file in basecall format to BED3 format ''' import sys import os def bed_frombasecall(fname): if fname == '-': f = sys.stdin else: f = open(fname) _bed_frombasecall(f) if fname != '-': f.close() def _bed_frombasecall(fileobj, out=sys.stdout): for line in fileobj: line = line.strip() if not line or line[0] == '#': continue cols = line.split('\t') chrom = cols[0] pos = int(cols[1]) - 1 out.write('%s\t%s\t%s\n' % (chrom, pos, pos + 1,)) def usage(): print __doc__ print 'Usage: bedutils frombasecall basecall.txt (- for stdin)' sys.exit(1) if __name__ == '__main__': fname = None for arg in sys.argv[1:]: if not fname and (os.path.exists(arg) or arg == '-'): fname = arg elif arg == '-h': usage() else: usage() if not fname: usage() bed_frombasecall(fname)
7a9ce81551a867e1acfdfb7be1dfb865cba17816
lee-saint/lab-python
/lec03_function/memory_model.py
1,259
3.828125
4
""" 파이썬 메모리 모델 - 파이썬이 변수들의 메모리 공관을 관리하는 방법 """ n1 = 1 print(f'주소 = {id(n1)} 저장된 값 = {n1}') n2 = n1 print(f'주소 = {id(n2)}, 저장된 값 = {n2}') n2 = 2 print(f'주소 = {id(n2)}, 저장된 값 = {n2}') n3 = 1 print(f'주소 = {id(n3)}, 저장된 값 = {n3}') # 정수 / 문자열의 경우 생성된 객체를 캐싱함(재활용) n3 = 3 - 1 # n2의 주소를 재활용 print(f'주소 = {id(n3)}, 저장된 값 = {n3}') # 정수, 문자열을 제외한 다른 객체들의 경우 값이 사용할 때마다 새로 생성됨 f1 = 1.2 print(f'주소 = {id(f1)}, 저장된 값 = {f1}') f2 = 1.2 print(f'주소 = {id(f2)}, 저장된 값 = {f2}') s1 = 'abc' print(f'주소 = {id(s1)}, 저장된 값 = {s1}') s2 = 'abc' print(f'주소 = {id(s2)}, 저장된 값 = {s2}') l1 = [1, 2, 3] print(f'주소 = {id(l1)}, 저장된 값 = {l1}') l2 = [1, 2, 3] print(f'주소 = {id(l2)}, 저장된 값 = {l2}') l2[0] = 100 print(l1) # list1에는 영향 없음 print(l2) l3 = l2 print(f'주소 = {id(l3)}, 저장된 값 = {l3}') l3[1] = 200 print(l2, l3) # == 연산자 VS is 연산자 a = [1, 2, 3] b = [1, 2, 3] print(f'==: {a == b}, is: {a is b}') print(f'==: {s1 == s2}, is: {s1 is s2}')
a89dfb9dc62fc325025c570d58897cd2222f9a9d
danny128373/Working-With-Images
/working_with_images.py
1,169
3.671875
4
from PIL import Image # opens image and assigns to mac mac = Image.open('images/example.jpg') # prints mac size as tuple (width, height) print(mac.size) # crops image mac, argument is a tuple (starting position x, starting position y, width, height) cropped_mac = mac.crop((0, 0, 100, 100)) # prints cropped_mac size as tuple (width, height) print(cropped_mac.size) # opens image and assigns to pencils pencils = Image.open('images/pencils.jpg') # prints pencils size as tuple (width, height) print(pencils.size) x = 0 y = 0 w = 1950 / 3 h = 1300 / 10 # cropping pencils image cropped_pencils = pencils.crop((x, y, w, h)) # prints cropped_pencils size as tuple (width, height) print(cropped_pencils.size) bottom_cropped_pencils = pencils.crop((0, 1100, w, 1300)) print(bottom_cropped_pencils.size) computer = mac.crop((800, 800, 1200, 1257)) mac.paste(im=computer, box=(0, 0)) blue = Image.open("images/blue_color.png").convert("RGBA") red = Image.open("images/red_color.jpg").convert("RGBA") # to change opacity rbga a=alpha blue.putalpha(128) red.putalpha(128) # pasting red on top of blue blue.paste(im=red, box=(0, 0), mask=red) blue.save("images/purple.png")
ce66d90fe4812ba2544533e0b2f2d258a822ba8f
daniel-reich/ubiquitous-fiesta
/xWW8PMuLN8hmAgLMJ_24.py
245
3.640625
4
def postfix(expression): stack = [] for op in expression.split(): if op in '+-*/': a = stack.pop() b = stack.pop() stack.append(eval('{}{}{}'.format(b, op, a))) else: stack.append(int(op)) return stack[0]
830e4d44ae10cb4d39ee94b55ebbd85d5a325ec3
typemytype/RoboFontStepByStep
/01_basicPython/06_dictionaries.py
796
4.4375
4
## Dictionaries # A dictionary is a keyword assigned collections of objects # keyword can be a string, number or an other kind of object # create a dictionary with curly brackets myDict = {"aKeyWord" : 6, "anOtherKeyWord" : "Hello World"} print myDict # retrive the value based on a keyword # if the keyword is not a valid keyword it will raise an KeyWord error print myDict["aKeyWord"] # retrive the value based on a keyword with a fallback print myDict.get("keyWordNotInTheDict", "myFallbackValue") # add/change a keyword value myDict["aKeyWord"] = 9 myDict["newKeyWord"] = "newValue" # get all keywords from the dictionary print myDict.keys() # get all values from the dictionary print myDict.values() # get a combined list of keywords and values from the dictionary print myDict.items()
71e43455916da3d8428d7761d922b48f17d3aae5
JayKimBravekjh/LongTimeRainfallPrediction
/Tutorial-Learning/Stock Price Predict/N-D input/stock_price_predict.py
5,792
3.65625
4
""" This is a tutoral, and it is downloaded from https://github.com/LouisScorpio/datamining/tree/master/tensorflow-program/rnn/stock_predict I made some changes in order to predict on the history predictions, not the test_dataset. While the result is not very good. Further modifies will be made. This code just for learning the RNN, I declare no copyright of this code, and the copyright belongs to the github user: LouisScorpio. If I violate your copyright, please contact me at liu.sy.chn@hotmail.com And I will delete this file in time. """ # In the project of N-D input, we can not use the same method, cause we can not predict the other factors which are the input data. # It means we can not like the 1-D input to predict anymore. Step-by-step prediction is impossible. # A way to solve this problem is to predic 1 time_step. We can change the prediction of the time-length by changing the length of the input. import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf rnn_unit=10 input_size=7 output_size=1 lr=0.0006 layer_num=2 f=open('./dataset/dataset_2.csv') df=pd.read_csv(f) data=df.iloc[:,2:10].values base_path = "Your Path" def get_train_data(batch_size=60,time_step=90,train_dataset_begin=0,train_dataset_end=5931): batch_index=[] data_train=data[train_dataset_begin:train_dataset_end] normalized_train_data=(data_train-np.mean(data_train,axis=0))/np.std(data_train,axis=0) print np.shape(normalized_train_data) train_x,train_y=[],[] for i in range(len(normalized_train_data)-2*time_step): if i % batch_size==0: batch_index.append(i) x=normalized_train_data[i:i+time_step,:7] y=normalized_train_data[i+time_step:i+2*time_step,7,np.newaxis] train_x.append(x.tolist()) train_y.append(y.tolist()) batch_index.append((len(normalized_train_data)-time_step)) return batch_index,train_x,train_y def get_test_data(time_step=20,test_begin=5931): data_test=data[test_begin:] mean=np.mean(data_test,axis=0) std=np.std(data_test,axis=0) normalized_test_data=(data_test-mean)/std size=(len(normalized_test_data)+time_step-1)//time_step test_x,test_y=[],[] x=normalized_test_data[0:time_step,:7] y=normalized_test_data[90:90+time_step,7] test_x.append(x.tolist()) test_y.extend(y) #test_x.append((normalized_test_data[(i+1)*time_step:,:7]).tolist()) #test_y.extend((normalized_test_data[(i+1)*time_step:,7]).tolist()) return mean,std,test_x,test_y weights={ 'in':tf.Variable(tf.random_normal([input_size,rnn_unit])), 'out':tf.Variable(tf.random_normal([rnn_unit,1])) } biases={ 'in':tf.Variable(tf.constant(0.1,shape=[rnn_unit,])), 'out':tf.Variable(tf.constant(0.1,shape=[1,])) } def lstm(X): batch_size=tf.shape(X)[0] time_step=tf.shape(X)[1] w_in=weights['in'] b_in=biases['in'] input=tf.reshape(X,[-1,input_size]) input_rnn=tf.matmul(input,w_in)+b_in input_rnn=tf.reshape(input_rnn,[-1,time_step,rnn_unit]) cell=tf.contrib.rnn.BasicLSTMCell(rnn_unit,reuse=tf.get_variable_scope().reuse) multi_cell=tf.contrib.rnn.MultiRNNCell([cell for _ in range(layer_num)], state_is_tuple=True) init_state=multi_cell.zero_state(batch_size,dtype=tf.float32) output_rnn,final_states=tf.nn.dynamic_rnn(multi_cell, input_rnn,initial_state=init_state, dtype=tf.float32) output=tf.reshape(output_rnn,[-1,rnn_unit]) w_out=weights['out'] b_out=biases['out'] pred=tf.matmul(output,w_out)+b_out return pred,final_states def train_lstm(batch_size=80,time_step=90,train_begin=0,train_end=5931): X=tf.placeholder(tf.float32, shape=[None,time_step,input_size]) Y=tf.placeholder(tf.float32, shape=[None,time_step,output_size]) batch_index,train_x,train_y=get_train_data(batch_size,time_step,train_begin,train_end) with tf.variable_scope("sec_lstm"): pred,_=lstm(X) loss=tf.reduce_mean(tf.square(tf.reshape(pred,[-1])-tf.reshape(Y, [-1]))) train_op=tf.train.AdamOptimizer(lr).minimize(loss) saver=tf.train.Saver(tf.global_variables(),max_to_keep=15) #module_file = tf.train.latest_checkpoint(base_path) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) #saver.restore(sess, module_file) for i in range(2000): for step in range(len(batch_index)-1): _,loss_=sess.run([train_op,loss],feed_dict={X:train_x[batch_index[step]:batch_index[step+1]],Y:train_y[batch_index[step]:batch_index[step+1]]}) print(i,loss_) if i % 200==0: print("save_model",saver.save(sess,'stock2.model',global_step=i)) train_lstm() def prediction(time_step=90): X=tf.placeholder(tf.float32, shape=[None,time_step,input_size]) mean,std,test_x,test_y=get_test_data(time_step) with tf.variable_scope("sec_lstm",reuse=True): pred,_=lstm(X) saver=tf.train.Saver(tf.global_variables()) with tf.Session() as sess: module_file = tf.train.latest_checkpoint(base_path) saver.restore(sess, module_file) test_predict=[] prob=sess.run(pred,feed_dict={X:[test_x[0]]}) predict=prob.reshape((-1)) test_predict.extend(predict) test_y=np.array(test_y)*std[7]+mean[7] test_predict=np.array(test_predict)*std[7]+mean[7] #acc=np.average(np.abs(test_predict-test_y[:len(test_predict)])/test_y[:len(test_predict)]) print test_predict plt.figure() plt.plot(list(range(len(test_predict))), test_predict, color='b') plt.plot(list(range(len(test_y))), test_y, color='r') plt.show() prediction()
d4a9ff4ad2d3531c515dc2427b04177600bd30be
Eudasio-Rodrigues/Linguagem-de-programacao
/praticas/pratica02-aula03.py
476
4.125
4
num1=int(input("Digite primeiro numero: ")) num2=int(input("Digite segundo numero: ")) print("adição=(+), subtração=(-),multiplicação=(*), divisão=(/)") op=input("digite operação") if op=="+": adição=num1+num2 print(adição) elif op =="-": subtração=num1-num2 print(subtração) elif op =="*": multiplicação=num1*num2 print(multiplicação) else: divisao=num1/num2 print(divisao)
adc7ae1b33686dbea2723ce5a58c54cf3374168c
cyrustabatab/KattisProgrammingProblems
/modulo.py
213
3.65625
4
def modulo(): n= 10 unique = set() for _ in range(n): number = int(input()) mod = number % 42 unique.add(mod) print(len(unique)) modulo()
97799118b02f72ec3cb0d49c8d3266dd5e31edb6
deesaw/PythonD-02
/classroom-examples/echo.py
262
4.25
4
text = input("Enter some thing (bye to quit): ") while text != "bye": print(text) text = input("Enter some thing : ") while True: text = input("Enter some thing (stop to quit): ") if text != 'stop': print(text) else: break
f34f458425673bc6c92bab4798dcc1e8a7331d04
daniel-reich/turbo-robot
/HqpZQPZiHbPK4HgEB_14.py
1,171
4.09375
4
""" Maxie is the largest number that can be obtained by **swapping two digits** , Minnie is the smallest. Write a function that takes a number and returns Maxie and Minnie. Leading zeros are not permitted. ### Examples maxmin(12340) ➞ (42310, 10342) maxmin(98761) ➞ (98761, 18769) maxmin(9000) ➞ (9000, 9000) # Sometimes no swap needed. maxmin(11321) ➞ (31121, 11123) ### Notes N/A """ def maxmin(n): print (n) return (swap(n,True), swap(n,False)) ​ def swap(n, revers): n = list(str(n)) # print(n) p = sorted(n,reverse= revers) print(p) i = 0 while n[i] == p[i]: if i == len(n)-1: return int("".join(n)) i += 1 k = i if not revers: if i == 0: if int(n[i]) == min([int(v) for _,v in enumerate(n) if v != "0"]): i +=1 while n[i] == '0': if i == len(n)-1: return int("".join(n)) i += 1 else: while p[k] == "0": if k == len(n)-1: return int("".join(n)) k += 1 ​ j = len(n) -i -1 - n[i:][::-1].index(p[k]) print (i,k,j) n[i],n[i+j] = n[i+j], n[i] return int("".join(n))
63ad8ef19d1f93099a1659e87e0e0ba1caa122a8
kyjswh/LeetCode
/src/LinkedList/MergeSortedLists.py
1,238
3.90625
4
__author__ = 'Daniel' ''' Given two sorted lists, do an in-place merge ''' #Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None def __repr__(self): l = [] p = self while p != None: l.append(p.val) p = p.next return str(l) def MergeTwoList(l1,l2): start1 = l1 start2 = l2 while start1 and start2: if start1.val <= start2.val: while start1 and start1.val <= start2.val: prev1 = start1 start1 = start1.next prev1.next = start2 else: while start2 and start2.val < start1.val: prev2 = start2 start2 = start2.next prev2.next = start1 if l1 == None: return l2 elif l2 == None: return l1 else: if l1.val <= l2.val: return l1 else: return l2 if __name__ == '__main__': n1 = ListNode(1) #n1.next = ListNode(3) #n1.next.next = ListNode(5) print(n1) n2 = ListNode(2) #n2.next = ListNode(4) #n2.next.next = ListNode(6) print(n2) print(MergeTwoList(n1,n2))
814cf7b8c60b625b7d5e62e46c27bc799a4d4822
dyy0711/pyTEST
/21.03.23-1.py
1,723
4.21875
4
#数据类型转换 name='张三' age=20 print(type(name),type(age)) #说明name和age的数据类型不相同 # print('我叫'+name+'今年'+age) #当将str类型与int类型进行连接时,报错,解决方案,类型转化 print('我叫'+name+'今年,'+str(age)+'岁') #将int类型通过str()函数转换成了str类型 #str()将其他类型转换成str类型 a=10 b=198.8 c=False print(type(a),type(b),type(c)) print(str(a),str(b),str(c),type(str(a)),type(str(b)),type(str(c))) #int()将其他的类型转int类型 s1='128' f1=98.7 s2='76.77' ff=True s3='hello' print(type(s1),type(f1),type(s2),type(ff),type(s3)) print(int(s1),type(int(s1))) #将str转成int类型,但前提为字符串为数字串 print(int(f1),type(int(f1))) #float转成int类型,截取整数部分,舍掉小数部分 #print(int(s2),type(int(s2))) 将str转成int类型报错,因为字符串为小数串 print(int(ff),type(int(ff))) #print(int(s3),type(s3)) 将str转成int类型时,字符串必须为数字串(整数),非数字串是不允许转换的,会报错 #float()函数,将其他类型转成float类型 a1='128.98' s2='76' ff=True a3='hello' i=98 print(type(a1),type(s2),type(ff),type(a3)) print(float(a1),type(float(a1))) print(float(s2),type(float(s2))) print(float(ff),type(float(ff))) #print(float(a3),type(float(a3))) 字符串中的数据如果是非字符串,则不允许转换 print(float(i),type(i)) #输入函数input() present=input('大圣想要什么礼物呢?') print(present) print(present,type(present)) #练习:从键盘录入两个整数,计算两个整数的和 a=input('请输入一个加数a:') b=input('请输入另一个加数b:') print(int(a)+int(b))
68e39c19435aa210bae645d53bc104b3f84c737b
nic0lewrlx/python101
/app01.py
2,657
4.125
4
print("Title of program: MCQ revision program") print() counter = 0 score = 0 total_num_of_qn = 3 counter +=1 tracker = 0 while tracker !=1: print("Q"+str(counter)+") "+ "find y if 8x2+4/y=22?") print(" a) 22") print(" b) 24") print(" c) 14") print(" d) 6") answer = input("Your answer: ") answer = answer.lower() if answer == "b": output = "correct!:)") score +=1 else answer == "a": output = "Wrong. Clue:4/y=22-8x2." score -=1 else answer == "c": output = "Wrong. Clue:4/y=22-8x2." score -=1 else answer == "d": output = "Wrong. Clue:4/y=22-8x2." score -=1 print() print(output) print() print("Your current score: " + str(round((score/total_num_of_qn*100),1)) + "%" ) print() print() counter +=1 tracker = 0 while tracker !=1: print("Q"+str(counter)+") "+ "how many atoms are there in NaHCO3 represents") print(" a) 7") print(" b) 12") print(" c) 6") print(" d) 4") answer = input("Your answer: ") answer = answer.lower() if answer == "a": output = "wrong. Clue:chemical symbols start with a capital letter." tracker =1 score -=1 elif answer == "b": output = "Wrong. clue:are you sure it is (NaHCO)3??." score -=1 elif answer == "c": output = "Correct!:)" score +=1 elif answer == "d": output = "Wrong. clue: I think you forgot about the 3." score -=1 else: output = "Please choose a, b, c or d only." print() print(output) print() print("Your current score: " + str(round((score/total_num_of_qn*100),1)) + "%" ) print() print() counter +=1 tracker = 0 while tracker !=1: print("Q"+str(counter)+") "+ "Which represents the electronic configuration of a non-metal?") print(" a) 2,1") print(" b) 2,8,3") print(" c) 2,8,8,2") print(" d) 2,7") answer = input("Your answer: ") answer = answer.lower() if answer == "a": output = "Wrong. Think again - how many electron shells are filled, and which group is this in?" score -=1 elif answer == "b": output = "Wrong. Think again - how many electron shells are filled, and which group is this in?" score -=1 elif answer == "c": output = "Wrong. Think again - how many electron shells are filled, and which group is this in?" score -=1 elif answer == "d": output = "Yes, that's right!" tracker =1 score +=1 else: output = "Please choose a, b, c or d only." print() print(output.lower()) print() print("Your current score: " + str(round((score/total_num_of_qn*100),1)) + "%" ) print() print() print("End of quiz!:)")