blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
af3d3e798e2d845a7024b3a3acf949f24e87b447 | DAVMARROS/AndroidPython | /CRUD.py | 1,950 | 4.25 | 4 | """
Nombre: CRUD.py
Objetivo: muestra la operacion de la estructura de datos llamada lista
Autor:
Fecha: 07/11/2019
"""
lista = []
def insetarItem():
item = str(input("Ingrese el elemento a insertar: "))
lista.append(item)
pausa()
def buscarItem():
item = str(input("Ingrese el elemento a buscar: "))
if item in lista:
print("Item encontrado: ",item)
else:
print("El item no existe en la lista: ")
pausa()
def buscarPosicion():
index = int(input("Ingrese la posicion del elemento a buscar: "))
if(len(lista)>index-1):
print("Item: ",lista[index-1])
else:
print("Indice fuera de rango")
pausa()
def modificarItem():
item = str(input("Ingrese el elemento a modificar: "))
if item in lista:
index = lista.index(item)
item = str(input("Ingrese el nuevo elemento: "))
lista[index] = item
else:
print("El item no existe en la lista")
pausa()
def eliminarItem():
item = str(input("Ingrese la posicion del elemento a eliminar: "))
if item in lista :
lista.remove(item)
else:
print("El item no existe en la lista")
pausa()
def pausa():
print("\nOperacion realizada")
wait = input("Oprime una tecla para continuar")
def reporte():
cont=1
for i in lista:
print("Item",cont,":",i)
cont+=1
pausa()
# Funcion main
def main():
ciclo="s"
while ciclo=="S" or ciclo=="s":
print("--- CRUD con listas ---\n")
print("1. Agregar elemento")
print("2. Buscar elemento")
print("3. Buscar por posicion")
print("4. Modificar elemento")
print("5. Eliminar elemento")
print("6. Listado")
print("7. Salir")
op=int(input("Selecciona la opcion: "))
if op==1:
insetarItem()
elif op==2:
buscarItem()
elif op==3:
buscarPosicion()
elif op==4:
modificarItem()
elif op==5:
eliminarItem()
elif op==6:
reporte()
elif op==7:
ciclo="n"
else:
print("Opcion no valida")
print("\n");
else:
print("*** Fin de programa ***")
# Para main
if __name__ == '__main__':
main()
|
272acbf2c87c73f0eee2243c6a12978cdb28a53f | tinghaoMa/python | /demo/base/lesson_10.py | 2,118 | 4.28125 | 4 | #!/user/bin/python
# -*- coding: utf-8 -*-
"""
迭代器
可以直接作用于for循环的数据类型有以下几种:
一类是集合数据类型,如list、tuple、dict、set、str等;
一类是generator,包括生成器和带yield的generator function。
这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。
"""
from collections import Iterable, Iterator
# 可以使用isinstance()判断一个对象是否是Iterable对象:
print(isinstance([], Iterable))
print(isinstance((), Iterable))
print(isinstance({}, Iterable))
print(isinstance('abc', Iterable))
print(isinstance(100, Iterable))
print(isinstance((x for x in range(10)), Iterable))
print(isinstance([x for x in range(10)], Iterable))
print('\n')
'''
生成器不但可以作用于for循环,还可以被next()函数不断调用并返回下一个值,
直到最后抛出StopIteration错误表示无法继续返回下一个值了。可以被next()函数
调用并不断返回下一个值的对象称为迭代器:Iterator
'''
# 使用isinstance()判断一个对象是否是Iterator对象
print(isinstance([], Iterator))
print(isinstance((), Iterator))
print(isinstance({}, Iterator))
print(isinstance('abc', Iterator))
print(isinstance(100, Iterator))
print(isinstance((x for x in range(10)), Iterator))
print(isinstance([x for x in range(10)], Iterator))
'''
生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。
把list、dict、str等Iterable变成Iterator可以使用iter()函数
'''
print('iterable 转换为 iterator 使用iter()函数')
print(isinstance(iter([]), Iterator))
print(isinstance(iter(()), Iterator))
print(isinstance(iter({}), Iterator))
print(isinstance(iter('abc'), Iterator))
'''
小结:
凡是可作用于for循环的对象都是Iterable类型;
凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象
'''
|
7b1199ca5d2309e5afec6865719c7aed17e8d129 | flacogabrielc/Selenium_Python | /Clase 2/entrada.py | 238 | 3.78125 | 4 | edad = input("Ingrese una edad: ")
print('su edad es ' +edad)
edad = int(edad)
print("su edad es " + str(edad))
print(edad + 5)
#print(edad +5) -> esto da error por tipo de datos debo castearla a int
print('hola mundo ' + 'hola planeta')
|
1126a543151da9ae36e32de62f0cd902e4bfcaf0 | MichaelJWest/Project-Euler | /problem5.py | 390 | 3.59375 | 4 | #2520 is the smallest number that can be divided by each of the numbers from 1 to
#10 without any remainder.
#What is the smallest positive number that is evenly divisible by all of the numbers
#from 1 to 20?
def gcd(a, b):
return b and gcd(b, a % b) or a
def lcm(a, b):
return a * b / gcd(a, b)
multiple = 20
for i in xrange(10, 21):
multiple = lcm(multiple, i)
print multiple |
14a287cb0d0731cfd0587877c694c73430254269 | manmeet-22/Python-Questions | /Questions/Q21.py | 491 | 3.546875 | 4 | class abc:
class_var = 0
sal=0
name=""
dept=0
def disp(self):
print(self.name ,self.sal, self.dept )
def total(self): return abc.class_var
def __init__(self,name,sal,dept):
abc.class_var+=1
self.name = name
self.sal = sal
self.dept = dept
obj1=abc("A",10,"a")
obj2=abc("B",20,"b")
obj3=abc("C",30,"b")
obj4=abc("D",40,"b")
obj1.disp()
obj2.disp()
obj3.disp()
obj4.disp()
print("The number of employees are ",obj4.total())
|
2cc454a67f43689d3131d30aa52f264bdf2d1b2b | kg55555/pypractice | /Part 1/Chapter 10/exercise_10.5.py | 211 | 3.84375 | 4 | while True:
answer = input("Why do you like programming? Enter 'q' to quit\n")
if answer == 'q':
break
with open('r_programming', 'a') as file_object:
file_object.write(answer + "\n") |
75568dfd7d28c9d53fb36385235ef32e2cc3a0c8 | bytoola/python2 | /m4 flow contral/basic if else.py | 400 | 3.734375 | 4 | '''
num = eval(input("Input number: "))
if num >= 60 :
print('passed!')
if num <80:
print("so so!!")
else:
print("good!")
else:
print('failed')
'''
'''
coverage,area = eval(input('please input two number'))
count = area // coverage
count += 0 if area % coverage == 0 else 1
unit = 'can' if count == 1 else 'cans'
print('need {0} {1} to piant'.format(count,unit))
'''
|
d2d111e80881166194cc0f67fda999f3758f0e18 | gabriellaec/desoft-analise-exercicios | /backup/user_259/ch150_2020_04_13_20_22_24_375515.py | 130 | 3.671875 | 4 | def calcula_pi(n):
radicando = 0
for i in range(1,n+1):
radicando+=6/(i**2)
pi = radicando**0.5
return pi |
947c5e9e0f7b784ae37e6d218cb6b083ad7b4c0f | mjvelota/OPS435-Lab3 | /lab3a.py | 441 | 3.609375 | 4 | #!/usr/bin/env python3
# return_text_value() function
#Author ID: mjvelota
def return_text_value():
name = 'Terry'
greeting = 'Good Morning ' + name
return greeting
# return_number_value()
def return_number_value():
num1 = 10
num2 = 5
num3 = num1 + num2
return num3
# Main Program
if __name__ == '__main___':
print('Python code')
text = return_text_value()
print(text)
number = return_number_value()
print(str(number))
|
9299be647b657196ed1bef9b9c35a1967d35f340 | y2sman/algorithm_solve | /baekjoon/[2] silver/1541_잃어버린 괄호/1541_잃어버린 괄호.py | 848 | 3.515625 | 4 | import re
tmp = input()
result = re.split('[+-]',tmp)
locate = 1
for i in range(len(tmp)):
if tmp[i] == "+":
result.insert(locate,tmp[i])
locate += 2
elif tmp[i] == "-":
result.insert(locate,tmp[i])
locate += 2
locate = 0
while "+" in result:
if result[locate] == "+":
tmp = int(result[locate-1]) + int(result[locate+1])
result.pop(locate-1)
result.pop(locate-1)
result.pop(locate-1)
result.insert(locate-1, tmp)
else:
locate += 1
if locate == len(result):
locate = 0
locate = 0
while "-" in result:
if result[locate] == "-":
tmp = int(result[locate-1]) - int(result[locate+1])
result.pop(locate-1)
result.pop(locate-1)
result.pop(locate-1)
result.insert(locate-1, tmp)
else:
locate += 1
if locate == len(result):
locate = 0
print(result[0])
|
191ced8c7883f926988b1d3eb0e96380fb28dea9 | AnushaPalla/python-ICP1 | /Firstprogram.py | 329 | 4.03125 | 4 | a=int(input("enter first number"))
b=int(input("enter second number"))
print("addition of 2 numbers is:",a+b)
print("hello world")
print("subtraction of 2 numbers is:", a-b)
print("multiplication:",a*b)
print("divison", a/b)
print("modulous", a%b)
string1=input("enter a string")
len=0
for i in string1:
len=len+1
print(len)
|
d90888975f2b30ffceebe385514b6a69d5ffbcc5 | svonme/python | /basis/sorted.py | 377 | 3.90625 | 4 | # -*- coding: utf-8 -*-
#
# @Time : 2018/4/8 18:13
# @Author : [email protected]
#
# sorted 数据排序
def sort(value):
return abs(value)
if __name__ == '__main__':
arr = [1, 2, 3, 1, 6, 9, 10]
# 默认排序
arr2 = sorted(arr)
# 数组倒序
arr2.reverse()
# 指定排序方式
arr3 = sorted(arr, reverse=True)
print(arr2)
print(arr3)
|
bd82cd284a8764760ad2a5b291aeeaf3e9ea5478 | theissn/py-tic-tac-toe | /main.py | 1,795 | 3.8125 | 4 | class Board():
def __init__(self):
self.list = {}
self.board = []
self.turn = 'x'
self.win_combs = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]
self.create()
def create(self):
num = 0;
for i in range(3):
line = []
for x in range(3):
line.append(num)
self.list[num] = False
num += 1
self.board.append(line)
def show(self):
for line in self.board:
for item in line:
if self.list[item] is False:
print(f"{item} ", end="")
else:
print(f"{self.list[item]} ", end="")
print("")
print("")
def move(self, num):
if self.list[num] == False:
self.list[num] = self.turn
def who(self):
if self.turn is 'x':
self.turn = 'o'
else:
self.turn = 'x'
return self.turn;
def won(self, move):
for combs in self.win_combs:
all = False
num = 0
for num in combs:
if self.list[num] == move:
all = True
num += 1
else:
all = False
if num is 3:
return True
if all == True:
return True
board = Board()
while True:
board.show()
move = board.who()
user_action = input(f"Make your move ({move}): (x to exit): ")
if (user_action.lower() is 'x'):
playing = False
else:
board.move(int(user_action))
if board.won(move) is True:
print(f"{move} won!!")
break
|
1c1af8ca3380f957c2aa8e2c1bbbe7a00998f230 | annabelflook/mr_calculator | /calculator_utils.py | 1,437 | 3.5625 | 4 | import re
from mendeleev import element
from collections import Counter
def split_into_brackets(molecule):
split_by_brackets = re.findall(r"(\(([^()]+)\)*)([0-9]*)|([A-Z][a-z]*)(\d*)", molecule)
return split_by_brackets
def stoichiometry(molecule):
counted = Counter()
split = split_into_brackets(molecule)
for segment in split:
*other, bracket_number, atom_type, atom_number = segment
if atom_type == '':
elements = split_into_brackets(segment[1])
for element in elements:
*other, atom_type, atom_number = element
if bracket_number == '':
bracket_number = 1
if atom_number == '':
atom_number = 1
number_of_atom = str(atom_type) * int(atom_number) * int(bracket_number)
counted += Counter({atom_type: int(len(number_of_atom)/len(atom_type))})
else:
if atom_number == '':
atom_number = 1
number_of_atom = str(atom_type) * int(atom_number)
counted += Counter({atom_type: int(len(number_of_atom)/len(atom_type))})
return dict(counted)
def calculate_mr(molecule):
stoich = stoichiometry(molecule)
mr_total = 0
for atom, number in stoich.items():
name = element(atom)
mr_total += name.mass * number
print(f'{mr_total:.2f} g/mol')
return mr_total
|
da8a5b72ef2dfd117c532d6e19a2a2c5bc9ce986 | smazhuvan/repl-works | /main.py | 230 | 3.921875 | 4 | listA = [24, 56, 89, 0, 15, -4, 25, -8, 125, -98]
def small_num(numbers):
smallest_num = numbers[0]
for num in numbers:
if num < smallest_num:
smallest_num = num
return(smallest_num)
print(small_num(listA))
|
3d2189b436a12d220fd330bb393f8565d6629e1c | aditjain588/Leet-Code-problems | /Remove Duplicates from Sorted Array.py | 265 | 3.59375 | 4 | class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
n = 0
while n <= len(nums)-3:
if nums[n] == nums[n+2]:
nums.remove(nums[n])
else:
n += 1
return len(nums) |
8a0cfbf7618f11a32ab007843c0ea28c0ac2671e | tanyafish/my-first-blog | /myfirstthings.py | 151 | 3.765625 | 4 | def hi(name):
print("hallo " + str(name) + "!")
girls = ["Alice", "Barb", "Callie", "Dave"]
for name in girls:
hi(name)
print("next girl")
|
4b1ad65dcda0f9fff7987bceabca33a8ffe7e8cf | rskarp/cs251proj9 | /data.py | 7,567 | 3.84375 | 4 | # Riley Karp
# data.py
# 2/20/2017
import sys
import csv
import numpy as np
#class that can read a csv data file and provide information about it
class Data:
def __init__(self, filename = None):
#creates a Data object by initializing the fields and reading the given csv file
#create and initialize fields
self.raw_headers = []
self.raw_types = []
self.raw_data = []
self.header2raw = {}
self.matrix_data = np.matrix([])
self.header2matrix = {}
self.matrix2header = {} #allows headers to be listed in order in self.get_headers()
if filename != None:
self.read(filename)
def read(self, filename):
#reads the given csv file and adds headers, types, and data to their respective fields
file = open( filename, 'rU' )
rows = csv.reader( file )
#append data to raw_data list field
for row in rows:
self.raw_data.append(row)
file.close()
#strip data to get rid of random spaces
for row in self.raw_data:
for j in range( len(row) ):
row[j] = row[j].strip()
#add headers and types to their respective fields
self.raw_headers = self.raw_data.pop(0)
self.raw_types = self.raw_data.pop(0)
#add values to header2raw dictionary & strip header strings
for item in self.raw_headers:
self.header2raw[ item ] = self.raw_headers.index(item)
#add numeric values to matrix_data and header2matrix dictionary
idx = 0
data = []
for i in range( len(self.raw_types) ):
if self.raw_types[i] == 'numeric':
#add headers and indexes to dictionary
header = self.raw_headers[i]
self.header2matrix[header] = idx
self.matrix2header[idx] = header
#add data to matrix_data
data.append([]) #makes new empty row
for r in range( self.get_raw_num_rows() ):
data[idx].append( self.raw_data[r][i] )
idx += 1
#put data into numpy matrix
self.matrix_data = np.matrix( data , dtype = float).T
def write( self, filename, headers = [] ):
#writes the data of the specified headers to a file of the given name
if len(headers) > 0:
d = self.get_data( headers )
file = filename + '.csv'
f = open( file, 'wb' )
writer = csv.writer( f, delimiter=',', quoting=csv.QUOTE_MINIMAL )
writer.writerow(headers)
types = []
for h in headers:
types.append( self.get_raw_types()[ self.header2raw[h] ] )
writer.writerow(types)
for i in range( d.shape[0] ):
row = []
for j in range( len(headers) ):
if headers[j] in self.header2raw.keys():
row.append( self.get_raw_value( i, headers[j] ) )
elif headers[j] in self.header2matrix.keys():
row.append( round( d[i,j],3 ) )
if row != []:
writer.writerow( row )
f.close()
def get_headers(self):
#returns a list of the headers of columns with numeric data
headers = []
for i in range( len(self.matrix2header) ):
headers.append( self.matrix2header[i] )
return headers
def get_num_columns(self):
#returns the number of columns with numeric data
return len(self.header2matrix)
def get_row(self, rIdx):
#returns the specified row of numeric data
if rIdx >= 0 and rIdx < self.get_raw_num_rows():
return self.matrix_data.tolist()[rIdx]
def get_value(self, rIdx, cString):
#returns the value of numeric data at the given row,col location
if rIdx >= 0 and rIdx < self.get_raw_num_rows() and cString in self.header2matrix:
return self.matrix_data[ rIdx, self.header2matrix[cString] ]
def get_data(self, headers):
#returns a matrix of numeric data from the columns with the specified list of headers
d = np.matrix([]) #empty matrix
d.shape = ( self.get_raw_num_rows(), 0 ) #reshape matrix so we can use hstack
for h in headers:
if h in self.header2matrix.keys():
cIdx = self.header2matrix[h]
col = self.matrix_data[ 0:, cIdx:cIdx+1 ]
d = np.hstack( [d,col] )
return d
def addColumn(self, header, type, points):
#adds a column of data with the given header, type, and list of data points
if len(points) == self.get_raw_num_rows():
self.header2raw[header] = self.get_raw_num_columns()
self.raw_headers.append(header)
self.raw_types.append(type)
for i in range( len(points) ):
self.raw_data[i].append(points[i])
if type == 'numeric':
self.header2matrix[header] = self.get_num_columns()
col = np.matrix( points ).T
self.matrix_data = np.hstack( [self.matrix_data, col] )
def get_raw_headers(self):
#returns a reference to the list of all the headers
return self.raw_headers
def get_raw_types(self):
#returns a reference to the list of data types in each column
return self.raw_types
def get_raw_num_columns(self):
#returns the total number of columns of data
return len(self.raw_headers)
def get_raw_num_rows(self):
#returns the total number of rows of data
return len(self.raw_data)
def get_raw_row(self, idx):
#returns the specified row of raw data
if idx >=0 and idx < self.get_raw_num_rows():
return self.raw_data[idx]
def get_raw_value(self, rIdx, cString):
#returns the value at the specified row,col location
if rIdx >=0 and rIdx < self.get_raw_num_rows():
return self.raw_data[ rIdx ][ self.header2raw[cString] ]
def toString(self):
#prints the contents of the Data object by rows and columns
string = ''
for item in [self.get_raw_headers(), self.get_raw_types()]:
for idx in range( self.get_raw_num_columns() ):
string += item[idx] + '\t'
string += '\n'
for row in self.raw_data:
for idx in range( len(row) ):
string += row[idx] + '\t'
string += '\n'
print string
def main(filename):
#tests all the methods of the Data class
d = Data( filename )
print '\t Testing Raw Methods'
print 'd.get_raw_headers: ' , d.get_raw_headers()
print 'd.get_raw_types: ' , d.get_raw_types()
print 'd.get_raw_num_columns: ' , d.get_raw_num_columns()
print 'd.get_raw_row(0): ' , d.get_raw_row(0)
# print 'raw_data: ' , d.raw_data
# print 'header2raw:' , d.header2raw
# d.toString()
headers = ['hi', 'headers', 'in', 'spaces', 'bye']
print '\n \t Testing Numeric Methods'
print 'd.get_headers: ' , d.get_headers()
print 'd.get_num_columns: ' , d.get_num_columns()
print 'd.get_row(0): ' , d.get_row(0)
print 'd.get_value( 1, "bad" ): ' , d.get_value( 1, 'bad' )
print 'd.get_data( headers ): \n' , d.get_data( headers )
print '\n \t Testing Analysis Methods'
print 'range: ' , a.data_range(headers,d)
print 'median: ' , a.median(headers,d)
print 'mean: ' , a.mean(headers,d)
print 'stdev: ' , a.stdev(headers,d)
print 'normalize_columns_separately: \n' , a.normalize_columns_separately(headers,d)
print 'normalize_columns_together: \n' , a.normalize_columns_together(headers,d)
print '\n \t Testing addColumn'
print 'd.get_raw_headers: ' , d.get_raw_headers()
print 'd.get_raw_types: ' , d.get_raw_types()
print 'd.raw_data: ' , d.raw_data
print 'd.get_data( headers ): \n' , d.get_data( headers )
print '\t adding column'
d.addColumn( 'newCol', 'numeric', [3,1,4] )
headers.append( 'newCol' )
print 'd.get_raw_headers: ' , d.get_raw_headers()
print 'd.get_raw_types: ' , d.get_raw_types()
print 'd.raw_data: ' , d.raw_data
print 'd.get_data( headers ): \n' , d.get_data( headers )
def testWrite(filename):
d = Data(filename)
headers = d.get_raw_headers()[0:5]
d.write( 'testWrite',headers )
if __name__ == '__main__':
if len(sys.argv) < 2:
print "Usage: python %s <csv_filename>" % sys.argv[0]
print " where <csv_filename> specifies a csv file"
exit()
# main( sys.argv[1] )
testWrite( sys.argv[1] ) |
91b646ec88ed305b5155948d456b728545760a11 | k-harada/AtCoder | /ARC/ARC105/A.py | 632 | 3.6875 | 4 | def solve(a, b, c, d):
s = a + b + c + d
if s % 2 == 1:
return "No"
h = s // 2
if a == h:
return "Yes"
elif b == h:
return "Yes"
elif c == h:
return "Yes"
elif d == h:
return "Yes"
elif a + b == h:
return "Yes"
elif a + c == h:
return "Yes"
elif a + d == h:
return "Yes"
return "No"
def main():
a, b, c, d = map(int, input().split())
res = solve(a, b, c, d)
print(res)
def test():
assert solve(1, 3, 2, 4) == "Yes"
assert solve(1, 2, 4, 8) == "No"
if __name__ == "__main__":
test()
main()
|
fde0936bc20ee946da14f13de151a66d164db1db | udaybhaskar578/Hacker-Rank-Challenges | /Code 30/CandyFillingBot.py | 889 | 3.765625 | 4 | # Question : https://www.hackerrank.com/contests/w30/challenges/candy-replenishing-robot
#!/bin/python3
import sys
def isShortOfCandies(candies):
if candies < 5:
return True
return False
def refillCandies(x):
global candies
candies = candies+x
def noOfCandiesRefilled(left,total,currTime,time):
if currTime == time:
return 0
elif currTime <= time and left < 5:
refillCandies(total-left)
return (total-left)
return 0
n,t = input().strip().split(' ')
n,t = [int(n),int(t)]
c = list(map(int, input().strip().split(' ')))
candiesAdded = 0
candies = n
x =1
for candiesTaken in c:
candies = candies - candiesTaken
if isShortOfCandies(candies):
candiesAdded = candiesAdded + noOfCandiesRefilled(candies,n,x,t)
candies = n
x = x+1
print(candiesAdded)
# your code goes here
|
4e6ade4462505f32531c458fbf3fee6052a57e5a | edwinevans/HarryPotterTerminalQuest | /Pigwarts/Review/numbers_fiz_hundred.py | 108 | 3.9375 | 4 | for number in range(1, 101):
if number % 3 == 0:
print "Fiz"
else:
print number
number = number + 1
|
c7b19216e5f6ca6b542b5edd4dfb8b816ab3ef5a | DivyaJyotiDas/Hackerrank | /counting-valleys.py | 1,125 | 3.640625 | 4 |
# Complete the countingValleys function below.
def countingValleys(str):
bal_factor = 0
start = ''
mountain = 0
valley = 0
for i in str:
if bal_factor == 0:
start = i
if start.lower() == 'u':
bal_factor += 1
mountain += 1
continue
if start.lower() == 'd':
bal_factor -= 1
valley += 1
continue
if bal_factor != 0:
bal_factor = check_mountain_valley(bal_factor, i)
return valley
def check_mountain_valley(bal_factor, i):
if bal_factor >= 1:
if i.lower() == 'u':
bal_factor += 1
return bal_factor
if i.lower() == 'd':
bal_factor -= 1
return bal_factor
if bal_factor <= -1:
if i.lower() == 'u':
bal_factor += 1
return bal_factor
if i.lower() == 'd':
bal_factor -= 1
return bal_factor
if __name__ == '__main__':
#n = int(input())
s = input()
result = countingValleys(s)
print(result) |
de7a3d9295a0fe974b8c8c90bd52c7ae8e78d604 | MalAnna/geekbrains-homework | /algorithms python/lesson1/task1.py | 298 | 3.734375 | 4 | a = int(input('Введите трехзначное число: '))
b = a // 100 + a % 100 // 10 + a % 10
c = (a // 100) * (a % 100 // 10) * (a % 10)
print(f'Сумма цифр трехзначного числа: {b}, произведение цифр трехзначного числа: {c}')
|
3ffaeadc6a0651974a6df33f382e4b85a100da44 | lordjavac/6-Nimt | /nimt6/tests/test_card.py | 1,962 | 4.03125 | 4 | import unittest
from ..card import Card
class TestCard(unittest.TestCase):
""" Test the Card class to verify that it functions properly. """
def test_rank(self):
''' Verify that we can create a card with a rank from 1 to 104. '''
for r in range(1, 105):
with self.subTest(msg=None):
c = Card(rank = r)
self.assertEqual(c.rank, r)
def test_minimum_rank(self):
''' Verify that we can't create a card with a rank < 1. '''
with self.assertRaises(ValueError):
c = Card(rank = 0)
def test_maximum_rank(self):
''' Verify that we cannot create a card with a rank > 104. '''
with self.assertRaises(ValueError):
c = Card(105)
def test_value(self):
''' Verify that the values are computed properly. '''
for rank in range(1, 105):
with self.subTest(msg=None):
c = Card(rank)
if rank == 55:
self.assertEqual(c.value, 7)
elif rank % 11 == 0:
self.assertEqual(c.value, 5)
elif rank % 10 == 0:
self.assertEqual(c.value, 3)
elif rank % 5 == 0:
self.assertEqual(c.value, 2)
else:
self.assertEqual(c.value, 1)
def test_eq(self):
''' Verify that equality works correctly. '''
self.assertTrue(Card(1) == Card(1))
self.assertTrue(Card(100) == Card(100))
self.assertFalse(Card(1) == Card(2))
def test_lt(self):
''' Verify that the < operator works correctly. '''
self.assertTrue(Card(1) < Card(2))
self.assertFalse(Card(2) < Card(1))
def test_gt(self):
''' Verify that the > operator works correctly. '''
self.assertTrue(Card(2) > Card(1))
self.assertFalse(Card(1) > Card(2))
if __name__ == '__main__':
unittest.main()
|
590d2bf17751f4bc312308293d69d0c3259436e0 | erjan/coding_exercises | /difference_between_maximum_and_minimum_price_sum.py | 2,177 | 3.84375 | 4 | '''
There exists an undirected and initially unrooted tree with n nodes indexed from 0 to n - 1. You are given the integer n and a 2D integer array edges of length n - 1, where edges[i] = [ai, bi] indicates that there is an edge between nodes ai and bi in the tree.
Each node has an associated price. You are given an integer array price, where price[i] is the price of the ith node.
The price sum of a given path is the sum of the prices of all nodes lying on that path.
The tree can be rooted at any node root of your choice. The incurred cost after choosing root is the difference between the maximum and minimum price sum amongst all paths starting at root.
Return the maximum possible cost amongst all possible root choices.
'''
'''
My original submission was weak, and with the recently added test case, it went TLE. The comment below (thank you @user7784J) included a
link from which I got the idea for a better way to approach the problem.
We assign a three-uplestateto each node. the root and each leaf gets (0,price,0), and each other link'sstate is
determined by the recurence relation indfs. The figure below is for Example 1 in the problem's description.
Best way to figure it out is to trace it from the recurence relation. The correct answer is24, which is
state[0] for node 1. BTW, if you start from a root other than0, the state for some nodes may change, but the answer doesn't.
'''
class Solution:
def maxOutput(self, n: int, edges: List[List[int]], price: List[int]) -> int:
g = defaultdict(list)
for a, b in edges: g[a].append(b) ; g[b].append(a)
def dfs(node1, node2 =-1):
p = price[node1]
state = (0, p, 0)
for n in g[node1]:
if n == node2: continue
(a1, a2, a3), (b1, b2, b3) = state, dfs(n, node1)
state = (max(a1, b1, a2 + b3, a3 + b2),
max(a2, b2 + p),
max(a3, b3 + p))
return state
if n <= 2: return sum(price) - min(price)
for node in range(n):
if len(g[node]) > 1:
return dfs(node)[0]
|
2c5af649506e4beddf9ea6cbb81c0df2498e5ce4 | progh2/highschool-python | /VI. 클래스/02. 클래스와 객체/05. 연산자 오버로딩/VI. 02. 05. OperatorOverloading.py | 632 | 3.921875 | 4 | class MyNumber:
def __init__(self, val):
self.val = val
def __add__(self, other):
print("__add__")
return MyNumber(self.val + other.val)
def __sub__(self, other):
print("__sub__")
return MyNumber(self.val - other.val)
def __mul__(self, other):
print("__mul__")
return MyNumber(self.val * other.val)
def __truediv__(self, other):
print("__truediv__")
return MyNumber(self.val / other.val)
n1 = MyNumber(2)
n2 = MyNumber(3)
n3 = n1 + n2
print(n3.val)
n4 = n1 - n2
print(n4.val)
n5 = n1 * n2
print(n5.val)
n6 = n1 / n2
print(n6.val)
|
45e225b315b5e181669c4c29db107c24f0a2a55a | suthirakprom/Python_BootcampKIT | /week02/ex/ex/54_matrix_addtion.py | 825 | 3.796875 | 4 | def matrix_addition(m1,m2):
k = l = m = 1
res = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]
print("MATRIX 1:")
for i in range(4):
for j in range(4):
print(m1[i][j], end=' ')
if l % 4 == 0:
print("")
l += 1
print("")
print("MATRIX 2:")
for i in range(4):
for j in range(4):
print(m2[i][j], end=' ')
if m % 4 == 0:
print("")
m += 1
print("")
print("THE RESULT:")
for i in range(4):
for j in range(4):
res[i][j] = m1[i][j] + m2[i][j]
print(res[i][j], end=" ")
if k % 4 == 0:
print("")
k += 1
matrix_addition([[1,2,3,4],[5,6,7,8],[1,2,3,4],[5,6,7,8]],[[1,2,3,4],[5,6,7,8],[1,2,3,4],[5,6,7,8]])
|
fb781a51e2f3add46ab504d797f0a21981a5295a | cheol-95/Algorithm | /Python/018. 네트워크/Network.py | 320 | 3.640625 | 4 | def solution(n, computers):
answer = 0
for i in range(len(computers)):
if answer < computers[i].count(0):
answer = computers[i].count(0)
return answer
n, computers = 3, [[1, 1, 0], [1, 1, 0], [0, 0, 1]]
# n, computers = 3, [[1, 1, 0], [1, 1, 1], [0, 1, 1]]
print(solution(n, computers)) |
176892863743bf66cf09446d35d2d04f472b395b | nyeo2/Nand2Tetris-Assembler | /binConverter.py | 396 | 3.609375 | 4 | def dectobin(dec):
if type(dec) != int:
dec = int(dec)
final = ''
while dec != 0:
final = str(dec % 2) + final
dec //= 2
return final
def bintodec(bina):
binal = []
final = 0
for char in bina:
binal.append(int(char))
expt = 0
while binal:
final += binal.pop() * (2 ** expt)
expt += 1
return final
|
84b522e4ce3f5d9486693bb97122dc3a35a41c34 | erba994/ftyers.github.io | /2018-komp-ling/practicals/tokenization/dictionary_extractor.py | 506 | 3.53125 | 4 | def dict_extract(filename):
with open(filename, "r", encoding="utf-8") as f:
l = f.readlines()
dict = []
for line in l:
if line[0].isdigit():
s = line.split("\t")
dict.append(s[1])
dict = set(dict)
return dict
if __name__ == "__main__":
with open("dictionary.txt", "w+", encoding="utf-8") as r:
filename = input("Enter filename here: ")
r.write("\n".join(dict_extract(filename)))
|
860424cb9d44326930bd2a91325e626556be209a | Ahnseungwan/Phython_practice | /2021.01/1.2/1.2 세트.py | 690 | 3.609375 | 4 | # 세트 (집합)
# 중복 안됨, 순서 없음
my_set = {1,2,3,3,3}
print(my_set)
java = {"유재석", "김태호", "양세형"}
python = set(["유재석", " 박명수"])
# 교집합 (java 와 phyton 을 모두 할 수 있는 개발자)
print(java & python)
print(java.intersection(python))
# 합집합 (java 도 할 수 있거나 python 할 수 있는 개발자)
print(java | python)
print(java.union(python))
# 차집합 (java 할 수 있지만 python은 할 줄 모르는 개발자)
print(java - python)
print(java.difference(python))
# python 할 줄 아는 사람이 늘어남
python.add("김태호")
print(python)
# java 를 잊어버림
java.remove("김태호")
print(java) |
d4a4f0d31e0ab45f9df48d71e1729ac8bb872655 | zhang435/Database | /assignment8/shortestCompletingWord.py | 1,676 | 3.609375 | 4 | import collections
class Solution:
# def shortestCompletingWord(self, licensePlate, words):
# """
# :type licensePlate: str
# :type words: List[str]
# :rtype: str
# """
# res = ""
# dic = collections.Counter(
# [i.lower() for i in licensePlate if i.lower() in "qwertyuioplkjhgfdsazxcvbnm"])
# for word in sorted(words, key=lambda x: len(x)):
# tmp = collections.Counter(
# [i.lower() for i in word if i.lower() in "qwertyuioplkjhgfdsazxcvbnm"])
# res = True
# for k, v in dict(dic).items():
# if k not in tmp or dic[k] > tmp[k]:
# res = False
# break
# if res:
# return word
def shortestCompletingWord(self, licensePlate, words):
prs = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43,
47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103]
alphs = "qwertyuioplkjhgfdsazxcvbnm"
self.pr_chars = dict(list(zip(alphs, prs)))
print(self.pr_chars)
num = self.prod_all(licensePlate)
length = float("inf")
res = ""
for word in words:
if self.prod_all(word) % num == 0 and len(word) < length:
length, res = len(word), word
return res
def prod_all(self, word):
res = 1
for w in word:
if w.isalpha():
res *= self.pr_chars[w.lower()]
return res
a = Solution()
res = a.shortestCompletingWord(licensePlate="1s3 PSt", words=[
"step",
"steps",
"stripe", "stepple"
])
print(res)
|
2115a8b09b09e5dbc3973af954568ce4f8337ee0 | mbhushan/python | /fn_local.py | 140 | 3.625 | 4 | x = 50
def func(x):
print 'current value of x: ', x
x=5
print 'value changed to: ', x
func(x)
print 'value of x is still: ',x
|
a0cbb2ca10dad0e5626a9bed52b9f070130d9ddd | kapc/problems | /Arrays/maximum_swap.py | 1,279 | 4.25 | 4 | #! /usr/env/python
"""
Maximum Swap
Difficulty:Medium
Given a non-negative integer, you could swap two digits at most once to get the maximum valued number. Return the maximum valued number you could get.
Example 1:
Input: 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Example 2:
Input: 9973
Output: 9973
Explanation: No swap.
Note:
The given number is in the range [0, 108]
"""
def maximum_swap(num):
"""
:type num: int
:rtype: int
"""
num_str = list(str(num))
start = 0
end = len(num_str) - 1
for i in range(0, len(num_str)):
digit1 = int(num_str[i])
digit2 = -1
index = -1
for j in range(i+1, len(num_str)):
if int(num_str[j]) >= digit2:
digit2 = int(num_str[j])
index = j
if digit1 < digit2:
tmp = num_str[i]
num_str[i] = num_str[index]
num_str[index] = tmp
return int("".join(num_str))
return int("".join(num_str))
def test_maximum_swap():
"""
:return:
"""
inputs = [99991, 2945, 10000, 19292, 0, 101921]
for i in inputs:
print maximum_swap(i)
test_maximum_swap() |
dea14f927da89441fabe3800f7d674adcc65420e | giometry/Data-Analysis-Snippets | /Obfuscation/obfuscation.py | 1,336 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Code to obfuscate dataframe
- Obfuscates numeric columns based on key
- Obfuscates column names
- Changes specified dataframe with obfuscated values
Created on 3/30/2021
@author: Giovanni R Budi
"""
from string import ascii_lowercase
import itertools
def obfuscate_numeric_values(dataframe, key):
"""
Obfuscates specified numeric columns in dataframe
Parameters
----------
dataframe : pandas dataframe
initial dataframe to obfuscate numeric values
key : pandas dataframe
dataframe that contains column names and key values to obfuscate initial dataframe values
"""
for col in key:
dataframe[col] = dataframe[col]/key[col].iloc[0]
def iter_all_strings():
"""
Creates an iterable of letters (a, b, c, ..., aa, ab, ..., aaa, etc.)
Yield
------
iterable
iterable of letters/strings
"""
for size in itertools.count(1):
for s in itertools.product(ascii_lowercase, repeat=size):
yield "".join(s)
def obfuscate_column_names(dataframe):
"""
Obfuscates column names in dataframe
Parameters
----------
dataframe : pandas dataframe
initial dataframe to obfuscate column names
"""
dataframe.columns = list(itertools.islice(iter_all_strings(), len(dataframe.columns)))
|
afee872e50b3918d15d0d542180bf36175564ef0 | RejaneCosta/Recuperacao02 | /soma/soma.py | 263 | 3.5625 | 4 | class Soma:
@staticmethod
def soma_numeros(numeros):
resultado = 0
for numero in numeros:
resultado = resultado + numero
return resultado
numeros = [1, 2 ,3, 4]
resultado = Soma.soma_numeros(numeros)
print(resultado)
|
f2f4d7e9c81141b3c5a1d053bc31f0c03787d546 | cafecinqsens/PY | /Chapter11_176_1.py | 600 | 3.96875 | 4 | import pandas as pd
data = {
'age': [23, 43, 12, 45],
'name':['민준', '현우', '서연', '동현'],
'height':[175.3, 180.3, 165.8, 172.7]
}
#사전형에 대해서는 학습하지 않았는데 리스트형과 거의 비슷함
# 따옴표에 있는 스트링은 일반적으로 'key'라고 하고 콜론(:) 다음에 나오는 리스트형의 데이터를 'value' 라고 함
x = pd.DataFrame(data, columns=['name', 'age', 'height'])
print(x)
'''
==결과값==
age name height
0 23 민준 175.3
1 43 현우 180.3
2 12 서연 165.8
3 45 동현 172.7
'''
|
baa7658ff220a20239c55c7157ff792b9c88eeb1 | aminhp93/python_fundamental | /names_part2.py | 749 | 3.53125 | 4 | def names(users):
j = 0
while j < len(users.values()):
arr1 = users.values()[j]
arr2 = users.keys()[j]
print arr2
k = 0
while k < len(arr1):
name = " ".join(arr1[k].values())
count = 0
for i in name:
if i != " ":
count += 1
print str(k+1) + " - " + name + " - " + str(count)
k += 1
j += 1
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name' : 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
names(users) |
95c8eb90a5c30642bb1ad30fadc6e78e8ddac566 | vickispark/pyBasics | /app5.py | 469 | 4.15625 | 4 | is_male = True
is_tall = False
if is_male:
print("you are a male")
else:
print("not a male")
if is_male and is_tall:
print("male or tall")
if is_tall:
print("tall")
if is_male:
print("male")
if is_male and is_tall:
print("both")
else:
print("either one")
elif is_tall and not is_male:
print("tall not male")
elif not(is_tall) and is_male:
print("male not tall")
else:
print("not both")
|
4eab69d9842dde85982e3d7c110934773594acf4 | pkhanna104/beta_single_unit | /un2key.py | 210 | 3.65625 | 4 |
def convert(unit):
if len(unit) == 2:
key = 'sig00'+unit
elif len(unit) == 3:
key = 'sig0'+unit
elif len(unit) == 4:
key = 'sig'+unit
else:
raise
return key |
2f89765e2046b8611441fc8a601c0b7a669c8eb5 | jimmybae/sw-expert-academy-python-code-problem | /Beginner/6220.py | 135 | 3.8125 | 4 | a = input()
if a.islower():
print("%s 는 소문자 입니다." % a)
elif a.isupper():
print("%s 는 대문자 입니다." % a) |
963b073fa116b599020ebd5d1dd2c4a7dea7683e | jsw13/Magical-Maze-Madness | /controllers/game_controller.py | 2,784 | 3.828125 | 4 | """ This module contains the GameController class """
import pygame
import pygame.locals
from views.game_view import GameView
class GameController:
""" Controller to handle the movement of the player. """
def __init__(self, maze, window, time):
""" Initializes private attributes.
Args:
maze (Maze): maze object
windoe: pygame display Surface object
"""
self._maze = maze
self._view = GameView(self._maze.maze, window)
self._time = time
def get_user_input(self):
""" Controller logic. Loops to get user input while game is not over. """
# Clock object to keep track of time
clock = pygame.time.Clock()
# Countdown timer
timer = self._time
dt = 0
direction = "down"
self._view.display_maze(self._time, direction)
pygame.key.set_repeat(150, 75)
state = "running"
while state == "running":
# Decrease timer
timer -= dt
dt = clock.tick(30)/1000
self._maze.open_exit()
for event in pygame.event.get():
if event.type == pygame.locals.QUIT:
state = False
elif event.type == pygame.locals.KEYDOWN:
if event.key in [pygame.locals.K_q, pygame.locals.K_ESCAPE]:
state = False
if event.key in [pygame.locals.K_w, pygame.locals.K_UP]:
direction = "up"
self._maze.move_player(-1, 0)
if event.key in [pygame.locals.K_a, pygame.locals.K_LEFT]:
direction ="left"
self._maze.move_player(0, -1)
if event.key in [pygame.locals.K_s, pygame.locals.K_DOWN]:
self._maze.move_player(1, 0)
direction = "down"
if event.key in [pygame.locals.K_d, pygame.locals.K_RIGHT]:
direction = "right"
self._maze.move_player(0, 1)
self._view.display_maze(timer, direction)
if self._maze.is_exit() or timer <= 0:
state = "finished"
self._time = timer
if self._time <= 0:
self._time = 0
return state
def check_score(self):
""" Get the score of the player. """
# If player reaches the exit before time expires
final_score = int((5 - self._maze.items_remaining())*(self._time)*(100))
score = (final_score, 5 - self._maze.items_remaining(), self._time)
return score
|
47fba521c87123d31d1ce695f5353848c9ac4365 | euzin4/gex003_algprog | /material/respostas_exercicios/lista3/exe7.py | 294 | 4.0625 | 4 | n1 = int(input("Digite o número 1: "))
maior = n1
menor = n1
n2 = int(input("Digite o número 2: "))
if n2 > maior:
maior = n2
if n2 < menor:
menor = n2
n3 = int(input("Digite o número 3: "))
if n3 > maior:
maior = n3
if n3 < menor:
menor = n3
print("Maior:", maior, "| Menor:", menor) |
b0ecc9803eb1a0f693530d10021f58425fbdd279 | lixiang2017/leetcode | /leetcode-cn/2331.0_Evaluate_Boolean_Binary_Tree.py | 673 | 4.03125 | 4 | '''
执行用时:56 ms, 在所有 Python3 提交中击败了79.52% 的用户
内存消耗:15.8 MB, 在所有 Python3 提交中击败了36.15% 的用户
通过测试用例:75 / 75
'''
# 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 evaluateTree(self, root: Optional[TreeNode]) -> bool:
if not root.left:
return root.val == 1
l = self.evaluateTree(root.left)
r = self.evaluateTree(root.right)
return l or r if root.val == 2 else l and r
|
d873c597bcdeaa09f6e26e7202c0f3d6da884ebb | ursstaud/PCC-Basics | /album.py | 563 | 4 | 4 | def make_album(artist_name, album_title, track_count = None):
"""Returns a dictionary describing an album"""
album = {'artist name': artist_name.title(), 'title': album_title.title()}
if track_count:
album['track_count'] = track_count
return album
beatles_info = make_album('the beatles', 'the white album')
print(beatles_info)
shlohmo_info = make_album('shlohmo', 'bad vibes')
print(shlohmo_info)
joji_info = make_album('joji','midsummer madness')
print(joji_info)
frank_info = make_album('frank ocean','blonde','10')
print(frank_info) |
c6503086d33d1d99122ed3fd6df2eaa06e7f934c | shuxiaokai/favv | /streamlit/app/app_car_accidents/app.py | 3,508 | 3.609375 | 4 | import streamlit as st
import pandas as pd
import numpy as np
import pydeck as pdk
import plotly.express as px
DATA_URL = "./app_car_accidents/Motor_Vehicle_Collisions_-_Crashes.csv"
@st.cache(persist=True)
def load_data(nrows):
data = pd.read_csv(DATA_URL, nrows=nrows, parse_dates=[['CRASH_DATE', 'CRASH_TIME']])
data.dropna(subset=['LATITUDE', 'LONGITUDE'], inplace=True)
lowercase = lambda x: str(x).lower()
data.rename(lowercase, axis='columns', inplace=True)
data.rename(columns={'crash_date_crash_time': 'date/time'}, inplace=True)
return data
def app_run():
st.title("Motor Vehicle Colllisions in NYC!")
st.markdown("This application is a Streamlit dashboard that can be used "
"to analyze motor vehicle collisions in NYC")
data = load_data(100000)
original_data = data
st.header("Where are the most people injured in NYC?")
injured_people = st.slider("Number of persons injured in vehicle collision", 0, 19, 3)
st.map(data.query("injured_persons >= @injured_people")[["latitude", "longitude"]].dropna(how="any"))
st.header("How many collisions occur during a given hour of the day")
# hour = st.selectbox("Hour to look at", range(0, 24), 1)
hour = st.slider("Hour to look at", 0, 23)
data = data[data['date/time'].dt.hour == hour]
st.markdown("Vehicle collissions between %i:00 and %i:00" % (hour, (hour + 1) %24))
midpoint = (np.average(data['latitude']), np.average(data['longitude']))
st.write(pdk.Deck(
map_style="mapbox://styles/mapbox/light-v9",
initial_view_state={
"latitude": midpoint[0],
"longitude": midpoint[1],
"zoom": 11,
"pitch": 50,
},
layers=[
pdk.Layer(
"HexagonLayer",
data=data[['date/time', 'latitude', 'longitude']],
get_position=['longitude', 'latitude'],
radius=100, # in meters
extruded=True,
pickable=True,
elevation_scale=4,
elevation_range=[0, 1000],
),
],
))
st.subheader("Breakdown by minute between %i:00 and %i:00" % (hour, (hour + 1) %24))
filtered = data[
(data['date/time'].dt.hour >= hour) & (data['date/time'].dt.hour < (hour + 1))
]
hist = np.histogram(filtered['date/time'].dt.minute, bins=60, range=(0, 60))[0]
chart_data = pd.DataFrame({'minute': range(60), 'crashes': hist})
fig = px.bar(chart_data, x='minute', y='crashes', hover_data=['minute', 'crashes'], height=400)
st.write(fig)
st.header("Top 5 dangerous streets by affected type")
select =st.selectbox("Affected type of people", ['Pedestrians', 'Cyclists', 'Motorists'])
top5=None
if select == 'Pedestrians':
top5 = original_data.query("injured_pedestrians >= 1")[["on_street_name", "injured_pedestrians"]].sort_values(by=['injured_pedestrians'], ascending=False).dropna(how='any')[:5]
elif select == 'Cyclists':
top5 = original_data.query("injured_cyclists >= 1")[["on_street_name", "injured_cyclists"]].sort_values(by=['injured_cyclists'], ascending=False).dropna(how='any')[:5]
else:
top5 = original_data.query("injured_motorists >= 1")[["on_street_name", "injured_motorists"]].sort_values(by=['injured_motorists'], ascending=False).dropna(how='any')[:5]
st.write(top5)
if st.checkbox("Show Raw Data", False):
st.subheader('Raw Data')
st.write(data) |
a71ad4149596f6cafcf29bcf06dffbea10d7bbe2 | orangeduice/cubesat_orbit | /cubsat3.py | 3,798 | 3.734375 | 4 | import sqlite3
from sqlite3 import Error
import requests
html = 'https://www.celestrak.com/NORAD/elements/cubesat.txt'
name = input("Enter Name: ")
DATA = ["","","","","","","","","","","","","","","","","","",""]
TLESIZE = [[0,23],[26,30],31,[33,34],[35,37],[38,40],[42,43],[44,55],[57,66],[68,75],[78,84],[88,91],[101,108],[110,117],[119,125],[127,134],[136,143],[145,155],[156,160]]
#conn = None
#conn = None
def create_connection(db_file):
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
##def create_db(db):
##
## """ create a database connection to a SQLite database """
## conn = None
## try:
## conn = sqlite3.connect(db)
## print(sqlite3.version)
## except Error as e:
## print(e)
## finally:
## if conn:
## conn.close()
def create_table(conn, create_table_sql):
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def insert_data(conn,a):
SN = a[0]
SCN = a[1]
C = a[2]
ID1 = a[3]
ID2 = a[4]
E1 = a[5]
E2 = a[6]
MM1 = a[7]
MM2 = a[8]
RPS = a[9]
ESN = a[10]
I = a[11]
RA = a[12]
E = a[13]
A = a[14]
MA = a[15]
MM = a[16]
R = a[17]
part = f"""INSERT INTO projects({SN},{SCN},{C},{ID1},{ID2},{E1},{E2},{MM1},{MM2},{RPS},{ESN},{I},{RA},{E},{A},{MA},{MM},{R}) VALUES(satellite_name,satellite_catalog_number,classification,International_Designator1,International_Designator2,Epoch1,Epoch2,Mean_motion1d,Mean_motion2d,RPS,Element_s3t_number,Inclination,R1ght_Ascension_0f_the_Ascending_Node,Eccentricity,Argument_0f_Perigee,Mean_Anomaly,Mean_Motion,Revolution_number_at_epoch);"""
print(part)
try:
c = conn.cursor()
c.execute(part)
except Error as e:
print(e)
def main():
database = "r"+input("enter directory: ")
#create_db(database)
#r"C:\sqlite\db\pythonsqlite.db"
table = """ CREATE TABLE IF NOT EXISTS projects (id integer PRIMARY KEY,
satellite_name text NOT NULL,
satellite_catalog_number integer,
classification text,
International_Designator1 integer,
International_Designator2 text,
Epoch1 integer,
Epoch2 decimal,
Mean_motion1d decimal,
Mean_motion2d decimal,
RPS decimal,
Element_s3t_number integer,
Inclination decimal,
R1ght_Ascension_0f_the_Ascending_Node decimal,
Eccentricity decimal,
Argument_0f_Perigee decimal,
Mean_Anomaly decimal,
Mean_Motion decimal,
Revolution_number_at_epoch integer
); """
#create_db(conn)
conn = create_connection(database)
if conn is not None:
create_table(conn, table)
else:
print("Error! cannot create the database connection.")
def fetch(html,name):
textTemp = ""
temp = ""
f= open("test.txt","w")
response = requests.get(html)
body2 = response.text
f.write(body2)
f.close()
f= open("test.txt","r")
printed = False
n = 0
for line in f:
if line.startswith(name):
printed = True
if printed and n<6:
n = n + 1
temp = line[:-1]
textTemp = textTemp + temp
print(line)
elif n<6:
printed = False
f.close()
a = 0
for i in range(0,19):
if (type(TLESIZE[i]) != int) :
DATA[i] = textTemp[TLESIZE[i][0] : TLESIZE[i][1]+1]
else:
DATA[i] = textTemp[TLESIZE[i]]
main()
database = "r"+input("enter directory: ")
conn = create_connection(database)
fetch(html,name)
insert_data(conn,DATA)
|
b5d6e17221eb7f62196a18fdbe0f92839c253a8b | symbolr/python | /demo/6.py | 101 | 3.5 | 4 | def fact(n):
if n==1:
return 1
return n*fact(n-1)
print(fact(1))
print(fact(5))
print(fact(100)) |
36af890a5e42ca1bfb1d165f02e8f2ede632f871 | J-Weaver0405/PingRequest | /exercise.py | 1,384 | 4.0625 | 4 | import random
import string
# uchars = uppercase
# lchars = lowercase
# dchars = digits
# schars = punctuation or special
def get_random_string(uchars = 2, lchars = 6, dchars = 1, schars = 1):
# Generates a 10 characters long random string
# with 3 upper case, 3 lowe case, 2 digits and 2 special characters
str_uchars, str_lchars, str_dchars, str_schars = '', '', '', ''
for i in range(uchars):
str_uchars += random.SystemRandom().choice(string.ascii_uppercase)
for i in range(lchars):
str_uchars += random.SystemRandom().choice(string.ascii_lowercase)
for i in range(dchars):
str_uchars += random.SystemRandom().choice(string.digits)
for i in range(schars):
str_uchars += random.SystemRandom().choice(string.punctuation)
random_str = str_uchars + str_lchars + str_dchars + str_schars
random_str = ''.join(random.sample(random_str, len(random_str)))
return random_str
print('Your Random String-1:', get_random_string())
def format_number(num):
if type(num) != int:
return 'you must enter a number'
elif num < 0:
return 'needs to be greater 0'
elif len(str(num)) < 3:
return num
num = str(num)
count = 0
for i in range(len(num)-1,0,-1):
count += 1
if count % 3 == 0:
num = num[:i] + ',' + num[i:]
return num
|
cc88b6a7b933aad1ae236bb3db78a6d51083d31f | Clair-s-Personal-REPL/GraphImplementation | /main.py | 9,471 | 4.34375 | 4 | # The main purpose of this application is to take in a graph, and to find a shortest path from one node to another node
# This program uses the pseudocode from this video: https://www.youtube.com/watch?v=oDqjPvD54Ss
# Had to make a few changes from the pseudocode since I am using an object here to implement the graph
# Instead of enqueue, it is put
# Instead of dequeue, it is get
# Instead of isEmpty, it is empty
from queue import Queue
import string
import random as rd
'''
graph_imp contains an adjacency list implemented as a dictionary, a number of nodes in the graph, and a queue that is only
to be used within the class. It currently contains functions that list all of the nodes and their adjacent nodes, functions
that can add and remove nodes inside the graph, and a function that finds the shortest path from one node to another node
input: graph - an adjacency dictionary that contains a node and a list of every node that is connected to it (default is
an empty dictionary)
output: None
'''
class graph_imp() :
def __init__(self, graph={}) :
self.graph = graph
self.num_nodes = len(graph)
self.to_traverse = Queue()
'''
list_all_nodes prints out all of the nodes that are inside the adjacency list
input: self
output: None
'''
def list_all_nodes(self):
for node in self.graph:
print(node, end = " ")
print()
'''
list_all_nodes_and_connections prints out all of the nodes that are inside the adjacency list, as well as all of the nodes that
they are adjacent to
input: self
output: None
'''
def list_all_nodes_and_connections(self):
for node in self.graph:
print("%s ->" % (node), end=" ")
for adjacents in self.graph[node]:
print("%s" % (adjacents), end=" ")
print()
'''
add_node adds a node and every node that is adjacent to it to the graph's adjacency list. Will update every other node in
the table that the new node connects to. If a node in the given adjacency list does not exist, then that node will be added
to the adjacency list as well. If the node exists and the adjacency list is different from the original adjacency list, the
adjacency list will be replaced, and any nodes that are not in the new list will lose their link to the original node. Any
node that is added will update the num_nodes variable as well.
input: self
node_name - the name of the node that is being added to the graph's adjacency list
node_adjacents - a list of all of the nodes that node_name is connected to
output: None
'''
def add_node(self, node_name, node_adjacents):
for node in self.graph:
if not self.graph[node]:
continue
if node_name not in self.graph:
continue
if node not in node_adjacents and node in self.graph[node_name]:
self.graph[node].remove(node_name)
if node_name not in self.graph:
self.num_nodes += 1
self.graph[node_name] = node_adjacents
for node in node_adjacents:
if node in self.graph:
if node_name not in self.graph[node]:
self.graph[node].append(node_name)
else:
self.graph[node] = [node_name]
self.num_nodes += 1
return
'''
remove_node removes a node from the adjacency graph, as well as removing every occurance of the node in the adjacency
lists of each other node.
input: self
node_name - the name of the node that is being removed from the list
output: None
'''
def remove_node(self, node_name):
del self.graph[node_name]
for node in self.graph:
if node_name in self.graph[node]:
self.graph[node].remove(node_name)
############################################################################################################################
'''
bfs_shortest_path uses breadth first search (bfs) to determine the shortest possible path between two different nodes
input: self
start_node - the starting node that is being traversed from
end_node - the ending node that is being traversed to
output: path - a list that contains the nodes from left to right to traverse through. If there is no path between the nodes,
the function returns an empty list.
'''
def bfs_shortest_path(self, start_node, end_node):
'''
solve uses a queue to determine the node that needs to be searched next. At the end, solve determines a path to each node
inside the adjacency list.
input: self
start_node - the starting node that is being traversed from
output: prev - a reverse list that contains a node and the node that points to it
'''
def solve(self, start_node):
self.to_traverse.put(start_node)
visited = {}
for node in self.graph:
visited[node] = False
visited[start_node] = True
prev = {}
for node in self.graph:
prev[node] = None
while(not self.to_traverse.empty()):
node = self.to_traverse.get()
neighbors = self.graph[node]
for nextt in neighbors:
if not visited[nextt]:
self.to_traverse.put(nextt)
visited[nextt] = True
prev[nextt] = node
return prev
'''
reconstruct_path builds a path using the end node, and goes up to the start_node.
input: self
start_node - the starting node that is being traversed from
end_node - the ending node that is being traversed to
prev - a reverse list that contains a node and the node that points to it
output: path - a list that contains the nodes from left to right to traverse through
'''
def reconstruct_path(self, start_node, end_node, prev):
path = []
at = end_node
while at != None:
path.append(at)
at = prev[at]
path.reverse()
if path[0] == start_node:
return path
return []
prev = solve(self, start_node)
path = reconstruct_path(self, start_node, end_node, prev)
return path
############################################################################################################################
'''
dfs_connected_nodes takes a node and determines which nodes that it can reach based off of the connections in the adjacency
list.
input: self
node_to_check - the node that is being checked for all nodes that it can reach
output: connected - nodes that the input node is connected to
'''
def dfs_connected_nodes(self, node_to_check):
visited = {}
connected = []
for key in self.graph:
visited[key] = False
'''
dfs takes a node and visits its next neighbor, if it is able, if it is unable to visit a node (one that is already visited), it will continue to look at its neighbors until they have all been visited, and goes back to the prior method called.
input: self
next_node - the node that is being visited
output: None
'''
def dfs(self, next_node):
visited[next_node] = True
for node in self.graph[next_node]:
if not visited[node]:
connected.append(node)
dfs(self, node)
dfs(self, node_to_check)
return connected
############################################################################################################################
'''
create_random_graph takes a graph object and populates it using a variable for the amount of times to loop through the
randomizer. The nodes correspond to a single uppercase letter in the English alphabet.
input: self
iterations - the number of times the loop should run
output: None
'''
def create_random_graph(self, iterations):
for i in range(0, iterations):
j = rd.randint(0, 25)
new_node = string.ascii_uppercase[j]
adjacent_list = []
for node in self.graph:
check = rd.randint(0, 2)
if check == 1:
adjacent_list.append(node)
self.add_node(new_node, adjacent_list)
'''
two_random_nodes takes a graph object and attempts to return two random nodes from the graph.
input: self
output: node1 - a node from the graph
node2 - a node from the graph
'''
def two_random_nodes(self):
listOfNodes = []
for nodes in self.graph:
listOfNodes.append(nodes)
return rd.choice(listOfNodes), rd.choice(listOfNodes)
############################################################################################################################
graph_object = graph_imp(graph={ "A": ["B", "C"],
"B": ["A", "G"],
"C": ["A", "D"],
"D": ["C", "H", "J"],
"E": ["F"],
"F": ["E", "I", "K"],
"G": ["B", "H"],
"H": ["D", "G"],
"I": ["F"],
"J": ["D"],
"K": ["F"]
})
graph_object.list_all_nodes_and_connections()
print(graph_object.dfs_connected_nodes("A"))
# graph_object = graph_imp()
# graph_object.create_random_graph(10)
# graph_object.list_all_nodes_and_connections()
# print(graph_object.num_nodes)
# start_node, end_node = graph_object.two_random_nodes()
# print("%s -> %s" % (start_node, end_node))
# path = graph_object.bfs_shortest_path(start_node, end_node)
# print(path)
# print(len(path) - 1)
|
cd79c28aaacf20d34a3c164ac1b7e471025f7a0f | 1huangjiehua/ArithmeticPracticalTraining | /201826404105黄杰华算法实训/任务一(二分查找(递归)).py | 716 | 3.578125 | 4 | def erfenfa(lis, left, right, num):
if left > right:#递归结束条件
return -1
mid = (left + right) // 2
if num < lis[mid]:
right = mid -1
elif num > lis[mid]:
left = mid + 1
else:
return mid
return erfenfa(lis, left, right, num)
#这里之所以会有return是因为必须要接收值,不然返回None
#回溯到最后一层的时候,如果没有return,那么将会返回None
lis = [15,58,68,94,12,45,35,36,14,54]
print(lis)
lis.sort()
print(lis)
while 1:
num = int(input('输入要查找的数:'))
res = erfenfa(lis, 0, len(lis)-1,num)
print(res)
if res == -1:
print('未找到!')
else:
print('找到!')
|
1c3758e6667396d7c9cf1814bfa313eebbf91e95 | ahtornado/study-python | /day11/class1.py | 1,140 | 4.375 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author :Alvin.Xie
# @Time :2017/11/6 22:41
# @File :class1.py
# 类定义
class People:
name = ''
age = 0
_weight = 0
_grade = 0
def __init__(self, n, a, w, g):
self.name = n
self.age = a
self._weight = w
self._grade = g
def speak(self):
print ("%s is speaking: I am %d years old" % (self.name, self.age))
p = People('tom', 10, 30, 1)
p.speak()
class Speaker():
topic = ''
name = ''
def __init__(self, n, t):
self.name = n
self.topic = t
def speak(self):
print ("I am %s,I am a speaker!My topic is %s" % (self.name, self.topic))
test = Speaker('Tim', 'Python')
test.speak()
# 多重继承
class Sample(Speaker, People):
a = ''
# _grade = 4
def __init__(self, n, a, w, g, t):
People.__init__(self, n, a, w, g)
Speaker.__init__(self, n, t)
print ("I am %s,I am %d years old,and I am %d, I am in grade %d and my topic is %s" % (self.name, self.age, self._weight, self._grade, self.topic))
test = Sample('Ken', 25, 80, 4, 'python')
|
a1793eec903a01aede99aba88db21680268661d1 | kishoraen1/kishore-python | /Coditional.py | 276 | 4.03125 | 4 | a = input("Enter First Number: ")
b = input("Enter Second Number: ")
while a is int and b is int:
if a == b:
print('Same Number')
elif a > b:
print ("Greater")
elif a < b:
print ("Smaller")
else:
print ("Something Wrong")
|
434416a3e86d7f1bd1a64f7d7716c26b9d3f585e | RamiJaloudi/Python-Scripts | /Good_Examples/Interest/scrape_read_csv_lines_str_object.py | 3,501 | 3.5625 | 4 | # Python_Page_Spider_Web_Crawler_Tutorial
# from https://www.youtube.com/watch?v=SFas42HBtMg&list=PLa1r6wjZwq-Bc6FFb9roP7AZgzDzIeI8D&index=3
# Spider algorithm.
# You need to EXECUTE the file in Shell, e.g. execfile("nytimes/scrape.py")
# First open cmd. Then cd C:\Users\Joh\Documents\Python Scripts\Web Crawler Projects\nytimes.
# Then enter Python Scrape.py
import urlparse
import urllib
#import urllib.request for Python3?
from bs4 import BeautifulSoup
import csv
import requests
import re
with open ("links.csv") as f:
f_csv = csv.reader(f)
#headers = next(f_csv)
for headers in f_csv:
#print headers
urls = headers
print type(urls)
urls = "http://www." + str(headers[0])
urls = urls.split()
visited = [urls]
#print urls
#print type(urls)
#print id(urls)
#print '\n'
while len(urls) >0:
try:
htmltext = urllib.urlopen(urls[0]).read()
#r = requests.get(urls[])
#urls.pop(0)
except:
print urls[0]
#print 'Exception'
soup = BeautifulSoup(htmltext)
regex = '<title>(.+?)</title>'
pattern = re.compile(regex)
titles = re.findall(pattern,htmltext)
#urls.pop(0)
## print headers
## print "STARTS HERE: \n"
## print "\n" + "\n"
## print soup.findAll('a', href=True)
##
## print "\n\n\n"
items = soup.findAll('a', href=True)
items2 = "STARTS HERE: " + '\n' + str(items)
saveFile = open ('crawl_findall.txt','a')
saveFile.write(str(urls)+ '\n')
#saveFile.write(str(titles))
#saveFile.write(str(items2))
#saveFile.close()
#saveFile = open ('crawl_findall.txt','a')
#saveFile.write(str(urls))
saveFile.write(str(titles)+ '\n')
#saveFile.write(str(items2))
#saveFile.close()
#saveFile = open ('crawl_findall.txt','a')
#saveFile.write(str(urls))
#saveFile.write(str(titles))
saveFile.write(str(items2) + '\n\n\n')
saveFile.close()
print str(urls[0])
print str(titles)
print str(items2)
print '\n\n\n'
#print items2
urls.pop(0)
'''
for tag in soup.findAll('a', href=True):
# print tag
# print tag['href'] # is you just want to print href
tag['href'] = urlparse.urljoin(url,tag['href'])
#print tag['href']
if url in tag['href'] and tag['href'] not in visited:
urls.append(tag['href'])
visited.append(tag['href']) # historical record, whereas above line is temporary stack or queue.
print visited
'''
|
d194fde701f467e04018b42b607a16765ab04df7 | philhoel/MiniGames | /Python/rps.py | 1,272 | 3.9375 | 4 | import random
c = "sad"
print(c.capitalize())
def cpu():
a = random.randint(1,4)
if a == 1:
return "Rock"
elif a == 2:
return "Paper"
else:
return "Scissors"
def player():
b = input("Enter Rock, Paper or Scissors: ")
#print(b.capitalize())
if (b.capitalize() != "Rock" and b.capitalize() != "Paper" and b.capitalize() != "Scissors"):
print("Needs to be rock, paper or scissors")
player()
else:
return b.capitalize()
print("Rock!")
print("Paper!")
print("Scissors!")
p = player()
cpu = cpu()
if cpu == p:
print(f"CPU: {cpu} || Player: {p}")
print("Its a tie")
elif cpu == "Rock" and p == "Paper":
print(f"CPU: {cpu} || Player: {p}")
print("You Win!")
elif cpu == "Scissors" and p == "Paper":
print(f"CPU: {cpu} || Player: {p}")
print("You Loose!")
elif cpu == "Paper" and p == "Rock":
print(f"CPU: {cpu} || Player: {p}")
print("You Loose!")
elif cpu == "Paper" and p == "Scissors":
print(f"CPU: {cpu} || Player: {p}")
print("You Win!")
elif cpu == "Scissors" and p == "Rock":
print(f"CPU: {cpu} || Player: {p}")
print("You Win!")
elif cpu == "Rock" and p == "Scissors":
print(f"CPU: {cpu} || Player: {p}")
print("You Loose!") |
cbc74d74d852d3eb35f90075180374acb092aa4f | it-college-n1915/cheatseat | /script/time.py | 427 | 3.890625 | 4 | #!/usr/bin/python
import time
seconds = int(input("何秒測りますか?分で測りたいときは:0 "))
if seconds == 0:
minute = int(input("何分測りますか? "))
count = minute * 60
for i in range(count):
print(count)
count -= 1
time.sleep(1)
else:
for i in range(seconds):
print(seconds)
seconds -= 1
time.sleep(1)
print("タイマー終了")
|
7a7b0044722db4ed830bd82877d2d068c1ce2f65 | fm75/performance | /cpu.py | 537 | 3.625 | 4 | #! /usr/bin/python3
import timeit
def wrapper(func, *args, **kwargs):
def wrapped():
return func(*args, **kwargs)
return wrapped
def doitn(n):
t = 0
for i in range(n + 1):
t += i
return t
def doit():
experiments = [1000, 10000, 100000, 1000000]
funcs = list()
for n in experiments:
funcs.append((n, (wrapper(doitn, n))))
for (n, func) in funcs:
print ('{:>8} {}'.format(n, min(timeit.repeat(func, repeat=2, number=3))))
if __name__ == '__main__':
doit();
|
e22aeffb0dcfbb95a00468eda8f664c9aab79bc3 | Farzana0627/Python-Practice | /Array_List/array1.py | 409 | 3.90625 | 4 | from array import *
print("Insertion")
array1 = array('i', [10,20,30,40,50])
array1.insert(2,60)
for x in array1:
print(x)
print("Deletion")
array1 = array('i', [10,20,30,40,50])
array1.remove(40)
for x in array1:
print(x)
print("Search")
array1 = array('i', [10,20,30,40,50])
print (array1.index(40))
print("Update")
array1 = array('i', [10,20,30,40,50])
array1[2] = 80
for x in array1:
print(x) |
67be17d583975e2ea74c0205b66ebf7593243cfd | DRTeam35/HereWeGo | /2019-2020/Tests/Motors and Camera/Camera_VideoStream_Image_Save.py | 1,669 | 3.71875 | 4 | # Python program to save a
# video using Test-OpenCV
import cv2
import os
# Create an object to read
# from camera
video = cv2.VideoCapture(0)
# We need to check if camera
# is opened previously or not
if (video.isOpened() == False):
print("Error reading video file")
# We need to set resolutions.
# so, convert them from float to integer.
frame_width = int(video.get(3))
frame_height = int(video.get(4))
size = (frame_width, frame_height)
# Below VideoWriter object will create
# a frame of above defined The output
# is stored in 'filename.avi' file.
#result = cv2.VideoWriter('filename.avi', cv2.VideoWriter_fourcc(*'MJPG'), 10, size)
path = ('/home/pi/Desktop/Videos/video_deneme.avi')
result = cv2.VideoWriter(path, cv2.VideoWriter_fourcc(*'MJPG'), 10, size)
ph = 1
while (True):
ret, frame = video.read()
frame = cv2.flip(frame, 1)
ssssssssssss frame = cv2.flip(frame, 0)
if ret == True:
# Write the frame into the
# file 'filename.avi'
result.write(frame)
# Display the frame
# saved in the file
cv2.imshow('Frame', frame)
# Press S on keyboard
# to stop the process
if cv2.waitKey(1) & 0xFF == ord('s'):
break
if cv2.waitKey(1) & 0xFF == ord('p'):
cv2.imwrite(os.path.join('/home/pi/Desktop/Images', 'image%s.jpg' % ph), frame)
ph += 1
print("Image saved")
# Break the loop
else:
break
# When everything done, release
# the video capture and video
# write objects
video.release()
result.release()
# Closes all the frames
cv2.destroyAllWindows()
print("The video was successfully saved") |
07e3a3644aa3f1de90e913b8171aea6af3b156ef | DeanHe/Practice | /LeetCodePython/AddTwoNumbersII.py | 1,632 | 4.03125 | 4 | """
You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example 1:
Input: l1 = [7,2,4,3], l2 = [5,6,4]
Output: [7,8,0,7]
Example 2:
Input: l1 = [2,4,3], l2 = [5,6,4]
Output: [8,0,7]
Example 3:
Input: l1 = [0], l2 = [0]
Output: [0]
Constraints:
The number of nodes in each linked list is in the range [1, 100].
0 <= Node.val <= 9
It is guaranteed that the list represents a number that does not have leading zeros.
Follow up: Could you solve it without reversing the input lists?
"""
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class AddTwoNumbersII:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
stack1, stack2 = [], []
while l1:
stack1.append(l1.val)
l1 = l1.next
while l2:
stack2.append(l2.val)
l2 = l2.next
dummy, carry = ListNode(), 0
while stack1 or stack2 or carry > 0:
sum = 0
if stack1:
sum += stack1.pop()
if stack2:
sum += stack2.pop()
if carry > 0:
sum += carry
carry = sum // 10
cur = ListNode(sum % 10)
cur.next = dummy.next
dummy.next = cur
return dummy.next
|
8998a671e75cd11d0063e4285f0b980411132128 | ryanpennings/workshop_swinburne_2021 | /examples/118_euler_angles.py | 699 | 4 | 4 | """Example: Rotations from euler angles, rotate an object based on 3 euler angles.
"""
from compas.geometry import Rotation
# euler angles
alpha, beta, gamma = -0.156, -0.274, 0.785
static, axes = True, 'xyz'
# Version 1: Create Rotation from angles
R1 = Rotation.from_euler_angles([alpha, beta, gamma], static, axes)
# Version 2: Concatenate 3 Rotations
xaxis, yaxis, zaxis = [1, 0, 0], [0, 1, 0], [0, 0, 1]
Rx = Rotation.from_axis_and_angle(xaxis, alpha)
Ry = Rotation.from_axis_and_angle(yaxis, beta)
Rz = Rotation.from_axis_and_angle(zaxis, gamma)
if static: # check difference between pre- and post-concatenation!
R2 = Rz * Ry * Rx
else:
R2 = Rx * Ry * Rz
# Check
print(R1 == R2)
|
b27c9aafd48cc36d2e40359e79b3dc0f953bca06 | georgeallbert/git-projetos | /Programas python ~ George Albert/078.py | 574 | 3.84375 | 4 | from time import sleep
print('\033[1;32m='*50)
print(f'{"NÚMEROS DIGITADOS":^50}')
print('='*50)
overflow = list()
for c in range(0,5):
overflow.append(int(input('\nDigite um número: ')))
sleep(1)
print('\033[1;33m='*50)
print(f'{"POSICÕESE E VALORES":^50}')
print('='*50)
for p, n in enumerate(overflow):
print(f'\nNa posição {p} está o valor {n}')
sleep(2)
print('\033[1;35m='*50)
print(f'{"MAIOR E MENOR":^50}')
print('='*50)
print(f'\nO maior número digitado foi {max(overflow)}')
sleep(1)
print(f'\nO menor número digitado foi {min(overflow)}')
|
f33495a88704ae07b8bce6cb4c8447aa24c65115 | viiicky/Problem-Solving | /LeetCode/1688.Count_of_Matches_in_Tournament.py | 584 | 3.6875 | 4 | import unittest
class Solution:
def numberOfMatches(self, n: int) -> int:
total_matches_played = 0
teams_advanced = n
while teams_advanced > 1:
matches_played = teams_advanced // 2
total_matches_played += matches_played
teams_advanced = matches_played + (teams_advanced % 2)
return total_matches_played
class SolutionTest(unittest.TestCase):
def test_number_of_matches(self):
sol = Solution()
self.assertEqual(sol.numberOfMatches(7), 6)
if __name__ == '__main__':
unittest.main()
|
fb55d0661eecf4d2f1d773a83f8751a2b85f9cdb | Nora-Wang/Leetcode_python3 | /None Algorithm/415. Add Strings.py | 1,017 | 3.71875 | 4 | Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
# time: O(n + m), space: O(n + m)
# n = len(num1), m = len(num2)
class Solution:
def addStrings(self, num1: str, num2: str) -> str:
res = []
index1 = len(num1) - 1
index2 = len(num2) - 1
curt = 0
while index1 >= 0 or index2 >= 0:
if index1 >= 0:
curt += int(num1[index1])
index1 -= 1
if index2 >= 0:
curt += int(num2[index2])
index2 -= 1
res.append(str(curt % 10))
curt //= 10
if curt:
res.append(str(curt))
return ''.join(reversed(res))
|
afcf06341e131c94cbb2f90bcfbb33f6b9b718a4 | brijesh-989/ITW-lab-1 | /Assignment 4/10.py | 265 | 4 | 4 | user_in=input("enter a string : ")
count=0
cint=0
for i in user_in:
if i.isupper() == True:
count+=1
elif i.islower() == True:
cint+=1
print(f"No of upper case characters are : {count}")
print(f"No of upper lower characters are : {cint}") |
f3c96c97e12fc5526394ab01220ec152e0406839 | ArunRamachandran/ThinkPython-Solutions | /Chapter5/simple_recursion.py | 149 | 3.78125 | 4 | # attempt to implement a simple recursion fn
def count_down(n):
if n <= 0:
print "Blastoff !"
else:
print n
count_down(n-1)
count_down(5)
|
4275d941634a6254ab7579a07920dbb5c3ed5eef | mohanalearncoding/Leetcodepython | /basball.py | 505 | 3.5625 | 4 | from typing import List
def calPoints( ops: List[str]) -> int:
arr=[]
s1=0
for i in range(len(ops)):
if ops[i]=='C':
arr.pop()
elif ops[i]=='D':
s1=int(arr[-1])*2
#print(s1,"s1")
arr.append(s1)
elif ops[i]=='+':
s1=int(arr[-1])+int(arr[-2])
arr.append(s1)
else:
arr.append(int(ops[i]))
#print(arr)
return sum(arr)
print(calPoints(["1"])) |
04f2430b75a0d7cfac88f04997bbcf34a4b38044 | sftth/portfolio | /language/python/path/5_get_file_extesion.py | 235 | 3.84375 | 4 | # reference: https://www.geeksforgeeks.org/how-to-get-file-extension-in-python/
import pathlib
# function to return the file extension
file_extension = pathlib.Path('my_file.txt').suffix
print("File Extension: ", file_extension) |
6e33df1d99ff6b74ea342e0d0441e2b6ccc2f4d8 | Benji-Huang/midnight-rider | /main.py | 7,439 | 3.5 | 4 | # main.py
# Midnight Rider
# A text-based adventure game
import random
import sys
import textwrap
import time
INTRODUCTION = """
WELCOME TO MIDNIGHT RIDER.
WE'VE STOLEN A CAR, WE NEED TO GET IT HOME.
THE CAR IS SPECIAL.
WE CAN'T LET THEM HAVE IT.
ONE GOAL: SURVIVAL... AND THE CAR.
REACH THE END BEFORE THE MEN GON GETCHU.
"""
WIN = """
YOU PRESSED THE BUTTON TO OPEN THE GATE.
THIS ISN'T THE FIRST TIME YOU'VE DONE THIS.
YOU CAN TIME IT PERFECTLY SO THAT YOU
SLIDE THE CAR IN AS THE GATES CLOSE.
YOU KNOW YOU DID THE RIGHT THING.
THE GOVERNMENT WOULD HAVE TORN THE CAR APART,
ANALYSING IT, TESTING IT, THEN DESTROYING IT.
THEY DON'T KNOW ITS SECRETS...
THAT IT HOLDS THE KEY TO DIFFERENT WORLDS.
AS YOU STEP OUT OF THE VEHICLE, FIDO RUNS
UP TO YOU.
"THANK YOU FOR SAVING ME," HE SAYS.
AS YOU TAKE A COUPLE OF STEPS AWAY FROM THE CAR,
IT MAKES A STRANGE NOISE.
BEFORE YOUR EYES, IT SHIFTS ITS SHAPE.
YOU'VE SEEN IT BEFORE, BUT ONLY ON TV.
"BUMBLEBEE...?"
----GAME OVER----
"""
LOSE_HUNGER = """
YOU SUCCUMBED TO YOUR HUNGER AND CANNOT CONTINUE.
THE FLASHING RED AND BLUE LIGHTS GET CLOSER AND
CLOSER AS YOU FADE IN AND OUT OF CONSCIOUSNESS.
THE END IS NEAR.
----GAME OVER----
"""
LOSE_AGENTS = """
THE AGENTS HAVE CLOSED IN ON YOU.
THERE ARE AT LEAST 20 CARS SURROUNDING YOU.
THE LEAD CAR BUMPS YOUR PASSENGER SIDE.
YOU MANAGE TO CORRECT YOUR STEERING
TO KEEP YOU FROM CRASHING.
YOU DIDN'T SEE THE AGENT'S CAR BESIDE YOU.
THE DRIVER BUMPS YOUR CAR.
AND THAT'S IT.
YOU SPIN UNCONTROLLABLY.
THE CAR FLIPS OVER AT LEAST TWO TIMES.
OR MORE... YOU SEEM TO HAVE LOST COUNT.
SIRENS.
"ARE THEY ALIVE?" THEY SAY AS YOU HEAR
FOOTSTEPS GETTING CLOSER.
"DOESN'T MATTER, ALL WE WANTED WAS THE CAR.
YOU SEE A DOG SLOWLY STEP OUT OF THE
OVERTURNED CAR.
"YOU WILL NEVER STOP THE REVOLUTION,"
THE DOG SEEMS TO SAY TO THE OFFICERS.
IT WAS IN THE CAR THE WHOLE TIME.
YOU DRIFT OFF INTO UNCONSCIOUSNESS.
----GAME OVER----
"""
LOSE_FUEL = """
YOUR CAR SPUTTERS AND SEEMS TO LET OUT
A BIG SIGH. THERE'S NO MORE FUEL LEFT.
THE COPS SURROUND YOU AND THEY STEP
OUT OF THEIR CARS. THE LEAD AGENT
RIPS THE DOOR OPEN AND THROWS YOU
OUT OF THE CAR.
"WE FINALLY GOT IT"
YOU FAILED.
----GAME OVER----
"""
CHOICES = """
----
A. EAT A PIECE OF TOFU
B. DRIVE AT A MODERATE SPEED
C. DRIVE FULL THROTTLE
D. STOP TO REFUEL (NO FOOD AVAILABLE)
E. STATUS CHECK
Q. QUIT
----
"""
def type_text_output(string):
for char in textwrap.dedent(string):
time.sleep(0.05)
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(1)
def main():
type_text_output(INTRODUCTION)
# CONSTANTS
MAX_FUEL_LEVEL = 50
MAX_DISTANCE_TRAVELLED = 100
MAX_TOFU = 3
MAX_HUNGER = 50
STARTING_AGENTS_DISTANCE = -20
# Variables
done = False
kms_travelled = 0
agents_distance = STARTING_AGENTS_DISTANCE
turns = 0
tofu = MAX_TOFU
fuel = MAX_FUEL_LEVEL
hunger = 0
#MAIN LOOP
while not done:
# Random events
# FIDO - refills your food (5%)
if tofu < 3 and random.random() < 0.05:
# Refill tofu
tofu = MAX_TOFU
# Player feedback
print("******** You look at your tofu container.")
print("******** It is filled magically.")
print("******** \"You're welcome\", says a small voice.")
print("******** The dog used its magic tofu cooking skills.")
# Check if reached END GAME
# WIN - Travelled the distance required
# Print win scenario
if kms_travelled > MAX_DISTANCE_TRAVELLED:
time.sleep(2)
type_text_output(WIN)
break
# LOSE - by hunger > MAX_HUNGER (50)
elif hunger > MAX_HUNGER:
time.sleep(2)
type_text_output(LOSE_HUNGER)
break
# LOSE - agents reach you
elif agents_distance >= 0:
time.sleep(2)
type_text_output(LOSE_AGENTS)
break
# LOSE - no fuel
elif fuel <= 0:
time.sleep(2)
type_text_output(LOSE_FUEL)
break
# Display hunger
if hunger > 33:
print("******** Your stomach rumbles, you need to eat something soon.")
time.sleep(1)
elif hunger > 20:
print("******** Your hunger is small, but manageable.")
time.sleep(1)
# Display the user their choices
print(CHOICES)
user_choice = input("WHAT DO YOU WANT TO DO?\n").lower().strip("!?,.")
if user_choice == "a":
# Eat/Hunger
if tofu > 0:
tofu -= 1
hunger = 0
print()
print("-------- Mmmmmmm, soybean goodness.")
print("YOUR HUNGER IS SATED")
print()
else:
print()
print("-------- YOU DON'T HAVE ANY TOFU")
print()
elif user_choice == "b":
# Moderate speed
player_distance_now = random.randrange(4, 12)
agents_distance_now = random.randrange(7, 15)
# Burn fuel
fuel -= random.randrange(3, 7)
# Player distance travelled
kms_travelled += player_distance_now
# Agent distance travelled
agents_distance -= player_distance_now - agents_distance_now
# Feedback to player
print()
print(f"-------- YOU TRAVELED {player_distance_now} KM.")
print()
elif user_choice == "c":
# FAST
player_distance_now = random.randrange(9, 16)
agents_distance_now = random.randrange(7, 15)
# Burn fuel
fuel -= random.randrange(7, 11)
# Player distance travelled
kms_travelled += player_distance_now
# Agent distance travelled
agents_distance -= player_distance_now - agents_distance_now
# Feedback to player
print()
print("ZOOOOOOOOM")
print(f"-------- YOU TRAVELED {player_distance_now} KM.")
print()
elif user_choice == "d":
# Refueling
# Fill up the fuel tank
fuel = MAX_FUEL_LEVEL
# Consider the agents coming closer
agents_distance += random.randrange(7, 15)
# Give player feedback
print()
print("-------- YOU FILLED THE FUEL TANK")
print("-------- THE AGENTS GOT CLOSER...")
print()
elif user_choice == "e":
# Display status of game
print(f"\t---STATUS CHECK---")
print(f"\tKM TRAVELLED: {kms_travelled}")
print(f"\tFUEL REMAINING: {fuel} L")
print(f"\tAGENTS ARE {abs(agents_distance)} KM BEHIND")
print(f"\tYOU HAVE {tofu} TOFU LEFT")
print(f"\t--------\n")
elif user_choice == "q":
done = True
else:
print("\tPlease select a valid input")
# UPKEEP
if user_choice in ["b", "c", "d"]:
hunger += random.randrange(8, 18)
turns += 1
time.sleep(1.5)
# Outro
print()
print(f"You finished the game in {turns} turns.")
print("Thanks for playing. Hope to see you again soon")
if __name__ == "__main__":
main() |
bbbaa7c0d8dd42ec802f72c2a07b7fdd908815ba | MANISH762000/Hacktoberfest-2021 | /Python Library/Pandas/indexing,selecting.py | 1,211 | 4.25 | 4 | import pandas as pd
Data = pd.read_csv('train.csv')
# The Native way
#it actually offers quite simple ways
#like if want to select a column(Fare)
print(Data.Fare.head()) # or Data["Fare"]
#if i want to be more specific
print(Data.Fare[0]) # or Data["Fare"][0]
#### INDEXING IN PANDAS ####
#1- Index Based Selection
#Using iloc()
print(Data.iloc[0]) #Returns the first row
### in native python it's column first and row second, but here it's vice versa
print(Data.iloc[:, 1])
print(Data.iloc[1:3, 1])
print(Data.iloc[[0, 1, 2], 1])
print(Data.iloc[-5:])
#2- Label-Based Selection
#Using loc()
print(Data.loc[0, "Fare"])
print(Data.loc[1:3, "Survived"])
print(Data.loc[:, ["Fare", "Age", "Sex"]])
#### MANIPULATING INDEXES
print(Data.set_index("Name"))
#### CONDITIONAL SELECTION
print(Data.Survived == 1)
print(Data.loc[Data.Survived == 1])
print(Data.loc[(Data.Survived == 1) & (Data.Sex == "female")])
print(Data.loc[(Data.Survived == 1) | (Data.Sex == "female")])
print(Data.loc[Data.Embarked.isin(["S", "C"])])
print(Data.Age.notnull())
#### ASSINGING DATA
Data['critic'] = 'everyone'
print(Data['critic'])
Data['reverse_indexing'] = range(len(Data), 0, -1)
print(Data["reverse_indexing"]) |
21f3daa1b4b2f773c98e6b3912e2fef91fc7882c | jeremytrindade/python-brothers | /PyCharm/CursoemVideo/desafio004.py | 244 | 3.734375 | 4 | n = input('digite algo: ')
print(type(n))
print('é um valor numerico? ', n.isnumeric())
print('é um valor alphanumerico? ', n.isalnum())
print('é um valor alpha? ', n.isalpha())
print('é um valor alpha em letras maiusculas? ', n.isupper())
|
d7f97fbffe64b6b7fd9d5304e22f23e8c0ce52ba | dermoth/AdventOfCode2017 | /Day3/Day3.py | 2,204 | 4.09375 | 4 | #!/usr/bin/env python3
import math
# Given an array of height n:
# 1. For odd n, the distance from 1 for n**2 can be calculated
# as (n/2, -n/2)
# 2. For even n, the distance from 2 for n**2 can be calculated
# as (-n/2, n/2)
#100 91
# 64 63 62 61 60 59 58 57
# 37 36 35 34 33 32 31 56
# 38 17 16 15 14 13 30 55
# 39 18 5 4 3 12 29 54
# 40 19 6 1 2 11 28 53
# 41 20 7 8 9 10 27 52
# 42 21 22 23 24 25 26 51
# 43 44 45 46 47 48 49 50
#109 81 82
def dist(number):
"""Find the distance from 1 to number"""
# Find the closest cartesian number to calculate distance from
# We have two candidated around sqrt(number)
low = int(math.sqrt(number))
high = low + 1
delta1 = abs(low ** 2 - number)
delta2 = abs(high ** 2 - number)
#print(number, low, high, delta1, delta2)
if delta1 <= delta2:
coord = getcoord(low, number)
else:
coord = getcoord(high, number)
# Distance to origin is sum of absolute coordinates
return abs(coord[0]) + abs(coord[1])
def getcoord(height, number):
"Get coordinates for number with closest height"
base = int(height / 2)
# Calculate using height, but add one to get to the next edge
# This simplifies calculating from higher number
ref = height ** 2 + 1
if height % 2:
# Odd, and extend to the right
coord = (base + 1, base * -1)
if number > ref:
# add delta to y
coord = coord[0], coord[1] + number - ref
elif number < ref:
# subtract delta from x
coord = coord[0] - ref + number, coord[1]
else:
# Even, and extend to the right (NB: from 2, so x + 1 - 1)
coord = (base * -1, base)
if number > ref:
# subtract delta from y
coord = coord[0], coord[1] - number + ref
elif number < ref:
# add delta to x
coord = coord[0] + ref - number, coord[1]
#print(number, height, ref, base, height, coord)
return coord
#print(dist(1))
#print(dist(12))
#print(dist(23))
#print(dist(44))
#print(dist(99))
#print(dist(1024))
print(dist(325489))
|
98f10244cd39f97e3257d05a09a39e49ece0bc7e | letrout/music | /lib/scale.py | 6,827 | 3.78125 | 4 | """
scale.py
A class to hold a collection of tones defined as a scale
(ie all tones within an octave range).
The scale is defined by relative distances between each of the tones and the
root.
The base structure of the scale is provided by degree_tones. This is a
dictionary of degree: tone, where 'degree' is the degree of the scale
(with the root being 1) and 'tone' is the number of cents above the root for
the degree.
"""
__author__ = "Joel Luth"
__copyright__ = "Copyright 2020, Joel Luth"
__credits__ = ["Joel Luth"]
__license__ = "MIT"
__maintainer__ = "Joel Luth"
__email__ = "[email protected]"
__status__ = "Prototype"
import lib.note as note
MIN_CENTS = 0
class Scale(object):
"""
Class to hold a musical scale
"""
def __init__(self, root_note=None, tones=None):
"""
Constructor
:param root_note: Note object, root note for the scale (default None)
:param tones: List of tones, each tone the number of cents above root
"""
# First degree is always the root
self.__degree_tones = {1: 0}
self.__root_note = None
self.root_note = root_note
if tones is not None and isinstance(tones, (list,)):
try:
for tone in sorted(tones):
self.add_tone(tone)
except TypeError:
pass
@property
def degree_tones(self):
"""
getter for __degree_tones
:return: dict of degree->tone, where tone is cents above root
"""
return self.__degree_tones
@property
def degrees(self):
"""
The degrees of the scale
:return: A sorted list of the scale degrees
"""
return sorted(list(self.degree_tones.keys()))
@property
def tones(self):
"""
Get the tones of the scale, in cents above root
:return: A sorted list of tones in the scale
"""
return sorted(list(self.degree_tones.values()))
@property
def degree_steps_cents(self):
"""
Get the steps of every degree (to the previous), in cents
:return: dict of degree->cents to previous degree
"""
steps = dict()
for degree, cents in self.degree_tones.items():
if degree == 1:
steps[1] = 0
else:
steps[degree] = cents - self.degree_tones[degree - 1]
return steps
def add_tone(self, cents):
"""
Add a tone to the scale
:param cents: difference from scale root, in cents
:return: new degree of the tone in the scale
None if invalid cents value
-1 if tone already exists in the scale
"""
my_tones = self.tones
new_degree = None
try:
float(cents)
except ValueError:
return None
if cents < MIN_CENTS:
return None
if cents in my_tones:
return -1
# new_position = bisect.bisect(self.tones, cents)
# bisect.insort(self.__tones, cents)
my_tones.append(cents)
# Rebuild self.__degrees dictionary
i = 1
self.__degree_tones = dict()
for tone in sorted(my_tones):
self.__degree_tones[i] = tone
if tone == cents:
new_degree = i
i += 1
return new_degree
def add_tone_rel_degree(self, degree, cents):
"""
Add a tone relative to an existing degree,
by the number of cents above the existing degree
(cents can be negative to insert below the degree)
:param degree: existing degree of the scale
:param cents: number of cents above the existing degree for new tone
(can be negative to insert a tone below an existing degree)
:return: the degree of the inserted tone, -1 if error
"""
new_degree = None
if degree not in self.degrees:
return -1
new_degree = self.add_tone(self.degree_tones[degree] + cents)
return new_degree
def move_degree(self, degree, cents):
"""
Move (retune) a degree by cents
:param degree: the scale degree to retune
:param cents: the number of cents by which to change the tone
(can be negative)
:return: 0 on success, -1 on error
"""
if degree == 1:
# can't remove the root
return -1
cur_deg_tones = self.degree_tones.copy()
try:
del self.__degree_tones[degree]
except KeyError:
return -1
new_cents = cur_deg_tones[degree] + cents
new_degree = self.add_tone(new_cents)
if new_degree is None or new_degree == -1:
# Re-tuned tone doesn't fit our scale constraints?
# reset degree_tones and return error
# FIXME: -1 means tone re-tuned to an existing tone, maybe that's ok?
self.__degree_tones = cur_deg_tones
return -1
return 0
def remove_degree(self, degree):
"""
Remove a scale degree
:param degree:
:return: 0 on success, -1 on error
"""
try:
del self.__degree_tones[degree]
except KeyError:
return -1
new_tones = self.tones
# Rebuild degree_tones
self.__degree_tones = dict()
for tone in new_tones:
self.add_tone(tone)
return 0
@property
def root_note(self):
"""
getter for self.__root_note
:return: self.__root_note
"""
return self.__root_note
@root_note.setter
def root_note(self, new_root):
"""
Sets a new root note for the scale
:param new_root: note.Note object or int (Hz)
:return: freq_ratio, the ratio of new root to the previous root
(None if no previous root)
"""
freq_ratio = None
if isinstance(new_root, note.Note):
freq_ratio = self.freq_ratio(new_root.freq)
self.__root_note = new_root
elif isinstance(new_root, int):
new_root_note = note.Note(new_root)
freq_ratio = self.freq_ratio(new_root_note.freq)
self.__root_note = new_root_note
return freq_ratio
def freq_ratio(self, new_freq):
"""
Calculate the ratio of some frequency to our root note
(does not change our current root note)
:param new_freq: the new frequency to compare (Hz)
:return: ratio of new frequency / our root
None if we don't currently have a root note frequency
"""
freq_ratio = None
if self.root_note is not None and self.root_note.freq:
freq_ratio = new_freq / self.root_note.freq
return freq_ratio
|
b053eb9dade4350e346c3c3198bd3708a62fb0e3 | page2me/Advent-of-Code-2021 | /Day-5/binary_boarding.py | 1,003 | 3.75 | 4 | #!/usr/bin/env python3
# Advent of Code 2020 Solution - Python
def seat_id_from_boarding_pass(boarding_pass):
row = 0
pass_row = boarding_pass[:7]
for char in pass_row:
row *= 2
if char == 'B':
row += 1
column = 0
pass_column = boarding_pass[7:]
for char in pass_column:
column *= 2
if char == 'R':
column += 1
return (row * 8) + column
if __name__ == '__main__':
with open("input", "r") as input_file:
boarding_passes = input_file.read().split('\n')
boarding_passes.pop() # Remove final empty line
all_seat_ids = [seat_id_from_boarding_pass(boarding_pass) for boarding_pass in boarding_passes]
print(f"Answer to part 1: {max(all_seat_ids)}")
lowest_id = min(all_seat_ids)
highest_id = max(all_seat_ids)
empty_seats = [sid for sid in range(lowest_id, highest_id) if sid not in all_seat_ids]
my_seat = empty_seats[0] # Full flight
print(f"Answer to part 2: {my_seat}")
|
a8dfc870c4334eb65a35eb9c52a215b031ab361c | GirlCoder99/Dice-Simulator | /dice.py | 667 | 3.78125 | 4 | import tkinter
import random
root = tkinter.Tk() #Accessing TK
root.geometry("700x450") #Creating Interface of Size 700 * 450
root.title("Roll Dice")
label = tkinter.Label(root, font=("times", 200)) #increases the size of the GUI Elements
def roll():
dice = ['\u2680', '\u2681', '\u2682', '\u2683', '\u2684', '\u2685']
label.configure(text = f'{random.choice(dice)} {random.choice(dice)}')
label.pack() #It is a gemoetry manager organizes the widgets in blocks before placing them in the parent widget
button = tkinter.Button(root, text = "Time to roll...", command = roll)
button.pack()
button.place(x = 330, y = 0)
root.mainloop() |
2bbf8aa278c38a358ce9ac8b82b74941cdbc71ff | deblina23/BasicPython | /scripts/exercise40.py | 298 | 4.03125 | 4 | #!/usr/bin/env python3
print("Problem:")
print(" Write a Python program to compute the distance between the points (x1, y1) and (x2, y2). ")
print("Solution:")
import math
def calculateDistance(x1,y1,x2,y2):
return math.sqrt((abs(x2-x1)**2)+(abs(y2-y1)**2))
print(calculateDistance(4,0,6,6))
|
b3e62ef93d22b3d4427ed865cfccbb0b617ebe02 | abbenteprizer/updating-graph | /updating_graph.py | 3,520 | 3.71875 | 4 | import csv
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
'''
This programs reads messages from a file and displays filtered data in graph.
Can automatically update graph depending on the graph-mode chosen as input
'''
### add argument to program ###
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--input_file")
parser.add_argument("-p", "--print_mode")
parser.add_argument("-w", "--windowsize")
args = parser.parse_args()
### Initialize variables ###
# when print_mode is 0, graph continuously updates values using a windowsize of 30
# when print_mode is 1, graph continuously updates and shows all values
# when print_mode is 2, graph shows all values, never updates graph
### set input data ###
if int(args.file) > 0:
input_file = int(args.input_file)
else:
print("no input_file given, set file with -f flag, terminating")
exit()
### set printing options ###
if int(args.print_mode) > 0:
print_mode = int(args.print_mode)
else:
print_mode = 0
if int(args.windowsize) > 0:
windowsize = int(args.windowsize)
else:
windowsize = 10
### matplotlib initialization ###
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
### Function info from file, filters the data and outputs a graph ###
def animate(i):
### read file and initialize variables ###
with open(input_file, 'r') as file:
lines = file.read().splitlines()
### initialize variables ###
### Filter the data ###
# Example;
# for index, line in enumerate(lines):
# data = line.split(' ')
# if data[0] == 'foo':
# list1.append(data[2])
# if data[0] == 'bar':
# list2[total_pdr_counter] = [data[1],0]
### store data you want to plot in variable print_list ###
# print_list =
### set printing boundaries, and printouts ###
print_length = len(print_list)
x_lower = len(print_list) - windowsize
x_higher = len(print_list) - 1
y_lower = 0 # put something here
y_higher = 100 # put something here
x_label = 'Number of experiments'
y_label = 'Times in ms'
### print automatically with moving window ###
if print_mode == 0:
if len(print_list) > windowsize:
x = range(print_length - windowsize, print_length)
y = print_list[-windowsize:]
ax1.clear()
plt.axis([x_lower, x_higher, y_lower, y_higher])
ax1.set_ylabel(x_label)
ax1.set_xlabel(y_label)
ax1.plot(x, y, marker='o', color='blue')
# for item in special_data: # print the vertical lines for special events
# if item in x:
# plt.vlines(item, ymin=y_lower, ymax=y_higher)
### print everything automatically ###
elif print_mode == 1:
x = range(0,len(pdr_list))
y = pdr_list
ax1.clear()
plt.axis([x_lower, x_higher, y_lower, y_higher])
ax1.set_ylabel(x_label)
ax1.set_xlabel(y_label)
ax1.plot(x, y, marker='o', color='blue', markersize=3)
# for item in special_data: # print the vertical lines for special events
# if item in x:
# plt.vlines(item, ymin=y_lower, ymax=y_higher)
### Print everything once ###
else:
x = range(0,len(pdr_list))
y = pdr_list
ax1.clear()
plt.axis([x_lower, x_higher, y_lower, y_higher])
ax1.set_ylabel(x_label)
ax1.set_xlabel(y_label)
ax1.plot(x, y, marker='o', color='blue', markersize=3)
# for item in special_data: # print the vertical lines for special events
# if item in x:
# plt.vlines(item, ymin=y_lower, ymax=y_higher)
### print the graph ###
if print_mode < 2:
ani = animation.FuncAnimation(fig, animate, interval=1000)
else:
animate(0)
plt.show()
|
f2196d413be060b43aecfaab025ef92cc9ad855d | bjk17/AoC_2019 | /03/Part_one.py | 1,053 | 3.6875 | 4 | #!/usr/bin/env python
def wpath_to_vset(wpath):
# wire path to "visited positions" set
vset = set()
pos = [0, 0]
for steps in wpath.split(","):
direction, length = steps[0], int(steps[1:])
if direction == 'U':
vset.update([(pos[0], pos[1] + step) for step in range(1, length + 1)])
pos[1] += length
elif direction == 'D':
vset.update([(pos[0], pos[1] - step) for step in range(1, length + 1)])
pos[1] -= length
elif direction == 'R':
vset.update([(pos[0] + step, pos[1]) for step in range(1, length + 1)])
pos[0] += length
elif direction == 'L':
vset.update([(pos[0] - step, pos[1]) for step in range(1, length + 1)])
pos[0] -= length
return vset
def manhattan_distance(pos):
return abs(pos[0]) + abs(pos[1])
wpath1, wpath2 = list(open("input.txt").read().split())
vset1, vset2 = wpath_to_vset(wpath1), wpath_to_vset(wpath2)
print(min(manhattan_distance(pos) for pos in vset1 & vset2))
|
021e9e0bfe226c359b8fb50d2760187c8c6d8259 | 19272/python-chessgame | /board.py | 2,480 | 3.609375 | 4 | from pieces import *
class ChessBoard:
def __init__(self):
self.selected = None
self.legal_moves = []
self.turn = "white"
self.board = {}
for row in range(8):
for column in range(8):
self.board[(row, column)] = None
for column in range(8):
self.board[(column, 1)] = Pawn("white", (column, 1))
self.board[(column, 6)] = Pawn("black", (column, 6))
self.board[(0, 0)] = Rook("white", (0, 0))
self.board[(7, 0)] = Rook("white", (7, 0))
self.board[(0, 7)] = Rook("black", (0, 7))
self.board[(7, 7)] = Rook("black", (7, 7))
self.board[(1, 0)] = Knight("white", (1, 0))
self.board[(6, 0)] = Knight("white", (6, 0))
self.board[(1, 7)] = Knight("black", (1, 7))
self.board[(6, 7)] = Knight("black", (6, 7))
self.board[(2, 0)] = Bishop("white", (2, 0))
self.board[(5, 0)] = Bishop("white", (5, 0))
self.board[(2, 7)] = Bishop("black", (2, 7))
self.board[(5, 7)] = Bishop("black", (5, 7))
self.board[(4, 0)] = Queen("white", (4, 0))
self.board[(4, 7)] = Queen("black", (4, 7))
self.board[(3, 0)] = King("white", (3, 0))
self.board[(3, 7)] = King("black", (3, 7))
def click_handler(self, value):
if not self.selected:
return self.__set_selected(value)
else:
return self.__move_piece(value)
def __set_selected(self, value):
if self.board[value] is not None \
and self.board[value].color == self.turn:
# SET SELECTED CELL
self.selected = value
# SET POSSIBLE MOVES
self.legal_moves = self.board[value].find_legal_moves(self.board)
print("Selected : {}".format(self.selected))
print("Legal moves :")
for i in self.legal_moves:
print(i)
print("-----------------")
return True
else:
return False
def __change_turn(self):
self.turn = "white" if self.turn == "black" else "black"
def __move_piece(self, target):
if target in self.legal_moves:
# UPDATING PIECE'S ATTRIBUTES
self.board[self.selected].position = target
if self.board[target]:
self.board[target].destroy()
# UPDATING BOARD
self.board[target] = self.board[self.selected]
self.board[self.selected] = None
# SET NEXT TURN
self.selected = None
self.legal_moves = []
self.__change_turn()
return True
else:
# UNSELECT PIECE
self.selected = None
self.legal_moves = []
return False
|
c924fe5e7cc149faaa6f6a10b6bc19e17a5b8499 | nikhilgajam/Python-Programs | /Gcd program in python.py | 329 | 3.625 | 4 | def gcdp(num1, num2):
i = gcd = 1
while i <= num1 and i <= num2:
if num1 % i == 0 and num2 % i == 0:
gcd = i
i += 1
return gcd
def gcd_rec(num1, num2):
if num2 != 0:
return gcd_rec(num2, num1 % num2)
else:
return num1
print(gcdp(12, 16))
|
52d25c434579b983c042aad5864dabb51a0c6086 | llcawthorne/old-python-learning-play | /Algorithms/make_tree.py | 1,684 | 3.78125 | 4 | #!/usr/bin/env python3
# Make tree from inorder and postorder traversal
# Implemented this for fun
# Follows the Problem 4.4.7 Algorithm and seems to work
class SimpleNode:
def __init__(self,value):
self.value = value
self.left = None
self.right = None
def printVal(self):
print(self.value,end=' ')
def printIO(self):
if self.left != None: self.left.printIO()
self.printVal()
if self.right != None: self.right.printIO()
def printPO(self):
if self.left != None: self.left.printPO()
if self.right != None: self.right.printPO()
self.printVal()
def printPR(self):
self.printVal()
if self.left != None: self.left.printPR()
if self.right != None: self.right.printPR()
def MakeTree(IO,PO):
# Handle base cases here
if IO == [] and PO == []: return
elif IO == []: print("Invalid input!"); exit()
elif PO == []: print("Invalid input!"); exit()
elif len(PO)>1 and IO[-1]==PO[-1]: print("Invalid input!"); exit()
root = SimpleNode(PO[-1])
leftIO,rightIO,leftPO,rightPO = [],[],[],[]
idx = 0
while IO[idx] != root.value:
leftIO.append(IO[idx])
idx += 1
idx+=1
while idx < len(PO):
rightIO.append(IO[idx])
idx+=1
for value in PO:
if value in leftIO:
leftPO.append(value)
elif value in rightIO:
rightPO.append(value)
root.left = MakeTree(leftIO,leftPO)
root.right = MakeTree(rightIO,rightPO)
return root
if __name__ == '__main__':
testList = MakeTree([9,3,1,0,4,2,7,6,8,5],[9,1,4,0,3,6,7,5,8,2])
testList.printIO()
print()
|
72961f138b75ff5c6212fbbd020884c9679da024 | lgc13/LucasCosta_portfolio | /python/RingOfFire_project/data.py | 2,410 | 3.59375 | 4 | import itertools
def Rules():
CARD_ACTIONS = [
{
'rank':'Ace',
'rule': "Waterfall..Everyone Drinks"
},
{
'rank':'2',
'rule': "F**k you: Tell someone to drink"
},
{
'rank':'3',
'rule': "F**c me: You drink!"
},
{
'rank':'4',
'rule': "Floor: last person to touch the floor, drinks!"
},
{
'rank':'5',
'rule': "Guys: all men must toast"
},
{
'rank':'6',
'rule': "Chicks: all ladies must toast"
},
{
'rank':'7',
'rule': "Heaven: last peron to point up must drink"
},
{
'rank':'8',
'rule': "Date: pick someone. You must both drink together when the other drinks, until the end of the game"
},
{
'rank':'9',
'rule': "Rhyme: say a word which everyone must rhyme with, going around clockwise. The person who can't, drinks"
},
{
'rank':'10',
'rule': "Question Master: the person holding this card must always drink double. The only way to get rid of this card, is by asking someone a question. If they verbally answer the question(without another question) then they take this card. * If another 10 is drawn, put the old on in the dead-pile"
},
{
'rank':'Jack',
'rule': "Thumb Master: at any point, put your thumb on the table without saying anything. Everyone must do the same once you've done this. Last person to do it, drinks. You can continually do this until another Jack is pulled"
},
{
'rank':'Queen',
'rule': "Queen Rule: create a rule that must be obeyed for the entirety of the game by all players. Any other Queen Rules added will stack. If any Queen Rule is broken at any time, that person must drink. * Queen Rule cannot be overruled by anything, including a 'King'"
},
{
'rank':'King',
'rule': "KING: place this card on your forehead. Until it falls, you can tell anyone to do anything"
}
]
deck = list(itertools.product(['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'],['Diamonds','Spades','Hearts','Clubs']))
return CARD_ACTIONS, deck
|
0d5afa45678e380a1b74a535d5e9848686edb301 | AppoPi/Projects | /Python/shuffling a list.py | 1,266 | 4.03125 | 4 | import random
from random import shuffle
def library(list):
# Slice list so that function doesn't alter parameter list
newlist = list[:]
# Call random library shuffle to randomize list order
shuffle(newlist)
return newlist
# Perfectly alternate from each half of the list
def faro(list):
r = []
# Divide list into two halves
l1 = list[:len(list)/2]
l2 = list[len(list)/2:]
# Alternate between each half
for (i, x) in zip(l1, l2):
# Create new list from alternating elements of the two halves
r.append(i)
r.append(x)
# Add back in the odd element
if len(list) % 2 == 1:
r.append(list[-1])
return r
# Remove at random from the list until there are none remaining
def fisherYates(list):
r = []
while(len(list) > 0):
# Generate random number
i = random.randint(0, len(list)-1)
# Add to list
r.append(list[i])
# Remove ("strikeout") random element
del list[i]
return r
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
list2 = ['apple','blackberry','cherry','dragonfruit','grapefruit','kumquat','mango','nectarine','persimmon','raspberry']
list3 = ['a','e','i','o','u']
lists = [list1, list2, list3]
for i in lists:
# random library shuffle
print library(i)
# Faro shuffle
print faro(i)
# Fisher And Yates shuffle
print fisherYates(i)
|
7fc957f0622c6486adbd6230d15aca2eafc42368 | raselkarim7/Coursera-DS-Algorithm-Specialization- | /Algorithmic-Toolbox/week2/gcd.py | 484 | 3.578125 | 4 | # Uses python3
import sys
def gcd_naive(a, b):
if (b > a):
a, b = b, a
if (b == 0 or a == 0):
return 1
while (a % b !=0 ):
c = a%b
a,b = b, c
current_gcd = b
return current_gcd
if __name__ == "__main__":
# input = sys.stdin.read()
inputData = input()
# print('input data === ', inputData)
a, b = map(int, inputData.split())
print(gcd_naive(a, b))
# Sample Input
# 22448866 66224488
#
# Sample Output
# 2222
|
1ba3d48d2f53723bef5f35676822dd643d4f915f | AmirOfir/SPOJ | /FENCE1.py | 320 | 3.671875 | 4 | # we have a wall, and we are connecting a fence to it on two points to get the max area
# considering the wall as a rod, the fence as a string. we have a semicircle
# The area of semicircle: (r^2)/(2PI)
# 1/(PI*2) = ~0.15915494309
while True:
l = int(input())
if l == 0: break
print("%.2f" % (l*l*0.15915494309))
|
1ebc827b1859b7149d49094d63cabfb759abfe77 | justinkhado/tides-ai | /tides/montecarlo/mcts_node.py | 2,886 | 3.671875 | 4 | from abc import ABC, abstractmethod
import math
import random
class MCTSNode(ABC):
'''
Abstract Monte Carlo Tree Search Node
'''
@abstractmethod
def __init__(self, state, parent=None, action=None):
'''
Params:
state: GameState corresponding to this node
action: action that parent of this node took to get to this node
parent: parent of this node
'''
self.state = state
self.parent = parent
self.action = action
self.children = []
@abstractmethod
def selection(self, c):
'''
Params:
c: exploration/exploitation constant; c = 0 => exploitation only
Returns the child with the highest UCT value
'''
pass
@abstractmethod
def expansion(self):
'''
Add child and return it
'''
pass
@abstractmethod
def rollout(self):
'''
Returns utility of game after selecting random moves until terminal state
'''
pass
@abstractmethod
def backpropagation(self, utility):
'''
Update number of visits 'n' and number of wins 'w' and do the same
for parent
'''
pass
class UCB1Node(MCTSNode):
'''
UCB1 variant of MCTS node
'''
def __init__(self, state, parent=None, action=None):
super().__init__(state, parent, action)
self.x = 0
self.n = 0
self.unexplored_actions = state.actions()
def selection(self, c):
possible_choices = []
for child in self.children:
possible_choices.append(self.ucb1(child.x, child.n, self.n, c))
return self.children[possible_choices.index(max(possible_choices))]
def expansion(self):
action = self.unexplored_actions.pop()
next_state = self.state.result(action)
child = UCB1Node(state=next_state, parent=self, action=action)
self.children.append(child)
return child
def rollout(self):
current_state = self.state
while not current_state.terminal_test():
action = random.choice(current_state.actions())
current_state = current_state.result(action)
return current_state.utility()
def backpropagation(self, utility):
self.n += 1
self.x += utility
if self.parent:
self.parent.backpropagation(utility)
@staticmethod
def ucb1(x, n, N, c):
'''
Parameters:
x: cumulative rewards sum for node
n: number of simulations for node
N: total number of simulations by parent of node
c: exploration/exploitation parameter
Returns the value from the UCB1 formula
'''
return (x / n) + c * math.sqrt(math.log(N) / n)
|
634cb17db22dc8179ede64f3ecd5e9f735c07287 | RomansWorks/CarND-Vehicle-Detection | /common_geometry.py | 3,265 | 3.5 | 4 |
class Point():
def __init__(self, x, y):
self.x = int(x)
self.y = int(y)
def scale(self, factor):
return Point(self.x*factor, self.y*factor)
def shift(self, dx, dy):
return Point(self.x+dx, self.y+dy)
def get_distance(self, other):
return ((self.x-other.x)**2+(self.y-other.y)**2)**0.5
def __repr__(self):
return "Point({},{})".format(self.x,self.y)
class Rect():
def __init__(self, p1, p2):
assert p2.x >= p1.x
assert p2.y >= p1.y
self.p1 = p1
self.p2 = p2
def get_height(self):
return self.p2.y - self.p1.y
def get_width(self):
return self.p2.x - self.p1.x
def get_left(self):
return self.p1.x
def get_right(self):
return self.p2.x
def get_top(self):
return self.p1.y
def get_bottom(self):
return self.p2.y
def scale(self, factor):
return Rect(self.p1.scale(factor), self.p2.scale(factor))
def shift(self, dx, dy):
return Rect(self.p1.shift(dx, dy), self.p2.shift(dx, dy))
def calculate_overlap(self, other):
left = max(self.get_left(), other.get_left())
right = min(self.get_right(), other.get_right())
top = max(self.get_top(), other.get_top())
bottom = min(self.get_bottom(), other.get_bottom())
if right - left <= 0 or bottom - top <= 0:
return None
else:
return Rect(Point(left, top), Point(right, bottom))
def calculate_area(self):
return self.get_height() * self.get_width()
def is_contained_in(self, other):
return self.get_top() >= other.get_top() and self.get_bottom() <= other.get_bottom() and self.get_left() >= other.get_left() and self.get_right() <= other.get_right()
def __repr__(self):
return "Rect({},{})".format(self.p1,self.p2)
def get_bbox_center(bbox):
x = (bbox[1][0] - bbox[0][0])/2 + bbox[0][0]
y = (bbox[1][1] - bbox[0][1])/2 + bbox[0][1]
return (int(x),int(y))
def test_point():
p = Point(10, 20)
assert(p.x == 10)
assert(p.y == 20)
p_scaled = p.scale(5)
assert(p_scaled.x == 50)
assert(p_scaled.y == 100)
p_shifted = p.shift(-10, 50)
assert(p_shifted.x == 0)
assert(p_shifted.y == 70)
assert(p.get_distance(Point(10, 30)) == 10)
assert(p.get_distance(Point(-10, 20)) == 20)
def test_rectangle():
r = Rect(Point(0, 100), Point(50, 200))
assert(r.p1.x == 0)
assert(r.p1.y == 100)
assert(r.p2.x == 50)
assert(r.p2.y == 200)
assert(r.get_height() == 100)
assert(r.get_width() == 50)
assert(r.calculate_area() == 5000)
assert(r.get_left() == 0)
assert(r.get_right() == 50)
assert(r.get_top() == 100)
assert(r.get_bottom() == 200)
r_non_overlapping = Rect(Point(500, 500), Point(600, 600))
assert(r.calculate_overlap(r_non_overlapping) == None)
r_overlapping = Rect(Point(25, 150), Point(75, 250))
overlap_rect = r.calculate_overlap(r_overlapping)
overlap_area = overlap_rect.calculate_area()
assert(overlap_area == 1250)
# TODO: Test shift
# TODO: Test scale
|
83344aa7fe907f101b97bc5b8e76a12f48abb02a | laycom/educational_projects | /less_1/less_1_task_4.py | 886 | 4.28125 | 4 | # 4. Пользователь вводит две буквы.
# Определить, на каких местах алфавита они стоят,
# и сколько между ними находится букв.
letter_1 = ord(input('Введите первую букву от "a" до "z": '))
letter_2 = ord(input('Введите вторую букву от "a" до "z": '))
first_letter = ord('a')
letter_1_position = letter_1 - first_letter + 1
letter_2_position = letter_2 - first_letter + 1
distance = abs(letter_2_position - letter_1_position - 1)
print('Буква {} --> место в алфавите {}'.format(chr(letter_1), letter_1_position))
print('Буква {} --> место в алфавите {}'.format(chr(letter_2), letter_2_position))
print('Между {} и {} находится {} букв(ы)'.format(chr(letter_1), chr(letter_2), distance)) |
d14dedeb2a5bc2d6cd953f17d4e6fe26a7d3a7bf | sasha-n17/python_homeworks | /homework_5/task_5.py | 552 | 3.515625 | 4 | with open('task_5.txt', 'w+', encoding='utf-8') as f:
f.write(input('Введите набор чисел, разделённых пробелом: '))
with open('task_5.txt', 'r+', encoding='utf-8') as f:
numbers = f.readline()
try:
if len(numbers) > 0:
print(f'Сумма чисел в файле: {sum([float(el) for el in numbers.split()])}')
else:
print('Файл пуст, нет чисел для подсчёта!')
except ValueError:
print('Некорректный ввод!')
|
1853291fdc7e3d9621d5daa771d1910e3f7bb065 | jedzej/tietopythontraining-basic | /students/skowronski_rafal/lesson_01_basics/lesson_02/problem_03.py | 329 | 4.15625 | 4 | # Solves problem 03 - Sum of digits
import math
def print_sum_of_digits():
number = abs(int(input('Enter integer number: ')))
sum = 0
while number != 0:
sum += number % 10
number = number // 10
print('\nSum of digits is: {0}'.format(sum))
if __name__ == '__main__':
print_sum_of_digits()
|
3fe5e2c56b16f04f26b5ca57cc426eb1da6df306 | Zahidsqldba07/PythonExamples-1 | /functions/intervalo.py | 245 | 3.5 | 4 | # coding: utf-8
# Aluno: Héricles Emanuel
# Matrícula: 117110647
# Atividade: Soma Intervalo
def soma_intervalo(a,b):
soma = 0
for i in range(a, b + 1):
soma += i
return soma
assert soma_intervalo(5,15) == 110
assert soma_intervalo(10,10) == 10
|
9dcaf7eee9a4fc2b969aa6711033fa62a4826dc2 | palash27/ASE-Group7-HW | /src/Sym.py | 908 | 3.59375 | 4 | import math
class Sym:
"""
Summarize a stream of symbols.
"""
def __init__(self) -> None:
self.n = 0
self.has = {}
self. most = 0
self.mode = None
def add(self, x):
"""
update counts of things seen so far
"""
if x != '?':
self.n = self.n + 1
self.has[x] = 1 + self.has.get(x, 0)
if self.has[x] > self.most:
self.most, self.mode = self.has[x], x
def mid(self):
"""
return the mode
"""
return self.mode
def div(self):
"""
return the entropy
"""
def fun(p):
"""
pass `p` and return p time log of p to the base 2
"""
return p*math.log(p,2)
e = 0
for _,n in self.has.items():
e = e + fun(n/self.n)
return -e
|
90f59ae08ad947a12369726aae28975b12da2c5f | ricardoifc/RepoProgram | /Python/2do ciclo/04 while cadena +/practica200519-ricardoifc-master/ejercicio1.py | 313 | 3.625 | 4 | """
file: ejercicio1.py
@ricardoifc
"""
nombre = input("ingrese su nombre\t")
nota = input("ingrese una nota\t")
nota2 = input("ingrese una nota2\t")
nota = float(nota)
nota2 = float(nota2)
promedio = (nota + nota2)/2
cadena = "Estudiante con %s, tiene un promedio de %f" % \
(nombre, promedio)
print(cadena) |
799ad44f6a265668733b149e9f311ac82287eaa9 | vladder47/tasks | /caesar.py | 947 | 3.953125 | 4 | def encrypt_caesar(plaintext, shift):
alpha = 'abcdefghijklmnopqrstuvwxyz'
alpha_big = alpha.upper()
ciphertext = ''
for i in plaintext:
if i in alpha:
ciphertext += alpha[(alpha.index(i) + shift) % len(alpha)]
elif i in alpha_big:
ciphertext += alpha_big[(alpha_big.index(i) + shift) % len(alpha_big)]
else:
ciphertext += i
return ciphertext
def decrypt_caesar(ciphertext, shift):
alpha = 'abcdefghijklmnopqrstuvwxyz'
alpha_big = alpha.upper()
plaintext = ''
for i in ciphertext:
if i in alpha:
plaintext += alpha[(alpha.index(i) - shift) % len(alpha)]
elif i in alpha_big:
plaintext += alpha_big[(alpha_big.index(i) - shift) % len(alpha_big)]
else:
plaintext += i
return plaintext
print(encrypt_caesar('Python3.6', 3))
print(decrypt_caesar('Sbwkrq3.6', 3)) |
680d0c59b1b415e302185021064eae261730bead | TawfikW/Portfolio | /Python/EvenOrOdd Game/EvenOrOdd Game.py | 1,324 | 3.625 | 4 | from tkinter import *
from tkinter import ttk
import random
root=Tk()
root.geometry('275x250+350+200')
root.title('EvenOrOdd')
button1 = ttk.Button(root, text='Play')
button1.grid(row=0, column=0, columnspan=2, padx=10, pady=10)
button2 = ttk.Button(root, text='Even')
button2.grid(row=3, column=0, padx=10, pady=20)
button3 = ttk.Button(root, text='Odd')
button3.grid(row=3, column=1, padx=10, pady=20)
v1=StringVar()
v2=StringVar()
e1 = Entry(root, textvariable=v1, width=40)
e1.grid(row=1, column=0, columnspan=2, padx=10)
e2 = Entry(root, textvariable=v2, width=20)
e2.grid(row=4, column=1, sticky=W)
label1 = Label(root, text='Is this number EVEN or ODD')
label1.grid(row=2, column=0, columnspan=2, padx=10)
label2 = Label(root, text='You are :')
label2.grid(row=4, column=0, padx=10,ipady=10, sticky=E)
def play(self):
e1.delete(0,END)
e2.delete(0,END)
x=random.randrange(0,999)
e1.insert(0,x)
def even(self):
number=int(e1.get())
if number % 2 == 0:
e2.insert(0,'a Genius')
else:e2.insert(0, 'a Failure')
def odd(self):
number=int(e1.get())
print(number)
if (number%2 != 0):
e2.insert(0,'a Genius')
else: e2.insert(0, 'a Failure')
button1.bind('<ButtonPress>', play)
button2.bind('<ButtonPress>', even)
button3.bind('<ButtonPress>', odd)
|
5f8ab90d58e4b02f96b2747c3ebc8ea66516342a | mcculleydj/rosetta-code | /python/strings/strings_7.py | 398 | 4.0625 | 4 | # O(n)
def is_rotation(s1, s2):
if len(s1) != len(s2):
return False
# let AB represent s1
# where A is the first part of the string and B is the second
# s2 is a rotation <=> s2 == BA (necessary and sufficient)
# let s2 concatenated be represented by BABA
# if s1 can be represented by AB then it must be a substring of s2 + s2
# O(n)
return s1 in s2 + s2
|
3b3af0b3c40636cfc4e43deb3694334907e020bb | hjalmarlindstrom/msudke-d | /hänga gubbe.py | 1,243 | 3.65625 | 4 |
import random
ordlista = ["hund", "mus", "dator", "stol", "bord", "skor", "ben"]
gissade_bokstäver = []
gissade_bokstäver_2 = []
gissningar = 0
ordet = ordlista[random.randrange(0, len(ordlista)-1)]
def gissning():
global gissade_bokstäver
global gissade_bokstäver_2
global gissningar
global ordet
gissning2 = input("Skriv en bokstav")
if gissning2 in ordet:
print("Rätt!")
gissningar = gissningar + 1
gissade_bokstäver_2.append(gissning2)
else:
gissade_bokstäver.append(gissning2)
print(gissade_bokstäver)
print("Du hade tyvärr fel!")
gissningar = gissningar + 1
print("Välkommen till hänga gubbe!")
print("Du kommer att ha 10 gissningar att gissa ordet!")
print("Lycka till!")
a = True
while a:
if len(ordet) < len(gissade_bokstäver_2):
gissning()
elif len(ordet) == len(gissade_bokstäver_2):
print("Du vann!")
a = False
print(gissade_bokstäver_2)
elif gissningar < 10:
gissning()
elif gissningar == 10 or gissningar > 10:
print("Du har tyvärr slut på gissningar")
a = False
|
df5a4d9f630bb35fab976c3b1127c79dc4c88c5d | MTrajK/coding-problems | /Strings/reverse_vowels.py | 1,967 | 4.15625 | 4 | '''
Reverse Vowels
Given a text string, create and return a new string constructed by finding all its vowels (for
simplicity, in this problem vowels are the letters in the string 'aeiouAEIOU') and reversing their
order, while keeping all non-vowel characters exactly as they were in their original positions.
Input: 'Hello world'
Output: 'Hollo werld'
=========================================
Simple solution, find a vowel from left and swap it with a vowel from right.
In Python, the string manipulation operations are too slow (string is immutable), because of that we need to convert the string into array.
In C/C++, the Space complexity will be O(1) (because the strings are just arrays with chars).
Time Complexity: O(N)
Space Complexity: O(N)
'''
############
# Solution #
############
def reverse_vowels(sentence):
arr = [c for c in sentence] # or just arr = list(sentence)
vowels = {
'a': True, 'A': True,
'e': True, 'E': True,
'i': True, 'I': True,
'o': True, 'O': True,
'u': True, 'U': True
}
left = 0
right = len(arr) - 1
while True:
# find a vowel from left
while left < right:
if arr[left] in vowels:
break
left += 1
# find a vowel from right
while left < right:
if arr[right] in vowels:
break
right -= 1
if left >= right:
# in this case, there are only 1 or 0 vowels
# so this is the end of the algorithm, no need from more reversing
break
# swap the vowels
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return ''.join(arr)
###########
# Testing #
###########
# Test 1
# Correct result => 'ubcdofghijklmnepqrstavwxyz'
print(reverse_vowels('abcdefghijklmnopqrstuvwxyz'))
# Test 2
# Correct result => 'Hollo werld'
print(reverse_vowels('Hello world')) |
95f636049c0b2c012946d0b98c8f9991bfa73f19 | g147/exercism-solutions | /python/difference-of-squares/difference_of_squares.py | 227 | 3.859375 | 4 | def sum_of_squares(limit):
return sum(n**2 for n in range(limit+1))
def square_of_sum(limit):
return sum(range(limit+1)) ** 2
def difference_of_squares(limit):
return square_of_sum(limit) - sum_of_squares(limit) |
278fd23b6c54340a92a987ea66f53f51a7ee8501 | ericzhai918/Python | /LXF_Python/Function_test/func_namingKeyword_para.py | 576 | 3.71875 | 4 |
#关键字参数什么都能传,这点我很不爽,要限制它传进去的东西怎么办?
#命名关键字参数,以*分隔
def person(name,age,*,city,job):
print(name,age,city,job)
person('Jack',24,city='Shanghai',job="OA")
person('Jack',24,job="OA",city='Shanghai')
#有可变参数,省略*
def person(name,age,*args,city,job):
print(name,age,args,city,job)
person('Jack',24,'Beijing','Engineer')#报错
#命名关键字参数可以有缺省值
def person(name,age,*,city='Beijing',job):
print(name,age,city,job)
person('Jack',24,job='Engineer') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.