blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
227830e710c39afc391898227688007985273ab9
Iam-El/Random-Problems-Solved
/Linked list/createLinkedlist.py
5,471
4.125
4
class Node: def __init__(self, data): self.data = data self.next = None class Linkedlist: def __init__(self): self.head = None # Inserting at the End of the Linked List def insertatEnd(self, newdata): # self.head should be node not none for this function # newnode=Node(newdata) # cur=self.head # while cur.next is not None: # cur.next=newnode # cur = cur.next # print(cur.next.data) if self.head is None: self.head = Node(newdata) current = self.head while current.next is not None: current = current.next current.next = Node(newdata) return self.head # insert one by one def AtEnd(self, newdata): NewNode = Node(newdata) if self.head is None: self.head = NewNode return laste = self.head while (laste.next): laste = laste.next laste.next = NewNode # display the elemets of linked list def disply(self): elements = [] cur = self.head while cur is not None: elements.append(cur.data) cur = cur.next print(elements) # print the elements of the linked list def listprint(self): printval = self.head while printval is not None: print(printval.data) printval = printval.next # find the length of linked list def lengthLinkedlist(self): count = 0 cur = self.head while cur is not None: count = count + 1 cur = cur.next print(count) # delete an item from linked list def removeAnItem(self, removedata): cur = self.head prev = None if cur is None: raise ValueError("Data not in list") while cur is not None: if cur.data == removedata: if prev is None: self.head = cur.next return else: prev.next = cur.next cur = cur.next else: prev = cur cur = cur.next # insert at the begining of the list # def insertatBeginning(self,newdata): # newnode=Node(newdata) # newnode.next=self.head # self.head=newnode # why is this . insnt it self.head.next?? def insertBeginning(self, newdata): if self.head is None: self.head = Node(newdata) else: newnode = Node(newdata) newnode.next = self.head self.head = newnode # def search(self, itemtosearch): # print('here') # cur = self.head # found = False # if cur is None: # raise ValueError("Data not in list") # while cur is not None: # if cur.data == itemtosearch: # Found = True # cur = cur.next # else: # cur = cur.next # Found = False # if Found: # print(True) # else: # print(False) # # def search(self, itemtosearch): # print("item to search",itemtosearch) # current=self.head # while current is not None: # if itemtosearch== # insert a node at specific position at linked list def insertAtSpecificPosition(self, data, position): ## another solution in hackerank newnode = Node(data) pos = 0 prev = None cur = self.head while cur is not None: pos = pos + 1 if pos == position: prev = cur cur = cur.next prev.next = newnode newnode.next = cur break else: cur = cur.next 1 - 1 - 2 - 20 - 5 # def insertAtSpecificPosition(self, data, position): ## another solution in hackerank prev = None current = self.head length = 1 while current is not None: if prev == None: prev = current current = current.next if length == position: newNode = Node(data) newNode.next = prev prev = current current = current.next return newNode.data length = length + 1 # def reverseLinkedList(self,): # inert newnode in between nodes(Inserting in between two Data Nodes) # delete at a specfic position # reverse a linked list # insert to linked list list = Linkedlist() list.insertatEnd(1) list.insertatEnd(2) list.insertatEnd(5) list.insertatEnd(20) print("done insering") # display the linked list list.disply() print("done displaying") # find the length of the linked list list.lengthLinkedlist() print("done displaying the length") # delete an item from linked list print("tesring deletekmkmkmkmkmkmk") list.disply() list.removeAnItem(5) list.disply() # # #print after deleteing # # list.disply() # insert at the beginning of the list list2 = Linkedlist() list2.insertBeginning(10) list2.insertBeginning(11) list2.insertBeginning(12) list2.disply() # print the linked list list.disply() # search an item in linked list # # list.search(20) # inserting a data and node speciac position print(list.insertAtSpecificPosition(8, 2)) print("sidddhdyydyydydd") list.disply()
d1366371ab09e23e16a6a551307a75f1f90e842c
GregorySkir/GG
/py/6read_zip.py
1,765
3.53125
4
import datetime import zipfile import csv def print_info(archive_name): if not zipfile.is_zipfile(archive_name): return ('not a zipfile') zf = zipfile.ZipFile(archive_name, 'r') for info in zf.infolist(): print (info.filename) print ('\tComment:\t', info.comment) print ('\tModified:\t', datetime.datetime(*info.date_time)) print ('\tSystem:\t\t', info.create_system, '(0 = Windows, 3 = Unix)') print ('\tZIP version:\t', info.create_version) print ('\tCompressed:\t', info.compress_size, 'bytes') print ('\tUncompressed:\t', info.file_size, 'bytes', '\n') def average_word_count(archive_name): with zipfile.ZipFile(archive_name) as zf: for filename in zf.namelist(): if filename.endswith('.csv'): with zf.open(filename, 'r') as open_file: count = 0 words = 0 for line in open_file: count += 1 words += len(line.split()) # data = zf.read(filename) if count > 0: print('file {0:s} has {1:d} lines with an average words count of {2:6.2f}'.format(repr(filename), count, words/count)) else: print('file {!r} is empty'.format(filename)) if __name__ == '__main__': my_example = 'Yelp' if my_example == 'Gutenberg': archive_name = '/Users/Neta/Documents/Teaching/Machine Learning 2018/Assignments/Gutenberg.zip' print_info(archive_name) else: archive_name = '/Users/Neta/Documents/Teaching/Introduction to Data Science /2019-2020/Exercises/yelp.csv.zip' average_word_count(archive_name)
7348458d8900ab64ea6ce0774b1045a8a57cd5d8
jiaxiaochu/spider
/00-Knowledge-review/04-闭包/05-修改闭包全局变量.py
816
3.765625
4
# coding = utf-8 def add_b(): global b b = 42 print("This id add_b's", b) def do_global(): global b b = b + 10 print("This is do_global's", b) do_global() print(b) add_b() # global 定义的变量,表明其作用域在局部以外, # 即局部函数执行完之后,不销毁 函数内部以global定义的变量 # def add_b(): # global b # b = 42 # def do_global(): # global a # a = b + 10 # print(b) # do_global() # print(a) # add_b() # print("a = %s , b = %s " %(a, b)) # def add_b(): # #global b # b = 42 # def do_global(): # global b # b = 10 # print(b) # do_global() # print(b) # add_b() # print(" b = %s " % b)
277c360773f3f7c048e518e76b58134744c3ee9e
gibum1228/Python_Study
/201814066_14.py
7,372
3.65625
4
""" 201814066 김기범 과제 14번 """ class Fraction: def __init__(self, n, d): """ 초기 값 정의해주는 메쏘드(자동 메쏘드) :param n: 분자 :param d: 분모 """ self.numer = n self.denom = d if n > 0 and d < 0: # 분자가 양수고 분모가 음수면 - 부호를 분자로 이동 self.denom = -d self.numer = -n # 새롭게 초기화하는 set 메쏘드 def setNumer(self, n): self.numer = n def setDenom(self, d): self.denom = d # 현재 값을 반환하는 get 메쏘드 def getNumer(self): return self.numer def getDenom(self): return self.denom # 현재 분수 값을 출력하는 print 메쏘드 def print(self): print("%d/%d" % (self.numer, self.denom)) # 덧셈 메쏘드 def add(self, o): n = (self.numer * o.denom) + (self.denom * o.numer) # 분자 계산 d = self.denom * o.denom # 분모 계산 ex = Fraction(n, d) # 덧셈 값을 ex에 저장 return ex # 결과값 반환 def __add__(self, o): # 덧셈 특수연산자 n = (self.numer * o.denom) + (self.denom * o.numer) # 분자 계산 d = self.denom * o.denom # 분모 계산 ex = Fraction(n, d) # 덧셈 값을 ex에 저장 return ex # 결과값 반환 # 뺄셈 메쏘드 def minus(self, o): n = (self.numer * o.denom) - (self.denom * o.numer) # 분자 계산 d = self.denom * o.denom # 분모 계산 ex = Fraction(n, d) # 뺄셈 값을 ex에 저장 return ex # 결과값 반환 def __sub__(self, o): # 뺄셈 특수연산자 n = (self.numer * o.denom) - (self.denom * o.numer) # 분자 계산 d = self.denom * o.denom # 분모 계산 ex = Fraction(n, d) # 뺄셈 값을 ex에 저장 return ex # 결과값 반환 # 나눗셈 메쏘드 def div(self, o): n = self.numer * o.denom # self 분자와 o 분모 곱하기 d = self.denom * o.numer # self 분모와 o 분자 곱하기 ex = Fraction(n, d) # 나눗셈 값을 ex에 저장 return ex # 결과값 반환 def __truediv__(self, o): # 나눗셈 특수연산자 n = self.numer * o.denom # self 분자와 o 분모 곱하기 d = self.denom * o.numer # self 분모와 o 분자 곱하기 ex = Fraction(n, d) # 나눗셈 값을 ex에 저장 return ex # 결과값 반환 # 곱셈 메쏘드 def multi(self, o): n = self.numer * o.numer # 분자끼리 곱하기 d = self.denom * o.denom # 분모끼리 곱하기 ex = Fraction(n, d) # 곱셈 값을 ex에 저장 return ex # 결과값 반환 def __mul__(self, o): # 곱셈 특수연산자 n = self.numer * o.numer # 분자끼리 곱하기 d = self.denom * o.denom # 분모끼리 곱하기 ex = Fraction(n, d) # 곱셈 값을 ex에 저장 return ex # 결과값 반환 # 최대공약수를 이용해 약분을 한다 def reduction(self): # 유클리드 호제법을 사용하기 위해서는 a > b 가 성립되어야 한다 a = max(self.numer, self.denom) # 큰 수를 a에 저장 b = min(self.numer, self.denom) # 작은 수를 b에 저장 # 2개의 자연수 a, b에 대해서 a를 b로 나눈 나머지를 r이라 하면(a>b), a와 b의 최대공약수는 b와 r의 최대공약수와 같다 while (a % b) != 0: # 유클리드 호제법 실행 ( 나머지가 0이면 조건문 탈출 ) r = a % b # 나머지 r a = b b = r n = self.numer // b # 최대공약수로 분자 나누기 d = self.denom // b # 최대공약수로 분모 나누기 ex = Fraction(n, d) # 약분된 값을 ex에 저장 return ex # 결과값 반환 # 출력 간단하게 해주는 메쏘드 def __str__(self): return "(" + str(self.numer) + "/" + str(self.denom) + ")" # 오퍼레이터 오버로딩(등호) 메쏘드 def __eq__(self, o): # 같다 특수연산자 """ self 와 o가 약분하여 같은 분수면 True 반환 :param o: 다른 분수 :return: 약분하여 같은 분수이면 True 반환 아니면 False 반환 """ g1 = gcm(self.numer, self.denom) # self 분모와 분자의 최대공약수 구하기 g2 = gcm(o.numer, o.denom) # other 분모와 분자의 최대공약수 구하기 if (self.numer // g1 == o.numer // g2) and (self.denom // g1 == o.denom // g2): # 약분된 분자와 분모가 같으면 return True # 참 반환 else: return False # 거짓 반환 # 같지 않다 특수연산자 def __ne__(self, o): """ 두 분수가 같으면 True, 아니면 False를 반환 """ if (self == o): # eq 메쏘드에서 오버리딩을 했기 때문에 간단하게 표현 가능 return False else: return True # 작다 특수연산자 def __lt__(self, o): g1 = self.numer * o.denom # self 분자 g2 = self.denom * o.numer # other 분자 if g1 < g2: # 분모는 같으니깐 분자 크기만 비교 return True # 참 반환 else: return False # 거짓 반환 # 작거나 같다 특수연산자 def __le__(self, o): if self == o or self < o: # eq, lt 메소드에서 오버리딩을 했기 때문에 간단하게 표현 가능 return True # 참 반환 else: return False # 거짓 반환 # 크다 특수연산자 def __gt__(self, o): g1 = self.numer * o.denom # self 분자 g2 = self.denom * o.numer # other 분자 if g1 > g2: # 분모는 같으니깐 분자 크기만 비교 return True # 참 반환 else: return False # 거짓 반환 # 크거나 같다 특수연산자 def __ge__(self, o): if self == o or self > o: # eq, gt 메소드에서 오버리딩을 했기 때문에 간단하게 표현 가능 return True # 참 반환 else: return False # 거짓 반환 # 최대공약수를 반환하는 함수 def gcm(x, y): # 두 정수 중 큰 수를 x에 저장, 작은 수를 y에 저장 if y > x: temp = y y = x x = temp # 유클리드 호제법에 의해 최대공약수 구함 while (y > 0): r = x % y x = y y = r return x # 프로그램 시작 부분 f1 = Fraction(4, -5) # 객체들 정의 f2 = Fraction(3, 2) f3 = Fraction(8, 31) f4 = Fraction(2, 3) f5 = Fraction(3, 5) f6 = Fraction(3, 7) f7 = Fraction(4, 8) f8 = Fraction(1, 2) f9 = Fraction(2, 81) f10 = Fraction(3, 9) print(f1, "*", f2, "=", (f1*f2).reduction()) # 곱셈 출력 print(f3, "-", f4, "=", (f3-f4).reduction()) # 뺄셈 출력 print(f5, "+", f6, "=", (f5+f6).reduction()) # 덧셈 출력 if f7 == f8: # f7과 f8이 같으면 print(f7, "==", f8, "= True") # 결과는 True else: # 아니면 print(f7, "==", f8, "= False") # 결과는 False if f9 >= f10: # f10보다 f9가 크거나 같으면 print(f9, ">=", f10, "= True") # 결과는 True else: print(f9, ">=", f10, "= False") # 결과는 False
515b34337df87e07e04b205836c281ad2baa1634
Ena-Sharma/Meraki_Solution
/Python_Programing_Excercise/Day_2/string_concatination2.py
490
4.15625
4
''' Apko ek string di jayegi jiske akhir me agar 'ing' hogi toh ushe aage apko 'ly' add karni hai aur agar 'ing' nhi hai toh 'ing' add karna hai. Lekin agar uske akhir meh 'ly' hai toh ushme app kuch bi add ni karoge Eg: Input: 'abc' Output: 'abcing' Input: 'string' Output: 'stringly' ''' string=raw_input('Enter the name:- ') var='ing' var2='ly' if string[-2:]==var2: print string elif string[-3:] != var: print string+'ing' else: if string[-3:]== var: print string+var2
55ceafa3e30e997bac0c6219141943391d4ae53e
HarishK501/100-days-of-coding
/longest-balanced-parenthesis.py
983
3.75
4
from stackADT import Stack def getLBPlength(S): # Longest Balanced Parenthesis(LBP) stk = Stack(len(S)+1) stk.push(-1) popCount = maxLen = 0 for i in range(len(S)): if S[i] == '(': stk.push(i) else: if not stk.isEmpty(): stk.pop() if stk.isEmpty(): stk.push(i) else: popCount = i - stk.top() # the important logic maxLen = max(maxLen, popCount) # else: # popCount = 0 return maxLen def main(): print("Program to find the length of the longest balanced parenthesis") print("Enter '#' to exit") while True: s = input("\n ➡ ") if s == "#": break print(" Result:", getLBPlength(s)) return if __name__ == "__main__": main() # s = ")())(()()()()" # s = "()()()()()" # s = "((((()"
9c559527aeb31f6f96b4db8a8a94248336c33306
anku255/Interviewbit
/Programming/String/reverse_the_string.py
578
3.578125
4
class Solution: def reverseWords(self, inputStr): inputStr = inputStr.strip() reversedStr = '' words = [] word = '' for char in inputStr: if char != ' ': word += char else: words.append(word) word = '' words.append(word) for i in range(len(words) - 1, 0, -1): reversedStr = reversedStr + words[i] + ' ' reversedStr += words[0] return reversedStr inputStr = "fwbpudnbrozzifml osdt ulc jsx kxorifrhubk ouhsuhf sswz qfho dqmy sn myq igjgip iwfcqq" s = Solution() print(s.reverseWords(inputStr))
d536ad106a052cef9d1a2fcffddfa3b357d2c225
harishbharatham/Python_Programming_Skills
/Prob12_3.py
661
3.71875
4
from account import account, atm for i in range (10): accountlist = [] accountlist.append(account(id1 = i)) def main1(): print(atmSim.mainMenu()) choiceInput = eval(input("Enter a choice:" )) if choiceInput == 1: print(atmSim.GetBalance()) main1() elif choiceInput == 2: d = eval(input("Enter amount to withdraw: ")) atmSim.withdraw(d) main1() elif choiceInput == 3: d = eval(input("Enter amount to deposit: ")) atmSim.withdraw(d) main1() else: None idInput = eval(input("Input your ID: ")) atmSim = atm(idInput) main1()
893be65167ff35ae6e6482cc758666c7bc523622
krisjanis-gross/remote-pi
/custom_configuration/b_griezeejs/input_functions/test1.py
420
3.703125
4
import os import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) buttonPin = 17 GPIO.setup(buttonPin,GPIO.IN) #initialise a previous input variable to 0 (assume button not pressed last) prev_input = 1 start_time = 0 current_time = 0 while True: #take a reading input = GPIO.input(buttonPin) # input = 0 when button is pressed # input = 1 when button is not pressed print(input) time.sleep(0.05)
15b888c88dcfb0a81fba91aaa38af83b276118da
kapilparab/HackerRank-Solutions-Python
/Algorithms/Utopian-Tree.py
326
3.5625
4
def utopianTree(n): init_height = 1 if n == 0: return init_height else: for i in range(1,n+1): if i%2==0: init_height += 1 else: init_height *= 2 return init_height cycles = [0,1,4] for i in cycles: utopianTree(i)
9184a9d9059a8b4c6fabfdfa6cdbcb647958dd68
k43lgeorge666/Python_Scripting
/basic code/lista2.py
233
3.53125
4
#!/usr/bin/python lista = [10,5,3,43,50,7] nro_elementos = 0 x = 0 while x<len(lista): if lista[x] >=7: nro_elementos = nro_elementos + 1 x = x+1 print("La cantidad de elementos mayores a 7 es: " + str(nro_elementos)) print("")
d3d18aebda9b9a1057fadc0d9f916e659f220518
plusuncold/word_bingo
/create_mode.py
2,519
3.765625
4
import game_data from typing import List, Dict ROUNDS = 5 DEFAULT_SAVE_PATH = 'game_state.json' def get_player_count() -> int: player_count = input('How many people are playing? ') return int(player_count) def get_players(player_count: int) -> List[str]: player_list = input('Who is playing? (Enter ' + str(player_count) + ' players separated by spaces) ') players = player_list.split() return players # Returns the order of selection from the list of players in snake draft order def get_selection_order(players: List[str], rounds: int) -> List[str]: selection_order = [] reverse = False for i in range(0,rounds): if reverse: for player in reversed(players): selection_order.append(player) reverse = False else: for player in players: selection_order.append(player) reverse = True return selection_order def get_word(player: str) -> str: word = input(player + ' select a word: ') return word def get_save_path() -> str: path = input('File to save game to [Default ' + DEFAULT_SAVE_PATH + ']') if path: return path else: return DEFAULT_SAVE_PATH def get_words(players: List[str], rounds: int) -> Dict[str, List[str]]: words = {} for player in players: words[player] = [] # The list of players names in order of word selection (snake draft) selection_order = get_selection_order(players, rounds) print('Select your words!') # Loop through and get all the words from input for player_selecting in selection_order: list_for_player = words[player_selecting] word = get_word(player_selecting) list_for_player.append(word) print('Selected words:') for player in words: print(player + ' ' + str(words[player])) return words def save_game_info(player_count: int, players: List[str], words: Dict[str, List[str]], game_file_path: str): game_state = game_data.GameState() game_state.set_members(player_count, players, words) game_state.save(game_file_path) # Create the game - define values and save to file def create_game(): # Get game info player_count = get_player_count() players = get_players(player_count) words = get_words(players, ROUNDS) game_file_path = get_save_path() # Save game info save_game_info(player_count, players, words, game_file_path)
af8aaa57c8c55c9e8136aa49b08ba393bb6c0803
patricknyu/random_stuff
/fizzbuzz.py
744
3.984375
4
def fib(n): if(n == 1): return [0] elif(n==2): return [0,1] else: fib_list = [0,1] for i in range(2,n+1): fib_list.append(fib_list[-1]+fib_list[-2]) return fib_list def sieve(n): sieve = [True]*n sieve[0] = False sieve[1] = False for i in range(2,n): if sieve[i]: for j in range(i*i,n,i): sieve[j] = False return sieve def fizzbuzz(n): fib_list = fib(n) s = sieve(fib_list[-1]+1) for i in range(0,len(fib_list)): if(fib_list[i] == 0): pass elif(fib_list[i] %3 == 0): fib_list[i] = "Buzz" elif(fib_list[i] %5 == 0): fib_list[i] = "Fizz" elif(s[fib_list[i]]): fib_list[i] = "FizzBuzz" return fib_list length = input('Enter how many fibonnaci fizzbuz you want :') print(fizzbuzz(length))
c6f358bb9755e681c69b66c750b7da2d64885c71
mazyvan/Python-Threads
/Hilos1.py
2,386
3.890625
4
import threading import sys import time from random import randint print('SUPER THREADING GAME v0.1 By Iván Sánchez') print() # Declaramos nuestras variables globales para guardar los numeros aleatorios number1 = 0 number2 = 0 ejecutarHilo_1 = True ejecutarHilo_2 = True # Declaramos la función que genera un nuevo número aleatorio def generate_random_number(): return randint(1, 99) def hilo1(): global number1, ejecutarHilo_1 time.sleep(100 / generate_random_number()) while ejecutarHilo_1: number1 = generate_random_number() print('Hilo 1: ' + str(number1)) print('') time.sleep(3) def hilo2(): global number2, ejecutarHilo_2 time.sleep(100 / generate_random_number()) while ejecutarHilo_2: number2 = generate_random_number() print('Hilo 2: ' + str(number2)) print('') time.sleep(3) print('Muy bien, las instrucciones son simples. En la pantalla apareceran numeros aleatorios entre el 0 y el 100') print('Tu mision (si decides aceptarla 8) sera intruducir esos valores antes de que el tiempo termine') print('Si no logras ingresar los valores, el juego continuara generando números aleatorios') start = input('>> ¿Deseas comenzar el desafio? (yes) (y/n): ') if start == 'n' or start == 'no': print('Ahh... que nena :(') sys.exit() print() print('Ready? Goo!') print() time.sleep(1) start_time = time.time() hilo_1 = threading.Thread(target=hilo1) hilo_1.start() hilo_2 = threading.Thread(target=hilo2) hilo_2.start() while hilo_1.isAlive() or hilo_2.isAlive(): isThisNumber = int(input('')) if isThisNumber == number1: ejecutarHilo_1 = False print('Bien mataste al hilo 1') print('') elif isThisNumber == number2: ejecutarHilo_2 = False print('Bien mataste al hilo 2') print('') else: print('Uy, que lento!') final_time = time.time() - start_time print('Has terminaado con todos los hilos ¡Felicidades!') print('/---------------------------------------------------\ ') print('| SCORE / PUNTUACION |') print('|---------------------------------------------------| ') print('|----------|----------------------------------------| ') print('| Time | ' + str(final_time) + ' Seg |') print('\----------|----------------------------------------/ ')
49b7aa41cf70b2b1eb17778299f147447a2d0adb
django-group/python-itvdn
/домашка/advanced/lesson 1/Alex Osmolowski/HW_01_02/udp_client.py
915
3.515625
4
# Задание 2 # Создайте UDP клиента, который будет отправлять уникальный идентификатор устройства на сервер, # уведомляя о своем присутствии. # UDP client socket import socket def main(): # создаем UDP socket (IP) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # цикл ввода и отправки сообщений на сервер while True: msg = input('Введите сообщение на сервер: ') msgb = msg.encode('utf-8') # отправляем сообщение на `127.0.0.1:7777` sock.sendto(msgb, ('127.0.0.1', 7777)) # проверка необходимости выхода из цикла if msg.strip().lower() == "stope": break if __name__ == '__main__': main()
7a33a88dc7478f886bccfc1e509c365b89b7781d
piloulac/leetcode
/9.palindrome_number.py
292
3.90625
4
# Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward. class Solution: def isPalindrome(self, x: int) -> bool: xStr = str(x) return xStr == xStr[::-1] # Next challenges: # do it without converting to string
23fec1961a1efccd7415be1376c7003253288370
andrezzadede/Curso_Guanabara_Python_Mundo_3
/Mundo 3 - Exercícios/87Exercicio.py
727
4.15625
4
#Aprimore o desafio anterior, mostrando no final: #A) A soma de todos os valores pares digitados #B) A soma dos valores da tecerceira coluna #C) O maior dos valores da segunda linha matriz = [[0,0,0], [0,0,0], [0,0,0]] maior = scol = pares = 0 for l in range(0,3): for c in range(0,3): matriz[l][c] = int(input(f'Digite para [{l}][{c}] ')) if matriz[l][c] % 2 == 0: pares += matriz[l][c] print(f'Soma dos Pares: {pares}') for l in range(0,3): scol += matriz[l][2] print(f'A soma da terceira coluna é: {scol}') #print(f'O maior numero da segunda linha: {seglinha}') for c in range(0,3): if c ==0: maior = matriz[1][c] elif matriz[1][c] > maior: maior = matriz[1][c] print(f'O maior número é:{maior}')
2c0b2aa89478c4d7bde199e479f963f644aafa81
Clockwick/DataStructureP2
/Practice/Recursion/SUBHAM.py
189
3.5
4
def fun(x): if(x > 0): x -= 1 fun(x) print(x, end=" ") x -= 1 fun(x) # Driver code a = 5 fun(a) # This code is contributed by SHUBHAMSINGH10
a0477f46064c87b8d5fa6f495e921ae1c5105181
Lazaraaus/python-card-games
/card_player.py
2,988
3.875
4
#Python class for a Player of our Card game #Global TODO: Add error catching blocks (built-in and self-defined) to all critical functions #Global TODO: Add unit tests for all classes and functions from card_suite import Deck class CardPlayer: """A simple class for modeling a player to play cards""" def __init__(self, username, player_number, score=0): """Initialize Player""" self.username = username self.player_number = player_number self.score = score self.hand = [] self.hand_length = 0 def __str__(self): return self.username + " as " + self.player_number + " playing " + game_type def GetUsername(self): return self.username def GetPlayerNumber(self): return self.player_number def GetScore(self): return self.score def ShowScore(self): print(self.score) def AddScore(self, points): self.score += points def SubScore(self, points): self.score -= points def PlayCard(self, index=0): return self.hand.pop(index) def GetCard(self, card): self.hand.append(card) self.hand_length += 1 def ShowHand(self): if self.hand_length == 0: print("Hand is empty") else: for card in self.hand: card.PrintCard() def DisplayCard(self, card_position): if card_position <= self.hand_length: self.hand[card_position].PrintCard() else: print(f"This card doesn't exist in {player.username}'s hand and can't be displayed") def PeekHand(self): if self.hand_length == 0: print("Hand is empty") else: self.hand[-1].PrintCard() def GetHandValue(self): sum = 0 for card in self.hand: sum += card.value return sum class CardDealer(CardPlayer): """A simple child class of CardPlayer to model a card game dealer""" def __init__(self, username='Dealer', player_number=0): """Function to initialize Card Dealer class""" #Call parent constructor super().__init__(username, player_number) #Class attribute to store list of current players self.player_list = [] self.deck = Deck() def BuildPlayersList(self, players): for player in players: self.player_list.append(player) self.player_list.append(self) def GetPlayersList(self): return self.player_list def PrintPlayersList(self): for player in self.player_list: print(player.GetUsername()) def RemovePlayer(self, player): self.player_list.remove(player) def GetPlayerScore(self, player): return player.GetPlayerScore() def PlayerAddPoints(self, player, points): player.AddScore(points) def PlayerSubPoints(self, player, points): player.SubScore(points) def DealCard(self, player): player.GetCard(self.deck.PopCard()) def DealCards(self, num_cards): for player in self.player_list: for num in range(1, num_cards + 1): self.DealCard(player) def EditValues(self, value_dict): for card in self.deck.contents: card.value = value_dict[card.rank]
48b25508ccd4b3882247542cb86008d66003327d
xexugarcia95/LearningPython
/CodigoJesus/Excepciones/Ejercicio1.py
495
3.890625
4
def division(a, b): try: return a/b except ZeroDivisionError: print("No se puede dividir entre cero") return "Operación errónea" while True: try: op1 = int(input("introduce un operador: ")) op2 = int(input("Introduce otro operador: ")) break except ValueError: print("Valor no válido") try: print(division(op1, op2)) except NameError: print("Debido a errores previos, las variables no están bien definidas")
fa6d6ca9198350b6282be28a65d8fb3a3f62f24c
KamilGrodzki97/Scripts
/Lab6/1.txt.txt
112
3.75
4
znaki = input("Podaj znaki: ") print("Znaki, które podałeś: " + znaki) for pozycja in znaki: print(pozycja)
99d71c5dffeb0cf85180b1b734eea0abc600dfa2
bugzPDX/learn_python
/projects/MyDungeon/mydungeon/mydungeon.py
6,510
3.96875
4
# Classes file from random import choice from textlist import text_list # Class for creating the main playing area class Dungeon(object): def __init__(self, x, y): self.rooms = [] self.cur_x = 0 self.cur_y = 0 for i in range(0, x): self.rooms.append([]) for j in range(0, y): self.rooms[i].append(None) # function to add rooms in an array def add_room(self, x, y, room): self.rooms[x][y] = room # funtions to handle navigation def north(self, args=[]): self.go(['north']) def south(self, args=[]): self.go(['south']) def east(self, args=[]): self.go(['east']) def west(self, args=[]): self.go(['west']) def go(self, args): direction = args[0] x = self.cur_x y = self.cur_y if direction == "north": if y == len(self.rooms[x]) - 1: print "You can't go that way." else: y += 1 elif direction == "south": if y == 0: print "You can't go that way" else: y -= 1 elif direction == "east": if x == len(self.rooms) - 1: print "You can't go that way." else: x += 1 elif direction == "west": if x == 0: print "You can't go that way" else: x -= 1 else: print "I don't know what that means." if self.rooms[x][y]: self.cur_x = x self.cur_y = y self.room().enter() else: print "You can't go that way." return self.room() def room(self): return self.rooms[self.cur_x][self.cur_y] # Class for creating rooms. Default "Kitchen" class Room(object): def __init__(self, name="Kitchen"): self.name = name self.__inventory = {} def enter(self, args=[]): print "You are in the %s" % self.name def look(self, args=[]): self.enter() if self.__inventory: print "You see %s lying on the floor" \ % text_list(self.__inventory.values()) else: return def fight(self, args=[]): print "You take a swing but there is nothing to fight" def add_item(self, item_name, item_description): self.__inventory[item_name] = item_description def take_item(self, item_name): if item_name in self.__inventory: item_description = self.__inventory[item_name] del self.__inventory[item_name] return item_description return None # Class for creating rooms that contain a monster # Will probably create a separate monster class. class MonsterRoom(Room): def __init__(self, monster, name="Monster Room"): self.monster = monster super(MonsterRoom, self).__init__(name) def enter(self, args=[]): super(MonsterRoom, self).enter() if self.monster: print "There is a %s here!" % self.monster def fight(self, args=[]): if not self.monster: print "There is nothing to fight here." return if choice([True, False]): print "You win!" self.monster = None else: print "You lose!" print "That was a ridiculously short game." user_command = raw_input("Play again? ").lower() if user_command == "yes": start() else: exit(0) # Class for creating a character class Character(object): def __init__(self, c_name): self.name = c_name self.__inventory = \ {"hat": "a knit hat", "mittens": "a pair of mittens", "key": "a brass key"} self.__dungeon = None def inventory(self, args=[]): print "You have %s" % text_list(self.__inventory.values()) def enter_dungeon(self, dungeon): print "Welcome %s! You find yourself standing in a strange " \ "%s." % (self.name, dungeon.room().name) self.__dungeon = dungeon def drop(self, args=[]): item_name = args[0] if item_name in self.__inventory: item_description = self.__inventory[item_name] print "You have dropped the %s." % item_name self.__dungeon.room().add_item(item_name, item_description) del self.__inventory[item_name] else: print "You don't have that." def get(self, args=[]): item_name = args[0] item_description = self.__dungeon.room().take_item(item_name) if item_description: print "You picked up %s." % item_description self.__inventory[item_name] = item_description else: print "I don't see %s." % item_name class Adventurer(Character): def __init__(self, a_name): if not a_name: print "No name huh? I guess you will be " \ "called Emanon" a_name = "Emanon" super(Adventurer, self).__init__(a_name) class Monster(Character): pass # Sets these so they can be global. my_adventurer = None my_dungeon = None # This is where things start happening. # Rooms, characters and such are created. # Player is prompted for a name. def start(): global my_adventurer global my_dungeon my_adventurer = Adventurer(raw_input("What is your name, Adventurer? ")) dark_room = Room("Dark Room") dark_room.add_item("lamp", "a brass lamp") my_dungeon = Dungeon(3, 3) my_dungeon.add_room(0, 0, Room()) my_dungeon.add_room(0, 1, MonsterRoom("Grue", "Dining Room")) my_dungeon.add_room(0, 2, dark_room) my_dungeon.add_room(1, 2, Room("Bedroom")) my_dungeon.add_room(2, 2, Room("Closet")) my_dungeon.add_room(2, 1, Room("Secret Passage")) my_dungeon.add_room(2, 0, Room("Hidden Room")) my_adventurer.enter_dungeon(my_dungeon) start() while True: print "Your coordinates are %s, %s" % (my_dungeon.cur_x, my_dungeon.cur_y) args = raw_input("> ").lower().split(' ') method = args.pop(0) has_error = True for obj in (my_adventurer, my_dungeon.room(), my_dungeon): try: getattr(obj, method)(args) has_error = False break except AttributeError: pass if has_error: print "Not sure what you mean"
79901da9b4410933324ab010b6335d0d17d256f8
hatleon/leetcode-9
/python/4_Median_of_Two_Sorted_Arrays.py
296
3.703125
4
#!/usr/bin/env python # coding=utf-8 def median(x): if len(x) % 2: return x[len(x) // 2] else: return (x[len(x) // 2 - 1] + x[len(x) // 2]) / 2 def findMedianSortedArrays(self, nums1, nums2): nums = nums1 + nums2 nums.sort() return Solution.median(nums)
9f69f60f745e6829f97731f9c0c73646ebdd20e5
DJaymeGreen/CollegeScoreCardAnalytics
/Ostu.py
7,826
3.921875
4
""" Author: D Jayme Green Date: 2/15/17 Ostu's Method and One-Dimensional Clustering This program splits vehicles into two groups: intentionally speeding or people who are maximizing safety. It studies traffic volume for road planning in order to maximize traffic flow. This problem does not cause any ethical concerns for me since it is trying to make the road better for everyone If this program was computer vision which automatically sends a ticket to a reckless driver, I would want to know how exactly it would be implemented and whether it was for safety or money. Also, I would consult the town/city people themselves if they want it as well as whether the road they put it on has a good speed limit. Being automatic, I want to be absolutely sure it is best for the community and everyone agrees. """ """ Matplotlib, csv, numpy imported Matplotlib is used to generate the graphs Csv is used to read in the csv data Numpy is used to allow floats into Matplotlib """ import matplotlib.pyplot as mpl import csv import numpy as np """ Constants are declared below for Histogram CarSpeedsFromCSV holds all of the numbers from the csv file which will be used for the histogram and the rest of the program """ currCarSpeedsFromCSV = list() def restartCarSpeedsFromCSV(): return(list()) #carSpeedsFromCSV = list() """ Reading in the .csv file and putting it into carSpeedsFromCSV list """ def openCSVFile(fileName, carSpeedsFromCSV): with open(fileName, newline='') as csvfile: reader = csv.reader(csvfile, delimiter=' ', quotechar='|') rowNum = 0 for row in reader: try: currCarSpeedsFromCSV.append(float(row[0])) except ValueError: print("Not adding row: "+ str(rowNum)) rowNum += 1 return carSpeedsFromCSV restartCarSpeedsFromCSV() currCarSpeedsFromCSV = openCSVFile('MedianWealth.csv', currCarSpeedsFromCSV) """ Creating a histogram from the data of the csv file The histogram will have bins starting at 38 and ending at 80 with 2mph difference """ counts, bins, patches = mpl.hist(currCarSpeedsFromCSV, bins=np.arange(min(currCarSpeedsFromCSV), 100000 + 5000,5000), linewidth=2, edgecolor='white') for patch, rightside, leftside in zip(patches, bins[1:], bins[:-1]): if rightside < 38000: patch.set_facecolor('blue') elif leftside > 38000: patch.set_facecolor('red') mpl.xlabel("Median Wealth of Graduates After 10 Years") mpl.ylabel('Amount of Colleges') mpl.title('Median Income of Graduates After 10 Years') mpl.grid(True) mpl.show() """ Ostu's Method for 1D Clustering Used design from lecture slides in order to do it """ """ Finds the variance of the data in carSpeedsFromCSV which are over or under the threshold given depending on isOver @param isOver Boolean specifying whether to find the variance over or under the threshold @param currentThreshold Int specifying what the threshold is currently to find the variance over or under it """ def findTheVariance(isOver, currentThreshold, carSpeedsFromCSV): sumOfAllOverOrUnder = 0 mu = 0 sumOfDifferenceSquared = 0 sizeOfPointsOverOrUnder = 0 standardDeviation = 0 if(isOver): for speeds in carSpeedsFromCSV: if(speeds > currentThreshold): sumOfAllOverOrUnder += speeds sizeOfPointsOverOrUnder += 1 if(sizeOfPointsOverOrUnder == 0): return 0 mu = float(sumOfAllOverOrUnder)/float(sizeOfPointsOverOrUnder) for speeds in carSpeedsFromCSV: if(speeds > currentThreshold): sumOfDifferenceSquared += pow(speeds-mu,2) return (sumOfDifferenceSquared/float(sizeOfPointsOverOrUnder)) else: for speeds in carSpeedsFromCSV: if(speeds <= currentThreshold): sumOfAllOverOrUnder += speeds sizeOfPointsOverOrUnder += 1 if(sizeOfPointsOverOrUnder == 0): return 0 mu = float(sumOfAllOverOrUnder)/float(sizeOfPointsOverOrUnder) for speeds in carSpeedsFromCSV: if(speeds <= currentThreshold): sumOfDifferenceSquared += pow(speeds-mu,2) return (sumOfDifferenceSquared/float(sizeOfPointsOverOrUnder)) """ Amount of points under or over the current threshold @param isOver Boolean determining whether to get the amount of points above (true) or below (false) @param currentThreshold The current threshold to find how many points are above or below """ def findAmountOfPoints(isOver, currentThreshold, carSpeedsFromCSV): amount = 0 for speeds in carSpeedsFromCSV: if(isOver): if(speeds > currentThreshold): amount += 1 else: if(speeds <= currentThreshold): amount += 1 return amount """ Variables used for Ostu's method initialized below """ totalThresholdPoints = max(currCarSpeedsFromCSV)-min(currCarSpeedsFromCSV) """ Ostu's Method for 1 Clustering It uses a multitude of functions before this and returns all of the valuable information to the places below """ def doOstuMethod(minRange, maxRange, carSpeedsFromCSV): bestMixedVariance = 99999999 bestThreshold = 0 allMixedVariances = list() for threshold in range(int(minRange),int(maxRange)): wtUnder = float(findAmountOfPoints(False, threshold, carSpeedsFromCSV))/float(totalThresholdPoints) if totalThresholdPoints != 0 else 0 varUnder = findTheVariance(False, threshold, carSpeedsFromCSV) wtOver = float(findAmountOfPoints(True, threshold, carSpeedsFromCSV))/float(totalThresholdPoints) if totalThresholdPoints != 0 else 0 varOver = findTheVariance(True, threshold, carSpeedsFromCSV) mixedVariance = (wtUnder * varUnder) + (wtOver * varOver) allMixedVariances.append(mixedVariance) if(mixedVariance < bestMixedVariance): bestMixedVariance = mixedVariance bestThreshold = threshold print("The best threshold is: " + str(bestThreshold)) print("The best, smallest variance is: " + str(bestMixedVariance)) return(bestMixedVariance, bestThreshold, allMixedVariances) """ All of the return values for Ostu's method These include the best variance, best threshold, and allMixedVariances These values are used later for the graph below """ OstuMethodReturn = doOstuMethod(min(currCarSpeedsFromCSV), max(currCarSpeedsFromCSV), currCarSpeedsFromCSV) bestMixedVariance = OstuMethodReturn[0] bestThreshold = OstuMethodReturn[1] allMixedVariances = OstuMethodReturn[2] """ Graph for mixed variance for the car data versus the value used to segment the data into two clusters """ bestThresholdList = [bestThreshold] * int(totalThresholdPoints) #for val in range(0,totalThresholdPoints): # bestThresholdList.append(bestThreshold) mpl.plot(allMixedVariances, bestThresholdList, 'ro') mpl.xlabel('Mixed Variance') mpl.ylabel('Best Value to Segment the Cars') mpl.title('Mixed Variance vs The Best Threshold of 1D Clustering') mpl.show() """ For the mystery data, we reset the list of car data used previous to an empty list Then we fill that empty list of the data from the Mystery_Data file Lastly, we do the Ostu's Method on the data which that prints out the best threshold and variance """ #currCarSpeedsFromCSV = restartCarSpeedsFromCSV() #currCarSpeedsFromCSV = openCSVFile('MedianWealth.csv', currCarSpeedsFromCSV) #doOstuMethod(6,38, currCarSpeedsFromCSV)
5817289b1f6c1d37720a6ca21ffde1e53fabdd95
LYblogs/python
/Python1808/第一阶段/day10-函数/测试代码页.py
2,162
3.984375
4
# # str = "-123" # # print(str[::-1]) # # class Solution: # def reverse( x): # """ # :type x: int # :rtype: int # """ # str1=str(x)[::-1] # return int(str1) # reverse(x=-123) # print(2**31) # list1=[1,2,3,4] # print(list1[0]+list1[1]) # def twoSum(nums, target): # """ # :type nums: List[int] # :type target: int # :rtype: List[int] # """ # list1=[] # for index in range(len(nums)): # for index1 in range(index,len(nums)): # if nums[index]+nums[index1] == target and nums[index]!=nums[index1]: # list1.append(index) # list1.append(index1) # return list1 # # print(twoSum([1,4,5,6],10)) # # def func2(): # print("我是函数2") # # list2 = [func2,100] # print(list2[0]()) #我是函数2 # #None # def test(x): # print(x) # # 声明一个int类型的变量a # a = 10 # #将变量a作为实参传递给变量test # test(a) # # # 声明一个function类型的变量 # def func3(): # print("我是函数3") # return "我是函数test" # test(func3()) #func3() => "我是函数test" # # iter2 = iter([1, 10, 100, 1000]) # for x in iter2: # print('==:', x) # # def creat_id(): # num = 1 # while True: # yield num # num+=1 # # re = creat_id() # a = next(re) # b = next(re) # print(a,b) # def creat_id(): # """ # 学号生成 # :return: # """ # num = 1 # while True: # yield num # num += 1 # re = creat_id() # # def nuw_studen(**kwargs): # """ # 添加学生信息 # :return: # """ # kwargs["学号"]="stu_00"+str(next(re)) # return kwargs # print(nuw_studen(name=1,age=18,tel=12121)) # print("学号",":",nuw_studen(name=1,age=18,tel=12121)["学号"],end=" ") # print("姓名",":",nuw_studen(name=1,age=18,tel=12121)["name"],end=" ") # print("年龄",":",nuw_studen(name=1,age=18,tel=12121)["age"],end=" ") # print("电话",":",nuw_studen(name=1,age=18,tel=12121)["tel"],end=" ") # I=1 # V=5 # X=10 # L=50 # C=100 # D=500 # M=1000 # s= "DID" # # for i in s: # # for x in s # # for i in s:
04c9960ecb87d42f5f07eb99f1918ece1fe75652
StefanDimitrovDimitrov/Python_Fundamentals
/Python_Fundamentals/Fundamentals level/02. Conditional Statements and Loops/Ex 09 Easter Cozonacs.py
606
3.78125
4
budget = float(input()) price_flour = float(input()) count = 0 current_budget = budget count_cozonac = 0 count_eggs = 0 price_pack_of_egg = price_flour * 0.75 price_milk_250ml = (price_flour + price_flour * 0.25) / 4 price_cozonac = price_flour + price_pack_of_egg + price_milk_250ml while current_budget > price_cozonac: current_budget -= price_cozonac count += 1 count_cozonac += 1 count_eggs += 3 if count == 3: count_eggs -= count_cozonac - 2 count = 0 print(f"You made {count_cozonac} cozonacs! Now you have {count_eggs} eggs and {current_budget:.2f}BGN left.")
caca5867fc73561fdecb0cb607f649dd5363d500
AugustoSavi/Python-primeiros-passos
/Desafio_026.py
303
4.03125
4
frase = input('Digite a Frase:') print('Numeros de vezes que aparecem o "A":{}'.format(frase.upper().count('A'))) print('A letra "A" apareceu primeiro na posição:{}'.format(frase.upper().find('A'))) print('A letra "A" apareceu por ultimo na posição:{}'.format(frase.upper().rfind('A')))
78f7afd6aedaebd8ce4fcc76b7a888e19baa35e4
EdenPlus/codingground
/PythonSandbox/main.py
3,636
3.796875
4
# Importing some stuff we'll need from itertools import permutations, product import urllib import urllib2 # Creating our method to remove stuff that isn't in standard english alphabet def ExtractAlphabetic(InputString): from string import ascii_letters return "".join([ch for ch in InputString if ch in (ascii_letters)]) # Feedback to the user print "" # These guys provide us with some whitespace in the output, making things look nicer print "Please wait while we connect to our dictionary..." # Pulling our dictionary req = urllib2.Request("http://www-01.sil.org/linguistics/wordlists/english/wordlist/wordsEn.txt") res = urllib2.urlopen(req) data = res.read() englishDictionary = data.split() # Feedback print "We've connected to our dictionary!" print "" userContinue = 0 while userContinue == 0: # Getting the user's phrase then establishing some of our variables symbols = ''.join(sorted(ExtractAlphabetic(raw_input("What is your phrase?: ")).lower())) print "Sorted string: " + symbols maxLength = len(symbols) print "String length: " + str(maxLength) print "" seen = set() listed = [] # Feedback print "Please wait while the generator runs it's course..." # Method to generate our permutations(Words) from the phrase def words1(chars=symbols, max_len=maxLength): print "" for length in xrange(1, maxLength + 1): for word in map(''.join, permutations(symbols, length)): if word in englishDictionary: if word not in seen: # Telling the user the words that have been created print "Unique word created: " + word # Returning the word in the map to be used by the for loop yield word print "" # Running our generator and pulling the words out of our generator for word in words1(): seen.add(word) # Feedback print "The generator has completed it's process!" print "" print "Now to move our words to the list..." # Pulling our words out of the set and checking if they are in the dictionary # Then sending them to a list because, I don't like sets for x in seen: listed.append(x) # Feedback print "We've moved our words into a list!" print "" print "Please wait a short bit while we sort our list..." # Sorting our list because, coding ground doesn't like in-line python final = sorted(listed, key=len) # Feedback print "We've sorted the list!" print "" print "Here's your words: " print "Format: (# of letters in the word) letter(s): (The generated word)" print "Summerized format:" print "[#] letter(s): [word]" print "" # Printing our words for y in final: print str(len(y)) + " letter(s): " + y # Establishing a variable with valid answers in it validAnswers = {"y", "ya", "yes", "yeah", "sure"} # Asking the user if they would like to keep using the program without reseting connection to the web page print "" print "Terms for this input (Case insensitive):" print "Yes: 'y' 'ya' 'yes' 'yeah' 'sure'" print "No: Anything that isn't in yes" print "" repeatQuestion = (raw_input("Shall we keep going?: ")).lower() print "" # Determining what the user's input means if repeatQuestion in validAnswers: # Keeps the program running userContinue = 0 else: # Ends the program print "Goodnight" print "" userContinue = 1
d3b4d92da9e737ef3986430c2e307ce3784b5f51
ORFMark/CS118
/InClassPY/emailVal.py
635
4.03125
4
fail="invalid email" hacker="hackerEmail" success="This is a valid Email" print("When you are finished entering email addresses, type 'done'.") cont="Yes" while True: usrEmail=input("Please input an email address: ") if usrEmail == 'done': break elif usrEmail.find('@') == -1: print("Invalid email") elif len(usrEmail) <= 4 or usrEmail[-4] == None or usrEmail[-4] != '.': print(fail) elif usrEmail.startswith('@')==True: print(fail) elif usrEmail.find('@hacker.com') != -1: print(hacker) else: print(success) print("Thank you for using Email Validator")
744c19831d45cb143aa15fc3077bf7376304760a
adrianogil/nanogenmo17
/src/main.py
1,228
3.578125
4
from island import Island from islandstory import IslandStory class Story: def __init__(self): self.story_size = 0 self.story_words = 0 def update_word_count(self, story_piece): words = 0 inside_word = False for s in story_piece: if inside_word and (s == ' ' or s == '\n' or s == '\t'): inside_word = False elif not inside_word and not (s == ' ' or s == '\n' or s == '\t'): inside_word = True words = words + 1 self.story_words = self.story_words + words def print_story(self, story_piece): self.story_size = self.story_size + len(story_piece) self.update_word_count(story_piece) print(story_piece) def generate_story(self): max_island_story_days = 10 while self.story_words < 50000: i = Island() island_story = IslandStory(i) for i in xrange(0, max_island_story_days): self.print_story(island_story.update_day()) # self.print_story('God created the region named as ' + i.island_name) s = Story() s.generate_story() print('\n\nStory has ' + str(s.story_words) + ' words')
b03b4d6c8a377d660b027257abee4ad48b2bf0d9
caterinasworld/gcd
/gcd_naive.py
419
3.515625
4
# implementation based on "A Comparison of Several Greatest Common Divisor Algorithms" # http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.259.1877&rep=rep1&type=pdf def brute_force(a, b): gcd = 0 # check whether a or b is the lower value if a > b: low = b else: low = a for i in range(1, low + 1): if a % i == 0 and b % i == 0: gcd = i return gcd
ca06a45713d58fddf8e0272c61c66ca5fc801171
Farewell1989/Hamiltonian-Generator
/Core/BasicClass/IndexPy.py
4,386
3.703125
4
''' Index. ''' from copy import deepcopy from re import split ANNIHILATION=0 CREATION=1 class Index: ''' This class provides a linear operator with an index. Attributes: site: integer The site index, start with 0, default value 0. orbital: integer The orbital index, start with 0, default value 0. spin: integer The spin index, start with 0, default value 0. nambu: integer '0' for ANNIHILATION and '1' for CREATION, default value ANNIHILATION. scope: string The scope of the index within which it is defined, default value 'None'. ''' def __init__(self,site=0,orbital=0,spin=0,nambu=ANNIHILATION,scope=None): self.site=site self.orbital=orbital self.spin=spin self.nambu=nambu self.scope=str(scope) def __str__(self): ''' Convert an instance to string. ''' if self.scope=='None': return 'Site,orbital,spin,nambu: '+str(self.site)+', '+str(self.orbital)+', '+str(self.spin)+', '+('ANNIHILATION' if self.nambu==ANNIHILATION else 'CREATION')+'\n' else: return 'Scope,site,orbital,spin,nambu: '+self.scope+', '+str(self.site)+', '+str(self.orbital)+', '+str(self.spin)+', '+('ANNIHILATION' if self.nambu==ANNIHILATION else 'CREATION')+'\n' def __repr__(self): ''' Convert an instance to string in a formal environment. ''' return self.scope+str(self.site)+str(self.orbital)+str(self.spin)+str(self.nambu) def __hash__(self): ''' Give an Index instance a Hash value. ''' return hash(self.scope+str(self.site)+str(self.orbital)+str(self.spin)+str(self.nambu)) def __eq__(self,other): ''' Overloaded operator(==). ''' if self.scope==other.scope and self.site==other.site and self.orbital==other.orbital and self.spin==other.spin and self.nambu==other.nambu: return True else: return False def __ne__(self,other): ''' Overloaded operator(!=). ''' return not self==other @property def dagger(self): ''' The dagger of the index, which keeps site, orbital and spin unchanged while sets nambu from CREATION to ANNIHILATION or vice versa. ''' return Index(self.site,self.orbital,self.spin,1-self.nambu,self.scope) def to_str(self,indication): ''' Convert an instance to string according to the parameter indication. ''' result='' for i in indication: if i in ('N','n'): result+=str(self.nambu)+' ' elif i in ('S','s'): result+=str(self.spin)+' ' elif i in ('C','c'): result+=str(self.site)+' ' elif i in ('O','o'): result+=str(self.orbital)+' ' elif i in ('P','p'): result+=self.scope+' ' return result def to_tuple(self,indication): ''' Convert an instance to tuple according to the parameter indication. ''' result=() for i in indication: if i in ('N','n'): result+=(self.nambu,) elif i in ('S','s'): result+=(self.spin,) elif i in ('C','c'): result+=(self.site,) elif i in ('O','o'): result+=(self.orbital,) elif i in ('P','p'): result+=(self.scope,) return result def to_index(str,indication): ''' Convert a string to index according to the parameter indication. ''' result=Index() values=split('\W+',str) for (i,v),value in zip(enumerate(indication),values): if v in ('N','n'): result.nambu=int(value) elif v in ('S','s'): result.spin=int(value) elif v in ('C','c'): result.site=int(value) elif v in ('O','o'): result.orbital=int(value) elif v in ('P','p'): result.scope=value else: raise ValueError('To_index error: each element of the indication must be "N" or "n"(nambu), "S" or "s"(spin), "C" or "c"(site), "O" or "o"(orbital), "P" or "p"(scope).') return result
317fbb4a2fcfdf0575c98ee751bb8026bb84f5f3
syurskyi/Algorithms_and_Data_Structure
/The Complete Data Structures and Algorithms Course in Python/template/Section 8 Python Lists/lists.py
1,258
4.0625
4
# Created by Elshad Karimov on 10/04/2020. # Copyright © 2020 AppMillers. All rights reserved. # Accessing/Traversing the list shoppingList = ['Milk', 'Cheese', 'Butter'] for i in range(len(shoppingList)): shoppingList[i] = shoppingList[i]+"+" # print(shoppingList[i]) empty = [] for i in empty: print("I am empty") # Update/Insert - List myList = [1,2,3,4,5,6,7] print(myList) myList.insert(4,15) myList.append(55) newList = [11,12,13,14] myList.extend(newList) print(myList) # Searching for an element in the List myList = [10,20,30,40,50,60,70,80,90] def searchinList(list, value): for i in list: if i == value: return list.index(value) return 'The value does not exist in the list' print(searchinList(myList, 100)) # List operations / functions total = 0 count = 0 while (True): inp = input('Enter a number: ') if inp == 'done': break value = float(inp) total = total + value count = count + 1 average = total / count print('Average:', average) numlist = list() while (True): inp = input('Enter a number: ') if inp == 'done': break value = float(inp) numlist.append(value) average = sum(numlist) / len(numlist) print('Average:', average)
15615a7ecfd303f50e03bd020ad26102129679c4
pritamsonawane/Assessment
/problemStmt12.py
310
3.59375
4
# -*- coding: utf-8 -*- """ Created on Tue Oct 10 14:44:37 2017 @author: User """ def DogAge(): humAge=input("enter dog age in human years: ") if humAge <=2.0: print "dog age is 10.5 years" else: dogAge = float((humAge-2) * 4 +(10.5)) print "dog age is %f years"% (dogAge)
5436bdee52c2477c3967ee9bba701ff093f75fb6
Aayush360/Shamshad_Ansari_CV_ANN
/list_3_9.py
856
3.984375
4
# masking: hiding or filtering of and image # we put focus on certain portion of the image while applying mask on the remaining portion # masking using Bitwise AND operation import cv2 import numpy as np # load an image nature = cv2.imread('../images/nature.jpg') cv2.imshow("original nature image", nature) # create a rectangular mask maskImage = cv2.rectangle(np.zeros(nature.shape[:2],dtype='uint8'),(50,50),(int(nature.shape[1])-50, (int(nature.shape[0]/2)-50)), (255,255,255),-1) cv2.imshow("mask image", maskImage) cv2.waitKey(0) # using bitwise and operaion to perfrom masking masked = cv2.bitwise_and(nature,nature,mask=maskImage) cv2.imshow("masked image", masked) cv2.waitKey(0)
3b1e773be979a6937c726040696c8fdc5121cde8
rajiv8/openCv_Files
/basicOperation.py
1,401
3.578125
4
# basic Operations import cv2 img = cv2.imread("./static/messi.jpg") img2 = cv2.imread("./static/Lenna.jpg") print(img.shape) # returns rows,columns and channels print(img.size) # total no.of pixels print(img.dtype) # returns datatype # b,g,r = cv2.split(img) #splitting the three channels # resizing the image - first method scale_percent=40 width = int(img.shape[1] * scale_percent / 100) height = int(img.shape[0] * scale_percent / 100) dsize=(width,height) # output = cv2.resize(img, dsize) # second method img= cv2.resize(img,(512,512)) img2=cv2.resize(img2,(512,512)) # b,g,r = cv2.split(output) #splitting the three channels after resizing # print(output.shape) # checking the shape of resized image # img = cv2.merge((b,g,r)) # merging the three channels # def click_event(event,x,y,flags,params): # if event == cv2.EVENT_LBUTTONDOWN: # print(x,",",y) # x, y are co-ordinates of clicks # cv2.imshow('image',output) # output = cv2.rectangle(output,(544,562),(670,652),(0,0,255),5) # output = cv2.rectangle(output,(502,520),(639,657),(0,0,255),5) # ball = output[544:562,652:670] # output[502:520,639:657] = ball adding = cv2.add(img,img2) # for simply adding the image adding = cv2.addWeighted(img,0.4,img2,0.3,0) # for inhancing the images cv2.imshow("image",adding) # cv2.setMouseCallback('image',click_event) cv2.waitKey(0) cv2.destroyAllWindows()
8b290568c6858916cddbea43c3431143764507be
wanhao2015/python
/Python learning/basic python/09.py
536
4.21875
4
for i,value in enumerate(['A','B','C','D']): print(i,value) for x,y in [(1,1),(2,4),(3,9)]: print(x,y) #请使用迭代查找一个list中最小和最大值,并返回一个tuple: def findMinAndMax(L): if L == []: return(None,None) min = max = L[0] for i,value in enumerate(L): if value < min: min = value min_i = i if value > max: max = value max_i = i return(min_i,min,max_i,max) list1 = [2,0,3,9,5] print(findMinAndMax(list1))
1e32322a36f8055fbfc3a286df988f97eab32cce
yost1219/python
/labs/lab5a.py
1,142
3.578125
4
""" Author: Yost Title: Lab 5A Date: 12 Sep 2018 Lab 5A: Utilizing Modules and Packages Instructions Using your calculator you created from Lab4A, split up the functionality into modules and utilize packaging. Some things you could split up: The user menu into it's own module on a higher level package Opeations into one module, lower level Algorithms into one module, lower level etc Requirments All requirments from Lab4A Utilize clean and proper dir and module names """ from modules.lab5amodules2 import * from lab5amodules import * #main def calculator(): calcMenu() #addition if choice == '1': add() #subtraction elif choice == '2': subtract() #division elif choice == '3': divide() #multiplication elif choice == '4': multiply() #power elif choice == '5': exponentiate() #mystery elif choice == '6': mystery() #fibonacci elif choice == '7': fibonacci() #else else: print "That is not a valid option. Goodbye." return calculator()
1ddbe7ff165395fc9a5a78adc0be903aadbe37fb
Camacaro/python-flask
/05-ejercicios/02-task.py
442
4.46875
4
# ingresar nombre y apellido e imprimirlo al reves nombre = input('Ingrese el nombre: ') apellido = input('Ingrese el apellido: ') # In this particular example, the slice statement [::-1] # means start at the end of the string and end at position 0, # move with the step -1, negative one, which means one step backwards. nombreCompleto = nombre + ' ' + apellido nombreCompletoReverse = nombreCompleto[::-1] print(nombreCompletoReverse)
29ee4d409888c9e68e8c7a61d61bf1f3bd5bd595
visw2290/Scripts-Practice
/Scripts-Pyc/sample game.py
458
3.859375
4
'''Its a program for getting Yes, no, maybe answers''' list1 = ['Yes', 'No','Maybe'] SampleFile = open('c:\\aaa\\quiz.txt') QuestionList = SampleFile.readlines() try: for i in QuestionList: print(i) Answer = input() if Answer.title() not in list1: print('Only Yes, No and Maybe accepted as answer!!Try again') Answer = input() finally: SampleFile.close() print("Thanks for participating in the survey")
45b54e25a5d71c4cb199df93769c090dd3612e36
SaiPrathekGitam/MyPythonCode
/Factors.py
378
4.25
4
# Program to find highest and smallest factor of given number n = int(input("Enter the number : ")) for i in range(n // 2 + 1, 1, -1): if n % i == 0: print(f"{i} is the highest factor of {n}") break else: print("prime") for i in range(2, n // 2 + 1): if n % i == 0: print(f"{i} is the smallest factor of {n}") break
541bd0f34cf176850d36fdc8a94af0c64682c047
TDBJR/Study
/Dictionary_Loops.py
573
4.6875
5
#Since the loop only sees the the name and not the value printing a dict in a loop will only list the names # so if you want it to list the value instead you type the name of the dict and the first variable of the for loop inside square brakets # the_links[keys] since keys is going to be the name it really means the_list['a'] and cylcles through all the names thus printing #all the values the_links={'a':'10','b':'20','c':'30','d':'40','e':'50'} for key in the_links: #print(key) print(the_links[key]) # print(the_links)
3e9f87cdd08a8de5630536ddc2405d574491ca3c
mehabhalodiya/Python
/11-cryptography/caesar_cipher.py
1,373
4.125
4
def cipher(): ans_start = input("Do you want to start? (YES/NO): ") ans_start = ans_start.upper() while(ans_start in 'YES'): print("What do you prefer to do?") ans = input("Press E to Encrypt and D to Decrypt: ") ans = ans.upper() if(ans=='E'): user_input = input("Enter the text you want to Encrypt: ") inlet = 'abcdefghijklmnopqrstuvwxyz1234567890' outlet ='4567890abcdefghijklmnopqrstuvwxyz123' encryption = '' encryption = encryption.maketrans(inlet,outlet) print("Decrypted code is:") print(user_input.translate(encryption)) elif(ans=='D'): user_input = input("Enter the text you want to Decrypt: ") inlet ='4567890abcdefghijklmnopqrstuvwxyz123' outlet = 'abcdefghijklmnopqrstuvwxyz1234567890' decryption = '' decryption = decryption.maketrans(inlet,outlet) print("Encrypted code is:") print(user_input.translate(decryption)) else: print("Please enter 'E' to Encrypt or 'D' to Decrypt.") ans_start = input("Do you want to do it again? ") ans_start = ans_start.upper() while (ans_start in 'NO'): print("Thank You!") break def main(): cipher() if __name__ == '__main__': main()
d8c5b81a7b66a63c7d8c9e6d8f85482a9e464337
mohammedSlimani/exercism
/python/isogram/isogram.py
589
4.0625
4
def is_isogram(string): # string is all lower case string = string.lower() # Searching for the repeated strings existing = [] for _str in string: if _str != ' ' and _str != '-': if _str in existing: return False else: existing.append(_str) return True ''' This is a smarter way of doing it! filter the string and then use the fact that sets have unique elements def is_isogram(string): string = [char for char in string.lower() if char.isalnum()] return len(set(string)) == len(string) '''
d4ed9ae0104f9055df6da5ab41f4001ed98b0f4e
Jnava3/Programming-Assignment-
/PA2.py
854
4.15625
4
""" John Nava Program #2: The Discount Calculator COSC 1306 Fall 2019 """ #Insert no. of items & original price itemnum=int(input("Items being sold: ")) cost=float(input("Original Cost ($): ")) #If the total cost is greater than or equal to $200 if(float(cost) >= float(200) and int(itemnum) <= 3): disc= .3 if(float(cost) >= float(200) and itemnum > 3 < 6): disc= .45 if(float(cost) >= float(200) and itemnum >= 6): disc= .60 #Other If statements if(float(cost) > 50 and float(cost) < 200): disc= .10 if(float(cost) <= 50): disc= 0 #Convert to percentage perc= int(disc * 100) #Calculate Final price savings= (cost * disc) fincost= float(cost-savings) #Display discount and final cost print("Discount Applied: " + str(perc) + "%") print("Final Cost: $" + "{0:.2f}".format(fincost))
dc35ff0c809696894b857e645416208ceda31c1c
BrandonLim8890/python
/automate_the_boring_stuff/chapter3/collatz.py
421
4.28125
4
def collatz(number): if number % 2 is 0: print(str(number) + " // 2") return number // 2 else: print("3 * " + str(number) + " + 1") return 3 * number + 1 number = 0 while number is not 1: print('Enter a number: ') try: guess = int(input()) number = collatz(guess) except ValueError: print('You did not use an integer') print(str(number))
41cdbe1b06ed21acb858b28635a52efbfcacc667
jtorain21/CS-115
/Property_Tax.py
1,924
4
4
# Joshua Torain CIS - 115 FON04 # write main function to control logic # write function to ask user for the value of their land # write function to calculate the assessment value of the land, which is 60% of actual value # write function to calculate the property tax, which is $0.72 for every $100 of the assessment value # wrtie function to display the assessment value and property tax # write main function def main(): user_property_value = property_value() assessment_value = calculate_assessment_value(user_property_value) property_tax = calculate_property_tax(assessment_value) display_values(user_property_value, assessment_value, property_tax) # ask user for value of their property. Store as a float def property_value(): # create variable to store users input user_property_value = float(input("What is the value of your property? ")) # return variable return user_property_value # write function to calculate assessment value. Use property value from user as parameter def calculate_assessment_value(user_property_value): # create variable to store calculation. assessment value is 60% of property value assessment_value = user_property_value * .60 # return variable return assessment_value # write function to calculate the property tax. Use assessment value as parameter def calculate_property_tax(assessment_value): # create variable to store calculation. Property tax is $0.72 for every $100 property_tax = (assessment_value / 100) * 0.72 # return variable return property_tax # write function to display assessment value and property tax. Use previous variables as parameters. Format in dollars. def display_values(user_property_value, assessment_value, property_tax): print("The Assessment Value is $ ", format(assessment_value, ',.2f')) print("The Property Tax is $ ", format(property_tax, ',.2f')) # call main function main()
6977809a8350e89c3f9e5475c445750bac37ece5
mohitleo9/interviewPractice
/Linked_Lists/2-6.py
217
3.71875
4
# Q this is about detecting the loop in a linkedList and printing out where the loop is? from LinkedLists import LinkedList, Node def loop(l): pass def main(): pass if __name__ == '__main__': main()
70e257694c47f412482f5035ea9178a0bb4e2dde
JessicaDeLuca/HelloWorld
/ex17_MoreFiles.py
1,304
3.84375
4
# Exercise 17 # Important functions # open(),read(),raw_input(),len(),exists(), write(), close() print "Begin Exercise 17: More Files \n" #Copy one file to another file from sys import argv from os.path import exists script, from_file, to_file = argv print "Copying from %s to %s" % (from_file, to_file) # we could do these two on one line, how? in_file = open(from_file) indata = in_file.read() print "The input file is %d bytes long" % len(indata) print "Does the output file exist? %r" % exists(to_file) print "Ready, hit RETURN to continue, CTRL-C to abort." raw_input() out_file = open(to_file, 'w') out_file.write(indata) print "Alright, all done." out_file.close() in_file.close() # MacBook-Pro-6:HelloWorld jessicadeluca$ python ex17.py test.txt test_copy2.txt # Begin Exercise 17: More Files # # Copying from test.txt to test_copy2.txt # The input file is 106 bytes long # Does the output file exist? False # Ready, hit RETURN to continue, CTRL-C to abort. # Steps for interesting clean output # State what the job does # State the file size # State is the output file exists or not using exists() # Ask for explicit consent before running the job # Return statement once job is successfully finished
2b0e4748d13be67e76c5c30deeb562f2ee83de08
ostin-r/Calculator
/calculator.py
3,816
3.796875
4
''' Austin Richards 1/5/21 this project made from the help of freeCodeCamp.org !!! ''' from tkinter import * gui = Tk() gui.title("Simple Calculator") # make the display e = Entry(gui, width=40, borderwidth=2) e.grid(row=0, column=0, columnspan=4, padx=10, pady=10) # functions for the buttons def button_click(number): current = e.get() e.delete(0, END) e.insert(0, str(current) + str(number)) def clear_display(): e.delete(0, END) def button_add(): first_number = e.get() global global_num global math math = "add" global_num = float(first_number) e.delete(0, END) def button_sub(): first_number = e.get() global global_num global math math = "sub" global_num = float(first_number) e.delete(0, END) def button_mul(): first_number = e.get() global global_num global math math = "mul" global_num = float(first_number) e.delete(0, END) def button_div(): first_number = e.get() global global_num global math math = "div" global_num = float(first_number) e.delete(0, END) def button_equal(): second_number = float(e.get()) e.delete(0, END) if math == "add": e.insert(0, global_num + second_number) elif math == "sub": e.insert(0, global_num - second_number) elif math == "mul": e.insert(0, global_num * second_number) elif math == "div": if second_number == 0: e.insert(0, "divide by 0 error") else: e.insert(0, global_num/second_number) else: e.insert(0, 'error') # make the buttons gen_width = 10 gen_height = 3 but1 = Button(gui, text="1", width=gen_width, height=gen_height, command=lambda: button_click(1)) but2 = Button(gui, text="2", width=gen_width, height=gen_height, command=lambda: button_click(2)) but3 = Button(gui, text="3", width=gen_width, height=gen_height, command=lambda: button_click(3)) but4 = Button(gui, text="4", width=gen_width, height=gen_height, command=lambda: button_click(4)) but5 = Button(gui, text="5", width=gen_width, height=gen_height, command=lambda: button_click(5)) but6 = Button(gui, text="6", width=gen_width, height=gen_height, command=lambda: button_click(6)) but7 = Button(gui, text="7", width=gen_width, height=gen_height, command=lambda: button_click(7)) but8 = Button(gui, text="8", width=gen_width, height=gen_height, command=lambda: button_click(8)) but9 = Button(gui, text="9", width=gen_width, height=gen_height, command=lambda: button_click(9)) but0 = Button(gui, text="0", width=gen_width, height=gen_height, command=lambda: button_click(0)) but_equal = Button(gui, text="=", width=gen_width, height=gen_height, command=button_equal) but_clear = Button(gui, text="clear", width= 44, height=gen_height, command=clear_display) but_decimal = Button(gui, text=".", width=gen_width, height=gen_height, command=lambda: button_click(".")) but_add = Button(gui, text="+", width=gen_width, height=gen_height, command=button_add) but_mul = Button(gui, text="*", width=gen_width, height=gen_height, command=button_mul) but_div = Button(gui, text="/", width=gen_width, height=gen_height, command=button_div) but_sub = Button(gui, text="-", width=gen_width, height=gen_height, command=button_sub) # put the buttons on the window but1.grid(row=3, column=0) but2.grid(row=3, column=1) but3.grid(row=3, column=2) but4.grid(row=2, column=0) but5.grid(row=2, column=1) but6.grid(row=2, column=2) but7.grid(row=1, column=0) but8.grid(row=1, column=1) but9.grid(row=1, column=2) but0.grid(row=4, column=1) but_add.grid(row=1, column=3) but_sub.grid(row=2, column=3) but_mul.grid(row=3, column=3) but_div.grid(row=4, column=3) but_equal.grid(row=4, column=2) but_clear.grid(row=5, column=0, columnspan=4) but_decimal.grid(row=4, column=0) gui.mainloop()
5412807d0657adf397e9221827a23d6dccdb0f33
wzds2015/RemoteSensing_Geophysics
/glacier/quadtree/quadtree.py
4,090
3.640625
4
import numpy as np import math import matplotlib.pyplot as plt def quadtree(data,th,max_l): ''' function used for generating a quadtree data (float): 2D image file (numpy array) th (float): threshold for standard deviation max_l (int): max level of leave (step=2**max_l) ''' line, col = data.shape[0], data.shape[1] dim = 1 if line >= col: dim_data = line else: dim_data = col while (dim<dim_data): dim *= 2 print "dim is: ", dim level_max = int(math.log(dim,2)) data_big = np.zeros((dim,dim),dtype=np.float32) * np.nan data_big[:line,:col] = data check = np.zeros((dim,dim),dtype=np.int16) level = np.copy(check) level[:,:] = level_max center_x = np.copy(check) center_y = np.copy(check) k = 1 for temp_level in range(max_l,0,-1): step = 2**temp_level for ni in range(0,dim,step): for nj in range(0,dim,step): temp_data = data_big[ni:ni+step,nj:nj+step] temp_data = temp_data[~np.isnan(temp_data)] if (0 in check[ni:ni+step,nj:nj+step]): if temp_data.size > 30 or temp_data.size == step**2: temp_std = np.std(temp_data) if temp_std < th: check[ni:ni+step,nj:nj+step] = k k += 1 level[ni:ni+step,nj:nj+step] = temp_level data_big[ni:ni+step,nj:nj+step] = np.average(temp_data) center_y[ni:ni+step,nj:nj+step] = ni + step/2. center_x[ni:ni+step,nj:nj+step] = nj + step/2. elif temp_data.size == 0: check[ni:ni+step,nj:nj+step] = -10 level[ni:ni+step,nj:nj+step] = temp_level center_y[ni:ni+step,nj:nj+step] = ni + step/2. center_x[ni:ni+step,nj:nj+step] = nj + step/2. data_big[ni:ni+step,nj:nj+step] = np.nan for ni in range(0,dim): for nj in range(0,dim): if check[ni,nj] == 0: center_y[ni,nj] = ni + 0.5 center_x[ni,nj] = nj + 0.5 check[ni,nj] = k level[ni,nj] = 0 k += 1 center_x = center_x.reshape(dim*dim,1) center_y = center_y.reshape(dim*dim,1) level = level.reshape(dim*dim,1) check1, indice_c = np.unique(check, return_index=True) ind = np.where(check1 == -10) indice_c = np.delete(indice_c,ind) check1 = np.delete(check1,ind) if -10 in check1: print "Array still contains nan! Check again.\n" exit(1) center_x1 = center_x[indice_c] center_y1 = center_y[indice_c] level1 = level[indice_c] return level1,center_x1,center_y1,data_big def plot_QDT(level,center_x,center_y,data): ''' function used for plotting a quadtree ''' v_min = data[~np.isnan(data)].min() v_max = data[~np.isnan(data)].max() fig, ax = plt.subplots(1) im = ax.imshow(data,cmap=plt.cm.jet, vmin=v_min, vmax=v_max) for ni in range(level.size): step = 2 ** level[ni] ''' if step >= 32: print str(ni) + " is wrong\n" fig.close() exit(1) ''' upleft_x = center_x[ni] - step/2. upleft_y = center_y[ni] - step/2. + 0.5 upright_x = center_x[ni] + step/2. upright_y = center_y[ni] - step/2. + 0.5 lowright_x = center_x[ni] + step/2. lowright_y = center_y[ni] + step/2. + 0.5 lowleft_x = center_x[ni] - step/2. lowleft_y = center_y[ni] + step/2. + 0.5 ax.plot([upleft_x,upright_x],[upleft_y,upright_y],'k-',linewidth=0.4) ax.plot([upright_x,lowright_x],[upright_y,lowright_y],'k-',linewidth=0.4) ax.plot([lowright_x,lowleft_x],[lowright_y,lowleft_y],'k-',linewidth=0.4) ax.plot([lowleft_x,upleft_x],[lowleft_y,upleft_y],'k-',linewidth=0.4) plt.savefig('QDT.png')
70393e5145ded52cda4f8caec0eb63927c0a9a7b
Gabrielly1234/Python_WebI
/estruturaRepetição/questao28.py
442
3.984375
4
#Faça um programa que calcule o valor total investido por um colecionador em sua coleção de CDs # e o valor médio gasto em cada um deles. O usuário deverá informar a quantidade de CDs # e o valor para em cada um. print("quant cd:") quant= int(input()) i=0 soma=0 for i in range (quant): print(" valor:") valor=float(input()) soma=soma+valor media=soma/quant print("valor investido:", soma) print("valor médio:", media)
af332c5181e584b3eaaba4c0b1234912a529c6eb
nandybishal23/Calender-using-Python
/main.py
1,463
3.6875
4
from tkinter import * import calendar def showCal() : new_gui = Tk() new_gui.config(background = "#00154f") new_gui.title("CALENDER") fetch_year = int(year_field.get()) l1=Label(new_gui,text=fetch_year,bg = "#f4af1b",fg="#00154f",font = ("times", 30, 'bold'),width=20) l1.grid(row = 1, column = 1) cal_content = calendar.calendar(fetch_year) cal_year = Label(new_gui, text = cal_content, font =("times",10, 'bold'),bg = "#eedc82",fg="#00154f") cal_year.grid(row = 5, column = 1,pady=20,padx=20) new_gui.mainloop() gui = Tk() gui.config(background = "white") gui.title("CALENDER") cal = Label(gui, text = "CALENDAR", bg = "#f4af1b",fg="#00154f",font = ("times", 30, 'bold')) cal.grid(row = 1, column = 1,columnspan=2) year = Label(gui, text = "Enter Year :",fg="#00154f",bg="white",font = ("times",30)) year.grid(row = 2, column = 1) year_field = Entry(gui,bg = "#eedc82",fg="#00154f",width=10,font = ("times",20)) year_field.grid(row = 2, column = 2,padx=5,pady=5) Show = Button(gui, text = "Show Calendar", fg = "#00154f",bg = "#f4af1b",width=12,font = ("times",15), command = showCal,activebackground="#00154f",activeforeground="#f4af1b") Show.grid(row = 4, column = 1) Exit = Button(gui, text = "Exit", fg = "White", bg = "red", width=12,font = ("times",15,"bold"),command = exit) Exit.grid(row = 4, column = 2,padx=5,pady=5) gui.mainloop()
a69f311c9f7461171120713da699a0ad171b1f1c
henry808/euler
/033/eul033.py
1,951
3.859375
4
#! /usr/bin/python from __future__ import print_function from fractions import Fraction # Project Euler # 33 def cancellable(num, den): """ returns a list of all digits except 0 that are in both numerator and denominator""" numorator = list(str(num).replace('0', '')) denominator = list(str(den).replace('0', '')) if len(numorator) < 2 or len(denominator) < 2: return [] return map(int, list(set(numorator) & set(denominator))) def remove_from(num, remove): """ only works for 2 digit numbers with no zeroes """ num = str(num) answer = num.replace(str(remove), '') if answer == '': # if answer is empty, there were two of same # and # we need to put one back in return int(num[:1]) else: return int(answer) def is_special_fraction(num, den): """ only works on 2 digit numerators and denominators""" if len(str(num)) != 2 or len(str(den)) != 2: return False can = cancellable(num, den) # if there are two cancellables, the numbers are either the # same (they will evaluate to 1 and be trivial) or else # they are opposite 78/87 and will not evaluae to 1 before # cancelling, so that means that special fractions have # to have only one cancellable value if not(len(can) == 1): return False can_value = can[0] new_num = remove_from(num, can_value) new_den = remove_from(den, can_value) if Fraction(new_num, new_den) == Fraction(num, den): return new_num, new_den else: return False if __name__ == '__main__': product = 1 for den in range(11, 99): for num in range(11, den): if not(den % 10 == 0) and not(num % 10 == 0): new = is_special_fraction(num, den) if new: print(num, "/", den, " = ", new[0], "/", new[1]) product *= Fraction(num, den) print("product:", product)
5ae034500e720a2bc12b2c6251b5ef7f59c21415
Rich43/rog
/albums/4/problem9.py/code.py
408
3.796875
4
def is_member(lst, a): '''(list,str) -> bool return whether str is a member of lst ''' x = 0 while x <= len(lst) - 1: if lst[x] == a: return True x += 1 continue return False lst =['a', 'c', 'f', 'g'] str = 'g' ans = is_member(lst, str) print(ans)
639995ac96283a256eeb5d03395a1bb3e56f96f3
frclasso/Apresentacao_Biblioteca_Padrao_Python_Unifebe_2018
/07_Date&Time/03_futureTimes_calendar.py
670
4.03125
4
#!/usr/bin/env python3 # Calculating future times from datetime import datetime, timedelta now = datetime.now() testDate = now + timedelta(days=2) # 2 days from now treeWeeksAgo = now - timedelta(weeks=3) # print(f"Daqui a dois dias: {testDate.date()}") # it's a datetime instance # print() # # print(f"Tree weeks ago: {treeWeeksAgo.date()}") # print() # Using calendar library import calendar # cal = calendar.month(2018,10) # October 2001 # print(cal) # # cal2 = calendar.weekday(2018, 10, 24) # What's 11 weekday # print(cal2) print() # leap year/bissextile year # print(calendar.isleap(1999)) # print(calendar.isleap(2000)) # print(calendar.isleap(2018))
3166e0875614fd7d814834f2991adead058728f9
17mirinae/Python
/Python/DAYOUNG/14_동적 계획법1/1_피보나치수.py
175
3.671875
4
n = int(input()) fibo = [0, 1] if n < 2: print(fibo[n]) else: for i in range(2, n+1): num = fibo[i-1] + fibo[i-2] fibo.append(num) print(fibo[n])
7e0a51bb9192ce583f83a56ffae9f6ffdd4e184f
jwsoat/Python-Game
/test.py
2,961
3.921875
4
def gameselector(): import random import time game = 0 while game == 0: game= int(input("Pick a game 1 - 3? ")) if game == 1: while game == 1: print("Game 1 Selected") print("Maths Calc rounding to 2dp") num1 = float(input("Number 1 ")) num2 = float(input("Number 2 ")) numansplus = num1 + num2 numanssub = num1 - num2 numanstimes = num1 * num2 numansdivide = num1 / num2 round(numansplus, 2) round(numanssub, 2) round(numanstimes, 2) plusround = round(numansdivide, 2) subround = round(numanssub, 2) roundtimes = round(numanstimes, 2) divideround = round(numansdivide, 2) print ("{} plus {} equals {}".format(num1,num2,plusround)) print ("{} minus {} equals {}".format(num1,num2,subround)) print ("{} times {} equals {}".format(num1,num2,roundtimes)) print ("{} divide {} equals {}".format(num1,num2,divideround)) playagain = input("play again") if playagain == "no": gameselector() #else: #continue while game == 2: print ("Gane 2 Selected") print ("Number guessing game") def numberguess(): number = random.randint(1,100) print (number) guesses = 0 print ("Guess number between 1 and 100") guesses +=1 while guesses <10: guess = int(input("Your guess")) guesses +=1 if guess < number: print ("try again") if guess > number: print ("try again") if guess == number: print ("You Won") print ("it took {} number of guesses".format(guesses)) playagain() if guess =="": print("try again") numberguess() while game == 3: dicerollmin = 1 dicerollmax = 6 rollagain = "yes" while rollagain == "yes" or rollagain == "y": print("rolling dice") time.sleep(1) print("the values are") print(random.randint(dicerollmin,dicerollmax)) print(random.randint(dicerollmin,dicerollmax)) rollagain = input("roll again?") if rollagain == "no": gameselector() def playagain(): playagain = input("play again") if playagain == "no": gameselector() def firsttime(): firsttimeans = input("have you played before? ") if firsttimeans == "no": print("Gane 1 Simple maths ") print("Game 2 Guess the Number ") print("Game 3 Dice Roll") gameselector() else: gameselector() firsttime() #keep at bottom
fc956051e95c71d1bb53748ee7da6f2cac42d95c
zihuan-yan/Something
/DataStructure/Mapping/__init__.py
13,035
3.578125
4
""" 映射 """ from abc import abstractmethod, ABCMeta from typing import * from random import randrange class MapBase(MutableMapping, metaclass=ABCMeta): class Item(object): __slots__ = 'key', 'value' def __init__(self, key, value): self.key = key self.value = value def __eq__(self, other): return self.key == other.key def __ne__(self, other): return not (self == other) def __lt__(self, other): return self.key < other.key class UnsortedTableMap(MapBase): def __init__(self): self._table = [] def __getitem__(self, key): for item in self._table: if item.key == key: return item raise KeyError('key error: {}' + repr(key)) def __setitem__(self, key, value): for item in self._table: if item.key == key: item.value = value return self._table.append(self.Item(key, value)) def __delitem__(self, key): for index in range(len(self._table)): if self._table[index].key == key: self._table.pop(index) return raise KeyError('key error: ' + repr(key)) def __len__(self): return len(self._table) def __iter__(self): for item in self._table: yield item.key class HashMapBase(MapBase, metaclass=ABCMeta): def __init__(self, capacity=11, prime=109345121): from random import randrange self._table: List[Any] = [None] * capacity self._length = 0 self.__prime = prime self.__scale = 1 + randrange(prime - 1) self.__shift = randrange(prime) def hash_function(self, key): """ MAD :param key: :return: """ return (hash(key) * self.__scale + self.__shift) % self.__prime % len(self._table) def __len__(self): return self._length def __getitem__(self, key): index = self.hash_function(key) return self._bucket_getitem(index, key) def __setitem__(self, key, value): index = self.hash_function(key) self._bucket_setitem(index, key, value) if self._length > len(self._table) // 2: self.__resize(2 * len(self._table) - 1) def __delitem__(self, key): index = self.hash_function(key) self._bucket_delitem(index, key) self._length -= 1 def __resize(self, capacity): _old_table = list(self.items()) self._table = capacity * [None] self._length = 0 for key, value in _old_table: self[key] = value @abstractmethod def _bucket_getitem(self, index, key): pass @abstractmethod def _bucket_setitem(self, index, key, value): pass @abstractmethod def _bucket_delitem(self, index, key): pass @abstractmethod def __iter__(self): pass class ChainHashMap(HashMapBase): def _bucket_getitem(self, index, key): bucket = self._table[index] if bucket is None: raise KeyError('key error: ' + repr(key)) return bucket[key] def _bucket_setitem(self, index, key, value): if self._table[index] is None: self._table[index] = UnsortedTableMap() _old_size = len(self._table[index]) self._table[index][key] = value if len(self._table[index]) > _old_size: self._length += 1 def _bucket_delitem(self, index, key): bucket = self._table[index] if bucket is None: raise KeyError('key error: ' + repr(key)) del bucket[key] def __iter__(self): for bucket in self._table: if bucket is not None and isinstance(bucket, UnsortedTableMap): for key in bucket: yield key class ProbeHashMap(HashMapBase): _AVAIL = object() def __is_available(self, index): return self._table[index] is None or self._table[index] is ProbeHashMap._AVAIL def __find_slots(self, index, key): first_avail = None while True: _item = self._table[index] if self.__is_available(index): if first_avail is None: first_avail = index if _item is None: return False, first_avail elif isinstance(_item, ProbeHashMap.Item) and key == _item.key: return True, index index = (index + 1) % len(self._table) def _bucket_getitem(self, index, key): _exist, _slots = self.__find_slots(index, key) if not _exist: raise KeyError('key error: ' + repr(key)) _item = self._table[_slots] if isinstance(_item, self.Item): return _item.value else: raise KeyError('value error: ' + repr(key)) def _bucket_setitem(self, index, key, value): _exist, _slots = self.__find_slots(index, key) if not _exist: self._table[_slots] = self.Item(key, value) self._length += 1 else: self._table[_slots].value = value def _bucket_delitem(self, index, key): _exist, _slots = self.__find_slots(index, key) if not _exist: raise KeyError('key error: ' + repr(key)) self._table[_slots] = ProbeHashMap._AVAIL def __iter__(self): for index in range(len(self._table)): if not self.__is_available(index): yield self._table[index].key class SortedTableMap(MapBase): def __init__(self): self._table = [] def __len__(self): return len(self._table) def __getitem__(self, key): index = self.__find_index(key) if index == len(self._table) or self._table[index].key != key: raise KeyError('key error: ' + repr(key)) return self._table[index].value def __setitem__(self, key, value): index = self.__find_index(key) if index < len(self._table) and self._table[index].key == key: self._table[index].value = value else: self._table.insert(index, self.Item(key, value)) def __delitem__(self, key): index = self.__find_index(key) if index == len(self._table) or self._table[index].key != key: raise KeyError('key error: ' + repr(key)) self._table.pop() def __iter__(self): for item in self._table: yield item.key def __reversed__(self): for item in reversed(self._table): yield item.key def __find_index(self, key, mode='ge'): low = 0 high = len(self._table) - 1 while low <= high: mid = (low + high) // 2 if key == self._table[mid].key: return mid elif key < self._table[mid].key: high = mid - 1 else: low = mid + 1 return high + 1 if mode == 'ge' else low - 1 def find_min(self): if len(self._table) > 0: _item = self._table[0] return _item.key, _item.value else: return None def find_max(self): if len(self._table) > 0: _item = self._table[-1] return _item.key, _item.value else: return None def find_le(self, key): index = self.__find_index(key, mode='le') if index >= 0: _item = self._table[index] return _item.key, _item.value else: return None def find_ge(self, key): index = self.__find_index(key) if index < len(self._table): _item = self._table[index] return _item.key, _item.value else: return None def find_lt(self, key): index = self.__find_index(key) if index > 0: _item = self._table[index - 1] return _item.key, _item.value else: return None def find_gt(self, key): index = self.__find_index(key) if index < len(self._table) and self._table[index].key == key: index += 1 if index < len(self._table): _item = self._table[index] return _item.key, _item.value else: return None def find_range(self, start, stop): if start is None: index = 0 else: index = self.__find_index(start) while index < len(self._table) and (stop is None or self._table[index].key < stop): _item = self._table[index] yield _item.key, _item.value index += 1 class CostPerformanceDatabase(object): def __init__(self): self.map = SortedTableMap() def best(self, cost): return self.map.find_le(cost) def add(self, cost, performance): _item = self.map.find_le(cost) if _item is not None and _item[1] > performance: return self.map[cost] = performance _item = self.map.find_gt(cost) while _item is not None and _item[1] <= performance: del self.map[_item[0]] _item = self.map.find_gt(cost) class SkipTable(MapBase): class Node(object): def __init__(self, element, next_=None, prev=None, above=None, below=None): self.element = element self.next = next_ self.prev = prev self.above = above self.below = below def __init__(self): self.start = self.Node((-float('inf'), None)) self.start.next = self.Node((float('inf'), None), prev=self.start) self.height = 0 self.size = 0 def __len__(self): return self.size def __iter__(self): _node = self.start while _node.below: _node = _node.below while _node.next.element[0] != float('inf'): yield _node.element[0] def __search(self, key): _node = self.start while _node.below is not None: _node = _node.below while _node.next.element[0] <= key: _node = _node.next return _node def __insert_after_above(self, left, below, element): _node = self.Node(element) if left is not None: _node.next, left.next, _node.prev = left.next, _node, left if below is not None: _node.above, below.above, _node.below = below.above, _node, below return _node def __getitem__(self, key): _node = self.__search(key) if _node is self.start: raise KeyError('key error: ' + repr(key)) return _node.element[1] def __setitem__(self, key, value): _node = self.__search(key) _next_node = None _index = -1 while True: _index += 1 if _index >= self.height: self.height += 1 _stop = self.start.next self.start = self.__insert_after_above(None, self.start, (-float('inf'), None)) self.__insert_after_above(self.start, _stop, (float('inf'), None)) _next_node = self.__insert_after_above(_node, _next_node, (key, value)) while _node.above is None: _node = _node.prev _node = _node.above if randrange(2) == 0: break self.size += 1 def __delitem__(self, key): _node = self.__search(key) while _node.above is not None: _node.prev.next = _node.next _node = _node.above if _node is self.start: raise KeyError('key error: ' + repr(key)) class MultiMap(object): _MAP_TYPE = dict def __init__(self): self.map = self._MAP_TYPE() self.length = 0 def __iter__(self): for key, value in self.map.items(): for v in value: yield v def add(self, key, value): _container = self.map.setdefault(key, []) _container.append(value) self.length += 1 def pop(self, key): value = self.map[key] v = value.pop() if len(value) == 0: del self.map[key] self.length -= 1 return key, v def find(self, key): value = self.map[key] return key, value[0] def find_all(self, key): value = self.map.get(key, []) for v in value: yield key, v if __name__ == '__main__': _chain = ChainHashMap() _chain['a'] = 1 _chain['b'] = 2 for i in _chain: print(i) print(_chain[i].value) _probe = ProbeHashMap() _probe['a'] = 1 _probe['b'] = 2 for i in _probe: print(i) print(_probe[i]) _skip = SkipTable() _skip[1] = 1 _skip[2] = 2 _skip[3] = 3 _skip[4] = 4 _skip[5] = 5 print(_skip[1]) print(_skip[2]) print(_skip[3]) print(_skip[4]) print(_skip[5])
fb17b5e9dd3cb2059afa76cc1f376151c9e738d7
denemorhun/Python-Reference-Guide
/Lesson 3 - More DS Examples/Ch07 - sets/07_02/start_07_02_sorting_friends.py
1,352
3.84375
4
""" Sorting Friends into Sets """ # set of all friends friends = set(['Mark', 'Rae', 'Verne', 'Richard', 'Aaron', 'David', 'Bruce', 'Garry', 'Bill', 'Connie', 'Larry', 'Jim', 'Landon', 'Dillon', 'Frank', 'Tom', 'Kyle', 'Katy', 'Olivia', 'Brandon']) # set of people who live in my zip code zipcode = set(['Jerry', 'Elaine', 'Cindy', 'Verne', 'Rudolph', 'Bill', 'Olivia', 'Jim', 'Lindsay', 'Rae', 'Mark', 'Kramer', 'Landon', 'Newman', 'George']) # set of people who play Munchkin munchkins = set(['Steve', 'Jackson', 'Frank', 'Bill', 'Mark', 'Landon', 'Rae']) # set of Olivia's friends olivia = set(['Jim', 'Amanda', 'Verne', 'Nestor']) # take the subset of friends who live close invite = friends.intersection(zipcode) # remove people who are already playing a game invite = invite - munchkins #merge with Olivia's friends olivia_available = olivia # Nestor is in Romania olivia_available.discard('Nestor') invite = invite.union(olivia_available) print(invite) while len(invite) > 0: f = invite.pop() if f is not 'Olivia': print(f"Call {f} and invite over!") # we can also do this using for # for buddy in invite: # if f is not 'Olivia': # print(f"Call {f} and invite over!")
faac6d3557770a3d1ebb5d2d2dbaab4487ed422b
jefinagilbert/problemSolving
/hr97_findMedian.py
112
3.71875
4
def findMedian(arr): arr.sort() return arr[len(arr)//2] arr = [5,3,1,2,4] print(findMedian(arr))
caaae06f5becb0434e27280b4fcd19b9ad62aed1
binrohan/30days_30problems
/problem010/day5.py
434
3.75
4
import math def isPrime(num): for x in xrange(2, int(round(math.sqrt(num))) + 1, 1): if num%x == 0: return False return num!=1 sum = 77 n = 20 while n<2000000: n += 1 if n>20 and n%2 != 0 and n%3 !=0 and n%4 !=0 and n%5 !=0 and n%6 != 0 and n%7 != 0 and n%8 != 0 and n%9 != 0 and n%11 != 0 and n%13 != 0 and n%17 != 0 and n%19 != 0: if isPrime(n): sum += n print n print sum
2211445cdaeb1d2b65f4ef8acefce04d9a6450b7
mygit20031984/py100exercises
/1_25/20.py
113
3.765625
4
d = {"a": 1, "b": 2, "c": 3} print(sum(d.values())) sum = 0 for e in d.values(): sum = sum + e print(sum)
39369c7228441056831214351e7bb0a782bddf0a
hudginspj/blue-limits
/experiments/collector.py
927
3.65625
4
MIN_WINDOWS = 10 WINDOW_SIZE = 10 class Collector(object): # The class "constructor" - It's actually an initializer def __init__(self): self.columns = 5 self.points = [] self.counter = -1 def addPoint(self, point): self.points.append(point) self.counter += 1 def nextXWindow(self): if self.counter >= WINDOW_SIZE + 1: ret = [] for i in range(WINDOW_SIZE): point = self.points[self.counter - i - 1] ret.append(point[0]) return ret else: return None def nextYOutputs(self): if self.counter >= WINDOW_SIZE + 1: return [self.points[self.counter][0]] else: return None if __name__ == "__main__": c = Collector() for i in range(100): c.addPoint([i]) print(c.nextXWindow()) print(c.nextYOutputs())
722272b9c526fc90582909fb1479c231c3f4b973
msmiel/mnemosyne
/books/Machine Learning/Machine Learning supp/code/appendixa-regular-expressions/FindCapitalized.py
144
4.3125
4
import re str = "This Sentence contains Capitalized words" caps = re.findall(r'[A-Z][\w\.-]+', str) print('str: ',str) print('caps:',caps)
5a86cc6a1b4ef28ca5bd741504d89f4985feb615
alvas-education-foundation/Rakshith_Rai
/coding_solutions/chocolatefeast.py
303
3.6875
4
def chocolateFeast(n, c, m): k=n//c n=k while(n>=m): n=n-m n=n+1 k+=1 return k t = int(input()) for t_itr in range(t): ncm = input().split() n =int(ncm[0]) c = int(ncm[1]) m = int(ncm[2]) result = chocolateFeast(n, c, m) print(result)
2851c4ed95a9a90b8b717590400447a6736d1875
SimeonTsvetanov/Coding-Lessons
/SoftUni Lessons/Python Development/Python Basics April 2019/Lessons and Problems/12 - Nested Loops Lab/05. Building.py
363
3.71875
4
levels = int(input()) rooms = int(input()) what_type = None for i in range(levels, 0, -1): for j in range(0, rooms): if i == levels: what_type = "L" elif i % 2 == 0: what_type = "O" elif i % 2 != 0: what_type = "A" print(f"{what_type}{i}{j} ", end="") print()
9669b179d98ac843b0469cad4de591487d9a068e
shukhrat121995/coding-interview-preparation
/heap/kth_largest_element_in_an_array.py
634
3.859375
4
""" Given an integer array nums and an integer k, return the kth largest element in the array. Note that it is the kth largest element in the sorted order, not the kth distinct element. """ import heapq class Solution: def findKthLargest(self, nums: list[int], k: int) -> int: heap = nums[:k] heapq.heapify(heap) for num in nums[k:]: # first you can use this method heapq.heappushpop(heap, num) # or you can use this one # heapq.heappush(heap, num) # if len(heap) > k: # heapq.heappop(heap) return heapq.heappop(heap)
bea598056323e203609226ca17706eaa137d3c01
JaydeepKachare/Python-Classwork
/Session12/Practice/02.py
597
3.609375
4
# Access specifiers in python Inheritance class Base : def __init__(self): pass def fun(self) : # public method print("Inside Base.fun") def _gun(self) : # protected method print("Inside Base._gun") def __sun(self) : # private method print("Inside Base.__sun") def main() : b = Base() b.fun() # public method b._gun() # protected method # b.__sun() # private method ==> Error if __name__ == "__main__" : main()
d9cf8c38b4f7d37210a597b0f86dec23e8e618ce
ingliscj/NCL-MSc-PORTFOLIO
/Python/BlackjackProject.py
5,863
3.75
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: from IPython.display import clear_output import random suits = ['Diamonds', 'Hearts', 'Clubs', 'Spades'] ranks = ['Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten','Jack' ,'Queen','King','Ace'] values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8 , 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11} class Card: def __init__(self,suit,rank): self.suit = suit self.rank = rank def __str__(self): return f"{self.rank} of {self.suit}" class Deck: def __init__(self): self.deck = [] for suit in suits: for rank in ranks: self.deck.append(Card(suit,rank)) def __str__(self): print(len(self.deck)) deck_update = '' for card in self.deck: deck_update += '\n' + card.__str__() return 'Deck contains: ' + deck_update def shuffle(self): random.shuffle(self.deck) def deal(self): single_card = self.deck.pop() return single_card class Hand: def __init__(self): self.cards = [] self.value = 0 self.aces = 0 def add_card(self,card): self.cards.append(card) self.value += values[card.rank] if card.rank == 'Ace': self.aces += 1 def ace_adjust(self): while self.value > 21 and self.aces: self.value -= 10 self.aces -= 1 class Chips: def __init__(self): self.bank = 500 self.bet = 0 def win_bet(self): self.bank += self.bet def lose_bet(self): self.bank -= self.bet def choose_bet(chips): while True: try: chips.bet = int(input('Place your bet: ')) except ValueError: print('Please input a valid number of chips!') else: if chips.bet > chips.bank: print('Sorry your bet cannot exceed: ', chips.bank) else: break def hit(deck,hand): hand.add_card(deck.deal()) hand.ace_adjust() def hit_or_stand(deck,hand): global playing while True: x = input('Would you like to hit or stand? Please enter "h" or "s": ') if x[0].lower() == 'h': hit(deck,hand) elif x[0].lower() == 's': print('Player is standing. Dealer is playing') playing = False else: print('Please enter a valid input!') continue break # Displays player's initial cards and one of the dealer's def show_some(player,dealer): clear_output() print("\nDealer's Hand: ") print(" <card hidden>") print("",dealer.cards[1]) print(" Dealer's Hand Value: ", values[dealer.cards[1].rank]) print("-"*20) print("\nPlayer's Hand: ", *player.cards, sep='\n ') print(" Player's Hand Value: ", player.value) print("-"*20) # Displays full hands of dealer and player def show_all(player,dealer): clear_output() print("\nDealer's Hand: ", *dealer.cards, sep='\n ') print("\nDealer's Hand Value: ", dealer.value) print("-"*20) print("\nPlayer's Hand: ", *player.cards, sep='\n ') print("\nPlayer's Hand Value: ", player.value) print("-"*20) def player_busts(player,dealer,chips): print("Player busts!") chips.lose_bet() def player_wins(player,dealer,chips): print("Player wins!") chips.win_bet() def dealer_busts(player,dealer,chips): print("Dealer busts!") chips.win_bet() def dealer_wins(player,dealer,chips): print("Dealer wins!") chips.lose_bet() def push(player,dealer): print("Dealer and Player tie! It's a push.") #GAME while True: print('Welcome to Blackjack! Dealer hits until 17 or higher. Enjoy!') # Initialize deck, shuffle it, and create player/dealer hands deck = Deck() deck.shuffle() player_hand = Hand() player_hand.add_card(deck.deal()) player_hand.add_card(deck.deal()) dealer_hand = Hand() dealer_hand.add_card(deck.deal()) dealer_hand.add_card(deck.deal()) # Set up player's chips, adjust for previous winnings & take bet player_chips = Chips() print('Your starting bank is: ' + str(player_chips.bank) + ' chips') choose_bet(player_chips) # Display first round of cards show_some(player_hand, dealer_hand) # Set boolean to control flow of loop playing = True while playing: hit_or_stand(deck, player_hand) show_some(player_hand, dealer_hand) if player_hand.value > 21: player_busts(player_hand, dealer_hand, player_chips) break if player_hand.value <= 21: while dealer_hand.value < 17: hit(deck, dealer_hand) show_all(player_hand, dealer_hand) if dealer_hand.value > 21: dealer_busts(player_hand, dealer_hand, player_chips) elif dealer_hand.value > player_hand.value: dealer_wins(player_hand, dealer_hand, player_chips) elif dealer_hand.value < player_hand.value: player_wins(player_hand, dealer_hand, player_chips) else: push(player_hand, dealer_hand) print("Player's winnings stand at: ", player_chips.bank) playing = int(input("Would you like to play another hand? Enter '1' if you would, and '0' if you're done!")) if playing: clear_output() continue else: clear_output() print('Thanks for playing!') break # In[ ]: # In[ ]: # In[ ]:
0eeabcf630404d36f1521182bdda6369426636c7
NickSeyler/MySortingAlgorithms
/Python/QuickSort.py
1,548
4.25
4
def quick_sort(arr): # if we don't know whether or not the array is sorted... if len(arr) > 1: # set pivot to the first index current_index = 0 # check all other items in the array for i in range(1, len(arr)): # if the item of the compared index is less than or equal to the item of the original pivot index, # increment the current index and swap that item with the compared item. # Note: this sometimes swaps the current index's item with itself. this is intended. if arr[i] <= arr[0]: current_index += 1 temp = arr[i] arr[i] = arr[current_index] arr[current_index] = temp # after checking all items, swap the pivot item with item of the new pivot index # in order to place the pivot item at its proper pivot temp = arr[0] arr[0] = arr[current_index] arr[current_index] = temp # perform the quicksort with items left of the index and right of the index. do not include the index left_arr = arr[0:current_index] right_arr = arr[current_index+1:len(arr)] quick_sort(left_arr) quick_sort(right_arr) # finally, combine the items left of the pivot index, the item of the pivot index, and the items right of the # pivot index. sorted_arr = left_arr + [arr[current_index]] + right_arr for i in range(0, len(arr)): arr[i] = sorted_arr[i]
aaecacbd2de47f4bc441cfc7a26ae7703c5f1138
david-sk/projecteuler
/src/problems/0062_cubic_permutations/v1.py
1,067
3.65625
4
# # Cubic permutations, v1 # https://projecteuler.net/problem=62 # # The cube, 41063625 (345^3), can be permuted to produce two other cubes: 56623104 (384^3) # and 66430125 (405^3). In fact, 41063625 is the smallest cube which has exactly three # permutations of its digits which are also cube. # Find the smallest cube for which exactly five permutations of its digits are cube. # def get_sorted_digits(n): digits = [] while n > 0: value = n % 10 n //= 10 for i in range(len(digits)): if value < digits[i]: digits.insert(i, value) break else: digits.append(value) return digits def run(): digits_map = {} key = '' n = 1 while True: key = ''.join(str(i) for i in get_sorted_digits(n ** 3)) if key in digits_map: digits_map[key][1] += 1 if digits_map[key][1] == 5: break else: digits_map[key] = [n, 1] n += 1 print('Smallest cube:', digits_map[key][0] ** 3)
ff8cab7193a3b3858033dac06f67f0287b827aa7
edinhooliveira/pyControl
/tkinter-matplot-test.py
458
3.53125
4
from tkinter import * from PIL import ImageTk, Image import numpy as np import matplotlib.pyplot as plt root = Tk() root.title('Codemy.com - Learn to Code!') #root.icobitmap('c:/GitHub/Python/Controle/ico/ifsp.ico') root.geometry("400x200") def graph(): house_prices = np.random.normal(200000, 25000, 5000) plt.hist(house_prices, 50) plt.show(); my_button = Button(root, text = "Graph It!", command = graph) my_button.pack() root.mainloop()
14f447b8fe4bb3e93c6df88f60bbb3c6b097f23f
chicocheco/automate_the_boring_stuff
/pdf_encrypting.py
842
3.75
4
import PyPDF2 pdf_file = open('meetingminutes.pdf', 'rb') pdf_reader = PyPDF2.PdfFileReader(pdf_file) pdf_writer = PyPDF2.PdfFileWriter() # Copy the PDF page by page. for page_num in range(pdf_reader.numPages): pdf_writer.addPage(pdf_reader.getPage(page_num)) # Encrypt the newly created PDF with the password 'swordfish'. pdf_writer.encrypt('swordfish') result_pdf = open('encryptedminutes.pdf', 'wb') pdf_writer.write(result_pdf) result_pdf.close() """ PDFs can have a user password (allowing you to view the PDF) and an owner password (allowing you to set permissions for printing, commenting, extracting text, and other features). The user password and owner password are the first and second arguments to encrypt(), respectively. If only one string argument is passed to encrypt(), it will be used for both passwords. """
6f3de8d13c6efdd7ab1d8119c8796127813ee7c8
dkhroad/fictional-barnacle
/p5/linkedlist.py
780
3.96875
4
class Node(object): def __init__(self,value): self.value = value self.next = None class LinkedList(object): def __init__(self): self.head = None self.last = None self.current = None def add(self,item): node = Node(item) if self.last: self.last.next = node self.last = node else: self.last = node if not self.head: self.head = self.last def __iter__(self): self.current = self.head return self def __next__(self): if self.current: value = self.current.value self.current = self.current.next return value else: raise StopIteration
c4dc7c5f0bd443c9bd32c53f4149c88a71b1095b
anto2318/python-blog
/bin/temp/openw.py
1,046
3.625
4
import requests def main(dict): city=dict["city"] q=dict["q"] if(city=="caracas"): r=requests.get("http://api.openweathermap.org/data/2.5/forecast?q=caracas&APPID=3b31a7e394e41c3a30759dfde1a3383e&units=metric") else: r=requests.get("http://api.openweathermap.org/data/2.5/forecast?q=madrid&APPID=3b31a7e394e41c3a30759dfde1a3383e&units=metric") result=r.json() if(q=="weather"): op = {"The current weather in {} is":result['list'][0]['weather'][0]['description']}.format(city) ##Aca es donde quiero poner el .format o algo asi elif(q=="windy"): op = {"The current wind speed is":result['list'][0]['wind']['speed']} elif(q=="feels"): op = {"It feels like":result['list'][0]['main']['feels_like']} elif(q=="temperature"): op = {"The temperature is":result['list'][0]['main']['temp']} else: op = {"ConMiGo got no answers ConMi":result['list'][0]} return op # return 'Currently, in {}, its {} degrees with {}'.format(city_name, temp, description)
b044102a3523535f1d12834626e232ccfe401ebe
catli/cs224
/assignment1/q2_neural.py
7,302
3.765625
4
#!/usr/bin/env python import numpy as np import random from q1_softmax import softmax from q2_sigmoid import sigmoid, sigmoid_grad from q2_gradcheck import gradcheck_naive def output_sigmoid(X, W1, b1): """ Step 1 of forward propogation Generate the sigmoid and the sigmoid gradient from input data """ # the X matrix contains a row for each observation (M) and the Dx is the # number of dimensions available for x (i.e. how many different words # are in the corpus recorded) # below we multiply the X-matrix by W1 to get a MxH matrix, where xw = np.matmul(X, W1) # we want to add the bias for each weights element-wise # we then translate each weight for each observation into h, the # sigmoid output that will be passed onto the next layer of weights # the sigmoid gradient will be used later during back-propagation s1 = xw+b1 print('****s1****') print(s1) h = sigmoid(s1) h_grad = sigmoid_grad(h) return h, h_grad def forward_prop_prediction(h, W2, b2): """ Step 2 of forward propogation Generate the prediction yhat from sigmoid and second weights """ # For each output h, we multiply it by another set of weights # this will output M x Dy output # where Dy representing all the dimension of output word guesses # (maps to the one hot vectors) # we also want to add the second bias onto each weight hw = np.matmul(h, W2) s2 = hw + b2 # the softmax converts every element on Dy into a likelihood # and regularizes it so that each row sum up to 1 # dimension is M x Dy yhat = softmax(s2) return yhat def calc_cost_from_prediction(labels, yhat): """ Step 3 of forward propogation Calculate cost function of current prediction based on true labels To calculate the cost function J = sum over i in m ( y_i * log (yhat_i) ) we multiple the labels M x Dy matrix by the log of predicted yhat (M x Dy) """ log_yhat = np.log(yhat) y_cost = labels*log_yhat j_cost = np.sum(-y_cost) return j_cost def forward_backward_prop(X, labels, params, dimensions): """ Forward and backward propagation for a two-layer sigmoidal network Compute the forward propagation and for the cross entropy cost, the backward propagation for the gradients for all parameters. Notice the gradients computed here are different from the gradients in the assignment sheet: they are w.r.t. weights, not inputs. Arguments: X -- M x Dx matrix, where each row is a training example x. labels -- M x Dy matrix, where each row is a one-hot vector. params -- Model parameters, these are unpacked for you. dimensions -- A tuple of input dimension, number of hidden units and output dimension """ ### Unpack network parameters (do not modify) ofs = 0 Dx, H, Dy = (dimensions[0], dimensions[1], dimensions[2]) W1 = np.reshape(params[ofs:ofs+ Dx * H], (Dx, H)) ofs += Dx * H b1 = np.reshape(params[ofs:ofs + H], (1, H)) ofs += H W2 = np.reshape(params[ofs:ofs + H * Dy], (H, Dy)) ofs += H * Dy b2 = np.reshape(params[ofs:ofs + Dy], (1, Dy)) # Note: compute cost based on `sum` not `mean`. ### YOUR CODE HERE: forward propagation # Generate the prediction using the input and parameters available h, h_grad = output_sigmoid(X, W1, b1) yhat = forward_prop_prediction(h, W2, b2) # print('******Yhat******') # print(yhat) # calculate cost function # print('*****cost*****') cost = calc_cost_from_prediction(labels, yhat) # print(cost) ### END YOUR CODE ### YOUR CODE HERE: backward propagation # Derivative of cost relative to z2: dcost / z2 = yhat- y # (proven for cost = - sum{ y * log(softmax(z2) } # since z2 = h*W2 + b2 # finding the derivative tells us the direction we need to move # against on b2 in order to get cost closer to 0 # (proved earlier that this is the derivative of softmax) # matrix size: M x Dy # if we find the average derivative across all observation M # then we get the gradient for b2 print('*****delta1*****') delta1 = yhat-labels M =delta1.shape[0] print(delta1) # Derivative of cost relative to h: dcost/ dh = delta1 * w2 # here we are applying the chain rule to calculate the next derivative # delta1 (M x Dy matrix) multiple against the transpose of W2 (Dy, H) # the output will be a M x H matrix # but you you need a Dy x M matrix print('*****delta2*****') delta2 = np.matmul(delta1, np.transpose( W2 ) ) print(delta2) # Derivaive of cost relative to z1 # we multiply delta2, the derivative of cost relative to h by # the derivative of the sigmoid (element-wise multiplication) # [TODO] Test delta3, derive this breaking out by element print('*****h_grad and h*****') print(h) print(h_grad) print('*****delta3*****') delta3 = delta2*h_grad print(delta3) # Derivative of cost relative to b2 # print('*****Gradientb2*****') one_m = np.ones(M).reshape(1,M) # print(one_m) gradb2 = np.matmul(one_m, delta1) # print(b2) # print('-------------') # print(gradb2) # print('*****GradientW2*****') gradW2 = np.matmul(np.transpose(h), delta1) # print(W2) # print('-------------') # print(gradW2) # print('*****Gradientb1*****') gradb1 = np.matmul(one_m, delta3) # print(b1) # print('-------------') # print(gradb1) # print('*****GradientW1*****') # [TODO] Test W1 derive this breaking out by element gradW1 = np.matmul(np.transpose(X), delta3 ) print('-----W1--------') print(W1) print('-----W1-gradient--------') print(gradW1) print('*****b1*****') print(b1) print('*****b2*****') print(b2) print('*****X*****') print(X) print('*****W2*****') print(W2) print('*****yhat*****') print(yhat) print('*****y*****') print(labels) ### END YOUR CODE ### Stack gradients (do not modify) grad = np.concatenate((gradW1.flatten(), gradb1.flatten(), gradW2.flatten(), gradb2.flatten())) print(grad) return cost, grad def sanity_check(): """ Set up fake data and parameters for the neural network, and test using gradcheck. """ print "Running sanity check..." N = 20 dimensions = [10, 5, 10] data = np.random.randn(N, dimensions[0]) # each row will be a datum labels = np.zeros((N, dimensions[2])) for i in xrange(N): labels[i, random.randint(0,dimensions[2]-1)] = 1 params = np.random.randn((dimensions[0] + 1) * dimensions[1] + ( dimensions[1] + 1) * dimensions[2], ) gradcheck_naive(lambda params: forward_backward_prop(data, labels, params, dimensions), params) def your_sanity_checks(): """ Use this space add any additional sanity checks by running: python q2_neural.py This function will not be called by the autograder, nor will your additional tests be graded. """ print "Running your sanity checks..." ### YOUR CODE HERE # raise NotImplementedError ### END YOUR CODE if __name__ == "__main__": sanity_check() your_sanity_checks()
3e31997ffcefceaaed3e15ddeb8a70cfddc6f867
kumakiwi/pypp
/29.py
176
3.5625
4
import sys x = raw_input("input a number: ") c = len(x) print "the number has %d digits" % c a = [i for i in x] a.reverse() for i in range(len(x)): sys.stdout.write(a[i])
ad2453475b7d1ff3c48e088ca0fca1f98eccbff5
codenigma1/Python_Specilization_University_of_Michigan
/Using Database with Python/Week-3/umich_rel_insert.py
1,633
4.21875
4
import sqlite3 conn = sqlite3.connect('relational.db') cur = conn.cursor() def create_table(): cur.execute("CREATE TABLE IF NOT EXISTS Artist (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT)") cur.execute("CREATE TABLE IF NOT EXISTS Genre(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT)") cur.execute("CREATE TABLE IF NOT EXISTS Album(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, artist_id INTEGER, title TEXT)") cur.execute("CREATE TABLE IF NOT EXISTS Track(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, title TEXT, album_id INTEGER, genre_id INTEGER, len INTEGER, rating INTEGER, count INTEGER)") # create_table() def data_entry(): cur.execute("INSERT INTO Artist(name) VALUES ('Led Zepplin'), ('AC/DC')"); cur.execute("INSERT INTO Genre(name) VALUES ('Rock'), ('Metal')"); cur.execute("INSERT INTO Album(title, artist_id) VALUES ('Who Made Who', 2), ('IV', 1)"); cur.execute("INSERT INTO Track(title, album_id, genre_id, len, rating, count) VALUES ('Black Dog', 5, 297,0, 2, 1), ('Stairway', 5, 482, 0, 2, 1), ('About to Rock', 5, 313, 0, 1, 2), ('Who Made Who', 5, 207, 0, 1, 2)") # conn.commit() # Here I used JOIN simple query. def select_data(): # cur.execute("SELECT Album.title, Artist.name, Album.artist_id, Artist.id FROM Artist JOIN Album WHERE Album.artist_id=Artist.id") cur.execute("SELECT Track.title, Artist.name,Album.title, Genre.name FROM Track JOIN Genre JOIN Artist JOIN Album WHERE Track.genre_id=Genre.id AND Album.id=Track.album_id AND Artist.id=Album.artist_id") print(cur.fetchall()) select_data() # data_entry() cur.close() conn.close()
7f606e6bfeaf00925e792108ed24f162a072bdc8
fernandofalla/Tarea1LFP
/Tarea1/PrintFunction.py
167
3.9375
4
def print_function(n): cadena = "" for i in range(n): cadena += str(i+1) return cadena n = int(input("Ingrese numero: ")) print(print_function(n))
9b8bc108d4ccdfb5b80068cdf8e47d02ef1caba7
ClaytonStudent/leetcode-
/OfferPython/18_delete_next_node.py
599
3.828125
4
# 题目:在O(1)时间内删除链表的节点 class ListNode(object): def __init__(self, x): self.val = x self.next = None class Soluton(object): def deleteNode(self,head,val): if head.val == val: return head.next pre,cur = head, head.next while cur and cur.val != val: pre,cur = cur,cur.next if cur: pre.next = cur.next return head A = ListNode(1) A.next = ListNode(2) A.next.next = ListNode(3) S= Soluton() head = S.deleteNode(A,1) print(head.val) print(head.next.val) print(head.next.next)
19af0effc4f19b5f799c1562e40b639a8d2dfd8a
GBobzin/sqlalchemy-challenge
/app.py
4,436
3.84375
4
# Step 2 - Climate App #Now that you have completed your initial analysis, design a Flask API based on the queries that you have just developed. #* Use Flask to create your routes. #Libraries import numpy as np import pandas as Pd import datetime as dt #Other tools import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from flask import Flask, jsonify #data engine = create_engine("sqlite:///Resources/hawaii.sqlite") Base = automap_base() Base.prepare(engine, reflect = True) measurement = Base.classes.measurement station = Base.classes.station session = Session(engine) app = Flask(__name__) ### Routes @app.route("/") def home(): return ( f"Welcome! I LOVE flask!<br/>" f"These are the available routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/<start><br/>" f"/api/v1.0/<start>/<end>" ) # * Convert the query results to a dictionary using `date` as the key and `prcp` as the value. # * Return the JSON representation of your dictionary. @app.route("/api/v1.0/precipitation") def precipitation(): last_year = dt.datetime(2017,8,23) - dt.timedelta(days = 365) prcp_result = session.query(measurement.date, measurement.prcp).filter(measurement.date >= last_year).all() precipitation = {date:prcp for date, prcp in prcp_result} return jsonify(precipitation) # * Return a JSON list of stations from the dataset. @app.route("/api/v1.0/stations") def stations(): # stationsq = session.query(station.name, station.station) # station_list = pd.read_sql(stationsq.statement, stationsq.session.bind) # return jsonify(station_list.to_dict()) # station_result station_result = session.query(station.station).all() station_list = list(np.ravel(station_result)) return jsonify(station_list) #Query the dates and temperature observations of the most active station for the last year of data. #from previous excercise, we know latest date is 23/08/2017 and most active station USC00519281 @app.route("/api/v1.0/tobs") def tobs(): last_year = dt.datetime(2017,8,23) - dt.timedelta(days = 365) tobs_result = session.query(measurement.date,measurement.tobs).filter(measurement.station== "USC00519281").filter(measurement.date >= last_year).all() temp_date = [] for tob in tobs_result: row = {} row["date"] = tobs_result[0] row["tobs"] = tobs_result[1] temp_date.append(row) #tobs_list = list(np.ravel(tobs_result)) return jsonify(temp_date) # * Return a JSON list of the minimum temperature, the average temperature, and the max temperature for a given start or start-end range. # * When given the start only, calculate `TMIN`, `TAVG`, and `TMAX` for all dates greater than and equal to the start date. #* When given the start and the end date, calculate the `TMIN`, `TAVG`, and `TMAX` for dates between the start and end date inclusive. app.route("/api/v1.0/<start>") def starting(start): temp_query = session.query(func.min(measurement.tobs),func.avg(measurement.tobs), func.max(measurement.tobs)).filter(measurement.date >= start).all() session.close() temps = [] for minT, maxT, avgT in temp_query: dict = {} dict['Min_temp']=minT dict['Max_temp']=maxT dict['Avg_temp']=avgT temps.append(dict) return jsonify(temps) # temps= list(np.ravel(temp_query)) #unsuccssful approach #return jsonify(temps) #for temp in temp_query: # dict = {} # dict['date']=temp[0] # dict['Min_temp']=temp[1] # dict['Max_temp']=temp[3] # dict['Avg_temp']=temp[2] # list.append(dict) @app.route("/api/v1.0/<start>/<end>") def starting_ending(start,end): temp_query = session.query(func.min(measurement.tobs),func.avg(measurement.tobs), func.max(measurement.tobs)).filter(measurement.date >= start).filter(measurement.date <= end).all() session.close() temps = [] for minT, maxT, avgT in temp_query: dict = {} dict['Min_temp']=minT dict['Max_temp']=maxT dict['Avg_temp']=avgT temps.append(dict) return jsonify(temps) if __name__ == '__main__': #url = 'http://127.0.0.1:5000/' #webbrowser.open_new(url) app.run(debug=True)
ffadd78aaf27bedcde5084ac80500ddcaf870cab
claudejin/leetcode
/solutions/203_Remove_Linked_List_Elements.py
692
3.640625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeElements(self, head: ListNode, val: int) -> ListNode: # trim heads while head and head.val == val: head = head.next # none is left if not head: return None # remove val prev_node, cur_node = head, head.next while cur_node: if cur_node.val == val: prev_node.next = cur_node = cur_node.next else: prev_node, cur_node = cur_node, cur_node.next return head
3133bf6f6b28c6c3996614742bd68e74a8f55131
KBALDE/oc_ai_eng_2021
/oc_p04_gthub/utils/utils_eng.py
6,090
3.703125
4
#import libraries import numpy as np import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.metrics import confusion_matrix from sklearn.model_selection import cross_val_score from sklearn.model_selection import cross_val_predict from sklearn.metrics import precision_score, recall_score, f1_score from sklearn.preprocessing import OrdinalEncoder from sklearn.preprocessing import LabelEncoder import matplotlib.pyplot as plt # a function to fit/predict and show metrics def modelFitCrossValPredMetrics(model, train, train_labels): ''' model : instantiate the model first train : data to fit train_labels : labels we use cross val predict so we do not a validation set, we can use only the training set ''' train_pred = cross_val_predict(model, train, train_labels, cv=3) print("Confusion Matrix \n \n", confusion_matrix(train_labels, train_pred)) print("\n") print("Precision : ", precision_score(train_labels, train_pred)) print("\n") print("Recall : " , recall_score(train_labels, train_pred)) print("\n") print("F_Score : " ,f1_score(train_labels, train_pred)) # feature importance def plot_feature_importances(df,col): """ Plot importances returned by a model. This can work with any measure of feature importance provided that higher importance is better. Args: df (dataframe): feature importances. Must have the features in a column called `features` and the importances in a column called `importance Returns: shows a plot of the 15 most importance features df (dataframe): feature importances sorted by importance (highest to lowest) with a column for normalized importance """ # Sort features according to importance df = df.sort_values('importance', ascending = False).reset_index() # Normalize the feature importances to add up to one df['importance_normalized'] = df['importance'] / df['importance'].sum() # Make a horizontal bar chart of feature importances plt.figure(figsize = (10, 15)) ax = plt.subplot() # Need to reverse the index to plot most important on top ax.barh(list(reversed(list(df.index[:col]))), df['importance_normalized'].head(col), align = 'center', edgecolor = 'k') # Set the yticks and labels ax.set_yticks(list(reversed(list(df.index[:col])))) ax.set_yticklabels(df['feature'].head(col)) # Plot labeling plt.xlabel('Normalized Importance'); plt.title('Feature Importances') plt.show() return df # PCA def pcaDataFrame(df): ''' take a quantitative dataframe return pca.components_, pca instance, and df of coord. ind and PCAs ''' # PCA libraries scaler=StandardScaler() n_components=df.shape[1] colz=['PC_'+ str(i) for i in range(1,n_components+1)] dex=df.index dexPca=df.columns X = df.values X_scaled=scaler.fit_transform(X) pca = PCA(n_components) df_v=pca.fit_transform(X_scaled) return pd.DataFrame(pca.components_, index=colz, columns=dexPca), \ pca, pd.DataFrame(df_v, index=dex, columns=colz) # One Hot Encoding def oneHotEncoding(df): # Create a label encoder object le = LabelEncoder() # Iterate through the columns for col in df: if df[col].dtype == 'object': # If 2 or fewer unique categories if len(list(df[col].unique())) <= 2: # Train on the training data #le.fit(df[col]) # Transform both training and testing data df[col] = le.fit_transform(df[col]) return df def ordinalEncoding(df): ordinal_encoder = OrdinalEncoder() return pd.DataFrame(ordinal_encoder.fit_transform(df), index=df.index, columns=df.columns) # correlation list with respect to one variable for quanti variables def corrByVar(df,var): ''' return a list of variables that are significantly correlated with the given variable parameters : df: dataframe var: var to be used for correlation computation ''' D={} for i in df.columns.tolist(): if i==var : continue else: D[i]=np.corrcoef(df[var], df[i])[0][1] d=pd.DataFrame.from_dict(D, orient='index', columns=['corrz']).sort_values('corrz', ascending=False) print("\nVariables that are very correlated with", var) #.index.tolist() return d[(d['corrz'] < -0.3) | (d['corrz'] > 0.3) ] # return list instead def corrByVarList(df,var): ''' return a list of variables that are significantly correlated with the given variable parameters : df: dataframe var: var to be used for correlation computation ''' D={} for i in df.columns.tolist(): if i==var : continue else: D[i]=np.corrcoef(df[var], df[i])[0][1] d=pd.DataFrame.from_dict(D, orient='index', columns=['corrz']).sort_values('corrz', ascending=False) print("\nVariables that are very correlated with", var) #.index.tolist() return d[(d['corrz'] < -0.3) | (d['corrz'] > 0.3) ].index.tolist() def display_scree_plot_coud(pca): scree = pca.explained_variance_ratio_*100 plt.figure(figsize=(15,8)) #plt.bar(np.arange(len(scree))+1, scree) plt.plot(np.arange(len(scree))+1, scree.cumsum(),c="red",marker='o') plt.xlabel("rang de l'axe d'inertie") plt.ylabel("pourcentage d'inertie") plt.title("Eboulis des valeurs propres") plt.show(block=False) def display_scree_plot_bar(pca): scree = pca.explained_variance_ratio_*100 plt.figure(figsize=(15,8)) plt.bar(np.arange(len(scree))+1, scree) #plt.plot(np.arange(len(scree))+1, scree.cumsum(),c="red",marker='o') plt.xlabel("rang de l'axe d'inertie") plt.ylabel("pourcentage d'inertie") plt.title("Eboulis des valeurs propres") plt.show(block=False)
9f084c12bb463631ecdf20e2a97a4ec33595ea82
Vadim91200/BlackJack
/ISN - Black Jack.py
5,234
3.59375
4
# -*- coding: utf-8 -*- from random import * jeu = [11, 11, 11, 11] #Création de la liste jeu def ajout_carte(main): a = choice(jeu) #On sélectionne aléatoirement une carte dans la liste 'jeu' main.append(a) #On ajoute cette carte a la liste 'main' jeu.remove(a) #On retire cette carte de la liste 'jeu' pour qu'elle ne soit pas retiré return main #On retourne la liste 'main' def tirage(): cartes = [] #On crée la liste vide 'cartes' for i in range(2):#On répète deux fois le tirage cartes.append(ajout_carte([]))#On affecte le résultat de ce tirage dans la lise 'cartes' print(cartes) if cartes[0] == 11 and cartes[1] == 11:#On vérifie si les deux cartes de la liste sont des 11 cartes[0] = 1#si c'est le cas on remplace le premier 11 par 1 return cartes #on retourne la liste 'cartes' def total(main): somme = sum(main) #On fait la somme de la liste 'main' if somme > 21 and main.count(11)!=0: #On teste si la somme est supérieur à 21 et que la liste contient un 11 main[main.index(11)] = 1 #Si c'est le cas on remplace le 11 par 1 somme = sum(main) #On refait la somme de la liste modifié return somme # On retourne la somme def jouer(): print("Bonjour et bienvenue au jeu de Black Jack!") k = input("Souhaitez vous débuter une partie? OUI ou NON:") while k != "OUI": k = input("Souhaitez vous débuter une partie? OUI ou NON:") if k == "OUI": x = tirage()# La variable 'x' contiendra les deux cartes du joueur y = tirage()#La variable 'y' contiendra les deux cartes de l'ordinateur j = []#On crée la liste 'j' qui contiendra les cartes du joueur o = []#On crée la liste 'o' qui contiendra les cartes de l'ordinateur t = 0 #On crée la variable 't' qui contiendra le total des cartes du joueur d = 0#On crée la variable 'd' qui contiendra le total des cartes de l'ordinateur for k in y: o.append(k[0])#On transforme la liste de liste 'y' en liste simple 'o' qui contient les cartes de l'ordinateur for k in x: j.append(k[0])#On transforme la liste de liste 'x' en liste simple 'j' qui contient les cartes du joueur d = total(o) #On fait le total des cartes de l'ordinateur t = total(j)#On fait le total des cartes du joueur print("Vos cartes sont", j, "Le total est de:",t)#On affiche les cartes du joueur et leurs total print("La première cartes de l'ordinateur est", o[0])#On affiche la première carte de l'ordinateur s = input("Souhaitez vous une nouvelle carte? Tapez N pour une nouvelle carte; P pour ne pas avoir de nouvelle carte:") #On demande au joueur s'il souhaite une nouvelle carte while s == "N": x.append(ajout_carte([]))#On ajoute une nouvelle carte à la liste de liste 'x' a = x.pop()#On isole la liste contenant la nouvelle carte for i in a: v = i #La variable 'v' contient la nouvelle carte sous forme d'int j.append(v)#On ajoute la nouvelle carte sous forme d'int a la liste simple 'j' print("Vos cartes sont", j)#On affiche la nouvelle main du joueur t = total(j)#On calcule le nouveau total if t > 21:#Si le total est supérieur à 21 print("Vous avez perdu la partie, votre score total est de: ", t) #On affiche que le joueur a perdu car il a dépassé 21 s=="P"#On arrête la boucle while else: print("Votre score total est de:", t)#On affiche le total des cartes du joueur s = input("Voulez vous une carte supplémentaire ?")#On lui demande s'il en veut une encore while d < 17: #Si le total des cartes de l'ordinateur est inférieur à 17 y.append(ajout_carte([])) #On ajoute une nouvelle carte à la liste de liste y a=y.pop()#On isole la liste contenant la nouvelle carte for i in a: v=i #La variable 'v' contient la nouvelle carte sous forme d'int o.append(v)#On ajoute la nouvelle carte sous forme d'int à la liste simple 'o' d=total(o)#On calcule le nouveau total if d>21:#Si le total des cartes de l'ordinateur est supérieur à 21 print("L'ordinateur a dépassé 21 vous avez gagné")#On affiche que l'ordinateur a perdu car il a dépassé 21 elif d<t:#si le total des cartes de l'ordinateur est inférieur au total des cartes du joueur print("Vous avez gagné la partie, votre score est de:", t ,"Le score de l'ordinateur est de:",d,".") #On affiche que le le joueur a gagné elif t<d:#si le total des cartes de l'ordinateur est supérieur au total des cartes du joueur print("Vous avez perdu, votre score est de:",t ,"Le score de l'ordinateur est de:",d,".") #On affiche que l'ordinateur a gagné elif t==d:#si le total des cartes de l'ordinateur est égal au total des cartes du joueur print("Il y a égalité")#On affiche qu'il y a égalité jouer()
bc0b134380f7b6ee4e9ce25bedaea8eb59c6fc81
int-0/python-pce
/pre-src/rects.py
2,612
3.90625
4
#!/usr/bin/env python """ This simple example is used for the line-by-line tutorial that comes with pygame. It is based on a 'popular' web banner. Note there are comments here, but for the full explanation, follow along in the tutorial. """ #Import Modules import os, pygame from pygame.locals import * if not pygame.font: print 'Warning, fonts disabled' if not pygame.mixer: print 'Warning, sound disabled' import walkable class RectFactory: def __init__(self, srf, new_rect_cb = None): self.srf = srf self.r_cb = new_rect_cb self.first_point = None def set_point(self, point): if self.first_point == None: self.first_point = point return rect = pygame.Rect(self.first_point, (point[0] - self.first_point[0], point[1] - self.first_point[1])) if not self.r_cb is None: self.r_cb(rect) self.first_point = None self.draw(rect) def draw(self, rect): pygame.draw.rect(self.srf, 0xffffff, rect, 2) # Function to show cross def put_cross(srf, point): h1 = (point[0] - 5, point[1]) h2 = (point[0] + 5, point[1]) v1 = (point[0], point[1] - 5) v2 = (point[0], point[1] + 5) pygame.draw.line(srf, 0xffffff, h1, h2) pygame.draw.line(srf, 0xffffff, v1, v2) def main(): """this function is called when the program starts. it initializes everything it needs, then runs in a loop until the function returns.""" # Initialize Everything pygame.init() screen = pygame.display.set_mode((1024, 768)) pygame.display.set_caption('Monkey Fever') pygame.mouse.set_visible(1) # Display The Background pygame.display.flip() # Prepare Game Objects clock = pygame.time.Clock() # Walkable areas warea = walkable.Walkable() # Rect factory rfactory = RectFactory(screen, warea.add_rect) # Main Loop while 1: clock.tick(60) # Handle Input Events for event in pygame.event.get(): if event.type == QUIT: return elif event.type == KEYDOWN and event.key == K_ESCAPE: return elif event.type is MOUSEBUTTONUP: rfactory.set_point(event.pos) points = warea.get_common_points() for point in points: put_cross(screen, point) # Draw Everything pygame.display.flip() # Game Over # This calls the 'main' function when this script is executed if __name__ == '__main__': main()
cfa73e903f7f28209ec2662d3b785323b3d12952
JayaramachandranAugustin/python_tutorial
/variables/variableassignment.py
444
4.0625
4
import sys a=2 print(type(a)) x,y,z=1,2,3 print("x is {} y is {} z is {}".format(x,y,z)) p,q=1,2 print("Before swap : p is {} q is {}".format(p,q)) p,q=q,p print("After swap : p is {} q is {}".format(p,q)) l,m,n=[1,2,3] print("l is {} m is {} n is {}".format(l,m,n)) #assign tuple to multiple variables d,e,f=(1,2,3) print("d is {} e is {} f is {}".format(d,e,f)) ''' None is absence of value *******''' abc=None print(type(abc))
627a073f5330942b70679bb92e29d5bc17cccba2
PJHutson/prg105
/7.2.py
1,339
4
4
def main(): import random # randomize random_list = [] for i in range(20): # set it to 20 numbers random_list.append(random.randrange(1, 101, 1)) # give the bounds return random_list def user(): # set up the user input count = 0 try: while count == 0: user_value = int(input("Please enter a number between 1 and 100: ")) if 1 <= user_value <= 100: # make sure user input is in the range count += 1 return user_value else: print("\nThat is not a valid number") except TypeError: print("Sorry, there was an error with your answer") except ValueError: print("Sorry, there was an error with your answer") def display(num, nums): # set up display index = 0 count = 0 while index < 20: # comparison, if user input is lower than numbers in list if int(nums[index]) > num: pri = nums[index] print(pri) else: count += 1 index += 1 if count == 20: print("None of the numbers in the list are greater than yours") # show you have the greatest number display(user(), main())
a07af432f7ab546c4daa2662a96b5c80806d04cb
SuperHong94/2020_1_
/파이썬공부/python example/5week/simpleset.py
692
3.578125
4
from functools import * def intersect(*ar): #함수인자이름앞에*은 가변인자리스트 (3장) return reduce(__intersectSC,ar) def __intersectSC(listX,listY): setList=[] for x in listX: if x in listY: setList.append(x) return setList def difference(*ar): setList=[] intersectSet=intersect(*ar) #여기 *은 듀플로받은것을 풀어 해친다. unionSet=union(*ar) for x in unionSet: if not x in intersectSet: setList.append(x) return setList def union(*ar): setList=[] for item in ar: for x in item: if not x in setList: setList.append(x) return setList
60c802a0dda1df93cae267073fb6f5d1a8780889
HughP/comp-think
/2017-2018/exams/python/second-partial-examination_ex_5_binary_search.py
1,278
3.90625
4
def binary_search(item, ordered_list, start, end): if start <= end: mid = ((end - start) // 2) + start mid_item = ordered_list[mid] if item == mid_item: return mid elif mid_item < item: return binary_search(item, ordered_list, mid + 1, end) else: return binary_search(item, ordered_list, start, mid - 1) if __name__ == "__main__": number_list = [0, 1, 6, 8, 11, 14, 16, 17, 18, 45] print("Input list:", number_list) print("Search for 0:", binary_search(0, number_list, 0, len(number_list) - 1)) print("Search for 1:", binary_search(1, number_list, 0, len(number_list) - 1)) print("Search for 7:", binary_search(7, number_list, 0, len(number_list) - 1)) print("Search for 45:", binary_search(45, number_list, 0, len(number_list) - 1)) book_list = ["American Gods", "Coraline", "Good Omens", "Neverwhere", "The Graveyard Book"] print("\nInput list:", book_list) print(binary_search("American Gods", book_list, 0, len(book_list) - 1)) print(binary_search("Good Omens", book_list, 0, len(book_list) - 1)) print(binary_search("The Sandman", book_list, 0, len(book_list) - 1)) print(binary_search("The Graveyard Book", book_list, 0, len(book_list) - 1))
486a75558ba5ef70d72e374111774c28bf65860d
ankur990/pythonlab
/ankur.py20.py
293
3.71875
4
st = st.split(" ") for i in range(0, len(st)): st[i] = "".join(st[i]) dupli = Counter(st) s = " ".join(dupli.keys()) print ("After removing the sentence is ::>",s) if __name__ == "__main__": st = input("Enter the sentence") remov_duplicates(st)
02bb96b73e239bd30977e7093f78b11f6998b79e
Ankitmandal1/Hactoberfest2021
/preOrder.py
598
3.671875
4
class TreeNode: def __init__(self,val): self.val = val self.left = None self.right = None def preorderTraversal(root): answer = [] preorderTraversalUtil(root, answer) return answer def preorderTraversalUtil(root, answer): if root is None: return answer.append(root.val) preorderTraversalUtil(root.left, answer) preorderTraversalUtil(root.right, answer) return root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) print(preorderTraversal(root))
30de8c01b85f269adfb81d1aa667e6e0938b208a
kcildo/exercicios_python
/exercicios_aula09_persistencia_de_dados_arquivo/metodo_readline.py
472
3.828125
4
# O Método readline() # lê somente uma linha # dados = open('teste.txt', 'r') # linha = dados.readline() # print(linha, end='') # dados.close() # lê a o texto todo nomeArquivo = input( 'Digite o nome do arquivo que deseja visualizar: ') # pede para o usuário entrar com o nome do arquivo a ser lido dados = open(nomeArquivo, 'r', encoding='utf-8') linha = dados.readline() while linha != '': print(linha, end='') linha = dados.readline() dados.close()
2ebe212d0b04d55cda54f9eeca765199f5bb966c
barry800414/NewsCrawler
/method/DepBased/WFMapping.py
1,512
3.5625
4
import json ''' This code implements the function for reading word-frequency mapping from files ''' WF_Folder = './' # load word-frequency mapping for each statement def loadWFDict(filename): with open(filename, 'r') as f: WFDict = json.load(f) # convert string to integer newDict = dict() for key, value in WFDict.items(): newDict[int(key)] = value return newDict def addToWFDict(wfTo, wfFrom): for key, value in wfFrom.items(): if key in wfTo: wfTo[key] += value else: wfTo[key] = value # deprecated # allowedType : the list of allowed POS-tagger types def mergeWFDict(allowedType): WFDict = dict() for type in allowedType: tmpDict = loadWFDict(WF_Folder + '%s_List.json' % (type)) addToWFDict(WFDict, tmpDict) return WFDict # filter the words in word-frequency dict, return a set of allowed words def filteredByThreshold(wf, threshold): words = set() fSum = sum(wf.values()) for w, f in wf.items(): if float(f)/fSum >= threshold: words.add(w) return words # get allowed words for each type of POS tagger, # return a dict (pos-tagger -> set of allowed words) # WFDictInTopic[P]: the word-frequency mapping of POS-tag P def getAllowedWords(WFDictInTopic, allowedPOSType, threshold): allowedWords = dict() for pos in allowedPOSType: allowedWords[pos] = filteredByThreshold(WFDictInTopic[pos], threshold) return allowedWords
54da56b836f6177fb1afdf4e8d9f8f65d87f54d7
kangkang59812/LeetCode-python
/231.2-的幂.py
885
3.578125
4
# # @lc app=leetcode.cn id=231 lang=python3 # # [231] 2的幂 # # https://leetcode-cn.com/problems/power-of-two/description/ # # algorithms # Easy (47.85%) # Likes: 176 # Dislikes: 0 # Total Accepted: 52.6K # Total Submissions: 109.9K # Testcase Example: '1' # # 给定一个整数,编写一个函数来判断它是否是 2 的幂次方。 # # 示例 1: # # 输入: 1 # 输出: true # 解释: 2^0 = 1 # # 示例 2: # # 输入: 16 # 输出: true # 解释: 2^4 = 16 # # 示例 3: # # 输入: 218 # 输出: false # # # @lc code=start class Solution: def isPowerOfTwo(self, n: int) -> bool: if n < 1: return False a = 2 i = 0 while True: a = 2**i if a == n: return True elif a > n: return False elif a < n: i += 1 # @lc code=end
a24863847403346d52b8545371042b96886bb558
mohitsh/python_work
/ProbSolv/binary_search2.py
531
3.796875
4
def binary_search(alist,item): first = 0 last = len(alist)-1 found = False while first <= last and not found: mid = (first+last)/2 if item == alist[mid]: found = True else: if item > alist[mid]: first = mid+1 elif item < alist[mid]: last = mid-1 return found, mid alist = [1,4,7,10,15,19,23,28,34,38,45,48,50,54,59] print binary_search(alist,7) print binary_search(alist,28) print binary_search(alist,48) print binary_search(alist,59) print binary_search(alist,100) print binary_search(alist,-10)
c6268e6ae2d51e15017d1a2f081993f155e18e27
JJader/python
/Lista/main.py
1,507
3.984375
4
from classes.celula import Cell from classes.lista import Lista import os def cabecario(): print("1 --> adicionar no final") print("2 --> adicionar no index") print("3 --> remover") print("4 --> pesquisar item") print("5 --> pesquisar posição") print("6 --> modificar") print("7 --> imprimir") print("8 --> sair") def main(): l1 = Lista() op = 0 while(op != 8): cabecario() try: op = int(input("Digite a opção desejada: ")) if op == 1: item = float(input("Digite o valor do item: ")) l1.append(item) if op == 2: item = float(input("Digite o valor do item: ")) index = int(input("Digite o valor do index: ")) l1.insert(index, item) if op == 3: item = float(input("Digite o valor do item: ")) l1.pop(item) if op == 4: item = float(input("Digite o valor do item: ")) print(l1.search(item)) if op == 5: index = int(input("Digite o valor do index: ")) print(l1[index]) if op == 6: item = float(input("Digite o valor do item: ")) index = int(input("Digite o valor do index: ")) l1[index] = item if op == 7: print(l1) except Exception as e: print(e) if __name__ == "__main__": main()
93794f6b08bd7f83a0176236a4fe89470f8a01e8
Andremarcucci98/Python_udemy_geek_university
/Capitulos/Secao_13/seek_cursors.py
1,596
4.53125
5
""" Seek e Cursors seek() -> É utilizada para movimentar o cursor pelo arquivo arquivo = open('texto.txt') print(arquivo.read()) # Movimentando o cursor pelo arquivo com a função seek() # seek() -> A função seek() é utilizada para movimentação do cursor pelo arquivo. Ela recebe um parâmetro arquivo.seek(0) print(arquivo.read()) # readline() -> Função que lê o arquivo linha a linha print(arquivo.readline()) # Imprimiu a primeira linha print(arquivo.readline()) # Imprimiu a segunda linha print(arquivo.readline()) # Imprimiu a terceira linha # readlines() linhas = arquivo.readlines() print(len(linhas)) # Obs.: Quando abrimos um arquivo com a função open() é criada uma conexao entre o arquivo no disco do computador e o nosso programa. Essa conexao é chamada de streaming. Ao finalizar os trabalhos com o arquivo devemos fechar essa conexão. Para isso utilizamos a função close() Passos para se trabalhar com um arquivo: 1 - Abrir o arquivo arquivo = open('texto.txt') 2 - Trabalhar o arquivo: print(arquivo.read()) print(arquivo.closed()) # False - Verifica se o arquivo está aberto ou fechado 3 - Fechar o arquivo: arquivo.close() print(arquivo.closed) # True - Verifica se o arquivo está aberto ou fechado print(arquivo.read()) # Obs.: Se tentarmos manipular o arquivo após seu fechamento, teremos um ValueError arquivo = open('texto.txt') # Com a função read() podemos limitar a quantidade de caracteres a serem lidos no arquivo print(arquivo.read(50)) Eu estou estudando na Geek University e estou apre """
98b15ef2f8a851640a3fc75a95925f83729ceb37
junyechen/PAT-Advanced-Level-Practice
/1023 Have Fun with Numbers.py
1,517
4.03125
4
""" Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, with no duplication. Double it we will obtain 246913578, which happens to be another 9-digit number consisting exactly the numbers from 1 to 9, only in a different permutation. Check to see the result if we double it again! Now you are suppose to check if there are more numbers with this property. That is, double a given number with k digits, you are to tell if the resulting number consists of only a permutation of the digits in the original number. Input Specification: Each input contains one test case. Each case contains one positive integer with no more than 20 digits. Output Specification: For each test case, first print in a line "Yes" if doubling the input number gives a number that consists of only a permutation of the digits in the original number, or "No" if not. Then in the next line, print the doubled number. Sample Input: 1234567899 Sample Output: Yes 2469135798 """ ############################## """ 本题用python做异常简单,因为不需要考虑数位、类型大小等问题 """ ############################## num = input() num_ = str(int(num)*2) if len(num) != len(num_): print("No") else: digit, digit_ = {}, {} for _ in range(10): digit[str(_)] = 0 digit_[str(_)] = 0 for _ in num: digit[_] += 1 for _ in num_: digit_[_] += 1 if digit_ == digit: print("Yes") else: print("No") print(num_)
ada3c504c621b94ed8acc5c19ff95329b1a719a8
zischuros/Introduction-To-Computer-Science-JPGITHUB1519
/Lesson 2 - Problem Set/Median/median.py
903
4.21875
4
# Define a procedure, median, that takes three # numbers as its inputs, and returns the median # of the three numbers. # Make sure your procedure has a return statement. def bigger(a,b): if a > b: return a else: return b def smaller(a,b): if a < b: return a else : return b def biggest(a,b,c): return bigger(a,bigger(b,c)) def smallest(a,b,c): return smaller(a,smaller(b,c)) def median(a,b,c): big = biggest(a,b,c) small = smallest(a,b,c) if (c == big and b == small) or (b == big and c == small) : return a if (c == big and a == small) or (a == big and c == small) : return b if (a == big and b == small) or (b == big and a == small) : return c print(median(1,2,3)) #>>> 2 print(median(9,3,6)) #>>> 6 print(median(7,8,7)) #>>> 7 print median(1,2,2)