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
66411ff8a8939a465b84c081d269090ededf9567
wusui/pentomino_redux
/tree_offspring.py
2,443
3.546875
4
""" _get_offspring and associated functions """ def get_complete_gen(tree): """ Given a tree, return a list of lists indexed by node number. Each list entry is a set of points that can be added as an offspring node to that node """ return map(_get_new_points(tree), range(len(tree))) def _get_new_points(tree): """ Gen_offspring_points wrapper """ def _func1(node): return _gen_offspring_points(_get_parents(tree, node)) return _func1 def _get_parents(tree, node, plist=None): """ Recursively look for parent nodes """ if plist is None: plist = [] plist.append(tree[node]['point']) if tree[node]['prev_gen'] < 0: return list(_uniqify(plist)) return _get_parents(tree, tree[node]['prev_gen'], plist) def _gen_offspring_points(parents): """ Wrapper to return T/F value frsom _make_one_list calls """ def _check_dupe(point): return point not in parents return list(filter(_check_dupe, _make_one_list(parents))) def _make_one_list(points): """ Return one list of unique points """ return _uniqify(_combined_lists(_get_all_possible_points(points))) def _uniqify(alist): """ Given a list, return a list with duplicates removed. """ return list(map(list, set(list(map(tuple, alist))))) def _combined_lists(alist, total=None): """ Given a list of lists, make that set of lists one list """ if total is None: total = [] if not alist: return total return _combined_lists(alist[1:], total + alist[0]) def _get_all_possible_points(points): """ Given a list of points, for each point return a list of all possible new neighbor points that can be added. """ return list(map(_get_next_points, points)) def _get_next_points(points): """ Return valid next points (yet unused neighbors to points passed) """ return list(filter(_is_configurable, _get_points(points))) def _get_points(point): """ Return list of possible neighbor points to a given point """ return [[point[0], point[1] + 1], [point[0], point[1] - 1], [point[0] + 1, point[1]], [point[0] - 1, point[1]] ] def _is_configurable(point): """ Filter comparison function to make sure point is in valid range """ return point[0] >= 0 and (point[1] >= 0 or point[0] > 0)
0d42ed8f2e6f96a6cd1cae24237a7cff15b04dd5
Susmit-A/IoT_HandsOn
/src/basics/Python/functions.py
623
4.375
4
# Here we shall see how to define a function in Python. # A function definition starts with the keyword 'def': def func(): print("No Parameters") def func(param): print(param) func(5) # Unlike OOP languages, Python doesn't support function overloading. # If multiple definitions of a function exist, the latest definition is taken # Also, blocks of code in Python are identified by the number of spaces before the lines. # For example, if 5 consecutive lines have 2 spaces preceeding them, they belong to the same block. # Each block in Python defines a scope for the variables defined in that block.
099fbb0631bd300d9badad07be491fba68779051
alejamorenovallejo/retos-phyton
/Ejercicio/Clases/ciclos.py
825
4.0625
4
#for loop(ciclo) suma = 0 #Esto es un Acumulador cuenta = 0 #Este es un contador numero = int(input("¿Hasta que número quieres sumar?")) for i in range(numero + 1): suma += i cuenta += 1 print("La suma de los números es ", suma) print("El ciclo se ejecuto ", cuenta, "veces") #Pero quiero que mi programa empiece desde 1 y no desde 0 suma2 = 0 #Esto es un Acumulador cuenta2 = 0 #Este es un contador for i in range(1,numero + 1): suma2 += i cuenta2 += 1 print("La suma de los números es ", suma2) print("El ciclo se ejecuto ", cuenta2, "veces") #Ahora quiero imprimir los pares suma3 = 0 #Esto es un Acumulador cuenta3 = 0 #Este es un contador for i in range(2,numero + 1,2): suma3 += i cuenta3 += 1 print("La suma de los números pares ", suma3) print("El ciclo se ejecuto ", cuenta3, "veces")
db269d36e8e791412a0fac7d7822f9a573ea3b72
kaio358/Python
/Mundo3/Funções/Desafio#101.py
395
3.875
4
def voto(anos): from datetime import date atual = date.today().year idade = atual - anos if idade < 16 : return f'A idade {idade} insuficiente, NEGADO !!' if 16 <= idade <18 or idade>69: return f'A idade {idade} é OPICIONAL' if 18 <= idade <= 69: return f'A idade {idade} é OBRIGATORIO' print(voto(int(input('Informe o ano de nascimento : '))))
449067634351a2e5207cfbcd61ef2f87a0a245fb
cwinslow22/Data-Structures
/linked_list/linked_list.py
1,524
3.75
4
""" Class that represents a single linked list node that holds a single value and a reference to the next node in the list """ class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): self.next_node = new_next class LinkedList: def __init__(self): self.head = None self.tail = None def add_to_tail(self, value): new_node = Node(value) if self.tail is None: self.head = new_node self.tail = new_node else: self.tail.next_node = new_node self.tail = new_node self.tail.next_node = None def remove_head(self): removed = self.head if self.head: if not self.head.next_node: self.head = self.head.next_node self.tail = None else: self.head = self.head.next_node # self.tail = None return removed.value def contains(self, value): if self.head: search_node = self.head while search_node is not None: if search_node.value == value: return True search_node = search_node.next_node return False def get_max(self): if self.head: max_value = self.head.value curr_node = self.head while curr_node is not None: if curr_node.value > max_value: max_value = curr_node.value curr_node = curr_node.next_node return max_value
03fca00bf92ab7d1bf4e15e6b82c4f2f274ea3c7
bcui6611/mortimer
/mortimer/grammar.py
11,214
3.59375
4
import globals from lepl import * from bisect import bisect_left import logging """ The following class definitions are used to aid in the construction of the Abstract Syntax Tree from the expression. For example, they allow simple tests such as isinstance(exprtree, Identfier). See expr_evaluate(exprtree, context). """ class Identifier(List): pass class Number(List): pass class Add(List): pass class Sub(List): pass class Mul(List): pass class Div(List): pass class FunctionCall(List): pass """ Grammar rules used by the lepl module. See http://www.acooke.org/lepl/ for more info """ my_Identifier = Token(r'[a-zA-Z_][a-zA-Z_0-9]*') > Identifier symbol = Token('[^0-9a-zA-Z \t\r\n]') my_Value = Token(UnsignedReal()) my_Number = Optional(symbol('-')) + my_Value > Number group2 = Delayed() my_Expr = Delayed() # first layer, most tightly grouped, is parens and numbers parens = ~symbol('(') & my_Expr & ~symbol(')') my_Function = my_Identifier & parens > FunctionCall group1 = my_Function | parens | my_Number | my_Identifier # second layer, next most tightly grouped, is multiplication my_Mul = group1 & ~symbol('*') & group2 > Mul my_Div = group1 & ~symbol('/') & group2 > Div group2 += my_Mul | my_Div | group1 # third layer, least tightly grouped, is addition my_Add = group2 & ~symbol('+') & my_Expr > Add my_Sub = group2 & ~symbol('-') & my_Expr > Sub my_Expr += my_Add | my_Sub | group2 def parse_expr(expr, context): """ Wrapper function to the entry lepl parse function. If manage to parse return Abstract Syntax Tree, otherwise send message over web socket to the web browser and return the empty string. """ try: result = my_Expr.parse(expr) return result except: logging.debug("Could not parse the expression " + str(expr)) return '' def series_by_name(seriesname, context): keysDictionary = {'keys': [context['file'], context['bucket']]} file = context['file'] bucket = context['bucket'] data = {} try: data = globals.stats[file][bucket] except: return [] result = [] for x in data: try: result.append([x['localtime'], x[seriesname]]) except: return [] return result def multiplying(op1, op2): if isinstance(op1, list) and not isinstance(op2, list): for x in op1: x[1] = x[1] * op2 return op1 elif isinstance(op2, list) and not isinstance(op1, list): for x in op2: x[1] = x[1] * op1 return op2 else: if len(op1) != len(op2): print('Error multiplying: lengths not equal. See function multiplying(op1, op2)') return [] else: for x in range(len(op1)): op1[x][1] = op1[x][1] * op2[x][1] return op1 def dividing(op1, op2): if isinstance(op1, list) and not isinstance(op2, list): for x in range(len(op1)): if op2 == 0: op1[x][1] = None else: op1[x][1] = op1[x][1] / op2 return op1 elif isinstance(op2, list) and isinstance(op1, list): if len(op1) != len(op2): print('Error dividing: lengths not equal. See function dividing(op1, op2)') return [] else: for x in range(len(op1)): if op2[x][1] == 0: op1[x][1] = None else: op1[x][1] = op1[x][1] / op2[x][1] return op1 else: print('Error dividing: dividing number by a list. See function dividing(op1, op2)') return [] def adding(op1, op2): if isinstance(op1, list) and not isinstance(op2, list): for x in op1: x[1] = x[1] + op2 return op1 if isinstance(op2, list) and not isinstance(op1, list): for x in op2: x[1] = x[1] + op1 return op2 else: if len(op1) != len(op2): print('Error in adding function: lengths not equal') return [] else: for x in range(len(op1)): op1[x][1] = op1[x][1] + op2[x][1] return op1 def subtracting(op1, op2): if isinstance(op1, list) and not isinstance(op2, list): for x in op1: x[1] = x[1] - op2 return op1 elif isinstance(op2, list) and isinstance(op1, list): if len(op1) != len(op2): print('Error in subtracting function: lengths not equal') return [] else: for x in range(len(op1)): op1[x][1] = op1[x][1] - op2[x][1] return op1 else: print('Error in subtracting function: subtracting list from a number') return [] def derivative(f): """ Function that returns the (approx) derivative of function f. """ def df(x, h=0.1e-4): return (f(x + h / 2) - f(x - h / 2)) / h return df def binary_search(a, x, lo=0, hi=None): hi = hi if hi is not None else len(a) pos = bisect_left(a, x, lo, hi) if pos == 0 or pos == hi or (a[pos] >= x and a[pos - 1] <= x): return pos else: return -1 def searchsorted(xin, xout): xin.sort() result = binary_search(xin, xout) return result def interpolate(derivseries, interpargs): xin = [] yin = [] for p in derivseries: xin.append(p[0]) yin.append(p[1]) lenxin = len(xin) def inter(xout): i1 = searchsorted(xin, xout) #s1 = numpy.searchsorted(xin, xout) # if i1 != s1: # print("s1 = " + str(s1) + " il = " + str(i1)) if i1 == 0: i1 = 1 if i1 == lenxin: i1 = lenxin - 1 x0 = xin[i1 - 1] x1 = xin[i1] y0 = yin[i1 - 1] y1 = yin[i1] if interpargs == 'linear': return (xout - x0) / (x1 - x0) * (y1 - y0) + y0 return inter def derivativewrapper(pointseries, interpargs): derivseries = [] # Remove all those that have null as second argument for x in pointseries: if x[1] != None: derivseries.append(x) # Return the interpolate function inter = interpolate(derivseries, interpargs) # Return the first derivative function applied to the interpolate function dg = derivative(inter) result = [] for x in pointseries: newx = [x[0], dg(x[0] + 0.5)] result.append(newx) return result def moving_average(pointseries, window): """ Function for calculating the moving average. The Python module Numpy can be used to calulate the moving average (using the convolve function), but Numpy is not compatible with pypy and so has not been used. """ smoothed = [] for n in range(len(pointseries)): rangestart = n - window rangeend = n + window + 1 samples = [] if rangestart < 0: rangestart = 0 samples.append(None) if rangeend > len(pointseries): rangeend = len(pointseries) samples.append(None) for x in range(rangestart, rangeend): samples.append(pointseries[x][1]) orig = pointseries[n] # in clojure code also check that n - window - 1 < 0. # Don't know why - does not appear to be required. Bug? if None in samples: result = [orig[0], None] else: numofsamples = len(samples) samplestotal = sum(samples) result = [orig[0], float(samplestotal) / float(numofsamples)] smoothed.append(result) return smoothed def expr_fun_table(fname, seriesname, context): """ Provides support for calling functions. Currently only rate is supported. """ if fname[0] == 'rate': # Get the uptime from the stats uptime = series_by_name('uptime', context) # Calculate the moving average of uptime movingaverage = moving_average(uptime, context['smoothing-window']) # Calculate the derivative of uptime derivativeresult = derivativewrapper(movingaverage, 'linear') # Get the series we are calculating the rate for series = series_by_name(seriesname[0], context) # Calculate the moving average of the series seriesmovingaverage = moving_average(series, context['smoothing-window']) # Calculate the derivative of the series seriesderivativeresult = derivativewrapper(seriesmovingaverage, 'linear') if len(derivativeresult) != len(seriesderivativeresult): print('Error: length of uptime derivative result != length of series derivative result. \ See function expr_fun_table(fname, seriesname, context).') return [] result = [] # Iterate through all the results for the derivative of uptime. # If any of the derivative results are negative replace them with None. for x in range(len(derivativeresult)): if derivativeresult[x][1] < 0: result.append([seriesderivativeresult[x][0], None]) else: result.append(seriesderivativeresult[x]) return result else: print('Error do not recognise function in expr_fun_table(fname, seriesname, context)') return [] def expr_evaluate(exprtree, context): """ Recursive function for performing traversal of Abstract Syntax Tree. """ if isinstance(exprtree, Number): return float(exprtree[0]) elif isinstance(exprtree, Identifier): return series_by_name(exprtree[0], context) elif isinstance(exprtree, FunctionCall): return expr_fun_table(exprtree[0], exprtree[1], context) elif isinstance(exprtree, Mul): op1 = expr_evaluate(exprtree[0], context) op2 = expr_evaluate(exprtree[1], context) return multiplying(op1, op2) elif isinstance(exprtree, Div): op1 = expr_evaluate(exprtree[0], context) op2 = expr_evaluate(exprtree[1], context) return dividing(op1, op2) elif isinstance(exprtree, Sub): op1 = expr_evaluate(exprtree[0], context) op2 = expr_evaluate(exprtree[1], context) return subtracting(op1, op2) elif isinstance(exprtree, Add): op1 = expr_evaluate(exprtree[0], context) op2 = expr_evaluate(exprtree[1], context) return adding(op1, op2) def expr_eval_string(expr, contextDictionary): """ wrapper function for fully parsing the query expression, then evaluating the expression returning the data. If expression cannot be parsed or there is no data then the empty list is returned. """ # Remove whitespace from start & end of the string. # Can't see whenever this is required however in the original mortimer. expr = expr.strip() # Uses the lepl module to parse the expression into an Abstract Syntax Tree. parsedExpression = parse_expr(expr, contextDictionary) result = [] # If successfully parsed the expression try to evaluate it. if parsedExpression != '': result = expr_evaluate(parsedExpression[0], contextDictionary) return result
2f9c9b9e5aaa56ae59308c36a98861e5c79941f7
itsolutionscorp/AutoStyle-Clustering
/assignments/python/61a_hw4/src/166.py
253
3.515625
4
def num_common_letters(goal_word, guess): goal_word_list = get_list(goal_word) guess_list = get_list(guess) commonChars = 0 for char in goal_word_list: if char in guess_list: commonChars += 1 return commonChars
8b4edd1237e54d579b69c4bcf9ed25335a05c481
roclas/utils27.py
/financial/ibex35/add_weekdays.py
392
3.515625
4
#!/usr/bin/env python import datetime,sys inputfile=sys.argv[1] weekdays=["mon","tue","wen","thu","fri","sat","sun"] for l in open(inputfile).readlines(): try: arr=l.split('"') date_str=arr[1] d,m,y=date_str.split("/") dt=datetime.date(int(y),int(m),int(d)) weekday=weekdays[dt.timetuple()[6]] print "\"%s\",%s" %(weekday,l) except Exception as e: print "error: %s" %e
9940c65e40f0bdd650ba3ad9bb376b3396d47267
MiraDevelYing/colloquium
/1.py
702
3.578125
4
#Введіть з клавіатури в масив п'ять цілочисельних значень. Виведіть їх в #один рядок через кому. Отримайте для масиву середнє арифметичне. #Дудук Вадим 122-Г import numpy as np while True: b=np.zeros(5,dtype=int) u=[] for i in range(5): b[i] = int(input('Введіть елементи: ')) for k in range(5): l=b[k] u.append(l) print(u) g=sum(u)/5 print('Середнє Арифметичне',g) result = input(' продовжити? Так - 1, Ні - інше: ') if result == '1': continue else: break
574d63d0c04756ba5a3654e6c0d16a0625a82f1d
xzeromath/euler
/myfunctions.py
1,421
4.4375
4
# https://www.geeksforgeeks.org/python-program-to-check-whether-a-number-is-prime-or-not/ # Instead of checking till n, we can check till √n because a larger factor of n must be a multiple of smaller factor that has been already checked. # The algorithm can be improved further by observing that all primes are of the form 6k ± 1, # with the exception of 2 and 3. This is because all integers can be expressed as (6k + i) for some integer k and for i = ?1, 0, 1, 2, 3, or 4; # 2 divides (6k + 0), (6k + 2), (6k + 4); and 3 divides (6k + 3). So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6k ± 1. (Source: wikipedia) # A optimized school method based # Python3 program to check # if a number is prime def isPrime(n): # Corner cases if (n <= 1): return False if (n <= 3): return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0): return False i = 5 while (i * i <= n): if (n % i == 0 or n % (i + 2) == 0): return False i = i + 6 return True def prime_list(limit): return [i for i in range(limit + 1) if isPrime(i)] #소수 리스트 if __name__ == '__main__': limit = 500 primelist = [i for i in range(limit + 1) if isPrime(i)] #소수 리스트 # This code is contributed # by Nikita Tiwari.
ea5b916dccb9420006a9b8aefa342d1f4809584c
MariVilas/teste
/Python/aula10h.py
314
4.15625
4
a=int(input('Entre com um número:')) b=int(input('Entre com um número:')) c=int(input('Entre com um número:')) if ( b - c ) < a < b + c : print('Triângulo Encontrado!') elif ( a - c ) < b < a + c: print('Triângulo Encontrado!') else: (a - b) < c < a + b print('Triângulo Encontrado!')
7e794d4c43d8b06720f4af66b39940a3d1f5e20a
gbharatnaidu/python_programs
/duplicate_numbers.py
417
3.578125
4
arr1=[1,10,12,12,1,1,5,10,23,1] arr2=[] for i in range(0,len(arr1)): arr2.append(-1) print(arr2) for i in range(0,len(arr1)): count=1 for j in range(i+1,len(arr1)): if(arr1[i]==arr1[j]): count+=1 arr2[j]=0 if(arr2[i]!=0): arr2[i]=count for i in range(0,len(arr1)): if(arr2[i]>0): print("no of times ",arr1[i]," is occured ",arr2[i])
987bd929b9641ecf9f5022773df5ab7a45caf750
SSK0001/SDE-Skills
/Week 3/CloneStack.py
471
3.515625
4
# Clone Stack def cloneStack(original): ''' type original: original stack type clone: clone stack with this rtype: clone ''' if len(original) == 0: return original tempStack = queue.LifoQueue() clone = [] while(len(original) > 0): tempStack.put(original.pop()) while(not tempStack.empty()): stackTop = tempStack.pop() original.append(stackTop) clone.append(stackTop) return clone
9eedb2b11a01c71bcadd0b4feeb421bad22d2b1d
zxycode-2020/python_base
/day16/6、文档测试/文档测试.py
416
3.8125
4
import doctest #doctest模块可以提取注释中的的代码执行 #doctest严格按照Python交互模式的输入提取 def mySum(x, y): ''' get The Sum from x and Y :param x: firstNum :param y: SecondNum :return: sum 注意有空格 example: >>> print(mySum(1,2)) 3 ''' return x + y print(mySum(1, 2)) #进行文档测试 doctest.testmod()
72bce4850e9ee2be49baa0bf0da265fd36d0ba52
Meenaashutosh/FileHandlingAssignment
/program9.py
428
4.3125
4
# 9.Write a Python program to count the frequency of words in a file file=open("file.txt","r+") word_count={} for word in file.read().split(): if word not in word_count: word_count[word] = 1 else: word_count[word] += 1 for l in word_count.items(): print l #output ''' python program9.py ('redmi', 1) ('apple', 1) ('vivo', 1) ('moto', 1) ('appo', 1) ('sony', 1) ('panasonic', 1) '''
f40a75f21b2c7ea6823e6c79b144dd21ceade09b
iamfakeBOII/pythonP
/reference/nested_loops.py
2,201
4.125
4
#NUMBER 1 - ASCENDING ''' num = int(input('ENTER HOW MANY ROWS ARE REQUIRED: ')) count = 1 for b in range(num): for i in range(count): print('1', end=" ") print('') count +=1 continue ''' #NUMBER 1 - DESCENDING ''' num = int(input('ENTER HOW MANY ROWS ARE REQUIRED: ')) count = num for b in range(num): for i in range(count): print('1', end=" ") print('') count -=1 continue ''' #NUMBER - 1,2,3,4 - ASCENDING ''' num_numbers = int(input('UNTIL WHICH NUMBER IS THE TRIANGLE REQUIRED: ')) count = 1 number = 2 for b in range(num_numbers): for i in range(count, number): print(i, end=" ") print('') #count += 1 number +=1 continue ''' #NUMBER - 1,2,3,4 - DESCENDING ''' num_numbers = int(input('FROM WHICH NUMBER IS THE TRIANGLE REQUIRED: ')) count = num_numbers number = count for b in range(num_numbers): for i in range(count): print(number, end=" ") print('') count -= 1 number -=1 continue ''' #NUMBER - 1,3,5,7.. - ODD - ASCENDING ''' new_num = int(input('HOW MANY ROWS ARE REQUIRED: ')) count = 1 number = 1 for b in range(new_num): for i in range(count): print(number, end=" ") print('') count += 2 number += 2 continue ''' #NUMBER - ODD - DESCENDING ''' new_num = int(input('HOW MANY ROWS ARE REQUIRED: ')) count = new_num*2 number = new_num*2 for b in range(new_num): for i in range(count): print(number, end=" ") print('') count -= 2 number -= 2 continue ''' #NUMBERS - 2,4,6,8... - EVEN - DESCENDING ''' new_num = int(input('HOW MANY ROWS ARE REQUIRED: ')) count = new_num*2 number = new_num*2 for b in range(new_num): for i in range(count): print(number, end=" ") print('') count -= 2 number -= 2 continue ''' #WORD SERIES word = input('ENTER A STRING: ') rows = len(word) count = 0 right = 1 for b in range(rows): for i in range(count, right): final = word[i] print(final, end=" ") print('') right += 1
a551c226e1667ee3639cc09be8dc3e1535aaace0
masif245/TicTacToe
/TicTacToeGame.py
3,137
3.828125
4
def welcomeMessage(): print ('Hello !!! Welcome to the tic tac toe game.') #clear = lambda: os.system('clear') def clear(): clr = "\n" * 100 print (clr) def getPlayedChoice(): Player1 = input('Hey Player 1 ! Enter your choice of character X/O: ') while (Player1 != 'X' and Player1 != 'O'): Player1 = input('Hey Player 1 ! Enter your choice of character X/O: ') #else: # break if Player1 == 'X': Player2 = 'O' else: Player2 = 'X' return Player1, Player2 def displayBoard(board): clear() print ('\t | | ') print ('\t {} | {} | {} '.format(board[0], board[1], board[2])) print ('\t____|____|____') print ('\t | | ') print ('\t {} | {} | {} '.format(board[3], board[4], board[5])) print ('\t____|____|____') print ('\t | | ') print ('\t {} | {} | {} '.format(board[6], board[7], board[8])) print ('\t | | ') def validate(board, idx): if board[idx-1] != 'X' and board[idx-1] != 'O': return True def getUserInput(plnum,board): val = input('Hey Player {} make your move (Enter poistion 1-9): '.format(plnum)) if validate(board, int(val)): return int(val) else: return False def wincheck(board,pnum): if len(board)<3: return False else: if (board[0]==board[1]==board[2]==pnum) or (board[3]==board[4]==board[5]==pnum) or (board[6]==board[7]==board[8]==pnum) or (board[0]==board[3]==board[6]==pnum) or (board[1]==board[4]==board[7]==pnum) or (board[2]==board[5]==board[8]==pnum)or (board[0]==board[4]==board[8]==pnum) or (board[2]==board[4]==board[6]==pnum): return True else: return False def main(): move = '' ii = '' welcomeMessage() board = ['']*9 Player1, Player2 = getPlayedChoice() print('Players your representation is Player 1-> {} Player 2-> {}'.format(Player1,Player2)) print('Lets Begin. Here is the empty board...') displayBoard(board) for ii in range(1,10): if ii % 2 == 0: move = getUserInput('2', board) while (move == False): print('Hey you cant cheat choose another index') move = getUserInput('2', board) board[move-1] = Player2 displayBoard(board) if wincheck(board, Player2)==True: print ('Player 2 wins') break else: move = getUserInput('1', board) while (move == False): print('Hey you cant cheat choose another index') move = getUserInput('2', board) board[move-1] = Player1 displayBoard(board) if wincheck(board, Player1)==True: print ('Player 1 wins') break if wincheck(board, Player1) == False and wincheck(board, Player2) == False: print('\n Hehehehehehhehe Match Draw') if __name__ == '__main__': main()
7ca2ecacbbd6a42b7937fd334251bc67baf9471d
haydenso/school-projects
/Pre-release/invalid_final.py
3,551
3.859375
4
# TASK 1 - Start of Day up_times = ["9:00", "11:00", "13:00", "15:00"] #Array of strings - variable up_seats = [480, 480, 480, 480] #Array of integers - variable up_tally = [0, 0, 0, 0] #Array of integers - variable up_revenue = [0.0, 0.0, 0.0, 0.0] #Array of real - variable down_times = ["10:00", "12:00", "14:00", "16:00"] down_seats = [480, 480, 480, 640] down_tally = [0, 0, 0, 0] down_revenue = [0.0, 0.0, 0.0, 0.0] ticket_cost = 25.0 #real/float - constant def screenDisplay(): print("\nJourney Up") for i in range(0,4): if up_seats[i] == up_tally[i]: seats = "Closed" else: seats = up_seats[i] - up_tally[i] print(f"{i+1}. {up_times[i]} - {seats}") print("\nJourney Down") for i in range(0,4): if down_seats[i] == down_tally[i]: seats = "Closed" else: seats = down_seats[i] - down_tally[i] print(f"{i+1}. {down_times[i]} - {seats}") screenDisplay() # TASK 2 - Purchasing tickets def calculate_revenue(journey, num, revenue): num_free_tickets = int(num) // 10 num_tickets_to_buy = int(num) - num_free_tickets revenue[int(journey)-1] += num_tickets_to_buy * ticket_cost return revenue #NUMBER OF PASSENGERS GOING UP --> while there are still seats avaiable to go up while up_times != up_tally: while True: num_passengers = input("\nHow many passengers are going? ") # Type check == Int and Range check 0 < x <= 80 if num_passengers.isnumeric() and 0 < int(num_passengers) <= 80: break else: print("Invalid input, number must be in between 1 and 80") while True: up = input(f"\nUp Journey Time? ") up_index = int(up)-1 if up_index <= 3 and up_seats[up_index] - up_tally[up_index] >= num_passengers: up_tally[up_index] += num_passengers calculate_revenue(up, num_passengers, up_revenue) else: print("Sorry invalid choice or not enough seats") continue down = input(f"Down Journey Time? ") down_index = int(down) - 1 if down_index <= 3 and down_seats[down_index] - down_tally[down_index] >= num_passengers: down_tally[down_index] += num_passengers calculate_revenue(down, num_passengers, down_revenue) break else: print("Sorry invalid choice or not enough seats") continue screenDisplay() booking = input("\nCreate another booking (y/n)? ") # this is not completely validated, is it ok if booking.lower() == 'n': break # TASK 3 print("\nJourney Up") for i in range(0,4): print(f"{i+1}. {up_times[i]} - {up_tally[i]} passengers - ${up_revenue[i]} made") print("\nJourney Down") for i in range(0,4): print(f"{i+1}. {down_times[i]} - {down_tally[i]} passengers - ${down_revenue[i]} made") # change sum function into manual function total_revenue = sum(up_revenue) + sum(down_revenue) total_passengers = sum(up_tally) # total passenger is the sum of up and down? or total number of unique passengers print(f"\n${total_revenue} total revenue, {total_passengers} total passengers") # change max function into manual function if max(up_tally) > max(down_tally): index = up_tally.index(max(up_tally)) print(f"{up_times[index]} had the most passengers") elif max(up_tally) < max(down_tally): index = down_tally.index(max(down_tally)) print(f"{down_times[index]} had the most passengers")
b9fd49ea64220ba74cdcd34b59a26697bab2fd8f
nasama/procon
/atcoder.jp/abc072/abc072_b/Main.py
67
3.53125
4
s = input() a = '' for i in range(0,len(s),2): a += s[i] print(a)
2fbe3b9b78105b8ea0b4f7db3d808bcecfd838c9
LichAmnesia/LeetCode
/python/230.py
914
3.84375
4
# -*- coding: utf-8 -*- # @Author: Lich_Amnesia # @Email: [email protected] # @Date: 2016-10-01 00:47:36 # @Last Modified time: 2016-10-01 13:06:36 # @FileName: 230.py # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def kthSmallest(self, root, k): """ :type root: TreeNode :type k: int :rtype: int """ return self.get(root, k) def calc(self, r): if r is None: return 0 l = self.calc(r.left) r = self.calc(r.right) return l + r + 1 def get(self, root, k): num = self.calc(root.left) if 1 + num==k: return root.val elif 1+num>k: return self.get(root.left, k) else: return self.get(root.right, k-1-num)
df6918320355f8e4ed958563e713300acefdc7cd
joaovictorfg/Peso2
/PesoIMC2.py
921
3.5625
4
#! /usr/bin/env python #-*- coding: UTF-8 -*- import math import os, sys print( 'IMC') peso = raw_input (' Digite seu peso e aperte enter: ') altura = raw_input ('Digite a sua altura e aperte enter: ') imc = float(peso)/(float(altura)*float(altura)) #print 'Seu IMC é : ', imc if imc <= 17.0: print ("Atenção! Você está abaixo do peso ideal") if imc > 17.0 and imc <= 18.49: print "Seu IMC é: ", imc print "Você está em seu peso normal" if imc > 18.5 and imc <= 24.99: print "Seu IMC é: " , imc print "Atenção! Você está acima de seu peso(sobrepeso)" if imc > 25.0 and imc <= 29.99: print "Seu IMC é: ", imc print "Atenção! Obesidade Grau I" if imc > 35.0 and imc <= 39.9: print "Seu IMC é: ", imc print "Atenção! Obesidade Grau II" if imc > 40.0: print "Seu IMC é: " , imc print "Atenção! Obesidade Grau III" print print "Fim do Programa"
c45763ef758ad83b852f5427b9074fe9fc490e83
paulinho-16/MIEIC-FPRO
/FPRO PLAY/TheCollatzSequence.py
253
3.8125
4
def collatz (n): result = str(n) + ',' while n != 1: if n%2==0: n = round(n/2) result += str(n) + ',' else: n = round(n*3+1) result += str(n) + ',' return result[:len(result)-1]
341ffd50afd5cbc49317fa987842099a1761026a
noorulameenkm/DataStructuresAlgorithms
/SDE_CHEAT_SHEET/Day 3/MajorityElementNBy2.py
1,167
3.890625
4
def majorityElementNByTwo(array): n_by_two = len(array) // 2 for i in range(len(array)): count = 0 for j in range(i, len(array)): if array[j] == array[i]: count += 1 if count > n_by_two: return array[i] def majorityElementNByTwo2(array): n_by_two = len(array) // 2 frequency = {} for num in array: frequency[num] = frequency.get(num, 0) + 1 if frequency[num] > n_by_two: return num # Moore's Algorithm def majorityElementNByTwo3(array): count, element = 0, 0 for num in array: if count == 0: element = num if element == num: count += 1 else: count -= 1 return element def main(): # First Approach print(majorityElementNByTwo([3,2,3])) print(majorityElementNByTwo([2,2,1,1,1,2,2])) # Second Approach print(majorityElementNByTwo2([3,2,3])) print(majorityElementNByTwo2([2,2,1,1,1,2,2])) # Third Approach print(majorityElementNByTwo3([3,2,3])) print(majorityElementNByTwo3([2,2,1,1,1,2,2])) main()
c3c0544c51eb3fd6c385b27ac1d29e59ac22897e
Godul/advent-of-code-2020
/day06/solution.py
672
3.578125
4
QUESTIONS = list(map(chr, range(ord('a'), ord('z') + 1))) def both_parts(): anyone_set = set() everyone_set = set(QUESTIONS) anyone_count = 0 everyone_count = 0 with open('input.txt') as file: for line in file: if line == '\n': anyone_count += len(anyone_set) everyone_count += len(everyone_set) anyone_set.clear() everyone_set.update(QUESTIONS) continue anyone_set.update(line[:-1]) everyone_set.intersection_update(line[:-1]) print(anyone_count) print(everyone_count) if __name__ == '__main__': both_parts()
c0e9579ae7b7a6875f4ffb44341f5909c4ae7ace
etzellux/Python-Demos
/NumPy/numpy_basics_7_shape_manipulation.py
515
3.625
4
#SHAPE MANIPULATION import numpy as np #%% array1 = np.array(10* np.random.random((2,3,3)),dtype=int) print(array1,"\n",) print(array1.ravel(),"\n") #arrayin düzleştirilmiş halini döndürür #%% array2 = np.array([[1,2],[3,4]]) print(array2,"\n") print(array2.T,"\n") #%% array3 = np.array([[1,2,3],[4,5,6]]) print(array3.reshape(3,2),"\n") #arrayin şekillendirilmiş halini döndürür print(array3.shape,"\n") array3.resize(3,2) #resize((n,m)) arrayi şekillendirir print(array3) print(array3.shape,"\n")
49329efa2d83d6c11b520cc7ea1304013acdeaf4
DStazic/Fraud_Analysis_Machine_Learning
/imputation.py
1,580
3.703125
4
#!/usr/bin/python import numpy as np import pandas as pd from fancyimpute import MICE def MultipleImputation(dataset, features): ''' Takes a dataset and a set of feature names that refer to features to be imputed in the dataset. Facilitates multiple imputation technique on missing data and returns the imputed dataset. dataset: dataset with missing values (dataframe) features: set with feature names specifying what features to be grouped for imputation (set or list) ''' # make copy of original dataset to prevent changes in original dataset dataset_copy = dataset.copy() # convert deferred_income to positive values in order to allow log10 transformation if "deferred_income" in features: dataset_copy["deferred_income"] *= -1 # do log10 transformation; +1 to transform 0 values data_log = np.log10(dataset_copy[list(features)]+1) # restrict min value to 0 to avoid <0 imputed values # --> important when fitting imputation model with feature values close to 0 data_filled = MICE(n_imputations=500, verbose=False, min_value=0).complete(np.array(data_log)) data_filled = pd.DataFrame(data_filled) data_filled.index = dataset.index data_filled.columns = data_log.columns # transform back to linear scale; subtract 1 to obtain original non-imputed values data_filled = 10**data_filled-1 # convert deferred_income back to negative values (original values) if "deferred_income" in features: data_filled["deferred_income"] *= -1 return data_filled
1ce16fd50c287cdd9024f1f5fe64e6201e9ba749
ZukGit/Source_Code
/python/plane/plane.py
9,401
3.625
4
#!C:/Users/Administrator/Desktop/demo/python #coding=utf-8 #导入pygame库 import pygame,random,sys,time #sys模块中的exit用于退出 from pygame.locals import * #定义导弹类 class Bullet(object): """Bullet""" def __init__(self, planeName,x,y): if planeName == 'enemy': #敌机导弹向下打 self.imageName = 'Resources/bullet-3.png' self.direction = 'down' elif planeName == 'hero': #英雄飞机导弹向上打 self.imageName = 'Resources/bullet-1.png' self.direction = 'up' self.image = pygame.image.load(self.imageName).convert() self.x = x self.y = y def draw(self,screen): if self.direction == 'down': self.y += 8 elif self.direction == 'up': self.y -= 8 screen.blit(self.image,(self.x,self.y)) #定义一个飞机基类 class Plane(object): """Plane""" def __init__(self): #导弹间隔发射时间1s self.bulletSleepTime = 0.3 self.lastShootTime = time.time() #存储导弹列表 self.bulletList = [] #描绘飞机 def draw(self,screen): screen.blit(self.image,(self.x,self.y)) def shoot(self): if time.time()-self.lastShootTime>self.bulletSleepTime: self.bulletList.append(Bullet(self.planeName,self.x+36,self.y)) self.lastShootTime = time.time() #玩家飞机类,继承基类 class Hero(Plane): """Hero""" def __init__(self): Plane.__init__(self) planeImageName = 'Resources/hero.png' self.image = pygame.image.load(planeImageName).convert() #玩家原始位置 self.x = 200 self.y = 600 self.planeName = 'hero' #键盘控制自己飞机 def keyHandle(self,keyValue): if keyValue == 'left': self.x -= 50 elif keyValue == 'right': self.x += 50 elif keyValue == 'up': self.y -= 50 elif keyValue == 'down': self.y += 50 #定义敌人飞机类 class Enemy(Plane): """docstring for Enemy""" def __init__(self,speed): super(Enemy, self).__init__() randomImageNum = random.randint(1,3) planeImageName = 'Resources/enemy-' + str(randomImageNum) + '.png' self.image = pygame.image.load(planeImageName).convert() #敌人飞机原始位置 self.x = random.randint(20,400) #敌机出现的位置任意 self.y = 0 self.planeName = 'enemy' self.direction = 'down' #用英文表示 self.speed = speed #移动速度,这个参数现在需要传入 def move(self): if self.direction == 'down': self.y += self.speed #飞机不断往下掉 class GameInit(object): """GameInit""" #类属性 gameLevel = 1 #简单模式 g_ememyList = [] #前面加上g类似全局变量 score = 0 #用于统计分数 hero = object @classmethod def createEnemy(cls,speed): cls.g_ememyList.append(Enemy(speed)) @classmethod def makeEnemyEmpty(cls): cls.g_ememyList = [] @classmethod def createHero(cls): cls.hero = Hero() @classmethod def gameInit(cls): cls.createHero() @classmethod def heroPlaneKey(cls,keyValue): cls.hero.keyHandle(keyValue) @classmethod def draw(cls,screen): delPlaneList = [] j = 0 for i in cls.g_ememyList: i.draw(screen) #画出敌机 #敌机超过屏幕就从列表中删除 if i.y > 680: delPlaneList.append(j) j += 1 for m in delPlaneList: del cls.g_ememyList[m] delBulletList = [] j = 0 cls.hero.draw(screen) #画出英雄飞机位置 for i in cls.hero.bulletList: #描绘英雄飞机的子弹,超出window从列表中删除 i.draw(screen) if i.y < 0: delBulletList.append(j) j += 1 #删除加入到delBulletList中的导弹索引,是同步的 for m in delBulletList: del cls.hero.bulletList[m] #更新敌人飞机位置 @classmethod def setXY(cls): for i in cls.g_ememyList: i.move() #自己飞机发射子弹 @classmethod def shoot(cls): cls.hero.shoot() #子弹打到敌机让敌机从列表中消失 ememyIndex = 0 for i in cls.g_ememyList: enemyRect = pygame.Rect(i.image.get_rect()) enemyRect.left = i.x enemyRect.top = i.y bulletIndex = 0 for j in cls.hero.bulletList: bulletRect = pygame.Rect(j.image.get_rect()) bulletRect.left = j.x bulletRect.top = j.y if enemyRect.colliderect(bulletRect): #判断敌机的宽度或者高度,来知道打中哪种类型的敌机 if enemyRect.width == 39: cls.score += 1000 #小中大飞机分别100,500,1000分 elif enemyRect.width == 60: cls.score += 5000 elif enemyRect.width == 78: cls.score += 10000 cls.g_ememyList.pop(ememyIndex) #敌机删除 cls.hero.bulletList.pop(bulletIndex) #打中的子弹删除 bulletIndex += 1 ememyIndex += 1 #判断游戏是否结束 @classmethod def gameover(cls): heroRect = pygame.Rect(cls.hero.image.get_rect()) heroRect.left = cls.hero.x heroRect.top = cls.hero.y for i in cls.g_ememyList: enemyRect = pygame.Rect(i.image.get_rect()) enemyRect.left = i.x enemyRect.top = i.y if heroRect.colliderect(enemyRect): return True return False #游戏结束后等待玩家按键 @classmethod def waitForKeyPress(cls): while True: for event in pygame.event.get(): if event.type == pygame.QUIT: cls.terminate() elif event.type == pygame.KEYDOWN: if event.key == K_RETURN: #Enter按键 return if event.key == 113: #pygame.quit() sys.exit(0) @staticmethod def terminate(): pygame.quit() sys.exit(0) @staticmethod def pause(surface,image): surface.blit(image,(0,0)) pygame.display.update() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: cls.terminate() elif event.type == pygame.KEYDOWN: if event.key == K_SPACE: return @staticmethod def drawText(text,font,surface,x,y): #参数1:显示的内容 |参数2:是否开抗锯齿,True平滑一点|参数3:字体颜色|参数4:字体背景颜色 content = font.render(text,False,(10,100,200)) contentRect = content.get_rect() contentRect.left = x contentRect.top = y surface.blit(content,contentRect) #主循环 if __name__ == '__main__': #初始化pygame pygame.init() #创建一个窗口与背景图片一样大 ScreenWidth,ScreenHeight = 460,680 easyEnemySleepTime = 1 #简单模式下每隔1s创建新的敌机 middleEnemySleepTime = 0.5 hardEnemySleepTime = 0.25 lastEnemyTime = 0 screen = pygame.display.set_mode((ScreenWidth,ScreenHeight),0,32) pygame.display.set_caption('飞机大战') #参数1:字体类型,例如"arial" 参数2:字体大小 font = pygame.font.SysFont(None,64) font1 = pygame.font.SysFont("arial",24) #记录游戏开始的时间 startTime = time.time() #背景图片加载并转换成图像 background = pygame.image.load("Resources/bg_01.png").convert() #背景图片 gameover = pygame.image.load("Resources/gameover.png").convert() #游戏结束图片 start = pygame.image.load("Resources/startone.png") #游戏开始图片 gamePauseIcon = pygame.image.load("Resources/Pause.png") gameStartIcon = pygame.image.load("Resources/Start.png") screen.blit(start,(0,0)) pygame.display.update() #开始显示启动图片,直到有Enter键按下才会开始 GameInit.waitForKeyPress() #初始化 GameInit.gameInit() while True: screen.blit(background,(0,0)) #不断覆盖,否则在背景上的图片会重叠 screen.blit(gameStartIcon,(0,0)) GameInit.drawText('score:%s' % (GameInit.score),font1,screen,80,15) for event in pygame.event.get(): if event.type == pygame.QUIT: GameInit.terminate() elif event.type == KEYDOWN: print(' type = ' +`event.type` +"| key = "+`event.key`) if event.key == K_LEFT: GameInit.heroPlaneKey('left') elif event.key == K_RIGHT: GameInit.heroPlaneKey('right') elif event.key == K_UP: GameInit.heroPlaneKey('up') elif event.key == K_DOWN: GameInit.heroPlaneKey('down') elif event.key == K_SPACE: GameInit.pause(screen,gamePauseIcon) #难度选择方面有bug.因为时间一直继续 interval = time.time() - startTime # easy模式 if interval < 10: if time.time() - lastEnemyTime >= easyEnemySleepTime: GameInit.createEnemy(5) #传入的参数是speed lastEnemyTime = time.time() # middle模式 elif interval >= 10 and interval < 30: if time.time() - lastEnemyTime >= middleEnemySleepTime: GameInit.createEnemy(10) lastEnemyTime = time.time() # hard模式 elif interval >= 30: if time.time() - lastEnemyTime >= hardEnemySleepTime: GameInit.createEnemy(13) lastEnemyTime = time.time() GameInit.shoot() GameInit.setXY() GameInit.draw(screen) #描绘类的位置 GameInit.drawText('%s' % (GameInit.score),font,screen,170,400) pygame.display.update() #不断更新图片 if GameInit.gameover(): time.sleep(1) #睡1s时间,让玩家看到与敌机相撞的画面 screen.blit(gameover,(0,0)) GameInit.drawText('%s' % (GameInit.score),font,screen,170,400) pygame.display.update() GameInit.score = 0 GameInit.waitForKeyPress() GameInit.makeEnemyEmpty() startTime = time.time() lastEnemyTime = time.time() GameInit.gameInit()
db8ed6fb0f0d48b7f2748800292eead7764ac1d3
MGloder/python-alg-exe
/array/move_zeros.py
1,109
3.890625
4
def is_validate(value): return value != 0 class MoveZeros: def __init__(self): """ * Move Zeroes * * - Given an array, move all 0's to the end of the array while maintaining the relative order of others. """ self.array = [0, 1, 0, 2, 5, 0, 3, 2, 0, 0] """ 赋值补0 """ def run(self): self.move_zeros() print(f"move zeros {self.array}") def move_zeros(self): for index in range(0, len(self.array)): if is_validate(self.array[index]): continue next_validate_index = self.find_next_valdiate_index(index) if next_validate_index == -1: break self.array[index] = self.array[next_validate_index] self.array[next_validate_index] = 0 def find_next_valdiate_index(self, index): for next_index in range(index + 1, len(self.array)): if is_validate(self.array[next_index]): return next_index return -1 if __name__ == '__main__': o = MoveZeros() o.run()
816bb95f2a1589c2733791e18900758863604f5b
jozsar/beadando
/43_feladat.py
444
3.5
4
def s_lista(s): ls=[] for i in range(len(s)+1): for j in range(i+1,len(s)+1): ls+=[s[i:j]] ls.sort(key=len) return ls def benne(ls,t): tartalmaz=True for i in ls: for k in t: if k not in i: tartalmaz=False if tartalmaz==True: return i tartalmaz=True return "" s=input("s=") t=input("t=") ls=s_lista(s) print(ls) print(benne(ls,t))
20c2be6108211ecd616c0e89f05c9c4ab2410739
alankrit03/LeetCode_Solutions
/129. Sum Root to Leaf Numbers.py
687
3.5
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def sumNumbers(self, root: TreeNode) -> int: self.ans = 0 def recur(node, curr): if not node: return curr = curr * 10 + node.val if (not node.left) and (not node.right): self.ans += curr return if node.left: recur(node.left, curr) if node.right: recur(node.right, curr) recur(root, 0) return self.ans
b2fd53bdc88b14b023f613aa3b820a94d67aa23f
Code-Abhi/Basic-games
/Tic tac toe/Tic_tac_toe.py
5,687
3.921875
4
def check_win(): #horizontally if board[0]==ch and board[1]==ch and board[2]==ch: print("TIC TAC TOE PLAYER 1 HAS WON") exit() elif board[0]==cy and board[1]==cy and board[2]==cy: print("TIC TAC TOE PLAYER 2 HAS WON") exit() elif board[3]==ch and board[4]==ch and board[5]==ch: print("TIC TAC TOE PLAYER 1 HAS WON") exit() elif board[3]==cy and board[4]==cy and board[5]==cy: print("TIC TAC TOE PLAYER 2 HAS WON") exit() elif board[6]==ch and board[7]==ch and board[8]==ch: print("TIC TAC TOE PLAYER 1 HAS WON") exit() elif board[6]==cy and board[7]==cy and board[8]==cy: print("TIC TAC TOE PLAYER 2 HAS WON") exit() #vertically elif board[0]==ch and board[3]==ch and board[6]==ch: print("TIC TAC TOE PLAYER 1 HAS WON") exit() elif board[0]==cy and board[3]==cy and board[6]==cy: print("TIC TAC TOE PLAYER 2 HAS WON") exit() elif board[1]==ch and board[4]==ch and board[7]==ch: print("TIC TAC TOE PLAYER 1 HAS WON") exit() elif board[1]==cy and board[4]==cy and board[7]==cy: print("TIC TAC TOE PLAYER 2 HAS WON") exit() elif board[3]==ch and board[5]==ch and board[8]==ch: print("TIC TAC TOE PLAYER 1 HAS WON") exit() elif board[2]==cy and board[5]==cy and board[8]==cy: print("TIC TAC TOE PLAYER 2 HAS WON") exit() #diagonally elif board[0]==ch and board[4]==ch and board[8]==ch: print("TIC TAC TOE PLAYER 1 HAS WON") exit() elif board[0]==cy and board[4]==cy and board[8]==cy: print("TIC TAC TOE PLAYER 2 HAS WON") exit() elif board[2]==ch and board[4]==ch and board[6]==ch: print("TIC TAC TOE PLAYER 1 HAS WON") exit() elif board[2]==cy and board[4]==cy and board[6]==cy: print("TIC TAC TOE PLAYER 2 HAS WON") exit() #BOARD_________________________________________________________________________________________ board=[" "," "," ", " "," "," ", " "," "," " ] def display_board(): print(" | "+board[0]+" | "+board[1]+" | "+board[2]+" | ") print(" | "+board[3]+" | "+board[4]+" | "+board[5]+" | ") print(" | "+board[6]+" | "+board[7]+" | "+board[8]+" | ") #GAME_________________________________________________________________________________________________ def playervsplayer(): i=1 while i<6: k=0 while k==0: position=int(input("player 1 enter your position from 1-9: ")) position=position-1 if position<=8: if board[position]==ch or board[position]==cy: print("space already occupied ") else: k=1 board[position]=ch check_win() display_board() else: print("INVALID CHARACTER") if i==5: print("draw") exit() k=0 while k==0: position2=int(input("player 2 enter your position from 1-9: ")) position2=position2-1 if position2<=8: if board[position2]==ch or board[position2]==cy: print("space already occupied ") k=0 else: k=1 board[position2]=cy check_win() display_board() else: print("INVALID POSITION") i=i+1 #player vs comp_____________________________________________________________________________________ import random def playervscomp(): i=1 while i<6: k=0 while k==0: position=int(input("player 1 enter your position from 1-9: ")) position=position-1 if position<=8: if board[position]==ch or board[position]==cy: print("space already occupied ") else: k=1 board[position]=ch check_win() display_board() else: print("INVALID CHARACTER") if i==5: print("draw") exit() k=0 while k==0: position2= random.choice([0,1,2,3,4,5,6,7,8,]) if board[position2]==ch or board[position2]==cy: print("space already occupied ") else: k=1 board[position2]=cy check_win() print(" ") display_board() #USER INPUT________________________________________________________________________________________ v=input("do you want to play 'single player' or 'multiplayer'? ").lower() q=0 while q==0: ch=input("player1 choose your symbol, 'x' or 'o': ").upper() if ch=="X": cy= "O" q=1 elif ch=="O": cy="X" q=1 else: print("invalid charecter") if v== "single player": playervscomp() elif v== "multiplayer": playervsplayer() else: print("INVALID choice, you may not play.") exit()
8ac8f081c5bf2e1529849fd359407e424631093f
catoteig/julekalender2020
/knowitjulekalender/door_04/door_04.py
1,108
3.6875
4
def count_groceries(deliverylist): groceries2 = [] aggregated = [0, 0, 0, 0] # sukker, mel, melk, egg with open(deliverylist) as f: groceries = f.read().splitlines() for element in groceries: groceries2.extend(element.split(',')) groceries2 = [x.strip() for x in groceries2] for element in groceries2: grocerytuple = element.partition(':') if grocerytuple[0] == 'sukker': aggregated[0] += int(grocerytuple[2]) elif grocerytuple[0] == 'mel': aggregated[1] += int(grocerytuple[2]) elif grocerytuple[0] == 'melk': aggregated[2] += int(grocerytuple[2]) elif grocerytuple[0] == 'egg': aggregated[3] += int(grocerytuple[2]) return aggregated def calculate_cakes(deliverylist): aggregated_list = count_groceries(deliverylist) aggregated_list[0] /= 2 aggregated_list[1] /= 3 aggregated_list[2] /= 3 return int(min(aggregated_list)) def test_1(): assert calculate_cakes('leveringsliste_test.txt') == 11 print(calculate_cakes('leveringsliste.txt'))
39865048937d430e610288e1b82a754f23105188
frclasso/DataScience
/Data_Camp_tutorials/Python_for_Spread_Sheet_users/same/script4.py
514
3.5625
4
#!/usr/bin/env python3 import pandas as pd #1 fruit_sales = pd.read_excel("fruit_stores.xlsx") #print(fruit_sales.head()) #2 - summary - by fruit by store totals = fruit_sales.groupby(['store', 'product_name'], as_index=False).sum() print(totals) #3 - sort the summary print() totals = (totals.sort_values('revenue', ascending=False).reset_index(drop=True)) print(totals) # 4 First row for each store print() top_store_sellers = totals.groupby('store').head(1).reset_index(drop=True) print(top_store_sellers)
8e780bdb0743cf302e2dc7d569647a1df3b5c117
luisarcila00/Reto1
/Clase 6/ejercicio_7.py
425
3.71875
4
def imprimir_caracter(caracter): if caracter == 'a' or caracter == 'A': return 'Android' elif caracter == 'i' or caracter == 'I': return 'IOS' else: return 'Opción inválida' print(imprimir_caracter('a')) print(imprimir_caracter('A')) print(imprimir_caracter('i')) print(imprimir_caracter('I')) print(imprimir_caracter('g')) print(imprimir_caracter('V')) print(imprimir_caracter(' '))
9c2a83ec4fd3895efe234ca83f26235889c2e147
Shashanksingh17/python-functional-program
/Distance.py
189
4.15625
4
from math import sqrt x_axis = int(input("Enter the distance in X-Axis")) y_axis = int(input("Enter the distance in Y-Axis")) distance = sqrt(pow(x_axis,2) + pow(y_axis, 2)) print(distance)
f77b9de79e3cefe46c5f517ff00093a11d29ec5d
EdwardBrodskiy/algorithms
/sorts/merge.py
580
3.78125
4
def merge_sort(arr): if len(arr) <= 1: return arr half = len(arr) // 2 lhalf = merge_sort(arr[:half]) rhalf = merge_sort(arr[half:]) return merge(lhalf, rhalf) def merge(a, b): ai, bi = 0, 0 output = [] while ai < len(a) and bi < len(b): if a[ai] < b[bi]: output.append(a[ai]) ai += 1 else: output.append(b[bi]) bi += 1 while ai < len(a): output.append(a[ai]) ai += 1 while bi < len(b): output.append(b[bi]) bi += 1 return output
d246526434485b833e1c78bf11af114c1bf7f1de
Gibbo81/LearningPython
/LearningPython/27ClassCodingBasics.py
4,079
4
4
class FirstClass: MutableField=[1,2,3] #this is an attribute present in all the istance # change in place will affect all the istance but immutable change or new assignment will create a new local variable for istance, the global one is unaffected #Placeorder AAAAAA def SetData(self, value): self.Data=value #this is an attribute is created only in the current running istance def PrintData(self): print(self.Data) class SecondClass(FirstClass): #inheritance def PrintData(self): print("------OVERLOAD------") print('Overloaded method %s :-) :-)' % self.Data) class OverloadPythonOperators: #overload 2 operator: tostring and + def __init__(self, value): self.Data=value def __add__(self, other): return OverloadPythonOperators(self.Data + other.Data) def __str__(self): return str('[This class: %s]' % self.Data) class TestDataPosition: #Placeorder AAAAAA globale = "all" def __init__(self, value): self.data=value print(FirstClass.__dict__) HookNameList= [name for name in FirstClass.__dict__ if name.startswith('__')] print(HookNameList) print('-----------------------------------------------------------------') istance = FirstClass() print('Class start out as an emty namespace instance.__dict__: ',istance.__dict__) #this give out only the attribute of this istance istance.SetData("testing") print('But we can create new attribute in the instance ',istance.__dict__) istance.PrintData() print('-----------------------------------------------------------------') istance2 = FirstClass() istance.MutableField[1]="TTTT" #In place change will affect all the different istance print(istance.MutableField) print(istance2.MutableField) istance.MutableField=34 #not in place we have created a new local variable for istance, the global one is uneffected print('Have created a new local instance: ',istance.__dict__) print(istance.MutableField) print(istance2.MutableField) print('-----------------------------------------------------------------') print('Working with inerithance') istance3 = SecondClass() istance3.SetData("Second is better") istance.PrintData() istance3.PrintData() print('-----------------------------------------------------------------') print("Using overloaded operator") x1=OverloadPythonOperators("base ") x2=OverloadPythonOperators("avanzato") print(x1+x2) #uses both + and tostring print('-----------------------------------------------------------------') #Placeorder AAAAAA print("Let's check where pyton put the different operator") #REALLY IMPORTANT u1=TestDataPosition('First') u2=TestDataPosition('Second') print('class TestDataPosition defined parameter: ',[name for name in TestDataPosition.__dict__ if not name.startswith('__')]) print("List of __dict__ of the first instance: ", list(u1.__dict__.keys())) print("List of __dict__ of the second instance: ", list(u2.__dict__.keys())) u1.globale="new global" print("With u1.globale='new global' I have not changed the global value but defined a new attribute for istance u1") TestDataPosition.globale="to change all" #to change the global one i need to do this! print("List of __dict__ of the first instance: ", list(u1.__dict__.keys())) print("List of __dict__ of the second instance: ", list(u2.__dict__.keys())) #The main point to take away from this look under the hood is that Python’s class model #is extremely dynamic. Classes and instances are just namespace objects, with attributes #created on the fly by assignment. Those assignments usually happen within the class #statements you code, but they can occur anywhere you have a reference to one of the #objects in the tree. #Instances of the same class do not have to have the same set of attribute because instance are #distinct namespace!!!!! #It's the same of global variable, in reading i go up to the three but in writing i create a new local vaiable!!!! print('-----------------------------------------------------------------')
7f2a98a34682d7d225649a2f2e996b35b66aa643
doom2020/doom
/sort-insert.py
825
3.90625
4
def insertion_sort(arr): """插入排序""" # 第一层for表示循环插入的遍数 for i in range(1, len(arr)): # 设置当前需要插入的元素 current = arr[i] # 与当前元素比较的比较元素 pre_index = i - 1 while pre_index >= 0 and arr[pre_index] > current: # 当比较元素大于当前元素则把比较元素后移 arr[pre_index + 1] = arr[pre_index] # 往前选择下一个比较元素 pre_index -= 1 # 当比较元素小于当前元素,则将当前元素插入在 其后面 arr[pre_index + 1] = current return arr insertion_sort([11, 11, 22, 33, 33, 36, 39, 44, 55, 66, 69, 77, 88, 99]) # 返回结果[11, 11, 22, 33, 33, 36, 39, 44, 55, 66, 69, 77, 88, 99]
6fe720349f891b99c20cc803503716c3a8a193ed
robotBaby/linearAlgebrapython
/HW1.py
748
3.859375
4
from sympy import * init_printing(use_unicode=True) #Problem8 a = Matrix([[1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5], [1,2,3,4,5]]) A3 = a*a*a print "Answer to question 8: A^3= " pprint(A3) print "\n" #Problem9 A = Matrix([[2,4,5], [2,6,1], [-2, 9, 15], [12, 0, 15], [3, 34, -52]]) B = Matrix([[2,4,5,4], [2,6,1,4], [-2,9,15,4]]) AB = A*B ABt = AB.T print "Answer to question 9: AB^t= " pprint(ABt) print "\n" #Problem10 M = Matrix([[2,4,5], [2,6,1], [-2,9, 15], [12, 0, 15], [3, 34, -52]]) Mrank = M.rank() print "Answer to question 10: Rank of matrix M= " pprint(Mrank) print "\n" #Problem11 Mm = Matrix([[1,0,1,3], [2,3,4,7], [-1,-3,-3,-4]]) Mmrref= Mm.rref()[0] print "Answer to question 11: Row echolon form of M= " pprint(Mmrref)
ff775119df7eb28b922b290967ad35a0239d5bc3
RaghavTheGreat1/code_chef
/Data Strucures & Algorithm/Complexity Analysis + Basics Warm Up/LRNDSA01.py
457
4.25
4
# Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits. # Example # Input: # 1 # 2 # 88 # 42 # 99 # Output: # 1 # 2 # 88 userInput = int(input()) while userInput != 42: print(userInput) userInput = int(input())
e4529b76a695c341fe847c38735e9fee18b4b67f
amiraliakbari/sharif-mabani-python
/by-session/ta-922/j8/a3.py
151
3.6875
4
def f(n): if n < 2: print 'A' return 1 a = f(n-1) print 'B' b = f(n-2) print 'C' return a + b f(6)
daaf672775550230e18397d382e5d3dbbd18e1a6
xxxxgrace/COMP1531-19T3
/Labs/lab01/19T3-cs1531-lab01/integers.py
239
4.03125
4
# Author: @abara15 (GitHub) ''' TODO Complete this file by following the instructions in the lab exercise. ''' integers = [1, 2, 3, 4, 5] integers.append(6) x = 0 for integer in integers: x += integer print(x) print(sum(integers))
434d57d7265a3932b4cb6cdca1606f65894cd547
Shruthi21/Algorithms-DataStructures
/14_BoatTrips.py
407
3.515625
4
#!/bin/python import sys def BoatTrip(n,c,m,p): capacity = c * m flag = 0 if len(p) == n: if max(p) > capacity: return 'No' else: return 'Yes' if __name__ == '__main__': n,c,m = raw_input().strip().split(' ') n,c,m = [int(n),int(c),int(m)] p = map(int, raw_input().strip().split(' ')) print BoatTrip(n,c,m,p)
d4bc41404a89437c5ee8ee4c62b33b90fc05efd0
apethani21/project-euler
/solutions/p16.py
253
3.953125
4
import time start_time = time.time() def digit_sum(n): s = 0 while n: s += n%10 n //= 10 return s print(digit_sum(2**1000)) end_time = time.time() print("Time taken: {} ms".format(round((end_time - start_time)*1000, 3)))
a0bf957342bf38edf181ae8d9d9b22c36adc89ca
NetJagaimo/Algorithm-and-Data-Structure-With-Python
/3_basic_data_structure/balanced_symbol.py
797
3.5625
4
''' 使用stack作為核對大中小括號的實作方式 ''' from stack import Stack def symChecker(symbolString): s = Stack() balenced = True index = 0 while index < len(symbolString) and balenced: symbol = symbolString[index] if symbol in "([{": s.push(symbol) else: if s.isEmpty(): balenced = False else: top = s.pop() if not matches(top, symbol): balenced = False index += 1 if balenced and s.isEmpty(): return True else: return False def matches(open, close): opens = "([{" closers = ")]}" return opens.index(open) == closers.index(close) print(symChecker("{[][]")) print(symChecker("{()[]{}}"))
068fb7fba7401a53ec6f09f1da6f8040d725b930
Adomkay/python-attributes-functions-school-domain-nyc-career-ds-062518
/school.py
542
3.671875
4
class School: def __init__(self, name): self._roster = {} self._name = name def roster(self): return self._roster def add_student(self, name, grade): if grade in self._roster: self._roster[grade].append(name) else: self._roster[grade] = [name] def grade(self, grade): return self._roster[grade] def sort_roster(self): for grade, names in self._roster.items(): self._roster[grade] = sorted(names) return self._roster
5ca765533611abf1250ea2897f71d78fd8b7131f
Angel07/Restaurante_Biggby_coffee
/EmployeeDB.py
538
3.640625
4
import sqlite3 con = sqlite3.connect("employee.db") print("BASE DE DATOS CREADA CON EXITO") con.execute("create table Employees (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, contraseña TEXT NOT NULL, address TEXT NOT NULL, tipo_usuario TEXT NOT NULL)") print("TABLA EMPLEADO CREADA SATISFACTORIAMENTE!!") con.execute("create table Bebidas (id INTEGER PRIMARY KEY AUTOINCREMENT, nombre TEXT NOT NULL, descripcion TEXT NOT NULL, valoracion INTEGER)") print("Tabla bebidas creada con exito") con.close()
10313e1029c082effde78494e6afc3da69a268a9
live2skull/TheLordOfAlgorithm
/problems_boj/스택/4949.py
928
3.625
4
## 균형잡힌 세상 - 4949(스택) import sys def int_input(): return int(input()) def ints_input(): r = input().split(' ') for _r in r: yield int(_r) from collections import deque char_open = ('(', '[') char_close = (')', ']') def main(): stack = deque() for line in sys.stdin: stack.clear() # 객체를 매번 다시 만들 필요는 없음. line = line[:-2] # 개행 문자 / 마지막 '.' 문자 if len(line) == 0: break result = True for _char in line: # type: str if _char in char_open: stack.appendleft(_char) elif _char in char_close: _cidx = char_close.index(_char) if not stack or stack.popleft() != char_open[_cidx]: result = False break print('no' if not result or stack else 'yes') # *_* if __name__ == '__main__': main()
71d86a6ba63f2a7e3da3ca985cb6f94b52281dc0
Jaseamsmith/U4L4
/problem4.py
320
4.15625
4
from turtle import * charlie = Turtle() nana = Turtle() charlie.color("blue") charlie.pensize(5) charlie.speed(5) charlie.shape("turtle") nana.color("green") nana.pensize(5) nana.speed(5) nana.shape("turtle") for x in range(1): charlie.circle(100) for y in range(3): nana.forward(100) nana.left(120) mainloop()
45c67000244cfa3d98ccee6c8f672cfa15ea4ba1
intellivoid/CoffeeHousePy
/deps/scikit-image/doc/examples/filters/plot_entropy.py
2,401
3.640625
4
""" ======= Entropy ======= In information theory, information entropy is the log-base-2 of the number of possible outcomes for a message. For an image, local entropy is related to the complexity contained in a given neighborhood, typically defined by a structuring element. The entropy filter can detect subtle variations in the local gray level distribution. In the first example, the image is composed of two surfaces with two slightly different distributions. The image has a uniform random distribution in the range [-15, +15] in the middle of the image and a uniform random distribution in the range [-14, 14] at the image borders, both centered at a gray value of 128. To detect the central square, we compute the local entropy measure using a circular structuring element of a radius big enough to capture the local gray level distribution. The second example shows how to detect texture in the camera image using a smaller structuring element. """ ###################################################################### # Object detection # ================ import matplotlib.pyplot as plt import numpy as np from skimage import data from skimage.util import img_as_ubyte from skimage.filters.rank import entropy from skimage.morphology import disk noise_mask = np.full((128, 128), 28, dtype=np.uint8) noise_mask[32:-32, 32:-32] = 30 noise = (noise_mask * np.random.random(noise_mask.shape) - 0.5 * noise_mask).astype(np.uint8) img = noise + 128 entr_img = entropy(img, disk(10)) fig, (ax0, ax1, ax2) = plt.subplots(nrows=1, ncols=3, figsize=(10, 4)) img0 = ax0.imshow(noise_mask, cmap='gray') ax0.set_title("Object") ax1.imshow(img, cmap='gray') ax1.set_title("Noisy image") ax2.imshow(entr_img, cmap='viridis') ax2.set_title("Local entropy") fig.tight_layout() ###################################################################### # Texture detection # ================= image = img_as_ubyte(data.camera()) fig, (ax0, ax1) = plt.subplots(ncols=2, figsize=(12, 4), sharex=True, sharey=True) img0 = ax0.imshow(image, cmap=plt.cm.gray) ax0.set_title("Image") ax0.axis("off") fig.colorbar(img0, ax=ax0) img1 = ax1.imshow(entropy(image, disk(5)), cmap='gray') ax1.set_title("Entropy") ax1.axis("off") fig.colorbar(img1, ax=ax1) fig.tight_layout() plt.show()
4b71c11166bfdc1b71d200e07f12b27cbb254bfd
ThenuVijay/Practice-Programs
/homework.py
1,369
3.8125
4
row =1 while row<=5: col = 1 while col<=row: print(row,end=' ') col+=1 print() row+=1 # output # 1 # 2 2 # 3 3 3 # 4 4 4 4 # 5 5 5 5 5 row =1 while row<=5: col = 1 while col<=row: print((col+row),end=' ') col+=1 print() row+=1 # output # 2 # 3 4 # 4 5 6 # 5 6 7 8 # 6 7 8 9 10 row =1 while row<=5: col = 1 while col<=row: print((col*row),end=' ') col+=1 print() row+=1 # output # 1 # 2 4 # 3 6 9 # 4 8 12 16 # 5 10 15 20 25 row =1 while row<=5: col = 1 while col<=row: print((col-row),end=' ') col+=1 print() row+=1 #2 # output # 0 # -1 0 # -2 -1 0 # -3 -2 -1 0 # -4 -3 -2 -1 0 # sentence=input("Enter sentence: ") # wordcount=1 # i=0 # while i<len(sentence)-1: # if sentence[i]==' ': # wordcount+=1 # i+=1 # print(wordcount) paragraph=input("Enter paragraph: ") sentencecount=1 i=0 while i<len(paragraph)-1: if paragraph[i]=='.': sentencecount+=1 i+=1 print("The number of sentences in the paragraph are:",sentencecount) row =1 while row<=5: col = 1 while col<=row: print(row,end=' ') col+=1 print() row+=2 #2 # output # 1 # 3 3 3 # 5 5 5 5 5 row =1 while row<=5: col = 1 while col<=row: print(row,end=' ') col+=2 print() row+=1 #output # 1 # 2 # 3 3 # 4 4 # 5 5 5
23c85c36d25af35a22ffccdac1ea7c39c9d632e1
debazi/python-projets
/modules/sqlite3-with-prettytable/crudSqlite3.py
1,260
3.765625
4
import sqlite3 from prettytable import * # creation et connection à la base de donnée conn = sqlite3.Connection('./db/crudDB.db') cursor = conn.cursor() #cursor.execute("""DROP TABLE IF EXISTS users""") # creation de la table utilisateur cursor.execute( """CREATE TABLE IF NOT EXISTS users( id INTEGER PRIMARY KEY, username TEXT, fullname TEXT, password TEXT )""" ) conn.commit() # creation du formulaire de saisie nb = 'o' while nb != 'f': print('=================================') username = input('Nom utilisateur: ') fullname = input('Nom complet: ') password = input('Mot de passe: ') # liste des données et insertion dans la base de donnée usersData = (username, fullname, password) cursor.execute( """INSERT INTO users(username, fullname, password) VALUES (?,?,?)""", usersData, ) conn.commit() print('---------------------------------') nb = input('Continuez la saisie? [o/f] ') # affichage des utilisateurs with conn: cursor.execute("""SELECT username, fullname FROM users""") tab = from_db_cursor(cursor) print(tab) print(' ') print("Merci d'avoir utilisé notre programme ")
2dfd2927fb560238d4f708fa13d66b290de870bc
kailinshi1989/leetcode_lintcode
/170. Two Sum III - Data structure design.py
1,570
3.890625
4
class TwoSum(object): def __init__(self): self.map = {} def add(self, number): if number in self.map: self.map[number] += 1 else: self.map[number] = 1 def find(self, value): for number in self.map: if value - number in self.map and (value - number != number or self.map[number] > 1): return True return False # Your TwoSum object will be instantiated and called as such: # obj = TwoSum() # obj.add(number) # param_2 = obj.find(value) """ 精简版 """ class TwoSum(object): def __init__(self): """ Initialize your data structure here. """ self.hash = {} def add(self, number): """ Add the number to an internal data structure.. :type number: int :rtype: None """ if number in self.hash: self.hash[number] += 1 else: self.hash[number] = 1 def find(self, value): """ Find if there exists any pair of numbers which sum is equal to the value. :type value: int :rtype: bool """ for num in self.hash: target = value - num if target == num and self.hash[num] > 1: return True elif target in self.hash and target != num: return True return False # Your TwoSum object will be instantiated and called as such: # obj = TwoSum() # obj.add(number) # param_2 = obj.find(value)
a0662d628774efbdb67ee1bc180377f05ac76afb
andrewharukihill/ProjectEuler
/55.py
572
3.640625
4
import time def reverse(num): num = str(num)[::-1] return int(num) def lychrel(num, iteration): if (iteration==50): return 1 else: rev = reverse(num) if (num == rev and iteration != 0): return 0 else: return lychrel(num+rev, iteration + 1) def main(): start_time = time.time() range_lim = 100000 out_sum = 0 for i in range(1,range_lim): out_sum += lychrel(i, 0) print("There are " + str(out_sum) + " Lychrel numbers from 1 to " + str(range_lim)) elapsed_time = time.time() - start_time print("\nTime elapsed: " + str(elapsed_time)) main()
1deecaca1ca8410c596d762e6589e70e4934cc40
adriano662237/fatec_ferraz_20211_ids_introducao_git
/calculadora.py
412
4.21875
4
a = int(input("Digite o primeiro valor")) b = int(input("Digite o segundo valor")) operacao = input("+: Soma\n-: Subtração\n: Multiplicação\n/:Divisão\n**: Exponenciação") if operação == '+': resultado = a + b elif operação == '-': resultado = a - b elif operação == '*': resultado = a * b elif operação == '/': resultado = a // b else: resultado = a ** b print(resultado)
3c494a8d7c5f824892cf3040d65ab94cd28ce1d2
jsmlee/123-Python
/helper_functions/character_model.py
729
3.546875
4
import pygame wLeft = [] wRight = [] still =[] num_sprite = 10 #sprite correlating to action,add to if more actions are added class player(): def __init__(self,xPos,yPos,pWidth,pHeight): self.xPos = xPos self.yPos = yPos self.pWidth = pWidth self.pHeight = pHeight self.wLeft = False self.wRight = False self.walkPos = 0 def draw(self, win): if walkPos > num_sprite: walkPos = 0 if self.wLeft: win.blit(wLeft[self.walkPos], (self.xPos,self.yPos)) elif self.wRight: win.blit(wRight[self.walkPos], (self.xPos,self.yPos)) else: win.blit(still, (self.xPos,self.yPos))
7b2fbe7171910720724e933e0d5a0a3cd3bd0c45
stephenrobic/PythonTargetPractice
/Target Practice.py
15,634
3.671875
4
import tkinter as tk import turtle import random class Darts: def __init__(self): self.scores = [500, 700] self.main_window = tk.Tk() # self.newgame_window = tk.Tk() #create frames for start screen self.title_frame = tk.Frame(self.main_window) self.buttons_frame = tk.Frame(self.main_window) self.version_frame = tk.Frame(self.main_window) #create title/label self.title_label = tk.Label(self.title_frame, text = "Welcome to Darts 2DX") self.title_label.pack() #create buttons self.newGame_button = tk.Button(self.buttons_frame, text = "New Game", command = self.chooseOptions, bg = 'green') self.highScores_button = tk.Button(self.buttons_frame, text = "High Scores", command = self.open_scores, bg = 'orange') self.quit_button = tk.Button(self.buttons_frame, text='Exit Game', command=self.main_window.destroy, bg = 'red') self.newGame_button.pack() self.highScores_button.pack() self.quit_button.pack() #version by bottom label self.version_label = tk.Label(self.version_frame, text = "version: s.r.0.5") self.version_label.pack() self.title_frame.pack() self.buttons_frame.pack() self.version_frame.pack() tk.mainloop() #!!!options (2n !window! for a new game def chooseOptions(self): self.main_window.destroy() #close main window self.options_window = tk.Tk() #create frames for Options New Game(2nd) window self.optionsTitle_frame = tk.Frame(self.options_window) self.color_frame = tk.Frame(self.options_window) self.difficulty_frame = tk.Frame(self.options_window) self.startButton_frame = tk.Frame(self.options_window) #create title: Options self.optionsTitle_label = tk.Label(self.optionsTitle_frame, text = "OPTIONS", font = ('Arial', 15)) self.optionsTitle_label.pack() #1st option: Color (title and radiobutton choices underneath) #1. Choose Color label self.color_label = tk.Label(self.color_frame, text = "\nChoose Color", font =('Arial', 12)) self.color_label.pack() #2. color radiobuttons #StringVar for radiobuttons self.color_rb_var = tk.StringVar(value='green') #set StringVar to green #self.color_rb_var.set('green') #create the radiobutton widgets for color in options frame self.yellow_rb = tk.Radiobutton(self.color_frame, text = 'Purple', bg = 'purple', variable = self.color_rb_var, value = 'purple', tristatevalue=0) #command = self.'add method ) self.green_rb = tk.Radiobutton(self.color_frame, text = 'Green', bg = 'green', variable = self.color_rb_var, value = 'green') self.red_rb = tk.Radiobutton(self.color_frame, text = 'Red', bg = 'red', variable = self.color_rb_var, value = 'red', tristatevalue=0) self.blue_rb = tk.Radiobutton(self.color_frame, text = 'Blue', bg = 'blue', variable = self.color_rb_var, value = 'blue', tristatevalue=0 ) self.yellow_rb.pack(side = 'left') self.green_rb.pack(side = 'left') self.red_rb.pack(side = 'left') self.blue_rb.pack(side = 'left') #3. Choose Difficulty label self.difficulty_label = tk.Label(self.difficulty_frame, text = "\nChoose Difficulty", font = ('Arial', 12)) self.difficulty_label.pack() #4. difficulty radiobuttons #StringVar for radiobuttons self.difficulty_rb_var = tk.StringVar() #set StringVar to easy self.difficulty_rb_var.set('easy') #create the radiobutton widgets for difficulty in options frame self.easy_rb = tk.Radiobutton(self.difficulty_frame, text = 'Easy', fg = 'chartreuse', variable = self.difficulty_rb_var, value = 'easy') self.hard_rb = tk.Radiobutton(self.difficulty_frame, text = 'Hard', fg = 'dark red', variable = self.difficulty_rb_var, value = 'hard', tristatevalue=0) self.easy_rb.pack(side = 'left') self.hard_rb.pack(side = 'left') #start game button self.start_button = tk.Button(self.startButton_frame, text = 'Start Game', command = self.game) #command to link to board for game self.start_button.pack() #pack frames self.optionsTitle_frame.pack() self.color_frame.pack() self.difficulty_frame.pack() self.startButton_frame.pack() def game(self): self.options_window.destroy() # Named constants self.SCREEN_WIDTH = 600 # Screen width self.SCREEN_HEIGHT = 600 # Screen height if self.difficulty_rb_var.get() == 'easy': #easy mode settings = square double size (50) self.TARGET_LLEFT_X = random.randint(-289,245) # Target's lower-left X self.TARGET_LLEFT_Y = random.randint (-289, 245) # Target's lower-left Y self.TARGET_WIDTH = 50 # Width of the target elif self.difficulty_rb_var.get() == 'hard': #hard mode = square 25 width self.TARGET_LLEFT_X = random.randint(-289,265) # Target's lower-left X self.TARGET_LLEFT_Y = random.randint (-289, 265) # Target's lower-left Y self.TARGET_WIDTH = 25 # Width of the target self.FORCE_FACTOR = 30 # Arbitrary force factor self.PROJECTILE_SPEED = 1 # Projectile's animation speed self.NORTH = 90 # Angle of north direction self.SOUTH = 270 # Angle of south direction self.EAST = 0 # Angle of east direction self.WEST = 180 # Angle of west direction # Setup the window. turtle.setup(self.SCREEN_WIDTH, self.SCREEN_HEIGHT) # Draw the target. turtle.hideturtle() turtle.speed(0) turtle.penup() turtle.goto(self.TARGET_LLEFT_X, self.TARGET_LLEFT_Y) turtle.pendown() turtle.setheading(self.EAST) turtle.forward(self.TARGET_WIDTH) turtle.setheading(self.NORTH) turtle.forward(self.TARGET_WIDTH) turtle.setheading(self.WEST) turtle.forward(self.TARGET_WIDTH) turtle.setheading(self.SOUTH) turtle.forward(self.TARGET_WIDTH) #Draw inner target turtle.hideturtle() turtle.speed(0) turtle.penup() self.inner_width = self.TARGET_WIDTH * .4 self.inner_target_x = self.TARGET_LLEFT_X + (.3 * self.TARGET_WIDTH) self.inner_target_y = self.TARGET_LLEFT_Y + (.3 * self.TARGET_WIDTH) turtle.goto(self.inner_target_x, self.inner_target_y) turtle.pendown() turtle.setheading(self.EAST) turtle.forward(self.inner_width) turtle.setheading(self.NORTH) turtle.forward(self.inner_width) turtle.setheading(self.WEST) turtle.forward(self.inner_width) turtle.setheading(self.SOUTH) turtle.forward(self.inner_width) #change turtle color turtle.color(self.color_rb_var.get()) self.lives = 3 self.score = 0 while (self.lives > 0): # Center the turtle. turtle.penup() turtle.goto(0, 0) turtle.pendown() turtle.setheading(self.EAST) turtle.showturtle() turtle.speed(self.PROJECTILE_SPEED) # Get the angle and force from the user. self.angle = float(input("\nEnter the projectile's angle: ")) self.force = float(input("Enter the launch force (1-12): ")) # Calculate the distance. self.distance = self.force * self.FORCE_FACTOR # Set the heading. turtle.setheading(self.angle) # Launch the projectile. turtle.pendown() turtle.forward(self.distance) # Did it hit the target? #main target if (turtle.xcor() >= self.TARGET_LLEFT_X and turtle.xcor() <= (self.TARGET_LLEFT_X + self.TARGET_WIDTH) and turtle.ycor() >= self.TARGET_LLEFT_Y and turtle.ycor() <= (self.TARGET_LLEFT_Y + self.TARGET_WIDTH)): self.score += 100 #extra 100 if inner target hit if (turtle.xcor() >= self.inner_target_x and turtle.xcor() <= (self.inner_target_x + self.inner_width) and turtle.ycor() >= self.inner_target_y and turtle.ycor() <= (self.inner_target_y + self.inner_width)): self.score += 100 print('Target hit! Your score is now: ' + str(self.score)) tk.messagebox.showinfo('You hit the target!', 'Great, you hit the target!') #clear board turtle.clear() if self.difficulty_rb_var.get() == 'easy': #easy mode settings = square double size (50) self.TARGET_LLEFT_X = random.randint(-289,245) # Target's lower-left X self.TARGET_LLEFT_Y = random.randint (-289, 245) # Target's lower-left Y self.TARGET_WIDTH = 50 # Width of the target elif self.difficulty_rb_var.get() == 'hard': #hard mode = square 25 width self.TARGET_LLEFT_X = random.randint(-289,265) # Target's lower-left X self.TARGET_LLEFT_Y = random.randint (-289, 265) # Target's lower-left Y self.TARGET_WIDTH = 25 # Width of the target # Draw the target. turtle.hideturtle() turtle.speed(0) turtle.penup() turtle.goto(self.TARGET_LLEFT_X, self.TARGET_LLEFT_Y) turtle.pendown() turtle.setheading(self.EAST) turtle.forward(self.TARGET_WIDTH) turtle.setheading(self.NORTH) turtle.forward(self.TARGET_WIDTH) turtle.setheading(self.WEST) turtle.forward(self.TARGET_WIDTH) turtle.setheading(self.SOUTH) turtle.forward(self.TARGET_WIDTH) #Draw inner target turtle.hideturtle() turtle.speed(0) turtle.penup() self.inner_width = self.TARGET_WIDTH * .4 self.inner_target_x = self.TARGET_LLEFT_X + (.3 * self.TARGET_WIDTH) self.inner_target_y = self.TARGET_LLEFT_Y + (.3 * self.TARGET_WIDTH) turtle.goto(self.inner_target_x, self.inner_target_y) turtle.pendown() turtle.setheading(self.EAST) turtle.forward(self.inner_width) turtle.setheading(self.NORTH) turtle.forward(self.inner_width) turtle.setheading(self.WEST) turtle.forward(self.inner_width) turtle.setheading(self.SOUTH) turtle.forward(self.inner_width) else: self.lives -= 1 print('You missed the target. You now have ' + str(self.lives) + ' lives.' + '\nYour score is: ' + str(self.score) ) #Game Over (lives = 0) tk.messagebox.showinfo('Game Over', 'Game Over! Your score is ' + str(self.score) + '!!!') self.enter_score() def enter_score(self): self.enterScore_window = tk.Tk() #frames self.score_title_frame = tk.Frame(self.enterScore_window) self.score_entername_frame = tk.Frame(self.enterScore_window) self.score_enterbutton_frame = tk.Frame(self.enterScore_window) #title label including score self.score_title_label = tk.Label(self.score_title_frame, text = 'Congrats! Your score is: ' + str(self.score)) self.score_title_label.pack() #create Label and Entry to enter name self.name_label = tk.Label(self.score_entername_frame, text = '\nYou made the top 10 list, Enter Your Initials: ') self.name_entry = tk.Entry(self.score_entername_frame, width = 10) self.name_label.pack(side = 'left') self.name_entry.pack(side = 'left') #create button to enter name self.enter_button = tk.Button(self.score_enterbutton_frame, text = 'Enter', command = self.writeScoreToFile) self.enter_button.pack() #pack frames self.score_title_frame.pack() self.score_entername_frame.pack() self.score_enterbutton_frame.pack() #label to enter score name #if score is high enough, enter name def writeScoreToFile(self): outfile = open('scores.txt', 'a') self.iname = self.name_entry.get() outfile.write(str(self.iname) + '\t' + str(self.score) + '\n') self.enterScore_window.destroy() outfile.close() def open_scores(self): #open file to read to GUI window infile = open('scores.txt', 'r') self.scores_window = tk.Tk() self.scoresTitle_frame = tk.Frame(self.scores_window) self.scores_frame = tk.Frame(self.scores_window) #create title: High Scores self.scoresTitle_label = tk.Label(self.scoresTitle_frame, text = "HIGH SCORES") self.scoresTitle_label.pack() #create listbox to display scores self.score_listbox = tk.Listbox(self.scores_frame, width = 30, height = 32) self.score_listbox.pack() #add scores to list for line in infile: self.score_listbox.insert(tk.END, line) self.scoresTitle_frame.pack() self.scores_frame.pack() darts = Darts()
5576e132990431909b2fac3ac24e0375b4097097
AdamZhouSE/pythonHomework
/Code/CodeRecords/2133/60837/238728.py
497
3.53125
4
def findMax(list): max=0 for i in range(len(list)): if list[i]>max: max=list[i] return max def isNotEqual(list): for i in range(len(list)-1): if list[i]!=list[i+1]: return True return False list=list(map(int,input().split(','))) max=findMax(list) result=0 while isNotEqual(list): for i in range(len(list)): if list[i]!=max: list[i]+=1 max+=1 max=findMax(list) result+=1 print(result)
93bc310d76b1478b59a78a24bc93dd2a08bdd730
ilya-lebedev/hhhomework2021
/core/classes.py
1,488
4.1875
4
class Car: # Реализовать класс машины Car, у которого есть поля: марка и модель автомобиля # Поля должны задаваться через конструктор def __init__(self, model, brand): self.model = model self.brand = brand def __str__(self): return self.model + ' ' + self.brand class Garage: # Написать класс гаража Garage, у которого есть поле списка машин # Поле должно задаваться через конструктор # По аналогии с классом Company из лекции реализовать интерфейс итерируемого # Реализовать методы add и delete(удалять по индексу) машин из гаража def __init__(self, cars): self.cars = cars def __iter__(self): return iter(self.cars) def __str__(self): return ' '.join(str(car) for car in self.cars) def add(self, car): self.cars.append(car) def delete(self, index): self.cars.pop(index) if __name__ == '__main__': car1 = Car('m1', 'b1') car2 = Car('m2', 'b2') cars = [car1, car2] garage = Garage(cars) print(garage) car3 = Car('m3', 'b3') garage.add(car3) print(garage) garage.delete(1) print(garage) for car in garage: print(car)
c36fd102bd30b22fc91b2e447a1b403c5636ffa9
elijahsk/cpy5python
/practical03/q07_display_matrix.py
854
4.28125
4
# Name: q07_display_matrix.py # Author: Song Kai # Description: Display a n*n matrix with 1 and 0 generated randomly # Created: 20130215 # Last Modified: 20130215 import random # check whether the string can be converted into a number def check(str): if str.isdigit(): return True else: print("Please enter a proper number!") return False # actual random printing process def print_matrix(n): # n rows for i in range(0,n): print(random.randint(0,1),end="") # n columns for j in range(1,n): print(" ",random.randint(0,1),end="") print() # input the dimension n=input("Enter the dimension of the matrix: ") # check until n is really a number while not check(n): n=input("Enter the dimension of the matrix: ") # print print("Below is the matrix generated:") print_matrix(int(n))
e9aa7bc8802dc5bbe3fefe2c1c6246bb90186ecb
GlenboLake/DailyProgrammer
/C214E_standard_deviation.py
379
3.84375
4
from math import sqrt def stddev(items): items = [float(x) for x in items] avg = sum(items)/len(items) var = sum([(x-avg)**2 for x in items])/len(items) return sqrt(var) def numlist(s): return [int(x) for x in s.split(' ')] print(stddev('5 6 11 13 19 20 25 26 28 37'.split())) print(stddev('37 81 86 91 97 108 109 112 112 114 115 117 121 123 141'.split()))
c50a8bcb2d2edec2bcff8109128d892458264aa5
birdhermes/CourseraPython
/5_week/Флаги.py
1,010
4.1875
4
# Напишите программу, которая по данному числу n от 1 до 9 выводит на экран n флагов. Изображение одного флага имеет # размер 4×4 символов, между двумя соседними флагами также имеется пустой (из пробелов) столбец. Разрешается вывести # пустой столбец после последнего флага. Внутри каждого флага должен быть записан его номер — число от 1 до n. Формат # ввода Вводится натуральное число. Формат вывода Выведите ответ на задачу. n = int(input()) for i in range(n): print('+___', end=' ') print() for i in range(n): print('|%s /' % (i+1), end=' ') print() for i in range(n): print('|__\\', end=' ') print() for i in range(n): print('| ', end=' ') print()
b9ea50eae4b8e47b186eaba6d2c45e6d385eb8c4
semmons1/Unix_File_Sytem
/project/bhelper.py
1,008
3.625
4
import os, sys def main(): ## validate command line args if len(sys.argv) == 1 or len(sys.argv) > 3: print("Usage: python bhelper.py <driver number> [<type of output>]") if not sys.argv[1] in range(1, 7): print("Please input a driver number between 1 and 6") if len(sys.argv) == 3 and (sys.argv[2] != 'f' or sys.argv[2] != 'c' or sys.argv[2] != 'a'): print("Please input a valid output type: f for failures, c for corrects, or a for all") driverNumber = sys.argv[1] outputType = 'a' if len(sys.argv) == 3: outputType = sys.argv[2] if outputType == 'a': outputType = '\"\"' elif outputType == 'f': outputType = 'fail\" | grep -v \"failed' else: outputType = 'correct' ## run the script os.system('make clean') os.system('make') for i in range(1, int(driverNumber) + 1): os.system('./drTester' + str(i) + ' | grep \"' + outputType + '\"') if __name__ == "__main__": main()
f5d1b04554ae41f5320e38e39ab3cbfff6826145
SensumVitae13/PythonGB
/LS1_3.py
395
3.75
4
# Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn. # Например, пользователь ввёл число 3. Считаем 3 + 33 + 333 = 369. n = int(input("Введите число n от 1 до 9: ")) amount = (n + int(str(n) + str(n)) + int(str(n) + str(n) + str(n))) print(f"Сумма чисел n+n+nnn = {amount}")
15af59e32baf53c3e99bfbcf5ee624468bc2169a
hoklavat/beginner-data-science
/05-MultipleLinearRegression(Sklearn)/05-Standardization.py
1,517
3.859375
4
#05-Standardization #standardization: process of transforming data into a standard scale for predict method. (original variable - mean)/(standard deviation) import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set() from sklearn.linear_model import LinearRegression data = pd.read_csv("MultipleLinearRegression.csv") data.head() data.describe() x = data[['SAT', 'Rand 1,2,3']] y = data['GPA'] from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaler.fit(x) x_scaled = scaler.transform(x) x_scaled # Regression with Scaled Features reg = LinearRegression() reg.fit(x_scaled,y) reg.coef_ reg.intercept_ # Summary Table reg_summary = pd.DataFrame([['Bias'],['SAT'],['Rand 1,2,3']], columns=['Features']) #Machine Learning Jargon: intercept >> bias reg_summary['Weights'] = reg.intercept_, reg.coef_[0], reg.coef_[1] #Machine Learning Jargon: coefficients >> weights reg_summary #weight closer to zero has smaller impact # Making Predictions with Standardized Coefficients (Weights) new_data = pd.DataFrame(data=[[1700,2], [1800,1]], columns=['SAT', 'Rand 1,2,3']) new_data reg.predict(new_data) #should be standardized new_data_scaled = scaler.transform(new_data) new_data_scaled reg.predict(new_data_scaled) # Effect of Removing Unsignificant Variable Rand 1,2,3 reg_simple = LinearRegression() x_simple_matrix = x_scaled[:,0].reshape(-1,1) reg_simple.fit(x_simple_matrix, y) reg_simple.predict(new_data_scaled[:,0].reshape(-1,1))
ccc3b34c86e74ebacf313bacfab62fe45ab0b751
AbdulAhadSiddiqui11/PyHub
/Basics/Strings.py
1,039
4.21875
4
# Both single and double quotes work. a = "hello" b = 'world!' print(a + " " + b) print() x = "aWeS0Me" print("String is " + x) print("Capitalizing the first letter : " + x.capitalize()) print("Converting stirng to lower case : " + x.casefold()) print("Converting all the letters to upper case : " , x.upper()) print("Number of times \"e\" shows up in the string :" , x.count("e")) # You cannot concat numbers and string, hence use "," print("Does string end with a ? " , x.endswith("a")) print("Does string end with e ? " , x.endswith("e")) print("Where is the first \"e\" located at ?" , x.find("e")+1) print("Are all the letters alphabets ? " , x.isalpha()) print("Making it a 10 charactered string : " , x.zfill(10)) print() x = "Hey there I am vijay!" print("New String : " + x) y = x.partition("vijay") print("Seperating vijay from string : " , y) y = x.replace("vijay","1StranGe") print("After replacing terms in string : " + y) print("Capitalizing the first letter of each word : " , x.title()) input("Press any key to exit ")
88159e01f91b68ac2c4a2c1d9d1cd2a86cb15d05
chintanvadgama/Algorithms
/findNextGreaterElement.py
1,414
3.609375
4
# Find a next greater element in arrary and if not exists then return -1 # 2 ways # 1. using 2 for loops # 2. using stack # [15,2,9,10] # 15 --> -1 # 2 --> 9 # 9 --> 10 # 10 --> -1 # 1. using 2 for loops class Stack: def __init__(self): self.stack = [] def push(self,item): self.stack.append(item) def isEmpty(self): if self.stack: return False else: return True def pop(self): return self.stack.pop() def peek(self): return self.stack[len(self.stack)-1] def size(self): return len(self.stack) def find_next_great_ele(arr): if arr: for i in range(0,len(arr),1): next_element = -1 for j in range(i+1,len(arr),1): # print 'arr[i] = %s, arr[j] = %s' %(arr[i],arr[j]) if arr[i] < arr[j]: next_element =arr[j] break print '%s ---> %s' %(arr[i],next_element) def find_next_grt_ele_stack(arr): s = Stack() # push the 1st ele to stack s.push(arr[0]) for i in range(0,len(arr),1): # assume the element is arr[i] next_ele = arr[i] if s.isEmpty() == False: element = s.pop() while element < next_ele: print '%s --> %s' %(element,next_ele) if s.isEmpty() == True: break element = s.pop() if element > next_ele: s.push(element) s.push(next_ele) while(s.isEmpty()==False): element = s.pop() print '%s --> -1' % element if __name__ == '__main__': find_next_great_ele([15,2,9,10]) find_next_grt_ele_stack([15,2,9,10])
307bcd423f522f6b799843bace5306ece9d95a1b
zimindkp/pythoneclipse
/PythonCode/src/Exercises/palindrome.py
853
4.4375
4
# K Parekh Feb 2021 # Check if a string or number is a palindrome #function to check if number is prime def isPalindrome(n): # Reverse the string # We create a slice of the string that starts at the end and moves backwards # ::-1 means start at end of string, and end at position 0 (the start), move with step -1 (1 step backwards) litmus = n[::-1] # Here is an example slice that starts from position 0 and goes till character 4 litmus2 = n[:4] print(litmus, "is the reversed string") print(litmus2, "is another string") if (litmus == n): return True else: return False # Driver Program # Enter number here tester = input("Enter a string\n") #Run the command if (isPalindrome(tester)): print (tester, "is a Palindrome") else: print (tester, "is NOT a Palindrome")
ca6c82d5cf36cd9018e49c296835a446143c4377
SetaSouto/torchsight
/torchsight/models/anchors.py
22,451
3.609375
4
"""Anchors module""" import torch from torch import nn from ..metrics import iou as compute_iou class Anchors(nn.Module): """Module to generate anchors for a given image. Anchors could be generated for different sizes, scales and ratios. Anchors are useful for object detectors, so, for each location (or "pixel") of the feature map it regresses a bounding box for each anchor and predict the class for each bounding box. So, for example, if we have a feature map of (10, 10, 2048) and 9 anchors per location we produce 10 * 10 * 9 bounding boxes. The bounding boxes has shape (4) for the x1, y1 (top left corner) and x2, y2 (bottom right corner). Also each bounding box has a vector with the probabilities for the C classes. In this case we could generate different anchors depending on 3 basic variables: - Size: Base size of the anchor. - Scale: Scale the base size to different scales. - Aspect ratio: Disfigure the anchor to different aspect ratios. And then shift (move) the anchors according to the image. So each location of the feature map has len(scales) * len(ratios) = A anchors. As the feature maps has different strides depending on the network, we need the strides values to adjust the shift of each anchor box. For example, if we have an image with 320 * 320 pixels and apply a CNN with stride 10 we have a feature map with 32 * 32 locations (320 / 10). So, each location represents a region of 10 * 10 pixels so to center the anchor to the center of the location we need to move it 5 pixels to the right and 5 pixels down so the center of the anchor is at the center of the location. With this, we move the anchor to the (i, j) position of the feature map by moving it by (i * stride, j * stride) pixels and then center it by moving it by (stride // 2, stride // 2), so the final movement is (i * stride + stride // 2, j * stride + stride // 2). --- Feature Pyramid Network --- The anchors could be for a Feature Pyramid Network, so its predicts for several feature maps of different scales. This is useful to improve the precision over different object scales (very little ones and very large ones). The feature pyramid network (FPN) produces feature maps at different scales, so we use different anchors per scale, for example in the original paper of RetinaNet they use images of size 600 * 600 and the 5 levels of the FPN (P3, ..., P7) with anchors with areas of 32 * 32 to 512 * 512. Each anchor size is adapted to three different aspect ratios {1:2, 1:1, 2:1} and to three different scales {2 ** 0, 2 ** (1/3), 2 ** (2/3)} according to the paper. So finally, we have 3 * 3 = 9 anchors based on one size, totally 3 * 3 * 5 = 45 different anchors for the total network. Keep in mind that only 3 * 3 anchors are used per location in the feature map and that the FPN produces 5 feature maps, that's why we have 3 * 3 * 5 anchors. Example: If we have anchors_sizes = [32, 64, 128, 256, 512] then anchors with side 32 pixels are used for the P3 output of the FPN, 64 for the P4, ... , 512 for the P7. Using the scales {2 ** 0, 2 ** (1/3), 2 ** (2/3)} we can get anchors from 32 pixels of side to 813 pixels of side. """ def __init__(self, sizes=[32, 64, 128, 256, 512], scales=[2 ** 0, 2 ** (1/3), 2 ** (2/3)], ratios=[0.5, 1, 2], strides=[8, 16, 32, 64, 128], device=None): """Initialize the network. The base values are from the original paper of RetinaNet. Args: sizes (sequence, optional): The sizes of the base anchors that will be scaled and deformed for each feature map expected. scales (sequence, optional): The scales to modify each base anchor. ratios (sequence, optional): The aspect ratios to deform the scaled base anchors. strides (sequence, optional): The stride applied to the image to generate the feature map for each base anchor size. device (str): The device where to run the computations. """ super(Anchors, self).__init__() if len(sizes) != len(strides): # As we have one size for each feature map we need to know the stride applied to the image # to get that feature map raise ValueError('"sizes" and "strides" must have the same length') self.strides = strides self.n_anchors = len(scales) * len(ratios) self.device = device if device is not None else 'cuda:0' if torch.cuda.is_available() else 'cpu' self.base_anchors = self.generate_anchors(sizes, scales, ratios) def to(self, device): """Move the module to the given device. Arguments: device (str): The device where to move the module. """ self.device = device self.base_anchors = self.base_anchors.to(device) return super(Anchors, self).to(device) def forward(self, images): """Generate anchors for the given image. If we have multiplies sizes and strides we assume that we'll have different feature maps at different scales. This method returns all the anchors together for all the feature maps in order of the sizes. It returns a Tensor with shape: (batch size, total anchors, 4) Why 4? The four parameters x1, y1, x2, y2 for each anchor. How many is total anchors? We have len(sizes) * len(strides) = A anchors per location of each feature map. We have len(sizes) = len(strides) = F different feature maps based on the image (for different scales). For each 'i' feature map we have (image width / strides[i]) * (image height / strides[i]) = L locations. So total anchors = A * F * L. So the anchors, for each image, are in the form of: [[x1, y1, x2, y2], [x1, y1, x2, y2], ...] And they are grouped by: - Every A anchors we have a location (x, y) of a feature map - The next A anchors are for the (x+1, y) of the feature map. - After all the columns (x) of the feature map then the next A anchors are for the (x, y + 1) location - After all rows and all columns we pass to the next feature map, i.e., the next size of anchors. So, the thing to keep in mind is that the regression values must follow the same order, first A values for the location (0, 0) of the feature map of smallest size, then the next A values for the (1, 0) location, until all the columns are covered, then increase the rows (the next A values must be for the location (0, 1), the next A for the (1, 1), and so on). Args: image (torch.Tensor): The image from we'll get the feature maps and generate the anchors for. Returns: torch.Tensor: A tensor with shape (batch size, total anchors, 4). """ # We have the base anchors that we need to shift and adjust to the given image. # The base anchors have shape (len(sizes), len(scales) * len(ratios), 4) # For a given stride, say i, we need to generate (image width / stride) * (image height / stride) # anchors for each one of the self.base_anchors[i, :, :] anchors = [] for image in images: image_anchors = [] for index, stride in enumerate(self.strides): base_anchors = self.base_anchors[index, :, :] # Shape (n_anchors, 4) height, width = image.shape[1:] # Get dimensions of the feature map feature_height, feature_width = round(height / stride), round(width / stride) # We need to move each anchor (i * shift, j * shift) for each (i,j) location in the feature map # to center the anchor on the center of the location shift = stride * 0.5 # We need a tensor with shape (feature_height, feature_width, 4) # shift_x shape: (feature_height, feature_width, 1) where each location has the index of the # x position of the location in the feature map plus the shift value shift_x = torch.arange(feature_width).to(self.device).type(torch.float) shift_x = stride * shift_x.unsqueeze(0).unsqueeze(2).repeat(feature_height, 1, 1) + shift # shift_y shape: (feature_height, feature_width, 1) where each location has the index of the # y position of the location in the feature map plus the shift value shift_y = torch.arange(feature_height).to(self.device).type(torch.float) shift_y = stride * shift_y.unsqueeze(1).unsqueeze(2).repeat(1, feature_width, 1) + shift # The final shift will have shape (feature_height, feature_width, 4 * n_anchors) shift = torch.cat([shift_x, shift_y, shift_x, shift_y], dim=2).repeat(1, 1, self.n_anchors) # As pytorch interpret the channels in the first dimension it could be better to have a shift # with shape (4 * anchors, feature_height, feature_width) like an image (channels, height, width) shift = shift.permute((2, 0, 1)) base_anchors = base_anchors.view(self.n_anchors * 4).unsqueeze(1).unsqueeze(2) # As shift has shape (4* n_anchors, feature_height, feature_width) and base_anchors has shape # (4 * n_anchors, 1, 1) this last one broadcast to the shape of shift final_anchors = shift + base_anchors # As the different strides generate different heights and widths for each feature map we cannot # stack the anchors for each feature map of the image, but we can concatenate the anchors if we # reshape them to (4, n_anchors * feature_height * feature_width) but to have the parameters in the # last dimension we can permute the dimensions. # Until now we have in the channels the values for each x1, y1, x2, y2, but the view method # follow the order of rows, cols, channels, so if we want to keep the values per each anchor # continuous we need to apply the permutation first and then the view. # Finally we get shape (total anchors, 4) final_anchors = final_anchors.permute((1, 2, 0)).contiguous().view(-1, 4) image_anchors.append(final_anchors) # Now we have an array with the anchors with shape (n_anchors * different heights * widths, 4) so we can # concatenate by the first dimension to have a list with anchors (with its 4 parameters) ordered by # sizes, x_i, y_i, all combination of aspect ratios vs scales # where x_i, y_i are the positions in the feature map for the size i anchors.append(torch.cat(image_anchors, dim=0)) # Now as each image has its anchors with shape # (n_anchors * feature_height_i * feature_width_i for i in range(len(strides)), 4) # we can stack the anchors for each image and generate a tensor with shape # (batch size, n_anchors * feature_height_i * feature_width_i for i in range(len(strides)), 4) return torch.stack(anchors, dim=0) def generate_anchors(self, sizes, scales, ratios): """Given a sequence of side sizes generate len(scales) * len(ratios) = n_anchors anchors per size. This allow to generate, for a given size, all the possibles combinations between different aspect ratios and scales. To get the total anchors for a given size, say 0, you could do: ``` anchors = self.generate_anchors(sizes, scales, ratios) anchors[0, :, :] ``` Or to get the 4 parameters for the j anchor for the i size: ``` anchors[i, j, :] ``` Args: anchors_sizes (sequence): Sequence of int that are the different sizes of the anchors. Returns: torch.Tensor: Tensor with shape (len(anchors_sizes), len(scales) * len(ratios), 4). """ # First we are going to compute the anchors as center_x, center_y, height, width anchors = torch.zeros((len(sizes), self.n_anchors, 4), dtype=torch.float).to(self.device) sizes, scales, ratios = [torch.Tensor(x).to(self.device) for x in [sizes, scales, ratios]] # Start with height = width = 1 anchors[:, :, 2:] = torch.Tensor([1., 1.]).to(self.device) # Scale each anchor to the correspondent size. We use unsqueeze to get sizes with shape (len(sizes), 1, 1) # and broadcast to (len(sizes), n_anchors, 4) anchors *= sizes.unsqueeze(1).unsqueeze(1) # Multiply the height for the aspect ratio. We repeat the ratios len(scales) times to get all the aspect # ratios for each scale. We unsqueeze the ratios to get the shape (1, n_anchors) to broadcast to # (len(sizes), n_anchors) anchors[:, :, 2] *= ratios.repeat(len(scales)).unsqueeze(0) # Adjust width and height to match the area size * size areas = sizes * sizes # Shape (len(sizes)) height, width = anchors[:, :, 2], anchors[:, :, 3] # Shapes (len(sizes), n_anchors) adjustment = torch.sqrt((height * width) / areas.unsqueeze(1)) anchors[:, :, 2] /= adjustment anchors[:, :, 3] /= adjustment # Multiply the height and width by the correspondent scale. We repeat the scale len(ratios) times to get # one scale for each aspect ratio. So scales has shape (1, n_anchors, 1) and # broadcast to (len(sizes), n_anchors, 2) to scale the height and width. anchors[:, :, 2:] *= scales.unsqueeze(1).repeat((1, len(ratios))).view(1, -1, 1) # Return the anchors but not centered nor with height or width, instead use x1, y1, x2, y2 height, width = anchors[:, :, 2].clone(), anchors[:, :, 3].clone() center_x, center_y = anchors[:, :, 0].clone(), anchors[:, :, 1].clone() anchors[:, :, 0] = center_x - (width * 0.5) anchors[:, :, 1] = center_y - (height * 0.5) anchors[:, :, 2] = center_x + (width * 0.5) anchors[:, :, 3] = center_y + (height * 0.5) return anchors @staticmethod def transform(anchors, deltas): """Adjust the anchors with the regression values (deltas) to obtain the final bounding boxes. It uses the standard box parametrization from R-CNN: https://arxiv.org/pdf/1311.2524.pdf (Appendix C) Args: anchors (torch.Tensor): Anchors generated for each image in the batch. Shape: (batch size, total anchors, 4) deltas (torch.Tensor): The regression values to adjust the anchors to generate the real bounding boxes as x1, y2, x2, y2 (top left corner ahd bottom right corner). Shape: (batch size, total anchors, 4) Returns: torch.Tensor: The bounding boxes with shape (batch size, total anchors, 4). """ widths = anchors[:, :, 2] - anchors[:, :, 0] heights = anchors[:, :, 3] - anchors[:, :, 1] center_x = anchors[:, :, 0] + (widths / 2) center_y = anchors[:, :, 1] + (heights / 2) delta_x = deltas[:, :, 0] delta_y = deltas[:, :, 1] delta_w = deltas[:, :, 2] delta_h = deltas[:, :, 3] predicted_x = (delta_x * widths) + center_x predicted_y = (delta_y * heights) + center_y predicted_w = torch.exp(delta_w) * widths predicted_h = torch.exp(delta_h) * heights # Transform to x1, y1, x2, y2 predicted_x1 = predicted_x - (predicted_w / 2) predicted_y1 = predicted_y - (predicted_h / 2) predicted_x2 = predicted_x + (predicted_w / 2) predicted_y2 = predicted_y + (predicted_h / 2) return torch.stack([ predicted_x1, predicted_y1, predicted_x2, predicted_y2 ], dim=2) @staticmethod def clip(batch, boxes): """Given the boxes predicted for the batch, clip the boxes to fit the width and height. This means that if the box has any side outside the dimensions of the images the side is adjusted to fit inside the image. For example, if the image has width 800 and the right side of a bounding box is at x = 830, then the right side will be x = 800. Args: batch (torch.Tensor): The batch with the images. Useful to get the width and height of the image. Shape: (batch size, channels, width, height) boxes (torch.Tensor): A tensor with the parameters for each bounding box. Shape: (batch size, number of bounding boxes, 4). Parameters: boxes[:, :, 0]: x1. Location of the left side of the box. boxes[:, :, 1]: y1. Location of the top side of the box. boxes[:, :, 2]: x2. Location of the right side of the box. boxes[:, :, 3]: y2. Location of the bottom side of the box. Returns: torch.Tensor: The clipped bounding boxes with the same shape. """ _, _, height, width = batch.shape boxes[:, :, 0] = torch.clamp(boxes[:, :, 0], min=0) boxes[:, :, 1] = torch.clamp(boxes[:, :, 1], min=0) boxes[:, :, 2] = torch.clamp(boxes[:, :, 2], max=width) boxes[:, :, 3] = torch.clamp(boxes[:, :, 3], max=height) return boxes @staticmethod def assign(anchors, annotations, thresholds=None): """Assign the correspondent annotation to each anchor. We know that in a feature map we'll have A anchors per location (i.e. feature map's height * width * A total anchors), where these A anchors have different sizes and aspect ratios. Each one of this anchors could have an 'assigned annotation', that is the annotation that has bigger Intersection over Union (IoU) with the anchor. So, all the anchors could have an assigned annotation, but, what we do with the anchors that are containing background and none object? That's the reason that we must provide some thresholds: one to keep only the anchors that are containing objects and one threshold to decide if the anchor is background or not. The anchors that has IoU between those threshold are ignored. With this we can train anchors to fit the annotation and others to fit the background class. And obviously keep a centralized way to handle this behavior. Arguments: anchors (torch.Tensor): The base anchors. They must have 4 values: x1, y1 (top left corner), x2, y2 (bottom right corner). Shape: (number of anchors, 4) annotations (torch.Tensor): The real ground truth annotations of the image. They must have at least the same 4 values. Shape: (number of annotations, 4+) thresholds (dict): A dict with the 'object' (float) threshold and the 'background' threshold. If the IoU between an anchor and an annotation is bigger than 'object' threshold it's selected as an object anchor, if the IoU is below the 'background' threshold is selected as a 'background' anchor. Returns: torch.Tensor: The assigned annotations. The annotation at index i is the annotation associated to the anchor at index i. So for example, if we have the anchors tensor and we want to get the annotation to the i-th anchor we could simply take this value returned and the get i-th element too. Example: >>> assigned_annotations, *_ = Anchors.assign(anchors, annotations) >>> assigned_annotations[10] # The annotation assigned to the 10th anchor. Shape: (number of anchors, 4+) torch.Tensor: A mask that indicates which anchors are selected to be objects. torch.Tensor: A mask that indicates which anchors are selected to be background. Keep in mind that if the thresholds are not the same some anchors could not be objects nor background. torch.Tensor: The IoU of the selected anchors as objects. Obviously all of them are over the 'object' threshold. """ if annotations is None or annotations.shape[0] == 0: # There are no assigned annotations num_anchors = anchors.shape[0] assigned_annotations = -1 * anchors.new_ones(num_anchors, 5) # There are no selected anchors as objects objects_mask = anchors.new_zeros(num_anchors).byte() # All the anchors are background background_mask = anchors.new_ones(num_anchors).byte() # There are no iou between anchors and objects iou_objects = anchors.new_zeros(0) return assigned_annotations, objects_mask, background_mask, iou_objects default_thresholds = {'object': 0.5, 'background': 0.4} if thresholds is None: thresholds = default_thresholds if 'object' not in thresholds: thresholds['object'] = default_thresholds['object'] if 'background' not in thresholds: thresholds['background'] = default_thresholds['background'] iou = compute_iou(anchors, annotations) # (number of anchors, number of annotations) iou_max, iou_argmax = iou.max(dim=1) # (number of anchors) # Each anchor is associated to a bounding box. Which one? The one that has bigger iou with the anchor assigned_annotations = annotations[iou_argmax, :] # (number of anchors, 4+) # Only train bounding boxes where its base anchor has an iou with an annotation over iou_object threshold objects_mask = iou_max > thresholds['object'] iou_objects = iou_max[objects_mask] background_mask = iou_max < thresholds['background'] return assigned_annotations, objects_mask, background_mask, iou_objects
c6468f1e40c442c13b97f54a677a7a23c336b057
Seetha4/GraduateTrainingProgram2018
/python/day8.py
1,317
3.59375
4
import pandas as pd raw_data1 = { 'subject_id': ['1', '2', '3', '4', '5'], 'first_name': ['Alex', 'Amy', 'Allen', 'Alice', 'Ayoung'], 'last_name': ['Anderson', 'Ackerman', 'Ali', 'Aoni', 'Atiches']} data1=pd.DataFrame(raw_data1) raw_data2 = { 'subject_id': ['4', '5', '6', '7', '8'], 'first_name': ['Billy', 'Brian', 'Bran', 'Bryce', 'Betty'], 'last_name': ['Bonder', 'Black', 'Balwner', 'Brice', 'Btisan']} data2=pd.DataFrame(raw_data2) raw_data3 = { 'subject_id': ['1', '2', '3', '4', '5', '7', '8', '9', '10', '11'], 'test_id': [51, 15, 15, 61, 16, 14, 15, 1, 61, 16]} data3=pd.DataFrame(raw_data3) print data1 print data2 print data3 all_data_row=pd.concat([data1,data2]) #all_data_row=pd.merge(data1,data2,how="outer") print("two dataframes along rows") print all_data_row all_data_col=pd.concat([data1,data2],axis=1) print("two dataframes along columns") print all_data_col df=pd.merge(all_data_row,data3) print df print("to Merge only the data that has the same 'subject_id' on both data1 and data2") df1=pd.merge(data1,data2,how="inner" ,on='subject_id') print df1 df2=pd.merge(data1,data2,how="outer",on='subject_id') print("Merge all values in data1 and data2, with matching records from both sides where available") print df2
69be4d17197541b83dd01bdfe2aa5e7049dd9202
r-ellahi/python_tasks
/task_sheet5b.py
2,129
4.15625
4
#CSV # Q1 read the ford_escort.csv example file using python csv library and print each row import csv with open('ford_escort.csv', 'r') as file: reader = csv.reader(file, delimiter = ',') for row in reader: print(row) # Q2 Extend the above so that the data is read into a dictionary import csv with open('ford_escort.csv', 'r') as file: csv_file = csv.DictReader(file) for row in csv_file: print(row) # Q3. Write the following data as CSV to a file. Adde a header row with titles. ['Joe', 'Bloggs', 40] ['Jane', 'Smith', 50] import csv with open('trial.csv', mode = 'w') as file: writer = csv.writer(file, delimiter = ',') writer.writerow(['First', 'Surname', 'Age']) writer.writerow(['Joe', 'Bloggs', '40']) writer.writerow(['Jane', 'Smith', '50']) # Q4. Write another block of code that will append the following data to the file created in Q3 ['Mike', 'Wazowski', 40] import csv with open('trial.csv', 'a') as file: writer = csv.writer(file, delimiter = ',') writer.writerow(['Mike', 'Wazowski', '40']) #EXTRA WORK - WRITING FROM A DICTIONARY import csv with open('dictionary.csv', 'w') as file: fieldnames = ['first_name', 'surname', 'age'] writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() writer.writerow({ 'first_name': 'Jack', 'surname': 'Smith', 'age': 25 }) #JSON # Q1: read the example.json handout file using the native python json library, # print the object that is created import json with open('example.json', 'r') as json_file: data = json.load(json_file) print(json.dumps(data, indent =3)) # indent allows for spacing in between values # Q2: print the "id" of all the items in the menu import json with open('example.json', 'r') as json_file: data = json.load(json_file) print(json.dumps(data['menu']['items'], indent =3)) # #Q3 Write the following data as JSON to a file import json data = { 'president': { 'name': 'Zaphod Beeblebrox', 'species': 'Betelgeusian' } } with open('data_file.json', 'w') as write_file: json.dump(data, write_file)
eb3fc28a057076563a37993b65bee8bd0bc56048
DamonTan/Python-Crash-Course
/chapter1-6/ex5-3.py
330
4.1875
4
alien_color = input("Please enter your alien's clolor: ") if alien_color == 'green': print("The alien is green, so you can get 5 points!\n") elif alien_color == 'yellow': print("The alien is yellow, so you can get 10 points!\n") elif alien_color == 'red': print("The alien is red, so you can get 15 points!\n")
86727a07d4b7fe7a6abd40bc643b4812a8dc5fc0
melodyzheng-zz/SIP-2017-starter
/Unit1_Foundations/shapes2/pythonshapes_starter.py
399
4.21875
4
from turtle import * import math # Name your Turtle. t = Turtle() # Set Up your screen and starting position. color = input("What color?") pencolor(color) setup(500,300) x_pos = 0 y_pos = 0 t.setposition(x_pos, y_pos) x= 0 begin_fill() s = input("How many sides?") for x in range (s): forward(50) right(360/int(s)) x = x+1 fillcolor(color) end_fill() ### Write your code below:
d830714198548e66a329a05ed4fcbb4d30e0e52d
alexwalling/ai3202
/Assignment_5/Graph.py
4,381
3.640625
4
class Node: def __init__(self, x, y, wall, reward): self.parent = None self.utility = 0 self.x = x self.y = y self.wall = wall self.reward = reward def printNode(self): print self.x, self.y, self.reward, self.utility, self.wall, self.parent class Graph: def __init__(self, height, width, gamma = 0.9): self.closed = set() self.nodes = [] self.actions = ['left', 'right', 'up', 'down'] self.height = height self.width = width self.gamma = gamma def MDP(self, graph): reward = 0 for y in range(len(graph)): for x in range(len(graph[0])): wall = False #print("x: ", x) #print ("y: ", y) #print ("Value: ", graph[y][x]) if graph[y][x] is '0': #empty space reward = 0 if graph[y][x] is '1': #mountain reward = -1 if graph[y][x] is '2': #wall wall = True reward = 0 if graph[y][x] is '3': #snake reward = -2 if graph[y][x] is '4': #barn reward = 1 if x == self.width - 1 and y == self.height - 1: #end state reward = 50 self.nodes.append(Node(x, y, wall, reward)) self.start = self.getNode(0, 0) self.end = self.getNode(len(graph[0]) - 1, len(graph) - 1) def getNode(self, x, y): #print "start print" #for i in self.nodes: # i.printNode() #print len(self.nodes) #print "x:",x,"y:" , y #print y * self.width + x #print self.width #print self.height return self.nodes[y * self.width + x] def printNodes(self): print "hello" for i in range(0, self.width * self.height): print self.nodes[i].printNode() def transition(self, x, y): actionvalue = [] for i in range(len(self.actions)): if self.actions[i] is 'left': temp = 0 if x - 1 >= 0: temp = .8 * self.getNode(x - 1, y).utility if y + 1 <= self.height - 1: temp = .1 * self.getNode(x, y + 1).utility + temp if y - 1 >= 0: temp = .1 * self.getNode(x, y - 1).utility + temp actionvalue.append(temp) if self.actions[i] is 'right': temp = 0 if x + 1 <= self.width - 1: temp = .8 * self.getNode(x + 1, y).utility if y + 1 <= self.height - 1: temp = .1 * self.getNode(x, y + 1).utility + temp if y - 1 >- 0: temp = .1 * self.getNode(x, y - 1).utility + temp actionvalue.append(temp) if self.actions[i] is 'up': temp = 0 if y + 1 <= self.height - 1: temp = .8 * self.getNode(x, y + 1).utility if x + 1 <= self.width - 1: temp = .1 * self.getNode(x + 1, y).utility + temp if x - 1 >= 0: temp = .1 * self.getNode(x - 1, y).utility + temp actionvalue.append(temp) if self.actions[i] is 'down': temp = 0 if y - 1 >= 0: temp = .8 * self.getNode(x, y - 1).utility if x + 1 <= self.width - 1: temp = .1 * self.getNode(x + 1, y).utility + temp if x - 1 >= 0: temp = .1 * self.getNode(x - 1, y).utility + temp actionvalue.append(temp) return actionvalue def valueIteration(self, epsilon): gamma = self.gamma delta = float('Inf') while delta > epsilon*(1 - gamma)/gamma: for n in reversed(self.nodes): if n.wall is False: currentUtility = n.utility # print n.x , " " , n.y # print max(self.transition(n.x, n.y)) n.utility = n.reward + gamma*max(self.transition(n.x, n.y)) delta = abs(currentUtility - n.utility) def path(self): self.adjacentNode(self.start) p = [] tempnode = self.end p.append(tempnode) while tempnode.parent is not self.start: tempnode = tempnode.parent p.append(tempnode) p.append(self.start) print "Printing Path" for n in reversed(p): #n.printNode() print "x:", n.x, "y:", n.y def adjacentNode(self, node): adjUtility = [] adjNode = [] if node.x < self.width-1: adjUtility.append(self.getNode(node.x + 1, node.y).utility) adjNode.append(self.getNode(node.x + 1, node.y)) if node.x > 0: adjUtility.append(self.getNode(node.x - 1, node.y).utility) adjNode.append(self.getNode(node.x - 1, node.y)) if node.y < self.height - 1: adjUtility.append(self.getNode(node.x, node.y + 1).utility) adjNode.append(self.getNode(node.x, node.y + 1)) if node.y > 0: adjUtility.append(self.getNode(node.x, node.y - 1).utility) adjNode.append(self.getNode(node.x, node.y - 1)) if node is not self.end: adjNode[adjUtility.index(max(adjUtility))].parent = node self.adjacentNode(adjNode[adjUtility.index(max(adjUtility))])
e6f3c3a0e327762910a2d3f54f26503d360c11c7
Sapna20dec/Dictionary
/questions9.py
412
3.625
4
# word="mississippi" # count=0 # for i in word: # if i=="m": # count["m"]=count["m"]+1 # elif i=="i": # count["i"]=count["i"]+1 # elif i=="s": # count["s"]=count["s"]+1 # elif i=="p": # count["p"]=count["p"]+1 # print(count) # dic="mississippi" # n={} # c=0 # for i in dic: # if i in n: # n[i]+=1 # else: # n[i]=1 # print(n)
8ad1393e905658f787eb36b313e4566622262dd6
staryjie/14day3
/day1/s1.py
1,727
3.5625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- ''' #10进制转二进制 num = int(input("Pls enter a number: ")) print(bin(num)) ''' ''' 8bit = 1bytes 字节,最小的存储单位,1bytes缩写为1B 1KB = 1024B 1MB = 1024KB 1GB = 1024MB ITB = 1024GB 1PB = 1024TB 1EB = 1024PB 1ZB = 1024EB 1YB = 1024ZB 1BB = 1024YB ''' ''' ASCII编码不支持中文 1981年5月1日,GB2312编码,又称国标码,共7445个字符图形,其中汉字占6763个。(中国的汉子远远不止这些,并且只支持简体) 1984年,台湾BIG5编码,只支持繁体,收录13053个中文字 1995年发布GBK1.0,支持简体和繁体,兼容GB2312,共收录21003个,同时包含中日韩文字里的所有汉字 2000年,发布GB18030,是对GBK编码的扩充,覆盖中文、日文、朝鲜语和中国少数民族文字,其中收录27484个汉字。兼容GBK和GB2312 1991年: -----为了解决每个国家质检编码不互通的问题,ISO标准组织出马了------- Unicode编码,国际标准字符集,它将世界各种语言的每个字符定义一个唯一编码,以满足跨语言、跨平台的文本信息转换。 Unicode(统一码、万国码)规定所有的字符和符号最少由16位来表示(2个字节),即2 **16 = 65536 UTF-8,是对Unicode编码的压缩和优化,它不再使用最少2个字节,而是将所有的字符和符号进行分类: ASCII码表中的内容使用1个字节保存、欧洲的字符用2个字节保存、东亚的字符用3个字符保存 windows系统中文版默认编码是GBK Mac OS/Linux系统默认编码是UTF-8 ''' ''' Python2,默认支持ASCII,(并不代表python2不支持中文) python3,默认支持UTF-8 '''
44fdd66802449cac5f9435e1046341de8df63c6c
palakbaphna/pyprac
/Lists/15JoinMethodList.py
613
4.5625
5
#the method join is used; this method has one parameter: a list of strings. # It returns the string obtained by concatenation of the elements given, # and the separator is inserted between the elements of the list; # this separator is equal to the string on which is the method applied a = ['red', 'green', 'blue'] print(' '.join(a)) print(''.join(a)) print('***'.join(a)) #b = [1, 2, 3, 4, 5, 6] #print(''.join(b)) # gives type error, because join can cancatenate only strings #so to join list with numbers or integers, we need to USE THE GENERATORS b = [1, 2, 3] print('.'.join([str(i) for i in b]))
a7a0dbfbf9780c50b91b81fd9147da1fb46458d2
love68/studypython
/basic/day01/demo/func4.py
207
3.90625
4
# 可变参数 def calc(*numbers): sum = 0 for n in numbers: sum = sum + n * n return sum print(calc(1,2,3,4,2.1)) num = [1,2,3] # list 作为可变参数 print(calc(*num))
f4728bf5ecf8c1b9fd66cbad669e239c676674e7
Pythoner-Waqas/Backup
/C vs Python/py prog/1.py
342
3.859375
4
#if user enter 7531, #it displays 7,5,3,1 separately. number = int(input("Please enter 4 digit integer ")) fourth_int = number%10 number = int(number/10) third_int = number%10 number = int(number/10) second_int = number%10 number = int(number/10) first_int = number print (first_int, "," , second_int, "," , third_int , "," , fourth_int)
ba5669f783d742c2469a4e27f4e634cff2416208
Mumulhy/LeetCode
/1185-一周中的第几天/DayOfTheWeek.py
838
3.84375
4
# -*- coding: utf-8 -*- # LeetCode 1185-一周中的第几天 """ Created on Mon Jan 3 10:23 2022 @author: _Mumu Environment: py38 """ class Solution: def dayOfTheWeek(self, day: int, month: int, year: int) -> str: week = ["Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"] idx = 0 # for y in range(1971, year): # idx += 2 if y % 4 == 0 and y != 2100 else 1 idx += year - 1971 + (year - 1969) // 4 idx %= 7 if year % 4 == 0 and year != 2100: months = [0, 0, 3, 4, 0, 2, 5, 0, 3, 6, 1, 4, 6] else: months = [0, 0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5] idx += months[month] + day idx %= 7 return week[idx] if __name__ == '__main__': s = Solution() print(s.dayOfTheWeek(15, 12, 2021))
6ed137e9b82850b61ab16a1976b26aa6b964462d
shahryarabaki/ICE
/src/collocations_method_1.py
5,114
3.59375
4
from nltk.corpus import wordnet import re from .pos_tagger import POS_tag_cleaner # Method to determine if a phrase is a collocation based on dictionary based technique # Uses WordNet from NLTK corpus to obtain definitions of the words when both # the word and it's sense are passed as inputs def Collocations_Method_1(_n_grams_from_input_text_file, _input_file_path, _apply_POS_restrictions, _verbose): if _verbose: # A file to save the verbose output of the program _output_file_verbose = str(_input_file_path).replace(_input_file_path.split('/')[-1], 'verbose.txt') _output_file_verbose = open(_output_file_verbose, 'a') print("\n--------------------------------------------------------------------------", file = _output_file_verbose) print("\tMethod-1: WordNet - Extracting collocations:", file = _output_file_verbose) print("--------------------------------------------------------------------------\n\n", file = _output_file_verbose) print("\tMethod-1: Using WordNet to extract collocations ...") # A list to store n-gram phrases that are collocations wordnet_collocations = [] # A list to store n-gram phrases that are not collocations n_grams_not_collocations = [] for _n_gram in _n_grams_from_input_text_file: if _verbose: print("\n%s:" %(_n_gram), file = _output_file_verbose) if _n_gram in wordnet_collocations or _n_gram in n_grams_not_collocations: # If a particular n-gram phrase is checked if it is a collocation before, # it will be present in one of the lists, wordnet_collocations OR n_grams_not_collocations # Hence, we move on to the next n-gram continue else: # Before checking if the n-gram is defined in WordNet we check if atlease one # POS tag is from the valid POS tag list: {Noun, Verb, Adverb, Adjective} if # _apply_POS_restrictions is set to True if _apply_POS_restrictions: valid_POS_tags = ['NN', 'VB', 'RB', 'JJ'] _valid_POS_tag_counter = 0 # A counter to count the number of valid POS tags in n-gram for _pos_tag in valid_POS_tags: if _pos_tag in _n_gram: _valid_POS_tag_counter += 1 if _valid_POS_tag_counter == 0: # If no valid POS tag is present in the n-gram, it is not a collocation # when POS restrictions are applied n_grams_not_collocations.append(_n_gram) if _verbose: print("\t'%s' does not have valid POS tags\n\tMoving on to the next phrase ..." %(_n_gram), file = _output_file_verbose) continue # We move to the next n-gram in the list # If POS restrictions are not to be applied on the n-gram _n_gram_lower = _n_gram.lower() + ' ' # Lower case _n_gram_lower = re.sub(r'_.*? ', ' ', _n_gram_lower).rstrip(' ') _n_gram_lower = _n_gram_lower.replace(' ', '_') if _verbose: print("\tLooking for phrase definitions in WordNet ...", file = _output_file_verbose) syn_sets = wordnet.synsets(_n_gram_lower) if len(syn_sets) == 0: if _verbose: print("\tWordNet does not have definitions for '%s'" %(_n_gram_lower), file = _output_file_verbose) n_grams_not_collocations.append(_n_gram) continue else: wordnet_collocations.append(_n_gram) if _verbose: print("\tCOLLOCATION: '%s' is defined in WordNet" %(_n_gram_lower), file = _output_file_verbose) continue # Output text file to save collocations _output_file_path_wordnet_collocations = str(_input_file_path).replace(_input_file_path.split('/')[-1], 'collocations_wordnet.txt') with open(_output_file_path_wordnet_collocations, 'w') as _output_file_wordnet_collocations: for _collocation in wordnet_collocations: print(POS_tag_cleaner(_collocation) + '\n', file = _output_file_wordnet_collocations) if _verbose: print("\n\tMethod-1: WordNet - Collocations are written to the file:\n\t%s" %(_output_file_path_wordnet_collocations), file = _output_file_verbose) # Output text file to save n-grams that are not collocations _output_file_path_wordnet_not_collocations = str(_input_file_path).replace(_input_file_path.split('/')[-1], 'not_collocations_wordnet.txt') _output_file_wordnet_not_collocations = open(_output_file_path_wordnet_not_collocations, 'w') with open(_output_file_path_wordnet_not_collocations, 'w') as _output_file_wordnet_not_collocations: for _n_gram in n_grams_not_collocations: print(POS_tag_cleaner(_n_gram) + '\n', file = _output_file_wordnet_not_collocations) if _verbose: print("\n\tMethod-1: WordNet - N-grams that are not collocations are written to the file:\n\t%s" %(_output_file_path_wordnet_not_collocations), file = _output_file_verbose) if _verbose: print("\n--------------------------------------------------------------------------", file = _output_file_verbose) print("\tMethod-1: WordNet - Collocation extraction - Complete", file = _output_file_verbose) print("--------------------------------------------------------------------------\n\n", file = _output_file_verbose) # Returning n-grams that are collocations and n-grams that are not if _verbose: print("\t\tCollocation extraction - Method-1 - successful") return wordnet_collocations, n_grams_not_collocations
edc60d1e12c1c5ae3dc0b38323ab67b5bfdcaf50
SohyunNam/sso
/test.py
140
3.5625
4
from collections import OrderedDict my_dict = OrderedDict() my_dict[1] = 1 my_dict[2] = 2 my_dict[3] = 3 print(my_dict.popitem(last=False))
4995a90907a61667a9a33aeb6fb0b33f5c9c3d69
diachkina/PythonIntroDiachkina
/Lesson6-7/home_work13.py
255
3.53125
4
from random import randint lst = [randint(1, 100) for _ in range(10)] print(lst) lst.append(0) k = int(input("Enter the index: ")) c = int(input("Enter the value: ")) for ind in range(len(lst) - 1, k, -1): lst[ind] = lst[ind - 1] lst[k] = c print(lst)
b6806536eab5f36c67cc590d27ba13000eabd294
Dismissall/info_msk_task
/io_and_operation/symmetrical_num.py
173
3.703125
4
number = int(input()) first_part = number // 100 second_part = number % 100 second_part = second_part % 10 * 10 + second_part // 10 print(second_part - first_part + 1)
712df6e153667b6165f0820c96c52ef633e8ff7e
xDannyCRx/Daniel
/ClassExample1.py
540
4.21875
4
#!/usr/bin/env python # coding: utf-8 # In[1]: class itspower: def __init__(self,x): self.x=x def __pow__(self,other): return self.x**other.x a=itspower(2) b=itspower(10) a**b # In[11]: def factorial(n): f=1 while n>0: f*=n n-=1 print(f) factorial(4) # In[12]: def factorial(numero): print ("Valor inicial ->",numero) if numero > 1: numero = numero * factorial(numero -1) print ("valor final ->",numero) return numero print (factorial(4)) # In[ ]:
6ca7afa79193b60dca8eef6df9348a59a04411f0
v1ktos/Python_RTU_08_20
/Diena_1_4_thonny/if_else_elif.py
692
4.125
4
# if a = 0 b = 5 c = 10 if a > b: print("a > b") print("Also do this") print(a*b) # a <= b: else: # if a <= b: print(a,b) print("a is less or equal than b") if a != 0: print("Cool a nonzero a") print(b / a) b += 6 b -= 1 if b > c: print("b is larger than c", b, c) elif b < c: print("b is smaller than c", b, c) else: print("b is equal to c", b, c) answer = input("Enter your code") if answer == "a": print("alpha") elif answer == "b": print("beta") elif answer == "c": print("gamma") else: print("you entered unclear", answer) print("This will run on matter what") a = 7 is_odd_digit = a in range(1,10,2) # 1, 3, 5,7,9
b1e8d42910fe31737b66a3f4c427122d37d1a76c
Artemis21/game-jam-2020
/artemis/utils.py
819
3.5
4
"""General utilities.""" import json import typing # --- Data storage files def open_file(file: str) -> dict: """Open the file, if present, if not, return an empty dict.""" try: with open(file) as f: return json.load(f) except FileNotFoundError: return {} def save_file(file: str, data: dict): """Save the file with modified data.""" with open(file, 'w') as f: json.dump(data, f, indent=1) def data_util(fun: typing.Callable, file: str) -> typing.Callable: """Wrap functions that need read/write access to data.""" def wrapper(*args, **kwargs) -> typing.Any: """Open the file and save it again.""" data = open_file(file) ret = fun(data, *args, **kwargs) save_file(file, data) return ret return wrapper
00a0d495c0e449a70003d685b40c7001501f6e40
lukereed/PythonTraining
/Class/Class_01/Class_01.py
2,814
4.5625
5
#!/usr/bin/python # Luke Reed # RES Python Class 01 # 01/07/2016 # Classic "hello world" welcome to programming print "Hello World!" print "Hello Again!" # We can now learn about different types type(55) # this will return 'int' for integers type(55.34) # this will return 'float' for floating points type(55) # this will also return 'float' for floating points type('text') # this will return 'str' for character strings # Now how about some numerical operations print 59/60 # will return '0' because of integer math print 59/60. # will return '0.983333333333' # Next we can combine text and numerical operations print 'here is some math:', 36+5./2 # EXERCISES! # 1. Math Operations # If you run a 10 kilometer race in 43 minutes 30 seconds, what is your average time per mile? # What is your average speed in miles per hour? (Hint: there are about 1.61 kilometers in a mile.) D = 10 m = 43 s = 30 miles = 10 / 1.61 time = (43 + 30 / 60.) / 60. # time in hours pace = time / miles * 60 mph = miles / time print "Average time per mile: ", pace, "minutes" print "Average speed (mph): ", mph # 2. The volume of a sphere with radius r is 4/3 pi r3. What is the volume of a sphere with radius 5? # first load up math library import math # import entire math library #from math import pi # alternative way to just import part of a library r = 5 volume = 4./3 * math.pi ** 3 print "The volume of a sphere with radius %d is %f" % (r,volume) # 3. If I leave my house at 6:52AM and run 1 mile at an easy pace (8:15 per mile), then 3 miles at temp (7:12 per mile) # and 1 mile at an easy pace again, what time do I get home for breakfast? start_time = (6*60 + 52) * 60 easy_pace = 8*60 + 15 tempo = 7*60 + 12 run_time = easy_pace + 3*tempo + easy_pace end_time = start_time + run_time end_hour = end_time / 60 / 60 end_minute = (end_time - (end_hour*60*60) ) / 60 end_second = (end_time - (end_hour*60*60) - (end_minute*60)) print "Breakfast will be at %d:%d:%d" % (end_hour,end_minute,end_second) # 4. Functions # Python provides a built-in function called len that returns the length of a string, so the value of len("allen") is 5. # Write a function named right_justify that takes a string named 's' as a parameter and prints the string with enough # leading spaces so that the last letter of the string is in column 70 of the display s = raw_input("Give me a string:\n>") # begin with asking for input from the user def right_justify(s): # define a function l = len(s) # determine the length of the inputted string print (' '*(70-l)+s) # use the ' ' for blank space and the + to concatenate the string # execute the function on the inputted string right_justify(s)
06945db5be1d64102ab05fdd3ebb04e474710788
vmasten/madlib-cli
/madlib.py
2,886
4.1875
4
"""Recreates the game of Mad Libs. First, the user is prompted for parts of speech. Then, the prompts are recombined into a silly story Finally, the completed story is displayed. """ import re def greeting(): """Greet the user and provide instructions.""" print("Let's write a silly story. I'm going to prompt you for some parts") print(" of speech and when I have everything I need, I'll tell you the") print("resulting story\n") def read_file(path): """Read path and return the data as a giant string.""" with open(path, 'r') as rf: return rf.read() def write_file(path, out): """Write a file back to the given path.""" with open(path, 'w') as wf: return wf.write(out) def get_keys(format_string): """Get parts of speech to be modified.""" key_list = [] end = 0 repetitions = format_string.count('{') for i in range(repetitions): start = format_string.find('{', end) + 1 end = format_string.find('}', start) key = format_string[start:end] key_list.append(key) return key_list def remove_keys(format_string): """Remove the parts of speech from the text for modification.""" regex = r"\{.*?\}" output = re.sub(regex, '{}', format_string) return output def parse(raw): """ Parse input for further processing. get_keys is called to get the parts of speech to be modified remove_keys is called to strip the parts of speech to be replaced """ prompts = get_keys(raw) stripped = remove_keys(raw) return prompts, stripped def add_response(prompt, responses): """User is prompted for specific input based on previously gathered keys. As each response is entered, it is appended into a list to be used later. """ if prompt[0] == 'A' or 'I': # In case the user is asked for an adjective or interjection # Can't help but fix grammar whenever possible response = input(f'Enter an {prompt}: ') responses.append(response) else: response = input(f'Enter a {prompt}: ') def get_responses(prompts): """Responses are gathered by the helper function above.""" responses = [] for prompt in prompts: add_response(prompt, responses) return responses def output_story(raw): """Call the above helper functions to bring it all together. First, the prompts are parsed into a more usable format. Next, the prompts are presented the user to gather parts of speech. Finally, the story is recombined and prepared for display to the user. """ prompts, stripped = parse(raw) responses = get_responses(prompts) story = stripped.format(*responses) return story if __name__ == "__main__": greeting() raw = read_file('test.txt') story = output_story(raw) write_file('madlib_complete.txt', story)
17b7410330ee2eda58e88f7800a127af79ee8a44
seggiepants/rosetta
/python/mugwump/mugwump.py
3,868
3.984375
4
from random import randint from math import sqrt CONSOLE_W = 80 GRID_W = 10 GRID_H = GRID_W MAX_TURNS = 10 NUM_MUGWUMPS = 4 def center_print(message): x = (CONSOLE_W - len(message)) // 2 # // does integer division print(' ' * x + message) def init_mugwumps(mugwumps): for mugwump in mugwumps: mugwump['x'] = randint(0, GRID_W - 1) mugwump['y'] = randint(0, GRID_H - 1) mugwump['found'] = False def pretty_print(left, message): for word in message.split(): # default is to split on whitespace if left > 0 and left < CONSOLE_W: print(' ', end='') left += 1 if left + len(word) > CONSOLE_W: print() left = 0 print(word, end='') left = left + len(word) return left def print_introduction(): center_print('MUGWUMP') center_print('CREATIVE COMPUTING MORRISTOWN, NEW JERSEY') print() print() print() # Courtesy People's Computer Company left = 0 left = pretty_print(left, 'The object of this game is to find four mugwumps') left = pretty_print(left, 'hidden on a 10 by 10 grid. Home base is position 0, 0') left = pretty_print(left, 'any guess you make must be two numbers with each') left = pretty_print(left, 'number between 0 and 9, inclusive. First number') left = pretty_print(left, 'is distance to the right of home base, and second number') left = pretty_print(left, 'is distance above home base.') print() print() left = 0 left = pretty_print(left, 'You get 10 tries. After each try, I will tell') left = pretty_print(left, 'you how far you are from each mugwump.') print() print() if __name__ == '__main__': print_introduction() mugwumps = [{'x': 0, 'y': 0, 'found': False} for i in range(NUM_MUGWUMPS)] while True: # Loop once for each time you play the game turn = 0 init_mugwumps(mugwumps) while True: # Loop once for each turn in a game turn = turn + 1 print() print() x = -1 y = -1 while x < 0 or x >= GRID_W or y < 0 or y >= GRID_H: line = input(f'Turn No. {turn}, what is your guess? ') try: position = [int(token) for token in line.split(',')] if len(position) >= 2: x = position[0] y = position[1] except: x = -1 y = -1 for i, mugwump in enumerate(mugwumps): if not mugwump['found']: if mugwump['x'] != x or mugwump['y'] != y: distance = sqrt((mugwump['x'] - x) ** 2 + (mugwump['y'] - y) ** 2) print(f'You are {round(distance, 2)} units from mugwump {i + 1}') else: mugwump['found'] = True print(f'YOU HAVE FOUND MUGWUMP {i + 1}') remaining = sum([1 for mugwump in mugwumps if not mugwump['found']]) if remaining == 0: print(f'YOU GOT THEM ALL IN {turn} TURNS!') break elif turn >= MAX_TURNS: print() print(f'Sorry, that\'s {turn} tries. Here is where they\'re hiding.') for i, mugwump in enumerate(mugwumps): if not mugwump['found']: print(f'Mugwump {i + 1} is at ({mugwump["x"]}, {mugwump["y"]})') break print ('THAT WAS FUN!') line = '' while len(line) == 0 or (line[0] != 'Y' and line[0] !='N'): line = input('Would you like to play again (Y/N)? ').strip().upper() if line[0] == 'N': break
7b3f5897e6e1c0a5a4c8e7590dacf428fab0fb6d
HiThereItsMeTejas/Python
/count.py
577
3.703125
4
import xlrd from collections import Counter def FindDuplicates(in_list): counts = Counter(in_list) two_or_more = [item for item, count in counts.items() if count >= 2] print (two_or_more) # print Counter(two_or_more) return len(two_or_more) > 0 workbook = xlrd.open_workbook(r"C:\Users\Vizi User34\Desktop\EN.JSON.xlsx") sheet = workbook.sheet_by_index(0) col_a = [sheet.row(row)[1].value for row in range(sheet.nrows)] # Read in all rows print('Duplicate Values : ') print (FindDuplicates(col_a)) print('All values in Row',Counter(col_a))
798533fc7479757df608a9b228323eea36a0e122
spradeepv/dive-into-python
/hackerrank/domain/data_structures/linked_lists/merge_point.py
766
3.953125
4
""" Find the node at which both lists merge and return the data of that node. head could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node """ def FindMergeNode(headA, headB): data = None while headA: temp = headB found = False while temp: dataA = headA.data dataB = temp.data #print dataA, dataB if dataA == dataB: data = dataA found = True break else: temp = temp.next if found: break headA = headA.next headB = headB.next return data
ea6f82c5c805e270785b1e05267f9cdfa08c03b3
krijnen/vuurschepen_northsea
/location.py
503
3.703125
4
from math import * class location(object): def __init__(self, x, y): self.x = x self.y = y def update(self, v, theta): self.x += v * cos(theta / 180 * pi) self.y += v * sin(theta / 180 * pi) def distance(self, location): dx = location.x - self.x dy = location.y - self.y return sqrt(dx**2 + dy**2) def angle(self, location): dx = location.x - self.x dy = location.y - self.y return atan2(dx,dy)*180/pi
0b4f14963b6d694152b44da08b02acb2402e01a3
chavan-tushar/python-CA1
/createPayslipUsingClass.py
5,172
3.5625
4
class PrintPaySlip: # def __init__(self): # self.forStaffID = staffID; def printSalarySlip(self): with open("./Accounts/Hours.txt") as hrs: for data in hrs: dataInList = data.split() forWeek = dataInList[0] forStaffID = dataInList[1] hrsWorked = float(dataInList[2]) # Below code is used to convert DD/MM/YYYY into YYYY_MM_DD format. date, month, year = forWeek.split("/") formatedDate = "_".join([year, month, date]) # Below lines will call function and data will be stored in approriate variables #print(EmployeeDetails.showMessage(self)) try: surname, firstName, PPSNumber, stdHrs, hrRate, overTimeRate, taxCredit, stdBand = EmployeeDetails.getStaffDetails(self,forStaffID) except: print(f"Record for StaffID {forStaffID} is not present in Employees.txt file") continue stdRate, highRate = TaxRate.getTaxRate(self) regHrs, overTimeHrs = 0, 0 if (hrsWorked > stdHrs): regHrs = stdHrs overTimeHrs = hrsWorked - regHrs elif (hrsWorked > 0 and hrsWorked <= stdHrs): regHrs = hrsWorked else: overTimeHrs = hrsWorked # Creating payslips with open(f"./Accounts/Payslips/{forStaffID}_{formatedDate}.txt", "w") as ps: # Calculations to be used while printing Payslip salFromRegHrs = regHrs * hrRate salFromOvertimeHrs = overTimeHrs * overTimeRate grossPay = salFromRegHrs + salFromOvertimeHrs partOfSalForStdRate = stdBand if (grossPay > stdBand) else grossPay partOfSalForHighRate = 0 if (grossPay <= stdBand) else grossPay - stdBand dedFromStdRate = ((partOfSalForStdRate * stdRate) / 100) dedFromHighRate = 0 if (grossPay <= stdBand) else ((highRate * partOfSalForHighRate) / 100) totalDeduction = dedFromStdRate + dedFromHighRate netDeduction = totalDeduction - taxCredit if (totalDeduction - taxCredit > 0) else 0 netPay = grossPay - netDeduction # Printing a Payslip ps.writelines("\n\t\t\t\tPAYSLIP\n\n\n"); ps.writelines(f"StaffID: {forStaffID}\n"); ps.writelines(f"Staff Name: {firstName} {surname}\n"); ps.writelines(f"PPSN: {PPSNumber}\n"); ps.writelines(f"Date: {forWeek}\n"); ps.writelines(f"\t\t\tHours\t\tRate\t\tTotal\n"); ps.writelines(f"Regular\t\t{regHrs}\t\t{hrRate}\t\t{salFromRegHrs}\n"); ps.writelines(f"Overtime\t\t{overTimeHrs}\t\t{overTimeRate}\t\t{salFromOvertimeHrs}\n\n"); ps.writelines(f"Gross Pay\t{grossPay}\n\n") ps.writelines(f"\t\t\t\t\tRate\t\tTotal\n"); ps.writelines(f"Standard Band\t\t{partOfSalForStdRate}\t\t{stdRate}%\t\t{dedFromStdRate}\n"); ps.writelines(f"Higher Rate\t\t{partOfSalForHighRate}\t\t{highRate}%\t\t{dedFromHighRate}\n\n"); ps.writelines(f"Total Deductions\t{totalDeduction}\n"); ps.writelines(f"Tax Credit\t\t{taxCredit}\n"); ps.writelines(f"Net Deduction\t\t{netDeduction}\n"); ps.writelines(f"Net Pay\t\t{netPay}\n"); print(f"Payslip for {forStaffID} for week {forWeek} is created.") class EmployeeDetails: def getStaffDetails(self,staffID): with open("./Accounts/Employees.txt") as empData: for empDetails in empData: empDetailsList = empDetails.split() if staffID == str(empDetailsList[0]): surname = empDetailsList[1] firstName = empDetailsList[2] PPSNumber = empDetailsList[3] stdHrs = float(empDetailsList[4]) hrRate = float(empDetailsList[5]) overTimeRate = float(empDetailsList[6]) taxCredit = float(empDetailsList[7]) stdBand = float(empDetailsList[8]) return surname, firstName, PPSNumber, stdHrs, hrRate, overTimeRate, taxCredit, stdBand class TaxRate: def getTaxRate(self): with open("./Accounts/Taxrates.txt") as tr: for data in tr: taxRate = data.split() stdRate = float(taxRate[0]) highRate = float(taxRate[1]) return stdRate, highRate if __name__ == "__main__": import os path = "/home/tushar/StudyMaterial/python-CA1/Accounts/Payslips" if (not os.path.isdir(path)): os.makedirs(path) # makedirs is used to create /Accounts/Payslips. payslip = PrintPaySlip() payslip.printSalarySlip()
a5cb61581e3e31485d2f69579ec38830b5fd8d00
Avinash110/LeetCode
/Backtracking/78 Subsets/Solution.py
917
3.546875
4
class Solution: # Using binary counter def subsetsUsingBinary(self, nums): output = [] length = len(nums) for i in range(2**length, 2**(length + 1)): binNum = bin(i) currSS = [] for j in range(3, len(binNum)): if binNum[j] == "1": currSS.append(nums[j - 3]) output.append(currSS) return output #Time Complexity: N*2^N | Space Complexity: N*2^N def subsetsUsingBacktracking(self, nums): self.output = [] nums.sort() self.helper([], nums, 0) return self.output def helper(self, tempList, nums, start): self.output.append([n for n in tempList]) for i in range(start, len(nums)): tempList.append(nums[i]) self.helper(tempList, nums, i+1) tempList.pop()
236ad98f976d13d21b5ef555d2d8fbf5e1185894
pavanmadiwa/Python--Let-s-upgrade
/Python- Let's upgrade- Day 2 Assignment.py
1,899
4.28125
4
#!/usr/bin/env python # coding: utf-8 # # Assignment 2: # a. Basic python syntax: # In[2]: #Ritual: print("Hello beautiful world") # In[4]: print("This is a back slash \ character ") # In[5]: print("Welcome python") # In[7]: print("This is my the use of \"backslash\" character") # In[10]: print("""This is an instance of a triple quotes Hey here is the difference """) # In[11]: """ this notebook was created by me """ # In[12]: print('usage of single quotes') # In[13]: print("usage \t of escape \n sequence") # In[16]: name = 'mickey mouse' age = 10 salary = 20000 print("Disney famous cartoon character is", name,"age is", age, "salary is", salary) # In[17]: print("Disney famous cartoon character is %s age is %d salary is %d" %(name, age, salary)) # In[18]: """ Variable assignment""" a = 20 b = 12 print(a) print(b) # In[19]: print(id(a)) print(id(b)) # In[20]: x = y = z = 50 print(x) print(y) print(id(y)) # In[21]: del(x) print(x) print(y) # In[22]: print(y) # In[23]: """Operators""" a = 50 b = 10 c= 3 print(a+b) print(a-b) print(a*b) print(a/b) print(a//b) print(a**c) print(a^c) # In[30]: x = 20 y = 10 print(x == y) print(x > y) print(x < y) print(x <= y) print(x >= y) print(x!= y) # In[31]: print(x = !y) # In[33]: x = 20 y = 10 print(x & y) print(x | y) print(~x) print(~y) # In[34]: print(bin(a)) # In[37]: x = 30 y = 15 print(x and y) print(x or y) # In[44]: p = 10 print(10 > 9 and p >= 10) print(10 < 9 and p >= 11) # In[46]: n = 20 print(10 < 9 or n > 10) print(10 > 9 or n <= 10) # In[47]: """ precedence rule""" print(15+3/2-1*15/11//20) # In[48]: a = -2 b = 266 c = 266 print(a is b) print(a is not c) print(b is c) # In[54]: str = "karna was a good friend" str1 = "friend" # str1 in str print(str not in str1) # In[56]: s = t = 266 print(id(s)) print(id(t))
5ff58f339b14906e013cd6b6291605d95e0beec1
tawhid37/Python-for-Everybody-Coding
/DataStructure Python/list2.py
581
3.953125
4
fname = input("Enter file name: ") file=open(fname,'r') count=0 lst=list() for x in file: line=x.rstrip() if line.startswith('From '): words=line.split() count=count+1 print(words[1]) print("There were", count, "lines in the file with From as the first word") """count = 0 for line in fh: line = line.rstrip() words=line.split() if len(words) == 0 : continue if words[0] !='From': continue email = words[1] print(email) if words[0] =='From': count+=1 print("There were", count, "lines in the file with From as the first word") """
013b7f6c9c9bdd75290bbf0a9ccc966352e4efd4
ganesh909909/html-bootstrap
/Acessing instance variables.py
356
3.84375
4
#within the class by using self from outside of the class by using object reference class student: def __init__(self,x,y): self.name=x self.age=y def info(self): print('hello my name is :',self.name)#(self) print('my age is :',self.age) s1=student('ganesh',24) s1.info() print(s1.name,[s1.age])#(object reference)
566c1185799ef4a59650bd5f4b804f76cc4c00c7
Arturou/Python-Exercises
/python_demos/function_exercises/level_one_two.py
288
3.90625
4
""" MASTER YODA: Given a sentence, return a sentence with the words reversed """ def master_yoda(text): arr = text.split(' ') arr = arr[::-1] return ' '.join(arr) print("Test #1: {}".format(master_yoda('I am home'))) print("Test #2 {}".format(master_yoda('We are ready')))
0fda2a640c3f4c394e003d1e7eaee69186c9885a
StephanieCherubin/Tweet-Generator
/robot_random_name.py
1,402
3.890625
4
# import random # import string # class Robot(object): # used_names = set() # def __init__(self): # self.reset() # def generate_new_random_name(self): # while True: # new_random_name = self.random_name() # if new_random_name not in self.used_names: # return new_random_name # def random_name(self): # return random.choice(string.ascii_uppercase) + \ # random.choice(string.ascii_uppercase) + \ # str(random.randrange(0,9)) + \ # str(random.randrange(0,9)) + \ # str(random.randrange(0,9)) # def reset(self): # self.name = self.generate_new_random_name() # self.used_names.add(self.name) # print(random_name("lsfd1")) import random import string class Robot(object): used_names = set() def __init__(self): self.reset() def generate_new_random_name(self): while True: new_random_name = self.random_name() if new_random_name not in self.used_names: return new_random_name def random_name(self): return random.choice(string.ascii_uppercase) + \ random.choice(string.ascii_uppercase) + \ str(random.randrange(0,9)) + \ str(random.randrange(0,9)) + \ str(random.randrange(0,9)) def reset(self): self.name = self.generate_new_random_name() self.used_names.add(self.name) print(random_name("lsgxf"))