blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
4405cd71e2b1676f601e75017539082489699a2b | onik282/Python | /L7/1.py | 839 | 3.609375 | 4 | class Matrix:
def __init__(self, list_1, list_2) -> object:
# self.matr = [list_1, list_2]
self.list_1 = list_1
self.list_2 = list_2
def __add__(self):
matr = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
for i in range(len(self.list_1)):
for j in range(len(self.list_2[i])):
matr[i][j] = self.list_1[i][j] + self.list_2[i][j]
return str('\n'.join(['\t'.join([str(j) for j in i]) for i in matr]))
def __str__(self):
return str('\n'.join(['\t'.join([str(j) for j in i]) for i in matr]))
my_matrix = Matrix([[5, 18, 11],
[6, 17, 23],
[41, 50, 9]],
[[45, 8, 2],
[6, 7, 93],
[24, 5, 97]])
print(my_matrix.__add__())
|
cabb95644f96e6a792854cbcf0662c3107be442c | gcd0318/pe | /l3/pe57.py | 1,140 | 3.96875 | 4 | """
It is possible to show that the square root of two can be expressed as an infinite continued fraction.
2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...
By expanding this for the first four iterations, we get:
1 + 1/2 = 3/2 = 1.5
1 + 1/(2 + 1/2) = 7/5 = 1.4
1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...
The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, 1393/985, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.
In the first one-thousand expansions, how many fractions contain a numerator with more digits than denominator?
"""
def add(f, n):
return[f[0]+n*f[1], f[1]]
def reciprocal(f):
return([f[1], f[0]])
def sqrt2(t):
if(0 == t):
return[1, 1]
else:
return(add(reciprocal(add(sqrt2(t-1), 1)), 1))
l = [1, 1]
times = 0
for i in range(0, 1000+1):
tl = l
l = add(reciprocal(add(tl, 1)), 1)
n = l[0]
d = l[1]
if(len(str(n)) > len(str(d))):
times = times + 1
print(times)
|
7292131b90604ccc75633ad9c40f70804c067feb | leesohyeon/Python_ac | /1111/classex/ClassTest07.py | 1,347 | 3.53125 | 4 | '''
제품의 가격과 수량을 넘겨주면,
총 금액을 알려주는 프로그램을 만들어보세요
class Payment:
변수..
메서드..
'''
# 1. 06.py 파일을 외워서, 스스로 작성해보기!
# 2. 할인율을 추가해서, 할인가격도 출력해보기!
class Payment:
counter=0
discount = 0.5
def __init__(self,price,number):
self.price=price
self.number=number
Payment.counter+=1
def cal(self):
self.tot=self.price*self.number
self.dcpay=self.price - (self.price * Payment.discount)
@classmethod #할인율을 변경하는 메서드
def update(cls,value):
# 0<할인율<1
# 만일 사용자가 위의 범위에서 벗어난 할인율을 적용하려 할때
# 다시 입력받도록 하자
while (0>value or value>=1):
value = float(input("할인율을 다시 입력하세요"))
cls.discount = value
@staticmethod
def message():
print("어서오세요")
print("할인행사중입니다")
def showinfo(self):
print("%s번째 제품입니다"%Payment.counter)
print("정가 : %d"%self.price)
print("정상가격 : %d"%self.tot)
print("할인가격 : %d"%self.dcpay)
notebook = Payment(1000,5)
notebook.cal()
notebook.showinfo()
|
9639d87c50f00ef17b68b1fe44f01eabaaa06b99 | dryabokon/algo | /math_06_rotate_mat.py | 1,425 | 3.546875 | 4 | # leetcode.com/problems/rotate-image/
# ----------------------------------------------------------------------------------------------------------------------
import numpy
# ----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
def rotate(A):
# (0,1) -> (1,3)
# (r,c) -> (c,C-1-r)
def rotate_tuple(point, C):
return (point[1], C - 1 - point[0])
R = len(A)
for r in range(0,R-1):
for c in range(r, R-r-1):
p1 =(r,c)
p2 = rotate_tuple(p1, R)
p3 = rotate_tuple(p2, R)
p4 = rotate_tuple(p3, R)
A[p1[0]][p1[1]] , A[p2[0]][p2[1]],A[p3[0]][p3[1]],A[p4[0]][p4[1]]=A[p4[0]][p4[1]] , A[p1[0]][p1[1]],A[p2[0]][p2[1]],A[p3[0]][p3[1]]
'''
p_start = (r,c)
value = A[p_start[0]][p_start[1]]
p_nxt = rotate_tuple(p_start,R)
while p_start!=p_nxt:
A[p_nxt[0]][p_nxt[1]],value =value,A[p_nxt[0]][p_nxt[1]]
p_nxt = rotate_tuple(p_nxt,R)
A[p_start[0]][p_start[1]] = value
'''
return
# ----------------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
#A = [[1,2,3,4],[5,6,7,8],[9,1,2,3],[4,5,6,7]]
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(numpy.array(A))
rotate(A)
print('------------')
print(numpy.array(A))
|
7b4b8d0c67b08fc70034165d47e1bfc707d198b7 | ersincebi/hackerrank | /30 Days of Code/Day 25 Running Time and Complexity.py | 994 | 3.890625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
import math
def isPrime(param):
flag = True
if param == 2:
flag = True
elif param == 1 or param%2==0:
flag = False
else:
for i in range(2, int(math.sqrt(param)+1)):
if param % i == 0:
flag = False
break
return 'Prime' if flag else 'Not prime'
# def isPrime(param):
# flag = True
# if param == 1:
# flag = False
# else:
# for i in range(2, int(math.sqrt(param)+1)):
# if param % i == 0:
# flag = False
# break
# flag = True
# for i in range(2, int(math.sqrt(param))):
# if param%i is 0:
# flag = False
# break
# return 'Prime' if flag else 'Not prime'
lst = ['1',
'4',
'9',
'16',
'25',
'36',
'49',
'64',
'81',
'100',
'121',
'144',
'169',
'196',
'225',
'256',
'289',
'324',
'361',
'400',
'441',
'484',
'529',
'576',
'625',
'676',
'729',
'784',
'841',
'907']
# for num in lst:
# print(isPrime(int(num)))
for _ in range(int(input())):
print(isPrime(int(input())))
|
e4c84c2d3d9c269d6d5f5798955d3c835d673f6e | woohyun212/Data_Science_and_AI_introductory_Coding_Solution | /chapter7/ex_7_1.py | 382 | 3.625 | 4 | fruit_list = ['banana', 'orange', 'kiwi', 'apple', 'melon']
largest_str = []
largest_str_len = len(max(fruit_list))
for i in fruit_list:
if len(i) == largest_str_len:
largest_str.append(i)
for i in largest_str:
fruit_list.remove(i)
print(f"가장 길이가 긴 문자열 : ", end='')
for i in largest_str:
print(i, end=" ")
print(f'\nfruit_list = {fruit_list}')
|
e2fdb46f3b66c81de4bed7967b5d326af8939e1f | DrBugKiller/offer | /经典代码/0914-计数排序.py | 1,075 | 3.6875 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019/9/14 10:57
# @Author : DrMa
'''
计数排序:
空间复杂度:n+k,n对应着新数组res,k代表计数数组count_array
时间复杂度:O(n+k)或者O(n),n代表遍历a,k代表遍历count_array
'''
def count_sort(a):
min_num=min(a)
max_num=max(a)
#构造计数数组
count_array=[0]*(max_num-min_num+1)
for num in a:
count_array[num-min_num]+=1#num-min_num目的是把a的每个数和count_array的下标对齐
#生成新数组
res=[]
for num,count in enumerate(count_array):
res+=[num+min_num]*count
return res
def count_sort2(a):
count_dict={}
min_num=min(a)
max_num=max(a)
# 构造计数字典
for num in range(min_num,max_num+1):
count_dict[num]=0
for num in a:
count_dict[num]+=1
# 生成新数组
res=[]
for num in range(min_num,max_num+1):
res+=[num]*count_dict[num]
return res
if __name__=='__main__':
raw_array=[2,4,2,5,2,6,7,8,9,2,4,5,6,7,11,-1]
new_array=count_sort2(raw_array)
print(new_array) |
2f3c745b5f381fe09922092bb48cdbf4fdcaced5 | SoliDeoGloria31/study | /AID12 day01-16/day03/exercise/rectangle2.py | 496 | 3.875 | 4 | # 练习:
# 写一个程序,打印一个高度为4行的矩形方框
# 要求输入一个整数,此整数代码矩形的宽度,打印
# 相应宽度的矩形
# 如:
# 请输入矩形宽度: 10
# 打印如下:
# ##########
# # #
# # #
# ##########
w = int(input("请输入矩形的宽度: "))
print('#' * w) # 打印第一行
print('#', ' ' * (w-2), '#', sep='') # 第二行
print('#', ' ' * (w-2), '#', sep='')
print('#' * w)
|
9576ab573518e6df91ec7a96e611a9d011dc9f31 | carodewig/advent-of-code | /advent-py/2015/day_03.py | 1,286 | 3.875 | 4 | """ day 3: perfectly spherical houses in a vacuum """
from collections import namedtuple
Location = namedtuple("Location", ["x", "y"])
def deliver_presents(directions):
location = Location(0, 0)
yield location
for step in directions:
if step == ">":
location = Location(location.x + 1, location.y)
elif step == "<":
location = Location(location.x - 1, location.y)
elif step == "^":
location = Location(location.x, location.y + 1)
elif step == "v":
location = Location(location.x, location.y - 1)
yield location
def unique_houses(directions):
return len(set(list(deliver_presents(directions))))
def unique_houses_two_santas(directions):
return len(set(list(deliver_presents(directions[::2])) + list(deliver_presents(directions[1::2]))))
assert unique_houses(">") == 2
assert unique_houses("^>v<") == 4
assert unique_houses("^v^v^v^v^v") == 2
assert unique_houses_two_santas("^v") == 3
assert unique_houses_two_santas("^>v<") == 3
assert unique_houses_two_santas("^v^v^v^v^v") == 11
DIRECTIONS = ""
with open("data/03.txt") as fh:
DIRECTIONS = fh.readline().strip()
assert unique_houses(DIRECTIONS) == 2081
assert unique_houses_two_santas(DIRECTIONS) == 2341
|
8e0ebd063f434f77c799372935d190507d700c5d | raymondmar61/pythonwilliamfiset | /exceptionhandlingasserttryexceptfinallyraise.py | 1,543 | 3.96875 | 4 | #williamfiset 23 Assert Try Raise Except Finally
#ASSERT
age = 344
#check condition, if false then run whatever is on the right of comma as an AssertionError
assert age >= 0, "How is your age negative?\n"
print("Your age is", age) #print Your age is 344
#TRY EXCEPT
while True:
try: #try: the code below which may work or not work
numerator = float(input("Enter a numerator: "))
denominerator = float(input("Enter a denominerator: "))
print("The fraction ratio is %f " % (numerator/denominerator))
except ZeroDivisionError as theZeroError: #print statement at except: is executed when an error happened at try:. In this case, user enters zero as denominator. Python has a custom defined error. Use ZeroDivisionError. Other custom defined errors are BaseException and Exception. Can have more than one except
print("An error has happened")
print("The error written at except: statement is printed here-->" ,theZeroError)
#FILES
#my_file = open("filename.txt", "w") #opens file. If not there, it creates one. Opens in write mode. Other modes are read and read-write.
#FINALLY
# my_file = open("filename.txt", "w")
# try:
# my_file.write("I wrote in a new file!\n")
# except Exception as error:
# print(error)
# except ZeroDivisionError as error:
# print(error)
# finally: #always execute no matter try: successful or unsuccessful
# my_file.close()
# pass
#RAISE
#user creates own errors with error messages
age = 199
if age > 135:
raise Exception("Your supposed to be dead! You are older than 135 years of age!") |
0d440309c3c3872b72e9d2899bef958c319a5412 | maheshkrishnagopal/HackerRankSolutions | /Python-Basic Data Types-Lists.py | 571 | 3.8125 | 4 | if __name__ == '__main__':
N = int(input());
list=[];
for i in range (0,N):
inp=input();
ip=inp.split(" ");
if (ip[0]=='insert'):
list.insert(int(ip[1]),int(ip[2]));
elif(ip[0]=='print'):
print(list);
elif(ip[0]=='remove'):
list.remove(int(ip[1]));
elif(ip[0]=='sort'):
list.sort();
elif(ip[0]=='pop'):
list.pop();
elif(ip[0]=='reverse'):
list.reverse();
elif(ip[0]=='append'):
list.append(int(ip[1]));
|
0cd91fa6cbfcda373178d8320c53c5f69e557a56 | oamam/algorithm | /sort/heap_sort.py | 924 | 3.59375 | 4 | # coding: utf-8
'''
node: n
parent node: (n + 1) / 2
left child node: 2n + 1
right child node: 2n + 2
'''
def make_heap(buff, end):
while True:
maked = True
for i in range(end):
n = buff[i]
c = 2*i + 1
if c >= end: break
lcn = buff[c]
if end > c + 1 and buff[c + 1] >= buff[c] and buff[c + 1] > n:
c += 1
if buff[c] > buff[i]:
t = buff[i]
buff[i] = buff[c]
buff[c] = t
maked = False
if maked: break
return buff
def heap_sort(buff):
buff = make_heap(buff, len(buff))
begin = 0
end = len(buff) - 1
while end >= 0:
if buff[begin] > buff[end]:
t = buff[begin]
buff[begin] = buff[end]
buff[end] = t
end -= 1
buff = make_heap(buff, end)
return buff
|
908f8c516e15b26b4a6edf1c0819d87e2d11e1b5 | lohitbadiger/python-basics-all | /43.py | 386 | 3.5625 | 4 | # functions with some input values
def spiceup(owners,staffs):
print('hello to the world of spiceup', owners, 'and welcome to ', staffs)
own=input('enter the name of the owner')
sft=input('enter the name of staffs')
spiceup(own,sft)
def home(rented):
print('hello im staying in ',rented ,'house')
name=input('enter the name of house')
home(name)
|
7459347af32b0873c7ca9d86feb4decdd5abed72 | mrmattkennedy/CS5800 | /Prog_Assign_1/nfa_lambda_dfa.py | 26,044 | 3.828125 | 4 | #!/usr/bin/env python3
"""Purpose of this module is to convert NFA/NFA lambda to DFA
Course is CS 5800
Author is Matthew Kennedy
Example:
Option to run either the .py file, or .exe file
With each option, can either
1) Pass in a file to read input from
2) Pass in command line arguments, specified in README
3) Enter inputs manually
"""
import os
import sys
import copy
import random
try:
import pyperclip
except:
pass
class NFAL_DFA:
"""Class to convert NFA\Lambda to DFA, as well as process strings for this new DFA
Attributes:
Q (list): States of M (starting NFA\Lambda)
S (list): (S)sigma of M (alphabet of NFA\Lambda), same for new DFA (M prime)
D (dict): (D)elta of M (starting NFA\Lambda)
start_state (str): q0, starting state of M
F (list): Final (accepting) states of M
input_trans_func (dict): input transition function of M
start_state_lambda_closure - Used as starting point for algorithm to convert NFA\Lambda to DFA
Q_prime (list): States of M prime (new DFA)
S_prime (list): (S)sigma of M prime (alphabet of DFA), same for M
D_prime (dict): (D)elta of M prime (new DFA)
F_prime (list): Final (accepting) states of M prime
"""
def __init__(self, args):
"""Init runs through methods procedurally
Starts by processing input arguments and getting necessary tuple elements of NFA\Lambda
Next, creates the input transition function for this NFA\Lambda
Next, gets the lambda closure of starting state of M, for use in the new DFA
Next, creates the DFA
After this, the program will create the graphviz file, then test strings on this new DFA
Args:
args (list): Command line arguments passed in
Returns:
None
"""
self.process_inputs(args)
self.create_input_transition_func()
self.get_q0_lambda_closure()
self.create_dfa()
self.output_dfa()
self.create_graphviz_format()
self.test_strings()
def test_strings(self):
"""Processes random strings, then gives user option to process strings
Args:
None
Returns:
None
"""
print('\n\n')
print('='*50)
print('Testing strings')
print('='*50)
print('\n')
run_random = input("Would you like to run pre-built random strings? If yes, type anything and hit enter, if not, just hit enter: ")
if run_random:
#Create random strings
strings = []
for _ in range(10):
string = ''.join(random.choice(self.S_prime) for i in range(random.randint(8, 20)))
strings.append(string)
#Test/output random strings
for s in strings:
result, comps = self.process_string(s)
self.print_nicely(s, result, comps)
print()
#Give the option for custom strings
while True:
s = input("Enter a string to test, or leave blank to exit:\t")
if s:
result, comps = self.process_string(s)
self.print_nicely(s, result, comps)
else:
break
def print_nicely(self, s, result, comps):
"""Prints out computations and result of processed string nicely
Aligns each output to the right, so much easier to read
Args:
s (str): String that was processed
result (str): ACCEPT or REJECT, result of the string being processed
comps (list): List of each computation in processing
Returns:
None
"""
#Get max length for each column
col0 = [i[0] for i in comps]
col0.append('Starting state')
col0_maxlen = max([len(i) for i in col0])
col1 = [i[1] for i in comps]
col1.append('Ending state')
col1_maxlen = max([len(i) for i in col1])
col2 = [i[2] for i in comps]
col2.append('Remaining string')
col2_maxlen = max([len(i) for i in col2])
col3 = [i[3] for i in comps]
col3.append('Character processed')
col3_maxlen = max([len(i) for i in col3])
#Print column header, then pad each line with the max length for that column to align
print('Starting state\tEnding state\tRemaining string\tCharacter processed')
print('-'*75)
for line in comps[:-1]:
col0_str_padded = line[0].ljust(col0_maxlen)
col1_str_padded = line[1].ljust(col1_maxlen)
col2_str_padded = line[2].ljust(col2_maxlen)
col3_str_padded = line[3].ljust(col3_maxlen)
print('{}\t{}\t{}\t{}'.format(col0_str_padded, col1_str_padded, col2_str_padded, col3_str_padded))
#Print last line (reason rejected or accepted), then print the string/actual result
print(comps[-1])
print('String {}: {}\n'.format(s, result))
def process_string(self, string):
"""Processes a string provided one char at a time.
If at any point no possible path to follow, returns False
If entire string processed, but ends not on a final string, return False
Otherwise, return True
Args:
None
Returns:
ACCEPT if string processed correctly
REJECT if not
Computations that took place
"""
#Start state
state = ''.join(self.start_state_lambda_closure)
computations = [[state, 'lambda', string, 'lambda']]
#Process string, if ever not an option to move, just return False
while string:
char_to_process = string[0]
if (state, char_to_process) in self.D_prime.keys():
old_state = state
state = self.D_prime[state, char_to_process]
string = string[1:]
if string:
computations.append([old_state, state, string, char_to_process])
else:
computations.append([old_state, state, 'lambda', char_to_process])
else:
computations.append('No transitions available')
return 'REJECT', computations
#Make sure actually in a final state
for f in self.F_prime:
f_str_repr = ''.join(f)
if f_str_repr == state:
computations.append('String finished processing, ended in final state')
return 'ACCEPT', computations
computations.append('String finished processing, ended at non-final state')
return 'REJECT', computations
def create_graphviz_format(self):
"""Creates graphviz formatted string (extra credit)
Prints it, also prompts user for save path if they want that
Args:
None
Returns:
None
"""
print("\n\nPlease enter a path to save file output to (leave blank to skip)")
save_path = input("Note: the graphviz text will be printed out here, as well as automatically copied (if pyperclip found on system):\t")
#Create string for final states
final_nodes_str_repr = ''.join(["{{{}}}".format(''.join(f)) for f in self.F_prime])
#Create string for all transition functions
transitions_str_repr = ""
for k, v in self.D_prime.items():
start = "{{{}}}".format(k[0])
end = "{{{}}}".format(v)
label = k[1]
line = '\t{} -> {} [ label = "{}" ];\n'.format(start, end, label)
transitions_str_repr += line
#Create actual output string
output_str = 'digraph matt_kennedys_output {{'
output_str += '\n\trankdir=LR;'
output_str += '\n\tsize="8,5"'
output_str += '\n\tnode [shape = doublecircle]; {}'.format(final_nodes_str_repr)
output_str += '\n\tnode [shape = circle];'
output_str += '\n{}'.format(transitions_str_repr)
output_str += '}}'
#Print text out, also put on clipboard
print(output_str, '\n\n')
try:
pyperclip.copy(output_str)
except:
print('Module pyperclip not on system, so text will not be put on clipboard automatically')
#Save output
if save_path:
with open(save_path, "w") as f:
f.write(output_str)
def output_dfa(self):
"""Displays each element of the tuple that defines the new DFA
Args:
None
Returns:
None
"""
save_dfa = input("If you'd like to save the new DFA, enter the file path:\t")
#Save new DFA is user would like
if save_dfa:
#Create strings
q_prime_str = 'Q: {}'.format(','.join([''.join(q) for q in self.Q_prime]))
s_prime_str = 'S: {}'.format(','.join(self.S_prime))
d_prime_str = 'D: '
for k, v in self.D_prime.items():
d_prime_str += '({},{},{}),'.format(k[0], k[1], v)
d_prime_str = d_prime_str[:-1]
q0_prime_str = 'q0: {}'.format(','.join(self.start_state_lambda_closure))
f_prime_str = 'F: {}'.format(','.join([''.join(f) for f in self.F_prime]))
#Save new strings
with open(save_dfa, 'w') as f:
f.write(q_prime_str + '\n')
f.write(s_prime_str + '\n')
f.write(d_prime_str + '\n')
f.write(q0_prime_str + '\n')
f.write(f_prime_str + '\n')
#Output transition table
print('Input transition table of M:')
for k, v in self.input_trans_func.items():
if not v:
v = ['0']
v.sort()
print('\t', k, '->', ''.join(v))
print('\nTuple elements of newly created DFA:\n')
#Output states
print("Q prime:")
for s in self.Q_prime:
print('\t', ''.join(s))
#Output alphabet
print("\nSigma prime is the same as Sigma (alphabet) of M, except for removal of lambda if it was present")
print(','.join(self.S_prime))
#Output delta
print('\nDelta prime:')
for k, v in self.D_prime.items():
print('\t', k, '->', v)
#Output start state
print('\nStart state of new DFA is equal to lambda closure of start state of M, which is {}'.format(''.join(self.start_state_lambda_closure)))
#Output final states
print('\nF prime:')
for f in self.F_prime:
print('\t', ''.join(f))
print('\n\n')
def create_dfa(self):
"""Creates DFA from start state lambda closure and input transition functioin.
For each node/symbol, check if that node has an arc reaching somewhere with that symbol
If not, break node down into states, then get the infinitary union of each state's input
transitive function value (Y).
Then, convert to string representation (or just 0 if Y is empty), add Y to the list of nodes,
and the string representation to the new DFA's transitive function table for that node/symbol
Args:
None
Returns:
None
"""
self.Q_prime = [self.start_state_lambda_closure]
self.S_prime = [s for s in self.S if s != 'lambda']
self.D_prime = {}
self.F_prime = []
#Check each node, verify the key exists in (D)elta_prime
for node in self.Q_prime:
#Check each symbol that isn't lambda
for symbol in self.S:
if symbol == 'lambda':
continue
#Get string repr of node, check if it already exists in D_prime
node_str_rep = ''.join(node)
if not (node_str_rep, symbol) in self.D_prime.keys():
Y = []
#For each state in taht node, get the input transitive function value
for state in node:
if self.input_trans_func[state, symbol]:
for s in self.input_trans_func[state, symbol]:
#If value not already in Y, add it
if s not in Y:
Y.append(s)
#Create string repr for Y, used for Delta
Y.sort()
Y_str_rep = "{}".format(''.join(Y)) if Y else '0'
if Y:
if Y not in self.Q_prime:
self.Q_prime.append(Y)
#Append string repr of Y as transition from the node/symbol
self.D_prime[node_str_rep, symbol] = Y_str_rep
#Create F_prime
self.F_prime = []
for node in self.Q_prime:
if any(s for s in node if s in self.F) and node not in self.F_prime:
self.F_prime.append(node)
#Add empty set recursion
if any (v for v in self.D_prime.values() if v == '0'):
for symbol in self.S:
if symbol != 'lambda':
self.D_prime[(0, symbol)] = 0
self.Q_prime.append(['0'])
def get_q0_lambda_closure(self):
"""Gets lambda closure for starting state - this is required for the NFA\Lambda to DFA algorithm
No other lambda closures needed. Just sees if there are any lambda branches to reach out on from start state
Follows as far as possible.
Args:
None
Returns:
None
"""
self.start_state_lambda_closure = [self.start_state]
if (self.start_state, 'lambda') in self.D.keys():
states_to_visit = copy.deepcopy(self.D[self.start_state, 'lambda'])
while states_to_visit:
curr_state = states_to_visit[0]
#Check if any other new lambda arcs from current state, add if there are
next_states = copy.deepcopy([v for k, v in self.D.items() if (curr_state in k and 'lambda' in k) and (curr_state not in v) and (state not in v)])
if next_states:
for s in next_states[0]:
if s not in states_to_visit:
states_to_visit.append(s)
self.start_state_lambda_closure.append(curr_state)
#Delete the state we were on from the list
del states_to_visit[0]
def create_input_transition_func(self):
"""Creates input transition function. Loops through each combo of state/symbol that isn't lambda
Keeps track of states for that specific transition - appends normally if not lambda
If any lambda arcs, adds any states reachable by lambda if original state has a looped element
Additionally, tries to reach out on lambda branches and search for the specified symbol, adds that state if possible
Args:
None
Returns:
None
"""
self.input_trans_func = {}
for state in self.Q:
for symbol in self.S:
if symbol == 'lambda':
continue
#Create empty list of states to store in table
states = []
#If w is an input that isn't lambda, process normally (append to states)
if (state, symbol) in self.D.keys():
for s in self.D[state, symbol]:
states.append(s)
#Check if there are any arcs with lambda that are not loops. Need to deep copy to use del function later
states_to_visit = copy.deepcopy([v for k, v in self.D.items() if (state in k and 'lambda' in k) and (state not in v)])
#If there are lambda arcs, use algorithm
if states_to_visit:
#Due to the way states to visit is acquired, it's just a nested list
states_to_visit = states_to_visit[0]
#Insert starting state into list
states_to_visit.insert(0, copy.deepcopy(state))
#While more lambda arcs, repeat algorithm
while states_to_visit:
#Update current state
curr_state = states_to_visit[0]
#Check if any other new lambda arcs from current state, add if there are
next_states = copy.deepcopy([v for k, v in self.D.items() if (curr_state in k and 'lambda' in k) and (curr_state not in v) and (state not in v)])
if next_states:
for s in next_states[0]:
if s not in states_to_visit:
states_to_visit.append(s)
#If the current state has transitions, check them for the input w. Add if it's there.
if (curr_state, symbol) in self.D.keys():
new_states = copy.deepcopy([s for s in self.D[curr_state, symbol]])
for s in new_states:
if s not in states:
states.append(s)
#Add the state if the initial state has a loop
if (state, symbol) in self.D and state in self.D[state, symbol]:
if curr_state not in states:
states.append(curr_state)
#Delete the state we were on from the list
del states_to_visit[0]
#Set input transition for state/symbol to states found
self.input_trans_func[state, symbol] = states
def process_inputs(self, args):
"""Processes input. Defaults to file path if -file flag specified
If file unreadable or flag not set, checks if user passed in all other necessary flags
If not that, prompts user for a file path, or the option to just enter info manually.
Args:
args (list): Command line arguments passed in to program
Returns:
None
"""
print('\n'*50)
#Check if help flag passed in
if "-h" in args or "-H" in args:
self.show_help()
#Check first if there is a path specified, and verify path is valid
if "-file" in args:
file_path = args[args.index("-file")+1]
self.read_file(file_path)
#Verify each required argument is flagged
elif (('-q' in args or '-Q' in args) and
('-s' in args or '-S' in args) and
('-d' in args or '-D' in args) and
('-q0' in args or '-Q0' in args) and
('-f' in args or '-F' in args)):
#Get states
q_key = '-q' if '-q' in args else '-Q'
self.Q = args[args.index(q_key)+1]
#Get (s)igma, or alphabet
s_key = '-s' if '-s' in args else '-S'
self.S = args[args.index(s_key)+1]
#Get (d)elta, or transition functions
d_key = '-d' if '-d' in args else '-D'
self.D = args[args.index(d_key)+1]
#Get q0, or start state
q0_key = '-q0' if '-q0' in args else '-Q0'
self.start_state = args[args.index(q0_key)+1]
#Get final states
f_key = '-f' if '-f' in args else '-F'
self.F = args[args.index(f_key)+1]
#Get necessary tuple elements as input
else:
print('\n\n')
file_path = input("Enter a file path (or just hit enter to instead enter each element manually):\t")
if file_path:
self.read_file(file_path)
else:
self.Q = input("Enter the states (Q), deliminated by commas (i.e. state1,state2...):\t")
self.S = input("Enter the alphabet (S), deliminated by commas (i.e. a,b,lambda,...):\t")
self.D = input("Enter the transition functions (Q), using the following format:\n(start_state,input_to_process,end_state_1,end_state_2,...),...:\t")
self.start_state = input("Enter the start state:\t")
self.F = input("Enter the final state(s), F, deliminated by commas (i.e. state1,state2...):\t")
if not self.Q or not self.S or not self.D or not self.start_state or not self.F:
self.show_help()
#Verify elements
self.verify_elements()
def verify_elements(self):
"""After getting all 5 necessary tuple elements for M, this method verifies them
For Q, just splits it
For S, just splits it
For D, splits accordingly, verifies all elements are present in Q and S
For q0, verifies q0 is part of Q
For F, verifies all F are part of Q
Args:
None
Returns:
None
"""
#Get states, remove whitespace just in case user forgot to
self.Q = [q.strip() for q in self.Q.split(',')]
for q in self.Q:
assert self.Q.count(q) == 1, "No duplicate states allowed"
#Get alphabet, remove whitespace just in case user forgot to
self.S = [s.strip() for s in self.S.split(',')]
for s in self.S:
assert self.S.count(s) == 1, "No duplicate alphabet items allowed"
#Get transitions, remove whitespace just in case user forgot to
temp_d = [d.strip().replace(')', '').replace('(', '') for d in self.D.split('),')]
self.D = {}
#Create dict for transitions, where key is (initial_state, input)
for transition in temp_d:
transition_split = [d.strip() for d in transition.split(',')]
self.D[transition_split[0], transition_split[1]] = transition_split[2:]
#Make sure input to process is part of S, states are part of Q
assert transition_split[1] in self.S, "Input to process in transitions must be part of S, {} is not".format(transition_split[1])
assert transition_split[0] in self.Q, "States specified in transition must be part of Q, {} is not".format(s)
for s in transition_split[2:]:
assert s in self.Q, "States specified in transition must be part of Q, {} is not".format(s)
#Verify q0 is part of Q
assert self.start_state in self.Q, "Starting state needs to be part of Q, {} is not part of {}".format(self.start_state, self.Q)
#Get final states, remove whitespace just in case user forgot to
self.F = [f.strip() for f in self.F.split(',')]
for f in self.F:
assert self.F.count(f) == 1, "No duplicate final states allowed"
#Verify F is part of Q
for f in self.F:
assert f in self.Q, "Final state(s) needs to be part of Q, {} is not part of {}".format(f, self.Q)
def read_file(self, file_path):
"""Reads a file for specified input,
looking at the start of each line for the required tuple elements
Args:
file_path (str): File path string to verify/read from
Returns:
None
"""
assert os.path.exists(file_path), "File must be a valid path"
#Read file
with open(file_path, 'r') as f:
tuple_counts = {'Q': 0, 'S': 0, 'D': 0, 'Q0': 0, 'F': 0}
#For each line, strip white space and trailing newline
for line in f:
line = line.rstrip('\n').strip()
#Get counts of each element of tuple defining M, make sure there is 1 of each
if line:
line_split = [l.strip() for l in line.split(':')]
if (line_split[0] == 'q' or line_split[0] == 'Q'):
tuple_counts['Q'] += 1
self.Q = line_split[1]
elif (line_split[0] == 's' or line_split[0] == 'S'):
tuple_counts['S'] += 1
self.S = line_split[1]
elif (line_split[0] == 'd' or line_split[0] == 'D'):
tuple_counts['D'] += 1
self.D = line_split[1]
elif (line_split[0] == 'q0' or line_split[0] == 'Q0'):
tuple_counts['Q0'] += 1
self.start_state = line_split[1]
elif (line_split[0] == 'f' or line_split[0] == 'F'):
tuple_counts['F'] += 1
self.F = line_split[1]
#Assert each key has count of 1
for k, v in tuple_counts.items():
assert v == 1, "Must be exactly 1 value for {}".format(k)
def show_help(self):
"""Prints help string, exits after
Args:
None
Returns:
None
"""
print("""
You can either execute .exe file, or run python file
3 options:
Specify a file using flag below
Run program with arguments passed in
Enter inputs manually, prompted by program
Flags:
-hH - Help message (exits after showing)
-qQ - States of M
-sS - Alphabet of M (s for Sigma)
-dD - Transition functions of M (d for Delta)
-q0 - Start state of M
-fF - Final states of M
-file - Specifies a file to read from (format specified in README, example also provided)
Note - if all flags provided, including -file, program will always try to read from file.""")
input()
sys.exit()
if __name__ == '__main__':
converter = NFAL_DFA(sys.argv) |
24b14aaf50b23a74a37e5b6fd35f4e1a82958e0e | klondikemarlen/design_patterns | /interface/ducks.py | 1,352 | 4 | 4 | import abc
from interface.quack_behaviors import Quack
from interface.fly_behaviors import FlyWithWings, FlyNoWay
class Duck(abc.ABC):
"""Duck that implements arbitrary fly and quack behaviors.
NOTE on set/get in python:
In the simplest use case you don't need these methods in Python!
Using a method allows for more complex modifications than simple assignment.
def set_fly_behavior(self, fb):
print("Duck transformed!")
self.fly_behavior = fb
duck.set_fly_behavior(ExampleFlyBehavior())
"""
@abc.abstractmethod
def __init__(self):
self.fly_behavior = None
self.quack_behavior = None
@abc.abstractmethod
def display(self):
pass
def perform_fly(self):
self.fly_behavior.fly()
def perform_quack(self):
self.quack_behavior.quack()
def swim(self):
print("All ducks float, even decoys!")
class MallardDuck(Duck):
def __init__(self):
super().__init__()
self.fly_behavior = FlyWithWings()
self.quack_behavior = Quack()
def display(self):
print("I'm a real Mallard duck.")
class ModelDuck(Duck):
def __init__(self):
super().__init__()
self.fly_behavior = FlyNoWay()
self.quack_behavior = Quack()
def display(self):
print("I'm a model duck.")
|
7a4dab2d6938b09f2ee44e114bd9828baeb614c5 | berkaybaltas1/Python | /Create Turtle Color.py | 233 | 4.15625 | 4 | #Name: Berkay Baltas
#Date: 09/13/2018
#This program asks the user for the turtle color and stamps it
import turtle
myturtle = turtle.Turtle()
mess = input("Please enter the turtle color: ")
myturtle.shape("turtle")
myturtle.color(mess)
|
429abea983f85acb2bd7ea53032d5b2d4234394a | JustinMacaulay/Seng474Project | /tweetRetrieval.py | 2,413 | 3.78125 | 4 | '''
tweetRetrieval.py
Stephanie Goodale
SENG 474 Project
11/10/2017
Use Twitter API and tweepy functions to access a chosen user's most
recent tweets and write into a CSV file. CSV format includes the
tweet ID, the datetime that it was posted, and the text of the tweet.
Note: Twitter only allows access to a users most recent 3240 tweets.
'''
#!/usr/bin/env python
#encoding: utf-8
import tweepy
import csv
import html
#consumer keys and access tokens, used for OAuth Twitter API
consumer_key = 'XQCnw2YBIgJCDJthDT6AQTiPD'
consumer_secret = 'uYLZJNpJuViuxoTWcutdKN4pV6AjqW79Oqams6HmbDMDMuHGxz'
access_token = '928741549969514496-6ffPlRa6GJMwb7Ohwd3pNEBmm71TZhq'
access_token_secret = 'ZoKgBKjfJeZwZl2NYZdPKGyLIJIpB7eFd6lzfHFBau3u7'
def get_all_tweets(screen_name):
#authorize twitter, initialize tweepy
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
#initialize a list to hold all the tweepy Tweets
alltweets = []
#make initial request for most recent tweets (200 is the maximum allowed count)
new_tweets = api.user_timeline(screen_name = screen_name,count=200, tweet_mode='extended')
#save most recent tweets
alltweets.extend(new_tweets)
#save the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
#keep grabbing tweets until there are no tweets left to grab
while len(new_tweets) > 0:
print('getting tweets before %s' % (oldest))
#all subsiquent requests use the max_id param to prevent duplicates
new_tweets = api.user_timeline(screen_name = screen_name,count=200,max_id=oldest, tweet_mode='extended')
#save most recent tweets
alltweets.extend(new_tweets)
#update the id of the oldest tweet less one
oldest = alltweets[-1].id - 1
print('...%s tweets downloaded so far' % (len(alltweets)))
#get extended tweets
for tweet in alltweets:
tweet.text = tweet.full_text
tweet.text = html.unescape(tweet.text)
#transform the tweepy tweets into a 2D array that will populate the csv
outtweets = [[tweet.id_str, tweet.created_at, tweet.text] for tweet in alltweets]
#write the csv
with open('%s_tweets.csv' % screen_name, 'w', encoding='utf_8_sig') as f:
writer= csv.writer(f)
writer.writerow(["id","created_at","text"])
writer.writerows(outtweets)
pass
if __name__ == '__main__':
#pass in the username of the account you want to download
get_all_tweets("realDonaldTrump")
|
b6ae132b4e5ec309b73c889087a2821074debd6b | Jason101616/LeetCode_Solution | /Tree/199. Binary Tree Right Side View.py | 1,116 | 4.15625 | 4 | # Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
# For example:
# Given the following binary tree,
# 1 <---
# / \
# 2 3 <---
# \ \
# 5 4 <---
# You should return [1, 3, 4].
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# idea: BFS, time: O(n), space: O(n)
from collections import deque
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
res = []
q = deque()
q.append(root)
while q:
curLevelLen = len(q)
for i in range(curLevelLen):
node = q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
res.append(node.val)
return res
|
77ef787c5adcd766d2c3c6ef431fbf22f87733eb | datasciences/Bayesian_Inference-graphical_models | /scripts/pymc3/05_trimodal-distribution.py | 1,024 | 3.921875 | 4 | '''
Create a trimodal distribution with different number of
data points.
Input: n_cluster:number of datapoints
mean
std: standard deviation
'''
import numpy as np
import seaborn as sns
def main():
# Create a mixture distribution with 3 means and std
# There has to be 90, 50 and 75 draws from each of these clusters
clusters = 3
# number of points in each cluster
n_cluster = [90, 50, 75]
# total number of points in the mixture distribution
n_total = sum(n_cluster)
# mean and std of the 3 clusters
means = [9, 21, 35]
std_devs = [2, 2, 2]
# Create a numpy array with the mean as many times you want to sample
x = np.repeat(means, n_cluster)
y = np.repeat(std_devs, n_cluster)
# create a numpy array of the draws
mix = np.random.normal(x, y)
# plot the distribution
sns.kdeplot(mix, shade = True)
plt.xlabel('mixture distribution', fontsize = 14)
plt.ylabel('density', fontsize = 14)
if __name__ == '__main__':
main()
|
ac65455af80de976b3eb10feef2cce0f312a2f97 | arpith-kp/interviewrelated | /leetcode_hard.py | 2,034 | 3.59375 | 4 | from collections import deque
from typing import List
def carrs():
def getCollisionTimes(A):
stack = []
n = len(A)
res = [-1] * n
for i in range(n - 1, -1, -1):
p, s = A[i]
while stack and (s <= A[stack[-1]][1] or (A[stack[-1]][0] - p) / (s - A[stack[-1]][1]) >= res[stack[-1]] > 0):
stack.pop()
if stack:
res[i] = (A[stack[-1]][0] - p) / (s - A[stack[-1]][1])
stack.append(i)
return res
cars = [[1, 2], [2, 1], [4, 3], [7, 2]]
getCollisionTimes(cars)
def robot_last():
def shortestPath(grid: List[List[int]], k: int) -> int:
if len(grid) == 1 and len(grid[0]) == 1:
return 0
queue = deque([(0, 0, k, 0)])
visited = {(0, 0, k)}
if k > (len(grid) - 1 + len(grid[0]) - 1):
return len(grid) - 1 + len(grid[0]) - 1
while queue:
row, col, eliminate, steps = queue.popleft()
for new_row, new_col in [(row - 1, col), (row, col + 1), (row + 1, col), (row, col - 1)]:
if (new_row >= 0 and
new_row < len(grid) and
new_col >= 0 and
new_col < len(grid[0])):
if grid[new_row][new_col] == 1 and eliminate > 0 and (new_row, new_col, eliminate - 1) not in visited:
visited.add((new_row, new_col, eliminate - 1))
queue.append((new_row, new_col, eliminate - 1, steps + 1))
if grid[new_row][new_col] == 0 and (new_row, new_col, eliminate) not in visited:
if new_row == len(grid) - 1 and new_col == len(grid[0]) - 1:
return steps + 1
visited.add((new_row, new_col, eliminate))
queue.append((new_row, new_col, eliminate, steps + 1))
return -1
grid = [[0,0,0], [1,1,0], [0,0,0], [0,1,1], [0,0,0]]
k=1
shortestPath(grid, k)
robot_last()
|
9bded1d02557e723f53863529fb1d23bdfa738b4 | AladinBS/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 546 | 3.703125 | 4 | #!/usr/bin/python3
""" Appends a line """
def append_after(filename="", search_string="", new_string=""):
""" appends a new line if a str is found
search_string: search str
new_string: appended str
filename: filename
"""
res_line = []
with open(filename, 'r', encoding="utf-8") as f:
for x in f:
res_line += [x]
if x.find(search_string) != -1:
res_line += [new_string]
with open(filename, 'w', encoding="utf-8") as f:
f.write("".join(res_line))
|
6c6ae51b8bf89c4db17bda2ed53b5fdef08e9103 | langepass88/Python-Begins | /Lesson2/5.py | 499 | 3.84375 | 4 | my_list = [7, 5, 3, 3, 2]
print(f'У нас есть набор натуральных чисел: {my_list}')
while True:
try:
num = int(input('Введите число: '))
except ValueError:
print('Программа завершена')
break
for i in range(len(my_list)):
if num > my_list[i]:
my_list.insert(i, num)
break
elif num <= my_list[-1]:
my_list.append(num)
break
print(my_list)
|
598232bf3efe5b37bfe6b35eb4fc2ba090699bcc | SobuleacCatalina/Introducere_Afisare_Calcule | /problema_4.py | 126 | 3.5 | 4 | nae=int(input("Introdu numarul de globulete albe:"))
nr=nae+3
nal=(nae+nr)-2
t=nae+nr+nal
print("Pe brad sunt",t,"globulete.") |
1490721df48e746827288e3121d5853fe75bff02 | daniel-reich/ubiquitous-fiesta | /q3JMk2yqXfNyHWE9c_10.py | 135 | 3.828125 | 4 |
def double_letters(word):
for i in range(len(word) - 1):
if word[i] == word[i + 1]:
return True
else:
return False
|
e043b87f17d384056534b49fe81cf526b0601172 | slm-bj/nlpia | /scripts/chapter2.py | 1,861 | 3.703125 | 4 | """ NLPIA Chapter 2 Section 2.1 Code Listings and Snippets """
import pandas as pd
sentence = "Thomas Jefferson began building Monticello at the age of "\
"twenty-six."
sentence.split()
# ['Thomas', 'Jefferson', 'began', 'building', 'Monticello', 'at', 'the',
# 'age', 'of', 'twenty-six.']
# As you can see, this simple Python function already does a decent job
# tokenizing the example sentence. A couple more vanilla python statements
# and you can create numerical vector representations for each word.
sorted(dict([(token, 1) for token in sentence.split()]).items())
[('Jefferson', 1),
('Monticello', 1),
('Thomas', 1),
('age', 1),
('at', 1),
('began', 1),
('building', 1),
('of', 1),
('the', 1),
('twenty-six.', 1)]
# A slightly better data structure
sentence = "Thomas Jefferson began building Monticello at the age of 26."
df = pd.DataFrame(pd.Series(dict([(token, 1) for token in sentence.split()])),
columns=['sent0']).T
df
# 26. Jefferson Monticello Thomas age at began building of the
# 0 1 1 1 1 1 1 1 1 1 1
# And a pandas dataframe is great for holding multiple texts
# (sentences, tweets, or documents)
sentences = "Thomas Jefferson began building Monticello at the age of 26.\n" \
"Construction was done mostly by local masons and carpenters.\n" \
"He moved into the South Pavilion in 1770.\n" \
"Turning Monticello into a neoclassical masterpiece was Jefferson's "\
"obsession"
corpus = {}
for i, sent in enumerate(sentences.split('\n')):
corpus['sent{}'.format(i)] = dict([(token, 1) for token in sent.split()])
df = pd.DataFrame.from_records(corpus).fillna(0).astype(int).T
dft = df.T
print(dft.sent0.dot(dft.sent1))
print(dft.sent0.dot(dft.sent2))
print(dft.sent0.dot(dft.sent3))
print([(k, v) for (k, v) in (dft.sent0 & dft.sent3).items() if v])
|
5562a78a5668bef37d45084d49dddc78f3fc36e8 | Bruk3/ctci-solutions | /chapter_1/1_is_unique/is_unique.py | 398 | 4 | 4 | '''Two different implementations of how to check whether or not a string
is made up of all unique characters. '''
def is_unique_1(string):
'''
string: str
returns boolean
Time Complexity: O(n)
Space Complexity: O(n)
'''
seen_chars = set()
for char in string:
if char in seen_chars:
return False
seen_chars.add(char)
return True
|
7b03370a974869a9d47707741c939b68a6050c0b | AyaAshreey/Codeforces | /785A/anton_and_polyhedrons.py | 329 | 3.8125 | 4 | """ Created by Henrikh Kantuni on 3/15/17 """
if __name__ == "__main__":
n = int(input())
total = 0
faces = {
"Tetrahedron": 4,
"Cube": 6,
"Octahedron": 8,
"Dodecahedron": 12,
"Icosahedron": 20,
}
while n > 0:
total += faces[input()]
n -= 1
print(total)
|
a377f40924c9e2c51b9d98611db8bb2c5434f955 | tfidfwastaken/codefundo2k18 | /preprocessing.py | 1,867 | 3.734375 | 4 | from nltk.tokenize import TweetTokenizer
from nltk.corpus import stopwords
import re, string
import nltk
import pandas as pd
import geograpy as geo
#from nltk.tag import StanfordNERTagger
#import ner
"""
This part of the program takes our dataframe df containing
tweet data and extracts useful tokens, or meaningful keywords which
we will be analysing and trying to make sense of
"""
df = pd.read_csv("tweet_data.csv", sep=";",error_bad_lines=False)
tweets_text = df["text"].tolist()
stopwords = stopwords.words('english') # stopwords are useless words like 'the', 'is' and all
english_vocab = set(word.lower() for word in nltk.corpus.words.words())
kerala = pd.read_csv('kerala.csv')
cities = list(kerala['Places'])
#districts = list(kerala['District'])
def process_tweets_texts(tweet):
if tweet.startswith('@null'):
return "[Tweet is unavailable]"
# Just some regular expressions that strips out more noise
tweet = re.sub(r'\$\w*','',tweet) # Remove tickers
tweet = re.sub(r'https?:\/\/.*\/\w*','',tweet) # Remove hyperlinks
tweet = re.sub(r'['+string.punctuation+']+', ' ',tweet) # Remove punctuations
twtok = TweetTokenizer(strip_handles=True, reduce_len=True)
tokens = twtok.tokenize(tweet)
tokens = [i.lower() for i in tokens if i not in stopwords and len(i) > 2 and
i in english_vocab]
return tokens
words = []
places = []
#for tw in tweets_text:
for tw in tweets_text[:1000]:
words += process_tweets_texts(tw)
places.append(geo.get_place_context(text=tw))
for tw in tweets_text[1000:2000]:
words += process_tweets_texts(tw)
places.append(geo.get_place_context(text=tw))
city = []
for p in range(len(places)):
pl = places[p].cities
for i in pl:
if i in cities:
city.append(i)
print(city)
|
d71b673ab50999918f3df497eb8ccf9bac93d5a7 | tigervanilla/Guvi | /player124.py | 229 | 3.578125 | 4 | def GCD(a,b):
if (a == 0) :
return b
return GCD(b % a, a)
def LCM(a,b):
return a*b//GCD(a,b)
n=int(input())
ar=list(map(int,input().split()))
for i in range(1,n):
ar[i]=LCM(ar[i],ar[i-1])
print(ar[-1])
|
9dbd66b0ea93a452d6b2b125de62175f4e87692c | jalletto/python_black_jack | /card.py | 277 | 3.515625 | 4 | class Card:
card_back = '| \\\\ | '
def __init__(self, suit, value, face=None):
self.suit = suit
self.face = face
self.value = value
def __str__(self):
return f'| { self.face if self.face else self.value }{ self.suit } | '
|
e036b03972a0506686af8cc0552eb1e08a06772a | myNameArnav/cheaper | /src/scraper.py | 1,888 | 3.796875 | 4 | """
The scraper module holds functions that actually scrape the e-commerce websites
"""
import requests
import formatter
from bs4 import BeautifulSoup
def httpsGet(URL):
"""
The httpsGet funciton makes HTTP called to the requested URL with custom headers
"""
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36", "Accept-Encoding":"gzip, deflate", "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "DNT":"1","Connection":"close", "Upgrade-Insecure-Requests":"1"}
page = requests.get(URL, headers=headers)
soup1 = BeautifulSoup(page.content, "html.parser")
return BeautifulSoup(soup1.prettify(), "html.parser")
def searchAmazon(query):
"""
The searchAmazon function scrapes amazon.com
"""
query = formatter.formatSearchQuery(query)
URL = f'https://www.amazon.com/s?k={query}'
page = httpsGet(URL)
results = page.findAll("div", {"data-component-type":"s-search-result"})
products = []
for res in results:
titles, prices, links = res.select("h2 a span"), res.select("span.a-price span"), res.select("h2 a.a-link-normal")
product = formatter.formatResult("amazon", titles, prices, links)
products.append(product)
return products
def searchWalmart(query):
"""
The searchWalmart function scrapes walmart.com
"""
query = formatter.formatSearchQuery(query)
URL = f'https://www.walmart.com/search?q={query}'
page = httpsGet(URL)
results = page.findAll("div", {"data-item-id":True})
products = []
for res in results:
titles, prices, links = res.select("span.lh-title"), res.select("div.lh-copy"), res.select("a")
product = formatter.formatResult("walmart", titles, prices, links)
products.append(product)
return products |
d0da99d02e647fd45849b36e75dac9f7478106d1 | daniel-leinad/progrepository | /hw5/hw5.py | 452 | 3.5625 | 4 | #5 вариан
#вводим список
i = []
#считываем слова
while True:
a = input()
if a == "":
break
#проверяем, оканчивается ли слово на tur, если да, то добавляем его в список
if a[-1]=="r" and a[-2]=="u" and a[-3]=="t":
i.append(a)
#записываем список в файл
f = open("output.txt","w")
f.write("\n".join(i))
f.close()
|
c8afd3010906603dd02cc8d4629c0eb901c803df | Kavi1808/beginer-2 | /armstrong or not.py | 204 | 3.703125 | 4 | num=135
order=len(str(num))
sum=0
temp=num
while temp>0:
digit=temp%10
sum+=digit**order
temp//=10
if num==sum:
print(num,"armstrong")
else:
print(num,"not armstrong")
|
628dc941223a5aae5fc81402c66c523e136dd450 | hboonewilson/1CS | /Homework/home_work1.py | 6,625 | 3.765625 | 4 | #Presume that you can only drive 8 hours per day. So, if a trip requires 15.25
#hours, it will require a one-night hotel stay at an additional cost (beyond gas
#and food costs) equal to hotelCostPerNight.
def tripCostAndInfo(distanceKM, vehSpeedMPS, vehKPL, gasCostPerLiter, breakfastCostPerDay,
lunchCostPerDay, dinnerCostPerDay, hotelCostPerNight):
#determine the time (hrs) you need to finish trip by dividing kilo per second by 60 and 1000 to make it kilo per hour then dividing by kilometers
time = distanceKM / (vehSpeedMPS * (60 ** 2) / 1000)
#calculate cost of fuel by calculating liters used then mult by cost of liter
fuel_cost = gasCostPerLiter * (distanceKM / vehKPL)
#calculate days traveled (time / 8) because 8hrs max a day
days = time / 8
#create days_rounded for future calculations
days_rounded = int(days)
#calulate nights in hotel by evaluating if days_str is whole number or not
days_str = str(days)
#if the last to indicies of days_str are '.0'
if days_str[-2:] == '.0':
#subtract a day from days and turn to an integer
total_hotel = int(days - 1)
else:
#if not, simply round down using days_rounded
total_hotel = days_rounded
#calculate total cost of hotel stays by mult hotel_num and hotelCostPerNight
hotel_price = total_hotel * hotelCostPerNight
#use days str to calculate number of dinners needed for the trip because every day needs a dinnner except for the last
#if the string of days it takes to get there is a whole number
if days_str[-2:] == '.0':
#sub a day
dinners = int(days_rounded - 1)
#if it isn't
else:
#just round down using days_rounded
dinners = days_rounded
#calculate dinner cost
din_cost = dinners * dinnerCostPerDay
#calculate breakfasts by rounding up and subtracting by -1
if days_str[-2:] == '.0':
brekfasts = int(days - 1)
else:
brekfasts = int(days + 1) - 1
#calculate breakfasts
brek_cost = brekfasts * breakfastCostPerDay
#new variable lunch
lunch = 0
#calculate lunches through while loop that finds the total hours of the last day
while time >= 8:
#while time is larger or the same as 8 continue to subtract 8 from time's total until it no longer is above or equal to 8
time -= 8
#add to lunch
lunch += 1
#with new time.. if it is higher than 4
if time > 4:
#add to lunch
lunch += 1
#calculate lunch total cost
lun_cost = lunch * lunchCostPerDay
#calculate total cost of trip by tallying up each variable costs (gas, brek, lunch, din, hotel)
trip_cost = lun_cost + brek_cost + din_cost + hotel_price + fuel_cost
#calculate total food cost with (brek, lunch, din)
food_total = lun_cost + brek_cost + din_cost
return round(trip_cost, 2), round(fuel_cost, 2), total_hotel, lunch, round(food_total, 2)
def convertMphtoMs(mph):
'''Convert miles per hour to meters persecond'''
kmh = mph * 1.609344
meters_per_hour = kmh * 1000
#return meters per second after dividing meters per hour by 60 twice... once
#for minutes then for seconds
return (meters_per_hour / (60 ** 2))
def convertMpgtoLKm(mpg):
return mpg * 1.609344 / 3.785411784
def compareVehiclesForTrip(distanceM, veh1Name, veh1SpeedMPH, veh1MPG, veh2Name, veh2SpeedMPH, veh2MPG, gasCostPerGallon, breakfastCostPerDay, lunchCostPerDay, dinnerCostPerDay, hotelCostPerNight):
'''Convert useful info from miles and gallons to km and liters to pass into tripCostAndInfo. use that information to derive a comparison between the two cars'''
#convert distanceM (miles to km) given 1 mile == 1.60934 kms
km = distanceM * 1.609344
#convert miles pergallon to km per liter of each car
car1_KmL = convertMpgtoLKm(veh1MPG)
car2_KmL = convertMpgtoLKm(veh2MPG)
#convert speed mph to kmh
car1_ms = convertMphtoMs(veh1SpeedMPH)
car2_ms = convertMphtoMs(veh2SpeedMPH)
#convert gas cost from gallon to L
gasCostPerL = gasCostPerGallon / 3.785411784
#first car
total1, gas1, hotel_nights1, lunches1, food1 = tripCostAndInfo(km, car1_ms,
#### variables above!####
car1_KmL, gasCostPerL, breakfastCostPerDay, lunchCostPerDay, dinnerCostPerDay, hotelCostPerNight)
#second car
total2, gas2, hotel_nights2, lunches2, food2 = tripCostAndInfo(km, car2_ms,
#### variables above!####
car2_KmL, gasCostPerL, breakfastCostPerDay, lunchCostPerDay, dinnerCostPerDay, hotelCostPerNight)
print(f"{distanceM} miles in vehicle '{veh1Name}' will cost ${total1}, including:\n${round((hotel_nights1 * hotelCostPerNight), 2)} for {hotel_nights1} hotel night(s), ${gas1} for gas, ${food1} for food (including {lunches1} lunch)")
print(f"{distanceM} miles in vehicle '{veh2Name}' will cost ${total2}, including:\n${round((hotel_nights2 * hotelCostPerNight), 2)} for {hotel_nights2} hotel night(s), ${gas2} for gas, ${food2} for food (including {lunches2} lunch)")
def testQ1():
'''make at least five calls to tripCostAndInfo with different arguments'''
a,b,c,d,e = tripCostAndInfo(1000.0, 33.33, 9.408, 3.0, 5.0, 7.0, 8.0, 20.0)
print('Call 1:', a,b,c,d,e)
a,b,c,d,e = tripCostAndInfo(1050.0, 34.33, 9.408, 4.0, 5.0, 7.0, 8.0, 20.0)
print('Call 2', a,b,c,d,e)
a,b,c,d,e = tripCostAndInfo(2000.0, 33.33, 9.408, 3.0, 5.0, 7.0, 8.0, 20.0)
print('Call 3',a,b,c,d,e)
a,b,c,d,e = tripCostAndInfo(1000.0, 33.33, 10.4, 3.0, 5.0, 7.0, 8.0, 60.5)
print('Call 4', a,b,c,d,e)
a,b,c,d,e = tripCostAndInfo(1000.0, 32.33, 9.408, 2.0, 4.0, 7.0, 8.0, 27.0)
print('Call 5', a,b,c,d,e)
def testQ2():
'''make at least five calls to compareVehiclesForTrip with different arguments'''
(compareVehiclesForTrip(1000, 'ford', 45.0, 30.0, 'chevy', 60.0, 25.0, 3.0, 4.0, 5.0, 7.0, 25.0))
print()
(compareVehiclesForTrip(1000, 'chevy', 75.0, 35.0, 'tesla', 100.0, 1.0, 4.0, 4.0, 5.0, 7.0, 30.0))
print()
(compareVehiclesForTrip(1000, 'ford', 45.0, 30.0, 'chevy', 60.0, 25.0, 3.0, 4.0, 5.0, 7.0, 25.0))
print()
(compareVehiclesForTrip(1000, 'honda', 64.0, 40.0, 'toyota', 77.0, 44.0, 3.0, 4.0, 8.0, 7.0, 25.0))
print()
(compareVehiclesForTrip(1000, 'audi', 120.0, 25.0, 'bmw', 110.0, 25.0, 3.0, 4.0, 8.0, 7.0, 45.0)) |
e42364ed8430045d297604cade4e3f8048c40847 | peternortonuk/reference | /python/class/abc.py | 976 | 4.3125 | 4 | '''
https://www.python-course.eu/python3_abstract_classes.php
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared,
but contains no implementation.
Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
Subclasses of an abstract class in Python are not required to implement abstract methods of the parent class.
'''
from abc import ABC, abstractmethod
class AbstractClassExample(ABC):
def __init__(self, value):
self.value = value
super().__init__()
@abstractmethod
def do_something(self):
pass
class DoAdd42(AbstractClassExample):
def do_something(self):
return self.value + 42
class DoMul42(AbstractClassExample):
def do_something(self):
return self.value * 42
import pdb; pdb.set_trace()
x = DoAdd42(10)
y = DoMul42(10)
print(x.do_something())
print(y.do_something())
|
079047d57b63b3a7887423e3b8c60dbc2470b994 | Yihan-Dai/Leetcode-Python | /4Sum/solutionTLE.py | 1,409 | 3.84375 | 4 | '''
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
For example, given array S = {1 0 -1 0 -2 2}, and target = 0.
A solution set is:
(-1, 0, 0, 1)
(-2, -1, 1, 2)
(-2, 0, 0, 2)
'''
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
list =[]
if nums == list:
return list
nums = sorted(nums)
for i in range(len(nums)):
for k in range(i+1,len(nums)):
target1 = nums[i] + nums[k]
target2 = target -target1
m = k+1
n = len(nums) - 1
while m < len(nums):
if nums[m] + nums[n] == target2 and m != n:
list.append([nums[i],nums[k],nums[m],nums[n]])
m +=1
else:
n -=1
if n+1 == m:
m +=1
n = len(nums) -1
return list |
9639a1717b7a146d70c2671f91271a2fddf105aa | Andrespazmi/Ejercicios1-parcial | /s2 ejercicio 1.py | 225 | 3.53125 | 4 | # SEGUNDA SEMANA, PRIMER EJERCICIO
""" """ num=20
if type(num) ==int:
print("respuesta; ",num*2)
else:
print("No es numerico")
def mensaje("men")
print(men)
mensaje("Primera tarea")
mensaje("Segunda tarea ") """ |
caa3b319f92b4803b8d42057ecf2fe75eafb1aa7 | bhotw/Puzzle-Hunt | /coins3-yellow/PuzzleHunt.py | 277 | 3.875 | 4 | def reverse_caesar_shift(message, shift):
secret = ""
message = message.upper()
for letter in message:
if letter == ' ':
secret += letter
else:
secret += chr((ord(letter) - ord('A') - shift) % 26 + ord('A'))
print(secret) |
e3ffaff0b7d907b789a1b2583c36ebd76d3cc3f7 | vishipayyallore/LearningPython_2019 | /Session1/CustomModules/stringmodule.py | 410 | 3.71875 | 4 | def show_characters_v1(name):
for index in range(len(name)):
print(name[index], end=' ')
else:
print()
def show_characters_v2(name):
end_count = -1 * (len(name) + 1)
for index in range(-1, end_count, -1):
print(name[index], end=' ')
else:
print()
def show_reverse_string(data):
print(data[::-1])
def show_swapcase(data):
print(data.swapcase())
|
c68e9c8b534bb0b3447e1e0acec1077b915a65ba | mlitfin123/AmeritradeTradingApp | /env/Lib/site-packages/btalib/indicators/mfi.py | 1,732 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
# Copyright (C) 2020 Daniel Rodriguez
# Use of this source code is governed by the MIT License
###############################################################################
from . import Indicator, sumn
class mfi(Indicator):
'''
Created by Gene Quong and Avrum Soudack to identify buying/selling
pressure by combining price and volume in the calculation.
Pressure is positive if the (typical) price increases and negative if it
decreases. The volume is the weight factor for how much pressure is being
exercised on the asset.
Formula:
- tp = typical_price = (high + low + close) / 3
- money_flow_raw = tp * volume
- flow_positive = Sum(money_flow_raw * (tp > tp(-1)), period)
- flow_netagive = Sum(money_flow_raw * (tp < tp(-1)), period)
- money_flow_ratio = flow_positive / flow_negative
- mfi 100 - 100 / (1 + money_flow_ratio)
See:
- https://school.stockcharts.com/doku.php?id=technical_indicators:money_flow_index_mfi
- https://www.investopedia.com/terms/m/mfi.asp
'''
group = 'momentum'
alias = 'MFI', 'MoneyFlowIndicator'
inputs = 'high', 'low', 'close', 'volume'
outputs = 'mfi'
params = (
('period', 14, 'Period to consider'),
)
def __init__(self):
tprice = (self.i.high + self.i.low + self.i.close) / 3.0
mfraw = tprice * self.i.volume
flowpos = sumn(mfraw * (tprice > tprice(-1)), period=self.p.period)
flowneg = sumn(mfraw * (tprice < tprice(-1)), period=self.p.period)
self.o.mfi = 100.0 - 100.0 / (1.0 + (flowpos / flowneg))
|
3f6b4352c9960a316745d25cc88dc3da11a05b34 | trippieiv/escaperoom | /map.py | 5,432 | 3.734375 | 4 | from items import *
room_cupboard = {
"name": "Cupboard",
"description":
"""You are currently stuck in a cupboard on the second floor of
a strange house. Your challenge is to overcome the obstacles and get
out of the house. The cupboard has an exit to the east and some wired
coat hangers in the corner of the room.""",
"exits": {"east": ["Bedroom", False]},
"items": [item_hanger]
}
room_bedroom = {
"name": "Bedroom",
"description":
"""You are standing in the middle of a bedroom. There is an exit to
the west which leads you back into the cupboard. To the south is another
door which cannot be opened. The exit to the east leads to what looks like
an ensuite bathroom, this door is also locked. With the right tools this door can
be picked.""",
"exits": {"west": ["Cupboard", False] , "east": ["Bathroom", True, item_hanger],
"south": ["Upstairs corridor", True, item_null]},
"items": [item_lamp, item_guitar, item_rug]
}
room_bathroom = {
"name": "Bathroom",
"description":
"""You are now in a dirty bathroom. There is a sign on the tiled wall that says
KEEP THIS BATHROOM CLEAN OR ELSE! West leads back to the bedroom. The exit to the south
is an exit into a corridor.""",
"exits": {"west": ["Bedroom", False], "south": ["Upstairs corridor", True, False]},
"items": [item_sign, item_medicine, item_mirror, item_soap, item_toothbrush, item_mop]
}
room_corridor = {
"name": "Upstairs corridor",
"description":
"""You are now in the middle of the upstairs corridor. The exit to the south
is a flight of stairs going down. However, there is a dalmatian patterned stair gate
with a four lettered lock code. You also wish that there is a cute dalmation dog somewhere
to comfort you. The code to the stair gate could be somewhere in the
corridor. The exit to the north leads back to the bedroom; to the
east there is a door to a study but it is only accessible using a smart card. There is a
photo on the wall next to a poster. There is also a really cute dog painting on the wall,
the longer you stare at the painting the more happy you become.""",
"exits": {"east": ["Study", True, item_id], "south": ["Stairs", True, "abra"],
"north": ["Bedroom", True, item_null]},
"items": [item_painting, item_poster, item_photo, item_gate]
}
room_study = {
"name": "Study",
"description":
"""You have now gained access to the study. The walls are lined with book shelves,
you see alot of books named 'Java Puns', you are definitely better off not reading them. There
is a large desk in the centre of the room. The exit to the west leads back to the
upstairs corridor.""",
"exits": {"west": ["Upstairs corridor", False]},
"items": [item_notepad, item_key, item_folders, item_books]
}
room_stairs = {
"name": "Stairs",
"description":
"""You are on the fluffy carpeted stairs. You can go north back to the
upstairs corridor or south to the eerie downstairs hallway.""",
"exits": {"north": ["Upstairs corridor", False], "south": ["Hallway", False]},
"items": []
}
room_kitchen = {
"name": "Kitchen",
"description":
"""You are now in a kitchen. You are especially annoyed by the dirty
plates left on the breakfast bar, also why is there a crowbar here? You can
go east to return to the hallway. The exit to the south leads to a dining room
and is currently jammed.""",
"exits": {"south": ["Dining room", True, item_crowbar], "east": ["Hallway", False]},
"items": [item_crowbar, item_plates]
}
room_dining = {
"name": "Dining Room",
"description":
"""You are now in a dining room. There is a alienware laptop on
the dining room table. Alienware? You think to yourself who in their
right mind would purchase that overpriced #£$%. There is also a pretty vase of flowers,
whoever picked those has good taste. The exit to the north leads back to the kitchen.""",
"exits": {"north": ["Kitchen", False]},
"items": [item_laptop, item_flowers]
}
room_living = {
"name": "Living Room",
"description":
"""You are currently in a living room. There is one large corner sofa, a TV and
a coffee table. The coffee table has an ID card and a cold cup of tea left on it.
There is only one exit which is to the west and returns you to the hallway.""",
"exits": {"west": ["Hallway", True, item_id]},
"items": [item_id, item_tea]
}
room_hallway = {
"name": "Hallway",
"description":
"""You are now in the downstairs hallway. There is an exit to the west which
leads to the living room. The exit to the east leads to the kitchen and
south there is the front door. However, the front door is locked and cannot be
opened without a key.""",
"exits": {"east": ["Living room", False], "west": ["Kitchen", False],
"south": ["Exit", True, item_key], "north": ["Stairs", False]},
"items": []
}
room_exit = {
"name": "Exit",
"description":
"""CONGRATULATIONS
You escaped the house!""",
"exits": {},
"items": [item_freedom]
}
rooms = {
"Cupboard": room_cupboard,
"Bedroom": room_bedroom,
"Bathroom": room_bathroom,
"Upstairs corridor": room_corridor,
"Study": room_study,
"Stairs": room_stairs,
"Kitchen": room_kitchen,
"Living room": room_living,
"Dining room": room_dining,
"Hallway": room_hallway,
"Exit": room_exit
}
|
83ad02261c6d5f4a9624b87da203cae7764f48e8 | RazvanKokovics/Planes | /imports/queue.py | 638 | 3.84375 | 4 | class Queue:
def __init__(self):
#initializes a a queue data structure
self._data = []
def push(self, item):
#function that pushes an item in the queue
self._data.append(item)
def pop(self):
#function that pops an item from the queue
#it returns the first element from the queue and it deletes it
if len(self._data) == 0:
return None
return self._data.pop(0)
def size(self):
#returns the size of the queue
return len(self._data)
def clear(self):
#clears the queue
self._data.clear()
|
bd628ebfebd7c0455aca4a593c189c50a998e522 | MarehanRefaat/HackerRank_Solutions | /10 Days of Statistics/Day 7: Spearman's Rank Correlation Coefficient/solution.py | 350 | 3.515625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
x = [float(i) for i in input().strip().split(" ")]
y = [float(i) for i in input().strip().split(" ")]
x_s = sorted(list(x))
y_s = sorted(list(y))
d = ([(x_s.index(x[i])-y_s.index(y[i]))**2 for i in range(n)])
res = 1-6*sum(d)/(n*(n**2-1))
print("%.3f"%res)
|
510466c5c4fa8c7efc5420cf51e83bb46d313682 | aynulislam/python_basic_covid_19 | /day6 part1.py | 1,976 | 3.96875 | 4 | #1 two dimensonal list
matrix = [
[10,20,30],
[12,16,18],
[15,25,35],
]
print(matrix[0][0])
print(matrix[1][2])
print(matrix[2][1])
for row in matrix:
for item in row:
print(item)
#practice
mat = [
[1,2,3,],
[2,3,4,],
[4,5,6],
]
for a in mat:
for b in a:
print(b)
#2
numbers = [1,2,3,4,6,7,8,9]
print(numbers)
numbers.append(30) #insert item in last index
print(numbers)
numbers.insert(0,10) #insert new item in specific index
print(numbers)
numbers.sort() #sort the list
print(numbers)
numbers.remove(30) #remove specific item
print(numbers)
numbers.pop() #remove last item of a list
print(numbers)
print(numbers.count(5)) #count how many times 5 in the list
numbers.count(100) #count the all item in the list by key words
print(numbers)
print(numbers.index(2)) #print the specific index number by his keywords item
numbers.reverse() #reverse all item in the list
print(numbers)
numbers_2 = numbers.copy() #copy the full list in new list
print(numbers_2)
numbers.clear() #remove all items in a list
print(numbers)
new_list = [ 'tamjid', 'islam', 'naim', 'hasan'] #print the specific index number by his keywords item
print(new_list.index('hasan'))
#3 remove duplicate item in the list
numbers = [2,2,4,5,6,7,7,8,11,3,4,7,9]
null_list = []
for number in numbers:
if number not in null_list:
null_list.append(number)
print(null_list)
#practice
ages = [10,20,11,20,17,18,30,35,20,10,35,18]
null_age = []
for age in ages:
if age not in null_age:
null_age.append(age)
print(null_age)
null_age.sort()
print(null_age)
#tuples
#tuples have only two method count and index
numbers = (10,10,1,20,20,20,30)
print(numbers.count(20))
print(numbers.index(10))
#unpacking tuple,list
coordinates = (10,12,20)
x = coordinates[0]
y = coordinates[1]
z = coordinates[2]
print(x * y * z)
x,y,z = coordinates
print(x*y*z)
coordinates_1 = [10,20,30]
x,y,z = coordinates_1
print(x+y+z)
|
49b6025ab39e528242d36336c8bebdc0f94cdd8c | andrecontisilva/Python-aprendizado | /diversos/PythonLogic.py | 1,128 | 4.25 | 4 | # Questão 1
# A lógica abaixo é um exemplo de sequência de Fibonacci.
# A questão queria saber qual seria o resultado de print(f(10)) [== 55]
# Mais detalhes em: http://www.devfuria.com.br/logica-de-programacao/recursividade-fibonacci/
"""
def f(i):
if i == 1 or i == 2:
return 1
return f(i-1) + f(i-2)
print(f(10))
"""
#Questão 2
"""
frutas = ["banana", "laranja", "manga", "uva"]
for k in range(-1, -4, -2):
print(frutas[k])
print("\n") # Só pra pular linha para deixar o teste abaixo mais legível:
print(frutas[-4])
"""
# Questão 3
# A lógica é um exemplo de cálculo Fatorial, neste caso 4! = 24
# (isto é, 4! = 4 x 3 x 2 x 1 = 24)
# Exemplos em: http://www.devfuria.com.br/logica-de-programacao/recursividade-fatorial/
"""
def foo(n):
if n > 1:
return n * foo(n-1)
return n
print(foo(4))
"""
# Questão 4
# Exemplo de troca de posições de variáveis.
# A questão queria a resposta do 'print(a)' [cujo resultado é 6].
# Ou seja, a = 3 e b = 6, porém, em a, b = b, a, ambos trocam de posição [a = 6 e b = 3]
"""
a = 3
b = a * 2
a, b = b, a
print(a)
print(b)
"""
|
92eb8575fde4b4525216c76823db8b4245ca0072 | manucirne/camadaFcomp | /4.HandShake2/enlaceTx.py | 4,419 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#####################################################
# Camada Física da Computação
#Carareto
#17/02/2018
# Camada de Enlace
####################################################
# Importa pacote de tempo
import time
# Threads
import threading
# Class
class TX(object):
""" This class implements methods to handle the transmission
data over the p2p fox protocol
"""
def __init__(self, fisica):
""" Initializes the TX class
"""
self.fisica = fisica
self.buffer = bytes(bytearray())
self.transLen = 0
self.empty = True
self.threadMutex = False
self.threadStop = False
def thread(self):
""" TX thread, to send data in parallel with the code
"""
while not self.threadStop:
if(self.threadMutex):
Tinicio = time.time()
self.transLen = self.fisica.write(self.buffer)
#print("O tamanho transmitido. IMpressao dentro do thread {}" .format(self.transLen))
self.threadMutex = False
Tfinal = time.time()
deltaT = (Tfinal - Tinicio)
txLen = len(self.buffer)
baudrate = 115200
print("-------------------------")
print("Tempo Esperado: ", (10)*txLen/baudrate,"s")
print("Tempo Medido: ", deltaT,"s")
print("-------------------------")
def threadStart(self):
""" Starts TX thread (generate and run)
"""
self.thread = threading.Thread(target=self.thread, args=())
self.thread.start()
def threadKill(self):
""" Kill TX thread
"""
self.threadStop = True
def threadPause(self):
""" Stops the TX thread to run
This must be used when manipulating the tx buffer
"""
self.threadMutex = False
def threadResume(self):
""" Resume the TX thread (after suspended)
"""
self.threadMutex = True
def sendBuffer(self, data):
""" Write a new data to the transmission buffer.
This function is non blocked.
This function must be called only after the end
of transmission, this erase all content of the buffer
in order to save the new value.
"""
self.transLen = 0
self.buffer = data
self.threadMutex = True
def getBufferLen(self):
""" Return the total size of bytes in the TX buffer
"""
return(len(self.buffer))
def getStatus(self):
""" Return the last transmission size
"""
#print("O tamanho transmitido. Impressao fora do thread {}" .format(self.transLen))
return(self.transLen)
def getIsBussy(self):
""" Return true if a transmission is ongoing
"""
return(self.threadMutex)
def empacotamento(txBuffer, txLen, end, stuffing, tipo):
if (tipo == 1) or (tipo == 2) or (tipo == 3):
txBuffer = bytes(1)
if (tipo == 4):
for i in range(txLen):
if txBuffer[i] == end[0]:
if txBuffer[i+1] == end[1]:
if txBuffer[i+2] == end[2]:
if txBuffer[i+3] == end[3]:
if txBuffer[i+4] == end[4]:
zero = bytes([txBuffer[i-1]])
s = bytes([txBuffer[i+5]])
if (bytes([txBuffer[i-1]]) != stuffing) or (bytes([txBuffer[i+5]]) != stuffing):
txBuffer = txBuffer[:i] + stuffing + end + stuffing + txBuffer[i+5:]
txLen = len(txBuffer)
print("txLen: ",txLen)
tamanhoEmByte = (txLen).to_bytes(2,byteorder='big')
vazio = bytes(5)
tipo = bytes([tipo])
head = vazio + tipo + tamanhoEmByte
payload = txBuffer
txBuffer = head + txBuffer + end
overhead = len(payload)/len(txBuffer)
#throughput = payload/deltaT
print("-------------------------")
print("OverHead: ", overhead, "%")
print("Tipo: ", tipo)
#print("Throughput: ", throughput,"bytes/s")
print("Head: ",head)
print("Stuffing: ",stuffing)
print("EOF: ",end)
print("-------------------------")
return txBuffer
|
5f7b5df87fad52417dd75b0582af9633bf5f3825 | qmnguyenw/python_py4e | /geeksforgeeks/python/python_all/101_15.py | 2,739 | 4.46875 | 4 | Python | Index Maximum among Tuples
Sometimes, while working with records, we might have a common problem of
maximizing contents of one tuple with corresponding index of other tuple. This
has application in almost all the domains in which we work with tuple records.
Let’s discuss certain ways in which this task can be performed.
**Method #1 : Usingmap() + lambda + max()**
Combination of above functionalities can solve the problem for us. In this, we
compute the maximum using lambda functions and max() and extend the logic to
keys using map().
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Index Maximum among Tuples
# using map() + lambda + max()
# initialize tuples
test_tup1 = (10, 4, 5)
test_tup2 = (2, 5, 18)
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
# Index Maximum among Tuples
# using map() + lambda + max()
res = tuple(map(lambda i, j: max(i, j), test_tup1,
test_tup2))
# printing result
print("Resultant tuple after maximization : " + str(res))
---
__
__
**Output :**
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (2, 5, 18)
Resultant tuple after maximization : (10, 5, 18)
**Method #2 : Usingmap() + zip() + max()**
The combination of above functions can also be used to achieve this particular
task. In this, we add inbuilt max() to perform maximization and zip the like
indices using zip() and extend logic to both tuples using map().
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Index Maximum among Tuples
# using map() + zip() + max()
# initialize tuples
test_tup1 = (10, 4, 5)
test_tup2 = (2, 5, 18)
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
# Index Maximum among Tuples
# using map() + zip() + max()
res = tuple(map(max, zip(test_tup1, test_tup2)))
# printing result
print("Resultant tuple after maximization : " + str(res))
---
__
__
**Output :**
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (2, 5, 18)
Resultant tuple after maximization : (10, 5, 18)
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
|
ccc478a11489932987c21ab38cf3577104cac1b3 | wangrui0/python-base | /com/day07/demo03_local_global_variable_diff.py | 1,066 | 3.6875 | 4 | '''
局部变量
def get_wendu(): # 如果一个函数有返回值,但是没有在调用函数之前 用个变量保存的话,那么没有任何的意义
wendu = 33
return wendu
def print_wendu(wendu):
print("温度是:%d" % wendu)
result = get_wendu()
print_wendu(result)
'''
# 定义一个全局变量
temperature = 0
# def get_temperature():
# temperature = 33 # 注意这只是新定义了一个局部变量
def get_temperature():
global temperature
temperature = 33
def print_temperature():
print("温度是:%d" % temperature)
get_temperature()
print_temperature()
# 如果temperature这个变量已经在全局变量的位置定义了,此时还想在函数中对这个全局变量进行修改的话
# 那么 仅仅是 temperature=一个值 这还不够,,,此时temperature这个变量是一个局部变量,仅仅是和全局变量的名字
# 相同罢了
# 使用global用来对一个全局变量的声明,那么这个函数中的temperature=33就不是定义一个局部变量,而是
# 对全局变量进行修改
|
de4a44dfc75940f4aa74634d41b7af393fad3f91 | PiJoules/Kalman-Filter | /kalman.py | 4,289 | 3.703125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy
class KalmanFilterLinear(object):
"""
Class modelling a linear Kalman Filter.
Linear because all the matrices used are constant and do not change
over time.
Equations
State prediciton:
Get our prediction of the next state given the last state (x_last) and
control vector (u). The control vector represents tracked external
influences to the system unrelated to the state itself
(ex: gravity/wind acting on a ball that was thrown.)
x_predicted = A * x_last + B * u
Covariance prediction:
Get our predicted error of the next state of the system given the last
state error (P_last) and estimated error covariance (Q). Q is
essentially the spread of noise in a system caused by untrcked
influences.
P_predicted = A * P_last * A_transposed + Q
Innovation:
Get how much different our prediction of the next state (x_predicted)
is from the measurement from sensors (z_n).
y = z_n - H * x_predicted
Innovation covariance:
Get predicted measurement error covariance given the last state error
covariance (P_predicted) and estimated measurement error
covariance (R). This is essentially the uncertainty caused by
errors in the sensors.
S = H * P_predicted * H_transposed + R
Kalman gain:
How much the state should be changed from the differences in
measurement given the predicted covariance (P_predicted) and
innovation covariance (S).
K = P_predicted * H_transposed * S_inverse
State update:
Update the next estimate of the state from the prediction
(x_predicted), the Kalman Gain (K), and innovation (y).
x = x_predicted + K * y
Covariance update:
Update the next estimate of the error from the prediction
(P_predicted) and the Kalman Gain (K)
P = (I - K * H) * P_predicted
Matrices (these are provided beforehand)
A:
State transition matrix.
Matrix for predicting the next state of a system in the next time step
from the previous state.
B:
Control matrix.
Matrix for predicting the next state of a system from a control vector.
H:
Observation matrix.
Matrix used for converting state values to measurement values.
For example, if we want to keep track of our position, velocity, and
acceleration, but our measurements are lat/lng coords, to compare
against the lat/lng measured by GPS, we will need to convert our
predicted pos, vel, and acc to lat/lng.
(H: pos, vel, acc => lat, lng)
Q:
Estimated process error covariance.
Covariance from untracked external influences outside of the system.
R:
Estimated process error covariance.
Covariance from uncertainty in the sensors getting the measurements.
"""
def __init__(self, A, B, H, x_init, P_init, Q, R):
self._A = A # State transition matrix
self._A_transposed = numpy.transpose(A)
self._B = B # Control matrix
self._H = H # Observation matrix
self._H_transposed = numpy.transpose(H)
self._x = x_init # State estimate
self._P = P_init # Covariance estimate
self._Q = Q # Estimated error in process
self._R = R # Estimated error in measurements
@property
def state_estimate(self):
"""Current state of the system (x)."""
return self._x
def update(self, control, measurement):
"""
Update the state + covariance from a new control vector
and measurement vector.
"""
# Prediction
x_predicted = self._A * self._x + self._B * control
P_predicted = self._A * self._P * self._A_transposed + self._Q
# Observation
innovation = measurement - self._H * x_predicted
innovation_P = self._H * P_predicted * self._H_transposed + self._R
# Update
K = P_predicted * self._H_transposed * numpy.linalg.inv(innovation_P)
self._x = x_predicted + K * innovation
size = K.shape[0]
self._P = (numpy.eye(size) - K * self._H) * P_predicted
|
68b9be7ceec2689ea655889b2f44bbef01ce0b6e | TrevorMorrisey/Project-Euler | /Python/pe004.py | 806 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 12 21:27:46 2019
@author: TrevorMorrisey
"""
def isPalindrome(string):
if len(string) == 1 or len(string) == 0:
return True
elif len(string) == 2:
return string[0] == string[1]
else:
if string[0] != string[len(string) - 1]:
return False
else:
return isPalindrome(string[1:len(string) - 1])
def largestPalindromeProduct(maxFactor):
highestSum = 0
for i in range(maxFactor + 1):
for j in range(maxFactor + 1):
currentSum = i * j
if isPalindrome(str(currentSum)):
if currentSum > highestSum:
#print('New highest sum:' + str(currentSum))
highestSum = currentSum
return highestSum
|
4de755ac11e20074407d339475cc1fcb2c4d83fd | Alireza-IT/python-practice | /jadi/4.sheygaraei ersbari.py | 725 | 4.03125 | 4 | class Computer:
count = 0 # moshtarke va age taghiri az taraf ye objecti ru in beshe bara hame avaz mishe
def __init__(self, ram, hard, cpu):
Computer.count += 1
self.ram = ram
self.hard = hard
self.cpu = cpu
def value(self):
return self.ram + self.hard + self.cpu
def __del__(self): # harmoqe ino delte kardi in etefagha biofte
Computer.count -= 1
class Loptop(Computer):
# //inherit form computer
def value(self):
return self.ram + self.hard + self.cpu + self.size
pass
pc1 = Computer(12, 2, 4)
pc2 = Computer(8, 4, 4)
print(pc1.value())
print(pc2.value())
loptop1 = Loptop(16, 2, 4)
loptop1.size = 13
print(loptop1.value())
|
8a0ff01a6eaceb990f41d03c4f11c79ccb315274 | j2woong1/algo-itzy | /SWEA/implementation/1974-스도쿠_검증/1974-스도쿠_검증-yeonju.py | 1,559 | 3.5 | 4 | def check_square(v):
x, y = v
box = [0] * 10
box[0] = 1
for i in range(3): # 3 x 3 박스 안에 1~9 모두 있나 확인
for j in range(3):
box[arr[x+i][y+j]] = 1
res = 1
for i in box:
if i != 1:
res = 0
break
return res
def check_vertical(v2):
x,y = v2 # 0,i
box2 = [0] * 10
box2[0] = 1
for i in range(9):
box2[arr[x+i][y]] = 1
res = 1
for i in box2:
if i != 1:
res = 0
break
return res
def check_horizontal(v2):
x,y = v3 # i,0
box3 = [0] * 10
box3[0] = 1
for i in range(9):
box3[arr[x][y+i]] = 1
res = 1
for i in box3:
if i != 1:
res = 0
break
return res
t = int(input()) # 테스트 케이스 개수 T
for tc in range(t):
arr = [list(map(int, input().split())) for _ in range(9)] # 리스트에 스도쿠 값들 입력 받기
total = 0
for i in range(3): # 3x3 의 맨 위 왼쪽 원소들을 따로 빼와서, check() 함수에 넣기
for j in range(3):
v = [3*i, 3*j]
total += check_square(v)
for i in range(9): # 세로로 체크
v2 = [0,i]
total += check_vertical(v2)
for i in range(9): # 가로로 체크
v3 = [i,0]
total += check_horizontal(v3)
if total ==27:
answer = 1
else:
answer = 0
print(f'#{tc+1} {answer}')
|
962316774571f4d0c226d0d2a7f3396effd86bc2 | JEmbry2019/Tuesday_Python_Project | /jeopardy.py | 823 | 3.59375 | 4 | import csv
with open('jeop_question.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file, delimiter='\t')
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
line_count += 1
else:
for row in csv_reader:
print(row) # added code to change appearence.
# print(f'\t{",".join(row)}.')
# line_count += 1
# print(f'Processed {line_count} lines.')
# CSV to a Dictionary and print
data = csv.DictReader(open("jeop_question.csv"))
print("CSV file as a dictionary-------------------------------------------------------------------------------:\n")
for row in data:
print(row)
for row in data:
print(row[''], row['department_name'], row['manager_id']) |
39e35e08489f33de16460f38649eb204bee63ce4 | vimleshtech/python-tutorial | /Sandbox/Python-Handson/GUI/8-Combo.py | 147 | 3.53125 | 4 | from tkinter import *
window = Tk()
combo = Combobox(window)
combo['values']= (1, 2, 3, 4, 5, "Text")
combo.current(3)
combo.grid(column=0, row=0)
|
4acdc3e8e4eb5729895781be3d52aeaca8f9cc9c | MD-AZMAL/python-programs-catalog | /questions/Trees/binary-trees/delete-tree.py | 251 | 3.6875 | 4 | """Author - Sidharth Satapathy"""
# Problem 9
# Assuming that the tree has getData(), setData(), getLeft(), getRight()
# Deleting a tree
def deleteTree(root):
if root is None:
return
deleteTree(root.left)
deleteTree(root.right)
del root |
47acb894929cd25c7a6fee22bacaa4a2a93935ad | dotchetter/RobBotTheRobot | /source/menu.py | 2,232 | 3.6875 | 4 | from datetime import datetime
from weekdays import Weekdays
"""
Details:
2019-11-24
Module details:
Lunch menu scraping feature
Synposis:
Provide a way for the chatbot to scrape
the lunch menu for the restaurant in school.
Return the menu scraped off the website.
"""
class Menu:
"""
Represent a menu in the form of a dictionary.
The dictionary is formatted in weekday format,
where 0 is monday and 4 is friday. 5 and 6
are present, but will remain empty since the
restaurant is closed. This will return None when
queried. Each value under said keys are lists
which will contain strings that are the menu
items for the given day.
"""
def __init__(self, soup = []):
self.soup = soup
self._weekly_menu = {
'måndag': [],
'tisdag': [],
'onsdag': [],
'torsdag': [],
'fredag': []
}
self._index_lookup = {
0: self._weekly_menu['måndag'],
1: self._weekly_menu['tisdag'],
2: self._weekly_menu['onsdag'],
3: self._weekly_menu['torsdag'],
4: self._weekly_menu['fredag'],
5: None,
6: None
}
self.creation_date = datetime.today().date()
self._serialize()
def __getitem__(self, index):
if isinstance(index, slice):
start, stop, step = index.indices(len(self._weekly_menu))
return tuple(self[i] for i in range(start, stop, step))
try:
item = self._index_lookup[index]
except Exception as e:
raise Exception(e)
return item
def _serialize(self):
"""
Iterate over the HTML content found in the
soup object received. Look for the weekday
markers, denoted by the keys in the
"""
selected_weekday = None
for html in self.soup:
if html.text.lower() in self._weekly_menu:
selected_weekday = html.text.lower()
continue
if selected_weekday:
self._weekly_menu[selected_weekday].append(html.text.lower())
@property
def creation_date(self):
return self._creation_date
@creation_date.setter
def creation_date(self, value):
self._creation_date = value
@property
def soup(self):
return self._soup
@soup.setter
def soup(self, value):
self._soup = value
@property
def weekly_menu(self):
return self._daily_menu
@weekly_menu.setter
def weekly_menu(self, value):
self._daily_menu = value
|
051bfcb3cfc4b31b506f9b0d26b7f0840745a01d | simnyatsanga/pandas-sklearn | /playing-with-pandas.py | 1,440 | 3.625 | 4 | import numpy as np
import pandas as pd
from pandas import DataFrame
import datetime
import pandas.io.data
import matplotlib.pyplot as plt
import sklearn
cars_df = pd.read_csv('ToyotaCorolla.csv')
print cars_df.shape
print cars_df.head()
cars_df['FuelType1'] = np.where(cars_df['FuelType'] == 'CNG', 1 , 0)
cars_df['FuelType2'] = np.where(cars_df['FuelType'] == 'Diesel', 1 , 0)
cars_df.drop('FuelType', axis=1, inplace=True)
#Scatter plotting two variables
plt.scatter(cars_df.KM, cars_df.Price)
plt.xlabel("Age")
plt.ylabel("Price")
plt.show()
#Pulling data from Yahoo finance
#sp500 = pd.io.data.get_data_yahoo('%5EGSPC', start = datetime.datetime(2000, 10, 1), end = datetime.datetime(2016, 8, 5))
# Reading csv into dataframe and setting date to be the intuitive x-axis when plotting more than variable
# df = pd.read_csv('sp500.csv', index_col = 'Date',parse_dates = True)
# Difference between columns
# df['H-L'] = df['High'] - df.Low
# Adding rolling mean column to the df using Close column
# df['100MA'] = pd.rolling_mean(df['Close'], 100, min_periods=1)
#
# Calculating standard deviation
# df['STD'] = pd.rolling_std(df['Close'], 25, min_periods=1)
# Correlation between variables. Useful to get insights on variables that maybe dependent on each other
# print df[['Volume', 'H-L']].corr()
#
# 2D Plotting several columns
# correllationComp[['AAPL', 'MSFT', 'TSLA', 'EBAY', 'SBUX', 'AAPL_Multi']].plot()
# plt.show()
|
2fb99cad816dc94df31676d9bd54c7dfecf101fa | juliencampus/python | /Denis/CalculTVA2/main.py | 1,546 | 3.890625 | 4 | # This is a sample Python script.
# Press Maj+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import math
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
def askName():
return input("Nom du produit ?")
def askTaxe():
taxe = float(input("Taxe à mettre en place ?"))
return round(taxe)
def askPrice():
return float(input("Prix du produit ?"))
def askStock():
return int(input("Stock du produit ?"))
def ttc(taxe, price):
return (((taxe / 100) * price) + price)
def ttcStock(totalPrice, stock):
return totalPrice * stock
def main():
nameProduit = askName()
priceProduit = askPrice()
taxe = askTaxe()
stock = askStock()
totalPriceTaxe = ttc(taxe, priceProduit)
totalPriceStock = ttcStock(totalPriceTaxe, stock)
print("Le produit", nameProduit, " qui coute", priceProduit, "avec", taxe, "% de taxe, revient à", totalPriceTaxe, "€")
if(totalPriceStock < 1000):
print("Le total des produits en stock est de", totalPriceStock, "€")
else:
print("Le total des produits en stock est de", totalPriceStock, "€ avec 12% de remise soit", totalPriceStock - (totalPriceStock * float(12/100)))
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
main()
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
2454bcd7025cdc5e16d91910c45e1532be959e89 | acondorba/Practicas---Python | /Problemas Python/Módulo 4/scripts/Problemas_Diversos.py | 3,316 | 3.859375 | 4 | print('Parte 1')
n = int(input('Introduce un número entero entre 1 y 10: '))
file_name = 'tabla-' + str(n) + '.txt'
f = open(file_name, 'w')
for i in range(1, 11):
f.write(str(n) + ' x ' + str(i) + ' = ' + str(n * i) + '\n')
f.close()
print('---------------------------------------------------------------------')
print('Parte 2')
n = int(input('Introduce un número entero entre 1 y 10: '))
file_name = 'tabla-' + str(n) + '.txt'
try:
f = open(file_name, 'r')
except FileNotFoundError:
print('No existe el fichero con la tabla del', n)
else:
print(f.read())
print('---------------------------------------------------------------------')
print('Parte 3')
n = int(input('Introduce un número entero entre 1 y 10: '))
m = int(input('Introduce otro número entero entre 1 y 10: '))
file_name = 'tabla-' + str(n) + '.txt'
try:
f = open(file_name, 'r')
except FileNotFoundError:
print('No existe el fichero con la tabla del ', n)
else:
lines = f.readlines()
print(lines[m - 1])
print('---------------------------------------------------------------------')
print('Expresiones Regulares')
from modulo import datos
import re
path = './data/re/short_tweets.csv'
s = '@robot9! @robot4& I have a good feeling that the show isgoing to be amazing! @robot9$ @robot7%'
s
patron = r"@robot\d\D"
print(re.findall(patron, s))
print('---------------------------------------------------------------------')
# Cadena entrada
s = "Unfortunately one of those moments wasn't a giant squid monster. User_mentions:2, likes: 9, number of retweets: 7"
s
patron = r"User_mentions:\d"
patron2= r"likes:\s\d"
patron3= r"number of retweets:\s\d"
print("Los usuarios que sigues este patron son: User_mentions:",(re.findall(patron, s)))
print("El número de likes es:",(re.findall(patron2, s)))
print("El numero de retweets",(re.findall(patron3, s)))
print('---------------------------------------------------------------------')
import re
path = './data/re/short_tweets.csv'
analisis_sentimientos = datos.read_pandas(path,780,782)
regex = r"\w+.txt" # complete aqui
for tweet in analisis_sentimientos:
print (re.findall(regex, tweet))
#print(tweet)
#Encuentre todos los casos
#print(re.findall(regex, tweet))
#print (re.findall(regex, tweet))
#regex = r"" # complete aqui
for tweet in analisis_sentimientos:
print(tweet)
# Encuentre todos los casos
#print(re.findall(regex, tweet))
print('---------------------------------------------------------------------')
import re
regex = r"\w+[._]\w+[._]\w+@\w+.com"
regex2 = r"\w+@\w+.com"
emails = ['[email protected]', '[email protected]', '!#[email protected]']
for example in emails:
# Match the regex to the string
if re.match(regex, example):
# Complete the format method to print out the result
#x= r"\[email protected]"
#print("La direccion de correo es valida",(re.findall(patron,x)))
print("The email {email_example} is a valid email".format(email_example=example))
elif re.match(regex2, example):
print("The email {email_example} is a valid email".format(email_example=example))
else:
print("The email {email_example} is invalid".format(email_example=example))
|
446b1c03eed13eebab18936d42dec354eb3ccd38 | Nicortiz72/ICPC_AlgorithmsProblems | /uva/846.py | 522 | 3.546875 | 4 | from sys import *
Sumatory=[0,1]
Values=[0,1]
n=3
i=2
lim=1<<31
while n<=lim:
Sumatory.append(n)
Values.append((2*Sumatory[i//2])+(0 if i%2==0 else (i//2)+1))
i+=1;n+=i
def binarySearch(k):
low=0;high=len(Values)
while low+1!=high:
mid=(low+high)>>1
if(Values[mid]==k): return mid
elif(Values[mid]>k): high=mid
else: low=mid
return high
def main():
t=int(stdin.readline())
for _ in range(t):
f,s=[int(x) for x in stdin.readline().split(" ")]
print(binarySearch(s-f))
main() |
4a6d72ec79d83d3cd098a8c03b719c90c8bcddb5 | IgnacioLoria1995/cursoPythonTest | /ejercicioII-test.py | 956 | 3.953125 | 4 | #Ejercicio II-test
#personas = int(input('Cuantas personas desea registrar?: '))
#while personas <1 or clientes >120:
# personas = int(input('Cuantas personas desea registrar?: '))
# print('Perfecto, iniciando proceso')
#else:
# print('Numero no valido de personas')
clientes = int(input('Ingrese numero de clientes entre 1 y 120: '))
while clientes <1 or clientes >120:
clientes = int(input('Ingrese numero de clientes entre 1 y 120: '))
else:
for i in range(clientes):
nombre = input('Ingrese nombre: ')
apellido = input('Ingrese apellido: ')
edad = int(input('Ingrese edad: '))
if edad < 18:
condicion_edad = 'menor'
elif edad < 65:
condicion_edad = 'mayor'
elif edad < 120:
condicion_edad = 'jubilado'
else:
condicion_edad = 'fallecido'
print('Su nombre es: '+nombre+' '+apellido+' '+'Y usted es '+condicion_edad)
|
6a764fd49bb0b8173adf004d9b5177b6145c5653 | liukai234/python_course_record | /函数和lambda表达式/lambda表达式.py | 1,494 | 4.28125 | 4 | '''
lambda表达式:lambda [parameter_list] : 表达式
语法格式要点:1、必须要lambda关键字来定义
2、lambda之后、冒号左边是参数列表,可以没有参数或者多个参数,右边是表达式的返回值
3、只能是单行表达式,本质上是匿名的、单行函数体
'''
# lambda表达式代替局部函数
def get_math_func(type):
'''
def square(n): # 求平方
return n*n
def cube(n): # 求立方
return n * n * n
def sum(n): # 求1+2+3+...+n
return (1 + n) * n / 2
'''
if type == 'square':
return lambda n: n * n
# return square
if type == 'cube':
return lambda n: n * n * n
# return cube
if type == 'sum':
return lambda n: (1 + n) * n / 2
# return sum
def test():
# 返回一个嵌套函数
math_func=get_math_func('cube')
print(math_func(5))
# lambda 表达式调用内置函数map()
x = map (lambda x: x * x if x % 2 == 0 else 0 , range(10))
print([y for y in x])
# [注]
# 刘润凤 19:36:14
# map() 会根据提供的函数对指定序列做映射
# 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表
# 刘润凤 19:39:03
# lambda写的单行函数:后边的表达式用了三目运算,如果是偶数,返回值就是 x*x,是奇数返回值为0 |
b083f970fb35d2aacb1c4f2d4cb6c312b96dd642 | greenfox-velox/danielliptak | /week3/day3/11.py | 470 | 3.875 | 4 | def create_triangle(hypotenuse):
if hypotenuse % 2 == 0:
print('Please give me odd number')
else:
for line in range(hypotenuse + 1):
star = line * '*'
space = int((hypotenuse - line) / 2) * ' '
if not line % 2 == 0:
print(space + star)
for line in range(hypotenuse-1, -1, -1):
star = line * '*'
space = int((hypotenuse - line) / 2) * ' '
if not line % 2 == 0:
print(space + star)
create_triangle(11)
|
c881d368184de47b885903d7d3d9fad4c4d0fa65 | AnushkaTiwari/FSDP_2019 | /Day03/teen_cal.py | 421 | 3.59375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 5 12:21:57 2019
@author: ANISHKA
"""
# Code Challenge : Teen Calculator
sum1=0
Dict={}
for num in range(3):
user=input("Enter the user name: ")
values=int(input("Enter the integer values: "))
Dict[user]=values
print(Dict)
if (values>=13 and values<20 and values!=15 and values!=16):
values=0
sum1=sum1+values
print( "Sum : " + str(sum1)) |
ef0ce6c54a9e1bc98804a3982255bb4a6ae0f6fd | jamiezeminzhang/Leetcode_Python | /ALL_SOLUTIONS/121_OO_Best_Time_to_Buy_and_Sell_Stock.py | 888 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 3 22:59:20 2016
121. Best Time to Buy and Sell Stock
Total Accepted: 84382 Total Submissions: 240817 Difficulty: Medium
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one
and sell one share of the stock), design an algorithm to find the maximum profit.
# The given solution is O(n)
My initial thought was O(n^2)
@author: zeminzhang
"""
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if prices == []: return 0
length, profit, low = len(prices), 0 , 2**31-1
for i in range(length):
if prices[i] < low: low = prices[i]
profit = max( prices[i] - low, profit)
return profit
|
b36ea86ab103d2ff603e09e4bf77e2f088c3483d | uchenna-j-edeh/dailly_problems | /after_twittr/unique_char.py | 531 | 4.125 | 4 | """
Implement an algorithm to determine if a string has all unique characters What if you can not use additional data structures?
example: input: 'uchenna'
output: false
"""
def is_unique_char(text):
#assuming it's ascii char which is 256 characters
my_list = []
for i in range(256):
my_list.append(0)
for t in text:
if my_list[ord(t)] == 1:
return False
my_list[ord(t)] = my_list[ord(t)] + 1
return True
print(is_unique_char('Uchenna'))
print(is_unique_char('Samuel'))
|
b5fec61309f25d77ef0099be1348b674ad74a653 | icancode20/my-codes | /Teach/Day 2/python ++.py | 298 | 3.78125 | 4 | import turtle
A = turtle.Pen()
turtle.bgcolor("black")
A.speed(0)
colors = ["red", "blue", "white"]
for x in range (150):
A.pencolor(colors[x % 3])
A.forward(x)
A.left(120)
A.goto(10,10)
for N in range (200):
A.pencolor(colors[N % 2])
A.circle(N)
A.left(45)
turtle.done() |
f3e4a992c8d98c6c11003855af340a10dafcc1d4 | wfsfgedtwwwarfsge/python_programming | /default/default_simple_error.py | 547 | 3.984375 | 4 | def greet(name, msg="Good morning!"):
"""
This function greets to
the person with the
provided message.
If the message is not provided,
it defaults to "Good
morning!"
"""
print("Hello", name + ', ' + msg)
greet("Hrishikesh")
greet("Shalini", "How do you do?")
def greet(msg = "Good morning!", name):
#greet(name = "Bruce",msg = "How do you do?")
# 2 keyword arguments (out of order)
#greet(msg = "How do you do?",name = "Bruce")
#1 positional, 1 keyword argument
#greet("Bruce", msg = "How do you do?")
|
f74b153c6af9dc791007fe2c2ab3311477792105 | metajinomics/dev | /fasta_tools/print_len_fasta.py | 647 | 3.609375 | 4 | #!/usr/bin/python
#usage: python print_len_fasta.py fastafile
import sys
flag = 0
length = 0
seq = []
name = ""
for line in open(sys.argv[1],'r'):
if (flag == 0 and line[:1]==">"):
name = line.strip()
flag = 1
continue
elif (flag == 1 and line[:1]==">"):
temp = ''.join(seq)
print len(temp)
#if( len(temp)> 500 and len(temp) < 2000):
# print name
# print temp
seq = []
name = line.strip()
else:
seq.append(line.strip())
temp = ''.join(seq)
print len(temp)
#if( len(temp)> 500 and len(temp) < 2000):
# print name
# print temp
|
111c8642273fdffe4899d0e35bb27e9cc213583e | nhlshstr/holbertonschool-higher_level_programming | /0x0A-python-inheritance/1-my_list.py | 227 | 3.625 | 4 | #!/usr/bin/python3
"""Contains class that inherits list"""
class MyList(list):
"""My list class inherited from list"""
def print_sorted(self):
""" Function to print sorted list """
print(sorted(self))
|
3c85ee4b838f8f0d9228677697cea9bd175603f5 | rscai/python99 | /python99/mtree/p501.py | 272 | 3.5 | 4 | from functools import reduce
from operator import and_
def istree(t):
if type(t) is not tuple:
return False
if len(t) != 2:
return False
if type(t[1]) is not list:
return False
return reduce(and_, [istree(e) for e in t[1]], True)
|
78b004b389db7b5ebb14c305a296d97ba6441d2c | tanneo/Python_exercises | /ex34.py | 202 | 3.90625 | 4 | #accessing elements of lists
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
print(animals[0])
print(animals[1])
#skip this exercise as familar with Syntax and move onto next |
03ea6dd6b98ce96efc490807f9fcf16bae986ea3 | CityofToronto/tw-front-back | /django/djangoAPI/utils.py | 994 | 3.640625 | 4 | '''Some General Utils'''
def num_to_alpha(num):
'''
Converts a number to its alpha base(26) implimentation
Starts at 1 = a, 27 = aa
'''
lst = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
if num < 27:
return lst[num - 1]
return num_to_alpha(int(num/26)) + lst[(num % 26) - 1]
class Result():
"""Format of results that come from model class functions"""
def __init__(self, success=False, message='', exception=None, error_code=0, obj_id=[], obj=[]):
self.success = success
self.message = message
self.exception = exception
self.obj_id = obj_id
self.error_code = error_code
self.obj = obj
def readable_message(self):
thing = str(self.exception) + ':' + \
str(type(self.exception)) if self.exception else ''
return str(self.error_code) + ':' + self.message + ':' + thing
|
8846ac77857c01c0a4cf6cbe718f5dbd7b16189a | marcosrodriguesgh/PythonCertificate | /lab5_1_11_9The_Digit_of_Life.py | 248 | 3.796875 | 4 | def digit_of_live(dateofbirth):
output = 0
for x in dateofbirth:
output += int(x)
return digit_of_live(str(output)) if output >= 10 else output
date = input('Please, give you birthday (YYYYMMDD): ')
print(digit_of_live(date))
|
9d9f9c21cb7edd8c2bbdd3e1e318380a5255cc27 | SB1996/Python | /Function/Function.py | 219 | 3.5625 | 4 | # Functions in Python ...!
# Function declaration
def displayName(_name) :
# Function defination
print(f"Hiii i'm {_name}")
return _name
name = displayName("Santanu Banik") # Function call
print(f"Name : {name}") |
3435f3c40fb565a83dc18907408aad5fb2fae528 | AbishaStephen/Codekata | /palin.py | 597 | 3.65625 | 4 | string = input("Enter the string")
string_shortener = ""
a = 0
s = 3
p_temp=0
s_temp=0
long = ""
for i in range(len(string)-2):
string_shortener = string[a:s]
if(string_shortener==string_shortener[::-1]):
p_temp = a
s_temp = s
for u in range(1000):
p_temp-=1
s_temp +=1
string_shortener = string[p_temp:s_temp]
if(string_shortener == string_shortener[::-1]):
if len(string_shortener)>len(long):
long = string_shortener
else:
break
a+=1
s+=1
print(long)
|
8c4c143c73941a6a115cdee9cc84655b87be0794 | monishnarendra/Python_Programs | /Insertion_Sort.py | 472 | 3.953125 | 4 | import time
list1 = []
n = int(input("Enter the number of elements in the list"))
for i in range(0,n):
list1.append(int(input("Enter the list elements")))
start_time = time.clock()
for i in range(1, len(list1)):
j = i
while j > 0 and list1[j] < list1[j - 1]:
temp = list1[j]
list1[j] = list1[j-1]
list1[j-1] = temp
j = j - 1
print("%s seconds" % (time.clock() - start_time))
print("Sorted list is")
print(list1) |
2e42d5a847c8a572eaefa9605ec6d7db59ae3750 | Rithik57/AI | /Informed and Uninformed/TSP brute force.py | 1,159 | 3.578125 | 4 | from itertools import permutations
from sys import maxsize
V = 4
def TSP(graph, S): #receives the graph and the starting vertex
# store all non active vertices in a list
vertex = []
for i in range(V): # V -> number of vertices
if i != S:
vertex.append(i)
minPath = maxsize
# consider all permutations
current = permutations(vertex)
for x in current:
currentWeight = 0
# for the current permutation add all paths
begin = S
for end in x:
currentWeight = currentWeight + graph[begin][end]
begin = end
currentWeight = currentWeight + graph[end][S] # add weight from last vertex to start to complete cycle
# check if the min path was found in this permutation
minPath = min(minPath, currentWeight)
print("weight for permutation : " + str(x) + " is : " + str(currentWeight))
return minPath
graph1 = [[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]]
start = int(input("Enter the starting vertex : "))
print("the min path weight for the graph is : "+str(TSP(graph1,start))) |
286a09b776c1c1335b6cda826f3b0e39676d514b | amaterasu1577/news | /main.py | 267 | 3.53125 | 4 | from client import News
def main():
news = News()
country = input("What country are you interested in?\n> ")
headlines = news.country_headlines(country)
for headline in headlines:
print(f"- {headline}")
if __name__ == '__main__':
main()
|
318b1fc380feaced13494796ba95fc26486ceb04 | AndreyNagorskiy/Geekbrains | /Python algorithms and data structures/2_Задание/les_2_task_3.py | 489 | 4.15625 | 4 | """ 3. Сформировать из введенного числа обратное по порядку входящих в него цифр и вывести на экран.
Например, если введено число 3486, надо вывести 6843."""
num = int(input('Введите целое число:'))
n2 = 0
while num > 0:
remainder = num % 10
num = num // 10
n2 = n2 * 10
n2 += remainder
print(f'Обратное ему число: {n2}')
|
f3aea1a8e16031b9f30e22c4e21decfb835e7023 | kalyan-ch/SltnsCrkdCpp | /Ch3StcksNQs/34QwStks.py | 411 | 3.828125 | 4 | #implement a queue with two stacks
from QueWStcks import NewQueue
from random import randint
qu = NewQueue()
qu.push(randint(1,100))
qu.push(randint(1,100))
qu.push(randint(1,100))
qu.push(randint(1,100))
print "before"
qu.printQ()
print "popping the q"
print qu.pop()
print qu.pop()
qu.push(randint(1,100))
print "after"
qu.printQ()
print "one more time"
print qu.pop()
print "after 2"
qu.printQ()
|
f09d716237ab693be041a6656664c88bc2b41c02 | guozanhua/xnn | /examples/mnist_loader.py | 2,346 | 3.515625 | 4 | import sys
import os
import numpy as np
from xnn.utils import numpy_one_hot
# ################## Download and prepare the MNIST dataset ##################
# This is just some way of getting the MNIST dataset from an online location
# and loading it into numpy arrays. It doesn't involve Lasagne or XNN at all.
def load_dataset():
# We first define some helper functions for supporting both Python 2 and 3.
if sys.version_info[0] == 2:
from urllib import urlretrieve
import cPickle as pickle
def pickle_load(f, encoding):
return pickle.load(f)
else:
from urllib.request import urlretrieve
import pickle
def pickle_load(f, encoding):
return pickle.load(f, encoding=encoding)
# We'll now download the MNIST dataset if it is not yet available.
url = 'http://deeplearning.net/data/mnist/mnist.pkl.gz'
filename = 'mnist.pkl.gz'
if not os.path.exists(filename):
print("Downloading MNIST dataset...")
urlretrieve(url, filename)
# We'll then load and unpickle the file.
import gzip
with gzip.open(filename, 'rb') as f:
data = pickle_load(f, encoding='latin-1')
# The MNIST dataset we have here consists of six numpy arrays:
# Inputs and targets for the training set, validation set and test set.
X_train, y_train = data[0]
X_val, y_val = data[1]
X_test, y_test = data[2]
# The inputs come as vectors, we reshape them to monochrome 2D images,
# according to the shape convention: (examples, channels, rows, columns)
X_train = X_train.reshape((-1, 1, 28, 28))
X_val = X_val.reshape((-1, 1, 28, 28))
X_test = X_test.reshape((-1, 1, 28, 28))
# The targets are int64, we cast them to int8 for GPU compatibility.
y_train = y_train.astype(np.uint8)
y_val = y_val.astype(np.uint8)
y_test = y_test.astype(np.uint8)
y_train = numpy_one_hot(y_train, 10)
y_val = numpy_one_hot(y_val, 10)
y_test = numpy_one_hot(y_test, 10)
# We just return all the arrays in order, as expected in main().
# (It doesn't matter how we do this as long as we can read them again.)
dataset = dict(
X_train=X_train,
y_train=y_train,
X_valid=X_val,
y_valid=y_val,
X_test=X_test,
y_test=y_test
)
return dataset |
8d59ac7347895230af851ab828fe075ceb0ae01e | ThaisMB/Curso-em-Video-Python-Exercicios | /ex058.py | 589 | 3.546875 | 4 | from random import randint
from time import sleep
palpite = 0
chute = 11
print('Pensei em um número entre 0 e 10. Você consegue adivinhar?')
computador = randint(0,10)
while chute!=computador:
chute = int(input('Em qual número eu pensei?'))
print('\033[33m PROCESSANDO... \033[m')
sleep(2)
if computador>chute:
print('\033[31m Mais...Tente outra vez!\033[m]')
elif computador<chute:
print('\033[31m Menos...Tente outra vez!\033[m')
palpite += 1
print('\033[36m PARABÉNS!Acertou com {} tentativas!\033[m'.format(palpite))
|
c1561fa35083edb3c4ac52f782a44d4961e8ddb3 | marklittle716/pythonfiles | /dictionary.py | 409 | 4 | 4 | # A Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
# Create dict
person = {
'first_name': 'John',
'last_name': 'Doe',
'age': 30
}
# Use constructor
person2 = dict(first_name='Sara', last_name="Connors")
print(person['first_name'])
print(person.get('last_name'))
#Add key/value
person['phone'] = '555-555-5555'
#get dict keys
print(person.keys()) |
eebfeba72961a6ee91b77dd0444c71448424a9a0 | MantieReid/100-days-of-code-round-2 | /Day 6/Fizz Buzz.py | 837 | 4.1875 | 4 | from typing import List
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
alist = [] # create a empty list
for i in range(1, n + 1): #use range to generate the numbers to add to the list
if i % 3 == 0 and i % 5 == 0: # if the number is a a multiple of 3 and five. Then add the string FizzBuzz to the list instead of that number.
alist.append("FizzBuzz")
elif i % 3 == 0: # if the number is a multiple of 3, then add the word fizz to the list.
alist.append("Fizz")
elif i % 5 == 0: # if the number is multiple of 5, then add the word buzz to the list.
alist.append("Buzz")
else: # else, add the current number to the list.
alist.append(i)
alist = list(map(str, alist)) # convert the elements of the list to a string.
return alist # return the list.
|
238127df834944d1b95b4be4d4456937e270ed3c | paymog/ProjectEuler | /Problems 70-79/71/bruteforce.py | 412 | 3.875 | 4 | # this is way too slow
from fractions import Fraction
fractions = set()
for denom in range(1, 1000001):
# print "testing %d" % denom
for num in range(denom * 3/7 -3, denom * 3 / 7 + 3):
fractions.add(Fraction(num, denom))
print "Converting to list"
fractions = list(fractions)
print "Sorting"
fractions = sorted(fractions)
print "Finding"
print fractions[fractions.index(Fraction(3, 7)) - 1]
|
725780126984dc3b8f2a7f2a61f48593c800b328 | samisken/CSE-231 | /proj06[1].py | 35,096 | 4 | 4 | ##################################################################################
#
# CSE 231 Project #6
# Samuel Isken CSE 231 - 730
#
#
# Algorithm
# Display hand and community cards and winner of hand
# ask if player wants to play again
# deal new hand and check all possible combos to determine winning hand
# display winning hand
# repeat until player prompts to stop or less than 9 cards remain
# end the program
#
#################################################################################
#GIVEN DONT CHANGE
##########################################################################
import cards
def less_than(c1,c2):
'''Return
True if c1 is smaller in rank,
True if ranks are equal and c1 has a 'smaller' suit
False otherwise'''
if c1.rank() < c2.rank():
return True
elif c1.rank() == c2.rank() and c1.suit() < c2.suit():
return True
return False
def min_in_list(L):
'''Return the index of the mininmum card in L'''
min_card = L[0] # first card
min_index = 0
for i,c in enumerate(L):
if less_than(c,min_card): # found a smaller card, c
min_card = c
min_index = i
return min_index
def cannonical(H):
#Sorts method - essentially a rewritten sort function
''' Selection Sort: find smallest and swap with first in H,
then find second smallest (smallest of rest) and swap with second in H,
and so on...'''
for i,c in enumerate(H):
# get smallest of rest; +i to account for indexing within slice
min_index = min_in_list(H[i:]) + i
H[i], H[min_index] = H[min_index], c # swap
return H
################################################################################
#GIVEN DONT CHANGE
################################################################################
def flush_7(H):
'''Return a list of 5 cards forming a flush,
if at least 5 of 7 cards form a flush in H, a list of 7 cards,
False otherwise.'''
#Initializes lists of suit
suit1 = []
suit2 = []
suit3 = []
suit4 = []
#Appends to suit lists
for c in H:
if c.suit() == 1:
suit1.append(c)
suit1 = cannonical(suit1)
if c.suit() == 2:
suit2.append(c)
suit2 = cannonical(suit2)
if c.suit() == 3:
suit3.append(c)
suit3 = cannonical(suit3)
if c.suit() == 4:
suit4.append(c)
suit4 = cannonical(suit4)
#Checks for flush
if len(suit1) >=5:
return suit1[:5]
if len(suit2) >=5:
return suit2[:5]
if len(suit3) >=5:
return suit3[:5]
if len(suit4) >=5:
return suit4[:5]
return False
#################################################################################
def straight_7(H):
#5 cards in a sequence
'''Return a list of 5 cards forming a straight,
if at least 5 of 7 cards form a straight in H, a list of 7 cards,
False otherwise.'''
#Initializes rank lists
rank1 = []
rank2 = []
rank3 = []
rank4 = []
rank5 = []
rank6 = []
rank7 = []
rank8 = []
rank9 = []
rank10 = []
rank11 = []
rank12 = []
rank13 = []
rank14 = []
straight_list = []
hand_list = []
for c in H:
if c.rank() == 1:
rank1.append(c)
if c.rank() == 2:
rank2.append(c)
if c.rank() == 3:
rank3.append(c)
if c.rank() == 4:
rank4.append(c)
if c.rank() == 5:
rank5.append(c)
if c.rank() == 6:
rank6.append(c)
if c.rank() == 7:
rank7.append(c)
if c.rank() == 8:
rank8.append(c)
if c.rank() == 9:
rank9.append(c)
if c.rank() == 10:
rank10.append(c)
if c.rank() == 11:
rank11.append(c)
if c.rank() == 12:
rank12.append(c)
if c.rank() == 13:
rank13.append(c)
if c.rank() == 14:
rank14.append(c)
if len(rank1) >=1:
hand_list += rank1[0:]
straight_list += "1" * len(rank1)
if len(rank2) >=1:
hand_list += rank2[0:]
straight_list += "2" * len(rank2)
if len(rank3) >=1:
hand_list += rank3[0:]
straight_list += "3" * len(rank3)
if len(rank4) >=1:
hand_list += rank4[0:]
straight_list += "4" * len(rank4)
if len(rank5) >=1:
hand_list += rank5[0:]
straight_list += "5" * len(rank5)
if len(rank6) >=1:
hand_list += rank6[0:]
straight_list += "6" * len(rank6)
if len(rank7) >=1:
hand_list += rank7[0:]
straight_list += "7" * len(rank7)
if len(rank8) >=1:
hand_list += rank8[0:]
straight_list += "8" * len(rank8)
if len(rank9) >=1:
hand_list += rank9[0:]
straight_list += "9" * len(rank9)
if len(rank10) >=1:
hand_list += rank10[0:]
straight_list += "10" * len(rank10)
if len(rank11) >=1:
hand_list += rank11[0:]
straight_list += "11" * len(rank11)
if len(rank12) >=1:
hand_list += rank12[0:]
straight_list += "12" * len(rank12)
if len(rank13) >=1:
hand_list += rank13[0:]
straight_list += "13" * len(rank13)
if len(rank14) >=1:
hand_list += rank14[0:]
straight_list += "14" * len(rank14)
#Straight_list is the full hand of cards
#Checks for straight
if int(straight_list[1]) - int(straight_list[0]) == 1 and int(straight_list[2]) - int(straight_list[1]) == 1 and int(straight_list[3]) - int(straight_list[2]) == 1 and int(straight_list[4]) - int(straight_list[3]) == 1:
hand_list = hand_list[0:5]
return hand_list
if int(straight_list[2]) - int(straight_list[1]) == 1 and int(straight_list[3]) - int(straight_list[2]) == 1 and int(straight_list[4]) - int(straight_list[3]) == 1 and int(straight_list[5]) - int(straight_list[4]) == 1:
hand_list = hand_list[1:6]
return hand_list
if int(straight_list[3]) - int(straight_list[2]) == 1 and int(straight_list[4]) - int(straight_list[3]) == 1 and int(straight_list[5]) - int(straight_list[4]) == 1 and int(straight_list[6]) - int(straight_list[5]) == 1:
hand_list = hand_list[2:]
return hand_list
return False
###############################################################################################################
def straight_flush_7(H):
'''Return a list of 5 cards forming a straight flush,
if at least 5 of 7 cards form a straight flush in H, a list of 7 cards,
False otherwise.'''
checker_one = straight_7(H)
if checker_one == False:
checker_one = []
else:
checker_one=checker_one
answer = flush_7(checker_one)
#Simply combines straight and flush functions
return answer
######################################################################################################
def four_7(H):
'''Return a list of 4 cards with the same rank,
if 4 of the 7 cards have the same rank in H, a list of 7 cards,
False otherwise.'''
rank1 = []
rank2 = []
rank3 = []
rank4 = []
rank5 = []
rank6 = []
rank7 = []
rank8 = []
rank9 = []
rank10 = []
rank11 = []
rank12 = []
rank13 = []
rank14 = []
for c in H:
if c.rank() == 1:
rank1.append(c)
if c.rank() == 2:
rank2.append(c)
if c.rank() == 3:
rank3.append(c)
if c.rank() == 4:
rank4.append(c)
if c.rank() == 5:
rank5.append(c)
if c.rank() == 6:
rank6.append(c)
if c.rank() == 7:
rank7.append(c)
if c.rank() == 8:
rank8.append(c)
if c.rank() == 9:
rank9.append(c)
if c.rank() == 10:
rank10.append(c)
if c.rank() == 11:
rank11.append(c)
if c.rank() == 12:
rank12.append(c)
if c.rank() == 13:
rank13.append(c)
if c.rank() == 14:
rank14.append(c)
#Checks for 4 of a kind
if len(rank1) >=4:
return rank1[:4]
if len(rank2) >=4:
return rank2[:4]
if len(rank3) >=4:
return rank3[:4]
if len(rank4) >=4:
return rank4[:4]
if len(rank5) >=4:
return rank5[:4]
if len(rank6) >=4:
return rank6[:4]
if len(rank7) >=4:
return rank7[:4]
if len(rank8) >=4:
return rank8[:4]
if len(rank9) >=4:
return rank9[:4]
if len(rank10) >=4:
return rank10[:4]
if len(rank11) >=4:
return rank11[:4]
if len(rank12) >=4:
return rank12[:4]
if len(rank13) >=4:
return rank13[:4]
if len(rank14) >=4:
return rank14[:4]
return False
def three_7(H):
#ASSUME NOT 4 of a kind from prior function
'''Return a list of 3 cards with the same rank,
if 3 of the 7 cards have the same rank in H, a list of 7 cards,
False otherwise.
You may assume that four_7(H) is False.'''
rank1 = []
rank2 = []
rank3 = []
rank4 = []
rank5 = []
rank6 = []
rank7 = []
rank8 = []
rank9 = []
rank10 = []
rank11 = []
rank12 = []
rank13 = []
rank14 = []
for c in H:
if c.rank() == 1:
rank1.append(c)
if c.rank() == 2:
rank2.append(c)
if c.rank() == 3:
rank3.append(c)
if c.rank() == 4:
rank4.append(c)
if c.rank() == 5:
rank5.append(c)
if c.rank() == 6:
rank6.append(c)
if c.rank() == 7:
rank7.append(c)
if c.rank() == 8:
rank8.append(c)
if c.rank() == 9:
rank9.append(c)
if c.rank() == 10:
rank10.append(c)
if c.rank() == 11:
rank11.append(c)
if c.rank() == 12:
rank12.append(c)
if c.rank() == 13:
rank13.append(c)
if c.rank() == 14:
rank14.append(c)
#Checks for three of a kind
if len(rank1) >=3:
return rank1[:3]
if len(rank2) >=3:
return rank2[:3]
if len(rank3) >=3:
return rank3[:3]
if len(rank4) >=3:
return rank4[:3]
if len(rank5) >=3:
return rank5[:3]
if len(rank6) >=3:
return rank6[:3]
if len(rank7) >=3:
return rank7[:3]
if len(rank8) >=3:
return rank8[:3]
if len(rank9) >=3:
return rank9[:3]
if len(rank10) >=3:
return rank10[:3]
if len(rank11) >=3:
return rank11[:3]
if len(rank12) >=3:
return rank12[:3]
if len(rank13) >=3:
return rank13[:3]
if len(rank14) >=3:
return rank14[:3]
return False
#######################################################################################################
def two_pair_7(H):
'''Return a list of 4 cards that form 2 pairs,
if there exist two pairs in H, a list of 7 cards,
False otherwise.
You may assume that four_7(H) and three_7(H) are both False.'''
rank1 = []
rank2 = []
rank3 = []
rank4 = []
rank5 = []
rank6 = []
rank7 = []
rank8 = []
rank9 = []
rank10 = []
rank11 = []
rank12 = []
rank13 = []
rank14 = []
pair_list = []
for c in H:
if c.rank() == 1:
rank1.append(c)
rank1 = cannonical(rank1)
if c.rank() == 2:
rank2.append(c)
rank2 = cannonical(rank2)
if c.rank() == 3:
rank3.append(c)
rank3 = cannonical(rank3)
if c.rank() == 4:
rank4.append(c)
rank4 = cannonical(rank4)
if c.rank() == 5:
rank5.append(c)
rank5 = cannonical(rank5)
if c.rank() == 6:
rank6.append(c)
rank6 = cannonical(rank6)
if c.rank() == 7:
rank7.append(c)
rank7 = cannonical(rank7)
if c.rank() == 8:
rank8.append(c)
rank8 = cannonical(rank8)
if c.rank() == 9:
rank9.append(c)
rank9 = cannonical(rank9)
if c.rank() == 10:
rank10.append(c)
rank10 = cannonical(rank10)
if c.rank() == 11:
rank11 = cannonical(rank11)
if c.rank() == 12:
rank12 = cannonical(rank12)
if c.rank() == 13:
rank13 = cannonical(rank13)
if c.rank() == 14:
rank14.append(c)
rank14 = cannonical(rank14)
if len(rank1) >=2:
pair_list.append(rank1[:2])
if len(rank2) >=2:
pair_list.append(rank2[:2])
if len(rank3) >=2:
pair_list.append(rank3[:2])
if len(rank4) >=2:
pair_list.append(rank4[:2])
if len(rank5) >=2:
pair_list.append(rank5[:2])
if len(rank6) >=2:
pair_list.append(rank6[:2])
if len(rank7) >=2:
pair_list.append(rank7[:2])
if len(rank8) >=2:
pair_list.append(rank8[:2])
if len(rank9) >=2:
pair_list.append(rank9[:2])
if len(rank10) >=2:
pair_list.append(rank10[:2])
if len(rank11) >=2:
pair_list.append(rank11[:2])
if len(rank12) >=2:
pair_list.append(rank12[:2])
if len(rank13) >=2:
pair_list.append(rank13[:2])
if len(rank14) >=2:
pair_list.append(rank14[:2])
if len(pair_list) >= 2:
return pair_list[0]+pair_list[1]
return False
def one_pair_7(H):
'''Return a list of 2 cards that form a pair,
if there exists exactly one pair in H, a list of 7 cards,
False otherwise.
You may assume that four_7(H), three_7(H) and two_pair(H) are False.'''
rank1 = []
rank2 = []
rank3 = []
rank4 = []
rank5 = []
rank6 = []
rank7 = []
rank8 = []
rank9 = []
rank10 = []
rank11 = []
rank12 = []
rank13 = []
rank14 = []
for c in H:
if c.rank() == 1:
rank1.append(c)
if c.rank() == 2:
rank2.append(c)
if c.rank() == 3:
rank3.append(c)
if c.rank() == 4:
rank4.append(c)
if c.rank() == 5:
rank5.append(c)
if c.rank() == 6:
rank6.append(c)
if c.rank() == 7:
rank7.append(c)
if c.rank() == 8:
rank8.append(c)
if c.rank() == 9:
rank9.append(c)
if c.rank() == 10:
rank10.append(c)
if c.rank() == 11:
rank11.append(c)
if c.rank() == 12:
rank12.append(c)
if c.rank() == 13:
rank13.append(c)
if c.rank() == 14:
rank14.append(c)
if len(rank1) >=2:
return rank1[:2]
if len(rank2) >=2:
return rank2[:2]
if len(rank3) >=2:
return rank3[:2]
if len(rank4) >=2:
return rank4[:2]
if len(rank5) >=2:
return rank5[:2]
if len(rank6) >=2:
return rank6[:2]
if len(rank7) >=2:
return rank7[:2]
if len(rank8) >=2:
return rank8[:2]
if len(rank9) >=2:
return rank9[:2]
if len(rank10) >=2:
return rank10[:2]
if len(rank11) >=2:
return rank11[:2]
if len(rank12) >=2:
return rank12[:2]
if len(rank13) >=2:
return rank13[:2]
if len(rank14) >=2:
return rank14[:2]
return False
def two_for_full_house(H):
rank1 = []
rank2 = []
rank3 = []
rank4 = []
rank5 = []
rank6 = []
rank7 = []
rank8 = []
rank9 = []
rank10 = []
rank11 = []
rank12 = []
rank13 = []
rank14 = []
for c in H:
if c.rank() == 1:
rank1.append(c)
if c.rank() == 2:
rank2.append(c)
if c.rank() == 3:
rank3.append(c)
if c.rank() == 4:
rank4.append(c)
if c.rank() == 5:
rank5.append(c)
if c.rank() == 6:
rank6.append(c)
if c.rank() == 7:
rank7.append(c)
if c.rank() == 8:
rank8.append(c)
if c.rank() == 9:
rank9.append(c)
if c.rank() == 10:
rank10.append(c)
if c.rank() == 11:
rank11.append(c)
if c.rank() == 12:
rank12.append(c)
if c.rank() == 13:
rank13.append(c)
if c.rank() == 14:
rank14.append(c)
if len(rank1) ==2:
return rank1[:2]
if len(rank2) ==2:
return rank2[:2]
if len(rank3) ==2:
return rank3[:2]
if len(rank4) ==2:
return rank4[:2]
if len(rank5) ==2:
return rank5[:2]
if len(rank6) ==2:
return rank6[:2]
if len(rank7) ==2:
return rank7[:2]
if len(rank8) ==2:
return rank8[:2]
if len(rank9) ==2:
return rank9[:2]
if len(rank10) ==2:
return rank10[:2]
if len(rank11) ==2:
return rank11[:2]
if len(rank12) ==2:
return rank12[:2]
if len(rank13) ==2:
return rank13[:2]
if len(rank14) ==2:
return rank14[:2]
#Returns empty list if fails as to not cause an error
return []
##############################################################################################################
def three_in_house_7(H):
result = three_7(H)
if result == False:
return []
return result
##############################################################################################################
def full_house_7(H):
'''Return a list of 5 cards forming a full house,
if 5 of the 7 cards form a full house in H, a list of 7 cards,
False otherwise.
You may assume that four_7(H) is False.'''
two_in_house = two_for_full_house(H)
three_in_house = three_in_house_7(H)
two_in_house = cannonical(two_in_house)
three_in_house = cannonical(three_in_house)
full_house_set = two_in_house + three_in_house
if len(full_house_set) == 5:
return full_house_set
return False
##############################################################################################################
def main():
D = cards.Deck()
D.shuffle()
my_deck = cards.Deck()
my_deck.shuffle()
community_list = []
hand_1_list = []
hand_2_list = []
x = "y"
while x == "y":
community_list = []
hand_1_list = []
hand_2_list = []
#Creates hands and community cards
for i in range(5):
community_list.append(my_deck.deal())
for i in range(1):
hand_1_list.append(my_deck.deal())
hand_1_list.append(my_deck.deal())
hand_2_list.append(my_deck.deal())
hand_2_list.append(my_deck.deal())
#Prints prompt and card data
print("-"*40)
print("Let's play poker!\n")
print("Community cards:",community_list)
print("Player 1:",hand_1_list)
print("Player 2:",hand_2_list)
print()
player_1_hand = hand_1_list + community_list
player_2_hand = hand_2_list + community_list
SF1 = straight_flush_7(player_1_hand)
SF2 = straight_flush_7(player_2_hand)
four_k1 = four_7(player_1_hand)
four_k2 = four_7(player_2_hand)
full_house1 = full_house_7(player_1_hand)
full_house2 = full_house_7(player_2_hand)
flush1 = flush_7(player_1_hand)
flush2 = flush_7(player_2_hand)
straight1 = straight_7(player_1_hand)
straight2 = straight_7(player_2_hand)
three_k1 = three_7(player_1_hand)
three_k2 = three_7(player_2_hand)
two_pair1 = two_pair_7(player_1_hand)
two_pair2 = two_pair_7(player_2_hand)
pair1 = one_pair_7(player_1_hand)
pair2 = one_pair_7(player_2_hand)
#The section below checks in order strongest to weakest hands and returns the tie or winner and prompts for next hand
#==============================================================================
if SF1 != False and SF2 != False:
print("TIE with two straight flushes: " , SF1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if SF1 != False:
print("Player 1 wins with a straight flush: " , SF1)
community_list = []
hand_1_list = []
hand_2_list = []
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if SF2 != False:
print("Player 2 wins with a straight flush: " , SF1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if four_k1 != False and four_k2 != False:
print("TIE with two four of a kind: " , four_k1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if four_k1 != False:
four_k1 = cannonical(four_k1)
print("Player 1 wins with four of a kind:" , four_k1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if four_k2 != False:
print("Player 2 wins with four of a kind:" , four_k2)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if full_house1 != False and full_house2 != False:
print("TIE with two full houses: " , full_house1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if full_house1 != False:
print("Player 1 wins with a full house: " , full_house1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if full_house2 != False:
print("Player 2 wins with a full house: " , full_house2)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if flush1 != False and flush2 != False:
flush1 = cannonical(flush1)
print("TIE with a flush:" , flush1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if flush1 != False:
print("Player 1 wins with a flush: " , flush1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if flush2 != False:
print("Player 2 wins with a flush: " , flush2)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if straight1 != False and straight2 != False:
print("TIE with two straights: " , straight1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if straight1 != False:
print("Player 1 wins with a straight: " , straight1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if straight2 != False:
print("Player 2 wins with a straight: " , straight2)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if three_k1 != False and three_k2 != False:
print("TIE with two three of a kind: " , three_k1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if three_k1 != False:
print("Player 1 wins with three of a kind: " , three_k1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if three_k2 != False:
print("Player 2 wins with three of a kind: " , three_k2)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if two_pair1 != False and two_pair2 != False:
print("TIE with two pairs:", two_pair1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if two_pair1 != False:
print("Player 1 wins with two pairs: " , two_pair1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if two_pair2 != False:
print("Player 2 wins with a two pairs: " , two_pair2)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if pair1 != False and pair2 != False:
print("TIE with two pairs:", pair1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if pair1 != False:
print("Player 1 wins with a pair: " , pair1)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
if pair2 != False:
print("Player 2 wins with a pair: " , pair2)
SF1 = False
SF2 = False
four_k1 = False
four_k2 = False
full_house1 = False
full_house2 = False
flush1 = False
flush2 = False
straight1 = False
straight2 = False
three_k1 = False
three_k2 = False
two_pair1 = False
two_pair2 = False
pair1 = False
pair2 = False
############################################################################
#Checks number of cards left after each hand
if len(my_deck) < 9:
print("Deck has too few cards so game is done.")
break
x = input("Do you wish to play another hand?(Y or N) ")
if x != "y":
break
##################################################
if __name__ == "__main__": #LEAVE ALONE
#################################################
main() |
4003ef6d31645c8c0ce59ec34985805593f10072 | Stran1ck/python_mini | /qwerty.py | 131 | 3.9375 | 4 | n = input()
m = input()
if len(n) < 7 and len(m) < 7:
print('Short')
elif n == m:
print('OK')
else:
print('Difference') |
03d0fe33796fae3335931ef032527c6a135d0e0f | Wambuilucy/CompetitiveProgramming | /Project Euler/ProjectEuler2.py | 712 | 3.8125 | 4 | #! /usr/bin/env python
'''
Project Euler 2 (https://projecteuler.net/problem=2)
Even Fibonacci Numbers
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
'''
from math import sqrt
def is_perfect_square(n):
n_ = int(sqrt(n))
return (n_ * n_ == n)
def is_fib(n):
return is_perfect_square(5 * n * n + 4) or is_perfect_square(5 * n * n - 4)
res = 0
for i in range(4000000):
if is_fib(i) and i % 2 == 0:
res += i
print(res)
|
3b6a0c4afe13b564e25c3f04a7563de076e5f451 | ryanmp/project_euler | /p003.py | 675 | 3.5625 | 4 | '''
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
'''
import math
def factors(n):
return reduce(list.__add__,
([i, n//i] for i in range(1, int(math.sqrt(n)) + 1) if n % i == 0))
def is_prime(n):
for i in xrange(2,int(math.sqrt(n))+1):
if n%i == 0:
return False
return True
def main(n):
factor_list = factors(n)
factor_list.sort(reverse=True)
for i in factor_list:
if is_prime(i):
return i
return -1
if __name__ == '__main__':
import boilerplate, time, resource
t = time.time()
r = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
boilerplate.all(main(600851475143), t, r)
|
cffd704fff0b7f39ffcdd3ecde13a5b8f6f5aa27 | ipeterov/random-stuff | /Утилиты/remove_shit_from_filenames_recursive.py | 674 | 3.53125 | 4 | import os
from os.path import join, getsize
path = input('Path: ')
shit = input('Shit: ')
to_be_renamed = []
for root, dirs, files in os.walk(path):
for f in files:
if shit in f:
#print('AAAA!! FOUND SHIT!!!1')
new_f = f.replace(shit, '')
to_be_renamed.append(join(root, f), join(root, new_f))
print('Following files are going to be renamed: ')
for f in to_be_renamed:
print(os.path.basename(f[0]) + ' -> ' + os.path.basename(f[1]))
proceed = input('Are you willing to proceed (y/n)? ')
if proceed == 'y':
for f in to_be_renamed:
os.rename(f[0], f[1])
print('Done.')
else:
print('Rename aborted.')
|
7d528974dd8f7e3856fdd67fb10a1c4af970859d | rajkonkret/python-szkolenie | /pon_3_ex6.py | 160 | 3.96875 | 4 | def is_even(number):
return number%2==0
number = int(input('Podaj liczbe'))
print(is_even(number))
mask = (1 << 2) - 1
little = number & mask
print(mask)
|
a5f336bbd976af28f84c03bafff3c6133d03dba9 | PIvanov94/SoftUni-Software-Engineering | /Programming Fundamentals Python 2020 Part 1/Final Exam Problem 1.py | 1,479 | 4.0625 | 4 | text = input()
line = input()
while not line == "Finish":
data = line.split()
command = data[0]
if command == "Replace":
current_char = data[1]
new_char = data[2]
text = text.replace(current_char, new_char)
print(text)
elif command == "Cut":
start_index = int(data[1])
end_index = int(data[2])
if start_index in range(len(text)) and end_index in range(len(text)):
fist_half = text[:start_index]
second_half = text[end_index + 1:]
text = fist_half + second_half
print(text)
else:
print("Invalid indices!")
elif command == "Make":
method = data[1]
if method == "Upper":
text = text.upper()
elif method == "Lower":
text = text.lower()
print(text)
elif command == "Check":
string = data[1]
if string in text:
print(f"Message contains {string}")
else:
print(f"Message doesn't contain {string}")
elif command == "Sum":
start_index = int(data[1])
end_index = int(data[2])
if start_index in range(len(text)) and end_index in range(len(text)):
substring = text[start_index:end_index+1]
substring = sum([ord(char) for char in substring])
print(substring)
else:
print("Invalid indices!")
line = input()
|
1509382beeb72538bc96a9d6e8ebb593d774e150 | silvadanilo/exercism | /python/word-count/word_count.py | 171 | 3.6875 | 4 | import re
from collections import Counter
def count_words(phrase):
splitted = re.findall(r"([a-z0-9]+(?:\'[a-z0-9]+)?)", phrase.lower())
return Counter(splitted)
|
7d0e1d4b42b9abee51a3f5fe9bf3257f79552b97 | weichuntsai0217/leetcode | /281-Zigzag_Iterator.py | 1,342 | 3.96875 | 4 | """
* Ref: https://discuss.leetcode.com/topic/24223/python-o-1-space-solutions
* Key points: No
* Explain your thought:
- Change v1 and v2 into iterator, and store them in a matrix
- When the "next" method is called, we alway return the top row of
the matrix, and append this row to the bottom of the matrix to keep the
zigzag property. How ever, if the length of this row is 1, don't append
it.
- When the method "hasNext" is called, just check if the matrix is empty.
* Compute complexity:
- Time complexity: ?
- Space complexity: O(n)
"""
class ZigzagIterator(object):
def __init__(self, v1, v2):
"""
Initialize your data structure here.
:type v1: List[int]
:type v2: List[int]
"""
self.vecs =[ (iter(row), len(row) ) for row in [v1, v2] if len(row) ]
def next(self):
"""
:rtype: int
"""
if self.hasNext():
row, n = self.vecs.pop(0)
val = next(row)
if n - 1 != 0: self.vecs.append((row, n-1))
return val
return None
def hasNext(self):
"""
:rtype: bool
"""
return len(self.vecs) != 0
# Your ZigzagIterator object will be instantiated and called as such:
# i, v = ZigzagIterator(v1, v2), []
# while i.hasNext(): v.append(i.next()) |
a5d02ff50e1ad7708c08aa475200bdd695ecaa8e | ElizabethFoley/Text-Based-Game | /game.py | 15,871 | 3.59375 | 4 | # CMPT 120L 113
# Libby Foley
# 20 Sep 2018
###
##
# In my final commit, I added a class object for the player and the locales
# I added and "use item" feature for the candle
# I made the candle have "limited uses"
# I added the ability for the player to ascend or descend down the stairway
# I added print a inventory function that prints the inventory
# I set a "win" condition
# I gave the user a chance to play again
##
from Player import Player
from Locale import Locale
player = Player("", "", "")
MAP = '''
nurse's office
|
|
|
library---stairway---secondFloor---door out---outside
| |
| |
| |
| classroom2
|
bathroom---------classroom1
|
|
|
hallway
'''
title = ("\nRun"
"\n=======\n")
print(title)
intro = (" You suddenly awake. Your heart is racing. You don't know where you are."
" You look around and calm down. It seems you're still at your high school."
" But something is different. The classrooms are the same, but everything"
" is run down and dark. There are cobwebs everywhere, holes in the floors"
" and walls, and turned over desks. You decide to look around to find a"
" familiar face. As you walk, you notice the hallway seems too quiet,"
" and you realize you're the only person in the entire school. Your"
" heart starts to pound. You question where everyone else is. Despite"
" your fear, you keep walking through the dark hall. You see something"
" at the end of the hall. You're suddenly surrounded by a horrible smell."
" You use you shirt to cover your nose and look down. You jump back, you"
" see blood and guts spilled out on the floor, along with a student ID tag. It looks as if someone"
" was just killed, but you thought you were the only one in the building."
" Where are you? You keep staring at the decomposing body, you can't look away."
" Suddenly, you hear something behind you. Maybe an axe dragging on the"
" floor. There's laughing too. You turn around...")
def showIntro():
print(title)
print(intro)
prompt()
# current locations
hallway = Locale("Hallway", ("You are in the same hallway. You have turned around, but see no one. Everything looks different."
"The halls have shifted. You are not where you were before. There are holes in"
"the floors everywhere and they seem to be endless. You start walking, everything is dark.") , None)
bathroom = Locale("Bathroom", ("You find a bathroom. It is the first room you see in the hallway. You open a stall and see a body"
"hanging, swaying above you. You scream, run out of the bathroom, and question where you really are."
"Finally, you get out and see an empty classroom."), None)
classroom1 = Locale("Classroom1", ("You walk into the classroom, hoping you escaped. It's dark, but there is one candle lit."
"Suddenly, the door slams shut and the candle goes out."
"It's now pitch black in the classroom. You start to hear voices circling around you."
"You feel as if you are going mad and scream in terror."
"You run for the door, stumbling over fallen desks and chairs."
"You pull at the door, but it won't open. You hear the same footsteps again and freeze."
"You turn around, no one is there."), "candle")
stairway = Locale("Stairway", ("You go out into the hall, still you see no one. However, you come across unfamiliar stairs."
"You decide to go up. As you walk, decaying body parts and spilled guts lay there, but you seem to be unphased."
"Are you going mad?"), None)
secondFloor = Locale("Second Floor", ("You are in the second floor hallway. This new floor is different"
"than the first. It only has one hallway with a door at the end."), None)
doorOut = Locale("Door Out", ("You head for the only door in the hallway, hoping it is a way out."
"All the windows and doors out of the school are locked shut. You pull on the handle, it opens."), None)
nurseOffice = Locale("Nurse's Office", ("You see a table on one side of the room and a small bed on the other. There's a broken cabinet"
"above the table. It is mostly empty, but you find a bloody syringe and wonder why the blood looks"
"so fresh."), "bloody syringe")
outside = Locale("Outside", ("You finally get outside on the second floor. There's hope for you after all... or is there? You soon realize"
"that there is nowhere for you to land if you jump down from the short hallway you are in. Trees surround you"
"and cover the floor on the ground below you. There is no way out after all."), None)
classroom2 = Locale("Classroom2", ("You find another classroom, but this one is different than the other one."
"You walk towards the teacher's desk in the front of the room and see something in one of the half open"
"drawers. It is a pair of scissors."), "scissors")
library = Locale("Library", ("You turn left at the stairway and there is a door. You walk in and see books scattered across the floor."
"Most of the books are dirty and torn apart. You then find a map on the floor among the books."), "map")
objects = [hallway, bathroom, classroom1, stairway, secondFloor, doorOut, nurseOffice, outside, classroom2, library]
ending = ("You hear footsteps and laughing behind you. You want to turn around, but instead you freeze."
"You can't move and your heart begins to race. Suddenly, you feel a sharp pain and"
"blood begin to run down your back. You have been killed.")
credit = ("\nCopyright (c) 2016-2018 Matthew A Johnson, [email protected]")
maxMoves = 25
def prompt():
input("\n<Press Enter to continue...>")
def earnPoints(pts):
player.score += pts
def take(locale):
print("You found: " + str(locale.item))
if locale.item !=None:
temp = True
else:
print("There are no items here")
temp = False
while temp:
taking = input("Do you want to take this item? 'yes' or 'no' ")
if taking.lower().strip() == "yes":
player.inventory.append(locale.item)
if locale.item == "map":
player.map = True
locale.item = None
temp = False
elif taking.lower().strip() == "no":
break
else:
print("You must enter 'yes' or 'no'")
# Locales
def goHallway():
player.description = hallway.description
player.locName = hallway.name
player.currentLoc = 0
player.numberOfMoves +=1
take(hallway)
if not hallway.visited:
earnPoints(5)
hallway.visited = True
def goBathroom():
player.description = bathroom.description
player.locName = bathroom.name
player.currentLoc = 1
player.numberOfMoves +=1
take(bathroom)
if not bathroom.visited:
earnPoints(5)
bathroom.visited = True
def goClassroom1():
player.description = classroom1.description
player.locName = classroom1.name
player.currentLoc = 2
player.numberOfMoves +=1
take(classroom1)
if not classroom1.visited:
earnPoints(5)
classroom1.visited = True
def goStairway():
player.description = stairway.description
player.locName = stairway.name
player.currentLoc = 3
player.numberOfMoves +=1
take(stairway)
if not stairway.visited:
earnPoints(5)
stairway.visited = True
def goSecondFloor():
player.description = secondFloor.description
player.locName = secondFloor.name
player.currentLoc = 4
player.numberOfMoves +=1
take(secondFloor)
if not secondFloor.visited:
earnPoints(5)
secondFloor.visited = True
def goDoorOut():
player.description = doorOut.description
player.locName = doorOut.name
player.currentLoc = 5
player.numberOfMoves +=1
take(doorOut)
if not doorOut.visited:
earnPoints(5)
doorOut.visited = True
def goNurseOffice():
player.description = nurseOffice.description
player.locName = nurseOffice.name
player.currentLoc = 6
player.numberOfMoves +=1
take(nurseOffice)
if not nurseOffice.visited:
earnPoints(5)
nurseOffice.visited = True
def goOutside():
player.description = outside.description
player.locName = outside.name
player.currentLoc = 7
player.numberOfMoves +=1
take(outside)
if not outside.visited:
earnPoints(5)
outside.visited = True
def goClassroom2():
player.description = classroom2.description
player.locName = classroom2.name
player.currentLoc = 8
player.numberOfMoves +=1
take(classroom2)
if not classroom2.visited:
earnPoints(5)
classroom2.visited = True
def goLibrary():
player.description = library.description
player.locName = library.name
player.currentLoc = 9
player.numberOfMoves +=1
take(library)
if not library.visited:
earnPoints(5)
library.visited = True
# Create Student ID
def setupPlayer():
print("Create your character. What is your high school student ID?")
name = input("Enter your name: ")
gender = input("Girl or Boy: ")
gradeLevel = input("What year of highschool are you in? (9th, 10th, 11th, 12th)? ")
player.name = name
player.gender = gender
player.gradeLevel = gradeLevel
print("Your student ID: " , player.name , " " , "Gender: " , player.gender , "Grade Level: " , player.gradeLevel)
prompt()
goHallway()
def showOutro():
if player.score == 50:
print("You have escaped.")
else:
print(ending)
print(credit)
def processInput():
global com
pass
com = input("Enter a command: ")
def updateGame():
print("updating the game")
updateGame()
def getCommand():
global cmd
cmd = input("\nWhat do you want to do next? ").strip().lower()
return cmd
def renderGame():
print("\nLocation: " , player.locName, " Score: ", player.score, " Moves: " , player.numberOfMoves)
print(player.description)
# play again
def playAgain():
again = input("Do you want to play again? 'yes' or 'no'")
if again.strip().lower() == "yes":
player.numberOfMoves = 0
player.score = 0
player.map = False
player.inventory = []
uses = 1
for x in objects:
x.visited = False
main()
else:
pass
def printInventory():
print("You have: ")
for x in player.inventory:
print(x)
# candle uses
uses = 1
def containsItem(inventory, item):
for x in inventory:
if x == item:
return True
return False
# Game Loop
def gameLoop():
global cmd, uses
while player.numberOfMoves < maxMoves and player.score < 50:
renderGame()
getCommand()
if cmd == "quit" or player.numberOfMoves >= maxMoves:
break
elif cmd == "help":
print("\nValid commands are: 'North' , 'South' , 'East' , 'West' , 'help' , 'quit' , 'inventory' , 'use candle (if found)'")
elif cmd == "map":
if player.map:
print(MAP)
else:
print("You haven't found the map yet.")
elif cmd == "inventory":
printInventory()
# use item: candle
elif cmd == "use candle":
if containsItem(player.inventory, "candle") and uses <= 3:
print("You light the candle")
uses += 1
elif not containsItem(player.inventory, "candle"):
print("You do not have a candle")
elif containsItem(player.inventory, "candle") and uses > 3:
print("You don't have any more candle uses")
elif cmd == "north":
if player.currentLoc == 0: #hallway
answer = input("Would you like to go up the stairs? 'yes'or 'no'")
if answer.lower().strip() == "yes":
goStairway()
elif answer.lower().strip() == "no":
print("You stay in the hallway")
goHallway()
elif player.currentLoc == 4: #secondFloor
goNurseOffice()
elif player.currentLoc == 8: #classroom 2
goSecondFloor()
else:
print("You can't go further North from here.")
elif cmd == "south":
if player.currentLoc == 1: #bathroom
goHallway()
elif player.currentLoc == 6: #nurse's office
goSecondFloor()
elif player.currentLoc == 3: #stairway
goHallway()
elif player.currentLoc == 2: #classroom1
goHallway()
elif player.currentLoc == 4: #second floor
goClassroom2()
else:
print("You can't go furhter South from here.")
elif cmd == "east":
if player.currentLoc == 0: #hallway
goClassroom1()
elif player.currentLoc == 3: #stairway
goSecondFloor()
elif player.currentLoc == 1: #bathroom
goHallway()
elif player.currentLoc == 4: #seconfloor
goDoorOut()
elif player.currentLoc == 5: #doorOut
goOutside()
elif player.currentLoc == 9: #library
answer = input("Would you like to go down the stairs? 'yes'or 'no'")
if answer.lower().strip() == "yes":
hallway()
elif answer.lower().strip() == "no":
print("You stay on the second floor")
goSecondFloor()
else:
print("You can't go further East from here.")
elif cmd == "west":
if player.currentLoc == 0: #hallway
goBathroom()
elif player.currentLoc == 2: #classroom1
goHallway()
elif player.currentLoc == 5: #doorout
goSecondFloor()
elif player.currentLoc == 4: #secondfloor
answer = input("Would you like to go down the stairs? 'yes'or 'no'")
if answer.lower().strip() == "yes":
goHallway()
elif answer.lower().strip() == "no":
print("You stay on the second floor")
goLibrary()
elif player.currentLoc == 7: #outside
goDoorOut()
elif player.currentLoc == 3: #stairway
goLibrary()
else:
print("You can't go further West from here.")
else:
print("\nThis is not a valid command.")
if player.score == 50 or player.numberOfMoves == maxMoves:
showOutro()
def main():
showIntro()
setupPlayer()
gameLoop()
playAgain()
main()
|
2f9a8ff361746408c214205f910dd05d45c4f2cf | 02dirceu/jogo-forca | /forca.py | 5,162 | 3.796875 | 4 | import random
def jogar(): #Função responsável por executar o jogo abrindo todas as outras funções
abertura()
palavra_secreta = carrega_palavra_secreta()
lista_letras = letras_acertadas(palavra_secreta)
regras(palavra_secreta, lista_letras)
print("Fim do jogo")
def abertura(): #Abre uma mensagem de abertura
print("*********************************")
print("Bem vindo ao jogo de Forca!")
print("*********************************\n")
print("Uma dica: As palavras referem-se a frutas!")
def carrega_palavra_secreta(): #Lê um arquivo txt que contém as palavras do jogo
arquivo = open("Frutas.txt", "r")
palavras = []
for linha in arquivo:
palavras.append(linha.strip().upper())
arquivo.close()
palavra_secreta = palavras[random.randrange(0, len(palavras))]
return palavra_secreta
def letras_acertadas(palavra): #Transforma a palavra numa lista do formato ['_', '_', '_', '_']
return ["_" for letra in palavra]
def regras(palavra_secreta, lista_letras): #Define as regras do jogo: 7 chutes
erros = 0
enforcou = False
acertou = False
while (not enforcou) and (not acertou):
chute = input("\nEntre com uma letra para a forca: ").strip().upper()
index = 1
lista = []
if (chute in palavra_secreta) and (chute not in lista_letras):
palavra_certa(palavra_secreta,chute, lista, lista_letras, index)
else:
erros = erros + 1
desenha_forca(erros)
enforcou = erros == 7
acertou = "_" not in lista_letras
if not acertou:
print("Ainda faltam acertar {} letras".format(lista_letras.count("_")))
if (not enforcou):
print("Você ainda tem {} chance(s) até ser enforcado.".format(7 - erros))
print(lista_letras)
if (acertou):
mensagem_vencedor()
else:
mensagem_perdedor(palavra_secreta)
def palavra_certa(palavra_secreta,chute, lista, lista_letras, index): #introduz a letra acertada na lista ['_', '_', '_', '_']
for letra in palavra_secreta:
if (chute == letra):
lista.append(index)
lista_letras[index - 1] = chute
print("\nVocê acertou a letra {} que está na(s) posição(ões) {}".format(chute, lista))
def mensagem_vencedor(): #imprime uma mensagem para o vencedor
print("\n\nParabéns, você ganhou!")
print(" ___________ ")
print(" '._==_==_=_.' ")
print(" .-\\: /-. ")
print(" | (|:. |) | ")
print(" '-|:. |-' ")
print(" \\::. / ")
print(" '::. .' ")
print(" ) ( ")
print(" _.' '._ ")
print(" '-------' ")
def mensagem_perdedor(palavra_secreta): #imprime uma mensagem caso não acerte todas as letras
print("Puxa, você foi enforcado!")
print("A palavra era {}".format(palavra_secreta))
print(" _______________ ")
print(" / \ ")
print(" / \ ")
print("// \/\ ")
print("\| XXXX XXXX | / ")
print(" | XXXX XXXX |/ ")
print(" | XXX XXX | ")
print(" | | ")
print(" \__ XXX __/ ")
print(" |\ XXX /| ")
print(" | | | | ")
print(" | I I I I I I I | ")
print(" | I I I I I I | ")
print(" \_ _/ ")
print(" \_ _/ ")
print(" \_______/ ")
def desenha_forca(erros): #imprime a forca a cada erro do usuário
print("Você errou!\n\n")
print(" _______ ")
print(" |/ | ")
if(erros == 1):
print(" | (_) ")
print(" | ")
print(" | ")
print(" | ")
if(erros == 2):
print(" | (_) ")
print(" | \ ")
print(" | ")
print(" | ")
if(erros == 3):
print(" | (_) ")
print(" | \| ")
print(" | ")
print(" | ")
if(erros == 4):
print(" | (_) ")
print(" | \|/ ")
print(" | ")
print(" | ")
if(erros == 5):
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | ")
if(erros == 6):
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | / ")
if (erros == 7):
print(" | (_) ")
print(" | \|/ ")
print(" | | ")
print(" | / \ ")
print(" | ")
print("_|___ ")
print()
if (__name__ == "__main__"):
jogar()
|
c878db51505a2cd2b6aa05ba1cdbe1ce8e280419 | das888purnendu/number-to-word-convertor-python3 | /num_cal.py | 2,873 | 3.953125 | 4 | def ten(tn):
if(tn=="10"):
return "Ten"
elif(tn=="11"):
return "Eleven"
elif(tn=="12"):
return "Twelve"
elif(int(tn[1])>2):
return num(tn[1])+"teen"
def num(d):
if(d=="2"):
return "Twen"
elif(d=="3"):
return "Thir"
elif(d=="4"):
return "Four"
elif(d=="5"):
return "Fif"
elif(d=="6"):
return "Six"
elif(d=="7"):
return "Seven"
elif(d=="8"):
return "Eight"
elif(d=="9"):
return "Nine"
def nums(ds):
if(ds=="1"):
return "one"
elif(ds=="2"):
return "two"
elif(ds=="3"):
return "three"
elif(ds=="4"):
return "four"
elif(ds=="5"):
return "five"
elif(ds=="6"):
return "six"
elif(ds=="7"):
return "seven"
elif(ds=="8"):
return "eight"
elif(ds=="9"):
return "nine"
else:
return ""
def zz(dd):
if(dd[0]=="1"):
return "ten"
elif dd[0]!="0":
return num(dd[0])+"ty"
else:
return ""
def cal(dg):
if len(dg)==1:
return nums(dg)
elif dg[1]=="0":
return zz(dg)
elif(dg[0]=="1"):
return ten(dg)
else:
return num(dg[0])+"ty "+nums(dg[1])
def unit(n):
if len(n) >0 and len(n)<8:
ln=len(n)
if ln==1 or ln==2:
return cal(n)
elif ln==3:
if cal(n[0])!="":
return cal(n[0])+" Hundred "+cal(n[1:])
else:
return cal(n[1:])
elif ln==4:
if cal(n[0])!="":
return cal(n[0])+" Thousand "+unit(n[1:])
else:
return unit(n[1:])
elif ln==5:
if cal(n[:2])!="":
return cal(n[:2])+" Thousand "+unit(n[2:])
else:
return unit(n[2:])
elif ln==6:
if cal(n[0])!="":
return cal(n[0])+" Lakh "+unit(n[1:])
else:
return unit(n[1:])
elif ln==7:
if cal(n[:2])!="":
return cal(n[0:2])+" Lakh "+unit(n[2:])
else:
return unit(n[2:])
def conv(n):
ln=len(n)
if ln>0 and ln<8:
return(unit(n))
elif ln >7:
rem= len(n)-7
if unit(n[:rem])!="":
return unit(n[:rem])+" Crore "+unit(n[rem:])
else:
return unit(n[rem:])
n=input("Enter a amount to convert into word : ")
if len(n)<15 and len(n)>0:
res = conv(n)
if res=="":
res = "Zero Rupee"
else:
res+=" Rupees"
else:
res="Input length will be 1 to 14"
print(res)
|
f4da6a5a3e69dd7f94e517523d3ae60b370f1dfa | agustinpodesta/Python-Course | /ejercicios_python/torre_de_control.py | 2,469 | 4.09375 | 4 | class Cola:
'''Representa a una cola, con operaciones de encolar y desencolar.
El primero en ser encolado es tambien el primero en ser desencolado.
'''
def __init__(self):
'''Crea una cola vacia.'''
self.items = []
def encolar(self, x):
'''Encola el elemento x.'''
self.items.append(x)
def desencolar(self):
'''Elimina el primer elemento de la cola
y devuelve su valor.
Si la cola esta vacia, levanta ValueError.'''
if self.esta_vacia():
raise ValueError('La cola esta vacia')
return self.items.pop(0)
def esta_vacia(self):
'''Devuelve
True si la cola esta vacia,
False si no.'''
return len(self.items) == 0
class TorreDeControl:
'''Representa el trabajo de una torre de control de un aeropuerto con
una pista de aterrizaje. Los aviones que están esperando para aterrizar
tienen prioridad sobre los que están esperando para despegar.
'''
def __init__(self):
'''Crea la 'cola' de espera de aviones'''
self.items_arribo = []
self.items_partida = []
def nuevo_arribo(self, avion):
'''Encola el avion que esta esperando aterrizar'''
self.items_arribo.append(avion)
def nueva_partida(self, avion):
'''Encola el avion que esta esperando despegar'''
self.items_partida.append(avion)
def ver_estado(self):
'''
Devuelve el estado de espera de aqellos aviones que
quieren aterrizar y aquellos que quieren partir
'''
print('Vuelos esperando para aterrizar:', ', '.join(self.items_arribo))
print(f'Vuelos esperando para despegar:', ', '.join(self.items_partida))
def asignar_pista(self):
'''
Elimina el primer elemento de la cola de aviones esperando aterrizar.
Cuando no haya mas aviones esperando arribar, elimina el primer
elemento de la cola de aviones esperando despegar.
'''
if not len(self.items_arribo) == 0:
print(f'El vuelo {self.items_arribo.pop(0)} aterrizó con exito')
return
elif len(self.items_partida) == 0:
print('No hay vuelos en espera.')
return
else:
print(f'El vuelo {self.items_partida.pop(0)} despegó con exito')
return
|
f9906f84e4705ddaa794cc2c7ef5e0bb9f1a4433 | Mr0grog/ca-covid-vaccination-stats | /ca_covid_vaccination_stats.py | 13,188 | 3.515625 | 4 | from ca_counties import california_counties
from datetime import datetime
import dateutil.tz
import json
import requests
PACIFIC_TIME = dateutil.tz.gettz('America/Los_Angeles')
def parse_tableau_json_stream(raw):
"""
Tableau's data is a series of JSON blobs, each preceded by the number of
bytes or characters (not sure which) in the JSON blob. The number is
delimited from the JSON by a semicolon. For example:
21;{"some": "json data"}16;{"more": "json"}
This is probably meant to be a streaming format (read up to the semicolon,
parse the number, read that many more bytes, and emit that data), though we
are treating it as a complete string here.
"""
remainder = raw
chunks = []
while remainder:
try:
size_string, remainder = remainder.split(';', 1)
except ValueError:
chunks.append(remainder)
break
else:
size = int(size_string)
chunk = remainder[:size]
remainder = remainder[size:]
data = json.loads(chunk)
chunks.append(data)
return chunks
def get_tableau_data(view, subview):
"""
Load the main data powering a Tableau Dashbaord. Returns a list of
dictionaries with data (the first is usually overall layout and structure,
while the second is usually data).
To find the arguments for this function, find the markup where a Tableau
dashbaord is embedded on a page. It'll usually be something like:
<object class="tableauViz" style="display:none;">
<param name="host_url" value="https://public.tableau.com/">
<param name="embed_code_version" value="3">
<param name="site_root" value="">
<param name="name" value="COVID-19VaccineDashboardPublic/Vaccine">
<param name="tabs" value="no">
<param name="toolbar" value="yes">
<param name="static_image"
value="https://public.tableau.com/static/images/CO/COVID-19VaccineDashboardPublic/Vaccine/1.png">
<param name="animate_transition" value="yes">
<param name="display_static_image" value="yes">
<param name="display_spinner" value="yes">
<param name="display_overlay" value="yes">
<param name="display_count" value="yes">
<param name="language" value="en">
<param name="filter" value="publish=yes">
</object>
We care most about the ``<param name="name" `...>`` element. Its ``value``
attribute contains the view and subview, separated by a forward slash. So
in the above example, we have:
<param name="name" value="COVID-19VaccineDashboardPublic/Vaccine">
And you'd get the corresponding data by calling this function with:
get_tableau_data('COVID-19VaccineDashboardPublic', 'Vaccine')
"""
# Use a session because we want to keep cookies around. The first request
# sets up cookies and generates a session ID, which is needed for the next
# request, that actually gets the data.
session = requests.Session()
dashboard_response = session.get(
f'https://public.tableau.com/interactive/views/{view}/{subview}',
params={
':embed': 'y',
':showVizHome': 'no',
':host_url': 'https://public.tableau.com/',
':embed_code_version': 3,
# ':tabs': 'no',
# ':toolbar': 'yes',
# ':animate_transition': 'yes',
# ':display_static_image': 'no',
# ':display_spinner': 'no',
# ':display_overlay': 'yes',
# ':display_count': 'yes',
# ':language': 'en',
# 'publish': 'yes',
# ':loadOrderID': 0,
},
# headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:87.0) Gecko/20100101 Firefox/87.0'}
)
tableau_session = dashboard_response.headers.get('x-session-id')
# Load actual data.
data_url = f'https://public.tableau.com/vizql/w/{view}/v/{subview}/bootstrapSession/sessions/{tableau_session}'
# TODO: Revisit and trim down the POST data here if possible.
# There's a lot here, and for the sake of time, I'm just using the data
# from an actual browser session. There's probably plenty that's not
# actually required.
post_data = {
'worksheetPortSize': '{"w":737,"h":500}',
'dashboardPortSize': '{"w":737,"h":500}',
'clientDimension': '{"w":737,"h":550}',
'renderMapsClientSide': 'true',
'isBrowserRendering': 'true',
'browserRenderingThreshold': '100',
'formatDataValueLocally': 'false',
'navType': 'Nav',
'navSrc': 'Boot',
'devicePixelRatio': '2',
'clientRenderPixelLimit': '25000000',
'allowAutogenWorksheetPhoneLayouts': 'false',
'sheet_id': 'Vaccine',
'showParams': '{"checkpoint":false,"refresh":false,"refreshUnmodified":false,"unknownParams":":embed_code_version=3&publish=yes"}',
'stickySessionKey': ('{"dataserverPermissions":"44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a",'
'"featureFlags":"{\\"MetricsAuthoringBeta\\":false}",'
'"isAuthoring":false,'
'"isOfflineMode":false,'
'"lastUpdatedAt":1613242758888,'
'"workbookId":7221037}'),
'filterTileSize': '200',
'locale': 'en_US',
'language': 'en',
'verboseMode': 'false',
':session_feature_flags': '{}',
'keychain_version': '1',
}
data_response = session.post(data_url, data=post_data)
# NOTE: it *might* be more correct to use data_response.content, but then
# we need to do some more fancy footwork with character decoding. In the
# mean time, using the decoded text here actually seems to work fine.
return parse_tableau_json_stream(data_response.text)
def get_tableau_values(data):
"""
Tableau's data lists all the values used throughout the view in a single
place, and the display information about each chart references these values
by data type (int, cstring, etc.) and index.
Return a simplified version of this: a dict mapping data types to lists of
values.
"""
data_values = (data[1]
['secondaryInfo']
['presModelMap']
['dataDictionary']
['presModelHolder']
['genDataDictionaryPresModel']
['dataSegments']
['0']
['dataColumns'])
return {valueset['dataType']: valueset['dataValues']
for valueset in data_values}
def tableau_column_data_value_references(column_data_object):
return (column_data_object.get('valueIndices') or
column_data_object.get('aliasIndices') or
column_data_object['tupleIds'])
def parse_tableau_chart(chart_definition, values_by_type):
"""
Parse the data underlying a chart in a Tableau dashboard. Returns a list of
dicts.
"""
columns = chart_definition['presModelHolder']['genVizDataPresModel']['paneColumnsData']
definitions = columns['vizDataColumns']
column_data = columns['paneColumnsList'][0]['vizPaneColumns']
# Simplify column definitions by calculating the name and joining the
# references in.
column_model = [{
'name': column.get('fieldCaption') or column.get('fn'),
'dataType': column.get('dataType'),
'references': tableau_column_data_value_references(column_data[index])
} for index, column in enumerate(definitions)]
# Pivot from columns to rows and dereference each value.
result = []
for row_index in range(len(column_model[0]['references'])):
row = {}
for column in column_model:
reference = column['references'][row_index]
if column['dataType']:
row[column['name']] = values_by_type[column['dataType']][reference]
else:
row[column['name']] = reference
result.append(row)
return result
def parse_tableau_value_chart(chart_definition, values_by_type, field_name):
data = parse_tableau_chart(chart_definition,
values_by_type)
return data[0][field_name]
def get_stats_from_tableau():
"""
Get the top-line stats (administered/shipped/delivered) come from a Tableau
dashboard.
"""
data = get_tableau_data('COVID-19VaccineDashboardPublicv2', 'Vaccine')
values_by_type = get_tableau_values(data)
charts = (data[1]
['secondaryInfo']
['presModelMap']
['vizData']
['presModelHolder']
['genPresModelMapPresModel']
['presModelMap'])
county_shots = parse_tableau_chart(charts['County Admin Bar'], values_by_type)
shots_by_county = {county_key(row['County']): row['SUM(Dose Administered)']
for row in county_shots}
all_tableau_data = {
'state': {
'administered': parse_tableau_value_chart(
charts['Administered'],
values_by_type,
'SUM(Dose Administered)'
),
'administered_per_day_avg': parse_tableau_value_chart(
charts['Administered'],
values_by_type,
'SUM(Daily Avg)'
),
'fully_vaccinated': parse_tableau_value_chart(
charts['Administered'],
values_by_type,
'SUM(Fully Vaccinated)'
),
'partially_vaccinated': parse_tableau_value_chart(
charts['Administered'],
values_by_type,
'SUM(Partially Vaccinated)'
),
'delivered': parse_tableau_value_chart(
charts['Delivered'],
values_by_type,
'SUM(Doses Delivered)'
),
'cdc_ltcf_delivered': parse_tableau_value_chart(
charts['Delivered CDC'],
values_by_type,
'SUM(Doses Delivered)'
),
},
'counties': shots_by_county
}
return all_tableau_data
def reformat_grouping(group_data):
return [{'group': group['CATEGORY'], 'value': group['METRIC_VALUE']}
for group in group_data]
def get_groupings_for_location(location):
"""
Stats by category (age, ethnicity, gender) come from separate JSON files
at well-known URLs for each county.
"""
race_ethnicity_url = f'https://files.covid19.ca.gov/data/vaccine-equity/race-ethnicity/vaccines_by_race_ethnicity_{location}.json'
age_url = f'https://files.covid19.ca.gov/data/vaccine-equity/age/vaccines_by_age_{location}.json'
gender_url = f'https://files.covid19.ca.gov/data/vaccine-equity/gender/vaccines_by_gender_{location}.json'
race_ethnicity = requests.get(race_ethnicity_url).json()
age = requests.get(age_url).json()
gender = requests.get(gender_url).json()
return {
'region': location,
'latest_update': race_ethnicity['meta']['LATEST_ADMIN_DATE'],
'race_ethnicity': reformat_grouping(race_ethnicity['data']),
'age': reformat_grouping(age['data']),
'gender': reformat_grouping(gender['data']),
}
def get_groupings():
return {
'state': get_groupings_for_location('california'),
'counties': {name: get_groupings_for_location(name)
for name in california_counties}
}
def county_key(name):
return name.lower().replace(' ', '_')
def cli():
tableau = get_stats_from_tableau()
groups = get_groupings()
state = groups['state'].copy()
state.update(tableau['state'])
counties = {}
for name in california_counties:
county = groups['counties'][name].copy()
county['total_administered'] = tableau['counties'][name]
counties[name] = county
# TODO: there should probably be some work done to verify that the last
# updated dates for all the various data sources match and use those dates
# instead of the current date.
# One issue here is that it's not clear whether the grouping data files are
# updated at the same/similar time as the Tableau dashboard. It's also
# unclear whether the date on the Tableau dashbaord is correct. For
# example, on 2/14/2021 at 18:53 Pacific, the dashboard reads:
#
# "Data: 2/14/2021 11:59pm | Posted: 2/15/2021"
#
# Both these dates are in the future. It could be that this is UTC, or it
# could just be innacurate. Another questionable point here is that these
# dates appear in the data, but not the data *time*, which makes it unclear
# whether "11:59pm" is simply hard-coded.
result = {
'date': datetime.now(tz=PACIFIC_TIME).date().isoformat(),
'state': state,
'counties': counties
}
print(json.dumps(result))
if __name__ == '__main__':
cli()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.