blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
13e4ecc1ae667399a763f8e3a28014d38b1f0639
daniel-reich/ubiquitous-fiesta
/Xkc2iAjwCap2z9N5D_12.py
137
3.53125
4
from datetime import date def has_friday_13(month, year): if date(year, month, 13).isoweekday() == 5: return True return False
d7b5630b85f8236689606279ab151628bc8d9a17
ClareVGitHub/LearningTools
/wortschatz_2.2.py
4,272
3.65625
4
# wortschatz is a learning aid for learning german as a foreign language. You can choose to add words and thier translation # to a sqlite database using sqlalchemy or you can choose the play mode which will cyce through your words to help you # memorize them. # Open in the terminal with >>> python3 wortschatz_2.2.py # requirements: You need to have installed python3 and sqlalchemy import sqlalchemy from sqlalchemy import create_engine engine = create_engine('sqlite:///ws.db') from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) session = Session() from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # Setting up table from sqlalchemy import Column, Integer, Numeric, String class Wortschatz(Base): __tablename__ = 'wortschatz' word_id = Column(Integer, primary_key = True) germanWord = Column(String(100), index = True) englishWord = Column(String(100), index = True) wordType = Column(String(50), index = True) score = Column(Integer) attempts = Column(Integer) # persisting the table Base.metadata.create_all(engine) # words = session.query(Wortschatz).all() # for word in words: # print(word.germanWord) from sqlalchemy import update # adding a word y = True addWs = y add = () play = () words = session.query(Wortschatz).all() correctAnswer = False answer = () skip = () mode = () print ('Type add to add new words OR play to play Wortschatz') mode = input() if mode == 'add': while addWs: print('Add German word') GW = input() print ('Add English word') EW = input() print ('Add word type') WT = input() cc_word = Wortschatz(germanWord = GW, englishWord = EW, wordType = WT, score = 0, attempts = 0) session.add(cc_word) session.commit() print('type y to add another word OR press enter to quit') keepGoing = input() if keepGoing != 'y': addWs = False print ('session ended') elif mode == 'play': play = True for word in words: correctAnswer = False while correctAnswer == False and play == True: print('Give the English for'+' '+(word.germanWord), 'OR enter skip or quit') answer = input() if answer == word.englishWord: correctAnswer = True word.score = word.score + 1 session.commit() word.attempts = word.attempts + 1 session.commit() print ('Correct!'+' '+ str(word.score)+' '+'correct out of'+' '+str(word.attempts)+' '+'attempts') elif answer == "skip": print ('the correct answer is:'+' '+(word.englishWord)) correctAnswer = True elif answer == 'quit': print('session ended') play = False break else: print('sorry wrong answer, try again') word.attempts = word.attempts + 1 session.commit() print (str(word.attempts)+' '+'attempts') for word in words: correctAnswer = False while correctAnswer == False and play == True: print('Give the German for'+' '+(word.englishWord), 'OR enter skip or quit') answer = input() if answer == word.germanWord: correctAnswer = True word.score = word.score + 1 session.commit() word.attempts = word.attempts + 1 session.commit() print ('Correct!'+' '+ str(word.score)+' '+'correct out of'+' '+str(word.attempts)+' '+'attempts') elif answer == 'skip': print('the correct answer is:'+' '+(word.germanWord)) correctAnswer = True elif answer == 'quit': print('session ended') play = False break else: print('sorry wrong answer, try again') word.attempts = word.attempts + 1 session.commit() print (str(word.attempts)+' '+'attempts')
093b73ba2ff2b0242193509732eaee7179e9a318
zavadsk20/GospAvtoBot
/KPZAV/test.py
596
3.625
4
import codecs #дозволяє обробляти кириличні символи def NewLetter(let): lett = { 'Е' : 'E', 'І' : 'I', 'О' : 'O', 'Р' : 'P', 'А' : 'A', 'Н' : 'H', 'К' : 'K', 'Х' : 'X', 'С' : 'C', 'В' : 'B', 'Т' : 'T', 'М' : 'M' } resl = "" let = let.upper() for i in let: if i in lett: resl += lett[i] else: resl += i return resl
135bf2213cec4d618b51185a7a3d0b5ef9a03133
KhauTu/C4E15---Khau-Tu
/Fundamentals/session02/for_example.py
143
4.21875
4
# for _ in range(2, 8, 3): # print("Hi") # print("Bye") # for i in range(2, 8, 3): # print("Hi") x = 7 for i in range(x): print(i)
034444d34f62a966482898e0571899c5677ca1f6
SticketInya/fcc_12_beginner_python_projects
/project_nbr_guesser/main.py
889
4.125
4
from random import randint def Guesser(max_nbr): nbr = randint(1, max_nbr) guess = 0 while guess != nbr: guess= int(input(f"Guess a number between 1 and {max_nbr} : ")) if guess<nbr: print(f"{guess} is too low.") elif guess>nbr: print(f"{guess} is too high.") print(f"Yay! You guessed the number ({nbr}) correctly!") def ComputerGuesser(max_nbr): low = 1 high = max_nbr response = '' while response != 'c': if low != high: guess= randint(low, high) else: guess = low response= input(f"Is {guess} too low (l), too high (h) or correct (c)?").lower() if response == 'h': high = guess-1 elif response== 'l': low = guess+1 print(f"Yay! The computer guessed the number ({guess}) correctly!") ComputerGuesser(100)
4e0ce6237e44a95639a509f338f026a6e8735e92
stgleb/problems
/python/linked_list/k_element_from_tail.py
552
3.796875
4
""" Find element on k-th position from list tail """ from python.linked_list import Node def kth_element(head, k): first = head second = head cnt = 0 while first is not None and cnt < k: first = first.next cnt += 1 while first is not None: first = first.next second = second.next return second if __name__ == "__main__": node5 = Node(5) node4 = Node(4, node5) node3 = Node(3, node4) node2 = Node(2, node3) node1 = Node(1, node2) print(kth_element(node1, 2).value)
cbeb6412c56e10b5e60b2f8b0e23bf79e4599b01
daher7/Python_Pildoras
/11_try_except_2.py
361
4.0625
4
def divide(): try: op1 = (float(input("Introduce un numero: "))) op2 = (float(input("Introduce otro numero: "))) print("La division es {}".format(op1/op2)) except ZeroDivisionError: print("Ha ocurrido un error. No se puede dividir entre 0") finally: print("Calculo finalizado") divide()
63365f512db4dd4f6f9ec941e37184891e437e96
alvinyeats/DesignPatterns
/Iterator/main.py
409
3.671875
4
from book_shelf import BookShelf from book import Book def main(): book_shelf = BookShelf() book_shelf.append_book(Book('21天精通Java')) book_shelf.append_book(Book('21天精通C++')) book_shelf.append_book(Book('21天精通PHP')) book_shelf.append_book(Book('21天精通Python')) for book in book_shelf: print(book.get_name()) if __name__ == '__main__': main()
69746b1102c7144ae9368add912d4ba80eb8c582
asadiqbalkhan/shinanigan
/syntax practice/writingfiles.py
974
4.46875
4
# List of commands # close -- Closes the file. # read -- Reads the contents in your file # readline -- Reads just one line of a text file # trancate -- Empties the file. Watch out if you care about a file # write('stuff') -- Writes "stuffs" to the file # Lets use some of this to make a simple little text editor from sys import argv script, filename = argv print("We're going to erase %r" % (filename)) print("If you don't want that, hit control-c") print("If you do want that, hit return ") input("?") print("Opening the file...") target = open(filename,'w') print("Truncating the file. Goodbye!") target.truncate() print("Now I'm going to ask you for three lines") line1 = input("Line 1: ") line2 = input("Line 2: ") line3 = input("Line 3: ") print("I'm going to write these to the file.") target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") print("And finally, we close it.") target.close()
6d69b679b04a8cabe807510a03ccf7ca20875035
yuhsh24/PythonMultiprocess
/lock.py
928
3.984375
4
# -*- coding:utf-8 -*- # RLock and Lock import threading from time import sleep class Counter: def __init__(self): self.__count = 0 self.__lock = threading.RLock() #self.__lock = threads.Lock() # Lock()不能在一个线程中被多次acquire,否则会进入死锁 def Increase(self, threadNum): self.__lock.acquire() #self.__lock.acquire() # RLock()能够在一个线程中被多次acquire self.__count += 1 sleep(1) print "%d: %d" % (threadNum, self.__count) #self.__lock.release() # RLock()只要acquire与release成对出现即可 self.__lock.release() if "__main__" == __name__: counter = Counter() threads = [] for i in xrange(10): t = threading.Thread(target=counter.Increase, args=(i, )) t.start() threads.append(t) for t in threads: t.join() print "All threads end!!!"
239bdbed20d44cf8abc0301178c9630b113f8d0c
alexreyes/LeetCode
/520.Detect Capital.py
461
3.59375
4
class Solution: def detectCapitalUse(self, word): splitWord = list(word) upperCount = 0 lowerCount = 0 for x in splitWord: if x.isupper(): upperCount +=1 else: lowerCount += 1 if (upperCount == len(word)): return True elif lowerCount == len(word): return True elif splitWord[0].isupper() and lowerCount == len(splitWord) - 1: return True else: return False x = Solution() print(x.detectCapitalUse("FlaG"))
5609504999847d39ffcb04dac76189950d0c2297
kirigaikabuto/distancelesson2
/lesson10/5.py
177
3.75
4
s="1 2 3 4 5 6 7 8 9" words=s.split() numbers=[] for i in words: num = int(i) numbers.append(num) print(numbers) sumi=0 for i in numbers: sumi = sumi + i print(sumi)
0239dcb9dacad51ffb7453395ad3c185d04cab8c
PriyankaKhire/ProgrammingPracticePython
/Verifying an Alien Dictionary.py
1,145
3.84375
4
# https://leetcode.com/problems/verifying-an-alien-dictionary/ class Solution(object): def __init__(self): self.orderHash = {} def putOrderInHash(self, order): for i in range(len(order)): self.orderHash[order[i]] = i def compareWords(self, w1, w2): i = 0 j = 0 while(i<len(w1) and j<len(w2)): print w1[i], w2[j] if(w1[i] == w2[j]): i = i+1 j = j+1 else: if(self.orderHash[w1[i]] > self.orderHash[w2[j]]): return False return True # Case where first word is larger than second like apple vs app. we want app before apple if(i < len(w1)): return False return True def isAlienSorted(self, words, order): self.putOrderInHash(order) for i in range(len(words)-1): if not(self.compareWords(words[i], words[i+1])): return False return True """ :type words: List[str] :type order: str :rtype: bool """
a0f388c0b5ef8de62166c3523d858abfb7a2898a
nicolasfcpazos/Python-Basic-Exercises
/Aula15_Ex066.py
488
3.765625
4
# Crie um programa que leia vários números inteiros pelo teclado. # O programa só vai parar quando o usuário digitar o valor 999, que é # a condição de parada. No final, mostre quantos números foram digitados # e qual foi a soma entre eles. (desconsiderando o flag, 999). n = s = 0 d = 0 while True: n = int(input('Digite um número: [999 para parar] ')) if n == 999: break s += n d += 1 print(f'O total de números digitados é {d} e a soma vale {s}')
1fd32dc39ba5daa5552b610ec98e56b30b40936a
bhayer96/Configuration-Scrubber-An-Automation-Tool
/Hide.py
4,373
3.59375
4
# User interactive program that hides sensitive material in a configuration. class Hide: def __init__(self): # Constructor valid = 0 while valid == 0: # Keep asking for a file name until an existing config is entered try: self.filename = self.fileName() # Gets the name for the config that needs to # have its content hidden. self.filetxt = open(self.filename, 'r') # Read mode valid = 1 # File found except IOError: # File not found print("\nConfiguration does not exist in current directory.") self.copyList = [] # Will be used to store lines and to update changes made. # It is used as a sort of temporary line editor. self.menu() # Intiate user menu. def menu(self): quit = 0 while quit == 0: # Continue until user decides to quit. print("\nType in data type to scrub or an action to complete using the menu below:\n\n" + "Description: de IP Address: ad\n" + "Key-string: ks Password: pw\n" + "Snmp-server: ss Display original: do\n" + "Display scrubbed: ds Quit: qu\n" ) choice = raw_input('>> ') # Need to use raw_input with Python 2 if choice == "de": self.readFile("description") elif choice == "ad": self.readFile("ip address") elif choice == "ks": self.readFile("key-string") elif choice == "ss": self.readFile("snmp-server") elif choice == "pw": self.readFile("password") elif choice == "do": print("\nDisplaying original configuration: ") self.filetxt.seek(0) print("\n" + self.filetxt.read()) print("Configuration done.") elif choice == "ds": try: # Check to see if a scrubbed file has been created hidden = open("Scrubbed_"+ self.filename, 'r') print("\nDisplaying scrubbed configuration: ") print("\n" + hidden.read()) print("Configuration done.") hidden.close() except IOError: print("\nScrubbed configuration file has not been created yet so cannot display.") elif choice == "qu": print("\nQuitting program...\n") self.filetxt.close() return else: print("\nChoice is not a part of the menu. Try again!") def fileName(self): # Used to get config file name from user. print("\nPlease enter file name, including the file extension.") filename = raw_input(">> ") return filename def readFile(self, word): i = 0 # Open or create a file to write content of config file, with hidden revisions hidden = open("Scrubbed_"+ self.filename, 'w') newLine = " " if not self.copyList: # If copyList is empty, that means this is the first time # readFile is being called and there is a special case # for that. self.filetxt.seek(0) # Starts at the first byte (byte 0) in the file for line in (self.filetxt): # Since this is the first call, read from original # config file. if word in line: # Look for key phrase if word == "ip address": # Special case for IP add. since counter is # needed. i += 1 newLine = "IP " + str(i) + "\n" # Make a hidden IP address. else: newLine = "** " + word + " removed **\n" # Hide content of line. hidden.write(newLine) # Write altered line to the hidden config file. self.copyList.append(newLine) # Also add this line to the copyList list # to make keeping track of which lines are # changed easier in the future calls. else: # No changes need to be made to the line. self.copyList.append(line) hidden.write(line) print("\nNAME OF NEW SCRUBBED FILE IS: " + "Scrubbed_"+ self.filename) else: # Not first call to readFile. for e in range(len(self.copyList)): # Iterate through copyList to copy and # change lines. if word in self.copyList[e]: if word == "ip address": i += 1 # Keeps track of how many IP addresses have been changed. newLine = "IP " + str(i) + "\n" else: newLine = "** " + word + " removed **\n" hidden.write(newLine) self.copyList[e] = newLine # Update in the list that this line has been changed # so that the change is not lost in the next call. else: hidden.write(self.copyList[e]) # No changes need to be made so use # what's stored in the list. hidden.close() hideConfig = Hide() # Creates an instance of the class to begin the program.
a2d0d6d80c05947bd69a5edd389a86a8ac16626f
n20084753/Guvi-Problems
/beginer/set-6/53-sum-digits.py
81
3.625
4
n = int(raw_input()) sum = 0 while n > 0: sum += n % 10 n = n / 10 print(sum)
1c0282cbe2d13b2f1c38755b7606f68871d943b5
matrix-revolution/algorithms
/addDigits.py
502
3.796875
4
class Solution(object): def addDigits(self, num): """ :type num: int :rtype: int """ sum_v = 0 sum_v += num % 10 num /= 10 while num > 0: sum_v += num % 10 num /= 10 if num <= 0 and sum_v > 9: num = sum_v sum_v = 0 return sum_v def main(): sol = Solution() num = 391 out = sol.addDigits(num) print out if __name__ == '__main__': main()
0b7725048f485a4c3afa4565568633ad1e96ca65
rafaelperazzo/programacao-web
/moodledata/vpl_data/139/usersdata/159/61423/submittedfiles/diagonaldominante.py
439
3.703125
4
# -*- coding: utf-8 -*- import numpy as np def soma(a): b=[] for i in range (0,a.shape[0],1): soma=0 for j in range (0,a.shape[1],1): if i!=j: soma=soma+a[i,j] b.append(soma) return (b) n=int(input('Tamanho da matriz:')) a=np.zeros((n,n)) for i in range (0,a.shape[0],1): for j in range (0,a.shape[1],1): a[i,j]=int(input('Valor:')) print(soma(a))
16b8b6fa104b1e0bb92580d504752ce07070295b
chanyoonzhu/leetcode-python
/1650-Lowest_Common_Ancestor_of_a_Binary_Tree_III.py
1,017
3.84375
4
""" # Definition for a Node. class Node: def __init__(self, val): self.val = val self.left = None self.right = None self.parent = None """ """ - hashset - O(h), O(h), h = n in worst case """ class Solution: def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node': p_ancestor = set() while p: p_ancestor.add(p) p = p.parent while q not in p_ancestor: q = q.parent return q """ - two pointers: - instinct: for each node to travel to ancestor after 1 switch, p travels: p to a (ancestor), a to root, q to a; q travels: q to a, a to root, p to a => the distance they travel are equal - O(h), O(1), h = n in worst case """ class Solution: def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node': p1, q1 = p, q while p1 != q1: p1 = p1.parent if p1.parent else q q1 = q1.parent if q1.parent else p return p1
7d173bda4453e1a124eca2beec5d05cf21380a2e
mkhoeini/random_problems
/python2.7/prob2.py
601
3.546875
4
def palindrom(s): a, b = 0, len(s)-1 while a < b: if s[a] == s[b]: a += 1 b -= 1 else: return False return True def find(s, b, e): result = s[b:e] while e < len(s): b += 1 e += 1 if palindrom(s[b:e]): while (b > 0) and (e < len(s)) and (s[b-1] == s[e]): b -= 1 e += 1 result = s[b:e] return result if __name__ == '__main__': s = raw_input() p1 = find(s, 0, 1) p2 = find(s, 0, 2) print (p1 if len(p1) >= len(p2) else p2)
afa8e6cbadefbf36eb15a9ea0f988ad211d2721d
xiluhua/python-demo
/demo/demo11_list_03切片.py
865
4.125
4
''' @author: xilh @since: 20200125 ''' list1 = ['physics', 'chemistry', 1997, 2000, 1, 2, 3, 4] print("== 列表切片 ==") print("list1 :", list1) list2 = list1[0:3] print("list2-1:", list2) list2 = list1[0:2] print("list2-2:", list2) list2 = list1[1:3] print("list2-3:", list2) list2 = list1[:3] # 和 list1[0:3]一样 print("list2-4:", list2) list2 = list1[:] # 全部复制,值一样但是地址(引用)不一样 print("list2-5:", list2) list2 = list1[::1] # 全部复制,值一样但是地址(引用)不一样 print("list2-6:", list2) print("值一样: list1 == list2,", list1 == list2) print("地址(引用)不一样: list1 is list2,", list1 is list2) list2 = list1[::2] # 间隔,取 2,4,6,8 print("list2-7:", list2) list2 = list1[::-1] # 倒序 print("list2-8:", list2)
8c1cfa91f4f99b72f62f8b8c07a3ac2791574d54
e1630m/green-hub
/green.py
4,968
3.765625
4
from alphanumeric import * import random import subprocess def num_days(year, month=13): ''' Returns number of days in given year (optionally, given year and month) Args: year (int): year in Gregorian calendar month (int): (optional) month ''' modifier = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) days = (31, 28 + modifier, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) if month != 13: return days[month - 1] return sum(days) def epoch_converter(y: int, m: int, d: int) -> int: ''' Returns UNIX epoch time Args: y (int): year in Gregorian calendar m (int): month in Gregorian calendar d (int): day in Gregorian calendar ''' ey, em, ed = 1970, 1, 1 epoch = 0 epoch += 86400 * sum(num_days(i) for i in range(ey, y)) epoch += 86400 * sum(num_days(y, i) for i in range(em, m)) epoch += 86400 * (d - ed) return epoch def jan_first(year:int, base=1899) -> int: ''' Returns the day of the week on January 1, year (Sunday == 0, Saturday == 6) Args: year (int): year in Gregorian calendar ''' backward = (year < base) sum_days = 0 - 2 * backward for y in range(base, year - backward, 1 - 2 * backward): sum_days += num_days(y) return sum_days % 7 if not backward else 6 - (sum_days % 7) def get_graph(year: int) -> list[int]: ''' Returns a blank graph for the year, 1 represents valid day. Args: year (int): year in Gregorian calendar Warning: It tries to mimic the contribution graph of GitHub.com. But GitHub.com has a bug on year 2000. https://github.com/username?tab=overview&from=2000-01-01 The graph started on Sunday, but it should start on Saturday. The other years seems okay. ''' graph = [[1 for _ in range(53)] for _ in range(7)] start = jan_first(year) days = num_days(year) for i in range(start): graph[i][0] = 0 for i in range(6, start + (days == 366), -1): graph[i][-1] = 0 return graph def draw_on_graph(year: int, s: str, daily_commits=9) -> list[int]: ''' Returns a drawing for the year, number represents # of commits for the day. Args: year (int): year in Gregorian calendar s (str): things to write (len < 9, English alphanumeric only) ''' assert len(s) < 9, 's should be shorter than 10 characters' assert all(1 if c.encode().isalpha() or c.isdigit() else 0 for c in s), \ 's should be English alphanumeric' graph = get_graph(year) line = [[0] for _ in range(7)] for i in range(7): for c in ''.join(c.lower() if c.isalpha() else c for c in s): line[i] += [daily_commits if n else 2 for n in cmap[c][i]] + [1] graph[i] = [graph[i][0]] + line[i][1:-1] + graph[i][len(line[i]) - 1:] return graph def num_commits(graph: list[int]) -> list[int]: ''' Returns number of commits from Jan 1 to Dec 31 Args: graph (list): what you got from draw_on_graph() ''' start, end = float('inf'), -float('inf') for i in range(7): if graph[i][0]: start = min(start, i) if graph[-i - 1][-1]: end = max(end, -i) return [graph[y][x] for x in range(53) for y in range(7)][start:end] def commit(y: int, cmts: list[int], limit: int, fname: str, c: str) -> None: ''' Make automated commits and returns None Args: y (int): the year you want to make automated commits (YYYY) cmts (list[int]): a list you got from num_commits which contains a number of commits from Jan 1 to Dec 31 in the given year limit (int): maximum daily commit fname (str): the name of dummy file you want to make commit c (str): commit comment ''' c = '"' + c + '"' epoch_day = epoch_converter(y, 1, 1) subprocess.run(f'touch {fname}') for cmt_today in cmts: rand_num = limit - random.randint(0, limit // 10) randomized_time = epoch_day for _ in range(rand_num if cmt_today > 2 else cmt_today): with open(fname, 'a+') as f: f.write('1') subprocess.run(f'git add {fname}') randomized_time += random.randint(1, 86399 // cmt_today) commit_cmd = f'git commit --date {randomized_time} -S -m {c}' subprocess.run(commit_cmd) epoch_day += 86400 def main(): year = 2020 draw = 'e1630m' max_daily_commits = 50 dummy_file_name = 'dummy.txt' comment = 'Automated Commit' cmt_lst = num_commits(draw_on_graph(year, draw, max_daily_commits)) commit(year, cmt_lst, 10, dummy_file_name, comment) if __name__ == '__main__': main()
3d0dd1c21f47c3aaecf00f38f422ed1e5726dd30
GalickayaAleksandra/hillel_hometask5
/task(5).py
815
3.9375
4
def my_file(): f_path = 'C:/Users/Александра/Desktop/homework6/file2' out_path = 'C:/Users/Александра/Desktop/homework6/shifr_file' open_file = open(f_path) file_read = open_file.read() my_date = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz" key = int(input("Please, enter your key(number from 1-25): ")) encrypted = "" for letter in file_read: position = my_date.find(letter) new_position = position + key if letter in my_date: encrypted = encrypted + my_date[new_position] else: encrypted = encrypted + letter print("Your cipher is: ", encrypted) out_file = open(out_path, 'w') out_file.write(encrypted) out_file.close() open_file.close() my_file()
427cbe1ca1cd0eba1e9e045ea03a761d1d4155c8
rokib7/pythoncrashcourse
/chapter_08/great.py
383
3.75
4
def show_magicians(magicians): for magician in magicians: print(magician.title()) def make_great(magicians): new_list = [] for magician in magicians: new_list.append(magician.title() + " the Great") return new_list magicians = ['merlin','gandalf','voldemort'] new_list = make_great(magicians[:]) show_magicians(magicians) show_magicians(new_list)
9e3bece0699928e54d8b97a092391d9bec2d2376
wang264/JiuZhangLintcode
/Algorithm/L2/optional/71_binary-tree-zigzag-level-order-traversal.py
1,604
4.0625
4
# 71. Binary Tree Zigzag Level Order Traversal # 中文English # Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, # then right to left for the next level and alternate between). # # Example # Example 1: # # Input:{1,2,3} # Output:[[1],[3,2]] # Explanation: # 1 # / \ # 2 3 # it will be serialized {1,2,3} # Example 2: # # Input:{3,9,20,#,#,15,7} # Output:[[3],[20,9],[15,7]] # Explanation: # 3 # / \ # 9 20 # / \ # 15 7 # it will be serialized {3,9,20,#,#,15,7} # Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None from collections import deque class Solution: """ @param root: A Tree @return: A list of lists of integer include the zigzag level order traversal of its nodes' values. """ def zigzagLevelOrder(self, root): # write your code here rslt = [] if root is None: return rslt level = 0 queue = deque([root]) while queue: level = level + 1 rslt_this_level = [] for _ in range(len(queue)): node = queue.popleft() rslt_this_level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) if level%2==0: rslt.append(list(reversed(rslt_this_level))) else: rslt.append(rslt_this_level) return rslt
a02a8a74d4a739a4f098cdb8e445843beb4bdea1
BeniaminK/hackerrank_project_euler
/Max/21-30/_22_names_scores.py
1,084
3.609375
4
#!/usr/bin/python # -*- coding: utf-8 -*- import unittest def get_name_score(name): score = 0 for elem in name: score += ord(elem) - 64 return score def solve(name, name_list): score = get_name_score(name) # print "Score: %d" % (score) import bisect idx = bisect.bisect_left(name_list, name) + 1 # print "Index of %s in %s is %d" % (name, name_list, idx) score *= idx return score def main(): T = int(raw_input()) names = [None for i in xrange(T)] for i in xrange(T): n = raw_input() names[i] = n names = sorted(names) T = int(raw_input()) for i in xrange(T): name = raw_input() print solve(name, names) if __name__ == '__main__': main() class MyTest(unittest.TestCase): def setUp(self): pass def test_solver(self): import sys import StringIO input = \ """5 ALEX LUIS JAMES BRIAN PAMELA 1 PAMELA """ oldstdin = sys.stdin sys.stdin = StringIO.StringIO(input) main() pass
849a2a8005b34cc3ad63f079c9a30d7c7c6528ef
MrHamdulay/csc3-capstone
/examples/data/Assignment_9/odtjoh001/question1.py
1,068
3.84375
4
"""Python program to analyse student marks read in from a file and determine which students need to see a student advisor. John Odetokun 11 May 2014""" import math filename= input("Enter the marks filename:\n") f = open( filename, "r") list = [] for line in f: list.append(line) f.close() nlist = [] for i in range(len(list)): lin = list[i].split(",") nlist.append(lin) marks = 0 for j in range(len(nlist)): marks += eval(nlist[j][1]) average = marks / len(list) print("The average is:", "{0:.2f}".format(average)) meansum = 0 for k in range(len(list)): meansum += (eval(nlist[k][1]) - average)**2 meansum = meansum / len(list) dev = math.sqrt(meansum) print("The std deviation is:", "{0:.2f}".format(dev)) minmark = average - dev studentadvlist = [] for a in range(len(list)): if (eval(nlist[a][1]) < minmark): studentadvlist.append(nlist[a][0]) if len(studentadvlist) != 0: print("List of students who need to see an advisor:") for k in studentadvlist: print(k)
47f7a499c705405822c50fa86959851d63c5f42d
Gbolly007/AdvancedPython
/Assignment6/As6_Number5.py
4,243
3.765625
4
# Python version 3.8 import sympy as sym from fractions import Fraction # list for storing results of operations lis = [] # variables to store symbolic computation a = sym.Symbol('a') b = sym.Symbol('b') c = sym.Symbol('c') d = sym.Symbol('d') e = sym.Symbol('e') f = sym.Symbol('f') g = sym.Symbol('g') h = sym.Symbol('h') i = sym.Symbol('i') j = sym.Symbol('j') k = sym.Symbol('k') l = sym.Symbol('l') m = sym.Symbol('m') n = sym.Symbol('n') o = sym.Symbol('o') p = sym.Symbol('p') q = sym.Symbol('q') r = sym.Symbol('r') s = sym.Symbol('s') t = sym.Symbol('t') u = sym.Symbol('u') v = sym.Symbol('v') w = sym.Symbol('w') x = sym.Symbol('x') y = sym.Symbol('y') z = sym.Symbol('z') # Loop to calculate while True: # Variable to accept input from user user_input = input('>>>') # Code block to check malformed input ui = user_input.split(' ') neg = '' for u in ui: if len(u) > 2: if '+' in u: v = u.split('+') kk = 0 for c in v: if len(c) == 0: v.pop(kk) kk += 1 if len(v) >= 2: v[0] = int(v[0]) if not type(v[0]) is int and type(v[1]) is str: print('err: invalid expression') neg = 'ss' elif '-' in u: v = u.split('-') jj = 0 for c in v: if len(c) == 0: v.pop(jj) jj += 1 if len(v) >= 2: v[0] = int(v[0]) if not type(v[0]) is int and type(v[1]) is str: print('err: invalid expressions') neg = 'ss' elif '*' in u: v = u.split('*') jj = 0 for c in v: if len(c) == 0: v.pop(jj) jj += 1 if len(v) >= 2: v[0] = int(v[0]) if not type(v[0]) is int and type(v[1]) is str: print('err: invalid expressions') neg = 'ss' try: # list to store disallowed operators that are not accepted for basic arithmetic operations mychar = ['%', '^', '='] # list to store disallowed operators that are not accepted for symbolic computation mychar_n = ['%', '^', '='] bsop = ['+', '-'] syms = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'z', 'y', 'x'] # condition to check if user passed the value of an list and convert it if '[' and ']' in user_input: uis = user_input.split(' ') ii = 0 for u in uis: if '[' in u: g = int(u[1]) gg = lis[g] ui[ii] = gg ii += 1 user_input = ' '.join(map(str, ui)) # condition that handles symbolic computation if any(x in user_input for x in syms): if not any(x in user_input for x in mychar_n) and len(neg) == 0: if 'expand' in user_input: user_input = user_input.replace('expand', '') lis.append(sym.expand(user_input)) print(str(len(lis)-1)+': ' + str(sym.expand(user_input))) else: li = eval(str(user_input)) lis.append(li) print(str(len(lis)-1)+': ' + str(li)) # condition that handles basic arithmetic else: if (x in user_input for x in bsop) and not any(x in user_input for x in mychar) and len(neg) == 0: li = eval(user_input) if user_input.count('/') > 1: if type(li) is float: li = str(Fraction(li).limit_denominator()) if type(li) is float: li = format(li, '.8f') lis.append(li) print(str(len(lis)-1)+': ' + str(li)) except: print('err: invalid expression')
ebf677c433a29be7f7dc78605a2480618c75e246
timmyshen/LearnPython
/euler-mike/1.py
137
3.90625
4
#!/usr/bin/env python3 # MZ # 233168 sum = 0 for x in range(1, 1000): if x % 3 == 0 or x % 5 == 0: sum = sum + x print(sum)
7d8bd5b8a3d7d4c02fc5e9216ba89ed3fd591b91
VineetPrasadVerma/GeeksForGeeks
/SudoPlacementCourse/BinarySearch.py
427
3.671875
4
def bin_search(arr, left, high, key): flag = 0 left = 0 high = len(arr)-1 while left <= high: mid = int((left + high) / 2) if arr[mid] == key: flag = 1 return mid break elif arr[mid] > key: high = mid - 1 else: left = mid + 1 if flag == 0: return -1 bin_search([1, 2, 5,8,9,10,11,12,13,14,16,17], 0, 7, 14)
d7ebb612f997020cb2f5b39aabd94748c8c51649
Luucx7/POO-P4
/3209.py
1,059
3.734375
4
# -*- coding: utf-8 -*- casos = int(input()) # Recebe a quantia de casos de teste for i in range(casos): # Executa o programa na quantia de vezes especificada entrada = list(map(int, input().split())) # Recebe uma linha de entrada, separa os valores, transforma em inteiro e transforma em lista soma = 0 # Variável inicial com os valores de soma quantiaFiltros = entrada[0] # Variável com a quantia de filtros de linha, posição zero da lista (primeiro valor) for j in range(1, quantiaFiltros + 1): # Executa um laço entre os valores, iniciando da posição 1 e encerrando na posição da quantia + 1 (pois o primeiro valor é reservado para a quantia) # irá executar na quantia de casos mas de forma diferente. soma += entrada[j] # Soma o valor a variável com a soma # Subtrai um da quantia de filtros, pois um filtro estará na tomada, e subtrai a quantia de filtros da soma, pois os mesmos estarão conectados nos filtros subjacentes. print(soma - (quantiaFiltros - 1)) # Imprime o valor na tela
26da94d4a58cc8c912faf1465767c66db07986ed
gauthamej/Gautham
/checkint.py
193
3.6875
4
user_input = input() try: if "." in user_input : val = float(user_input) print("yes") else: val = int(user_input) print("yes") except ValueError: print("No")
b011f79b1dd8cd37658c34efd2bcce252b910374
tophatraptor/avogadro-format
/avogadro.py
1,817
3.5625
4
import sys import os import argparse #Ordinal code from user 'Winston Ewert' on stackexchange SUFFIXES = {1: 'st', 2: 'nd', 3: 'rd'} def ordinal(num): # I'm checking for 10-20 because those are the digits that # don't follow the normal counting scheme. if 10 <= num % 100 <= 20: suffix = 'th' else: # the second parameter is a default. suffix = SUFFIXES.get(num % 10, 'th') return str(num) + suffix def main(): parser = argparse.ArgumentParser(description='Tool for formatting python output in an easy-to-read format') parser.add_argument("eventlist",help="Path to alphabetically-arranged, newline-delimited list of ISO events") parser.add_argument("scoresheet",help="Path to scoresheet tsv") parser.add_argument("--outfile",help="Path to output file") args = parser.parse_args() event_file = args.eventlist scoresheet_file = args.scoresheet outfile = args.outfile events = [] with open(event_file,'r') as fh: for line in fh: events.append(line.strip()) school_list = [] with open(scoresheet_file,'r') as fh: for line in fh: school_list.append(line.strip().split('\t')) if(outfile): with open(outfile,'w') as fh: for school in school_list: fh.write("{} - {} place\n".format(school[0],ordinal(int(school[-1])))) for i, x in enumerate(events): fh.write(x + " - " + ordinal(int(school[i+1])) + "\n") fh.write('\n') else: for school in school_list: print("{} - {} place".format(school[0],ordinal(int(school[-1])))) for i, x in enumerate(events): print(x + " - " +ordinal(int(school[i+1]))) print('\n') if __name__=='__main__': main()
e8ebe4106f25138b6a82edb6e2b689f6f814b810
nguyenquangnhat1208/NguyenQuangNhat-fundamental-c4e27
/Fundamentals/Session05/Homework/ex78.py
395
4.25
4
def remove_dollar_sign (s): s_remove = s.replace("$","") return s_remove n = input("nhap vao ky tu : ") print("chuoi sau khi bo ky tu :",remove_dollar_sign(n)) string_with_no_dollars = remove_dollar_sign("$80% percent of $life is to show $up") if string_with_no_dollars == "80% percent of life is to show up": print("Your function is correct") else: print("Oops, there's a bug")
813805f6b8749b5b7f92f14c27275347e7e51a65
Jyoshna9346/Become-Code-Python
/recursions basics.py
1,051
3.640625
4
''' def fun(n): if n<=1: return n return fun(n-1)+fun(n-2) n=int(input()) print(fun(n)) #fun(n)//5 ''' ''' def fun(n): if n<=1: return print(n) fun(n-1) fun(n-2) n=int(input()) fun(n) input = 5 5 4 3 2 2 3 2 ''' ''' def fun(n): if n<=1: print('H',n) return print(n) fun(n-1) fun(n-2) fun(n-3) n=int(input()) fun(n) 5 5 4 3 2 H 1 H 0 H -1 H 1 H 0 2 H 1 H 0 H -1 H 1 3 2 H 1 H 0 H -1 H 1 H 0 2 H 1 H 0 H -1 ''' ''' def fun(n): if n<=1: return print(n) fun(n-1) fun(n-2) n=int(input()) fun(n) input=6 6 5 4 3 2 2 3 2 4 3 2 2 ''' ''' def fun(n): if n<=1: return print(n) fun(n-2) fun(n-1) n=int(input()) fun(n) input=6 6 4 2 3 2 5 3 2 4 2 3 2 ''' def fun(n): if n<=1: return fun(n-2) fun(n-1) print(n) n=int(input()) fun(n) input = 6 2 2 3 4 2 3 2 2 3 4 5 6
ede3267830ccafcd3a73939155ecc0a8f774d27d
CircularWorld/Python_exercise
/month_01/teacher/day16/demo03.py
971
3.84375
4
""" 迭代器 让自定义对象参与for循环 迭代自定义对象 练习:exercise02,03 """ class SkillIterator: def __init__(self, data): self.data = data self.index = -1 def __next__(self): self.index += 1 if self.index < len(self.data): return self.data[self.index] else: raise StopIteration() class SkillManager: def __init__(self): self.__skills = [] def add_skill(self, skill): self.__skills.append(skill) def __iter__(self): return SkillIterator(self.__skills) manager = SkillManager() manager.add_skill("降龙十八掌") manager.add_skill("六脉神剑") manager.add_skill("乾坤大挪移") # 迭代自定义对象 # for skill in manager: # print(skill) iterator = manager.__iter__() while True: try: item = iterator.__next__() print(item) # 降龙十八掌 except StopIteration: break
1ebd447ee36364fd4aa4d8e52feac65d2bc9efc9
radomirbrkovic/algorithms
/dynamic-programming/exercises/maximum-path-sum-triangle.py
446
3.515625
4
# Maximum path sum in a triangle. https://www.geeksforgeeks.org/maximum-path-sum-triangle/ N = 3 def maxPathSum(tri, m, n): for i in range(m - 1, -1, -1): for j in range(i+1): if tri[i +1] [j] > tri[i+1][j +1]: tri[i][j] += tri[i+1][j] else: tri[i][j] += tri[i+1][j+1] return tri[0][0] tri = [[1, 0, 0], [4, 8, 0], [1, 5, 3]] print(maxPathSum(tri, 2, 2))
94d85afd1650593013fed37ba59cedfc813a2c89
faf4r/pynput
/连点器v1.py
1,348
3.5625
4
from pynput import mouse from pynput.mouse import Button, Controller import time def listen(): def on_move(x, y): print('Pointer moved to {0}'.format( (x, y))) def on_click(x, y, button, pressed): print('{0} at {1}'.format( 'Pressed' if pressed else 'Released', (x, y))) if not pressed: # Stop listener return False def on_scroll(x, y, dx, dy): print('Scrolled {0} at {1}'.format( 'down' if dy < 0 else 'up', (x, y))) # Collect events until released with mouse.Listener( on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener: listener.join() # ...or, in a non-blocking fashion: listener = mouse.Listener( on_move=on_move, on_click=on_click, on_scroll=on_scroll) listener.start() def main(times): # input click times listen() time.sleep(2) mouse_c = Controller() for i in range(times): time.sleep(0.1) # 一定要加,不然点太快直接没了 mouse_c.click(Button.left) print('clicked {} times'.format(times)) if __name__ == '__main__': # 运行后先监听,单击左键后,等2秒开始连点 main(50)
99a9b9c7187e1698d6ded73de850f8a22fb09206
tofuadmiral/leetcodermans
/findduplicate.py
633
3.6875
4
class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ """ look for duplicates, at least one duplicate, find it constant extra space can't modify the array runtime should be less than n squared one duplicate number, but could be more than one we know the sum of the numbers should be """ n=len(nums) for i in range(n): for j in range(i+1, n): if nums[i]==nums[j]: return nums[i]
2080483b6560a32ff7e0c920026364483da32b20
basiliomp/intro_to_python
/Intro_to_Python2019-10-07.py
796
4.375
4
# -*- coding: utf-8 -*- """ Seventh session Created on Mon Oct 7 19:33:20 2019 @author: Basilio """ ################### # Mathematical sets ################### # A set is a collection of unique objects s = set() print(len(s)) # Adding the first element into the set 's' s.add('b') print(len(s)) print(s) # Sets do not admit duplicates. # Adding a second (different) element s.add('a') print(len(s)) print(s) # Adding a third (already present!) element s.add('b') print(len(s)) print(s) # Sets are unordered. for element in set([1, 5, 9, 2]): print(element) ################ # More on lists. ################ # Imagine you are storing values in an empty l = [] for i in range(3): l.append(i) print(l) # That would be totally equivalent to: l = [i for i in range(3)] print(l)
b45f505c99ceb493467602b4b379dcd37f1acbf9
OrianaLombardi/Python-
/fundamentos/ejercicio-if.py
388
4.09375
4
mes=int(input("Ingrese un numero de mes(1-12): ")) estacion: None if mes==1 or mes==2 or mes==12: estacion="Invierno" elif mes==3 or mes==4 or mes==5: estacion="Primavera" elif mes==6 or mes==7 or mes==8: estacion="Verano" elif mes==9 or mes==10 or mes==11: estacion="Otoño" else: estacion="Mes incorrecto" print("Estacion: ", estacion , "para el mes:" , mes)
6cdabf4b24903aee31e0a37f83d729945a68b803
AkshayMirashe/Codinjas
/Conditionals & Loops/Assignment_SumOfEven&Odd.py
494
4.125
4
''' Write a program to input an integer N and print the sum of all its even digits and sum of all its odd digits separately. Digits mean numbers, not the places! That is, if the given integer is "13245", even digits are 2 & 4 and odd digits are 1, 3 & 5. ''' n = int(input()) evenSum = 0 oddSum = 0 while n != 0: m = n % 10 n = int(n / 10) if m % 2 == 0: evenSum = evenSum + m else: oddSum = oddSum + m print(str(evenSum) + ' ' + str(oddSum))
6842ce63f7ca84e85cd5b7ac3e94212a7ea534af
maykim51/ctci-alg-ds
/mybst.py
1,492
4.0625
4
''' CTCTI 4.2. Minimal Tree: Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height. ''' ''' Minimal heights = 꽉채워서? BST Soltuion: 루트의 상황으로 생각!!! 무조건!! sub tree개념으로. ''' class Node(): def __init__(self, data): self.data = data self.left, self.right = None, None def __str__(self): print(self.data) class BST(): def __init__(self, root: Node): self.root = root def insert(self, data): node = Node(data) if self.root is None: self.root = node return if data == self.root.data: print('invalid input! dup!') return if data < self.root.data and self.root.left is None: self.root.left = node elif data < self.root.data: BST(self.root.left).insert(data) elif data > self.root.data and self.root.right is None: self.root.right = node elif data > self.root.data: BST(self.root.right).insert(data) return if __name__ == "__main__": n1 = Node(9) bst = BST(n1) bst.insert(7) bst.insert(5) print(bst) # def minialTree(arr, tree = []): # if tree = []: # root = arr[len(arr)//2]
e5d80ea2a252927d9753d86179fd105c6899236f
mengyx-work/CS_algorithm_scripts
/leetcode/LC_318_maximum_word_length_product.py
1,709
3.78125
4
''' 1. use bit to indicate whether a letter exists 2. sor the word list by word length, so the maximum computation O(n^2) a. ASCII value for character: convert ASCII value into character ord('a') ## 97 chr(97) ## 'a' convert character into ASCII value ord('z') ## 122. b. convert string to list list('abc') ## ['a', 'b', 'c'] convert list into set set(['a', 'a', 'b']) ''' class Solution(object): def word2bits(self, word): bits = '' char_set = set(list(word)) for asc_value in range(97, 123): if chr(asc_value) in char_set: bits += '1' else: bits += '0' #return bits return int(bits, 2) def maxProduct(self, words): """ :type words: List[str] :rtype: int """ if len(words) == 0 or len(words) == 1: return 0 #sorted_words = words[:] #sorted_words.sort(key = len, reverse=True) words_in_bits = [self.word2bits(word) for word in words] maxLen = 0 for i in range(len(words_in_bits) -1): word_A = words_in_bits[i] for j in range(i, len(words_in_bits)): word_B = words_in_bits[j] if word_A & word_B == 0: if maxLen < len(words[i]) * len(words[j]): maxLen = len(words[i]) * len(words[j]) return maxLen solut = Solution() #print solut.word2bits('hahab') test_a = ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"] print solut.maxProduct(test_a) test_b = ["a", "ab", "abc", "d", "cd", "bcd", "abcd"] print solut.maxProduct(test_b) test_c = ["a", "aa", "aaa", "aaaa"] print solut.maxProduct(test_c)
b5bcbbeb743fa2df495e303dc70e10e37647fc64
MJC598/Personal-Projects
/MachineLearning/naive_bayes.py
659
3.5
4
#prepping for Machine Learning class by following along with code from Intro to Machine Learning on Udacity #just creating so simple datasets since its Naive Bayes import numpy as np #import data from GSBC data collected #currently throwing an error regarding invalid numbers in np.array, when I have internet check docs on np.array X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) Y = np.array([1, 1, 1, 2, 2, 2]) from sklearn.naive_bayes import GaussianNB classifier = GaussianNB() #fit = train #X is features, Y is labels classifier.fit(X,Y) #ask for prediction, this must always be after fit print(classifier.predict([[-0.8, -1]]))
8cf70328c6a3483dc74c6a2cfc1fb3031de148f6
AlBeck862/rummy_game
/rummy_fxns.py
4,645
3.953125
4
import random import itertools from card import Card from deck import Deck def start_new_hand(): """Initialize a new hand of Rummy 500.""" deck = Deck() #get a new deck hand_size = 10 #10 cards dealt to each player player1_hand = [] #empty player 1 hand player2_hand = [] #empty player 2 hand discard_line = [] #empty discard line (on the tabletop) # Deal cards to player hands from the deck for i in range(hand_size): player1_hand.append(deck.draw()) player2_hand.append(deck.draw()) # Flip the top card of the deck onto the table top to start the discard line discard_line.append(deck.draw()) return deck,discard_line,player1_hand,player2_hand def count_similar_values(player_hand): """Count the number of cards of each value in a player's hand.""" value_counts = [0,0,0,0,0,0,0,0,0,0,0,0,0] #ace through king possible_values = ["a","2","3","4","5","6","7","8","9","10","j","q","k"] # Count the number of cards of each value in the player's hand. for card in player_hand: for val in range(len(possible_values)): if card.get_value() == possible_values[val]: value_counts[val] += 1 return zip(possible_values,value_counts) def has_triplet(player_hand): """ Check if the player has one or many triplets in their hand. Generates a dictionary stating whether a triplet of each value exists in the hand. """ zipped_count = count_similar_values(player_hand) triplets = {key:(True if val==3 else False) for (key,val) in zipped_count} return triplets #{card value:True/False given triplet or not} def has_quartet(player_hand): """ Check if the player has one or many quartets in their hand. Generates a dictionary stating whether a quartet of each value exists in the hand. """ zipped_count = count_similar_values(player_hand) quartets = {key:(True if val==4 else False) for (key,val) in zipped_count} return quartets #{card value:True/False given triplet or not} def sort_for_straights(suit_list): """Sorts a suited list according to card values.""" numerical_list = [False] * 14 #list of 14 None-type spaces, ace-low through ace-high # Establish the order of the cards for card in suit_list: try: num_value = int(card.get_value()) except: if card.get_value() == "jack": num_value = 11 elif card.get_value() == "queen": num_value = 12 elif card.get_value() == "king": num_value = 13 elif card.get_value() == "ace": num_value = 14 else: print("Error: straight sorting failed.") numerical_list[num_value-1] = True numerical_list[0] = numerical_list[13] #force the ace count to be the same in both ace locations # Return a boolean list representing card presence in the given suit, ordered from ace-low to ace-high return numerical_list def has_straight(player_hand): """Check if the player has one or many straights in their hand.""" # Create one list for each suit in the player's hand all_hearts = [] all_diamonds = [] all_clubs = [] all_spades = [] for card in player_hand: if card.is_suit("hearts"): all_hearts.append(card) if card.is_suit("diamonds"): all_diamonds.append(card) if card.is_suit("clubs"): all_clubs.append(card) if card.is_suit("spades"): all_spades.append(card) # Get the order of cards for each suit hearts = sort_for_straights(all_hearts) hearts.append(False) #append False to prevent a list-index error below diamonds = sort_for_straights(all_diamonds) diamonds.append(False) #append False to prevent a list-index error below clubs = sort_for_straights(all_clubs) clubs.append(False) #append False to prevent a list-index error below spades = sort_for_straights(all_spades) spades.append(False) #append False to prevent a list-index error below # Place all suit lists into a single multi-dimensional list all_suits = [hearts,diamonds,clubs,spades] # Package straight cards and lengths together straights = [False] * 20 #this is more than enough slots to cover for the number of possible straights in a hand straight_num = 0 suit_count = 0 for suit in all_suits: suit_count += 1 for i in range(len(suit)): # Edge case for the first index (cannot check the previous index) if i == 0: if suit[0]: start_index = 0 # Detect the start of a potential straight elif suit[i] and not suit[i-1]: start_index = i # Detect the end of a potential straight elif suit[i] and not suit[i+1]: end_index = i if (end_index - start_index) >= 2: straights[straight_num] = (suit_count,start_index,end_index) straight_num += 1 else: pass # Return the suit and the indeces of the cards bounding each straight return straights
933b29e07c4696bf067c15511f5c7055e44e3f72
zombiewafle/Estructure-Class-Lab-No.9
/Lab No.9.py
1,293
3.78125
4
# Author: Javier Salazar # Optional program of the Floyd Algorithm #The import of the math library from math import inf from itertools import product def floyd_warshall(n, edge): #Variables rn = range(n) distance = [[inf] * n for i in rn] nxt = [[0] * n for i in rn] #The addition of ther vertices for i in rn: distance[i][i] = 0 for u, v, w in edge: distance[u-1][v-1] = w nxt[u-1][v-1] = v-1 for k, i, j in product(rn, repeat=3): sum_of_distance_ik_kj = distance[i][k] + distance[k][j] if distance[i][j] > sum_ik_kj: distance[i][j] = sum_ik_kj nxt[i][j] = nxt[i][k] print("pair distance path") for i, j in product(rn, repeat=2): if i != j: path = [i] while path[-1] != j: path.append(nxt[path[-1]][j]) print("City" + "%d → City%d %4d %s" % (i + 1, j + 1, distance[i][j], ' → '.join(str(p + 1) for p in path))) #Show the matrix with the pair, the distance with the path if __name__ == '__main__': floyd_warshall(4, [[1, 3, -2], [2, 1, 4], [2, 3, 3], [3, 4, 2], [4, 2, -1]])
1b63ff94eac013b1eb2ef69af104cbd6fbb24765
meirf57/CS50x-MyProjects
/pset6/mario/mario_less.py
429
4.40625
4
# this is a function to prompt for a digit def number(): global num num = input("height: ") if num.isdigit() == False: num = 0 num = int(num) # using function number() # checking that digit is 1-8 while num < 1 or num > 8: number() sign = num - 1 # printing # in steps shape for i in range(num): for j in range(sign): print(" ", end="") print("#" * (num - sign)) sign = sign - 1
2bc17120a3b02f6b96cb7d60db1fabcbe47efa3a
lechodiman/IIC2233-Learning-Stuff
/Functional/generators.py
429
3.609375
4
def square_numbers(nums): for i in nums: yield(i * i) def double_inputs(): while True: x = yield yield x * 2 def generator_function(): while True: val = yield print(val) if __name__ == '__main__': g = generator_function() next(g) g.send('Holi') g.send('Chao') # gen = double_inputs() # next(gen) # print(gen.send(10)) # print(gen.send(20))
d4b339c4ab50eddfed622bfaff236f7730b30fda
Rodger-M/Machine-Learning-Python
/Regression/Multiple Linear Regression/multiple_linear_regression_m.py
1,664
3.9375
4
# Multiple Linear Regression # Importing the libraries # Importando as bibliotecas import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset # Importando os dados dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values # Encoding categorical data # Codificando dados categóricos from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder = LabelEncoder() X[:, 3] = labelencoder.fit_transform(X[:, 3]) onehotencoder = OneHotEncoder(categorical_features = [3]) X = onehotencoder.fit_transform(X).toarray() # Avoiding the Dummy Variable Trap - Skipping one encoded column # Evitando "Dummy Variable Trap" - Pulando uma coluna codificada X = X[:, 1:] # Splitting the dataset into the Training set and Test set # Dividindo os dados em conjunto de treino e teste from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # Feature Scaling (We don't use this time) # Recurso de escalonamento (Não usamos desta vez) """from sklearn.preprocessing import StandardScaler sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) sc_y = StandardScaler() y_train = sc_y.fit_transform(y_train)""" # Fitting Simple Linear Regression to the Training Set # Ajustando a Regressão Linear Simples ao conjunto de treino from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) # Predicting the Test set results # Predizendo os resultados do conjunto de teste y_pred = regressor.predict(X_test)
111f578358b04a67edc011cab30168c2dc578e86
MauricioBritoCon/EstudosdePython
/Mundo2/CondicoesAninhadas.py
5,143
3.859375
4
import datetime import random computador = random.randint(0, 2) usuario = input("Escolha entre 'pedra' 'papel' 'tesoura': ") usuario = usuario.lower() if computador == 0: escolha = 'pedra' elif computador == 1: escolha = 'papel' else: escolha = 'tesoura' if computador == 0 and usuario == 'pedra' or computador == 1 and usuario == 'papel' or computador == 3 and usuario == 'tesoura' : print(f"Você empatou pois o computador escolheu {escolha} e você tambem.") elif computador == 0 and usuario == 'papel' or computador == 1 and usuario == 'tesoura' or computador == 2 and usuario == 'pedra': print(f"Você ganhou pois o computador escolheu {escolha} e você {usuario}.") else: print(f'Você perdeu pois escolheu {usuario} e o computador escolheu {escolha}') preco = float(input("Digite o preço do produto: R$")) forma = input("Digite a forma de pagamento 'cheque' 'dinheiro' 'cartao' '2xcartao' ou '3x+cartao'") if forma == 'dinheiro' or forma == 'cheque': print(f"O produto vai custar {preco - (preco * 0.10)}") elif forma == 'cartao': print(f"O produto vai custar {preco - (preco * 0.05)}") elif forma == '2xcartao': print(f"O produto vai custar {preco}") elif forma == '3x+cartao': print(f"O produto vai cust {preco + (preco * 0.20)}") else: print("Forma de pagamento invalida") anoAtual = datetime.datetime.now() peso = float(input("Digite seu peso em kg: ")) altura = int(input("Digite sua altura cm: ")) imc = peso / ((altura / 100) ** 2) if imc < 18.5: print("Você esta abaixo do peso") elif imc >= 18.5 and imc < 25: print("Você esta no peso ideal") elif imc >= 25 and imc < 30: print("Você tem sobrepeso") elif imc >= 30 and imc < 40: print("Você tem obesidade") else: print("Voce tem obesidade morbida") reta1 = float(input(f"Digite o comprimento da primeira reta: ")) reta2 = float(input(f"Digite o comprimento da segunda reta: ")) reta3 = float(input(f"Digite o comprimento da terceira reta: ")) if reta1 + reta2 >= reta3 and reta3 + reta2 >= reta1 and reta3 + reta1 >= reta1: if reta1 == reta2 and reta2 == reta3: print(f"O triangulo é equilatero") elif reta1 == reta2 or reta3 == reta1: print(f"Este é um triangulo isósceles tem 2 lados iguais") else: print("Este triangulo é escaleno") else: print("Estas retas nao fazem um triangulo") anoNascimento = int(input("Digite aqui o ano do seu nascimento: ")) idade = anoAtual.year - anoNascimento if idade <= 9: print(f"Você tem {idade}anos e pertence aos nadadores mirim") elif idade <= 14: print(f"Você tem {idade}anos e pertence aos nadadores infantis") elif idade <= 19: print(f"Você tem {idade}anos e pertence aos nadadores junior") elif idade == 20: print(f"Você tem {idade}anos e pertence aos nadadores sênior") else: print(f"Você tem {idade}anos e pertence aos nadadores master") nota1 = float(input("Digite sua primeira nota: ")) nota2 = float(input("Digite sua segunda nota: ")) mediaNota = (nota1 + nota2) / 2 if mediaNota < 5.00: print(f"Parabens você foi reprovado com a media {mediaNota}") elif 5 <= mediaNota <= 6.9: print(f"Parabens você esta de recuperação com a media {mediaNota}") else: print(f"Meus pesames você foi aprovado com a media {mediaNota}") nascimento = int(input("Digite o ano de nascimento: ")) idade = anoAtual.year - nascimento if idade > 18: print(f"Já passou o tempo do seu alistamento em {idade - 18}anos") elif idade == 18: print("Esta na hora de se alistar") else: print(f"Ainda faltam {18 - idade} anos para você se alistar ") n1 = int(input("Digite o primeiro numero inteiro: ")) n2 = int(input("Digite o segundo numero inteiro: ")) if n1 > n2: print("O primeiro numero é maior") elif n2 > n1: print("O segundo numero é maior") else: print("Ambos são iguais") opcao = int(input("Digite '1' para converter em binario '2' em octa e '3' em hexa: ")) numero = int(input("Digite um numero que queria converter para binario: ")) if opcao == 1: numeroBi = bin(numero) print(f"O numero {numero} em binario é: {numeroBi}") elif opcao == 2: numeroOcta = oct(numero) print(f"O numero {numero} em octa é: {numeroOcta}") elif opcao == 3: numeroHexa = hex(numero) print(f"O numero {numero} em hexa é: {numeroHexa}") else: print("Digite uma opção valida") valorCasa = float(input("Digite o valor da casa sem ponto: R$")) salario = float(input("Digite o valor do seu salario: R$")) tempo = int(input("Em quantos anos quer pagar o emprestimo? ")) valorPrestacao = valorCasa / (tempo * 12) if valorPrestacao >= (salario * 0.30): print("Seu emprestimo não foi aprovado pois o valor mensal supera 30% do seu salario") print(f"O valor do seu emprestimo mensal: R${valorPrestacao} e seu salario é R${salario}") elif valorPrestacao < (salario * 0.30): print(f"Seu emprestimo foi aprovado pois o valor de R${valorPrestacao} é menor que 30% de seu salario de R${salario}")
d851e0130a4835c40033926e46aa805d999ea8ea
siyingl6/Algorithmic-Trading-Bot
/venv/lib/python3.6/site-packages/fmclient/data/message.py
1,758
3.53125
4
import datetime from enum import Enum class Message(object): """ Class for abstract the message entity. The messages will be exchanged between a web browser and the algorithm. """ def __init__(self, source, content, type, date=datetime.datetime.utcnow(), name=None): """ The message type is defined by the content, the type of the message, the date of creation, and an optional name. The name attribute is relevant only for custom messages. :param source: source of the message. :param type: message type (one of MessageType enum). :param content: content of the message. :param date: date of message. :param name: optional name for custom message types. """ self._source = source self._type = type self._content = content self._date = date self._name = name @property def source(self): return self._source @source.setter def source(self, value): self._source = value @property def type(self): return type @type.setter def type(self, value): self._type = value @property def content(self): return self._content @content.setter def content(self, value): self._content = value @property def name(self): return self._name @name.setter def name(self, value): self._name = value class MessageType(Enum): """ Message types for the messages that the trading algorithm will exchange with the web browser. The message types are for the algorithmic logic and not the python code. """ ERROR = 1 DEBUG = 2 INFO = 3 WARN = 4 CUSTOM = 5 USER = 6 COMM = 7
2413a8b38b5da912a19ecd7ceeabd9c9a5aacf04
sirejik/software-design-patterns
/creational_patterns/builder/builder.py
1,112
4.3125
4
""" Separates the construction of a complex object from its representation, so that different representations can result from the same design process. """ from abc import ABCMeta, abstractmethod class Product: def __init__(self): self.param = None def set_param(self, param): self.param = param def __repr__(self): return 'Product with the following parameters: parameter \'{}\'.'.format(self.param) class Builder(metaclass=ABCMeta): def __init__(self): self.product = Product() @abstractmethod def build(self): pass def get_product(self): return self.product class ConcreteBuilder(Builder): def build(self): self.product.set_param('param') class Director(metaclass=ABCMeta): def __init__(self, builder: Builder): self.builder = builder def build(self): self.builder.build() def get_product(self): return self.builder.get_product() concrete_builder = ConcreteBuilder() director = Director(concrete_builder) director.build() product = director.get_product() print(product)
2d3b1373fd48e20acd707d3b248a6bfc40006abc
Jhesker/StatisticalComputing
/HeskerStatComp1/11.1codeImplimentation.py
2,884
3.625
4
# -*- coding: utf-8 -*- """ Created on Wed Jul 24 21:12:50 2019 @author: jhesk """ class Node(object): def __init__(self, name): self.name = name def getName(self): return self.name def __str__(self): return self.name class Edge(object): def __init__(self, src, dest): self.src = src self.dest = dest def getSource(self): return self.src def getDestination(self): return self.src.getName() + '->(' + str(self.weight) + ')'\ + self.dest.getName() class Digraph(object): def __init__(self): self.nodes = [] self.edges = {} def addNode(self, node): if node in self.nodes: raise ValueError('Duplicate node') else: self.nodes.append(node) self.edges[node] = [] def addEdge(self, edge): src = edge.getSource() dest = edge.getDestination() if not (src in self.nodes and dest in self.nodes): raise ValueError('Node not in graph') self.edges[src].append(dest) def childrenOf(self, node): return self.edges[node] def hasNode(self, node): return node in self.nodes def __str__(self): result = '' for src in self.nodes: for dest in self.edges[src]: result = result + src.getName() + '->'\ + dest.getName() + '\n' return result[:-1] class Graph(Digraph): def addEdge(self, edge): rev = Edge(edge.getDestination(), edge.getSource()) Digraph.addEdge(self, rev) def printPath(path): result = '' for i in range(len(path)): result = result + '->' return result def BFS(graph, start, end, toPrint = False): initPath = [start] pathQueue = [initPath] if toPrint: print('Current BFS path:', printPath(path)) while len(pathQueue) != 0: tmpPath = pathQueue.pop(0) print('Current BFS path:', printPath(tmpPath)) lastNode = tmpPath[-1] if lastNode == end: return tmpPath for nestNode in graph.childrenOf(lastNode): if nestNode not in tmpPath: newPath = tmpPath + [nestNode] pathQueue.append(newPath) def test(): nodes = [] for name in range(6): nodes.append(Node(str(name))) g = Digraph() for n in nodes: g.addNode(n) g.addEdge(Edge(nodes[0],nodes[1])) g.addEdge(Edge(nodes[1],nodes[2])) g.addEdge(Edge(nodes[2],nodes[3])) g.addEdge(Edge(nodes[2],nodes[4])) g.addEdge(Edge(nodes[3],nodes[4])) g.addEdge(Edge(nodes[3],nodes[5])) g.addEdge(Edge(nodes[0],nodes[2])) g.addEdge(Edge(nodes[1],nodes[0])) g.addEdge(Edge(nodes[3],nodes[1])) g.addEdge(Edge(nodes[4],nodes[0])) g = test() sp = BFS(g, nodes[0], nodes[5]) print('Shortest path found by BFS:', printPath(sp))
627f0ec95dd584a25f43722f110f08103a641d2a
0n1udra/Learning
/Python/Python_Problems/Rosalind-master/019_PERM.py
839
3.78125
4
#!/usr/bin/env python ''' A solution to a ROSALIND bioinformatics problem. Problem Title: Enumerating Gene Orders Rosalind ID: PERM Rosalind #: 019 URL: http://rosalind.info/problems/perm/ ''' from itertools import permutations def factorial(n): '''Returns the value of n!''' if n < 2: return 1 else: return n*factorial(n-1) with open('data/rosalind_perm.txt') as input_data: perm_set = range(1, int(input_data.read())+1) # Create a list containing ordered lists of all permutations. perm_list = map(list,list(permutations(perm_set))) with open('output/019_PERM.txt', 'w') as output_data: # Write the total number of permutations, n! output_data.write(str(factorial(len(perm_set)))) # Write the permuations in the desired format. for permutation in perm_list: output_data.write('\n'+' '.join(map(str,permutation)))
80c3d50c8f0445a7cdc5fcc301f975c6297fe52a
sonthanhnguyen/projecteuler
/project_euler_21.py
2,149
3.875
4
""" Project Euler 21: Amicable numbers Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a <> b, then a and b are an amicable pair and each of a and b are called amicable numbers. For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220. Evaluate the sum of all the amicable numbers under 10000. """ import time def find_divisor_sum(number): """ Find sum of all proper divisors of a number :param number: :return: sum of all proper divisors of that number """ sum1 = 0 for i in range(1, number): if number % i == 0: # i is a divisor sum1 += i return sum1 def find_amicable_pairs(number): """ Find all amicable pairs for numbers less than the number :param number: :return: a list of all amicable pairs """ # Create a list containing sum of all proper divisors of i, with i ranging from 1 to n. # This list contains n items list_of_sum = [find_divisor_sum(i) for i in range(1, number + 1)] # 'pairs' is a list in which each component is an amicable pair pairs = [] # Loop through 'list_of_sum' to find every amicable pairs for i in range(1, number): temp = list_of_sum[i] # Check if there is any number that forms a pair with this 'temp' value if (temp >= 1 and i + 1 < temp <= number and list_of_sum[temp - 1] == i + 1): # Find the pair, add it to 'pairs' pairs.append([i + 1, temp]) return pairs def find_amicable_sum(pairs): """ Find sum of all pairs """ return sum([sum(pair) for pair in pairs]) def main(): """ Test function """ number = 10000 start_time = time.time() result = find_amicable_sum(find_amicable_pairs(number)) stop_time = time.time() print("Result is {0} found in {1} seconds".format(result, stop_time - start_time)) if __name__ == '__main__': main()
2d3a49e3b209c563a6d500a93cb328922658d924
AlexLinGit/SICP-and-Other-Code
/Python Crash Course Exercises/chapter 7 - while and input/rollercoaster.py
249
4.25
4
height = input("How tall are you, in inches? ") height = int(height) if height >= 36: print("You are eligible to ride!") elif height <= 0: print("Ain't no one that short. Enter a new value.") else: print("You are too short, midget!")
ccf9030ee228ffd57e6bdf782596d01652a41815
JasonVann/CrackingCodingInterview
/LeetCode/Ex700/Ex720.py
5,674
3.859375
4
class TrieNode: def __init__(self): self.child = [None]*26 self.is_end_of_word = False class Dis(object): def longestWord3(self, words): ans = "" wordset = set(words) for word in words: if len(word) > len(ans) or len(word) == len(ans) and word < ans: if all(word[:k] in wordset for k in xrange(1, len(word))): ans = word return ans def longestWord2(self, words): resword, res = '', {''} for word in sorted(words): if word[:-1] in res: res.add(word) resword = max(resword, word, key=len) return resword def longestWord(self, words): # Python2 import collections from functools import reduce Trie = lambda: collections.defaultdict(Trie) trie = Trie() END = True for i, word in enumerate(words): reduce(dict.__getitem__, word, trie)[END] = i stack = trie.values() ans = "" while stack: cur = stack.pop() if END in cur: print(39, cur, END, cur[END], words[cur[END]]) word = words[cur[END]] if len(word) > len(ans) or len(word) == len(ans) and word < ans: ans = word stack.extend([cur[letter] for letter in cur if letter != END]) return ans class HashTable: def longestWord(self, words): """ :type words: List[str] :rtype: str """ lookup = set() for word in words: lookup.add(word) best = '' for word in words: for i in range(len(word)+1): if word[:i+1] in lookup: if i > len(best): best = word[:i+1] elif i == len(word) and len(word) == len(best) and word < best: best = word else: break return best class Solution: def longestWord(self, words): """ :type words: List[str] :rtype: str """ trie = Trie() for word in words: trie.addWord(word) node = trie.root best = '' path = '' best = self.expand(node, path, best) return best def expand(self, node, path, best): last_node = node for idx, child in enumerate(node.child): if child: new_path = path + chr(idx+ord('a')) if child.is_end_of_word: if len(best) < len(new_path): best = new_path elif len(best) == len(new_path) and new_path < best: best = new_path best = self.expand(child, new_path, best) return best class Trie2: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() # self.child = [None]*26 # self.is_end_of_word = False def addWord(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ node = self.root for i in range(len(word)): idx = ord(word[i])-ord('a') if node.child[idx] == None: node2 = TrieNode() node.child[idx] = node2 node = node.child[idx] node.is_end_of_word = True def search(self, word): """ Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. :type word: str :rtype: bool """ if len(word) == 0: return False node = self.root if '.' not in word: return self.exact_search(word) return self.node_search(word, node) def node_search(self, word, node): for i in range(len(word)): idx = ord(word[i])-ord('a') if word[i] != '.': if node.child[idx] == None: return False else: node = node.child[idx] else: for j in range(26): if node.child[j] != None: res = self.node_search(word[i+1:], node.child[j]) if res: return True return False return node.is_end_of_word def exact_search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ node = self.root for i in range(len(word)): idx = ord(word[i])-ord('a') if node.child[idx] == None: return False node = node.child[idx] return node.is_end_of_word def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ node = self.root for i in range(len(prefix)): idx = ord(prefix[i])-ord('a') if node.child[idx] == None: return False node = node.child[idx] return True words = ["w","wo","wor","worl","world"] #words = ["m","mo","moc","moch","mocha","l","la","lat","latt","latte","c","ca","cat"] words = ["yo","ew","fc","zrc","yodn","fcm","qm","qmo","fcmz","z","ewq","yod","ewqz","y"] #words = ['y', 'yo', 'yod', 'yodn'] #words = reversed(words) Ex720 = Solution() Ex720 = Dis() print(Ex720.longestWord(words))
c8820b2f437f1423e6b1fc658c9da58a1e183fae
matthappens/iterator_talk
/code/tree.py
2,263
3.734375
4
import random class IterableTree(object): def __init__(self): self.root = None def __iter__(self): self.clear_visited() return InorderTraversalIterator(self.root) def insert(self, value): z = TreeNode(value) parent = None traverse = self.root while traverse: parent = traverse if z.value < traverse.value: traverse = traverse.left else: traverse = traverse.right z.parent = parent if parent is None: self.root = z elif z.value < parent.value: parent.left = z else: parent.right = z def inorder_traversal(self, node): def it(node): if node: it(node.left) print node.value it(node.right) it(self.root) def clear_visited(self): """ Use this to reset the tree between iterations """ def unvisit(n): if n: n.visited = False unvisit(n.left) unvisit(n.right) unvisit(self.root) class InorderTraversalIterator(object): def __init__(self, root): self.root = root self.t_stack = [self.root] def next(self): if len(self.t_stack) > 0: node = self.t_stack.pop() while (node.left is not None and not node.left.visited): self.t_stack.append(node) node = node.left if node.right: self.t_stack.append(node.right) node.visited = True return node else: raise StopIteration() class TreeNode(object): def __init__(self, value): self.value = value self.left = None self.right = None self.parent = None self.visited = False def __repr__(self): return self.value def make_tree(): it = IterableTree() for i in range(16): it.insert(random.randint(0, 16)) return it def inorder_traversal(tree): def _inorder(node): if node: _inorder(node.left) print(node.value) _inorder(node.right) _inorder(tree.root)
f73e64b0a3bc08400a0205d7aacda60ba3e32ba0
helbertsandoval/verificadores-conversores-impresion-tipo-boleta
/conversores_booleano.py
836
4.09375
4
#1 Convertir el real 85.2 a booleano x=85.2 a = bool(x) print (a, type(a)) #2 Convertir el entero 105 a booleano x =105 a = bool(x) print (a, type(a)) #3 Convertir la cadena75 a booleano x ="75" a = bool(x) print (a, type(a)) #4 Convertir la cadena 205 a booleano x ="205" a = bool(x) print (a, type(a)) #5 Convertir la cadena 95 a booleno x ="95" a = bool(x) print (a, type(a)) #6 Convertir el entero 110 a booleano x =110 a = bool(x) print (a, type(a)) #7 Convertir el entero 210 a booleano x =210 a = bool(x) print (a, type(a)) #8 Convertir la booleano 530 a booleano x =(530==530) a = bool(x) print (a, type(a)) #9 Convertir el real 31.3 a booleano x =31.3 a = bool(x) print (a, type(a)) #10 Convertir el booleano 115 a booleano x =(115==115) a = bool(x) print (a, type(a))
251d15629f898fe7d65af27ff0e4735f95775429
GuanYangCLU/AlgoTestForPython
/LeetCode/linkedList/0025_Reverse_Nodes_in_k-Group.py
1,050
3.671875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: # as max length is 5000, should valid for recursion, link to a asuumed reversed tail # length check if not head: return None checkIndexPointer = head for i in range(k): if not checkIndexPointer: # length < k return head checkIndexPointer = checkIndexPointer.next # length >= k head, tail = self.reverseAll(head, k) tail.next = self.reverseKGroup(checkIndexPointer, k) return head def reverseAll(self, head, k): if not head: return (None, None) if k == 1: return (head, head) newHead, newTail = self.reverseAll(head.next, k - 1) head.next = None newTail.next = head return (newHead, head)
ff0350292913f5b0b07e5685e597fbc5471c6a82
Luca2460/Imeneo-Leetcodes-Solutions-in-Python
/13. Roman to Integer.py
680
3.859375
4
def romanToInt(s: str) -> int: # note: len(s) <= 15 out = 0 symbols = {'M':1000, 'CM':900, 'D':500, 'CD':400, 'C':100, 'XC':90, 'L':50, 'XL':40, 'X':10, 'IX': 9, 'V':5, 'IV':4, 'I':1} while len(s) != 0: if s[-2:] in symbols: out = out + symbols[s[-2:]] s = s[:-2] else: out = out + symbols[s[-1]] s = s[:-1] return out # TIME complexity: O(N), where N is the length of the string (One might also say O(1) since the maximum cost is known and constant) # SPACE complexity: O(1)
8af83ac2c0fe7c48146b52e564db417e86f11a72
yhuang13/projecteuler
/problem6.py
356
3.65625
4
#etween the sum of the squares of the first one hundred natural numbers and the square of the sum. min_num = 1 max_num = 100 sum_square = 0 for x in range(min_num, max_num + 1): sum_square += x**2 square_sum = 0 for x in range(min_num, max_num + 1): square_sum += x square_sum = square_sum ** 2 print square_sum - sum_square
d5d3862dc089e0ddee1a548ffdba9632f13515d3
Aasthaengg/IBMdataset
/Python_codes/p03826/s651345424.py
300
3.78125
4
height_a, length_a, height_b, length_b = map(int, input().split()) rectangle_a = height_a * length_a rectangle_b = height_b * length_b if rectangle_a == rectangle_b: print(rectangle_a) elif rectangle_a > rectangle_b: print(rectangle_a) elif rectangle_b > rectangle_a: print(rectangle_b)
8b4ac3603cb25ed412c241e7add97952d29ab866
millanmilu/Learn-Python-with-Milu-
/53_class_sup.py
260
3.71875
4
class Vehicle: def start(self): print("starting engine") def stop(self): print("stopping engine") class TwoWheeler(Vehicle): def say(self): super().start() print("i Have two wheels") super().stop() a = TwoWheeler() a .say()
122810a056dc0623a00f4fb2174b2aa0151bdd06
tammyvitorino/AD1-Cederj_ProgramacaoComInterfacesGraficas
/Projeto Vídeo Locadora/DVD.py
1,548
3.546875
4
#!/usr/bin/env python # coding: UTF-8 # ## @package DVD # # @author Tamara Vitorino # @since 23/08/2017 import AbstractItem, sys, datetime class DVD(AbstractItem.AbstractItem): ## # Constructs a new Item with the given title, genre, and barcode. # This constructor may only be invoked by subclasses. # @param title the title of the item # @param genre the genre of the item # @param barcode a unique integer identifier for the item # def __init__(self, title, genre, barcode): z = 350 super().__init__(title, genre, barcode, z) ## # Rents this item if it is not already rented and sets the # due date. # @param today # the date on which this item is being rented # the loanDuration # @throws Exception # if the item cannot be rented # def setRented(self, today, x = 5): super().setRented(today, x) ## # Return the bonuses and free when they aplly # def calculateLateFee(self, today): AbstractItem.AbstractItem.firstDay = 100 AbstractItem.AbstractItem.otherDays = 100 return AbstractItem.AbstractItem.calculateLateFee(self, today) # Tests def main(): item1 = DVD("A Movie Name", "Action", 1) print(item1) item1.setRented(datetime.datetime.today()) print(item1) print("Late Fee: ", item1.calculateLateFee(datetime.datetime.today())) print("Rental Cost: ", item1.getRentalCost()) item1.setRented(datetime.datetime.today()) if __name__ == "__main__": sys.exit(main())
a3f01e06cc170831e99324d76fb86266e417579f
triztian/UCLAIntroDataScience
/Module2/module2b.py
5,821
4.3125
4
# Module 2b # Author: Tristian Azuara # Email: tristian.azuara@gmail.com # UCLA: Introduction to Data Science # print('# A) Variables, types and casting') # Unlike other languages like javascript, python does not implicitly cast # objects into strings when using the '+' operator with strings. # One must cast any non-str objects into strings a = 1 b = 'one' r = str(a) + b print(r) print("""# B) Create a list of integers, strings, i.e. someList = [3, ' S', 'B', 21] # Separate the list into one of only strings, and one of only intergers.""") mix_list = [3, 'S', 'B', 21, 99, 78, 'aa', 'xx'] def make_type_filter(typ): """Creates a filter for the provided type. It will return `True` if the element matches the provided type. """ return lambda x: type(x) is typ # We use the `filter` function and a function that creates a filter to be applied # to each element of the list. ints = list(filter(make_type_filter(int), mix_list)) # We use a list comprehension along with a filter expression that checks for the appropriate # types. For this particular use case the comprehension is far easier to read. strs = [x for x in mix_list if type(x) is str] print(ints) print(strs) print("""C) Compare and contrast the data structure from the official Python list of # data structures (i.e. tuples, dicts, lists), i.e. Tuples are the ONLY # immutable data structure (there are lists, tuples, sets, dictionaries)""") # Lists # Lists allow us to have a heterogenous sequence of elements, elements # can be repeated. # Lists can be combined, extended, sliced `[:]`, traversed in for-loops and # elements can be accessed by indexes in square brackets `my_list[3]` my_list = ['1', 99, 84, 2.8] print(my_list) # Sets # Sets like lists can hold a heterogenous _collection_ of elements, however # the order of the elements in a set is not guaranteed, a set by definition is # an unordered collection (like dictionaries) a `Set` also does not allow for # duplicate elements, set elements are not accessed by index set elements must # be hashable and support some of the mathematical set operations. my_set = {1,2,2,2,2,2,1,3, 'a', 'a'} empty_set = set() print(my_set) # {1, 2, 3, 'a'}, order may change # Dictionaries # A dictionary defines a mapping of keys to values. The key element must be # hashable (a unique identity can derived for it), the value element doesn't # have to be hashable. # A dictionary value can be a complex data structure such as a class or even # another dictionary, set, list or tuple my_dict = {'a': 99, 'b': 42, 'c': 'string!', 99: [1, 2, 3], 88: {1,2,2,2,3}} empty_dict = {} # Tuples # A tuple is an immutable data structure in Python, it is simply an ordered collection # of values, because tuples are _immutable_ their contents cannot be reassigned # after they've been created (however, if the values happen to be classes the can mutate # their internal state). Also unlike lists or dictionaries, tuples can be used # as dictionary keys because of their immutability my_tuple = (1, 2, 3, 'a', 'b', 'c') empty_tuple = () print("""# D) Compare and contrast some Python specialized data types/objects # (please select at least a minimum of 2 items, i.e. datetime, collections)""") # Datetime, Timedelta # Manupilating dates and computing differences between them is a common task # when analyzing data, it's also used for calculating deadlines, time elapsed # and more specifically to plot time series graphs. # Datetime is provided by the datetime package, it's imported like so: # # from datetime import datetime # # One may be tempted to simply represent a date and time as tuples, dictionaries, # lists or as a custom class, however the Python3 standard library already # includes functions and methods that take care of timezone information, # translation between timezones, computation and addition or subtraction to date # not no mention handling many of the nuances of our date and time systems (such # as daylight savings, formatting, localization, etc) # # Subtracting ('-' operator) 2 dates yields a `timedelta` object which contains # the difference in days, seconds and years between such dates, timedelta objects # can be added ('+' operator) to other datetime and timedelta objects to produce # new dates and timedelta objects. from datetime import datetime now = datetime.now() # current date and time with the computer's timezone # Months are 1-based (unlike list or tuple indexes) b = datetime(2020, 2, 3) # Last Monday a = datetime(2020, 2, 10) # Next Monday diff = a - b # Time delta fortnight = diff * 2 # or diff + diff b + fortnight # Payday! # Enum # An enumeration is a way to define a finite set of values that are different # instances or occurrences within a category. # It defines unique constant symbols that can be compared and iterated. For example # usually one defines a list of operations modes to global variables, instead # An enum structure could be used that would provide iteration, value protection ( # by making it a constant) and it'd also improve readability. Because Enums # are hashable, they can be used as dictionary keys from enum import Enum class OperationMode(Enum): PRODUCTION = 1 DEBUG = 2 print(OperationMode.PRODUCTION) print("""# E) Write a function that separates out the negative and positive integers in # a list, i.e. someList = [3,-3, 4, -5]""") def split_sign(numbers, exclude_zero=False): """Splits a list of numbers by their sign""" positive = [] negative = [] for x in numbers: if x < 0: negative.append(x) elif x > 0: positive.append(x) else: # 0 goes on both?, or it could be excluded if not exclude_zero: negative.append(x) positive.append(x) return (positive, negative) numbers = [1, 2, 3, 4, -0, 0, -2, -4, 5, 2, -1, -56, 9, -33] pos, neg = split_sign(numbers) print(neg) print(pos)
d1107f6cf16d534ba7794d9556e737cf3df4e6c7
shaktisinghmandhan/data_structure
/linked_list/k_consecutive_nodes_string.py
741
3.78125
4
from linked_list import LinkedList def k_consecutive_nodes_string(head, k): result = "" j = k while head and j >= 0: if j == 0: j = k result += " " else: j = j - 1 result += head.data head = head.next return result if __name__ == '__main__': head = LinkedList('a') head.next = LinkedList('b') head.next.next = LinkedList('c') head.next.next.next = LinkedList('d') head.next.next.next.next = LinkedList('e') head.next.next.next.next.next = LinkedList('f') head.next.next.next.next.next.next = LinkedList('g') head.next.next.next.next.next.next.next = LinkedList('h') print k_consecutive_nodes_string(head, 3)
420b68a6cd270854a4199e21385e581df4647e3e
fly2rain/LeetCode
/move-zeroes/move-zeroes.py
683
3.515625
4
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ nonzero_idx = 0 for current_idx in range(len(nums)): if nums[current_idx]: nums[nonzero_idx] = nums[current_idx] nonzero_idx += 1 else: pass for zero_idx in range(nonzero_idx, len(nums)): nums[zero_idx] = 0 if __name__ == '__main__': nums = [1, 0, 2, 0, 4] Solution().moveZeroes(nums) print nums nums = [0, 1, 0, 3, 12, 0] Solution().moveZeroes(nums) print nums
5dc073a3f190362d3e1687a5106b275ef82d85ea
IvanWoo/coding-interview-questions
/puzzles/top_k_frequent_elements.py
1,313
3.90625
4
# https://leetcode.com/problems/top-k-frequent-elements/ """ Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2: Input: nums = [1], k = 1 Output: [1] Constraints: 1 <= nums.length <= 105 k is in the range [1, the number of unique elements in the array]. It is guaranteed that the answer is unique. Follow up: Your algorithm's time complexity must be better than O(n log n), where n is the array's size. """ import heapq from collections import Counter, defaultdict def top_k_frequent(nums: list[int], k: int) -> list[int]: counter = defaultdict(int) for n in nums: counter[n] += 1 sorted_q = sorted([(val, key) for key, val in counter.items()], reverse=True) return [key for _, key in sorted_q[0:k]] def top_k_frequent(nums: list[int], k: int) -> list[int]: counter = Counter(nums) return [key for key, _ in counter.most_common(k)] # https://github.com/python/cpython/blob/4b107d86f38f6778562d4fe5e1d881b52c9d9d6c/Lib/collections/__init__.py#L625-L630 def top_k_frequent(nums: list[int], k: int) -> list[int]: if k == len(nums): return nums c = Counter(nums) return heapq.nlargest(k, c.keys(), key=c.get)
44796c76337d1d79711ef03be3cb9f668625fbda
Amrisha0306/python-task3
/c5.py
324
3.953125
4
W= input('Please enter a string: ') def most_frequent(string, reverse= False): d = dict() for key in string: if key not in d: d[key] = 1 else: d[key] += 1 return dict(sorted(d.items(), key = lambda x: x[1], reverse = reverse)) print (most_frequent(W, True))
3e8b2f65228cb1c3fc8badc726fbfdf72c70f3ac
shenchuang006/python
/calc.py
735
3.671875
4
# coding=utf-8 import sys; def add(a, b): return a + b; # 这时,要解析传递的参数,需要用到 sys 模块: if __name__ == '__main__': #意思是说:模块既可以被导入(到 Python shell 或者其他模块中),也可以作为脚本来执行 args = sys.argv # 用于获取命令行参数 print(args) print(add(int(args[1]), int(args[2]))); ''' 没错,通过 sys.argv 可以获取命令行参数,它是一个 list 类型。 sys.argv[0] 表示代码本身文件路径,参数索引从 1 开始。 使用很简单,参数之间以空格隔开: $ python calc.py 2 3 ['calc.py', '2', '3'] 5 $ python calc.py 4 5 ['calc.py', '4', '5'] 9 ''' print("__name__",__name__);
3a6f47d24e0cbecc5b399eec78e829c4568d6578
Parolo41/advent-of-code-202
/D3P1.py
499
3.640625
4
inputFile = open('D3P1.txt', 'r') FileLines = inputFile.readlines(); xPosition = 0 xVelocity = 3 treeCount = 0 for line in FileLines: xPosition %= (len(line) - 1) pointer = '' pointer += ' ' * xPosition pointer += 'v' print(pointer) print(line[:-1]) if line[xPosition] == '#': treeCount += 1 print("yes tree") else: print("no tree") print() xPosition += xVelocity print(f"There are {treeCount} trees")
0eee0cff7baa1859e16d2cc5eeb67421f5236034
jrjed/advent_of_code_2016
/day6/script6.py
753
3.59375
4
import collections def readcol(datafile): with open(datafile) as f: rows = [] for line in f: rows.extend(line.split()) columns = zip(*[list(row) for row in rows]) f.close() return columns def decode_col(columns, rank): code = '' for column in columns: count = collections.Counter(column) if rank.lower() == 'most': sel = 0 elif rank.lower() == 'least': sel = len(count) - 1 letter = count.most_common()[sel][0] code += letter return code def main(): # Part 1 print(decode_col(readcol('input6.txt'), 'most')) # Part 2 print(decode_col(readcol('input6.txt'), 'least')) if __name__ == '__main__': main()
0fe749861eb9ea3ef034d1013a5a8a898b322153
arpan0317/AI440
/Project_3/Code3_asg235_ftt7.py
10,255
3.65625
4
import random import sys import csv class point: def __init__(self, col: int, row: int): self.col = col self.row = row #state 1 = flat, 2 = hilly, 3 = forested, 4 = maze of caves class cell: def __init__(self, pt: point, state, prob): self.pt = pt self.state = state self.prob = prob #make a map with each cell being randomly assigned a state #make a FalseNegativeMap with each cell holding the chance of a false negative for that type of state #setting a random target cell class land: def __init__(self): self.dim = 50; self.FalseNegativeMap = [ [ None for i in range(self.dim) ] for j in range(self.dim) ] self.map = [ [ None for i in range(self.dim) ] for j in range(self.dim) ] for i in range(0, self.dim): for j in range(0, self.dim): pt = point(i,j) rand = random.randint(1, 4) c = cell(pt, rand, float.hex(1/2500)) if rand == 1: self.FalseNegativeMap[i][j] = float.hex(0.1) elif rand == 2: self.FalseNegativeMap[i][j] = float.hex(0.3) elif rand == 3: self.FalseNegativeMap[i][j] = float.hex(0.7) elif rand == 4: self.FalseNegativeMap[i][j] = float.hex(0.9) self.map[i][j] = c randCol = random.randint(0, self.dim-1) randRow = random.randint(0, self.dim-1) self.target = point(randCol, randRow) #helper method to print the land map def printLand(self): for k in range(0, self.dim): for m in range(0, self.dim): print(self.map[k][m].state,' ', end = ' ') print() #helper method to print the probability map def printProb(self): for k in range(0, self.dim): for m in range(0, self.dim): print(float.fromhex(self.map[k][m].prob),' ', end = ' ') print() #updates the probaility on the map by using equations from Problem 1 def updateProb(self, col, row): for i in range(0, self.dim): for j in range(0, self.dim): if i == col and j == row: continue self.map[i][j].prob = float.hex(float.fromhex(self.map[i][j].prob)/(float.fromhex(self.map[col][row].prob)*float.fromhex(self.FalseNegativeMap[col][row])+(1-float.fromhex(self.map[col][row].prob)))) self.map[col][row].prob = float.hex((float.fromhex(self.FalseNegativeMap[col][row])*float.fromhex(self.map[col][row].prob))/(float.fromhex(self.map[col][row].prob)*float.fromhex(self.FalseNegativeMap[col][row])+(1-float.fromhex(self.map[col][row].prob)))) #used for Basic Agent 1 to search for the next cell to visit by checking all the probailities and choosing the highest one #also calculates and returns distance needed to get to that cell def searchNext(self, currCol, currRow): points = [] prob = round(float.fromhex(self.map[0][0].prob), 10) for i in range(0, self.dim): for j in range(0, self.dim): if round(float.fromhex(self.map[i][j].prob), 10)>round(prob, 10): points = [] prob = float.fromhex(self.map[i][j].prob) pt = (i,j) points.append(pt) elif round(float.fromhex(self.map[i][j].prob), 10) == round(prob, 10): pt = (i,j) points.append(pt) col = points[0][0] row= points[0][1] distance = abs(currCol-col)+abs(currRow-row) for point in points: newDistance = abs(currCol-point[0])+abs(currRow-point[1]) if distance>newDistance: distance = newDistance col = point[0] row = point[1] return col, row, distance #main agent 1 method to check if we fouind the target cell and if it was successful, if not, update the probabilties and find the next cell to visit and update distance travelled def agent1(self): currCol = random.randint(0, self.dim-1) currRow = random.randint(0, self.dim-1) distance = 0 search = 0 while True: search +=1 if self.map[currCol][currRow].pt.col == self.target.col and self.map[currCol][currRow].pt.row == self.target.row: if random.random() > float.fromhex(self.FalseNegativeMap[currCol][currRow]): return distance+search self.updateProb(currCol, currRow) currCol, currRow, mDistance = self.searchNext(currCol, currRow) distance += mDistance #search method for Basic Agent 2 taking into account the probability of finding the target def Agent2Search(self, currCol, currRow): points = [] prob = round(float.fromhex(self.map[0][0].prob)*(1-float.fromhex(self.FalseNegativeMap[0][0])), 10) for i in range(0, self.dim): for j in range(0, self.dim): if round((float.fromhex(self.map[i][j].prob)*(1-float.fromhex(self.FalseNegativeMap[i][j]))), 10)>round(prob, 10): points = [] prob = float.fromhex(self.map[i][j].prob)*(1-float.fromhex(self.FalseNegativeMap[i][j])) pt = (i,j) points.append(pt) elif round((float.fromhex(self.map[i][j].prob)*(1-float.fromhex(self.FalseNegativeMap[i][j]))), 10) == round(prob, 10): pt = (i,j) points.append(pt) col = points[0][0] row= points[0][1] distance = abs(currCol-col)+abs(currRow-row) for pt in points: newDistance = abs(currCol-pt[0])+abs(currRow-pt[1]) if distance>newDistance: distance = newDistance col = pt[0] row = pt[1] return col, row, distance #main agent 2 method that goes thru and checks the whole maze def agent2(self): currCol = random.randint(0, self.dim-1) currRow = random.randint(0, self.dim-1) distance = 0 search = 0 while True: search +=1 if self.map[currCol][currRow].pt.col == self.target.col and self.map[currCol][currRow].pt.row == self.target.row: if random.random() > float.fromhex(self.FalseNegativeMap[currCol][currRow]): return distance+search self.updateProb(currCol, currRow) currCol, currRow, mDistance = self.Agent2Search(currCol, currRow) distance += mDistance #imporved search based on our imporovement algorithm def improvedSearch(self, currCol, currRow): points = [(currCol, currRow)] pointsSecond = [(currCol, currRow)] prob = 0 for i in range(0, self.dim): for j in range(0, self.dim): if abs(currCol-i)+abs(currRow-j)>50: continue elif (round((float.fromhex(self.map[i][j].prob)*(1-float.fromhex(self.FalseNegativeMap[i][j]))), 10) < round((float.fromhex(self.map[points[0][0]][points[0][1]].prob)*(1-float.fromhex(self.FalseNegativeMap[points[0][0]][points[0][1]]))), 10) and round((float.fromhex(self.map[i][j].prob)*(1-float.fromhex(self.FalseNegativeMap[i][j]))), 10) > round((float.fromhex(self.map[pointsSecond[0][0]][pointsSecond[0][1]].prob)*(1-float.fromhex(self.FalseNegativeMap[pointsSecond[0][0]][pointsSecond[0][1]]))), 10)): pointsSecond.append((i, j)) elif round((float.fromhex(self.map[i][j].prob)*(1-float.fromhex(self.FalseNegativeMap[i][j]))), 10)>round(prob, 10): pointsSecond = points points = [] prob = float.fromhex(self.map[i][j].prob)*(1-float.fromhex(self.FalseNegativeMap[i][j])) pt = (i,j) points.append(pt) elif round((float.fromhex(self.map[i][j].prob)*(1-float.fromhex(self.FalseNegativeMap[i][j]))), 10) == round(prob, 10): pt = (i,j) points.append(pt) col = points[0][0] row= points[0][1] secondCol = pointsSecond[0][0] secondRow = pointsSecond[0][1] distanceSecond = abs(currCol-col)+abs(currRow-row) + abs(col-secondCol)+abs(row-secondRow) distance = 101 if len(points)<=2: for pt1 in points: for pt2 in pointsSecond: newDistance = abs(currCol-pt1[0])+abs(currRow-pt1[1])+abs(pt1[0] - pt2[0])+abs(pt1[1]-pt2[1]) if distance>newDistance: distance = newDistance col = pt1[0] row = pt1[1] finalDistance = abs(currCol-pt1[0])+abs(currRow-pt1[1]) else: for i in range(0, len(points)): for j in range(0, len(points)): if(i == j): continue newDistance = abs(currCol-points[i][0])+abs(currRow-points[i][1])+abs(points[i][0] - points[j][0])+abs(points[i][1]-points[j][1]) if distance>newDistance: distance = newDistance col = points[i][0] row = points[i][1] finalDistance = abs(currCol-points[i][0])+abs(currRow-points[i][1]) return col, row, finalDistance #improved agent main method that checks if it was success, if not search for next cell and rerun def improvedAgent(self): currCol = random.randint(0, self.dim-1) currRow = random.randint(0, self.dim-1) distance = 0 search = 0 while True: search +=1 if self.map[currCol][currRow].pt.col == self.target.col and self.map[currCol][currRow].pt.row == self.target.row: if random.random() > float.fromhex(self.FalseNegativeMap[currCol][currRow]): return distance+search self.updateProb(currCol, currRow) currCol, currRow, mDistance = self.improvedSearch(currCol, currRow) distance += mDistance
6c132434f5b177a6ae62032a13145739f60a7670
t0ny00/Inteligencia-2-Proeycto-1
/RLM.py
4,433
3.578125
4
import numpy as np import matplotlib.pyplot as plt def Normalize(array): n = len(array) media = np.mean(array,axis=0) dev_standar = np.std(array,axis=0) #Create normalized array new_array = [] for elem in array: temp = np.divide((elem - media) ,dev_standar) new_array.append(temp) out = np.asarray(new_array) # print out return out def gradientDescent(x, y, weights, alpha, numIterations): n = x.shape[0] # Number of data entries cost_function_plot_data = [] # Array with the value of the cost function for each iteration for i in range(0, numIterations): # Calculate the product of the weights with each entry hypothesis = [] for instance in x: sum = 0 for j in range(instance.size): sum += instance[j]*weights[j] hypothesis = np.append(hypothesis,sum) delta = hypothesis - y # Calculate the cost function value cost = np.sum(delta ** 2) / (2 * n) # Store the iteration number and the cost function value into an array cost_function_plot_data = np.append(cost_function_plot_data, [i, cost], axis=0) # Calculate the gradient value gradient = np.dot(x.transpose(), delta) / n weights = weights - alpha * gradient cost_function_plot_data = cost_function_plot_data.reshape(numIterations, 2) return weights, cost_function_plot_data def costFunctionPlot(data, numberIterations, alpha): x = data[:, 0] y = data[:, 1] plt.plot(x, y) plt.title(r'Convergence Curve for $\alpha=$' + str(alpha) + ' and ' + str(numberIterations) + ' iterations') plt.ylabel('Cost Function Value') plt.xlabel('Number of Iterations') plt.show() def scatterPlot(x, y, weights): temp = np.dot(x,weights) # temp = temp.reshape(temp,x.shape()[0],x.shape()[1]) print temp line_point1 = np.dot(x[0], weights) line_point2 = np.dot(x[-1], weights) plt.title('Scatter Plot with Adjusted Curve') plt.ylabel('Y Values') plt.xlabel('X Values') plt.plot(x[:, 1], y, 'o') plt.plot(x,temp, 'r-', lw=3) plt.show() def biasMetric(weights,x,y): predicted_result = np.dot(x, weights) delta = predicted_result - y return np.average(delta) def maximumDeviationMetric(weights,x,y): predicted_result = np.dot(x,weights) delta= np.absolute(predicted_result-y) return np.max(delta) def meanMaximumDeviationMetric(weights,x,y): predicted_result = np.dot(x,weights) delta= np.absolute(predicted_result-y) return np.average(delta) def meanSquareErrorMetric(weights,x,y): predicted_result = np.dot(x,weights) delta = np.power(predicted_result - y,2) return np.average(delta) if __name__ == '__main__': data = np.loadtxt("AmesHousing-training_set2.txt") numberIterations = 30 alpha = 0.1 numberRows = data.shape[0] numberColumns = data.shape[1] weights = np.zeros(numberColumns - 1) y = data[:, numberColumns - 1] x = data[:, 1:numberColumns - 1] x = Normalize(x) y = Normalize(y) # Add for every entry the x0=1 x = np.insert(x,0,1,axis=1) data_test = np.loadtxt("AmesHousing-test_set2.txt") numberRows2 = data_test.shape[0] numberColumns2 = data_test.shape[1] y2 = data_test[:, numberColumns2 - 1] x2 = data_test[:, 1:numberColumns2 - 1] x2 = Normalize(x2) y2 = Normalize(y2) # Add for every entry the x0=1 x2 = np.insert(x2,0,1,axis=1) weights, cost_function_data = gradientDescent(x, y, weights, alpha, numberIterations) print biasMetric(weights,x,y) print maximumDeviationMetric(weights, x, y) print meanMaximumDeviationMetric(weights,x,y) print meanSquareErrorMetric(weights,x,y) print 'Using data_test' print biasMetric(weights,x2,y2) print maximumDeviationMetric(weights, x2, y2) print meanMaximumDeviationMetric(weights,x2,y2) print meanSquareErrorMetric(weights,x2,y2) # np.savetxt('Parte1/x01-costFunct-30Iter-' + str(alpha)+'.txt', cost_function_data, delimiter='\t') # np.savetxt('Parte1/x01-weights-30Iter.txt', weights.reshape(1,2), delimiter='\t') # temp = np.append(x,y.reshape(numRows,1),1) # np.savetxt('Parte1/x01-data-30Iter.txt', temp, delimiter='\t') # # print a # # costFunctionPlot(cost_function_data, numberIterations, alpha) # scatterPlot(x, y, weights)
d6bdd3af96b503e38548a06717e136f15d957824
kmouse/Game_1
/Game/Data/Code/button.py
6,064
3.671875
4
import pygame import os from Data.Code.load import get_image, get_font pygame.init() def resize_image(width, height, location): image = pygame.image.load(get_image(location)).convert_alpha() if width == 0: width = image.get_width() if height == 0: height = image.get_height() image = pygame.transform.scale(image, (width, height)) return image # This is the base class for any button object class Button(pygame.sprite.Sprite): def __init__(self, screen, text, command, x, y, width=0, height=0, image="Buttons\\button.png", highlight_image="Buttons\\button_highlighted.png", pressed_image="Buttons\\button_pressed.png", init_command="", text_size=24, text_align="center", image_align="center", type="Button", press_method="click"): # Initialise the sprite module pygame.sprite.Sprite.__init__(self, self.containers) # Make the image self.image = resize_image(width, height, image) self.image_align = image_align # Set up the rect for drawing # if the width or height is 0, that is the default width or height for the image if width == 0: self.rect_width = self.image.get_width() else: self.rect_width = width if height == 0: self.rect_height = self.image.get_height() else: self.rect_height = height self.rect = pygame.Rect(0, 0, self.rect_width, self.rect_height) if self.image_align == "center": self.rect.center = eval(x, {"width":screen.get_width()}), eval(y, {"height":screen.get_height()}) elif self.image_align == "topleft": self.rect.topleft = eval(x, {"width":screen.get_width()}), eval(y, {"height":screen.get_height()}) # Stores the equations for positions self.position_formula = x, y # Store the images self.plain_image = resize_image(width, height, image) self.highlight_image = resize_image(width, height, highlight_image) self.pressed_image = resize_image(width, height, pressed_image) # This gets whether the mouse pressed self self.pressed = 0 self.text_size = text_size self.text = text self.text_align = text_align self.image_locations = [get_image(image), get_image(highlight_image), get_image(pressed_image)] self.type = type font = pygame.font.Font(get_font('arial.ttf'), text_size) font_surface = font.render(text, 1, (0, 0, 0)) font_size = font.size(text) if text_align == "center": self.plain_image.blit(font_surface, (self.image.get_width() / 2 - font_size[0] / 2, self.image.get_height() / 2 - font_size[1] / 2)) self.highlight_image.blit(font_surface, (self.image.get_width() / 2 - font_size[0] / 2, self.image.get_height() / 2 - font_size[1] / 2)) self.pressed_image.blit(font_surface, (self.image.get_width() / 2 - font_size[0] / 2, self.image.get_height() / 2 - font_size[1] / 2)) elif text_align == "left": self.plain_image.blit(font_surface, (20, self.image.get_height() / 2 - font_size[1] / 2)) self.highlight_image.blit(font_surface, (20, self.image.get_height() / 2 - font_size[1] / 2)) self.pressed_image.blit(font_surface, (20, self.image.get_height() / 2 - font_size[1] / 2)) # This is the command run when the button is pressed self.command = command self.init_command = init_command self.press_method = press_method # Run the init_command self.run_init_command() # Get the pos for the new screen size def update_pos(self, screen): if self.image_align == "center": self.rect.center = eval(self.position_formula[0], {"width":screen.get_width()}), eval(self.position_formula[1], {"height":screen.get_height()}) elif self.image_align == "topleft": self.rect.topleft = eval(self.position_formula[0], {"width":screen.get_width()}), eval(self.position_formula[1], {"height":screen.get_height()}) def update(self, mouse_pos, mouse_down, screen): pressed = False mouse_rect = pygame.Rect(mouse_pos, (1, 1)) # If the mouse is on the button # When self.pressed == 1 then the mouse is down and started over the button # When self.pressed == 0 then the mouse is not down # When self.pressed == 2 then the mouse is down but did not start over the button or button is already used if self.rect.colliderect(mouse_rect): if mouse_down[0] and self.pressed == 0: self.pressed = 1 self.image = self.pressed_image elif mouse_down[0] and self.pressed == 1: self.pressed = 1 if self.press_method == "mouse down": self.run_command(); self.pressed = 2; pressed = True self.image = self.pressed_image elif mouse_down[0] and self.pressed == 2: self.pressed = 2 else: if self.pressed == 1: if self.press_method == "click": self.run_command() pressed = True self.pressed = 0 self.image = self.highlight_image else: if mouse_down[0] and self.pressed == 0: self.pressed = 2 elif mouse_down[0] and self.pressed == 1: self.pressed = 1 elif mouse_down[0] and self.pressed == 2: self.pressed = 2 else: self.pressed = 0 self.image = self.plain_image # Update rect self.rect = pygame.Rect(0, 0, self.rect_width, self.rect_height) self.update_pos(screen) return pressed def run_init_command(self): exec(self.init_command) def run_command(self): exec(self.command)
56fe9f0c301b899c41af2e74f2fbdfa758a44974
ErkkoI/Sahkista
/minority_game.py
4,247
3.578125
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 19 19:04:54 2020 @author: eelil """ import numpy as np import matplotlib.pyplot as plt def lastMBits(n, m): return n & ((1 << m) - 1) def insertRightBit(n, bit): return (n << 1) | bit # N is the number of players, m is the length of memory def runMinorityGame(N, m, n_iterations): m = int(m) n_strategies = 2 past = 0 # The past actions are stored in the bits, right-most bit is the latest action strategies = np.random.randint(low=0, high=2, size=(N, n_strategies, 2**m)) performance = np.zeros((N, n_strategies)) chosenStrategy = np.zeros(N) n1_values = np.zeros(n_iterations) histories = np.zeros(2**m) p1_given_mu = np.zeros(2**m) n1_given_mu = np.zeros(2**m) for k in range(n_iterations): # If the performance of the strategies are equal, the first one is chosen chosenStrategy = np.argmax(performance, axis=1) # Shape (N,) actions = strategies[np.arange(N), chosenStrategy, :] # Shape (N,2**m) past_index = lastMBits(past, m) chosen_actions = actions[:, past_index] # Shape (N,) n1 = sum(chosen_actions) n1_values[k] = n1 action = 1 if n1 < N/2 else 0 past = insertRightBit(past, action) performance += strategies[:, :, past_index] == action p1_given_mu[past_index] += action n1_given_mu[past_index] += n1 histories[past_index] += 1 # for mu in range(2**m): # chosen_actions_mu = actions[:, mu] # n1_mu = sum(chosen_actions_mu) # action_mu = 1 if n1_mu < N/2 else 0 # p1_given_mu[mu] += action_mu # print(past_index) # print(chosen_actions) # print(action) # print(past) # print(strategies) # print(performance) # H = np.nanmean((2*n1_given_mu / histories - N)**2) p1_given_mu /= histories H = np.nanmean((p1_given_mu - 0.5)**2) sigma = np.std(n1_values) return sigma, H, p1_given_mu, n1_values if __name__ == '__main__': time_series = False p_values = True scaling_results = False if scaling_results: save = True n_games = 50 N_vals = np.array([51, 71, 101, 151, 201, 251]) m_vals = np.arange(2, 13) # n_games = 1 # N_vals = [251] # m_ = 4 # m_vals = [m_] sigmas = np.zeros((len(N_vals), len(m_vals), n_games)) H_vals = np.zeros((len(N_vals), len(m_vals), n_games)) n_iterations = 1000 for j, N in enumerate(N_vals): print('\nN = {}\n'.format(N)) for i, m in enumerate(m_vals): print(i, '/', len(m_vals)) for n in range(n_games): sigma, H, _, _ = runMinorityGame(N, m, n_iterations) sigmas[j, i, n] = sigma H_vals[j, i, n] = H if save: np.savez('minority_game_results_5000.npz', sigmas=sigmas, N_vals=N_vals, m_vals=m_vals, H_vals=H_vals) if time_series: N = 251 m_vals = [2, 5, 12] n_iterations = 500 plt.figure() for i, m in enumerate(m_vals): _, _, _, time_series = runMinorityGame(N, m, n_iterations) plt.subplot(len(m_vals), 1, i+1) plt.plot(time_series, label='m={}'.format(m)) plt.ylim([75,175]) plt.grid() plt.xlabel('Iteration') plt.ylabel('n_1') plt.legend() if p_values: N = 101 m_vals = [5,6] n_iterations = 50000 plt.figure() for i, m in enumerate(m_vals): _, _, p_vals, _ = runMinorityGame(N, m, n_iterations) plt.subplot(len(m_vals), 1, i+1) plt.bar(np.arange(2**m), p_vals, label='m={}'.format(m)) plt.ylim([0,1]) plt.grid() plt.xlabel('$\mu$') plt.ylabel('P(1|$\mu$)') plt.legend()
8e052ec9d528c4a88e9e23d3ee04ddad24d14a35
Rupsa25/DailyCodingProblem
/day2.py
861
4
4
# -*- coding: utf-8 -*- """ Created on Wed Dec 16 09:27:12 2020 @author: Rupsa """ "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." "Time Complexity:O(n^2)" def newArray(arr): l=[] for i in range(len(arr)): prod=1 for j in range(len(arr)): if i==j: continue prod=prod*arr[j] l.append(prod) return l "Time complexity:O(n)" def prodArray(arr): i=1 prod=[1 for i in range(len(arr))] temp=1 #left prdoduct for i in range(len(arr)): prod[i]=temp temp*=arr[i] #right product temp=1 for j in range(len(arr)-1,-1,-1): prod[j]*=temp temp*=arr[j] return prod
b339f6ced09317166f5ce49eb6f4bab693da1020
ProvisionLab/Iris_reco
/blob.py
874
3.671875
4
# Standard imports import cv2 import numpy as np; # Read image gray = cv2.imread("02.bmp", cv2.IMREAD_GRAYSCALE) output = gray.copy() # detect circles in the image circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.9, 300) # ensure at least some circles were found if circles is not None: # convert the (x, y) coordinates and radius of the circles to integers circles = np.round(circles[0, :]).astype("int") # loop over the (x, y) coordinates and radius of the circles for (x, y, r) in circles: # draw the circle in the output image, then draw a rectangle # corresponding to the center of the circle cv2.circle(output, (x, y), r, (0, 0, 255), 4) cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1) # show the output image cv2.imshow("output", np.hstack([gray, output])) cv2.waitKey(0)
c12ac60099dc44da4d268f5e8862e4af681d5e2f
kinsonpoon/CUHK
/csci3320/asg2/ex2.py
4,230
3.71875
4
import os.path import numpy as np import matplotlib.pyplot as plt from scipy import misc from sklearn.decomposition import PCA def load_data(digits, num): ''' Loads all of the images into a data-array. The training data has 5000 images per digit, but loading that many images from the disk may take a while. So, you can just use a subset of them, say 200 for training (otherwise it will take a long time to complete. Note that each image as a 28x28 grayscale image, loaded as an array and then reshaped into a single row-vector. Use the function display(row-vector) to visualize an image. ''' totalsize = 0 for digit in digits: totalsize += min([len(next(os.walk('train%d' % digit))[2]), num]) print('We will load %d images' % totalsize) X = np.zeros((totalsize, 784), dtype = np.uint8) #784=28*28 for index in range(0, len(digits)): digit = digits[index] print('\nReading images of digit %d' % digit) for i in range(num): pth = os.path.join('train%d' % digit,'%05d.pgm' % i) image = misc.imread(pth).reshape((1, 784)) X[i + index * num, :] = image print('\n') return X def plot_mean_image(X, digits = [0]): ''' example on presenting vector as an image ''' plt.close('all') meanrow = X.mean(0) # present the row vector as an image plt.imshow(np.reshape(meanrow,(28,28))) plt.title('Mean image of digit ' + str(digits)) plt.gray(), plt.xticks(()), plt.yticks(()), plt.show() def main(): digits = [0, 1, 2] # load handwritten images of digit 0, 1, 2 into a matrix X # for each digit, we just use 500 images # each row of matrix X represents an image X = load_data(digits, 500) # plot the mean image of these images! # you will learn how to represent a row vector as an image in this function plot_mean_image(X, digits) # print(len(X)) #print(len(X[1499])) #################################################################### # plot the eigen images, eigenvalue v.s. the order of eigenvalue, POV # v.s. the order of eigenvalue # you need to # 1. do the PCA on matrix X; # # 2. plot the eigenimages (reshape the vector to 28*28 matrix then use # the function ``imshow'' in pyplot), save the images of eigenvectors # which correspond to largest 9 eigenvalues. Save them in a single file # ``eigenimages.jpg''. # # 3. plot the POV (the Portion of variance explained v.s. the number of # components we retain), save the figure in file ``digit_pov.jpg'' # # 4. report how many dimensions are need to preserve 0.9 POV, describe # your answers and your undestanding of the results in the plain text # file ``description.txt'' # # 5. remember to submit file ``eigenimages.jpg'', ``digit_pov.jpg'', # ``description.txt'' and ``ex2.py''. # YOUR CODE HERE! #################################################################### n_components = 784 pca = PCA(n_components=n_components, svd_solver='randomized',whiten=True).fit(X) eigenimages = pca.components_.reshape((n_components, 28, 28)) #print(len(eigenimages),len(eigenimages[0])) for i in range(9): plt.imshow(eigenimages[i]) plt.title(i+1) plt.gray(), plt.xticks(()), plt.yticks(()), plt.show() #X_pca = pca.transform(X) #3 pov = np.cumsum(pca.explained_variance_ratio_) var_exp=sorted(pov) #cum_var_exp = np.cumsum(var_exp) plt.bar(range(784), var_exp, alpha=0.5, align='center',label='individual explained variance') # plt.step(range(9), cum_var_exp, where='mid', # label='cumulative explained variance') plt.ylabel('Explained variance ratio') plt.xlabel('Principal components') plt.title('the Portion of variance explained v.s. the number of components we retain') plt.legend(loc='best') plt.tight_layout() plt.show() for i in range(len(var_exp)): if var_exp[i] >0.9: print("Number of dimensions:",i+1) print("Values:",var_exp[i]) break if __name__ == '__main__': main()
7585618cdc4739146bd08508afe1271da2697437
AnmAgrawal/HackerrankSolutions
/betweenTwoSets.py
854
4.03125
4
# You will be given two arrays of integers and asked to determine all integers that satisfy the following two conditions: # The elements of the first array are all factors of the integer being considered # The integer being considered is a factor of all elements of the second array # These numbers are referred to as being between the two arrays. You must determine how many such numbers exist. def getTotalX(a, b): # Write your code here a.sort() b.sort() nums = set() for i in range(a[len(a)-1],b[0]+1): count = 0 for j in range(len(a)): if(i%a[j] == 0): count+=1 if count == len(a): f = 0 for k in b: if k%i == 0: f += 1 if f == len(b): nums.add(i) return len(nums)
81c2978ad2e7d8049879d7cec0452d1c8d19d459
keurfonluu/My-Daily-Dose-of-Python
/Solutions/31-spiral-traversal-of-grid.py
2,303
3.921875
4
#%% [markdown] # You are given a 2D array of integers. Print out the clockwise spiral traversal of the matrix. # # Example # ``` # grid = [ # [1, 2, 3, 4, 5], # [6, 7, 8, 9, 10], # [11, 12, 13, 14, 15], # [16, 17, 18, 19, 20], # ] # ``` # The clockwise spiral traversal of this array is: # 1, 2, 3, 4, 5, 10, 15, 20, 19, 18, 17, 16, 11, 6, 7, 8, 9, 14, 13, 12 #%% def matrix_spiral_print(M): # Indice bounds imin = 1 # First line is the first to be processed imax = len(M)-1 jmin = 0 jmax = len(M[0])-1 # Indices and increments i, j = 0, 0 # Current position on the array iinc, jinc = 1, 1 # Increments # Loop until all the grid has been processed count = 0 spiral = [] traverse_cols = True while count < len(M)*len(M[0]): spiral.append(M[i][j]) # Traverse columns of array if traverse_cols: cond1 = j == jmax and jinc > 0 # Check if at last column cond2 = j == jmin and jinc < 0 # Check if at first column if cond1 or cond2: # Switch processing direction and increment limits jinc *= -1 if cond1: jmax -= 1 elif cond2: jmin += 1 # Go to next row to process i += iinc traverse_cols = False else: j += jinc # Traverse rows of array else: cond1 = i == imax and iinc > 0 # Check if at last row cond2 = i == imin and iinc < 0 # Check if at first row if cond1 or cond2: # Switch processing direction and increment limits iinc *= -1 if cond1: imax -= 1 elif cond2: imin += 1 # Go to next column to process j += jinc traverse_cols = True else: i += iinc count += 1 # Print spiral print(", ".join(str(x) for x in spiral)) grid = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], ] matrix_spiral_print(grid) # %%
f564b75a0550add414a2987b036263ed73008e3b
mychristopher/test
/pyfirstweek/tkinter学习/Label控件.py
839
3.71875
4
#!/usr/bin/python # -*- coding: utf-8 -*- import tkinter #创建窗口 win = tkinter.Tk() #设置标题 win.title("caicai") #设置大小和位置 win.geometry("400x400+200+20") #label:标签控件可以显示文本 #win 父窗体,text:文本内容 , bg 背景色 ,fg 字体颜色 # font 字体,wraplength 指定多宽之后换行,justify 指定怎样对齐 #anchor 位置n e s w 居中center ne se, label = tkinter.Label(win, text = "caicai is a small sun", bg="pink", fg="red", font = ("黑体",20), width=100, height=2, wraplength=1000, justify="left", anchor="center") #显示出来 label.pack() win.mainloop()
0834893cf6dab92a818df60b683be9e3ed929134
stOracle/Migrate
/Programming/CS313E/ExpressionTree.py
6,241
3.578125
4
# File: ExpresssionTree.py # Description: An algorithm to do math using a tree # Student's Name: Stephen Rauner # Student's UT EID: STR428 # Course Name: CS 313E # Unique Number: 50945 # Date Created: 4/24/16 # Date Last Modified: 4/25/16 # ///////////////////////////////////////////////////////////////////////////////// # ///////////////////////////////////////////////////////////////////////////////// # ///////////////////////////////////////////////////////////////////////////////// class Stack (object): def __init__ (self): self.stack = [] # ///////////////////////////////////////////////////////////////////////////////// def push (self, item): self.stack.append(item) # ///////////////////////////////////////////////////////////////////////////////// def pop (self): return self.stack.pop() # ///////////////////////////////////////////////////////////////////////////////// def peek (self): return self.stack[-1] # ///////////////////////////////////////////////////////////////////////////////// def isEmpty (self): return (len(self.stack) == 0) # ///////////////////////////////////////////////////////////////////////////////// def size (self): return (len(self.stack)) # ///////////////////////////////////////////////////////////////////////////////// # ///////////////////////////////////////////////////////////////////////////////// # ///////////////////////////////////////////////////////////////////////////////// class Node (object): def __init__ (self, data): self.data = data self.rChild = None self.lChild = None # ///////////////////////////////////////////////////////////////////////////////// def __str__ (self): if (self.lChild == None) and (self.rChild == None): return "Data: {}".format(self.data) return "Data: {}\nlChild: {}\nrChild: {}".format( self.data, self.lChild, self.rChild) # ///////////////////////////////////////////////////////////////////////////////// # ///////////////////////////////////////////////////////////////////////////////// # ///////////////////////////////////////////////////////////////////////////////// class Tree (object): def __init__(self): self.root = None # ///////////////////////////////////////////////////////////////////////////////// def __str__ (self): return str(self.root) # ///////////////////////////////////////////////////////////////////////////////// def createTree (self, s): # start the tree with 'empty' node, set it to current self.root = Node(" ") current = self.root # start the stack stack = Stack() Tokens = ["+", "-", "*", "/"] for el in s: # for the following, I just followed Mitra's algorithm if (el == "("): newNode = Node(" ") current.lChild = newNode stack.push(current) current = newNode elif (el == ")"): if (stack.isEmpty()): break else: current = stack.pop() # if el is an operator elif (el in Tokens): newNode = Node(" ") current.data = el current.rChild = newNode stack.push(current) current = newNode # if el is a number else: current.data = el current = stack.pop() # ///////////////////////////////////////////////////////////////////////////////// def evaluate (self): # I changed evaluate so it doesn't need an imput parameter. # it becomes a recursive method of the tree Class which # breaks the trees into subtrees to run the method on aNode = self.root # once you hit the bottom of the tree, return the data if (aNode.lChild == None) and (aNode.rChild == None): return int(aNode.data) # create two trees for the left sub-tree and the right sub-tree lTree = Tree() lTree.root = aNode.lChild rTree = Tree() rTree.root = aNode.rChild if (aNode.data == "+"): return lTree.evaluate() + rTree.evaluate() elif (aNode.data == "-"): return lTree.evaluate() - rTree.evaluate() elif (aNode.data == "*"): return lTree.evaluate() * rTree.evaluate() elif (aNode.data == "/"): return lTree.evaluate() / rTree.evaluate() # ///////////////////////////////////////////////////////////////////////////////// def evaluate2 (self, s): # I included a second evaluate function which uses the stack # rather than recursion because I didn't know which you wanted. s = s.split() theStack = Stack() Tokens = ["+", "-", "*", "/"] total = 0 for el in s: if (el in Tokens): oper2 = int(theStack.pop()) oper1 = int(theStack.pop()) if (el == "+"): val = oper1 + oper2 elif (el == "-"): val = oper1 - oper2 elif (el == "*"): val = oper1 * oper2 else: val = int(oper1 / oper2) theStack.push(val) else: theStack.push(el) return theStack.pop() # ///////////////////////////////////////////////////////////////////////////////// # recursive function which creates a left and right sub-tree to run the # method on. Same for postOrder. def preOrder (self): aNode = self.root if (aNode.lChild == None) and (aNode.rChild == None): return aNode.data lTree = Tree() lTree.root = aNode.lChild rTree = Tree() rTree.root = aNode.rChild return aNode.data + " " + lTree.preOrder() + " " + rTree.preOrder() # ///////////////////////////////////////////////////////////////////////////////// def postOrder (self): aNode = self.root if (aNode.lChild == None) and (aNode.rChild == None): return aNode.data lTree = Tree() lTree.root = aNode.lChild rTree = Tree() rTree.root = aNode.rChild return lTree.postOrder() + " " + rTree.postOrder() + " " + aNode.data # ///////////////////////////////////////////////////////////////////////////////// # ///////////////////////////////////////////////////////////////////////////////// # ///////////////////////////////////////////////////////////////////////////////// def main(): inFile = open("expression.txt", "r") for line in inFile: st = line.strip() exp = line.strip().split() ExpTree = Tree() ExpTree.createTree(exp) print("\n{} = {}".format(st, int(ExpTree.evaluate()))) print("Prefix Expression: {}".format(ExpTree.preOrder())) print("Postfix Expression: {}".format(ExpTree.postOrder())) inFile.close() main()
290013d5c272fdce351d88002e6ac56cbaed6acd
MargulisMax/opsschool3-coding
/home-assignments/session1/exercise2.py
1,942
3.796875
4
""" Usage: python3 exercise2.py """ import json from urllib.request import urlopen, quote API_KEY = 'APPID=9c8b160816fc48b0288a6136e0989b2a' API_UNITS = '&units=metric&' API_QUERY = 'http://api.openweathermap.org/data/2.5/weather?q=' def get_location_by_ip(): with urlopen('http://ip-api.com/json') as jsonrsp_ip: utfdata_ip = jsonrsp_ip.read(493).decode('utf-8') loadjson_ip = json.loads(utfdata_ip) return loadjson_ip['city'], loadjson_ip['countryCode'] def get_weather_by_location(mycity, mycountrycode): urlconc = API_QUERY + quote(mycity) + ',' + mycountrycode + API_UNITS + API_KEY with urlopen(urlconc) as jsonrsp_wr: utfdata_wr = jsonrsp_wr.read(843).decode('utf-8') loadjson_wr = json.loads(utfdata_wr) return loadjson_wr def main(): mylocation = GetLocationByIP() myweather = GetWeatherByLocation(mylocation[0], mylocation[1]) textfile = open('myweather.txt', 'w') textfile.write('Weather Description Is: ' + str(myweather['weather'][0]['description']) + '\n') textfile.write('Temperature Will Be: ' + str(myweather['main']['temp']) + ' degrees Celsius' + '\n') textfile.write('Humidity Will Be: ' + str(myweather['main']['humidity']) + '%' + '\n') textfile.write('Wind Speed Will Be: ' + str(myweather['wind']['speed']) + ' Meter/sec') textfile.close() cities = ['jerusalem', 'berlin', 'moscow', 'london', 'paris', 'vienna', 'amsterdam', 'brasilia', 'havana', 'athens'] countries = ['IL-Israel', 'DE-Germany', 'RU-Russia', 'UK-England', 'FR-France', 'AT-Austria', 'NL-Netherland', 'BR-Brazil', 'CU-Cuba', 'GR-Greece'] count = 0 for city in cities: globalweather = GetWeatherByLocation(city, countries[count].split('-')[0]) print('The weather in ' + city + ',' + countries[count].split('-')[1] + ' is ' + str(globalweather['main']['temp']) + ' degrees.') count += 1 if __name__ == '__main__': main()
3410168797f2572b3d5620ac99de91deb53a77eb
Asfhen/python-para-zumbis-resolvido
/Lista de exercicio 3/exercicio 2.py
251
4.09375
4
user = input('Digite seu nome de usuario: ') while True: psw = input('Digite sua senha: ') if psw == user: print('Sua senha não pode ser igual seu nome de usuario') else: print('Usuario e senha cadastrados!') break
3ca55a7c42b6ef0b7d7827d41b4dadc4550e1667
YashasviBhatt/Python
/countdown.py
208
3.90625
4
import time countdwn=int(input("Enter Countdown Limit : ")) while countdwn >= 0 : print(countdwn) countdwn=countdwn-1 time.sleep(1) # sleep(n) to give delay of n seconds
1510caa6aae575e8cea528c18a60ba15c6ded254
Maanume/Final-Project-SDL
/remove_stopwords.py
901
4.125
4
import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize stop_words = nltk.corpus.stopwords.words('english') # if desired, add more words for the stopword list. New_stopwords = ["hon.", "member", "mr."] stop_words.extend(New_stopwords) # below add the text file you would like to run through the program. txt_file = open("text1.txt") txt_line = txt_file.read() txt_words = txt_line.split() sw_found = 0 # below create name for file containing words not removed with stop words. for check_word in txt_words: if not check_word.lower() in stop_words: appendFile = open('stopwords-removed.txt', 'a') appendFile.write(" "+check_word) appendFile.close() else: sw_found +=1 print(check_word) print(sw_found, "stop words found and removed") # add name of file from above in this line print("Saved as 'stopwords-removed.txt'")
b95751d63096ced1b7fa51de1034f7cbcf354556
beatrizcf2/projeto-camfis
/Projeto3/teste.py
612
4.15625
4
# Fonte: https://www.geeksforgeeks.org/how-to-create-a-countdown-timer-using-python/ # import the time module import time # define the countdown func. def countdown(size, t): # fica dentro do loop ate t=0 while t>0: mins, secs = divmod(t, 60) #calcula o n de min e seg timer = '{:02d}:{:02d}'.format(int(mins), int(secs)) print(timer, end="\r") #print q sobrepoe o anterior time.sleep(0.1) #conta 1 seg t -= 0.1 print('Fire in the hole!!') # input time in seconds t = input("Enter the time in seconds: ") # function call countdown(int(t))
1f2ae3b8353b3606e1388d11dec83f0730815505
ajbrzoz/How-To-Think-Like-a-Computer-Scientist
/Chapter9/Ex9-22-9.py
329
4.0625
4
# Exercise 9.22.9 # Write a function that recognizes palindromes. def is_palindrome(my_str): count = 0 palin = True while count < len(my_str) and palin: if my_str[0] == my_str[-1]: my_str = my_str[1:-1] is_palindrome(my_str) else: palin = False return palin
1a192e71c9e315df0bb255cc9d03d766c183b829
JorgeEspina/Proyecto2s12017_201403632_201503393
/EDD_Proy2/DRIVE/Drive/AVL.py
3,322
3.625
4
class NodoAVL: def __init__(self,nombre): self.left = None self.right = None self.nombre = nombre def __str__(self): return "%s" % self.nombre class ArbolAVL: def __init__(self): self.nodo = None self.altura = -1 self.balance = 0 def insertar(self, nombre): n=NodoAVL(nombre) aux = ASCII(nombre,1) num = ASCII(self.nodo.nombre,1) for n in range(2,len(nombre)): if self.nodo == None: self.nodo = n self.nodo.left = ArbolAVL() self.nodo.right = ArbolAVL() num = ASCII(self.nodo.nombre,n) break elif aux < num: self.nodo.left.insertar(nombre) break elif aux > num: self.nodo.right.insertar(nombre) break elif aux == num: aux = ASCII(nombre,n) num = ASCII(self.nodo.nombre,n) self.balancear() def balancear(self): self.verAltura(recursive=False) self.verBalance(False) while self.balance < -1 or self.balance > 1: if self.balance > 1: if self.nodo.left.balance < 0: self.nodo.left.rotarIzq() self.verAltura() self.verBalance() self.rotarDer() self.verAltura() self.verBalance if self.balance < -1: if self.nodo.right.balance > 0: self.nodo.right.rotarDer() self.verAltura() self.verBalance self.rotarIzq() self.verAltura() self.verBalance() def verAltura(self, recursive=True): if self.nodo: if recursive: if self.nodo.left: self.nodo.left.verAltura() if self.nodo.right: self.nodo.right.verAltura() self.altura = 1 + max(self.nodo.left.altura, self.nodo.right.altura) else: self.altura = -1 def verBalance(self, recursive=True): if self.node: if recursive: if self.nodo.left: self.nodo.left.verBalance() if self.nodo.right.verBalance() self.balance=self.nodo.left.altura - self.nodo.right.altura else: self.balance=0 def rotarDer(self): nuevo = self.nodo.left.nodo nuevo2 = nuevo.right.nodo raiz = self.nodo self.nodo = nuevo raiz.left.nodo = nuevo2 nuevo.right.nodo = raiz def rotarIzq(self): nuevo = self.nodo.right.nodo nuevo2 = nuevo.left.nodo raiz = self.nodo self.nodo = nuevo raiz.right.nodo=nuevo2 nuevo.left.nodo = raiz def eliminar(self, nombre): if self.nodo.nombre != None: aux = ASCII(nombre,1) num = ASCII(self.nodo.nombre,1) for n in range(2,len(nombre)): if self.nodo.nombre = nombre: if not self.nodo.left.nodo and not self.nodo.right.nodo: self.nodo = None elif not self.nodo.left.nodo: self.nodo = self.nodo.right.nodo elif not self.nodo.right.nodo: self.nodo=self.nodo.left.nodo else: siguiente = self.nodo.right.nodo while siguiente and siguiente.left.nodo: siguiente = siguiente.left.nodo if siguiente: self.nodo.right.eliminar(siguente.nombre) aux = ASCII(nombre,1) num = ASCII(self.nodo.nombre,1) elif aux < num: self.nodo.left.eliminar(nombre) break elif aux > num: self.nodo.right.eliminar(nombre) break elif aux == num: aux = ASCII(nombre,n) num = ASCII(self.nodo.nombre,n) self.balancear() def ASCII(nombre, posi): letra = nombre[:posi] return ord(letra)
e10810ec080b44b2a780b4b85c346284a0e9cbcc
EvanMisshula/advpy
/10-args.py
781
4
4
## args and kwargs def doubler(f): def g(x): return 2* f(x) return g def f1(x): return x + 1 g=doubler(f1) print g(3) print g(-1) #doesn't work def f2(x, y): return x + y g = doubler(f2) print g(1,2) ## Error def magic(*args, **kwargs): print "unnamed args:", args print "keyword args:", kwargs magic(1, 2, key="word", key2="word2") def other_way_magic(x, y, z): return x + y + z x_y_list = [1, 2] z_dict = { "z" : 3 } print other_way_magic(*x_y_list, **z_dict) def doubler_correct(f): """works no matter what kind of inputs f expects""" def g(*args, **kwargs): """whatever arguments g is supplied, pass them through to f""" return 2 * f(*args, **kwargs) return g g = doubler_correct(f2) print g(1, 2) # 6
cd1866983f868264c96817f79030b190ffaa990a
MonterrosaEdair/Portafolio1
/multiplicarRecursivo.py
370
3.765625
4
#E: 2 números #S: Multiplicar un número por su factor sin el operando #R: El numero debe ser entero def multiplicarRecursivo(num,factor): if isinstance(num,int) and isinstance(num,int) and num>=0 and factor>=0: if num==0: return 0 else: return num+multi(num,factor-1) else: return ("Error")
b51834b999f6489e8d6be951f1d28d013d3a2bee
chenlfc/learnPython
/Python编程_从入门到实践/Part 1/Chapter 6 to 11/division.py
647
3.890625
4
# -*- coding: utf-8 -*- # cretae by o.c. 2018/7/25 from _for_ex import pt_title pt_title('division.py'.upper()) print("Give me two numbers, and I'll divide them.") print("Enter 'q' to quit.") while True: first_number = input("\nFirst number: ") if first_number.lower() == 'q': break second_number = input("\nSecond number: ") if second_number.lower() == 'q': break try: answer = int(first_number) / int(second_number) except ValueError: print("ERROR please enter some number!!!") except ZeroDivisionError: print("ERROR you can't divide by 0!") else: print(answer)
907efbe3fd6bdbefad75720082110c23a3610b8a
Liliana327/holbertonschool-low_level_programming
/0x1C-makefiles/5-island_perimeter.py
637
3.78125
4
#!/usr/bin/python3 ''' returns the perimeter of the island described in grid ''' def island_perimeter(grid): '''grid is a list of list of integers ''' width = 0 height = 0 for zone in range(len(grid)): for water in range(len(grid[zone])): if grid[zone][water] == 1: width += 1 if zone != len(grid) - 1: if grid[zone + 1][water] == 1: height += 1 if water != len(grid[zone]) - 1: if grid[zone][water + 1] == 1: height += 1 return(width * 4) - (height * 2)
e9e157359728deb97e4a3d4e8187b067cd88e02f
joseph-hurtado/quarg
/examples/trivial3.py
405
4.03125
4
#!/usr/bin/env python3 """Basic maths functions. Simple use of the quarg module, with no additional annotation. """ import quarg def prod(x,y = 1): """Multiply two numbers. This is pretty basic stuff.""" print(x, "*", y, "=", int(x) * y) def sum(x, y = 0): """Add two numbers. Addition was known to the ancient Babylonians.""" print(x, "+", y, "=", int(x) + y) quarg.main()
f0aa1c289d3d4e98ae59ed0563aeee990d9e0931
ssola/project-euler
/problem25/fibonacci.py
351
3.609375
4
''' Problem 25 1000-digit Fibonacci number https://projecteuler.net/problem=25 ''' def fib(n): fibValues = [0,1] for i in xrange(2,n+1): fibValues.append(fibValues[i-1] + fibValues[i-2]) return fibValues[n] currentValue = 0 index = 0 while len(str(currentValue)) < 1000: index += 1 currentValue = fib(index) print index
2a9618088ebd2e4c6bccee23ece591c0c85a0103
emmjab/flights_analysis
/src/00-FilterFlights.py
495
3.75
4
#!/usr/bin/env python # coding: utf-8 import pandas as pd import sys # It would be more robust to use argparse or click, but we want this to be simple if len(sys.argv) < 3: sys.exit("Please invoke with two arguments: input and output paths") input_path = sys.argv[1] output_path = sys.argv[2] # Read in the data df = pd.read_csv(input_path) df.head() # Select only flights to Austin (AUS) df = df[df['DEST'] == 'AUS'] df.head() # Save the result df.to_csv(output_path, index=False)
9134172bf36ed53c6a2d4403c13887d047846238
Bency2410/moduleprgrms.py
/checkeven.py
82
3.671875
4
def even(x): if(x%2==0): return "even" else: return "Odd "