blob_id
stringlengths
40
40
repo_name
stringlengths
6
108
path
stringlengths
3
244
length_bytes
int64
36
870k
score
float64
3.5
5.16
int_score
int64
4
5
text
stringlengths
36
870k
b83627edd6786755ea028b55670281982f22896d
egalli64/pythonesque
/cip/karel/ch04.py
1,298
3.734375
4
""" Karel the Robot - Learns Python Source: https://compedu.stanford.edu/karel-reader/docs/python/en/intro.html My notes: https://github.com/egalli64/pythonesque/cip/karel Chapter 3: Decomposition https://compedu.stanford.edu/karel-reader/docs/python/en/chapter4.html """ from stanfordkarel import * def main(): """Decomposition: short functions, focused on a single action, identified by a significative name""" move() fill_pothole() move() # Fills the pothole beneath Karel's current position by # placing a beeper on that corner. For this function to work # correctly, Karel must be facing east immediately above the # pothole. When execution is complete, Karel will have # returned to the same square and will again be facing east. def fill_pothole(): """ Precondition: Karel is on a pothole facing east Karel fills the pothole with a beeper Postcondition: Karel is on the filled pothole facing east """ turn_right() move() put_beeper() turn_around() move() turn_right() def turn_right(): turn_left() turn_left() turn_left() def turn_around(): turn_left() turn_left() if __name__ == '__main__': # A 5x4 world, Karel starts from [1,2], there's a pothole in 2 run_karel_program("cip_ch04")
a1869bcb396ba2682988b98d3b1aa0d57f2e4d37
Aryank47/PythonProgramming
/encapsulation.py
282
3.75
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 4 14:12:56 2019 @author: Aryan Kumar """ class student: def display(self,name=None): if len(name)<= 5: print('hello') else: print(name," hello") s=student() s.display('aryan')
d58522df78cb862ca60bc6c86bd6b865f1f8517f
hansrajdas/algorithms
/Level-3/letter_and_numbers.py
1,608
3.890625
4
#!/usr/bin/python # Date: 2020-11-27 # # Description: # Given an array filled with letters and numbers, find the longest subarray # with an equal number of letters and numbers. # # Approach: # Scan given array and create another delta array which has difference of # number of numbers seen and number of letters seen till a given index. # Then, we will scan delta array to find same difference at 2 indices which are # max indices apart. # # Complexity: # O(N) time and space def get_delta_subarray(s): delta = 0 delta = 0 delta_list = [] for x in s: if x.isdigit(): delta += 1 else: delta -= 1 delta_list.append(delta) return delta_list def get_longest_match(delta): delta_to_indices = {0: -1} res = { 'start': 0, 'end': 0 } for i in range(len(delta)): if delta[i] not in delta_to_indices: delta_to_indices[delta[i]] = i else: start = delta_to_indices[delta[i]] longest = res['end'] - res['start'] if i - start > longest: res['start'] = start res['end'] = i return res def get_subarray(string, indices): s = [] for i in range(indices['start'] + 1, indices['end'] + 1): s.append(string[i]) return s def max_subarray_same_letters_and_nums(s): delta = get_delta_subarray(s) max_indices = get_longest_match(delta) return get_subarray(s, max_indices) print(max_subarray_same_letters_and_nums('abc112345d')) print(max_subarray_same_letters_and_nums('aaaa11a11aa1aa1aaaaa'))
104fc9f285a0bd2b94fd3143fe445dff0b690a9e
pooja-pichad/more_excersise
/q8.duplicate.py
907
3.8125
4
# Socho aapke paas do lists hain. Ab aapko nayi list banani hai jisme dono lists ke elements # hone chaiye. Lekin yeh dhyan mein rakhna hai ki dono lists ke saare elements sirf ek-ek # baar hi hone chaiye. Agar humare paas yeh do lists hain: list1 = [1, 5, 10, 12, 16, 20] list2 = [1, 2, 10, 13, 16] # Toh humari nayi list yeh hogi: # # new_list = [1, 2, 5, 10, 12, 13, 16, 20] # Yahan dekho ki dono lists ke items ek ek baar aa rahe hain. * Jaise dono lists mein # 1 aa raha tha, lekin nayi list mein ek hi baar aa raha hai. # Aise hi 10 aur 16 bhi dono list mein aa raha tha, lekin nayi list mein ek hi baar hai # Aur 5, 2, 12, 13 aur 20 mein se kuch pehli list mein the aur kuch dusri mein, lekin i=0 a=[] while i<len(list1): b=list1[i] if b not in list2: a.append(b) i=i+1 j=0 while j<len(list2): c=list2[j] a.append(c) j=j+1 print(a) # i=i+1
f773087fe699bcec83fe2310160534da45ec1a22
limciana/cs150-project
/iowithparse.py
8,041
3.5
4
# list of tokens # storing and printing of variables, integer muna # specify sa pagrun ng python yung filename # not \n sensitive # string variable value has "" # CONSIDER ARRAY IN TYPE CHECKING # KUNG MAY TIME: LINE NUMBER SA PARSING # TYPE CASTING (kung may time) # float and int can be stored vice versa # PAALALA # need anong line number ang mali # wag makalimutan lagyan ng error # always try except import sys filename=sys.argv[-1] file=open(filename, "r") import ply.lex as lex #list of reserved words reserved={ 'INTEGER':'INTEGER', 'FLOAT':'FLOAT', 'STRING':'STRING', 'VARIABLES':'VARIABLES', 'PAKITA':'PAKITA', 'BASA':'BASA', 'IARRAY':'IARRAY', 'FARRAY':'FARRAY', 'SARRAY':'SARRAY' } #list of token names tokens=['NAME', 'LITSTRING', 'LITINTEGER', 'LITFLOAT', 'EQUAL', 'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'POWER', 'MODULO']+list(reserved.values()) literals=['{','}','(',')'] #regular expression rules def t_LITSTRING(t): r'\".*\"' str=t.value new_str="" escaped=0 for i in range(0, len(str)): c=str[i] if escaped: #print("you there") if c=="n": c="\n" elif c=="t": c="\t" elif c=="\\": #print("you there1") c="\\" escaped=0 elif c=="\\": #print("ESCAPED") escaped=1 continue new_str+=c t.value=new_str return t def t_LITFLOAT(t): r'\d+[.]\d+' try: t.value = float(t.value) except ValueError: print("Value too large for float.") print("Error at line ", end="") print(t.lineno) sys.exit() t.value = 0.0 return t def t_LITINTEGER(t): r'\d+' try: t.value = int(t.value) except ValueError: print("Value to large for integer.") print("Error at line ", end="") print(t.lineno) sys.exit() t.value = 0 return t def t_ID(t): r'[A-Z]+' t.type=reserved.get(t.value, 'ID') # default value ay ID if hindi siya nasa reserved if t.type =='ID': print("Illegal character '%s' at line " % t.value, end="") print(t.lineno) sys.exit() else: return t #token names rules t_NAME=r'[a-z][a-z0-9_]*' #put EQUAL EQUAL HERE t_PLUS = r'\+' t_MINUS = r'-' t_TIMES = r'\*' t_DIVIDE = r'/' t_POWER = r'\^' t_MODULO = r'\%' t_EQUAL=r'=' #ISAMA SI EQUAL SA TOKEN LIST def t_lbrace(t): r'\{' t.type='{' return t def t_rbrace(t): r'\}' t.type='}' return t def t_lparen(t): r'\(' t.type='(' return t; def t_rparen(t): r'\)' t.type=')' return t t_ignore=' \t' #line number count def t_newline(t): r'\n+' t.lexer.lineno+=len(t.value) def t_error(t): print("Illegal character '%s'" % t.value[0]) print("Error at line ", end="") print(t.lineno) sys.exit() #t.lexer.skip(1) lexer=lex.lex() import ply.yacc as yacc precedence = ( ('left','PLUS','MINUS'), ('left','TIMES','DIVIDE', 'MODULO'), ('right','POWER'), ('right','UMINUS'), ) #list of variable names variable_names = {} #declaring of variables then rest of program def p_program_start(t): '''program : init body | body | init ''' #pwedeng walang VARIABLES def p_init_variable(t): '''init : VARIABLES '{' vardecnames '}' ''' #dapat may laman #initializing 0 as value of variables #when adding to array, type matters. For now, empty array def p_vardecnames_names(t): '''vardecnames : INTEGER NAME vardecnames | FLOAT NAME vardecnames | STRING NAME vardecnames | IARRAY NAME vardecnames | FARRAY NAME vardecnames | SARRAY NAME vardecnames | INTEGER NAME | FLOAT NAME | STRING NAME | IARRAY NAME | FARRAY NAME | SARRAY NAME ''' if t[1]=='INTEGER': variable_names[t[2]]=[t[1], 0] elif t[1]=='FLOAT': variable_names[t[2]]=[t[1], 0.0] elif t[1]=='STRING': variable_names[t[2]]=[t[1], ""] elif t[1]=='IARRAY' or t[1]=='FARRAY' or t[1]=='SARRAY': variable_names[t[2]]=[t[1], []] #for each statement in rest of program def p_body_state(t): '''body : body statement | statement ''' def p_statement_print(t): '''statement : PAKITA '(' NAME ')' | PAKITA '(' LITSTRING ')' ''' #print(t[3]) if t[3][0]=='\"' and t[3][len(t[3])-1] =='\"': #print("hi") print(t[3][1:len(t[3])-1], end="") else: # try except try: temp=variable_names[t[3]] except LookupError: print("Variable name '%s' not found." % t[3]) sys.exit() if variable_names[t[3]][0] == 'STRING': #print("hello1") print(variable_names[t[3]][1][1:len(variable_names[t[3]][1])-1], end="") else: print(variable_names[t[3]][1], end="") def p_statement_read(t): #type checking sa basa dapat evaluated muna kung int float string same type '''statement : BASA '(' NAME ')' ''' try: temp=variable_names[t[3]] except Exception: print("Undefined name '%s'" % t[1]) sys.exit() if variable_names[t[3]][0]=='INTEGER': try: temp=input() temp=float(temp) temp=int(temp) except Exception: print("Expected type INTEGER for '%s'." % t[3]) #dagdag line sys.exit() #print(type(t[3])) variable_names[t[3]][1] = temp elif variable_names[t[3]][0]=='FLOAT': try: temp=float(input()) except Exception: print("Expected type FLOAT for '%s'." % t[3]) sys.exit() variable_names[t[3]][1] = temp elif variable_names[t[3]][0]=='STRING': temp=input() if temp[0]!='\"' and temp[len(temp)-1]!='\"': print("Input string should be enclosed in \"\".") sys.exit() else: variable_names[t[3]][1] = temp else: print("Parameter '%s' is not valid for BASA." % t[3]) #variable_names[t[3]][1]=input() def p_statement_assignment(t): #remember to check if actual type and expected type are compatible #assignment of literal and variables '''statement : NAME EQUAL expression''' #to be done in integer operations #if variablenames[t[1]][0] == try: temp=variable_names[t[1]] except Exception: print("Undefined name '%s'" % t[1]) sys.exit() if variable_names[t[1]][0]=='INTEGER': #print(type(t[3])) if type(t[3]).__name__!='int' and type(t[3]).__name__!='float': print("Expected type INTEGER for '%s'." % t[1]) #dagdag line sys.exit() else: variable_names[t[1]][1] = int(t[3]) elif variable_names[t[1]][0]=='FLOAT': #print(type(t[3]).__name__) if type(t[3]).__name__!='int' and type(t[3]).__name__!='float': #print(type(t[3]).__name__) print("Expected type FLOAT for '%s'." % t[1]) sys.exit() else: if type(t[3]).__name__=='int': variable_names[t[1]][1]=float(t[3]) else: variable_names[t[1]][1] = t[3] elif variable_names[t[1]][0]=='STRING': if type(t[3]).__name__!='str': print("Expected type STRING for '%s'." % t[1]) sys.exit() else: variable_names[t[1]][1] = t[3] #variable_names[t[1]][1] = t[3] def p_expression_binop(t): '''expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression | expression POWER expression | expression MODULO expression ''' if type(t[1]).__name__ == 'str' or type(t[1]).__name__== 'list': print("Invalid data types in '%s'." % t[1]) sys.exit() elif type(t[3]).__name__=='str' or type(t[3]).__name__=='list': print("Invalid data types in '%s'." % t[3]) sys.exit() else: if t[2] == '+': t[0] = t[1] + t[3] elif t[2] == '-': t[0] = t[1] - t[3] elif t[2] == '*': t[0] = t[1] * t[3] elif t[2] == '/': t[0] = t[1] / t[3] elif t[2] == '^': t[0] = t[1] ** t[3] elif t[2] == '%': t[0] = t[1] % t[3] def p_expression_uminus(t): 'expression : MINUS expression %prec UMINUS' t[0] = -t[2] def p_expression_group(t): '''expression : '(' expression ')' ''' t[0] = t[2] def p_expression_types(t): '''expression : LITSTRING | LITINTEGER | LITFLOAT''' t[0] = t[1] def p_expression_var(t): '''expression : NAME''' try: t[0] = variable_names[t[1]][1] except LookupError: print("Undefined name '%s'" % t[1]) sys.exit() def p_error(t): print("Syntax error at line '%s'" % t.value) sys.exit() parser=yacc.yacc() while True: line=file.read() if not line: file.close() break else: lexer.input(line) parser.parse(line)
773c12943c7b0e20132e4bfbd9fe781ec95938b5
vivianLL/LeetCode
/10_RegularExpressionMatching.py
3,522
3.984375
4
''' 10. Regular Expression Matching https://leetcode.com/problems/regular-expression-matching/ Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). Note: s could be empty and contains only lowercase letters a-z. p could be empty and contains only lowercase letters a-z, and characters like . or *. ''' import re class Solution: def isMatch(self, s: str, p: str) -> bool: # 正则匹配 return re.match('^' + p + '$', s) != None # ^匹配字符串的开头 $匹配字符串的末尾 +匹配1个或多个的表达式。 # # 递归写法 # # s已被匹配且p已耗完 # if not s and not p: # not比len()==0和s==[]或s==""更简便 # return True # # p已耗完但s未被完全匹配 # if len(s) > 0 and len(p) == 0: # 或if not p # return False # # # 如果模式第二个字符是* # if len(p) > 1 and p[1] == '*': # if len(s) > 0 and (s[0] == p[0] or p[0] == '.'): # # 如果第一个字符匹配,三种可能1、模式后移两位;2、字符串移1位 # return self.isMatch(s, p[2:]) or self.isMatch(s[1:], p) # else: # # 如果第一个字符不匹配,模式往后移2位,相当于忽略x* # return self.isMatch(s, p[2:]) # # 如果模式第二个字符不是* # if len(s) > 0 and (s[0] == p[0] or p[0] == '.'): # return self.isMatch(s[1:], p[1:]) # else: # return False # # 递归简化写法 # if p == "": # return s == "" # if len(p) > 1 and p[1] == "*": # return self.isMatch(s, p[2:]) or (s and (s[0] == p[0] or p[0] == '.') and self.isMatch(s[1:], p)) # else: # return s and (s[0] == p[0] or p[0] == '.') and self.isMatch(s[1:], p[1:]) # 动态规划 dp = [[False for j in range(len(p) + 1)] for i in range(len(s) + 1)] # 初始化二维表dp print(dp) dp[0][0] = True # s 和 p 都为空时 # 若 s 为空时 for j in range(1, len(p) + 1): # dp[0][j]= (p[j-1]=="*")and(j>=2)and(dp[0][j-2]) # 等同于下列语句 if p[j - 1] == '*': if j >= 2: dp[0][j] = dp[0][j - 2] print(dp) for i in range(1, len(s) + 1): for j in range(1, len(p) + 1): # j-1才为正常字符串中的索引 # p当前位置为"*"时,(代表空串--dp[i][j-2]、一个或者多个前一个字符--( dp[i-1][j] and (p[j-2]==s[i-1] or p[j-2]=='.')) if p[j - 1] == '*': dp[i][j] = dp[i][j - 2] or ( dp[i - 1][j] and (p[j - 2] == s[i - 1] or p[j - 2] == '.')) # dp[i][j-1] or # p当前位置为"."时或者与s相同时,传递dp[i-1][j-1]的真值 else: dp[i][j] = (p[j - 1] == '.' or p[j - 1] == s[i - 1]) and dp[i - 1][j - 1] return dp[len(s)][len(p)] sol = Solution() ans = sol.isMatch("aa","a*") print(ans) ans = sol.isMatch("aa",".*") print(ans) # 递归时注意判断s和p的长度,防止越界
ff19c4c667a1af7f347f5404e31e747af77222bc
bdebelle/lpfs
/controlstructure/whileloopdemo.py
454
3.8125
4
""" execute statements repeatedly conditions are used to stop the execution of loops iterable items are strings, lists, tuples, dictionary """ # while x < 10: # print("value of x is " + str(x)) # x = x + 1 # print("one more line") l =[] num =0 while num < 10: l.append(num) print("Value if x is " + str(num)) num += 1 print(l) import time y = 10 while y > 0: y = y-1 print("%d" % (y)) time.sleep(1) print("poof")
500a82a7a65ec692131a56c91e05bf75d5e5dfc6
LaxmanRaikar/PythonPrograms
/bridge/quadratic.py
411
4.0625
4
""" this program is used to find the quadratic roots author:Laxman Raikar since:8 JAN,2019 """ from tech import functional try: a = int(input("Enter the value of a ")) b = int(input("Enter the value of b ")) c = int(input("Enter the value of c ")) functional.quadraticFunctions(a,b,c) # calls the method and pass the value except ValueError: print("Input only accepts decimal numbers")
6a6b0972cbd1dcf62ca827482e55d07e4af017a0
HIT-jixiyang/offer
/banlance_tree.py
1,524
3.53125
4
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def IsBalanced_Solution(self, pRoot): # write code here self.deep = {} self.getDeep(pRoot) return self.isBan(pRoot) def isBan(self, root): if not root: return True if not root.left and root.right: if self.deep[hash(root.right)]>=2: return False return True if not root.right and root.left: if self.deep[hash(root.left)]>=2: return False return True if not root.right and not root.left: return True if root.left and root.right: A=self.isBan(root.left) B=self.isBan(root.right) c=abs(self.deep[hash(root.left)] - self.deep[hash(root.right)]) <= 1 return A and B and c def getDeep(self, root): if not root: self.deep[hash(root)] = 0 elif not root.left and not root.left: self.deep[hash(root)] = 1 else: self.getDeep(root.left) self.getDeep(root.right) self.deep[hash(root)] = max(self.deep[hash(root.left)], self.deep[hash(root.right)]) + 1 if __name__ == '__main__': t1=TreeNode(1) t2=TreeNode(2) t3=TreeNode(3) t4=TreeNode(4) t1.left=t2 t2.left=t3 t1.right=t4 S=Solution() print(S.IsBalanced_Solution(t1))
bccfabbd00eeb884107f1bd1ef3fa8705f272865
asliboyar/freshman_codes
/assignment_4.py
1,883
4.5
4
''' Write a python program with appropriate comments that accepts an input text file from user and performs the following operations: - Reads the file and finds the longest word in the file and writes the length of the longest word, longest word, and its line number in the source file to a result file (all the results should be in a single line separated by comma). Also, print the results on the console - Writes another file that contains all lines starting and including the line that contains longest word in the source file till the end of file. - If the input file is not found then the program should print appropriate error message and keep prompting the user until a valid file is entered. Please use exception handling to accomplish this. ''' #getting input for file def input_file(): while True: input_file = input("File name:") try: with open(input_file, 'r') as x: return x.readlines() except EnvironmentError: print("Wrong name, try again!") #length of the longest word, longest word, its line number def result_file(longestword,wordline): x = open("result_file.txt", 'w') result = str(len(longestword)) + ", " + longestword + ", " + str(wordline) x.write(result) x.close #longest word and the rest of the file def result2_file(inputfile,wordline): y = open("result2_file.txt", 'w') for i in range(wordline,len(inputfile)): y.write(inputfile[i]) y.close def main(): inputfile = input_file() wordline = 0 longestword = "" cnt = 1 for i in inputfile: longestword_of_line = sorted(i.split(), key = len)[-1] if len(longestword_of_line) > len(longestword): longestword = longestword_of_line wordline = cnt cnt += 1 print(str(len(longestword)) + ", " + longestword + ", " + str(wordline)) result_file(longestword,wordline) result2_file(inputfile,wordline) main()
f714f1cb2aa6b511990cfeeffe14888c06b3d912
aamlj/GitPython
/reverseOrder_MikeJones.py
277
4.09375
4
#a = input("Enter fifteen numbers in [ ] seperated by commas to be reversed: ") #a.reverse() #print ("Your numbers reversed are", a) #author: Mike Jones # This program will return a list of numbers in reverse order using the append command # and the reverse function
cd120a7c977322d6bdda4b825c2759a64156690a
andrewlee21/PythonFundamentals
/Weeks 1-2/cc_nestedif.py
243
4.09375
4
priceIsRight = 15 if priceIsRight<5: print("Price is too low!") elif priceIsRight>=5 and priceIsRight<=9: print("Price is almost there!") elif priceIsRight==10: print("Price is exactly that!") else: print("Price is too high!")
34a873caa3c40e219985d3c40ed7fef17c7a82e7
juanfariastk/FunnyAlgorithms
/Factorial/Factorial.py
484
4.28125
4
def factorial(n): fact = 1 for i in range(1, n+1): fact *= i return fact def factorial_recursion(n): if (n == 0): return 1 else: return n * factorial_recursion(n-1) number = int(input("Enter a number: ")) if num < 0: print("Sorry, Factorial does not exist for negative numbers") else: print("Factorial using Recursive Approach: ", factorial_recursion(number)) print("Factorial using Iterative Approach: ", factorial(number))
3df75daafd0477df1c0cddd7ee2f2bc1ff4d7416
ronaldvilchez98/Santotomas_estructuras_programacion
/python_3/guia4/Ejercicio_7.py
1,038
4.0625
4
''' :::::::::::::::::::::::::::::::::::::::::::::: :: @github: adrian273 :: :: @email: [email protected] :: :::::::::::::::::::::::::::::::::::::::::::::: 7@ Lea las horas trabajadas de un trabajador, valor hora, número de cargas y determine,Si el número de cargas es mayor o igual a 3 asigne un bono de un 10% sobre el salario, Si el número de cargas es 2, asigne un bono del 5% y si tiene una carga entonces asigne un 3% de bono. Muestre el salario del trabajador. ''' time_work = int(input('Ingrese horas de trabajo \n')) value_time = int(input('Ingrese valor de hora \n')) number_cargo = int(input('Ingrese numero de carga \n')) salary = time_work * value_time if number_cargo >= 3: salary_bono = salary * 1.1 print('El salario final es $' + str(int(salary_bono))) elif number_cargo == 2: salary_bono = salary * 1.05 print('El salario final es $' + str(int(salary_bono))) else: salary_bono = salary * 1.03 print('El salario final es $' + str(int(salary_bono)))
d6c14b925991cd8fc80cc012a12f8708b867c7d6
fadhiladiahap/Fadhila-Diah-Ayu-P._I0320038_Andhika_Tugas7
/I0320038_Soal1_Tugas7.py
323
3.546875
4
# Metode center Judul = "Survei Pelanggan Rumah Makan Selera Kita" a = Judul.center (50,'=') print (a) # Metode endswith str = "Apakah makanannya higenis?" print("Apakah makannnya higenis?") print (str.endswith("higenis?")) #Metode replace dan endswith str = "Apakah makanannya enak?" b = str.replace ("enak","sedap") print(b) print(str.endswith("enak?"))
9ee1b825d49e9187a2afce2897f03280abca332d
Mepacor/AdventOfCode
/5/main.py
1,113
3.765625
4
# Reading data and defining general functions boardingPasses = open("boarding-seats.txt", 'r').read().splitlines() def binToDec(string): result = 0 for index, char in enumerate(string): result += toBit(char) * (2 ** (len(string)-index-1)) return result def toBit(char): if(char == "B" or char == "R"): return 1 elif(char == "F" or char == "L"): return 0 # Part 1: find the highest seat ID maxSeatId = -1 for boardingPass in boardingPasses: seatId = binToDec(boardingPass) if(maxSeatId < seatId): maxSeatId = seatId print("Day 5 - Part one: highest seat id is", maxSeatId) # Part 2: finding our seat ID seatIds = [] for boardingPass in boardingPasses: seatIds.append(binToDec(boardingPass)) seatIds = sorted(seatIds) ourSeatId = -1 index = 0 while(ourSeatId < 0 and index < len(seatIds)-1): index += 1 seatId = seatIds[index] previousSeatId = seatIds[index-1] nextSeatId = seatIds[index+1] if( (previousSeatId + nextSeatId) % seatId == 1): ourSeatId = seatId + 1 print("Day 5 - Part two: our seat id is", ourSeatId)
2c3ab1c730c64088ec1d6f768d5634d556417ff7
Tuchev/Python-Fundamentals---january---2021
/10.Exams/03. Programming Fundamentals Final Exam Retake/03. Need for Speed III.py
1,761
3.875
4
class Car: def __init__(self, car_name: str, mileage: int, fuel: int): self.car_name = car_name self.mileage = mileage self.fuel = fuel n = int(input()) garage = [] for _ in range(n): car_name, mileage, fuel = input().split("|") car = Car(car_name, int(mileage), int(fuel)) garage.append(car) command = input() while not command == "Stop": data = command.split(" : ") action, car_name = data[0], data[1] car = [auto for auto in garage if auto.car_name == car_name][0] if action == "Drive": distance, used_fuel = int(data[2]), int(data[3]) if used_fuel <= car.fuel: car.fuel -= used_fuel car.mileage += distance print(f"{car_name} driven for {distance} kilometers. {used_fuel} liters of fuel consumed.") if car.mileage > 99999: print(f"Time to sell the {car_name}!") garage.remove(car) else: print(f"Not enough fuel to make that ride") elif action == "Refuel": new_fuel = int(data[2]) if new_fuel + car.fuel > 75: new_fuel = 75 - car.fuel car.fuel += new_fuel print(f"{car_name} refueled with {new_fuel} liters") elif action == "Revert": kilometers = int(data[2]) car.mileage -= kilometers if car.mileage < 10000: car.mileage = 10000 else: print(f"{car_name} mileage decreased by {kilometers} kilometers") command = input() sorted_garage = sorted(garage, key=lambda car: (-car.mileage, car.car_name)) for auto in sorted_garage: print(f"{auto.car_name} -> Mileage: {auto.mileage} kms, Fuel in the tank: {auto.fuel} lt.")
0cfc5f52a1b0bb0b35a34b5d5660f4b92ac02734
bruno-victor32/Curso-de-Python---Mundo-1-Fundamentos
/ex030.py
164
3.921875
4
n1 = int(input('Digite na tela um número inteiro: ')) res = n1 % 2 if res == 1: print('O número digitado e IMPAR') else: print('O número digitado e PAR')
0296bf48105d04f51407e54d7c5102551848ec91
jchigne/T09_ChigneGarrampie
/ChigneGarrampie/funciones24.py
570
3.640625
4
# Ejercicio 23 import os import libreria # Calcular el area lateral de una piramide # Declaracion de datos #imput pi=int(os.sys.argv[1]) radio=int(os.sys.argv[2]) generatris=int(os.sys.argv[3]) piramide=libreria.piramide(pi,radio,generatris) if (piramide>=200): # Si la piramide supera los 200 print("La piramide es alta") else: # Si la piramide no supera los 200 print("La piramide es baja") #fin_if #output print("El area lateral de la piramide es:",piramide)
0c64ae29817587b9073ac98b4ce98cc78119c062
Malak-Ghanom/Python
/Class_Assignment/CA04/q4.py
400
4.0625
4
"""Given a list of numbers iterate over it and print numbers which are divisible by 5. If you find number greater than 150 stop the exit iteration.""" my_list = [20,13,15,80,99,111,116,120,170] print(f"The numbers that are divisible by (5) are: ", end=" ") for i in range(0,len(my_list)-1): if my_list[i]> 150: break elif my_list[i] % 5 == 0: print(my_list[i], end=" ")
0db6403ffa26562178f64642c73198a1bcff593f
Nikdwal/YetAnotherScrambleGenerator
/yasg/scramble.py
470
3.984375
4
import kociemba # the inverse of a single move def inverse_move(move : str): if len(move) <= 1: return move + "\'" if move[-1] == "'": return move[0] return move # the inverse of an algorithm def inverse_alg(alg : str): return " ".join(reversed([inverse_move(move) for move in alg.split(" ")])) # generate an algorithm for the given random state def generate_state(random_state): return inverse_alg(kociemba.solve(random_state))
26fd68aa9be0e213353292bf55516fdf18737e47
romponciano/py_useful-scripts
/replace-image-pixels.py
539
4.125
4
# Rmulo Ponciano # 03 Nov 2018 # This script replace all the pixels of a defined color, in an image, for another defined color. E.g. If you want to replace all red pixels with white pixels. from PIL import Image imgPathWithFormat = '' rgb = (0, 0, 0) finalColor = (255, 255, 255) imgOutputPathWithFormat = '' im = Image.open(imgPathWithFormat) pixels = list(im.getdata()) idx = 0 for i in pixels: if i == rgb: pixels[idx] = finalColor idx = idx + 1 im2 = Image.new(im.mode, im.size) im2.putdata(pixels) im2.save(imgOutputPathWithFormat)
4412d560d7b31d2b5aa3551953a543226be1a390
Damoy/AlgoTraining
/AlgoExpert/src2/python/RemoveKthNodeFromEnd.py
1,205
3.859375
4
class LinkedList: def __init__(self, value): self.value = value self.next = None def getNodesInArray(self): nodes = [] current = self while current is not None: nodes.append(current.value) current = current.next return nodes def removeKthNodeFromEnd(head, k): left = head right = head cpt = 0 while cpt != k: right = right.next cpt += 1 if right is None: head.value = head.next.value head.next = head.next.next else: while right is not None and right.next is not None: left = left.next right = right.next left.next = left.next.next l = LinkedList(0) l.next = LinkedList(1) l.next.next = LinkedList(2) l.next.next.next = LinkedList(3) l.next.next.next.next = LinkedList(4) l.next.next.next.next.next = LinkedList(5) l.next.next.next.next.next.next = LinkedList(6) l.next.next.next.next.next.next.next = LinkedList(7) l.next.next.next.next.next.next.next.next = LinkedList(8) l.next.next.next.next.next.next.next.next.next = LinkedList(9) print(l.getNodesInArray()) removeKthNodeFromEnd(l, 5) print(l.getNodesInArray())
93cdf9cc7a1e1dc5cd3acb9ba1e3c403fc2748cf
vitalizzare/NumFOCUS_Telethon_by_James_Powell
/code_snippets/Z_zip.py
1,260
3.640625
4
''' From the @NumFOCUS telethon title: Z for zip author: @dontusethiscode date: December 19, 2020 python version: >= 3.8 video: https://youtu.be/gzbmLeaM8gs?t=15648 edited by: @vitalizzare date: January 10, 2021 ''' xs = [1, 2, 3, 4, 5, 6, 7] print(f'{xs = }') for x, y, z in zip(xs[0:], xs[1:], xs[2:]): print(f'{x, y, z = }') from itertools import islice, tee nwise = lambda g, n=2: zip(*(islice(g, idx, None) for idx, g in enumerate(tee(g, n)))) for x, y, z in nwise('abcde', 3): print(f'{x, y, z = }') from itertools import repeat, chain first = lambda g, n=1: zip(chain(repeat(True, n), repeat(False)), g) for is_first, x in first('abcde', 3): print(f'{is_first, x = }') from itertools import zip_longest nwise_longest = lambda g, n=2, fv=None: zip_longest( *(islice(g, idx, None) for idx, g in enumerate(tee(g, n))), fillvalue=fv) last = lambda g, n=1, s=object(): ((y[-1] is s, x) for x, *y in nwise_longest(g, n+1, s)) for is_last, x in last('abcde', 2): print(f'{is_last, x = }') for is_first, (is_last, curr) in first(last('abcd')): if is_first: print('first element is', curr) elif is_last: print('last element is', curr) else: print('...', curr)
4112228fae4c271fb32c4aaccbc858e21625bdef
machinemessiah/python-sample-neural-networks
/3L3D1SizeNetwork.py
12,040
3.5625
4
import sys #print (sys.version) #sys.exit() import numpy as np def pprint(*arg): for a in arg: print(a) return def prnt(*arg): for a in arg: print(a) return # sigmoid function # this is used to output a probability value between 0 and 1 from any value # we use a sigmoid function as a default model def nonlin(x,deriv=False): # do we want the derivative of the value on the sigmoid curve? # ie. the straightline tangent at the point x on the sigmoid curve if(deriv==True): return x*(1-x) # this is equal to: 1/(1+(1/e^x)) return 1/(1+np.exp(-x)) # input dataset # 4 samples, 3 input nodes for each # this is arranged in the x direction (4 rows, 3 columnns) inputData = np.array([ [[0,0,1],[1,1,1],[0,1,0]], [[0,1,0],[0,1,0],[1,1,1]], [[1,1,1],[0,1,1],[1,1,1]], [[0,0,0],[1,1,1],[0,1,1]] ]) # Output dataset. # This is the desired output dataset. # This is arranged in the x direction (4 rows, 1 column). outputData = np.array([ [[0,1,1]], [[0,1,0]], [[1,1,1]], [[0,0,1]] ]) prnt("\noutputData",outputData.shape,outputData,"\ninputData",inputData.shape,inputData) # How many training steps training_steps = 1 # Seed random numbers to make calculation deterministic. # Seeding means we will get the same "random" values each time we run this script, # this allows us to see how any changes to our code effect the results. np.random.seed(1); # Initialize weights randomly with mean average of 0. # np.random.random_sample((3,1)) returns a 3 by 1 array of samples between 0 and 1 # entire expression returns a 3 by 1 array of samples between -1 and 1 # (hence "mean average of 0" above). # # This is our first "synapse", it is the mapping of the input layer to the first "hidden" layer. # It is a matrix of dimension (3,4) because we have 3 inputs and 4 outputs; in other words # in order to connect each node in the input layer (size 3) with each node in the # second "hidden" layer (size 4), we require a matrix of dimensionality (3,4) # # It is best practice to initialize weights randomly with a mean average of 0. # # This is essentially the "neural network", all the "learning" (or modification of weights) # happens within these two matricies since the input and output layers are transitory. synapse0i = 2 * np.random.random_sample((3,4)) - 1; synapse0j = 2 * np.random.random_sample((3,4)) - 1; synapse0k = 2 * np.random.random_sample((3,4)) - 1; pprint("\nsynapse0i",synapse0i.shape,synapse0i) #pprint("\n\nsynapse0j\n",synapse0j.shape,"\n",synapse0j) #pprint("\n\nsynapse0k\n",synapse0k.shape,"\n",synapse0k) # This is our second synapse, it is the mapping of the first "hidden" layer to the # second "hidden" layer. # It is a matrix of dimension (4,1) because we have 4 inputs from the first hidden layer # and 1 output. synapse1i = 2 * np.random.random_sample((4,3)) - 1; synapse1j = 2 * np.random.random_sample((4,3)) - 1; synapse1k = 2 * np.random.random_sample((4,3)) - 1; pprint("\nsynapse1i",synapse1i.shape,synapse1i) #pprint("\n\nsynapse1j\n",synapse1j.shape,"\n",synapse1j) #pprint("\n\nsynapse1k\n",synapse1k.shape,"\n",synapse1k) #print("\n\nsynapse0\n",synapse0.shape,"\n",synapse0,"\n\nsynapse1\n",synapse1.shape,"\n",synapse1) # Here is where we "teach" our neural network. # We loop through the training code 10000 times for j in range(training_steps): # Forward propagation # Even though our inputData contains 4 training examples (rows), we treat them as a single # training example, this is called "full batch" training. # We can use any number of training examples using this method. layer0 = inputData # This is the prediction step. # Here we let the neural network try to predict the output given the input. # # First we multiply layer0 (our input data) by our synapse (using dot product) # then pass the output through our sigmoid function. # The dimensionalities are (4,3) for layer0 and (3,1) for the synapse, thus our output matrix # is of dimensionality (4,1) since we must have the number of rows in the first matrix (4) # and the number of columns in the second matrix (1). # # Since we gave 4 training examples, we end up with 4 guesses for the correct answer; # each of these guesses is the neural network's guess for a given input. # The number of guesses (and dimensionality of the output matrix) will always match the number # of training examples we provide (any number will work). # # (The dot product is a scalar value which is the magnitude of each vector multipled together # and then by the cosine of the angle between them; this is the same as # [given 2 vectors A and B] Ax*Bx + Ay*By). layer0i = np.empty((0,3)) for l0i_iter in range(0,4): layer0i = np.append(layer0i, [layer0[l0i_iter][0]], axis=0) #print("\n",layer0i,"\n",layer0[l0i_iter][0]) pprint("\nlayer0i",layer0i.shape,layer0i) layer1i = nonlin(np.dot(layer0i, synapse0i)) layer0j = np.empty((0,3)) for l0j_iter in range(0,4): layer0j = np.append(layer0j, [layer0[l0j_iter][1]], axis=0) #print("\n",layer0i,"\n",layer0[l0i_iter][0]) #pprint("\n\nlayer0j\n",layer0j.shape,"\n",layer0j) layer1j = nonlin(np.dot(layer0j, synapse0j)) layer0k = np.empty((0,3)) for l0k_iter in range(0,4): layer0k = np.append(layer0k, [layer0[l0k_iter][2]], axis=0) #print("\n",layer0i,"\n",layer0[l0i_iter][0]) #pprint("\n\nlayer0k\n",layer0k.shape,"\n",layer0k) layer1k = nonlin(np.dot(layer0k, synapse0k)) pprint("\nlayer1i",layer1i.shape,layer1i) #pprint("\n\nlayer1j\n",layer1j.shape,"\n",layer1j) #pprint("\n\nlayer1k\n",layer1k.shape,"\n",layer1k) '''layer1 = np.array([layer1i,layer1j,layer1k]) pprint("\n\nlayer1\n",layer1.shape,"\n",layer1) pprint("\n\nlayer1.T\n",layer1.T.shape,"\n",layer1.T)''' # all sublayers are (4,3) layer2i = nonlin(np.dot(layer1i,synapse1i)).reshape(4,1,3) pprint("\nlayer2i",layer2i.shape,layer2i) layer2j = nonlin(np.dot(layer1j,synapse1j)).reshape(4,1,3) #pprint("\n\nlayer2j\n",layer2j.shape,"\n",layer2j) layer2k = nonlin(np.dot(layer1k,synapse1k)).reshape(4,1,3) #pprint("\n\nlayer2k\n",layer2k.shape,"\n",layer2k) layer2 = ((layer2i + layer2j + layer2k)/3) pprint("\nlayer2",layer2.shape,layer2) # How much did we miss by? How large was the error? # We subtract the "guesses" (layer1, our hidden layer) from the "real" answers (our output layer), # which results in a vector of positive and negative numbers reflecting the difference between # the guess and the real answer for each node. layer2i_error = outputData - layer2i pprint("\nlayer2i_error", layer2i_error.shape,layer2i_error) layer2j_error = outputData - layer2j #pprint("\n\nlayer2j_error\n", layer2j_error.shape,"\n",layer2j_error) layer2k_error = outputData - layer2k #pprint("\n\nlayer2k_error\n", layer2k_error.shape,"\n",layer2k_error) '''layer2_error = (((layer2i_error+layer2min_error)/2 + (layer2j_error+layer2min_error)/2 + (layer2k_error+layer2min_error)/2)/3).reshape(4,1,3) pprint("\n\nlayer2_error\n", layer2_error.shape,"\n",layer2_error)''' # Output the error value calculated every 10000 steps if (j% 10000) == 0: print ("Error_i:"+str(np.mean(np.abs(layer2i_error)))) print ("Error_j:"+str(np.mean(np.abs(layer2j_error)))) print ("Error_k:"+str(np.mean(np.abs(layer2k_error)))) ##pprint ("Error:"+str(np.mean(np.abs(layer2_error)))) # This is our "Error Weighted Derivative". # Here we are multiplying our error vector by the derivative for each of the guesses (which lie # somewhere on our sigmoid curve). # # We use "elementwise" multiplication, which means we multiply each element in the first vector # by element in the same position in the second vector. # Example: [1,2,3]*[6,4,2] = [(1*6),(2*4),(3*2)] = [6,8,6] # # This reduces the error of "high confidence" predictions. # Guesses which have a shallow slope derivative, ie. which fall near top right or bottom left # on the sigmoid curve are guesses with high confidence which need little modification. # Guesses which have a sharp slope, ie. which fall towards the middle of the sigmoid curve, # are "wishy washy" guesses which need more modification (multiplication by greater numbers). layer2i_delta = layer2i_error * nonlin(layer2i, True) pprint("\nlayer2i_delta", layer2i_delta.shape,layer2i_delta) layer2j_delta = layer2j_error * nonlin(layer2j, True) #pprint("\n\nlayer2j_delta\n", layer2i_delta.shape,"\n",layer2j_delta) layer2k_delta = layer2k_error * nonlin(layer2k, True) #pprint("\n\nlayer2k_delta\n", layer2k_delta.shape,"\n",layer2k_delta) '''layer2_delta = ((layer2i_delta.dot(layer2j_delta.T).dot(layer2k_delta))/3).reshape(4,1,3) pprint("\n\nlayer2_delta\n", layer2_delta.shape,"\n",layer2_delta)''' # How much did layer1 values contribute to the layer2 error (according to the weights)? # We use the "confidence weighted error" from layer2 to establish an error for layer1. # To do this, it simply sends the error across the weights from l2 to l1. # This gives what you could call a "contribution weighted error" because we learn # how much each node value in layer1 "contributed" to the error in layer2. # This step is called "backpropagating" and is the namesake of the algorithm. layer1i_error = layer2i_delta.dot(synapse1i.T).reshape(4,4) pprint("\nlayer1i_error", layer1i_error.shape,layer1i_error) layer1j_error = layer2j_delta.dot(synapse1j.T).reshape(4,4) #pprint("\n\nlayer1j_error\n", layer1j_error.shape,"\n",layer1j_error) layer1k_error = layer2k_delta.dot(synapse1k.T).reshape(4,4) #pprint("\n\nlayer1k_error\n", layer1k_error.shape,"\n",layer1k_error) '''layer1_error = ((layer1i_error.dot(layer1j_error.T).dot(layer1k_error))/3) pprint("\n\nlayer1_error\n", layer1_error.shape,"\n",layer1_error)''' layer1i_delta = (layer1i_error * nonlin(layer1i, True)).reshape(4,1,4) pprint("\nlayer1i_delta", layer1i_delta.shape,layer1i_delta) layer1j_delta = (layer1j_error * nonlin(layer1j, True)).reshape(4,1,4) #pprint("\n\nlayer1j_delta\n", layer1j_delta.shape,"\n",layer1j_delta) layer1k_delta = (layer1k_error * nonlin(layer1k, True)).reshape(4,1,4) #pprint("\n\nlayer1k_delta\n", layer1k_delta.shape,"\n",layer1k_delta) '''layer1_delta = ((layer1i_delta.dot(layer1j_delta.T).dot(layer1k_delta))/3) pprint("\n\nlayer1_delta\n", layer1_delta.shape,"\n",layer1_delta) pprint("\n\nlayer1.T\n", layer1.T.shape,"\n",layer1.T)''' # Here we update the weighting of our synapses using our calculated layer1_delta. # We update all elements in our synapse vector (matrix of size (3,1)) at the same time since # we are using "full batch" training (see line 65), but below is an example of what we are # doing to each weighting/element in our synapse. # Example: weight_update = input_value * layer1_delta_value # Since we are doing the updates in a batch operation, we must transpose the input layer, which # is in the x direction (4 rows, 3 columns) to the y direction to match the direction of the # layer1_delta vector (3 rows, 1 column) before we calculate the dot product and add the # corrections to the synapse vector (3 rows, 1 column) synapse1i += layer1i.T.dot(layer2i_delta.reshape(4,3)) pprint("\nsynapse1i", synapse1i.shape,synapse1i) synapse1j += layer1j.T.dot(layer2j_delta.reshape(4,3)) #pprint("\n\nsynapse1j\n", synapse1j.shape,"\n",synapse1j) synapse1k += layer1k.T.dot(layer2k_delta.reshape(4,3)) #pprint("\n\nsynapse1k\n", synapse1k.shape,"\n",synapse1k) '''synapse1 += ((synapse1i.dot(synapse1j.T).dot(synapse1k))/3) pprint("\n\nsynapse1\n", synapse1.shape,"\n",synapse1)''' synapse0i += layer0i.T.dot(layer1i_delta.reshape(4,4)) pprint("\nsynapse0i", synapse0i.shape,synapse0i) synapse0j += layer0j.T.dot(layer1j_delta.reshape(4,4)) #pprint("\n\nsynapse0j\n", synapse0j.shape,"\n",synapse0j) synapse0k += layer0k.T.dot(layer1k_delta.reshape(4,4)) #pprint("\n\nsynapse0k\n", synapse0k.shape,"\n",synapse0k) '''synapse0 += ((synapse0i.dot(synapse0j.T).dot(synapse0k))/3) pprint("\n\nsynapse0\n", synapse0.shape,"\n",synapse0)''' prnt("\nDeired Output:",outputData) prnt("\nOutput after training:", layer2)
96bf7d6ee8aaf93b1a95ab958c26e69dd0e0d0e3
SMS-NED16/crash-course-python
/python_work/chapter_7/exercises/7_4_pizza.py
221
4.21875
4
user_input = "" while user_input.lower() != 'quit': user_input = input("What topping would you like to add to your pizza? ") if user_input.lower() != 'quit': print("Adding " + user_input.title() + " to your pizza.")
3ae4f01221e3508b79cd7135a1cfd360a8245c13
Saboorhub/movie_website
/media.py
1,086
3.9375
4
#the webbrowser module is imported so the open(url) function can be used to allow for displaying web page contents. import webbrowser #As the doc string states, this class is used to store movies-related information which are then used with other modules or files such as entertainment_center and fresh_tomatoes. class Movie(): """This class stores some movies related information such as the title, storyline, image and youtube trailers of the movies.""" #once the class Movie is called, the following functions also called instance methods will be run. def __init__(self, movie_title, movie_storyline, movie_poster_image_url, movie_trailer): """This function initializes the variables such as title, storyline, poster_image_url and trailer_youtube_url """ self.title = movie_title self.storyline = movie_storyline self.poster_image_url = movie_poster_image_url self.trailer_youtube_url = movie_trailer def show_trailer(self): """This function using the webbrowser module opens trailer_youtube_url in a browser.""" webbrowser.open(self.trailer_youtube_url)
956ed834afa213f012df30c677ed7ac164f708ed
paulolemus/leetcode
/Python/add_digits.py
971
3.796875
4
# Source: https://leetcode.com/problems/add-digits/description/ # Author: Paulo Lemus # Date : 2017-11-16 # Info : #258, Easy, 92 ms, 92.50% # Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. # # For example: # # Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. # # Follow up: # Could you do it without any loop/recursion in O(1) runtime? # # Credits: # Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. # 96 ms, 75% class Solution: def addDigits(self, num): """ :type num: int :rtype: int """ while num > 9: num = sum(map(int, str(num))) return num # 92 ms, 92.50% class Solution2: def addDigits(self, num): """ :type num: int :rtype: int """ while num > 9: num = num // 10 + num % 10 return num
46b9e87c2c97450e20bdf258c9d24c47a8a8c909
codeperson1/coderbytes
/array_addition.py
897
3.703125
4
def ArrayAddition(arr): # tmparr = arr.copy() tmparr = [] for i in range(0, len(arr)): tmparr.append(arr[i]) tmparr.sort(reverse=True) most = tmparr[0] for i in range(0, len(tmparr)-1): total = tmparr[i] j = i + 1 while(j < len(tmparr)): total += tmparr[j] if(total == most): return True j += 1 j = i + 1 while(j < len(tmparr)): total -= tmparr[j] if(total == most): return True j += 1 return False # keep this function call here # to see how to enter arguments in Python scroll down #print ArrayAddition(raw_input()) #print(ArrayAddition([3,5,-1,8,12])) print(ArrayAddition([-6,1,2,3,5,7])) #print(ArrayAddition([9,3,2,1,2])) #print(ArrayAddition([9,3,-5,-9,18])
10a53f64bb745f4ff74151f36854556ebd924b3b
raotarun/ASSINMENT-python_advance
/ASSINMENT-python_advance/ASSIGNMENT13.py
1,886
4.59375
5
################################LIST COMPREHENSION & GENERATOR EXPRESSION########################## #Q.1- Write a python program to print the cube of each value of a list using list comprehension. lst=[1,2,3,4,5] lst=[i**3 for i in lst] print(lst) #Q.2- Write a python program to get all the prime numbers in a specific range using list comprehension. lst=[i for i in range(2,20) for j in range(2,i) if(i%j==0) ] a=[i for i in range(2,20) if(i not in lst )] print(a) #Q.3- Write the main differences between List Comprehension and Generator Expression. ''' ANS:-In terms of syntax, the only difference is that you use parenthesis instead of square brackets. The type of data returned by list comprehensions and generator expressions differs. The generator yields one item at a time — thus it is more memory efficient than a list.''' ##############################LAMBDA & MAP############################# #Q.1- Celsius = [39.2, 36.5, 37.3, 37.8] Convert this python list to Fahrenheit using map and lambda expression. Celsius = [39.2 ,36.5, 37.3, 37.8] f=list(map(lambda x: 1.8*x+32,Celsius)) print(f) #Q.2- Apply an anonymous function to square all the elements of a list using map and lambda. lst=[1,2,3] def squ(n): return n*n s=list(map(lambda n:squ(n),lst)) print(s) ###############################FILTER & REDUCE######################### #Q.1- Filter out all the primes from a list. lst=[1,2,3,4,5,6,7,8,9] def isprime(n): flag=1 if(n>1): for i in range(2,n): if(n%i==0): flag=0 break if(flag==1): return n p=list(filter(lambda n: isprime(n),lst)) print(p) #Q.2- Write a python program to multiply all the elements of a list using reduce. lst=[1,2,3,4,5,5] from functools import * m=reduce(lambda x,y:x*y,lst) print(m)
b98efc9ee480c1de93ae6a9949280fa0bdc25968
leet23/python_kurs
/03_Kolekcje/LISTzad5.py
811
3.59375
4
'''Utwórz “na sztywno” 2-wymiarową tablicę, tak, by kolejne wiersze zawierały dane osób, natomiast w kolumnach będzie znajdować się imię, nazwisko, zawód, np: Dorota, Wellman, dziennikarka Adam, Małysz, sportowiec Robert, Lewandowski, piłkarz Krystyna, Janda, aktorka Wyświetl w sposób przyjazny dla użytkownika''' tablica = [ ["Dorota", "Wellmann", "dziennikarka"], ["Adam", "Małysz", "Sportowiec"], ['Krystyna', 'Janda', 'aktorka'], ['Robert', 'Lewandowski', 'piłkarz'] ] for row in tablica: print(row[0], row[1], "-", row[2]) '''print(tablica[0][0], tablica[0][1], '-', tablica[0][2]) print(tablica[1][0], tablica[1][1], '-', tablica[1][2]) print(tablica[2][0], tablica[2][1], '-', tablica[2][2]) print(tablica[3][0], tablica[3][1], '-', tablica[3][2])'''
106e09f271a148a511df01bdef495cb12172b3d4
EVERLYNE/python-class
/income.py
912
4.03125
4
class Taxpayer: income = 0 name = "Jane Doe" minimum = 0 def __init__(self,name, income ,minimum): self.income = income self.name = name self.minimum = minimum self.validateIncome() self.validateName() self.ValidateMinimum() def validateIncome(self): if self.income.isnumeric() == False: raise ValueError("The income {} is not numeric".format(self.income)) def validateName(self): if self.name .isnumeric(): raise ValueError("The name {} is not a string".format(self.name)) def ValidateMinimum(self): if float(self.income) < 100001: raise ValueError("Bellow minimum wage") def calculate_tax(self): return float (self.income)* 0.3 income = input("what is your income") name = input ("what is your name") minimum = input("what is your minimum") employee = Taxpayer(name, income, minimum) print(employee.calculate_tax())
86734f4f0b422a213480654aa1215c0a48084bb9
YiWaiChow/leaguetool
/main.py
2,756
3.6875
4
from Champion.Champ_List import ChampionList from Champion.Score.ScoreCalculator import Scorecalculator from Champion.Score.decisionTree import ScoreAVLTree from Game.CurrentGame import Game from User.User import User CL = ChampionList() CG= Game() name = input("enter your user name below:") perfer = input("enter your champion preference, Example: AD , AP, AR, MR") user = User(name) user.add_prefer(perfer) print("please enter your champion pool one 1 by one, type end when all champion from your champion pool is enter , " "this tool currently support up to champion with alphabet a-b") champ_input = None while champ_input != "end": champ_input = input("type here") champion = CL.find_champ(champ_input) if champion is None: print("either champion is not currently supported or name is incorrect") else: user.add_champ_to_pool(champion) print("here is the champion entered so far") print(user.get_pool()) print("now enter all enemy champion that is selected so far in this game, if all champion are entered, type end") champ_input = None position = 1 "entering enemy team champion" while champ_input != "end": if position == 6: break champ_input = input("enter here") champion = CL.find_champ(champ_input) if champ_input == "end": print("all enemy champion is entered") elif champion is None: print("either champion is not currently supported or name is incorrect") else: CG.add_champ(champion, position, "e") position += 1 print("now enter all allies champion that is selected so far in this game, if all champion are entered, type end") champ_input = None position = 1 while champ_input != "end" : if position == 6: break champ_input = input("enter here") champion = CL.find_champ(champ_input) if champ_input == "end": print("all allies champion is entered") elif champion is None: print("either champion is not currently supported or name is incorrect") else: CG.add_champ(champion, position, "a") position += 1 SC = Scorecalculator(CL, CG, user) att_list = SC.att_in_need() print("here is the attrivbute in need for this game") print(att_list) SC.calculate_champscore(att_list) for champ in CL.get_champ_list(): print(champ.get_score()) SAT = ScoreAVLTree() TopNode = None for x in CL.get_champ_list(): print(x) if x not in CG.achamp and x not in CG.echamp: print(x) TopNode = SAT.insert(TopNode, x) SAT.preOrder(TopNode) MAX_node = SAT.max_score(TopNode) print("here is the recommanded champion based on the attribute needed and peference of the user ") for x in (MAX_node.get_champ_list()): if x not in CG.echamp: print(x)
3024f8db2db0c05114bfa1bfd2696c5c7fe3e1c9
anchalgithub/Project-100
/atm.py
1,588
4.03125
4
print("Welcome to the Toronto Bank.") class atm: def __init__(self,cardNo,pin): self.cardNo=cardNo self.pin=pin def check_balance(self): print("Your balance is 50K.") def withdrawl(self,amount): if amount<50000: new_amount=50000-amount print("You have withdrawn $" + str(amount)+ ". Your remaining balance is $ "+str(new_amount)) elif amount>50000: print("Insufficient funds!") amount=int(input("Please enter amount again: ")) new_amount=50000-amount print("You have withdrawn $" + str(amount)+ ". Your remaining balance is $ "+str(new_amount)) def main(): card_number=(input("Insert card number: ")) pin_number=(input("Insert pin number: ")) new_user=atm(card_number, pin_number) print("Please choose your activity") print("1)Balance enquiry 2)Withdrawl") activity=int(input("Enter activity number: ")) if(activity==1): new_user.check_balance() elif(activity==2): amount=int(input("Enter amount: ")) new_user.withdrawl(amount) #If a person chooses a wrong number, then the function should happen again. else: print("Please enter a valid number!") activity=int(input("Enter activity number: ")) if(activity==1): new_user.check_balance() elif(activity==2): amount=int(input("Enter amount: ")) new_user.withdrawl(amount) if __name__=="__main__": main()
c0988dcf62d0c384ff26f8692a5dda7eaa8d4b50
ahmedyoko/python-course-Elzero
/string7.py
3,869
4.34375
4
# string method ####################### # method is the function of object or dotted function to do something #1-len => length or the number of the characters #2-strip method : to remove space from the right and left , rstrip : for right only, lstrip : for left only #3-Title method : convert first letter to capital case and convert any letter after number to capital case #4-capitalize method #5-zfill method : needs number of characters , it is short for zero fill #6-upper and lower method #7-split method : separate object into its elements in the form of list, by default it separate by space #8-center method: make the name at the center of a set of wanted characters => center(total character or width,fill chch) #9-count method : to count the argument occurs between parathesis , it has mandatory argument : counted text #10-swapcase method : change the state of letters #11-startswith method : means is , It takes argument as count #12-endswith method : the same as previous #............................. # 1-len => length or the number of the characters a = " I love python" b = " I love python " print(len(a)) print(len(b)) # method is the function of object or dotted function to do something # strip method : to remove space from the right and left , rstrip : for right only, lstrip : for left only b = " I love python " print(b.strip()) print(b.rstrip()) print(b.lstrip()) print(len(b.lstrip())) # don't forget to put the character between 2 quotes , otherwise it will give you syntaxError b = "###I love python####" print(b.strip("#")) print(b.rstrip("#")) print(b.lstrip("#")) print(len(b.lstrip("#"))) b = "@#@#@#I love python@#@#@#@#" print(b.strip("@#")) print(b.rstrip("@#")) print(b.lstrip("@#")) print(len(b.lstrip("@#"))) #Title method : convert first letter to capital case and convert any letter after number to capital case a = " I love 3d Graphics and 2g Technology and python" print(a.title()) #capitalize method a = " I love 3d Graphics and 2g Technology and python" print(a.capitalize()) #zfill method : to make the same pattern of number or make all number has the same character by using zero #zfill method : needs number of characters , it is short for zero fill a, b , c = "1" , '11' , '111' print(a) print(b) print(c) print(a.zfill(3)) #upper and lower method a = "osama" b = "ahmed" print(a.upper()) print(b.lower()) #split method : separate object into its elements in the form of list, by default it separate by space a = 'I love pthon and PHP' print(a.split()) a = 'I-love-pthon-and-PHP' print(a.split()) #split accept 2 values : separator as dash , max split : make split to number maximum and make all other in one element a = 'I-love-pthon-and-PHP' print(a.split('-')) a = 'I-love-pthon-and-PHP' print(a.split('-',2)) #rsplit the same but the direction rlt a = 'I-love-pthon-and-PHP' print(a.rsplit('-',2)) #center method: make the name at the center of a set of wanted characters => center(total character or width,fill chch) a = 'osama' print(a.center(9)) # by default make osama at the center of spaces print(a.center(9,'#')) # make osama at the center of hashes print(a.center(9,'@')) # make osama at the center of @ # count method : to count the argument occurs between parathesis , it has mandatory argument : counted text f = ' I love python and php because php is easy' print(f.count('php')) # count has optional argument : start and end print(f.count('php', 0 , 25)) # swapcase method : change the state of letters a = ' I Love Python' b = ' i loVE pythoN' print(a.swapcase()) print(b.swapcase()) # startswith method : means is , It takes argument as count a = 'I Love Python' print(a.startswith('I')) print(a.startswith('P',7,12)) #endswith method : the same as previous a = 'I Love Python' print(a.endswith('n')) print(a.endswith('e',2,6)) # begin with zero index and end not included
3f5d1a9ec154209edb7adbf888e08eb2ff4d4039
slohani-ai/Set_password_at_Terminal
/user_pass.py
4,716
3.640625
4
'''@Sanjaya Lohani, Uploaded July 24, 2017''' import sqlite3 as sq import getpass import os import sys def open_account(name): def openn(): conn = sq.connect(name) cur = conn.cursor() #cur.execute("DROP TABLE IF EXISTS ACCOUNTS") cur.execute('''CREATE TABLE ACCOUNTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, FIRST_NAME NOT NULL, LAST_NAME NOT NULL, USER TEXT NOT NULL, PASSWORD TEXT NOT NULL);''') conn.close() def openn2(): conn = sq.connect(name) cur = conn.cursor() cur.execute("DROP TABLE IF EXISTS ACCOUNTS") cur.execute('''CREATE TABLE ACCOUNTS (ID INTEGER PRIMARY KEY AUTOINCREMENT, FIRST_NAME NOT NULL, LAST_NAME NOT NULL, USER TEXT NOT NULL, PASSWORD TEXT NOT NULL);''') conn.close() try: openn() except: print 'Data_base already exists, want to override?' command = raw_input('y/n? :') if command == 'y': key = getpass.getpass('key: ') if key == '00000': openn2() else: sys.exit('Key did not match') else: sys.exit('thank you') def insert(name): print ('----------** Inputs Are Case Sensitive **---------------------------') print ('') first_name = raw_input('First_name: ') last_name = raw_input('Last_name: ') user = raw_input('user_name: ') password = getpass.getpass('password: ') n_p = getpass.getpass('Retype password: ') assert password == n_p,'Retyped password did not match, please re-run' conn = sq.connect(name) cur = conn.cursor() params = (first_name,last_name,user,password) cur.execute("INSERT INTO ACCOUNTS VALUES(NULL,?,?,?,?)",params) conn.commit() conn.close() def display(name): print ('----------** Inputs Are Case Sensitive **---------------------------') print ('') key = getpass.getpass('Administrative key: ') if key == '00000': pass else: sys.exit('Key did not match') conn = sq.connect(name) cur = conn.cursor() rows = cur.execute("SELECT ID,FIRST_NAME,LAST_NAME,USER,PASSWORD from ACCOUNTS") for row in rows: print 'ID: ',row[0] print 'FIRST NAME',row[1] print 'LAST NAME',row[2] print 'USER: ',row[3] print 'PASSWORD: ',row[4], '\n' def extract(name): conn = sq.connect(name) cur = conn.cursor() rows = cur.execute("SELECT ID,FIRST_NAME,LAST_NAME,USER,PASSWORD from ACCOUNTS") pas = [] lists = [] for row in rows: lists.append((row[0],row[1],row[2],row[3],row[4])) #for row in rows: # pas.append(row[4]) conn.commit() conn.close() return lists def update(name): print ('----------** Inputs Are Case Sensitive **---------------------------') print ('') last_name = raw_input('Last_name: ') lists = extract(name) #print lists[1][2] mask = [] for i in range(len(lists)): if last_name == lists[i][2]: old_pass = raw_input('Old Password: ') assert old_pass in lists[i],'Sorry, old password could be located. Please re-run' n_user = raw_input('New user_name: ') n_pass = getpass.getpass('New password: ') r_pass = getpass.getpass('Retype password: ') assert n_pass == r_pass,'Retyped password did not match, please run again' conn = sq.connect(name) cur = conn.cursor() params = (n_user,n_pass,last_name) cur.execute("UPDATE ACCOUNTS set USER = ?, PASSWORD = ? where LAST_NAME = ?",params) conn.commit() conn.close() print 'Update Done !' mask.append(1) break else: pass if len(mask) == 0: print 'User could not be located. Please run again' else: pass #print 'User could not be located. Please run again' #sys.exit() def delete(name): print ('----------** Inputs Are Case Sensitive **---------------------------') print ('') last_name = raw_input('Last_name: ') lists = extract(name) mask = [] for i in range(len(lists)): if last_name == lists[i][2]: old_p = raw_input('password: ') assert old_p == lists[i][4],'Password did not match to the last name' conn = sq.connect(name) cur = conn.cursor() params = (lists[i][2],) cur.execute("DELETE from ACCOUNTS where LAST_NAME = ?",params) conn.commit() conn.close() mask.append(1) print ('{} {} user has been removed'.format(lists[i][1],lists[i][2])) break else: pass if len(mask) != 0: pass else: print ('Users could not be located')
67ff30bf6095d176377d78a8d233491240b29a24
pybites/challenges
/39/habereet/wordvalue.py
944
4.0625
4
from data import scrabble_scores, LETTER_SCORES def get_data_file(): return "dictionary.txt" def read_dictionary(): with open(get_data_file()) as file: lines = file.readlines() lines = [line.strip() for line in lines] return lines def word_value(word): word_score = 0 for character in word: if character.isalpha(): word_score += letter_value(character.upper()) return word_score def letter_value(letter): return LETTER_SCORES[letter] def calculate_max_word(current_max, test): if test[1] > current_max[1]: return test else: return current_max def find_max_word(): max_word = ("", 0) words = read_dictionary() for word in words: test=(word, word_value(word)) max_word = (calculate_max_word(max_word, test)) return max_word if __name__ == "__main__": max_word = find_max_word() print(f'The word in {get_data_file()} with the largest Scrabble value is {max_word[0]} with a value of {str(max_word[1])}.')
ea6085172dc3034af4a6fd2f33b8dc880c5779fc
zorga/python
/divers/prod.py
304
3.6875
4
#!/usr/bin/python from itertools import product def main(): A = map(int, raw_input().strip().split(' ')) B = map(int, raw_input().strip().split(' ')) res = (list(product(A, B))) fin = "" for e in res: fin += str(e) + ' ' print fin if __name__ == '__main__': main()
7e69d07c6b5c07417b7f36e8ed923614d7a0d895
kxu68/BMSE
/examples/AY_2017_2018/semester_2/Week 6- Non-parametric statistics/Statistics_is_Easy_Codes/OneWayAnovaSig.py
7,374
3.921875
4
#!/usr/bin/python ###################################### # One-Way ANOVA Significance Test # From: Statistics is Easy! By Dennis Shasha and Manda Wilson # # Assuming that there is no difference in the three drugs used, tests to see the probability # of getting a f-statistic by chance alone greater than or equal to the one observed. # Uses shuffling to get a distribution to compare # to the observed f-statistic. # # Author: Manda Wilson # # Example of FASTA formatted input file: # >grp_a # 45 44 34 33 45 46 34 # >grp_b # 34 34 50 49 48 39 45 # >grp_c # 24 34 23 25 36 28 33 29 # # Pseudocode: # # 1. Calculate f-statistic for the observed values (in our example it is 11.27). # a. Initialize within sum of squares (wss), total sum (ts), # total count (tc), and between sum of squares (bss) to 0 # b. For each group: # i. Within group mean (wgm) = sum of group values / number of values in group # ii. Store the number of values in group # iii. Sum the following: for each value in the group # I. Subtract the value from wgm # II. Square the result of step (1biiiI) # III. Add the result of step (1biiiII) to wss # c. Total mean (tm) = ts / tc # d. For each group: # i. Subtract the wgm from tm # ii. Square the result of step (1di) # iii. Multiply the result of step (1dii) by # the number of values in that group (stored in step (1bii)) # iv. Add the result of step (1diii) to bss # e. Between degrees of freedom (bdf) = number of groups - 1 # f. Within degrees of freedome (wdf) = tc - number of groups # g. Within group variance (wgv) = wss / wdf # h. Between group variance (bgv) = bss / bdf # i. f-statistic = wgv / bgv # # 2. Set a counter to 0, this will count the number of times we get a f-statistic # greater than or equal to 11.27. # # 3. Do the following 10,000 times: # a. Shuffle the observed values. To do this: # i. Put the values from all the groups into one array # ii. Shuffle the pooled values # iii. Reassign the pooled values to groups of the same size as the original groups # b. Calculate f-statistic on the results from step (3a), just as we did in step (1) # c. If the result from step (3b) is greater than or equal to our observed f-statistic (11.27), # increment our counter from step (2). # # 3. counter / 10,000 equals the probability of getting a f-statistic greater than or equal to # 11.27, assuming there is no difference between the groups # ###################################### import random ###################################### # # Adjustable variables # ###################################### input_file = 'OneWayAnova.vals' ###################################### # # Subroutines # ###################################### # a list of lists def shuffle(grps): num_grps = len(grps) pool = [] # throw all values together for i in range(num_grps): pool.extend(grps[i]) # mix them up random.shuffle(pool) # reassign to groups new_grps = [] start_index = 0 end_index = 0 for i in range(num_grps): end_index = start_index + len(grps[i]) new_grps.append(pool[start_index:end_index]) start_index = end_index return new_grps def sumofsq(vals, mean): # the sum of squares for a group is calculated # by getting the sum of the squared difference # of each value and the mean of the group that value belongs to count = len(vals) total = 0 for i in range (count): diff_sq = (vals[i] - mean)**2 total += diff_sq return total def weightedsumofsq(vals, weights, mean): count = len(vals) total = 0 for i in range (count): diff_sq = (vals[i] - mean)**2 total += weights[i] * diff_sq return total # expects list of lists def onewayanova(grps): num_grps = len(grps) within_group_means = [] grp_counts = [] within_ss = 0 total_sum = 0 total_count = 0 for i in range (num_grps): grp = grps[i] grp_count = len(grp) grp_sum = sum(grp) within_group_mean = grp_sum / float(grp_count) grp_counts.append(grp_count) total_count += grp_count # add to total number of vals total_sum += grp_sum within_group_means.append(within_group_mean) # to get the within group sum of squares: # sum the following: for every element in the overall group # subtract that element's value from that element's group mean # square the difference # get within group sum of squares # this is calculated by summing each group's sum of squares within_ss += sumofsq(grp, within_group_mean) total_mean = total_sum / total_count # to get the between group sum of squares: # sum the following: for every element in the overall group # subtract that element's group mean from the overall group mean # square the difference # grp_counts are used as weights between_ss = weightedsumofsq(within_group_means, grp_counts, total_mean) # now we want to find out how different the groups are between each other # compared to how much the values vary within the groups # if all groups vary a lot within themselves, # and there is no significant difference # between the groups, then we expect the differences between # the groups to vary by about the same amount # so lets get the ratio of the between group variance and # the within group variance # if the ratio is 1, then there is no difference between the groups # if it is significantly larger than one, # then there is a significant difference between the groups # remember: even if the groups are significantly different, # we still won't know which groups are different # the between group degrees of freedom # is equal to the number of groups - 1 # this is because once we know the number of groups - 1, # we know the last group between_df = len(grp_counts) - 1 # the within group degrees of freedom # is equal to the total number of values minus the number of groups # this is because for each group, once we know the count - 1 values, # we know the last value for that group # so we lose the number of groups * 1 degrees of freedom within_df = total_count - num_grps within_var = within_ss / within_df between_var = between_ss / between_df f_stat = between_var / within_var return f_stat ###################################### # # Computations # ###################################### # list of lists samples = [] # file must be in FASTA format infile=open(input_file) for line in infile: if line.startswith('>'): # start of new sample samples.append([]) elif not line.isspace(): # line must contain values for previous sample samples[len(samples) - 1] += list(map(float,line.split())) infile.close() observed_f_statistic = onewayanova(samples) count = 0 num_shuffles = 10000 for i in range(num_shuffles): new_samples = shuffle(samples) f_statistic = onewayanova(new_samples) if (f_statistic >= observed_f_statistic): count = count + 1 ###################################### # # Output # ###################################### print("Observed F-statistic: %.2f" % observed_f_statistic) print(count, "out of 10000 experiments had a F-statistic greater than or equal to %.2f" % observed_f_statistic) print("Probability that chance alone gave us a F-statistic", end=' ') print("of %.2f or more" % observed_f_statistic, "is", (count / float(num_shuffles)))
4d59faad874c3d94d1e7daba1d3b9080fe1b7baf
KDjonev/SyllabusParser
/venv/VotedPerceptron.py
3,119
3.78125
4
import csv from math import log def RunVotedPerceptron(Xtrain_file, Ytrain_file, test_data_file, pred_file): '''The function to run your ML algorithm on given datasets, generate the predictions and save them into the provided file path Parameters ---------- Xtrain_file: string the path to Xtrain csv file Ytrain_file: string the path to Ytrain csv file test_data_file: string the path to test data csv file pred_file: string the prediction file to be saved by your code. You have to save your predictions into this file path following the same format of Ytrain_file ''' # read data from Xtrain_file, Ytrain_file and test_data_file xData, yData, testXData = readTrainingData(Xtrain_file, Ytrain_file, test_data_file) # your algorithm predictions = VotedPerceptron(xData, yData, testXData) # save your predictions into the file pred_file savePredictions(pred_file, predictions) def readTrainingData(Xtrain_file, Ytrain_file, test_data_file): with open(Xtrain_file, 'rb') as f: reader = csv.reader(f) xData = list(reader) for i in range(len(xData)): xData[i] = [float(x) for x in xData[i]] with open(Ytrain_file, 'rb') as f: reader = csv.reader(f) yData = list(reader) for i in range(len(yData)): yData[i] = [float(x) for x in yData[i]] for i in range(0, len(yData)): if yData[i][0] == 0.0: yData[i][0] = -1.0 with open(test_data_file, 'rb') as f: reader = csv.reader(f) testXData = list(reader) for i in range(len(testXData)): testXData[i] = [float(x) for x in testXData[i]] return xData, yData, testXData def savePredictions(pred_file, predictions): with open(pred_file,'wb') as resultFile: wr = csv.writer(resultFile, dialect='excel') wr.writerows(predictions) def VotedPerceptron(xData, yData, testXData): k = 1 c = [0] * (len(xData) + 5) w = [] w.append([0] * len(xData[-1])) w.append([0] * len(xData[-1])) t = 0 T = 20 while t <= T: for yi, xi in zip(yData, xData): XdotW = sum([i*j for (i, j) in zip(xi, w[k])]) if yi[0] * XdotW <= 0: yixi = [x * yi[0] for x in xi] w.append([0] * len(xData[-1])) w[k+1] = [sum(x) for x in zip(w[k], yixi)] c[k+1] = 1 k = k + 1 else: c[k] = c[k] + 1 t = t + 1 predictions = [] for test in testXData: y = 0 for smallK in range(1, k): XdotW = sum([i*j for (i, j) in zip(test, w[smallK])]) signbit = 1 if XdotW < 0.0: signbit = -1 y = y + c[smallK] * signbit if y >= 0: predictions.append(['1']) else: predictions.append(['0']) return predictions def main(): RunVotedPerceptron('Xtrain90.csv', 'Ytrain90.csv', 'Xtest.csv', 'Results.csv') if __name__ == "__main__": main()
225f18c7342af2874635578a53241566268c2bb5
cliu0507/CodeForFun
/Coding Topics/Binary Search Tree/Search and Insertion.py
2,017
3.75
4
BST Search and Insertion Binary Search Tree, is a node-based binary tree data structure which has the following properties: The left subtree of a node contains only nodes with keys less than the node’s key. The right subtree of a node contains only nodes with keys greater than the node’s key. The left and right subtree each must also be a binary search tree. There must be no duplicate nodes. Searching a key To search a given key in Bianry Search Tree, we first compare it with root, if the key is present at root, we return root. If key is greater than root’s key, we recur for right subtree of root node. Otherwise we recur for left subtree. # A utility function to search a given key in BST def search(root,key): # Base Cases: root is null or key is present at root if root is None or root.val == key: return root # Key is greater than root's key if root.val < key: return search(root.right,key) # Key is smaller than root's key return search(root.left,key) Insertion of a key(注意插入的时候其实是先搜索 一旦到leaf node再进行插入) A new key is always inserted at leaf. We start searching a key from root till we hit a leaf node. Once a leaf node is found, the new node is added as a child of the leaf node. class Node: def __init__(self,key): self.left = None self.right = None self.val = key # A utility function to insert a new node with the given key def insert(root,node): if root is None: root = node else: if root.val < node.val: if root.right is None: root.right = node else: insert(root.right, node) else: if root.left is None: root.left = node else: insert(root.left, node) # A utility function to do inorder tree traversal def inorder(root): if root: inorder(root.left) print(root.val) inorder(root.right)
2e314abb7161302971b9d9e1f6303d7c9928ad17
gmaurer/algorithmPractice
/structures/bfs.py
968
3.53125
4
from assets import graph, queue def breadth_first_search1(graph, start, target): frontier = queue.Queue() frontier.put(start) visited = {} visited[start] = True while not frontier.empty(): current = frontier.get() print("Visiting %r" % current) if current is target: print("Found %r" % current) break for next in graph.neighbors(current): if next not in visited: frontier.put(next) visited[next] = True def breadth_first_search2(graph, start): frontier = queue.Queue() frontier.put(start) came_from = dict() came_from[start] = None while not frontier.empty(): current = frontier.get() for next in graph.neighbors(current): if next not in came_from: frontier.put(next) came_from[next] = current return came_from #def binary_breadth_first_search(node,level):
e594930a374c348c6eba7a60a1932cfb375be658
DILLORG/CIS189
/Module 13/numberGuesser/game/numberGuesser.py
2,170
3.953125
4
from random import randint, shuffle class NumberGuesser: def __init__(self, min, max, amount): """ Construct all number guesser objects :params min smallest generated number, max largest generated number amount amount of numbers to generate. :returns NumberGuesser. """ self.__guesses = [] # Holds user's guesses. self.__nums = [] # Holds generated numbers. # Generate a random list of numbers to choose from. for num in range(amount): self.__nums.append(randint(min, max)) # Set the correct number to the first member in the list. self.__correct = self.__nums[0] # Shuffle list. shuffle(self.__nums) def add_guess(self, guess): """ Add a guess to the list of guessed numbers if the guess is not in the list of generated numbers raise a value error. :params user's guess. :returns none """ guess = int(guess) if guess not in self.__nums: raise ValueError(f"{guess} not in possible numbers.") self.__guesses.append(guess) def is_winner(self): """ Check if the user has guessed correctly :params none :returns true if the user guessed correctly. """ return self.__correct in self.__guesses def force_winner(self, index): """ Force winning number to a given index. :params index of winning number. :returns none. """ index = int(index) if index > len(self.__nums): raise IndexError(f"{index} is larger the list of possibles") # Set the correct number and append it to the list. self.__correct = self.__nums[index] self.__guesses.append(self.__correct) def get_possibles(self): """ Return the list of generated numbers. :params none. :returns none. """ return self.__nums def get_guesses(self): """ Return the list of guessed numbers. :params none. :returns none. """ return self.__guesses
74ac39d1dfaf7036a56fcc239a83dcf52eed3fe8
sandykrishdaswani/5-1.py
/5-18.py
64
3.59375
4
z=int(input()) sum=0 for i in range(1,z+1): sum +=i print(sum)
426cf3cae5172633c4d28bc52af8778c78725f04
viewv/leetcode
/35. Search Insert Position.py
219
3.6875
4
class Solution: def searchInsert(self, nums, target): nums.append(target) nums=sorted(nums) for x in range(0,len(nums)): if nums[x]==target: break return x
7ada7cb544d8bdb1c651bab03c9ca4d7be7a7e15
jwyx3/practices
/leetcode/dynamic-programing/count-the-repetitions.py
1,719
3.546875
4
# https://leetcode.com/problems/count-the-repetitions/ # http://www.cnblogs.com/grandyang/p/6149294.html # find repetition pattern for s2 from S1 # find count of s2 in S1 as count, then answer will count / n2. # the problem can be two subproblems: count of repeat pattern part and remaining part # use Pigeonhole Principle # Time: O(len(s1)*len(s2)) # Space: O(min(n1, len(s2)) class Solution(object): def getMaxRepetitions(self, s1, n1, s2, n2): """ :type s1: str :type n1: int :type s2: str :type n2: int :rtype: int """ # visited[k] will be repeated when it tried len(s2) + 1 times n = min(len(s2) + 1, n1) # repeat_count: number of s2 found for first k s1 repeat_count = [0] * (n + 1) # next_idx: the index of s2 for next s1 next_idx = [0] * (n + 1) # the index of s1 for visited next_idx visited = [-1] * len(s2) visited[0] = 0 j = count = 0 for k in xrange(1, n + 1): for i in xrange(len(s1)): if s1[i] == s2[j]: j += 1 if j == len(s2): count += 1 j = 0 repeat_count[k] = count next_idx[k] = j if visited[j] >= 0: start = visited[j] interval = k - start repeat, remain = divmod(n1 - start, interval) pattern_count = (repeat_count[k] - repeat_count[start]) * repeat remain_count = repeat_count[start + remain] return (pattern_count + remain_count) / n2 visited[j] = k return repeat_count[n1] / n2
3bce7717ccc755a128b2a8e614155bd97dab0b48
s38m/Python_learning
/password_guest.py
377
3.53125
4
#encoding = utf8 #password guest print('猜密碼遊戲') pwd = '123456' chance = 3 while chance > 0: data = input('請輸入密碼: ') chance -= 1 if pwd == data: print('恭喜你!猜對了!') break else: if chance > 0: print('密碼錯誤! 剩餘%d次機會' %chance) else: print('遊戲失敗!!')
3284e932c2feb37b54fc25c3987665a320f7be46
HasunSong/maestro-gtl-mileage
/mileage_graph.py
1,339
3.59375
4
# %% import numpy as np import matplotlib.pyplot as plt # 주어진 E(e)와 초기 마일리지에 대해, 예상되는 진행 라운드 수를 대강 예상한 것. def max_round(e, init_mileage): cost = 0 for k in range(1, 100000000): if cost + (k+e) > init_mileage: return k-1 else: cost += (k+e) # 총 라운드 진행 수 K와, 라운드별 보상 point_list를 받아서, 총 파이 리턴 def get_pi(K, point_list): return sum(point_list[:K+1]) ########################### 여기만 조절하면 됨 ########################## INIT_MILEAGE = 100 # 초기에 각 플레이어에게 주어지는 마일리지 POINT_LIST = [0] # POINT_LIST[k] = k라운드 보상 포인트 # 지수적으로 증가하는 보상 for k in range(1, 100): POINT_LIST.append(100 * 2**(k-1)) ######################################################################## e_list = np.arange(0, 10, 0.01).tolist() K_list = [] for e in e_list: K_list.append(max_round(e, INIT_MILEAGE)) pi_list = [] for K in K_list: pi_list.append(get_pi(K, POINT_LIST)) plt.figure() plt.subplot(1,2,1) plt.title("E(e) - #Round Curve") plt.xlim([0, 10]) plt.ylim([0, 20]) plt.plot(e_list, K_list) plt.subplot(1,2,2) plt.title("E(e) - Total Pi Curve") plt.xlim([0, 10]) plt.plot(e_list, pi_list) plt.show()
95d1d9824513e8c9b1ee02100f50cc71e8e21252
adarshav/Python-
/assignment4a.py
4,390
4.125
4
#1. Find the maximum of three numbers. # def max(a, b, c): # if(a > b): # if(a > c): # return a; # elif(b > c): # return b; # else: # return c; # print(max(3,9, 5)); # 2. Find the sum of the numbers in a list. # def sum(list1): # sum = 0; # for i in list1: # sum = sum + i; # return sum; # print(sum([10, 1, 3])); #3. Reverse a string without using built-in function. def rev(str1): str2="" for i in range(len(str1)-1,-1,-1): str2+=str1[i]; print(str2) str1=input("Enter a string") rev(str1); 4 def fre(str1): di={} for i in str1: if i in di: di[i]+=1 else: di[i]=1 return di string1=input("enter a string") fli=fre(string1) print(fli) 5 def pal(data1): data2="" for i in range(len(data1)-1,-1,-1): data2+=data1[i]; return data2 data1=input("Enter a number") data2=pal(data1) if(data1==data2): print(data1,"is a palindrome") else: print(data2,"is not a palindrome") 6 def occ(list1,string1): for i in string1: if i in list1: list1.remove(i) return list1 initlist=['a','b','c','d','e','f','g','h'] string1=input("enter a string") finallist=occ(initlist,string1) if len(finallist)==0: print("String contains all characters") else: print("String contains all characters except",finallist) 7 def computeGCD(x, y): try: if x > y: small = y else: small = x for i in range(1, small+1): if((x % i == 0) and (y % i == 0)): gcd = i return gcd except: pass x=int(input("Enter a number ")) y=int(input("Enter another number")) if(x<1 or y<1): print("Please enter the number") else: gcd=computeGCD(x,y) print("GCD of",x," and ",y," is ",gcd) 8 def sum(num): if num==1: return 1 else: return num+sum(num-1) x=int(input("enter a number")) val=sum(x) print(val) 9 def decimalToBinary(n): try: if n > 1: decimalToBinary(n//2) print (n%2,end=" ") except: pass num=int(input("Enter a number")) decimalToBinary(num) 10 print("Please select operation -\n 1. Add 2. Subtract 3. Multiply 4. Divide") option= input("Select operations form 1, 2, 3, 4 :") num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if option == '1': print(num1, "+", num2, "=",num1+num2) elif option == '2': print(num1, "-", num2, "=",num1-num2) elif option == '3': print(num1, "*", num2, "=",num1*num2) elif option == '4': print(num1, "/", num2, "=",num1/num2) else: print("Invalid input") 11 def dev(n): ls=[] for i in range(2,n+1): if(n%i==0): ls.append(i) print("possible devisors are",ls) sum(ls) def sum(ls): count=0 sum=0 for i in ls: count+=1 sum+=i print("sum of all devisors are",sum,"count of all devisors are",count) x=int(input("Enter a number")) dev(x) 12 ls=[] str1=" " while str1!="": str1=input("Enter a string") if(str1!=""): ls.append(str1) for i in ls: print("length of",i,"is",len(i)) 13 def pascal(n): result = [] for row in range(n): newrow = [1] for col in range(1, row+1): newcell = newrow[col-1] * float(row+1-col)/col newrow.append(int(newcell)) result.append(newrow) return result x=pascal(5) for i in x: print(i) 14 def prime(lower,upper): for num in range(lower,upper + 1): if num > 1: flag=1; for i in range(2,num): if (num % i) == 0: flag=0 break if(flag==1): print(num,end=" ") lower = int(input("Enter lower range: ")) upper = int(input("Enter upper range: ")) prime(lower,upper) 15 def sum(list1,list2): sum=[] for i in range(1,(n*n)+1): sum.append(list1[i]+list2[i]) return sum def diff(list1,list2): diff=[] for i in range(1,(n*n)+1): diff.append(list1[i]-list2[i]) return diff list1=list2=[] n=int(input("enter the total no of col")) print("Enter the first matrix") for i in range(1,(n*n)+1): data=int(input("Enter number")) list1.append(data) print("Enter the second matrix") for i in range(1,(n*n)+1): data=int(input("Enter number")) list2.append(data) sum=sum(list1,list2) diff=diff(list1,list2) print("Sum= ") count=0 for i in range(0,len(sum)): print(sum[i],end=" ") count+=1 if(count>=n): print() count=0 print("Diff= ") count=0 for i in range(0,len(sum)): print(diff[i],end=" ") count+=1 if(count>=n): print() count=0
975593541457bce016567ded8efbf51c0a12da69
laxminagln/IOSD-UIETKUK-HacktoberFest-Meetup-2019
/Beginner/fibonacciSequence.py
675
4.34375
4
########################## Code By - ORASHAR ########################### ########################## Fibonacci Sequence ########################### def Fibonacci(n): n1 = 0 n2 = 1 c = 0 ans = [] if n == 1: ans = n1 else: while c < n: ans.append(n1) nth = n1 + n2 n1 = n2 n2 = nth c += 1 print(f"fibonacci sequence upto {n} terms ", end=': ') for a in ans: print(a, end = ' ') try: n = int(input("enter number of terms: ")) if n < 0: print("Input must be a positive number") else: Fibonacci(n) except: print("invalid input!")
74635914f2726b51d2a7b1fca2ab180674ad5eab
jinho9610/py_algo
/sw_academy/2050.py
97
3.515625
4
data = list(input()) for i in range(len(data)): print(ord(data[i]) - ord('A') + 1, end=' ')
718bee2247c870bfd52d223c45b42796834edf9d
sergiogbrox/guppe
/Seção 4/exercicio12.py
565
3.953125
4
""" 12- Leia uma distância em milhas e apresente-a convertida em quilômetros. A fórmula de conversão é: K=1,61*M, sendo K a distancia em quilômetros e M em milhas. """ print('\nDigite uma distância em milhas para ser convertida em quilometros\n') milhas = input() try: milhas = float(milhas) print(f''' "{milhas} milhas" é equivalente a: {milhas * 3.6} quilômetros''') except ValueError: print(f''' "{milhas}" não é um número. Somente numeros são aceitos, reais ou inteiros. Feche o programa e tente novamente.''')
2ec08599413f86e31d80b13b3a7af37d7fbf1c0a
YaChenW/LeetCode
/876. Middle of the Linked List.py
535
3.90625
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def middleNode(self, head, depth=1, stop=-1): """ :type head: ListNode :rtype: ListNode """ if stop == -1: stop = (self.getSize() + 1) // 2 return head if depth == stop else self.middleNode(hean.next, depth + 1, stop) def getSize(self, head): return 1 + self.getSize(head.next) if head.next != Nonde else 0
168fa00ddc607c36de61c958124be6b0856f43a0
k4nuck/practice
/LinkedList.py
2,396
4.1875
4
import os class ListNode(object): def __init__(self): self.next = None self.value = None self.prev = None class LinkedList(object): def __init__(self): self.head = ListNode() self.tail = self.head self.head.value = 1 self.num_nodes = 1 # Add a new node at the head of the list def append(self,node_val): temp_node = ListNode() self.head.next = temp_node temp_node.prev = self.head self.head = temp_node self.head.value = node_val self.num_nodes += 1 # Add a new node before the tail of the list def prepend(self,node_val): temp_node = ListNode() self.tail.prev = temp_node temp_node.next = self.tail self.tail = temp_node self.tail.value = node_val self.num_nodes += 1 # Insert a node at the given node number def insert(self,node_num,node_val): new_node = ListNode() new_node.value = node_val temp_node = self.get_node(node_num) # store node to adjust prev value temp_node2 = temp_node.prev # store prev node to adjust next value new_node.prev = temp_node.prev new_node.next = temp_node temp_node.prev = new_node temp_node2.next = new_node if node_num == 0: self.tail = new_node if node_num == self.num_nodes - 1: self.head = new_node self.num_nodes += 1 # Remove the node number supplied def remove(self,node_num): temp_node = self.get_node(node_num) # get node to remove temp_node2 = temp_node.prev # get previous node to adjust next value temp_node3 = temp_node.next # get next node to adjust prev value temp_node3.prev = temp_node.prev temp_node2.next = temp_node.next del temp_node self.num_nodes -= 1 # Return the pointer to the node number requested. def get_node(self,node_num): if node_num >= self.num_nodes or node_num < 0: print ("out of range") return 0 elif node_num == 0: return self.tail.value elif node_num == self.num_nodes-1: return self.head.value else : temp_node = self.tail for x in range (0,node_num): temp_node = temp_node.next return temp_node # Print the values for all nodes in the list. def print_list(self): temp_node = self.tail for x in range (0,self.num_nodes): print (temp_node.value) temp_node = temp_node.next test_list = LinkedList() for x in range (2,10): test_list.append(x) test_list.print_list() test_list.insert(5,22) test_list.print_list() test_list.remove(6) test_list.print_list()
d58f3293579765b743b4c794596ad1caeaf1461f
tuhiniris/Python-ShortCodes-Applications
/file handling/Read a String from the User and Append it into a File.py
505
4.21875
4
''' Problem Description: ------------------- The program takes a string from the user and appends the string into an existing file. ''' print(__doc__) print('-'*25) fileName=input('Enter file name along with path: ') file3=open(fileName,"a") string=input('Enter string to append: ') file3.write(string) file3.close() print('Contents of appended file: ') print('-'*25) file4=open(fileName,"r") line1=file4.readline() while line1!="": print(line1) line1=file4.readline() file4.close()
84e672eeeabe633e629c5e5c65f0eddccff95798
KrisCheng/HackerPractice
/Python/oop/property.py
1,361
3.78125
4
# @property # -*- coding: utf-8 -*- # without property # class Student(object): # def get_score(self): # return self._score # # def set_score(self, value): # if not isinstance(value, int): # raise ValueError('score is not a integer!') # if value < 0 or value > 100: # raise ValueError('score must be 0~100!') # self._score = value # # s = Student() # s.set_score('ss') # using @property class Student(object): @property def score(self): return self._score @score.setter def score(self, value): if not isinstance(value, int): raise ValueError('score is not a integer!') if value < 0 or value > 100: raise ValueError('score must be 0~100!') self._score = value s = Student() s.score = 10 # practice class Screen(object): @property def width(self): return self._width @property def height(self): return self._height @property def resolution(self): return self._height * self._width @width.setter def width(self, value): self._width = value @height.setter def height(self, value): self._height = value s = Screen() s.width = 1024 s.height = 768 print(s.resolution) assert s.resolution == 786432, '1024 * 768 = %d ?' % s.resolution
46f7374a7bbbced567979f480fbea3c249d40a14
chefmohima/DS_Algo
/min_heap_implementation.py
1,864
3.671875
4
# Min heap implementation class minHeap: def __init__(self): self.heap = [] def insert(self,val): self.heap.append(val) if len(self.heap) > 1: self.restoreUp(len(self.heap)-1) def getMin(self): if self.heap: return self.heap[0] return None def removeMin(self): if len(self.heap) > 1: min = self.heap[0] # swap min with last element self.heap[0], self.heap[-1] = self.heap[-1], self.heap[0] del(self.heap[-1]) self.restoreDown(0) return min if len(self.heap) == 1: return self.heap[0] del(self.heap[0]) else: return None def restoreUp(self, index): # compare with parent and swap as necessary # continue till parent exists and parent > value at index parent_index = (index-1)//2 if parent_index>=0 and self.heap[parent_index] > self.heap[index]: self.heap[index], self.heap[parent_index] = self.heap[parent_index], self.heap[index] self.restoreUp(parent_index) def restoreDown(self,index): minindex = index leftindex = 2*index +1 rightindex = 2*index + 2 if rightindex <= len(self.heap)-1: # find minimum if self.heap[leftindex] < self.heap[minindex]: minindex = leftindex if self.heap[rightindex] < self.heap[minindex]: minindex = rightindex if minindex != index: # need to swap self.heap[minindex], self.heap[index] = self.heap[index], self.heap[minindex] self.restoreDown(minindex) heap = minHeap() heap.insert(12) heap.insert(10) heap.insert(-10) heap.insert(100) print(heap.getMin()) print(heap.removeMin()) print(heap.getMin()) heap.insert(-100) print(heap.getMin())
72e7ff0d8e2efd5db7fff1d5a79b646a0dfda01c
coreyryanhanson/tanzania_water_project
/visualization_functions.py
10,822
3.65625
4
import functools import pandas as pd import seaborn as sns import numpy as np import matplotlib.pyplot as plt class Multiplot(object): """An object to quickly generate multiple plots for each column in a DataFrame""" def __init__(self, df, n_cols=3, figsize=(15, 15), style="darkgrid"): """Sets up the general parameters to be used across all graphs.""" self.df = df self.columns = self.df.columns self.figsize = figsize self.set_cols(n_cols) self.linearity_plots = 5 self.style = style def _multicol_plot_wrapper(func): """Decorator to be used to wrap plotting function to generate and plot multiple matplotlib figures and axes objects for multiple columns.""" @functools.wraps(func) def wrapper(self, *args, **kwargs): self.fig, self.axes = self._generate_subplots() for self.ax_i, self.last_col in enumerate(self.columns): self._determine_ax() func(self, *args, **kwargs) plt.show() return wrapper def _determine_ax(self): """Sets current axis based on iterator and axes object. If only one column, it does not look for a column index.""" row, col = self.ax_i // self.n_cols, self.ax_i % self.n_cols if self.n_cols == 1: self.last_ax = self.axes[row] else: self.last_ax = self.axes[row][col] def _generate_subplots(self): """Creates subplots based on current parameter attributes""" sns.set_style(self.style) return plt.subplots(nrows=self.n_rows, ncols=self.n_cols, figsize=self.figsize) def _plot_qq_manual(self, comparison_df): """Class no longer uses this. Replaced with the generated plots from statsmodels.""" columns = comparison_df.columns ax_kwargs = {x: y for x, y in zip(["x", "y"], columns)} qq_data = pd.DataFrame(columns=columns) for column in columns: qq_data[column] = np.quantile(comparison_df[column], np.arange(0, 1, .01)) return sns.scatterplot(data=qq_data, ax=self.last_ax, **ax_kwargs) def _plot_ccpr(self, model): """Creates a Component and Component Plus Residual plot""" sm.graphics.plot_ccpr(model, 1, ax=self.last_ax) self.last_ax.lines[1].set_color("r") def _plot_qq(self, model): """Creates a qq plot to test residuals for normality.""" sm.graphics.qqplot(model.resid, dist=scs.norm, line='45', fit=True, ax=self.last_ax) def _plot_resid(self, model): """Plots a scatterplot of residuals along a dependant variable""" resid, x = model.resid, df[self.last_col] line = np.array([[x.min(), 0], [x.max(), 0]]).T sns.scatterplot(x, resid, ax=self.last_ax) sns.lineplot(x=line[0], y=line[1], ax=self.last_ax, **{"color": "r"}) self.last_ax.set_title('Residual_plot') self.last_ax.set_ylabel('Residual values') def _plot_resid_hist(self, model): sns.distplot(model.resid, ax=self.last_ax) self.last_ax.set_title('Residual_distribution') self.last_ax.set_xlabel('Residual values') def _plot_yfit_y_pred_v_x(self, model): """Plots a y and y fitted vs x graph""" sm.graphics.plot_fit(model, 1, ax=self.last_ax) def _prediction_df(self, predictions, actual): """Currently unused function that combines predictions and test data into a single dataframe.""" columns, pred_list = ["predicted", "actual"], np.stack((predictions, actual)) return pd.DataFrame(pred_list.T, columns=columns) def _sb_linearity_plots(self, model): """For loop that creates the axes and plots for linearity checks""" self.fig, self.axes = self._generate_subplots() for self.ax_i in np.arange(self.linearity_plots): self._determine_ax() self._sb_linearity_switch(model, self.ax_i) plt.show() def _sb_linearity_switch(self, model, i): """Uses if statement switches to allow different functions to be inserted in the for loop that dynamically sets the axes.""" if i == 0: self._plot_yfit_y_pred_v_x(model) if i == 1: self._plot_resid(model) if i == 2: self._plot_ccpr(model) if i == 3: self._plot_resid_hist(model) if i == 4: self._plot_qq(model) def _set_rows(self, n_plots=False): """Determines the amount of row axes needed depending on the total plots and the column size""" if not n_plots: n_plots = self.df.columns.size self.n_rows = math.ceil(n_plots / self.n_cols) def _test_goldfeld_quandt(self, model, lq, uq): """Runs a Goldfeld Quandt test for heteroscadasticity.""" column = self.last_col lwr = self.df[column].quantile(q=lq) upr = self.df[column].quantile(q=uq) middle_idx = self.df[(self.df[column] >= lwr) & (self.df[column] <= upr)].index idx = [x - 1 for x in self.df.index if x not in middle_idx] gq_labels = ['F statistic', 'p-value'] gq = sms.het_goldfeldquandt(model.resid.iloc[idx], model.model.exog[idx]) return list(zip(gq_labels, gq)) def _test_jarque_bera(self, model): """Runs a Jarque-Bera test for normality""" jb_labels = ['Jarque-Bera', 'Prob', 'Skew', 'Kurtosis'] jb = sms.jarque_bera(model.resid) return list(zip(jb_labels, jb)) def _xyz(self, terms, iterable): """Grabs axis values from a dictionary and inserts the iterable into the first empty instance. Returns a dictionary of only filled axes.""" x, y, z = terms.get("x"), terms.get("y"), terms.get("z") var_list = [x, y, z] for i, var in enumerate(var_list): if not var: var_list[i] = iterable break var_dict = {key: value for key, value in zip(["x", "y", "z"], filter(None, var_list))} return var_dict def _xyz_to_kwargs(self, kwargs, iterable, return_axes=False): axes = self._xyz(kwargs, iterable) new_kwargs = kwargs.copy() new_kwargs.update(axes) if return_axes: return new_kwargs, axes else: return new_kwargs def modify_col_list(self, columns, drop=True): """Allows changes to what columns will be graphed. Default is to drop, but can add columns as well.""" if drop: self.columns = self.columns.drop(columns) else: columns = pd.Index(columns) self.columns = self.columns.append(columns) self.columns = self.columns.drop_duplicates() self._set_rows() def set_cols(self, n_cols): """Changes the amount of plot columns to display and adjusting the rows needed accordingly.""" self.n_cols = n_cols self._set_rows() def sb_linearity_test(self, column, target): """Tests for linearity along a single independant feature and plots associated visualizations.""" self.last_col = column self._set_rows(self.linearity_plots) formula = f'{target}~{column}' model = smf.ols(formula=formula, data=self.df).fit() r_squared, mse = model.rsquared, model.mse_model, rmse, p_values = math.sqrt(mse), model.pvalues coef, intercept = model.params[1], model.params[0] jb = self._test_jarque_bera(model) gq = self._test_goldfeld_quandt(model, .45, .55) print(f"{column} predicting {target}:") print(f"R2: {r_squared}, MSE: {mse}, RMSE: {rmse}:") print(f"Coeficient: {coef}, Intercept: {intercept}") print("") print("P-values:") print(p_values) print("") print("Jarque-Bera:") print(*jb) print("") print("Goldfeld-Quandt:") print(*gq) self._sb_linearity_plots(model) # Resets rows to their defaults self._set_rows() @_multicol_plot_wrapper def sb_multiplot(self, func, kwargs=None, default_axis=False): """Flexible way of calling iterating through plots of a passed Seaborn function. Default axis determines what axis the iterated variables will take on. Leave blank for one dimensional plots.""" if default_axis and kwargs: kwargs = self._xyz_to_kwargs(kwargs, self.last_col) return func(data=self.df, ax=self.last_ax, **kwargs) else: return func(self.df[self.last_col], ax=self.last_ax, **kwargs) #Changes long numeric values and replaces them with more human readable abbreviations. def scale_units(value): if value < .99: new_val = str(round(value,3)) elif value < 1000: new_val = str(round(value)) elif value < 1000000: new_val = str(round(value/1000))+"k" elif value < 1 * 10**9: new_val = str(round(value/(10**6)))+"M" elif value < 1 * 10**12: new_val = str(round(value/(10**9)))+"B" elif value < 1 * 10**15: new_val = str(round(value/(10**12)))+"T" else: new_val = str(value) return new_val #Inverts the log functions put on features. To be applied on ticks, so that the scale is visually condensed but the values # are human readable. def unlog_plot(values, base): to_series = pd.Series(values) exponented = base**to_series return exponented.map(scale_units).values.tolist() #Shows the full breadth of possilbe values and nans for a column of a dataframe. def full_value_counts(df, column): unique = df[column].unique().size totalna = df[column].isna().sum() percent_na = totalna/df[column].size print(f"There are {unique} unique values with {totalna} nan values making up {percent_na*100:.1f}%") for value, count in df[column].value_counts().iteritems(): print(f"{count}-{value}") # Modifications to masked heatmap parameters from lecture notes. def trimmed_heatmap(df, columns, font_scale=1, annot=True): plt.figure(figsize=(15, 10)) corr = df[columns].corr() sns.set(style="white") # Generate a mask for the upper triangle mask = np.zeros_like(corr, dtype=np.bool) mask[np.triu_indices_from(mask)] = True # Set up the matplotlib figure f, ax = plt.subplots(figsize=(11, 9)) # Generate a custom diverging colormap cmap = sns.diverging_palette(220, 10, as_cmap=True) sns.set_context('talk', font_scale=font_scale) # Draw the heatmap with the mask and correct aspect ratio sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.95, center=0, square=True, linewidths=.5, cbar_kws={"shrink": .5}, annot=annot) return plt.show()
ce8a8cb5a96d364ee9a01545c4a27429518aca7c
fikriauliya/CS6.006
/dynamic_programming_test.py
1,489
3.640625
4
import unittest from dynamic_programming import * class DynamicProgrammingTest(unittest.TestCase): def test_fibonacci(self): self.assertEqual(fibonacci(1), 1) self.assertEqual(fibonacci(2), 1) self.assertEqual(fibonacci(3), 2) self.assertEqual(fibonacci(4), 3) self.assertEqual(fibonacci(5), 5) self.assertEqual(fibonacci(6), 8) self.assertEqual(fibonacci(7), 13) self.assertEqual(fibonacci(8), 21) def test_fibonacci_memoization(self): self.assertEqual(fibonacci_memoization(1), 1) self.assertEqual(fibonacci_memoization(2), 1) self.assertEqual(fibonacci_memoization(3), 2) self.assertEqual(fibonacci_memoization(4), 3) self.assertEqual(fibonacci_memoization(5), 5) self.assertEqual(fibonacci_memoization(6), 8) self.assertEqual(fibonacci_memoization(7), 13) self.assertEqual(fibonacci_memoization(8), 21) self.assertEqual(fibonacci_memoization(100), 354224848179261915075) def test_fibonacci_bottom_up(self): self.assertEqual(fibonacci_bottom_up(1), 1) self.assertEqual(fibonacci_bottom_up(2), 1) self.assertEqual(fibonacci_bottom_up(3), 2) self.assertEqual(fibonacci_bottom_up(4), 3) self.assertEqual(fibonacci_bottom_up(5), 5) self.assertEqual(fibonacci_bottom_up(6), 8) self.assertEqual(fibonacci_bottom_up(7), 13) self.assertEqual(fibonacci_bottom_up(8), 21) self.assertEqual(fibonacci_bottom_up(100), 354224848179261915075) if __name__ == "__main__": unittest.main()
e7ea691047aa336b116a8bacead90686cf8cd445
bcdavis/python-scripts
/scripts-2017/1-99.py
1,004
4.65625
5
#1 use for loop to print odd numbers form 1 to 99 """ for i in range(1,100,2): print(i) """ #2 use for loop to print the multiples of 3 from 300 down to 3 """ for i in range(300,2 ,-3): print(i) """ #3 use for loop to print the first power of 2 starting at 2 """ prod = 2 print(prod) for i in range(9): prod *= 2 print(prod) """ #4 write program that asks for two numbers, a and b. #The program should print out the sum of the integers in range a to b (inclusive) #assume b is always bigger than a """ a = int(input("enter the value for a: ")) b = int(input("enter the value for b: ")) total = 0 for i in range(a,b+1): total += i print("the sum is", total) """ #5 write a program that reads an integer value and prints the #sum of all even integers #between 2 and the input value, inclusive. #assume the input is always higher than 2. """ limit = int(input("enter the limit: ")) total = 0 for i in range(2,limit + 1,2): total +=i print("total is",total) """
b221d1b04ce209be539b01022b029425250b2edc
alivcor/leetcode
/20. Valid Parentheses/main.py
525
4
4
def isValid(s): """ :type s: str :rtype: bool """ stack = [] match = {'(': ')', '{': '}', '[': ']'} for x in s: if x == '(' or x == '{' or x == '[': stack.append(x) elif x == ')' or x == '}' or x == ']': if len(stack) > 0 and x == match[stack[len(stack) - 1]]: stack.pop() else: return False # print stack if len(stack) == 0: return True else: return False print isValid("728+(9+2)")
32faf3f2fa4e78271ea6d800ab06838862276e56
Duckancover/02_python_puzzle
/brascets.py
1,114
3.609375
4
# -*- coding: utf-8 -*- """ Created on Mon Dec 4 13:40:20 2017 @author: Oleg.Shcherbinin """ def checkio(expression): d = {"{":1, "[":2, "(":3} e = [] f = {"}":1, "]":2, ")":3} for i in expression: if i in d.keys(): e.append(d[i]) if i in f.keys(): try: if f[i] == e[-1]: e.pop(-1) else: return False except IndexError: return False if len(e) == 0: return True else: return False #These "asserts" using only for self-checking and not necessary for auto-testing if __name__ == '__main__': assert checkio("((5+3)*2+1)") == True, "Simple" assert checkio("{[(3+1)+2]+}") == True, "Different types" assert checkio("(3+{1-1)}") == False, ") is alone inside {}" assert checkio("[1+1]+(2*2)-{3/3}") == True, "Different operators" assert checkio("(({[(((1)-2)+3)-3]/3}-3)") == False, "One is redundant" assert checkio("2+3") == True, "No brackets, no problem" print ("OK")
d392e65a3adbd71c97945b87a4651343c1a7040e
datalyo-dc-m1/tp-python-AwfulJojo
/tp1/guess_number.py
1,594
4.03125
4
# from random import randint # number_to_guess = randint(0, 10) # has_won = False # while has_won is False: # user_propal = int(input("Essayez de deviner le nombre entre 0 et 10 : ")) # while user_propal < 0 or user_propal > 10: # print("Vous devez entrer un nombre entre 0 et 10 !") # user_propal = int(input("Essayez de deviner le nombre entre 0 et 10 : ")) # if number_to_guess == user_propal: # has_won = True # elif number_to_guess > user_propal: # print("Le nombre que vous avez saisi est trop petit") # elif number_to_guess < user_propal: # print("Le nombre que vous avez saisi est trop grand") # print("Vous avez trouvé le nombre ! C'était bien", number_to_guess) from random import randint number_to_guess = randint(0, 100) has_won = False cpt = 0 while has_won is False and cpt < 5: user_propal = int(input("Essayez de deviner le nombre entre 0 et 100 : ")) while user_propal < 0 or user_propal > 100: print("Vous devez entrer un nombre entre 0 et 100 !") user_propal = int(input("Essayez de deviner le nombre entre 0 et 100 : ")) if number_to_guess == user_propal: has_won = True elif number_to_guess > user_propal: print("Le nombre que vous avez saisi est trop petit") elif number_to_guess < user_propal: print("Le nombre que vous avez saisi est trop grand") cpt+=1 if has_won is False: print("Vous n'avez pas trouvé le nombre ! C'était", number_to_guess) if has_won is True: print("Vous avez trouvé le nombre ! C'était bien", number_to_guess)
21552a2d049c363f4bd746e440586fb8c6cf597c
mmiocic/MarketPolo
/MarketPolo_Py38/main.py
7,064
4.03125
4
# Description : This program uses an artificial recurrent neural network called Long Short Term Memory (LSTM) # to predict the closing stock price of a corporation (Apple Inc.) using the past 60 day stock price. # Import libraries import math import pandas_datareader as web import numpy as np import pandas as pd from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, LSTM import matplotlib.pyplot as plt # Constants SCALER = MinMaxScaler(feature_range=(0, 1)) def get_and_check_stock(): stock = input("Enter a ticker symbol: ") print("Checking the stock " + stock + " ...") try: quote = web.DataReader(stock, data_source='yahoo', start='2021-01-04', end='2021-01-04') except: print("Could not find information on the ticker: " + stock) return None return stock def get_data(stock): # Get the stock quote df = web.DataReader(stock, data_source='yahoo', start='2012-01-01', end='2019-12-17') # Show the data pd.set_option('display.max_columns', None) print(df) # Get the number of rows and columns in the data set # print(df.shape) # Visualize the closing price history # plt.figure(figsize=(16,8)) # plt.title('Closing Price History') # plt.plot(df['Close']) # plt.xlabel('Date', fontsize=18) # plt.ylabel('Close Price USD ($)', fontsize=18) # plt.show() # Create a new dataframe with only the 'Close' column data = df.filter(['Close']) # Convert the dataframe to a numpy array dataset = data.values # add np # Get the number of rows to train the model on # using 80% of the data for training and 20% for testing training_data_len = math.ceil(len(dataset) * .8) print("Length of training dataset: " + str(training_data_len)) # Scale the data scaled_data = SCALER.fit_transform(dataset) print(scaled_data) return data, dataset, scaled_data, training_data_len def preprocessing(scaled_data, training_data_len): # Create the training data set # Create the scaled training data set train_data = scaled_data[0:training_data_len, :] # Split the data in x_train and y_train x_train = [] y_train = [] for i in range(60, len(train_data)): x_train.append(train_data[i - 60:i, 0]) y_train.append(train_data[i, 0]) if i <= 61: # use 60 and 61 to see differences in iterations print(x_train) print(y_train) # Convert the x_train and y_train to numpy arrays x_train, y_train = np.array(x_train), np.array(y_train) # Reshape the data # samples, #timesteps, #features --LSTM requireing 3D data with these params # x_train only 2D so reshape it # in this example #features is only 1 which is the Closing price x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1)) return x_train, y_train def build_and_test_lstm(x_train, y_train, dataset, scaled_data, training_data_len): # Build the LSTM model model = Sequential() model.add(LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], 1))) # 50 is number of neurons model.add(LSTM(50, return_sequences=False)) # another LSTM layer but return is False because wont add anymore model.add(Dense(25)) # another densly connected NN layer with 25 neurons model.add(Dense(1)) # Compile the model model.compile(optimizer='adam', loss='mean_squared_error') # Train the model model.fit(x_train, y_train, batch_size=1, epochs=1) # Create the testing data set # Create a new array containing scaled values from 1543 to 2003 (remaining 20%) test_data = scaled_data[training_data_len - 60:, :] # Create teh data sets x_tests, y_tests x_test = [] y_test = dataset[training_data_len:, :] for i in range(60, len(test_data)): x_test.append(test_data[i - 60:i, 0]) # Convert the data to a numpy array x_test = np.array(x_test) # Reshape the data x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1)) # Get the models predicted price values predictions = model.predict(x_test) predictions = SCALER.inverse_transform(predictions) # Get the root mean squared error (RMSE) rmse = np.sqrt(np.mean(predictions - y_test) ** 2) print(rmse) # lower number means more accurate prediction return predictions, model def visualization(data, training_data_len, predictions): # Plot the data plt.style.use('fivethirtyeight') train = data[:training_data_len] valid = data[training_data_len:] valid['Predictions'] = predictions # Visualize the data plt.figure(figsize=(16, 8)) plt.title('Model') plt.xlabel('Date', fontsize=18) plt.ylabel('Close Price USD ($)', fontsize=18) plt.plot(train['Close']) plt.plot(valid[['Close', 'Predictions']]) plt.legend(['Train', 'Validation', 'Predictions'], loc='lower right') plt.show() # Show the valid and predicted prices print(valid) def make_prediction(model, stock): # Get the quote apple_quote = web.DataReader(stock, data_source='yahoo', start='2012-01-01', end='2019-12-17') # Create a new dataframe new_df = apple_quote.filter(['Close']) # Get the last 60 day closing price values and convert the dataframe to an array last_60_days = new_df[-60:].values # Scale the data to be values between 0 and 1 last_60_days_scaled = SCALER.fit_transform(last_60_days) # Create an empty list x_test = [] # Append the past 60 days x_test.append(last_60_days_scaled) # Convert the X_test set to numpy array x_test = np.array(x_test) # Reshape the data x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1)) # Get the predicted scale price predict_price = model.predict(x_test) # undo the scaling predict_price = SCALER.inverse_transform(predict_price) print(predict_price) # Get actual quote of next day apple_quote2 = web.DataReader(stock, data_source='yahoo', start='2019-12-18', end='2019-12-18') print(apple_quote2['Close']) def main(): print("Hagimemasho! \n") ticker = get_and_check_stock() if ticker is not None: close_price_data, close_dataset, scaled_close_dataset, training_length = get_data(ticker) xtrain, ytrain = preprocessing(scaled_close_dataset, training_length) tested_predictions, model = build_and_test_lstm(xtrain, ytrain, close_dataset, scaled_close_dataset, training_length) visualization(close_price_data, training_length, tested_predictions) make_prediction(model, ticker) else: print("Invalid ticker. Please check symbol and try again.") if __name__ == "__main__": main()
5d7344e3f26aaddf774cc11d8fd1e996a2b38c06
Pyk017/Python
/Tkinter/Radio_Button_and_Message_Boxes.py
2,398
3.71875
4
from tkinter import * from tkinter import messagebox root = Tk() root.title("Tkinter") root.iconbitmap("G:\Tkinter\Images\MyIcon.ico") mylabel1 = Label(root, text="This is a Radio Button and Message Box Combo.").pack() option = StringVar() option.set("showinfo") def clickable(val): if val == "showinfo": temp = messagebox.showinfo("Box", "Information Box") Label(root, text="This is a showinfo Message Box!").pack() elif val == "showwarning": temp = messagebox.showwarning("Box", "Warning Box") Label(root, text="This is showwarning Message Box!").pack() elif val == "showerror": temp = messagebox.showerror("Box", "Error Box") Label(root, text="This is a showerror Message Box!").pack() elif val == "askquestion": temp = messagebox.askquestion("Box", "Question Box") Label(root, text="This is a askquestion Message Box!").pack() if temp == "yes": Label(root, text="You have clicked Yes!").pack() else: Label(root, text="You have clicked No!").pack() elif val == "askokcancel": temp = messagebox.askquestion("Box", "Ok-Cancel Box") # print(temp) Label(root, text="This is a askokcancel Message Box!").pack() if temp == "yes": Label(root, text="You have clicked Yes!").pack() else: Label(root, text="You have clicked No!").pack() elif val == "askyesno": temp = messagebox.askquestion("Box", "Yes-No Box") # print(temp) Label(root, text="This is a askyesno Message Box!").pack() if temp == "yes": Label(root, text="You have clicked Yes!").pack() else: Label(root, text="You have clicked No!").pack() Radiobutton(root, text="showinfo", variable=option, value="showinfo").pack(anchor=W) Radiobutton(root, text="showwarning", variable=option, value="showwarning").pack(anchor=W) Radiobutton(root, text="showerror", variable=option, value="showerror").pack(anchor=W) Radiobutton(root, text="askquestion", variable=option, value="askquestion").pack(anchor=W) Radiobutton(root, text="askokcancel", variable=option, value="askokcancel").pack(anchor=W) Radiobutton(root, text="askyesno", variable=option, value="askyesno").pack(anchor=W) button = Button(root, text="Click Me!", command=lambda : clickable(option.get())).pack() root.mainloop()
c3cda5a5c9e98f7bc32286cb95bb2d86d1573a32
nickbaf/Snake-Adventure
/myLib2383.py
13,873
3.640625
4
#***************************************# # Nikolaos Bafatakis, AEM 2383 # # [email protected] # # Snake Adventure Beta v1.10.0 # # # # >>Libraries<< # #***************************************# import pygame, sys,time from pygame.font import SysFont from random import randint from collections import deque from pygame.locals import * from pygame.sprite import * def clear_screen(surf): '''Method for clearing the screen with white color''' surf.fill((255,255,255)) pygame.display.update() def main_screen(surf): '''Method for showing the menu screen on the screen,it loads an image and blits it into the screen...The Menu options are handled within the menu screen loop in main.py''' rect=pygame.Rect(0,0,1280,720) sprite=pygame.image.load('Images/loadscreen.bmp').convert() surf.blit(sprite,(0,0)) pygame.display.update() def createEngine(): '''Method that reads the game data from a file and creates the Engine set that contains every data for each of the levels of the game''' fo = open("data.txt", "r") engine=[] while True: l1=fo.readline() if l1=='': break else: l2=str(fo.readline()) score=str(fo.readline()) c=[] '''Because we read from the file a color in the format(xxx,yyy,zzz) readline converts it to string,so this for-loop takes only the 9 numbers given: xxx,yyy,zzz and discards the commas and the brackets''' for i in range(0,12): if i % 4==0: continue c.append(l2[i]) e=Engine(l1,c,score) #Each engine contains the necessery data for handling each level of the game #of course we can expand the engine class to implement more options for each level engine.append(e) return engine class Engine(): '''This class represents a level in the game,it stores all the necessery info for hadling each level of the game.''' def __init__(self,objective,c,s): '''Basic constractor that stores: i)The Goal of the level(objective) ii)The colour of the level(c) iii)The number of points required to win the level''' self.objective=objective self.color=[] self.color.append(int(c[0])*100+int(c[1])*10+int(c[2])) self.color.append(int(c[3])*100+int(c[4])*10+int(c[5])) self.color.append(int(c[6])*100+int(c[7])*10+int(c[8])) self.score=s class Option(Sprite): '''This class represents the options for the main menu.With this class a minor animation effect is implemented in the main menu of the game.''' def __init__(self,Xaxis,Yaxis,txt,step,color,dimX=300,dimY=50,speed=2): '''Basic constractor that handles: i)the text(e.x Start,Quit)(txt) ii)the step, in the animation were the text gets draged from the left we can add a step in order to seperate each animation.(Note in the main menu screen the "Quit" tile makes a slight delay) iii)the color of the text iv)The X axis and the Y axis that the text is shown.''' self.Xaxis=Xaxis self.Yaxis=Yaxis Sprite.__init__(self) self.rect=pygame.Rect(Xaxis-2000-step,Yaxis,dimX,dimY) self.t=text(txt,color,70) def move(self,surf): '''The animation handler that moves the text into the screen from the outer left to the the point specified form the user in the Xaxis and Yaxis.''' flag=True if self.rect.x<self.Xaxis: self.rect.move_ip(30,0) flag=False #print(self.rect.x,self.rect.y) self.t.render(surf,self.rect.x,self.rect.y) return flag def pos(self): '''Method for returning the position of the option text.This method has been kept only for debug perposes''' return (Xaxis,Yaxis) class text(): '''Class for printing text to screen.''' def __init__(self,t,color,size): '''Constractor that uses pygame.font.SysFont to build the text''' self.t=t self.font=pygame.font.SysFont('Calibri',size,True) self.text=self.font.render(self.t,True,color) def colorChange(self,color): '''Method for changing the color of the text''' self.text=self.font.render(self.t,True,color) def render(self,surf,x,y): '''Method for bliting the text into a surface''' surf.blit(self.text,(x,y)) class Score(): '''This class implements a scoreboard that keeps track of time and the player's score''' def __init__(self): '''Constractor that: i)initializes the time,score and total score''' self.score=0 self.level=50 #THE TIME that is used in the game. self.time_now=100 self.start_time=0 self.totalscore=0 def start_timer(self): '''Method for capturing the current time''' self.start_time=time.time() def changeScore(self,apple): '''Method for changing the score.''' if apple == 1: #Standard Aapl self.score += 50 self.totalscore +=50 elif apple == 2:#Luxury Aalp,NOT used in this game self.score +=250 self.totalscore+=250 elif apple ==3:#Lives,that isn't used either.Maybe in a later version(!). self.lives -=1 def printScore(self, surf): '''Method that blits the score and the remaining time into the screen''' BLACK = (0, 0, 0) WHITE = (255, 255, 255) score_now=text('Score: '+str(self.score),(255,200,5),30) score_now.render(surf,1050,2) self.time_now=int(self.level+self.start_time-time.time()) t=text('Time: '+str(self.time_now),(255,200,5),30) t.render(surf,12,5) class Direction: '''Class that represents a direction. When a snake's tail is due to turn into a direction it will be the coordinates(x,y) that will tell the tail where to turn''' def __init__(self,x,y,d): self.xAxis=x self.yAxis=y self.direction=d class Aapl(Sprite): '''Aapl(Apple Inc. stock symbol in NASDAQ), is as you imagined the apple that the snake eats. it spawns randomly into the screen in size 30x30 pixels''' def __init__(self,dimX=30, dimY=30): '''Basic contstructor for Aapl which handles: i)the X and Y cordinates in the screen, which are produced in random order ii)image of the Aapl.''' Sprite.__init__(self) self.createX=randint(30,1250) self.createY=randint(30,690) self.rect=pygame.Rect(self.createX, self.createY, dimX, dimY) self.image=pygame.image.load('Images/aapl.png') self.transimage = pygame.transform.scale(self.image, (dimX, dimY)) def projectAapl(self,surf): '''Method for blitting the Aapl in screen''' surf.blit(self.transimage, self.rect) class Snake(Sprite): '''This class represents the Snake used in the game''' def __init__(self, createX, createY,img,\ dimX=30, dimY=30, speedX=1): '''Constructor that gives birth to a little tiny snake 30 by 30 pixels.This constructor handles: i)X and Y cordinates ii)Image of the Snake iii)The orientation which the snake moves is represented by boolean variables. iv)Speed of the snake which is 1 pixel per frame.Changing this requires further modification of the game code.''' Sprite.__init__(self) self.rect=pygame.Rect(createX, createY, dimX, dimY) self.image=pygame.image.load(img) self.transimage = pygame.transform.scale(self.image,(dimX,dimY)) self.moveLeft=False self.moveRight=False self.moveUp=False self.moveDown=False self.speedX=speedX self.corners=deque([]) if(img=='Images/head.png'):#Boolean variable to recognise the head of the snake self.head=True else: self.head=False def tailTurn(self,x,y,direction): '''Overiding Method for turning the tail of the snake''' pass def resetMovement(self): '''Resets the movement of the snake''' self.moveLeft=False self.moveRight=False self.moveUp=False self.moveDown=False def getMove(self): '''Methof that returns a string representation of the direction of the snake that it's currently moving at.''' if self.moveRight: return 'Right' elif self.moveLeft: return 'Left' elif self.moveUp: return 'Up' else: return 'Down' def setMove(self,move): '''Method that takes as argument a string representation of a direction(e.x Right,Up) and sets this direction to the snake.''' if move=='Right': self.moveRight=True elif move=='Left': self.moveLeft=True elif move=='Up': self.moveUP=True else: self.moveDown=True def move(self, surf, horiz=800):#!!!!!!!!DES HORIZ '''Method for moving the snake in the screen. After checking to which direction the snake wants to be moved, then it moves the rectangle and applies the right image to the snake .We have 4 images for the head representing 4 different directions.Appling this policy, that with the change of movement we change the picture instead than rotating the original one;was made in order to make the code faster and more reliable.This solution of replacing the picture was applied in the optimization process of the code''' if self.moveLeft: self.rect.move_ip(-self.speedX, 0) self.transimage = pygame.transform.scale(pygame.image.load('Images/headLeft.png'),(30,30)) elif self.moveRight: self.rect.move_ip(self.speedX, 0) self.transimage = pygame.transform.scale(pygame.image.load('Images/headRight.png'),(30,30)) elif self.moveUp: self.rect.move_ip(0,-self.speedX) self.transimage = pygame.transform.scale(pygame.image.load('Images/headUp.png'),(30,30)) elif self.moveDown: self.rect.move_ip(0,self.speedX) self.transimage = pygame.transform.scale(pygame.image.load('Images/headDown.png'),(30,30)) surf.blit(self.transimage, self.rect) class Tail(Snake): '''This class represents a tail of the little snake.It inherits from the class Snake, and each snake has a couple number of tails.''' def __init__(self, createX, createY,img,\ dimX=30, dimY=30, speedX=1): Snake.__init__(self,createX, createY,img) def tailTurn(self,x,y,direction): '''Method for appending in the queue a turn in the Snake's tail''' a=Direction(x,y,direction) self.corners.append(a) def setMove(self,move): if move=='Right': self.moveRight=True elif move=='Left': self.moveLeft=True elif move=='Up': self.moveUP=True else: self.moveDown=True def move(self, surf, horiz=800): '''Method for moving the tail of the snake. Every time the head turns, a direction object is created with attributes: the direction of the snake and the coordinate(x,y) in which when the tail reaches, it must turn.''' if(len(self.corners)>0): #If the queue isn't empty, meaning that the tails must turn somewhere a=self.corners[0] #pop the first direction #print(a.xAxis,self.rect.x,a.yAxis,self.rect.y) if a.xAxis==self.rect.x and a.yAxis==self.rect.y: #if the current position of the tail matches the position in which the tail must turn self.resetMovement() #reset the tail's movement movement=a.direction #take the direction from a and set it to the tail if movement=='Down': self.moveDown=True elif movement=='Up': self.moveUp=True elif movement=='Right': self.moveRight=True elif movement=='Left': self.moveLeft=True self.corners.popleft() #remove the direction from the queue if self.moveLeft: self.rect.move_ip(-self.speedX, 0) elif self.moveRight: self.rect.move_ip(self.speedX, 0) elif self.moveUp: self.rect.move_ip(0,-self.speedX) elif self.moveDown: self.rect.move_ip(0,self.speedX) surf.blit(self.transimage, self.rect) class OST(): '''Method that handles the Music of the Game''' def __init__(self,filename): '''Constructor that builds a Sound file gained from pygame.mixer''' self.s=pygame.mixer.Sound(filename) def starti(self,i): '''Method for starting the playback of the sound''' self.channel=self.s.play(i) def start(self): self.channel=self.s.play() def stop(self): '''Method for stoping the playback of the sound''' self.s.stop() def pause(self): '''Method for pausing the playback of the sound''' pygame.mixer.init() self.channel.pause() def unpause(self): '''Method for unpausing the playback of the sound.This method is not working(yet)!!!!''' self.channel.unpause()
264d742b5948faf19305f86d3d36f54eeb3fd62f
heneryville/aind-udacity
/isolation/tests/reachability_test.py
2,725
3.515625
4
import unittest import isolation import game_agent from reachability import * from importlib import reload class ReachabilityTest(unittest.TestCase): def test_it_finds_reachability_on_open_board(self): player1 = "Player 1" player2 = "Player 2" game = isolation.Board(player1, player2, 4,4) """ 3|X|3|2 -------- 2|3|2|1 -------- 1|2|1|4 -------- 2|3|2|3 """ reachables = reachability(game,(0,1)) self.assertEqual([p[0] for p in reachables.pairs()],[3,2,1,2,0,3,2,3,3,2,1,2,2,1,4,3]) def test_it_finds_reachability_on_open_board_another_position(self): player1 = "Player 1" player2 = "Player 2" game = isolation.Board(player1, player2, 4,4) game.set((0,1),'A') """ 5|A|3|2 -------- 2|1|4|3 -------- 3|4|1|2 -------- B|3|2|5 """ reachables = reachability(game,(3,0)) self.assertEqual([p[0] for p in reachables.pairs()],[5,2,3,0,float("inf"),1,4,3,3,4,1,2,2,3,2,5]) def test_it_gives_inf_on_unreachables(self): player1 = "Player 1" player2 = "Player 2" game = isolation.Board(player1, player2, 4,4) game.set((1,1),'/') game.set((2,2),'/') """ 3|X|3|∞ -------- 4|/|2|1 -------- 1|2|/|4 -------- ∞|3|2|3 """ reachables = reachability(game,(0,1)) self.assertEqual([p[0] for p in reachables.pairs()],[3,4,1,float("inf"),0,float("inf"),2,3,3,2,float("inf"),2,float("inf"),1,4,3]) def test_it_finds_oppossible_reachability(self): player1 = "Player 1" player2 = "Player 2" game = isolation.Board(player1, player2, 4,4) """ Reach for A 3|A|3|2 -------- 2|3|2|1 -------- 1|2|1|4 -------- B|3|2|3 Reach for B 5|A|3|2 -------- 2|1|4|3 -------- 3|4|1|2 -------- B|3|2|5 Combined 3|A | 3|2 ---------- 2|-1| 2|1 ---------- 1| 2| 1|-2 ---------- B| 3|-1|3 """ reachables = opposed_reachability(game,(0,1),(3,0)) self.assertEqual([p[0] for p in reachables.pairs()],[3,2,1,0,0,-1,2,3,3,2,1,2,2,1,-2,3]) def vest_it_runs_in_realistic_time(self): player1 = "Player 1" player2 = "Player 2" size_x = 1000 size_y = 100 game = isolation.Board(player1, player2, size_x,size_y) reachables = reachability(game,(0,1)) if __name__ == '__main__': unittest.main()
3f81ae070a09cd33d6075a74a0baedaad99bd4f9
ParkDAY/basic1
/basic1.py
1,288
3.5
4
#직원들의 급여를 5%인상하고 거주 지역을 파악하는 코드 SALARY_RAISE_FACTOR=0.05 # 5%인상하기 위한 변수 STATE_CODE_MAP = {'WA': 'Washington', 'TX': 'Texas'} # key와 value를 할당하는 문법{} def update_employee_record(rec): # def는 define. 즉 정의하는 것. rec은 딕셔너리를 사용하는 매개변수. old_sal = rec['salary'] new_sal = old_sal * (1 + SALARY_RAISE_FACTOR) rec['salary'] = new_sal state_code = rec['state_code'] rec['state_name'] = STATE_CODE_MAP[state_code] input_data = [ {'employee_name': 'Susan', 'salary': 10000.0, 'state_code': 'WA'}, {'employee_name': 'Ellen', 'salary': 7500.0, 'state_code': 'TX'} ] for rec in input_data: #input_data 성분을 변수로 하는 반복문을 만드는 for in 문법 update_employee_record(rec) name = rec['employee_name'] salary = rec['salary'] state = rec['state_name'] print(name + ' now lives in ' + state) print(' and makes $' + str(salary)) a=100 b=1.2 c=3E+3 d="abc" print(type(a)) print(type(b)) print(type(c)) print(type(d)) print("abc") print("'abc'") print('"abc"') print("abc"[2]) print("abc"[1]) print("abcd"[1:3]) my_list = ["a","b","c"] my_set = set(my_list) my_tuple = tuple(my_list) print(my_list)
b0f10b174ed1b6c19816d7cd6363164ecc977446
JasonMace/Tic-Tac-Toe_final
/Problems/Party time/main.py
153
3.6875
4
names = list() actual = "" while actual != ".": actual = input() if actual != ".": names.append(actual) print(names) print(len(names))
64c50d61c43dca374d27774c8e382634fae4191c
AdvonKoulthar/DanzaharArteest
/tooltip.py
3,212
3.609375
4
import tkinter as tk import math class Example(tk.Frame): def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) self.l1 = tk.Label(self, text="Hover over me") self.l2 = tk.Label(self, text="", width=40) self.l1.pack(side="top") self.l2.pack(side="top", fill="x") self.l1.bind("<Enter>", self.on_enter) self.l1.bind("<Leave>", self.on_leave) def on_enter(self, event): self.l2.configure(text="Hello world") def on_leave(self, enter): self.l2.configure(text="") ##if __name__ == "__main__": ## root = tk.Tk() ## Example(root).pack(side="top", fill="both", expand="true") ## root.mainloop() def showStats(who): statReadout = tk.Tk() statReadout.title('Player Stats') statReadout.geometry('400x600-50+50') txt = who.name + " the " + who.race name = tk.Label(statReadout,text=txt,background="red") name.grid(column=0,columnspan=20,sticky='N') txt = math.floor(who.hp_cur) txt2 = math.floor(who.hp_max) txt = str(txt) + "/" + str(txt2) health = tk.Label(statReadout,text="Health",background="red") health.grid(column = 0,row=2,columnspan=2,sticky="W") healthc = tk.Label(statReadout,text=txt) healthc.grid(column = 0,row=3,columnspan=2,sticky="W") txt = math.floor(who.experience) txt2 = who.level*100 txt = str(txt) + "/" + str(txt2) exp = tk.Label(statReadout,text="Experience",background="Blue",fg="cyan") exp.grid(column = 2,row=2,columnspan=2,sticky="W") expc = tk.Label(statReadout,text=txt) expc.grid(column = 2,row=3,columnspan=2,sticky="W") attsh = tk.Label(statReadout,text="Attributes",background="cyan") attsh.grid(column=5,row=2,columnspan=2,sticky="W") skl = (who.strength-math.floor(who.strength))*10 float(skl) txt = "Strength " + str(math.floor(who.strength)) + "/%0.2f%%" % (skl) attstr = tk.Label(statReadout,text=txt) attstr.grid(column=5,row=3,columnspan=2,sticky="W") skl = (who.dexterity-math.floor(who.dexterity))*10 float(skl) txt = "Dexterity " + str(math.floor(who.dexterity)) + "/%0.2f%%" % (skl) attdex = tk.Label(statReadout,text=txt) attdex.grid(column=5,row=4,columnspan=2,sticky="W") skillh =tk.Label(statReadout,text="Skills",background="orange") skillh.grid(column=0,row=5,columnspan=2,sticky="W") txt = "Unarmed " + str(math.floor(who.unarmed)) skun = tk.Label(statReadout,text=txt) skun.grid(column=0,row=6,columnspan=1,sticky="W") txt = "Dagger " + str(math.floor(who.dagger)) skda = tk.Label(statReadout,text=txt) skda.grid(column=0,row=7,columnspan=1,sticky="W") txt = "Sword " + str(math.floor(who.sword)) sksw = tk.Label(statReadout,text=txt) sksw.grid(column=0,row=8,columnspan=1,sticky="W") skl = (who.survivalist-math.floor(who.survivalist))*10 float(skl) txt = "Survivalist " + str(math.floor(who.survivalist)) + "/%0.2f%%" % (skl) sksu = tk.Label(statReadout,text=txt) sksu.grid(column=2,row=6,columnspan=1,sticky="W") txt = "Block " + str(who.block) skbl = tk.Label(statReadout,text=txt) skbl.grid(column=2,row=7,columnspan=1,sticky="W")
542f339220419b31ca91c909d33a8da4bbec4b63
gguillamon/PYTHON-BASICOS
/python_ejercicios basicos_II/Ejercicio9.py
530
3.9375
4
# 9.- Escribir un programa que pida cuatro números enteros por teclado y determine el mayor y el # 2 # menor de los cuatro números. Ejemplo: # Introduzca 4 números enteros: 20 34 10 -18 # Mayor número: 34 # Menor número: -18 mayor=1 menor=0 numeros=[] for i in range(4): elementos=int(input("Introduzca un numero: ")) numeros.append(elementos) if numeros[i]>mayor: mayor=numeros[i] elif numeros[i]<menor: menor=numeros[i] print("El mayor es %s y el menor es %s " %(mayor,menor))
79cc62b5e9eb6f6ceb412579886bca1b8868298d
serdarkocerr/Python_Calismalar
/ornekler.py
15,732
4.03125
4
#!/usr/bin/env python # coding: utf-8 # In[3]: sayi = 1; while(sayi<10): print(sayi) sayi = sayi+1 # In[4]: for sayi in range(10): print(sayi) # In[5]: for sayi in range(1,10): print(sayi) # In[6]: for sayi in range(10,1,-1): print(sayi) # In[7]: basariNotu = 50; if(basariNotu > 50): print("Basarili :)") else: print("Basarisiz :(") # In[8]: isim =input("isminizi klavyeden giriniz ") print(isim) # In[9]: sayi1 = int(input("sayi1 giriniz : ")) sayi2 = int(input("sayi2 giriniz : ")) print("sayi1 + sayi2 : " , sayi1+sayi2) # In[10]: import os print ("Kullanıcı adı: ", os.environ["USERNAME"]) print ("Bilgisayar adı: ", os.environ["COMPUTERNAME"]) print ("Ev dizini: ", os.environ["HOMEPATH"]) print ("İşlemci: ", os.environ["PROCESSOR_IDENTIFIER"]) print ("İşlemci sayısı: ", os.environ["NUMBER_OF_PROCESSORS"]) print ("İşletim sistemi:", os.environ["OS"]) # In[11]: # harf sayılarının toplamı from collections import Counter print (Counter('bilisim sistemleri')) # In[12]: import sys print (sys.version) # In[15]: ### 2. slayt def ekran_goruntu(): print ("Sakarya Üniversitesi") print ("Bilgisayar ve Bilişim Bilimleri Fakültesi") print ("Sakarya") ekran_goruntu() #function call # In[16]: def toplamaIslemi(x, y): toplam = x + y ekran = ' {} ve {} sayılarının toplamı: {}.'.format(x, y, toplam) print(ekran) def main(): toplamaIslemi(10, 20) # parametre gönderilmesi toplamaIslemi(10000, 20000) # parametre gönderilmesi a = int(input("bir sayi giriniz: ")) b = int(input("yeni bir sayi giriniz: ")) toplamaIslemi(a, b) # parametre gönderilmesi main() # In[21]: def print_menu(): print(35*"-" + "MENU" + 35*"-") print("sayi girmek için 1") print("sayilari toplamak için 2") print("sayilari çıkartmak için 3") print("sayilari çarpmak için 4") print("sayilari bölmek için 5") print("programdan çıkış için 6") print(70*"-") donguDegiskeni = True while(donguDegiskeni): print_menu() giris = int(input("islem giriniz:")) if(giris == 1): sayi1 = int(input("sayi1: ")) sayi2 = int(input("sayi2: ")) elif (giris == 2): print("toplamları : " , sayi1+sayi2) elif (giris == 3): print("farklari :" , sayi1-sayi2) elif (giris == 4): print("çarpımları: " , sayi1*sayi2) elif (giris == 5): print("bölümleri = ", sayi1/sayi2) elif (giris == 6): donguDegiskeni = False; else: print("yanlis sayi girdiniz. Tekrar giriniz.") # In[22]: liste = [i for i in range(10)] print (liste) print liste = list(range(10)) print (liste) # In[23]: ## HAFTA 3 sayilar = [0] * 10 print (sayilar) # In[24]: #range(start, stop, step) for i in range(3, 16, 3): print(i) # In[25]: sicaklik_degerleri = [19, 10, 13, 12, 11, 9, 8] hafta_ici = sicaklik_degerleri[0:5] print (sicaklik_degerleri) print (hafta_ici) # In[26]: #SLICING - Dilimleme sicaklik_degerleri = [19, 10, 13, 12, 11, 9, 8] # bütün liste, sondan iki eleman hariç hafta_ici = sicaklik_degerleri[-7:-2] print (sicaklik_degerleri) print (hafta_ici) # In[27]: #SLICING - Dilimleme hafta_ici=sicaklik_degerleri[-1] # listedeki son eleman print (hafta_ici) hafta_ici=sicaklik_degerleri[-2:] # listedeki son iki eleman print (hafta_ici) hafta_ici=sicaklik_degerleri[:-2] # son iki eleman hariç bütün elemanlar print (hafta_ici) # In[48]: #SLICING – Dilimleme sicaklik_degerleri = [19, 10, 13, 12, 11, 9, 8] hafta_ici=sicaklik_degerleri[::2] # baştan sona kadar 0,2,4,6,8. elemanlar. 2 burada step demek. print (hafta_ici) hafta_ici=sicaklik_degerleri[::-1] # Sondan başlayarak bütün elemanlar (-1 step ters git demektir.) print (hafta_ici) hafta_ici= sicaklik_degerleri[1::-1] # Sondan başlayarak ilk iki eleman (-1 step ters git demektir.) print (hafta_ici) hafta_ici= sicaklik_degerleri[:-3:-1] # Sondan başlayarak son iki elemanlar print (hafta_ici) hafta_ici= sicaklik_degerleri[-3::-1] # Sondan başlayarak son iki eleman hariç print (hafta_ici) hafta_ici= sicaklik_degerleri[-3::1] # Sondan başlayarak son iki eleman hariç print (hafta_ici) # In[47]: nums = [10, 20, 30, 40, 50, 60, 70, 80, 90] print (nums[-2:1:-1]) print (nums[-2:1:-3]) print (nums[1::-1]) print (nums[1:]) print (nums[-1::-1]) # In[51]: def main(): # Liste paket_isimleri = ['AX', 'GP', 'NAV', 'SL', 'CRM'] # ekran çıktısı print('Listedeki veriler:') print(paket_isimleri) # ekran çıktısı print('Listedeki 2 veri:') print(paket_isimleri[2]) # sıfırıncı elemanın silinmesi. paket_isimleri.remove('AX') print ("ilk eleman listeden silindi") print(paket_isimleri) # ekran çıktısı print('listedeki son elemanın silinmesi:') print(paket_isimleri) paket_isimleri.pop() print('Listeye veri silme:') print(paket_isimleri) # Call the main function. main() # In[52]: cars = ['bmw', 'audi', 'toyota', 'subaru', 'fiat'] print("Here is the original list:") print(cars) print("\nHere is the sorted list:") print(sorted(cars)) print("\nHere is the reverse alphabetical list:") print(sorted(cars, reverse=True)) print("\nHere is the original list again:") print(cars) # In[54]: ## HAFTA 4 tuple01=() # boş bir tuple a = (100) print (a) # In[55]: tuple002 = (100, 200, 300, 350) print (tuple002) print (tuple002[-1]) print (tuple002[0:1]) print (tuple002[0:3]) print (tuple002[2]) # In[56]: #tuple’a yeni eleman ilavesi tuple003 = (100, 200, 300, 400) print (tuple003) yeniTuple = tuple003 yeniTuple += (500,) tuple003 += (5000,) print (yeniTuple) print (tuple003) # In[57]: #İndex Oluşturma: #Belli bir tuple elemanına erişebilmek için parantez içindeki konum numarası belirtilir. #Pozitif ve negatif indeksleme yapılabilir. sicaklik_degeri = (10, 13, 14, 9, 8, 16, 11) print (sicaklik_degeri[0]) print (sicaklik_degeri[2]) print (sicaklik_degeri[-1]) print (sicaklik_degeri[-6]) # In[59]: #Tuple Sıralama(Ascending Order, Sorting) sicaklik_degeri = (10, 13, 14, 9, 8, 16, 11) sicaklik_degeri = sorted(sicaklik_degeri) print (sicaklik_degeri) # In[60]: #Tuple Büyükten Küçüğe Sıralama(Descending Order, Sorting) sicaklik_degeri = (10, 13, 14, 9, 8, 16, 11) sicaklik_degeri = sorted(sicaklik_degeri, reverse = True) print (sicaklik_degeri) # In[64]: liste= [10, 30, 50] tuple=(60,65,70,"serdar") print (liste) print (tuple) #veri elemanı değişikliği liste[1]=100 #tuple[1]=300 #TypeError: 'tuple' object does not support item assignment print (liste) print (tuple) # In[65]: # tuple'ın 1. elemanını değiştirmek için liste= [10, 30, 50] tuple=(60,65,70) print (liste) print (tuple) #veri elemanı değişikliği liste[1]=100 #tuple[1] elemanın değerinin 300 olarak değiştirilmesi n=1 tuple= tuple[ : n] + (300 ,) + tuple[n + 1 : ] print (liste) print (tuple) # In[66]: nested_tuple = (4, 5, 6), (7, 8, 9, 10) print (nested_tuple) # In[67]: tuple=('sakarya', 'universitesi') * 4 print (tuple) # In[68]: tuple = (1, 2, 2, 2, 3, 4, 2, 3, 6, 8, 2) print (tuple.count(2)) # 2 rakamının sayılması # In[69]: port = {22: "SSH", 23: "Telnet" , 53: "DNS", 80: "HTTP" } print (port) # In[70]: ERP = {"AX": "MS AXAPTA", "NAV" :"MS Navision"} print (ERP) print (ERP['AX']) print (ERP['NAV']) # In[72]: #copy() fonksiyonu ERP = {"AX": "MS AXAPTA", "NAV" :"MS Navision", "SAP": "Systems Applications and Products"} print print (ERP) print print (ERP['AX']) print (ERP['SAP']) ERPDict=ERP.copy() #Dict kopyalama print (ERPDict) print(ERP.get('AX')) # In[77]: # copy() fonksiyonu ERP = {"AX": "MS AXAPTA", "NAV" :"MS Navision", "SAP": "Systems Applications and Products"} print print (ERP) print print (ERP['AX']) print (ERP['SAP']) ERPDict=ERP.copy() #Dict kopyalama print (ERPDict) print ERP["Odoo"]= "Odoo ERP Software" #dict veri yapısına üye ilave etme print (ERP) print (ERP.get("SAP", "not found")) #dict veri yapısında sorgu print (ERP.get("ABC", "not found")) #dict veri yapısında sorgu # In[79]: ERP = {"AX": "MS AXAPTA", "NAV" :"MS Navision", "SAP": "Systems Applications and Products"} print (ERP) print ERP["Odoo"]= "Odoo ERP Software" #dict veri yapısına üye ilave etme print (ERP) print (ERP.get("SAP", "not found"))#dict veri yapısında sorgu print (ERP.setdefault('AX', "unknown")) #key ile sorgu print (ERP.setdefault('Dolibarr', "Dict veri yapısında mevcut değildir")) #key ile sorgu print (ERP) # In[86]: # in Sorguda True or False boolean sonuç döndürmektedir. ERP = {"AX": "MS AXAPTA", "NAV" :"MS Navision", "SAP": "Systems Applications and Products"} print (ERP) print ("SAP" in ERP) #dict veri yapısında sorgu print ("Adempiere" in ERP) #dict veri yapısında sorgu # In[89]: #Dictionary veri yapısındaki key’leri listeler ERP = {"AX": "MS AXAPTA", "NAV" :"MS Navision", "SAP": "Systems Applications and Products"} print (ERP) print print (ERP.keys()) print (ERP.values()) # In[91]: ERP = {"AX": "MS AXAPTA", "NAV" :"MS Navision", "SAP": "Systems Applications and Products"} print (ERP) print ERP.items() # item() metodu print (ERP.items()) #clear() metodu ERP.clear() print (ERP) # In[92]: #Dictionary yapısı farklı key- value türlerini alabiliyor. dict = {'Marka': 'Toyota', 'Yıl': 2016, 1:'Test'} print ("Marka : %s" % dict.get('Yıl')) print ("Value : %s" % dict.get('Servis', "Mevcut Değil")) # In[93]: #HAFTA 5 - 6 #pandas kütüphanesi: # versiyon belirleme import pandas as pd pd.__version__ # In[94]: # install edilen kütüphaneler pd.show_versions() # In[96]: #Python versiyon kontrol: import sys print(sys.version) # In[97]: #pandas veri yapısı olarak 2 yapı kullanılmaktadır: #Series #DataFrame import pandas as pd #seri = pd.Series([data], index=[index]) sayilar = pd.Series([0, 1, 4, 9, 16, 25, 36, 49], name='Sayi Kareleri') print (sayilar) # In[100]: #index oluştruma import pandas as pd okyanus_derinlik= pd.Series([1205, 3646, 3741, 4080, 3270],index=['Kuzey Denizi', 'Atlas', 'Hint', 'Pasifik', 'Güney Okyanusu']) print(okyanus_derinlik) # In[101]: #indeks ve dilimleme(Slicing) import pandas as pd okyanus_derinlik = pd.Series([1205, 3646, 3741, 4080, 3270], index=['Kuzey Denizi', 'Atlas', 'Hint', 'Pasifik', 'Güney Okyanusu']) print (okyanus_derinlik) print print (okyanus_derinlik[2]) print print (okyanus_derinlik[0:3]) #dilimleme işlemi print print (okyanus_derinlik['Pasifik']) print print (okyanus_derinlik['Atlas':'Pasifik'])#dilimleme işlemi # In[102]: #Dictionary ile Series deklarasyonu (tanımlaması) # Dictionary ile Series deklarasyonu import pandas as pd okyanus_derinlik = pd.Series({ 'Kuzey Denizi': 1205, 'Atlas': 3646, 'Hint': 3741, 'Pasifik': 4080, 'Güney Okyanusu': 3270 }) print (okyanus_derinlik) # In[103]: import pandas as pd okyanus_derinlik = pd.Series({ 'Kuzey Denizi': 1205, 'Atlas': 3646, 'Hint': 3741, 'Pasifik': 4080, 'Güney Okyanusu': 3270 }) print (okyanus_derinlik) print max_derinlik = pd.Series({ 'Kuzey Denizi': 5567, 'Atlas': 8486, 'Hint': 7906, 'Pasifik': 10803, 'Güney Okyanusu': 7075 }) print (max_derinlik) # In[105]: #DATA FRAME yapısı import pandas as pd okyanus_derinlik = pd.Series({ 'Kuzey Denizi': 1205, 'Atlas': 3646, 'Hint': 3741, 'Pasifik': 4080, 'Güney Okyanusu': 3270 }) print (okyanus_derinlik) print(35*"-") max_derinlik = pd.Series({ 'Kuzey Denizi': 5567, 'Atlas': 8486, 'Hint': 7906, 'Pasifik': 10803, 'Güney Okyanusu': 7075 }) print print(max_derinlik) print(35*"-") derinlikler = pd.DataFrame({ 'ortalama Derinlik (metre)': okyanus_derinlik, 'Maksimum Derinlik (metre)':max_derinlik }) print print (derinlikler) # In[106]: #date_rage kullanımı import pandas as pd dates = pd.date_range('20170101', periods=14) print (dates) # In[107]: import pandas as pd import numpy as np import matplotlib as plt df = pd.read_csv("https://raw.githubusercontent.com/yew1eb/DM-Competition-Getting-Started/master/AV-loan-prediction/train.csv") #pandas kullanılarak veri setinin dataframe’e alınması print (df.head(5))# veri seti başlangıcı ilk 5 veri listesi # In[108]: #describe() fonksiyonu ile veri setindeki nümerik alanlar incelebilir. print (df.describe()) # In[109]: #Nümerik olmayan alanların frekans dağılımı açısından analizi: print (df['Property_Area'].value_counts()) # In[121]: #Gelir Analizi Histogram diyagramı: df['ApplicantIncome'].hist(bins=50) # In[126]: print (len(df)) #toplam veri sayısı print (len(df.columns)) #toplam sütun sayısı # In[131]: #HAFTA 7-8 #DataFrame yapısının Series dictionary nesnesi ile oluşturulması: # stockSummaries bir dictionary'dir. Keyler 'AMZN' gibi stringler, value'ları ise seridir. import pandas as pd import numpy as np # EPS hisse başına gelir # Share outstanding ödenmemiş hisse # Beta risk # P/E Fiyat kazanç oranı # Market cap şirketin değeri stockSummaries={ 'AMZN': pd.Series([346.15,0.59,459,0.52,589.8,158.88], index=['Closing price','EPS', 'Shares Outstanding(M)', 'Beta', 'P/E','Market Cap(B)']), 'GOOG': pd.Series([1133.43,36.05,335.83,0.87,31.44,380.64], index=['Closing price','EPS','Shares Outstanding(M)', 'Beta','P/E','Market Cap(B)']), 'FB': pd.Series([61.48,0.59,2450,104.93,150.92], index=['Closing price','EPS','Shares Outstanding(M)', 'P/E', 'Market Cap(B)']), 'YHOO': pd.Series([34.90,1.27,1010,27.48,0.66,35.36], index=['Closing price','EPS','Shares Outstanding(M)', 'P/E','Beta', 'Market Cap(B)']), 'TWTR':pd.Series([65.25,-0.3,555.2,36.23], index=['Closing price','EPS','Shares Outstanding(M)', 'Market Cap(B)']), 'AAPL':pd.Series([501.53,40.32,892.45,12.44,447.59,0.84], index=['Closing price','EPS','Shares Outstanding(M)','P/E', 'Market Cap(B)','Beta'])} print (stockSummaries) #print (stockSummaries['AMZN']) # In[129]: #Series DataFrame haline dönüşmesi stockDF=pd.DataFrame(stockSummaries); print (stockDF) # In[134]: # DataFrame'nin csv dosyası olarak çalışılan klasörde kaydedilmesi stockDF.to_csv('hisseSenediTest.csv') kaydedilen = pd.read_csv('hisseSenediTest.csv') print(kaydedilen) # In[135]: import pandas as pd import numpy as np veri = pd.read_csv('https://raw.githubusercontent.com/tdpetrou/Learn-Pandas/master/data/movie.csv') print(35*"-") print(veri.head()) print(35*"-") print(veri.head(10)) print(35*"-") print(veri.tail()) print(35*"-") print(veri.tail(10)) # In[140]: print (veri['director_name']) print(35*"-") print (veri.director_name) print(35*"-") print(35*"-") #data set 'den iki farklı veri türünde iki farklı seri oluşturma director = veri['director_name'] actor = veri['actor_1_facebook_likes'] print(35*"-") print print (director) print(35*"-") print (actor) # In[138]: # bütün name space import edildi from math import * factorial(5) # In[139]: # kütüphane m alias olarak import edildi import math as m m.factorial(5) # In[ ]:
1520dcca401820d363cf8d39136fdf5dfec9b280
Jamaliela/Intro-to-Classes
/t13_point.py
4,349
4.3125
4
###################################################################### # Author: Emily Lovell & Scott Heggen TODO: Ela Jamali & Thomas West # Username: lovelle & heggens TODO: Jamalie & Westt # # Assignment: T13: Intro to Classes # # Purpose: Demonstrates a Point class and a related main() to create objects ###################################################################### # Acknowledgements: # # Based on the point class from our textbook: http://cs.berea.edu/courses/csc226book/classes_and_objects_I.html # licensed under a Creative Commons # Attribution-Noncommercial-Share Alike 3.0 United States License. #################################################################################### import turtle # needed by both point class and main() import random # needed by main() import math # needed in drawing lines and calculating distance class Point: """ The Point class represents and manipulates x,y coordinates. It is dependent upon the turtle libraries for draw_point() method. In particular, a Screen must exist and the color mode should be set to 255 """ def __init__(self, x=0, y=0): # Each Point object has its own x and y coordinates and possibly a turtle """ Initializer method a.k.a. Constructor: Creates a new point at x, y. If no x, y are given, the point is created at 0, 0 :param x: the x coordinate of the point :param y: the y coordinate of the point """ self.x = x self.y = y self.turtley = None self.color = "red" def __str__(self): """ Makes the str() function work with Points :return: A formatted string for better printing """ return "({0}, {1})".format(self.x, self.y) def distance_from_origin(self): """ Compute my distance from the origin :return: float representing distance from (0, 0) """ return ((self.x ** 2) + (self.y ** 2)) ** 0.5 def user_set(self): """ Allows the user to change the x and y value of a Point :return: None """ self.x = int(input("Enter x: ")) self.y = int(input("Enter y: ")) def draw_point(self, r=0, g=0, b=0, text=""): # black is the default color """ Instantiates a Turtle object and draws the Point on the Screen :param r: the red channel :param g: the green channel :param b: the blue channel :param text: any additional text to stamp :return: None """ if not self.turtley: self.turtley = turtle.Turtle() self.turtley.hideturtle() self.turtley.color(r, g, b) self.turtley.penup() self.turtley.goto(self.x, self.y) self.turtley.showturtle() self.turtley.stamp() # This code was added from the original point.py class # to allow custom text to be written to the screen self.turtley.penup() if text == "": self.turtley.write(str(self), True) else: self.turtley.write(text, True) self.turtley.hideturtle() def dist(self, p): # we want this method to calculate the distance between the points dis = math.sqrt((p.y-self.y)**2+(p.x-self.x)**2) # this follows the math formula for calculating the distance between points return dis # end class def main(): """ A program that demonstrates the use of the Point class :return: None """ wn = turtle.Screen() wn.colormode(255) # change color modes p = Point() # Instantiate an object of type Point at (0, 0) print("point = " + str(p)) q = Point(30, 40) # Make a second point at (30, 40) print("point = " + str(q)) p.draw_point() # draw Point p as the default color of black q.draw_point(255, 0, 0) # draw Point q as red (255, 0, 0) print(q.dist(p)) print("\nPlease enter x and y values. To end enter x = 0 and y = 0.") while q.x != 0 or q.y != 0: q.user_set() print("point = " + str(q)) q.draw_point(random.randrange(256), random.randrange(256), random.randrange(256)) print("Exiting. Bye!") wn.bye() if __name__ == "__main__": main()
24086693998f535168f9594d6a7c88f14ecb7006
thirihsumyataung/Python_Tutorials
/inherentence_Area_Calculation_Python.py
806
3.96875
4
class Area: def __init__(self, length , width, height): self.length = length self.width = width self.height = height def getLength(self): return self.length def getWidth(self): return self.width def display(self): print(f'Length is: {self.length} ') print(f'Width is: {self.width} ') print(f'Length is: {self.height} ') class Rectangle(Area): def areaOfRec(self): result = (self.length * self.width * self.height) print(result) return result class Triangle(Area): def areaOfRec(self, length, height): result = (0.5 * length * height) print(result) return result tri = Triangle(13,4,1) tri.areaOfRec(13, 4 ) rec =Rectangle(3,5,12) rec.areaOfRec() rec.display()
9ebc8072d48df6cc0efea3fc0422268c7a86c38e
sashapotash29/CTCI_brainteasers
/chapter_1_arrays_and_strings/1_arrays_strings.py
4,301
4.25
4
# 1.1 is unique? - Determine if a string contains unique characters def is_unique(string): comparison_list=[] for letter in string: if letter.lower() in comparison_list: return False comparison_list.append(letter.lower()) if len(comparison_list) == len(string): return True else: pass # # TESTING AREA # print("sasha") # output = is_unique("sasha") # print(output) # output = is_unique("cat") # print("cat") # print(output) # # CLOSE TESTING AREA # 1.2 Check Permutation? - Determine with two strings if one string is a permutation of the other def is_perm(stringOne, stringTwo): if stringOne == stringTwo: return True if len(stringOne) == len(stringTwo): test_string = "" for letter in stringOne: if letter in stringTwo: test_string += letter else: return False return True else: return False # # TESTING AREA # print("bat and tab") # output = is_perm("bat", "tab") # print(output) # print("sapplein and saplpien") # output = is_perm("sapplein", "saplpien") # print(output) # # CLOSE TESTING AREA # 1.3 Check Permutation? - Determine with two strings if one string is a permutation of the other def urlify(string): url_string="" for letter in string: if letter == " ": url_string += "%20" else: url_string += letter return url_string # # TESTING AREA # print("Mr John Smith") # output = urlify("Mr John Smith") # print(output) # print("the url for all urls") # output = urlify("the url for all urls") # print(output) # # CLOSE TESTING AREA # 1.4 Palindrome Permutation? - Determine if a string has the ability to form a palindrome def pal_perm(string): if len(string)%2==0: print("even") word_dict = {} for letter in string: if letter in word_dict.keys(): word_dict[letter] += 1 else: word_dict[letter] = 1 checker = 0 for key, value in word_dict.items(): if word_dict[key] == 2: checker += 1 else: return False if checker%2==0: return True else: print(checker) else: print("odd") word_dict = {} for letter in string: if letter in word_dict.keys(): word_dict[letter] += 1 else: word_dict[letter] = 1 checker = 0 for key, value in word_dict.items(): if checker == 2: print("checker caught it") return False elif value%2 == 0: pass elif value == 1: checker +=1 if checker == 1: return True else: return False # # # TESTING AREA # print("abba") # output = pal_perm("abba") # print(output) # print("ccall") # output = pal_perm("ccall") # print(output) # # CLOSE TESTING AREA # 1.5 One Away? - Determine if one string is a single character away from being the second string def one_away(string, check): if string == check: return True elif len(string) == len(check): wrong = 0 for letter in string: if letter in check: print("yes " + letter) if letter not in check: wrong += 1 if wrong == 1: print(string) print(check) return True elif wrong >1: print(string) print(check) return False elif len(string)%len(check)==1 or len(check)%len(string) ==1: wrong = 0 for letter in string: if letter in check: pass if letter not in check: wrong += 1 if wrong <= 1: print(string) print(check) return True elif wrong >1: print(string) print(check) return False else: print("else") return False # # TESTING AREA # print("aaaa and aaa") # output = one_away("aaaaa","aaa") # print(output) # print("pale and bake") # output = one_away("pale", "bake") # print(output) # # CLOSE TESTING AREA # 1.6 String Compression? - Determine the amount of each character in a row def string_compr(string): final_string = "" counter = 1 for index in range(0,len(string)): if index == len(string)-1: final_string += string[index] + str(counter) elif string[index] == string[index+1]: counter+=1 elif string[index+1]: if string[index] != string[index+1]: final_string += string[index] + str(counter) counter=1 else: print("in else") final_string += string[index] + str(counter) return final_string # # TESTING AREA # print("aaaabbbaaccdddjj") # output = string_compr("aaaabbbaaccdddjj") # print(output) # print("abcd") # output = string_compr("abcjjjkkaskaasasskkksd") # print(output) # # CLOSE TESTING AREA
41bc4f6869948ac6b9f7b4f011cb79ef98a7368d
pahuja-gor/Python-Lectures
/CS 1064/dictionary_lookup.py
2,529
3.8125
4
import time def load_words(): ''' This function opens the words_alpha.txt file, reads it line-by-line, and adds the word with a different fake definition into both a list and a dictionary ''' with open('words_alpha.txt') as word_file: word_list = [] word_dictionary = {} counter = 0 for line in word_file: word_list.append([line.rstrip('\n'), ('fake definition'+str(counter))]) word_dictionary[line.rstrip('\n')] = ('fake definition'+str(counter)) counter += 1 print(" First word: {}".format(word_list[0])) print(" Middle word: {}".format(word_list[int(len(word_list)/2)])) print(" Last word: {}".format(word_list[-1])) return (word_list, word_dictionary) def timing_trial(word_to_find, word_list, word_dictionary, n_lookups): ''' Given a word to search for, this function will look inside both the list and dictionary to check for its existence, timing the lookup time. In case lookup time is small, specify larger n_lookups ''' # List timing list_start_time = time.time_ns() for i in range(n_lookups): wordInList = False for word, defn in word_list: if word == word_to_find: # Found it! Stop searching in this lap. wordInList = True break list_end_time = time.time_ns() list_total_time = (list_end_time - list_start_time) / 1000000000 # Dictionary timing dict_start_time = time.time_ns() for i in range(n_lookups): wordInList = False if word_to_find in word_dictionary: wordInList = True dict_end_time = time.time_ns() dict_total_time = (dict_end_time - dict_start_time) / 1000000000 return (list_total_time, dict_total_time) if __name__ == '__main__': print("Building list and dictionary...") (english_list, english_dictionary) = load_words() print("List and dictionary complete!\n") search_for = input("Tell me to look up a word: ") while search_for: niter = 1000 (list_time, dict_time) = timing_trial(search_for, english_list, english_dictionary, niter) print("Search time to retrieve the definition of " + search_for + ":") print(" list: {} seconds for {} lookups".format(list_time, niter)) print(" dict: {} seconds for {} lookups".format(dict_time, niter)) print("") search_for = input("Tell me to look up a word: ") print("Exiting!")
69e2a85ce1d61c83fe24b7061415669fbe135f53
XZANATOL/HR-PS
/Python/Easy/Text Wrap/Method.py
555
3.96875
4
#!/bin/python3 import textwrap def wrap(string, max_width): # count variable to add a newline for the max_width value count = 0 # string after wrapping variable output = "" # convert into list string = list(string) # wrapping loop for i in string: output += i count +=1 if count % max_width == 0: output += "\n" #retrun wrapped string return output if __name__ == '__main__': string, max_width = input(), int(input()) result = wrap(string, max_width) print(result)
05148eb7c5e7af4e59bdb6099937de6a2eb53684
snowlance7/Python-Projects
/week5/tree_pattern.py
263
4.03125
4
print("Tree Pattern\n") branches = int(input("Enter the number of branches: ")) def printTree(maxN): def tree(n): if n > 0: tree(n-1) print(n,"*" * n * maxN) tree(n-1) tree(maxN) printTree(branches)
af4047e7ebcc15abfc144b2c83c3e3196b8a72a0
francosbenitez/unsam
/04-listas-y-listas/05-arboles-2/lista-de-altos.py
743
3.5625
4
""" Ejercicio 4.19: Lista de altos de Jacarandá Usando comprensión de listas y la variable arboleda podés por ejemplo armar la lista de la altura de los árboles. H=[float(arbol['altura_tot']) for arbol in arboleda] Usá los filtros (recordá la Sección 4.3) para armar la lista de alturas de los Jacarandás solamente. """ import csv def leer_arboles(nombre_archivo): arboles = list() f = open(nombre_archivo, encoding="utf8") rows = csv.reader(f) headers = next(rows) for row in rows: lote = dict(zip(headers, row)) arboles.append(lote) return arboles arboleda = leer_arboles("Data/arbolado.csv") H = [ float(arbol["altura_tot"]) for arbol in arboleda if arbol["nombre_com"] == "Jacarandá"]
776893028cff2254a172405757fcad8f4806af75
Aasthaengg/IBMdataset
/Python_codes/p03803/s651862453.py
125
3.515625
4
M,N = map(int,input().split()) if M == N: print('Draw') elif (M>N and N!=1) or M==1: print('Alice') else: print('Bob')
8d25d7eaaa4831572cff7471af811861dafc9477
Dilip992801/Assignment_4
/321810304005_prime no.py
259
4.09375
4
def prime(n=int(input('Enter a number: '))): if n<=1: return False elif n==2: return True else: for i in (2,n//2): if(n%i==0): return False return True if(prime()): print('Number is prime number') else: print('Number is not prime number')
e7d0483533d01794877cd262dd43c7420578a2d1
Avery123123/LeetCode
/dataStructure/queue/Dqueue.py
944
3.828125
4
class DQueue(object): def __init__(self): self.data = [] def isEmpty(self): return self.data == [] def insertHead(self,newElem): self.data.insert(0,newElem) def insertTail(self,newElem): self.data.append(newElem) def deleteHead(self): if self.isEmpty(): raise Exception("Your Dqueue is empty!") else: return self.data.pop(0) def deleteTail(self): if self.isEmpty(): raise Exception("Ypur DQueue is empty!") else: return self.data.pop() def getHead(self): if self.isEmpty(): raise Exception("Your DQueue is empty!") else: return self.data[0] def getTail(self): if self.isEmpty(): raise Exception("Your DQueue is empty!") else: return self.data[len(self.data)-1] def size(self): return len(self.data)
93d3bc2a9eeb1ae1b5c9610aee0524242d976a0b
Remyaaadwik171017/mypythonprograms
/collections/dictionary/dict2.py
282
3.796875
4
employee={"id":1001,"employee_name":"remya","designation":"manager","salary":20000} print(employee["employee_name"]) print("company" in employee) employee["company"]="luminar" print(employee) employee["salary"]+=15000 print(employee) for i in employee: print(i,":",employee[i])
c37166f6bd9ecf9217d30419d3faf2e4917f6fc7
alexcarlos06/CEV_Python
/Mundo 1/Desafio 026.py
875
4.375
4
# Faça um programa que leia uma frase pelo teclado e mostre #quantas vezes aparece a letra desejada e em que posição ela aparece a primeira vez e em que posição ela aparece a úlitma vez # Lendo o nome informado excluindo os espaços do inicio e do final da frase e transformando todos os caracteres da sting em letra maiuscula e retirando os espaços digitados no inicio e no final da frase # Lendo a letra a ser procurada dentro da frase e retirando os espaços antes e depois da letra f = str(input('Digite uma frase: ')).upper().strip() c = str(input('Qual letra deseja contar dentro da frase? ')).upper().strip() # Mostrando na tela os resultados obtidos print('Foram encontradas "{1}" letras "{0}" dentro da frase.\nA letra "{0}" aparece na {2}º posição e por último na {3}º posição".'.format(c, f.count(c), f.find(c)+1,f.rfind(c)+1)) #Desafio concluído
685de3db9b7ea6967629302afcc30a6f401ceca4
negonzalez1024/Python
/Ejercicio2.py
202
3.78125
4
def calcularnumero(numero): while 1: if numero%2==0: aT = True else: aT=False if aT: print("El numero es par") else: print("El numero no es par") return aT
f48a14cbfcf33d4b6fedb3792f1d2e947d5b50f7
ger-hernandez/UTP-backup
/week3/while5.py
250
3.5625
4
#Mostrar los múltiplos de 8 hasta el valor 500. Debe aparecer en pantalla 8 - 16 - 24, etc. def while_exercise5(): i = 1 m = 8 r = 0 while r < 500: r = m * i print(f'{r}', end = '-') i += 1 while_exercise5()
514054723de2954d274c021457426660087f5742
mahaderony/Computational-Methods-In-Hydrology
/P1.py
1,194
3.921875
4
# Problem 01: Calculating Cosine of an angle with Maclaurine Series and comparing it with exact result import math x = int(input('Enter the angle in degree ')) xr = float(x * (math.pi / 180)) # Using Exact Formula Exact_cos = math.cos(xr) print('The Exact value of Cos', x, 'degree is', Exact_cos, ) # Using Maclaurine Series Approx_cos_2 = float(1 - (xr ** 2 / math.factorial(2))) Approx_cos_3 = float(1 - (xr ** 2 / math.factorial(2)) + (xr ** 4 / math.factorial(4))) Approx_cos_4 = float(1 - (xr ** 2 / math.factorial(2)) + (xr ** 4 / math.factorial(4)) - (xr ** 6 / math.factorial(6))) print('The Approximate value of Cos', x, 'Using 2 terms of Maclaurin is', Approx_cos_2, ) Err2 = float(((Exact_cos - Approx_cos_2) * 100) / Exact_cos) print('the error is', Err2, 'percent') print('The Approximate value of Cos', x, 'Using 3 terms of Maclaurin series is', Approx_cos_3, ) Err3 = float(((Exact_cos - Approx_cos_3) * 100) / Exact_cos) print('the error is', Err3, 'percent') print('The Approximate value of Cos', x, 'Using 4 terms of Maclaurin Series is', Approx_cos_4, ) Err4 = float(((Exact_cos - Approx_cos_4) * 100) / Exact_cos) print('the error is', Err4, 'percent')
f8abf3c1a6c5f61ed350ed5bfa0ba21e0371c628
WitRud/Python
/acro.py
1,030
3.515625
4
import re try: inputFile = open('inp.txt','r') inputF = inputFile.read() inputFile.close()#opening file except IOError: print "Cannot read a file . Check if inp.txt exists in this directory" else: names = re.findall(r'[A-Z][a-z]*\s[A-Z][a-z]*',inputF,re.M|re.S)#list of names(first name+' '+second name) replacement = {}#creating a dictionary if names: for i in names:#iterating via list searching for separete names replacement[i.split(' ')[1]] = re.search(r'\s[A-Z]',i,re.M|re.S).group()[1]+"."#add new position in dictionary: 'key value' is second name, 'value' is acronym from second name for key, value in replacement.iteritems(): inputF = re.sub(r'\b(?=\w)%s\b(?!\w)' % key,value,inputF)#search for full second names and replace them by acronym outputFile = open('off.txt','w') if inputF: outputFile.write(inputF)#saving file else: print 'error while saving file' outputFile.close()
73991166ce413af12df6f4a0b204e5d5b455737e
Madhivarman/DataStructures
/leetcodeProblems/removeDuplicates.py
560
3.859375
4
""" Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. """ def removeDuplicates(nums): seen = set() count = 0 for i in nums: if i not in seen: nums[count] = i count += 1 seen.add(i) return count aslist = [1,1,1,2,2,3,4,5,5,6] solution = removeDuplicates(aslist) print(solution)
dfa67916c3170ca81507f71241f7336b1e0e5d7c
anaswara-97/python_project
/exam2/file_obj.py
489
3.703125
4
class Student: def studDetails(self,name,roll,course,mark): self.name=name self.roll=roll self.course=course self.mark=mark def display(self): print("name : ",self.name) print("roll no : ",self.roll) print("course : ",self.course) print("mark : ",self.mark) f=open("abc","r") for i in f: l=i.split(",") n=l[0] ro=l[1] co=l[2] m=l[3] s = Student() s.studDetails(n,ro,co,m) s.display()
874f89495b2c241a2d81b1aea256a5a6dc36eb29
yangwei-nlp/LeetCode-Python
/OldBoy/p9_4 栈和队列.py
1,612
3.78125
4
# 记住原则,栈:后进先出;队列:先进先出。在编程中,我们常常用到这两个简单的原则来帮助我们解决复杂的问题。 # 检测括号是否有效 def bracket_match(s): """ 检查括号是否有效 """ stack = [] d = {'{':'}', '(': ')', '[': ']'} for cha in s: if cha in ['(', '[', '{']: stack.append(cha) elif cha == d[stack[-1]]: # 消掉,如[] stack.pop() elif not stack: # 来了个反括号,如] return False else: # 符号不匹配,如[) return False return True if not stack else False print(bracket_match("()()[]{}{}()")) print(bracket_match("()([)[]{}{}()")) # 教科书写法 P141 def check_parens(text): parens = "({[" all_parens = "({[]})" opp_parens = {'(': ')', '[': ']', '{': '}'} def paren_generator(text): # 生成括号和其位置 text_len = len(text) i = 0 while True: while i < text_len and text[i] not in all_parens: i += 1 if i >= text_len: return yield text[i], i i += 1 stack = [] for pr, i in paren_generator(text): if pr in parens: stack.append(pr) elif not stack: return False elif opp_parens[stack.pop()] != pr: return False return True if not stack else False print(check_parens("()())(){(}{}()[]")) print(check_parens("()()(){}{}()[][")) print(check_parens("()()(){}{}()[][]"))
d0d79240fe9198925a0c15d5465a4a3d96de60d5
TessFerrandez/AdventOfCode-Python
/2017/Instruction.py
627
3.5
4
class Instruction: def __init__(self, instr_str): parts = instr_str.strip().split(" ") self.dest = parts[0] self.op = parts[1] self.by = int(parts[2]) self.left_comp = parts[4] self.comp = parts[5] self.right_comp = int(parts[6]) def __str__(self): return ( "dest:" + self.dest + " op:" + self.op + " by:" + str(self.by) + " l:" + self.left_comp + " comp:" + self.comp + " r:" + str(self.right_comp) )
2cdfa125086a97e778d7b5b78847c9da6d7aadcb
TryNeo/practica-python
/ejerccios/ejerccio-89.py
1,230
4.1875
4
#!/usr/bin/python3 """ Omirp se define como un número primo que al invertir sus dígitos da otro número primo. Escriba un algoritmo para determinar si un número n tiene la característica de ser un número Omirp. """ def isPrime(num): if num < 1: return False elif num == 2: return True else: for i in range(2, num): if num % i == 0: return False return True def omirp(n): omirp = [i for i in n] omirp.reverse() new_omirp = ''.join(omirp) print(f"Se invierte sus digitos:{new_omirp}") resultado = isPrime(int(new_omirp)) if resultado is True: print(f"{new_omirp} es Numero Primo") return True else: print(f"{new_omirp} no es Numero Primo entonces") return False def main(): n = input("ingrese numero:") resultado = isPrime(int(n)) if resultado is True: print(f"{n} es un numero Primo") resultado = omirp(n) if resultado is True: print(f"Entonces el numero {n} es un numero omirp") else: print(f"Entonces el numero {n} no es numero omirp") else: print(f"{n} No es Primo") if __name__ == "__main__": main()
86960227f33e6733636c1f9ddcd88bc33f1a10e5
AvramPop/Fundamentals-Of-Programming
/lab03/Validation/ExpenseValidation.py
890
3.90625
4
from Constants import * def isValidDay(day): """ Checks whether day is a valid day (it is a natural number between 1 and 30) :param day: (int) the day to be checked :return: True if day is valid, False otherwise """ return type(day) == int and 1 <= day <= 30 def isValidAmount(amount): """ Checks whether amount is a valid amount (it is a natural number) :param amount: (int) the amount to be checked :return: True if amount is valid, False otherwise """ return type(amount) == int and amount > 0 def isValidExpenseType(expenseType): """ Checks whether expenseType is a valid expenseType (one of: housekeeping, food, transport, clothing, internet, others) :param expenseType: (string) the expenseType to be checked :return: True if expenseType is valid, False otherwise """ return expenseType in expenseTypeEnum
26436cb63a73a5618133638e421a071620b4e5b2
Jecoro/BoletinPythonVoluntario
/EJ5.py
636
3.65625
4
class Peers(object): # Atributo de Clase. list_Numbers = [10, 20, 10, 40, 50, 60, 70] # Constructor. def __init__(self, int_Obj): self.int_Obj = int_Obj # Método de Instancia. def findPeers(self): for i in range(len(self.list_Numbers)): if (self.list_Numbers[i] + self.list_Numbers[i - 1]) == self.int_Obj: self.i = i self.i_1 = (i-1) def __str__(self): return ("Los Indices que Suman {0} son ({2}, {1}).".format(self.int_Obj, self.i, self.i_1)) if __name__ == '__main__': peers = Peers(50) peers.findPeers() print(str(peers))
c702961173e9941be0ac766b09ee1d90a6799f07
dswisher/rosalind
/BioinformaticsStronghold/revp/revp.py
732
3.703125
4
import sys if len(sys.argv) < 2: print 'You must specify the name of the file to load.' sys.exit(1) def read_fasta(fname): seq = "" with open(fname, "r") as file: for line in file: line = line.strip() if line[0] != '>': seq += line return seq def rev_comp(seq): comp = { 'A':'T', 'C':'G', 'G':'C', 'T':'A'} sc = '' for c in reversed(seq): if c in comp: sc += comp[c] return sc def main(): seq = read_fasta(sys.argv[1]) for i in xrange(len(seq)-3): for j in xrange(min(12, len(seq)-i), 3, -1): s = seq[i:i+j] if s == rev_comp(s): print "%d %d" % (i + 1, j) main()
e56ae5ed7eba7bf0721288e1eba05581215bf394
azavana/Machine-Learning_Deep-Learning
/Regression/Linear/linear_regression.py
855
3.609375
4
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt learning_rate = 0.01 training_epochs = 100 a = 2 # y = ax x_train = np.linspace(-1,1,101) y_train = a*x_train+np.random.randn(*x_train.shape)*0.33 # Solving linear regression X = tf.placeholder(tf.float32) Y = tf.placeholder(tf.float32) def model(X,w): return tf.multiply(X,w) w = tf.Variable(0.0, name="weights") y_model = model(X,w) cost = tf.square(Y-y_model) train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) sess = tf.Session() init = tf.global_variables_initializer() sess.run(init) for epoch in range(training_epochs): for (x,y) in zip(x_train,y_train): sess.run(train_op,feed_dict={X: x, Y: y}) w_val = sess.run(w) sess.close() plt.scatter(x_train,y_train) y_learned = x_train*w_val plt.plot(x_train,y_learned,'r') plt.show()
6b901290181af0b3adc272bb6008a15a53d1d2dc
ncfoa/100DaysOfCode_Python
/027/gui_playground.py
969
4.125
4
from tkinter import * def reset(): label["text"] = "Hello World" def button_click(): label["text"] = "OMG YOU CLICKED IT!" def display_text(): label["text"] = text.get() # Create window w = Tk() w.title("Dave's Window") w.minsize(width=800, height=600) w.config(padx=20, pady=20) # Create border frame = Frame(w, borderwidth=5, relief=SUNKEN) frame.grid(column=0, row=2) # Create Label label = Label(text="Hello World!", font=("Arial", 24, "bold")) label.grid(column=2, row=0) label.config(padx=5, pady=5) # Create Text Entry Box text = Entry(frame, borderwidth=5, relief=FLAT) text.grid(column=0, row=2) text.insert(END, "What are you doing?") # Create Buttons button = Button(text="click me...", command=button_click) button.grid(column=2, row=2) display_button = Button(text="display", command=display_text) display_button.grid(column=1, row=2) reset_button = Button(text="reset", command=reset) reset_button.grid(column=3, row=3) w.mainloop()
833a138a2fb25bf9354f196ec1845f5f2a8e2e81
1234567890boo/ywviktor
/OOPcoinfliptkcopy.py
1,011
3.859375
4
from tkinter import * from random import * class Guess: def __init__(self): self.window=Tk() self.select=StringVar() self.select.set('head') self.guess=['head','tail'][randint(0,1)] self.head=Radiobutton(self.window,text='head',variable=self.select,value='head') self.tail=Radiobutton(self.window,text='tail',variable=self.select,value='tail') self.b=Button(self.window,text='guess',command=self.find) self.show=Label(self.window,text='label') def find(self): if self.select.get()==self.guess: self.show['text']='Correct' else: self.show['text']='Wrong' def draw(self): self.show.grid(row=0,column=0,columnspan=2) self.b.grid(row=1,column=0,columnspan=2) self.tail.grid(row=2,column=0) self.head.grid(row=2,column=1) w=Guess() w.draw() w.window.mainloop() #Homework: #f1 f2 f3 #f4 f5 f6 #enter quantity of fruit #________ #you have to pay (selected fruit*num)
98c2e9adfa0c288262cbfd2b0fe5b6a866b36f3b
nadav366/intro2cs-ex10
/ship.py
984
3.75
4
from game_object import * LIFE_QUANTITY = 3 START_DIRECTION = 0 class Ship(GameObject): """ A class that is the game ship. The class inherit GameObject. """ SHIP_RADIOS = 1 def __init__(self, x_location, y_location): """ Constructor ship :param x_location: number, the position of the object in Axis x :param y_location: number, the position of the object in Axis y """ super(Ship, self).__init__(x_location, y_location) # Builds the object self.__direction = START_DIRECTION self.__life = LIFE_QUANTITY """ The following functions modify and return ship properties- """ def rotate(self, deg_to_rotate): self.__direction += deg_to_rotate def get_direction(self): return self.__direction def get_radios(self): return self.SHIP_RADIOS def remove_life(self): self.__life -= 1 def get_life(self): return self.__life