blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
17932e97ff3da05e2b61597ddb09456548999773 | markabrennan/code_challenges | /buy_sell_stock.py | 2,028 | 3.640625 | 4 | """
Classic greedy search problem
from Interview Cake
Three Versions - third one is from Interview Cake
"""
def gf3(l):
mn = l[0]
mx = None
for i in range(1, len(l)):
cur = l[i]
if mx is None:
mx = cur - mn
else:
mx = max(cur-mn, mx)
mn = min(cur, mn)
return mx
def gf2(l):
if len(l) < 2:
return 0
print(f'l: {l}')
prev = l[0]
cur = l[1]
mx = cur - prev
for i in range(2, len(l)):
cur = l[i]
print(f'cur: {cur} | prev: {prev} | mx: {mx} | cur-prev: {cur-prev}')
if cur > prev:
mx = max(mx, cur-prev)
else:
prev = cur
return mx
def get_max_profit(stock_prices):
if len(stock_prices) < 2:
raise ValueError('Getting a profit requires at least 2 prices')
# We'll greedily update min_price and max_profit, so we initialize
# them to the first price and the first possible profit
min_price = stock_prices[0]
max_profit = stock_prices[1] - stock_prices[0]
# Start at the second (index 1) time
# We can't sell at the first time, since we must buy first,
# and we can't buy and sell at the same time!
# If we started at index 0, we'd try to buy *and* sell at time 0.
# This would give a profit of 0, which is a problem if our
# max_profit is supposed to be *negative*--we'd return 0.
for current_time in range(1, len(stock_prices)):
current_price = stock_prices[current_time]
# See what our profit would be if we bought at the
# min price and sold at the current price
potential_profit = current_price - min_price
# Update max_profit if we can do better
max_profit = max(max_profit, potential_profit)
# Update min_price so it's always
# the lowest price we've seen so far
min_price = min(min_price, current_price)
return max_profit
# test cases
p1 = [10, 7, 5, 8, 11, 9]
p2 = [10, 7, 5, 8, 11, 9, 2]
p3 = [9, 7, 4, 1]
|
19d78d4f96bf20e7317d43cd656ea071ea496556 | appu0308/python | /repl.it/main.py | 1,332 | 4.1875 | 4 | #import reverse_sentence.py
'''Problem Statement
Write a script that performs the following tasks serially:
Create an empty list 'emplist1' using list operation.
Print 'emplist1'.
Append to empty list 'emplist1' created above with element 9.
Append another element 10 to 'emplist1'.
Print 'emplist1'.
Create an empty list 'emplist2' using [].
Print 'emplist2'.
Extend the empty list 'emplist2' created above with elements 'a', 'b', 'c'.
Print 'emplist2'.
Remove the last element of 'emplist2', and assign it to variable 'e'.
Print 'emplist2'.
Print the variable 'e'.
'''
emplist1=[]
print(emplist1)
emplist1.append(9)
emplist1.append(10)
print(emplist1)
emplist2=[]
print(emplist2)
emplist2.append('a')
emplist2.append('b')
emplist2.append('c')
print(emplist2)
emplist2.remove('c')
emplist2.append('e')
print(emplist2)
'''Problem Statement
Write a script that performs the following tasks serially:
Create an empty tuple 'tup1' using tuple operation.
Print 'tup1'.
Create another tuple 'tup2', by passing 'Welcome' string as argument to tuple function.
Print 'tup2'.
Find and print the count of character 'e' in 'tup2'.
Determine the index of character 'e' in 'tup2' and print it.
Find the length of tuple 'tup2' and print it.
'''
'''
tup1=tuple()
print(tup1)
tup2=tuple('Welcome')
print(tup2.index('e'))
print(len(tup2))'''
|
ff68de078c8591fc2858d6fc4ba9208ff700f2ef | jdutton1439/python-syntax | /python-syntax/words.py | 970 | 4.40625 | 4 | def print_upper_words1(words):
"""
Prints each word from the words list in upper case
"""
for word in words:
print(word.upper())
def print_upper_words2(words):
"""
Prints each word from words list that
starts with 'e' or 'E' in upper case
"""
for word in words:
if word.startswith("e") or word.startswith("E"):
print(word.upper())
def print_upper_words3(words, must_start_with):
"""
Prints each word from the words list that
starts with the values in must_start_with
in upper case
"""
for word in words:
for letter in must_start_with:
if word.startswith(letter):
print(word.upper())
print_upper_words1(["hello","hey","yo","goodbye","yes"])
print_upper_words2(["hello","eagle","yo","goodbye","yes","Ethereal"])
print_upper_words3(["hello","eagle","yo","goodbye","yes","Ethereal"], {"e","y"}) |
da7072e6aaa4f93aa2e2c9b2006537345d6b8939 | sicou2-Archive/pcc | /python_work/part1/ch08/c8_1.py | 4,229 | 4.59375 | 5 | def display_message():
'''Displays a summary of what was learned in Chapter 8'''
print('We learned about creating and using Functions in the Python '
'programming\n language!')
display_message()
print('\nNEXT 8_2')
def favorite_book(book):
'''Displays the title of the users favorite book'''
print(f'My favorite book is "{book.title()}".')
favorite_book('where is joe merchant')
print('\nNEXT 8_3 and 8_4')
def make_shirt(size, message='I love Python'):
'''Informs the user of the size of shirt and message requested.'''
print(f"The size of the shirt will be {size}. The message will have"
f" a badass typeset,\nwith bold colors, and say, "
f"'{message}'.")
make_shirt('S', 'Howdy dammit!')
print('Next shirt')
make_shirt('L')
print('Next shirt')
make_shirt('M')
print('\nNEXT 8_5')
def describe_city(city, country='Canada'):
print(f"{city.title()} is in {country.title()}")
describe_city('montreal')
describe_city('toronto')
describe_city('london', 'england')
print('\nNEXT 8_6')
def city_country(city, country):
c_and_c = f'{city}, {country}'
return c_and_c.title()
print(city_country('austin', 'texas'))
print(city_country('petoria', 'south africa'))
print(city_country('tillinton', 'england'))
print('\nNEXT 8_7 and 8_8')
def make_album(artist, album, songs=None):
if songs:
music_album = {
'Artist': artist.title(),
'Album': album.title(),
'Number of songs': songs
}
else:
music_album = {
'Artist': artist.title(),
'Album': album.title(),
}
return music_album
# while True: #No I am not going to do another q to quit thing. No. Not now.
# artist_text = 'Please enter the name of the artist/band. \n>>>'
# album_text = 'Please enter the name of the album. \n>>>'
# songs_text = 'If known please enter the number of songs on the album. \n'
# 'Otherwise please leave blank or enter 0 (zero) \n>>>'
# artist = input(artist_text)
# album = input(album_text)
# songs = input(songs_text)
# print(make_album(artist, album, songs))
#print(make_album('boston','dont look back', 5))
#print(make_album('metalica','fuel', 8))
#print(make_album('pink floyd','the wall'))
print('\nNEXT 8_9')
messages = [
'Dog is a good boy!',
'Gypsy is a good girl!',
'Hans is a good boy!',
'Blaze is a good boy!',
'Kidd was a good boy!',
]
def print_messages(to_print):
for item in to_print:
print(item)
print_messages(messages)
print('\nNEXT 8_10 and 8_11')
messages = [
'Dog is a good boy!',
'Gypsy is a good girl!',
'Hans is a good boy!',
'Blaze is a good boy!',
'Kidd was a good boy!',
]
messages_sent = []
def send_messages(text_messages):
while text_messages:
to_send = text_messages.pop(0)
print('\nSENDING TEXT MESSAGE: ')
print(to_send)
print('MESSAGE SENT')
messages_sent.append(to_send)
send_messages(messages[:])
print('Messages: ', messages, 'Sent: ', messages_sent)
print('\nNEXT 8_12')
def sandwich_toppings(*args):
print("\nThe requested toppings for the next order are: ")
for topping in args:
print(f"- {topping}")
print("BUILDING ORDER")
sandwich_toppings('eggs', 'ash')
sandwich_toppings('salmon', 'salt', 'pickles')
sandwich_toppings('sand', 'bacon', 'cat meat', 'zinc')
print('\nNEXT 8_13')
def user_profile(first, last, **kwargs):
print(f"This is what we know about {first.title()} {last.title()}: ")
for key, fact in kwargs.items():
print(f"- {key} : {fact.title()}")
user_profile('dan','jones', hair='blond', build='average')
print('\nNEXT 8_14')
def car_info(manufacture, model, **kwargs):
car_dict = {}
car_dict['make'] = manufacture
car_dict['model'] = model
for key, value in kwargs.items():
car_dict[key] = value
return car_dict
car_1 = car_info('subaru', 'outback', color='blue', tow_package=True)
print(car_1)
|
3276b202f272cc2d24178b1b32c5241e16c46a3c | nikhil-aivalli/Getting-Started-with-Python-wrt-Datascience | /Day1.py | 2,999 | 4.09375 | 4 | """
Guido Vasn Rossum
1991
www.poojaangurala.com
starting with python
data types
sequence types
"""
x=5
print(x)
print(type(x))
y=5.6
print(type(y))
s='hello'
print(type(s))
b=True
print(type(b))
#sequence types
#list
l=[1,3,5,'abc']
print(type(l))
#tuple
t=('nikhil',22,'hubballi')
print(type(t))
l[1]
l[0:3]
l[2:]
l1=[1,2,3,4,5,6,7,8,9,0,12,12,223,133,33,11,33,22,'ds',(100,101,102)]
l1[2:]
l1[4]
#in operator
3 in l #output-true
3 in t #output-false
3 not in t #output-true
'a' in s #output-false
'll' in s #output-true
'lol' in s #output-false
#airthmatic operators
x+y
x-y
x*y
x/y
x%y
x^y
2^2 #exponent 2e^2
2**2 #power
"""
create two lists,
two tuples,
two strings
then apply '+' on them
and print
"""
list1=[1,2,3]
list2=['a','b','c']
tuple1=('x','y',3)
tuple2=(4,5,6)
print(list1+list2)
print(tuple1+tuple2)
list1+list2
tuple1+tuple2
#'*' operator
t1=t*2
l2=l*2
a= input()
print(a)
b= input(' ')
print(b)
c='HI AKXDM SAKCM'
print (c.lower())
print (len(c))
#count gives number of occurence of the specified character
print (c.count('A'))
#find gives index of first occurence of the specified character
print (c.find('A'))
print(c.isdigit()) #output-false
print(c.isalpha()) #output-false
c1=c.split()
c2=" ".join(c1)
print(type(c1)) #list
print(type(c2)) #string
str1="hi kcks kskc kmm"
str2=str1.split()
z="asdfd"
print(z+"nikhil")
z[2:5]
##########################################
str=input()
if str.isalpha():
print(str[2:].upper()+str[:2].upper()+ "J1")
else :
print("enter a valid string")
###################################################
#function of list
l=[1,3,5,'abc']
l.append('nikhi')
l.append(3)
l.count(3)
l.remove(3)
del l[2]
l[2]='csdcs'
l[4]='jkij'
l.insert(4,56)
t=('ds',85)
l.extend(t)
l1=list(t)
l.reverse()
l4=[1,2,3,4,5,6,7,8,9,0,12,12,223,133,33,11,33,22,'ds',(100,101,102)]
l4.sort()
l4.pop(1)
l5=[2,3,4,3,43,43,432,43423,4,32423,42342,11111111111]
max(l5)
min(l5)
sum(l5)
for i in l5:
print(i)
l5.index(4)
t1=(2,34,33,1,'abc','a')
max(t1) #max min will not work for tuple with character value
#Dictionary
d={'name':'NIKHIL','occupation':'STUDENT','email':'nikhilaivalli@gmail.com'}
d['contact']=7795933438
del d['occupation']
d.items()
d.keys()
d.values()
d1=d
d.clear()
# it will delete contents of both d1 and d as d1 is the copy of d.....d1 has only address of d
d.get('email')
d['sacsac'] #keyerror will get
d.get('cszfsd') #no error return null
d['age']=22
d['age']=23
d.popitem() # poped ('occupation', 'STUDENT')
for i in d.values():
print(i)
###########################################
l1=['INDIA','CHINA','USA','AUSTRELIA','SRILANKA']
l2=['10M','15M','5M','6M','1M']
d2=zip(l1,l2)
print(d2)
d2=dict(d2)
###################################################
-
|
95e9be4c7c2b616e2689dbd8d532391162bc85f1 | yyrrll/wizard | /2-data/2-hierarchy/3-interfaces/nested-mappings/exercises/42-eight-queens/given/check_solution/eight_queens.py | 1,255 | 3.640625 | 4 | #!/usr/bin/env python
# NB: output needs manipulation to match Racket solution output
BOARD_SIZE = 8
def under_attack(column, existing_queens):
# ASSUMES that row = len(existing_queens) + 1
row = len(existing_queens)+1
for queen in existing_queens:
r,c = queen
if r == row: return True # Check row
if c == column: return True # Check column
if (column-c) == (row-r): return True # Check left diagonal
if (column-c) == -(row-r): return True # Check right diagonal
return False
def solve(n):
if n == 0: return [[]] # No RECURSION if n=0.
smaller_solutions = solve(n-1) # RECURSION!!!!!!!!!!!!!!
solutions = []
for solution in smaller_solutions:# I moved this around, so it makes more sense
for column in range(1,BOARD_SIZE+1): # I changed this, so it makes more sense
# try adding a new queen to row = n, column = column
if not under_attack(column , solution):
solutions.append(solution + [(n,column)])
return solutions
solutions = solve(8)
sorted_solutions = []
for solved in solutions:
sorted_solutions.append(tuple(sorted(solved, key=lambda x: x[0], reverse=True)))
import pprint
pprint.pprint(sorted_solutions)
|
0513de49071f988140747bddf9c5050e7b711f01 | qeedquan/challenges | /codegolf/shortest-power-set-implementation.py | 1,597 | 4.875 | 5 | #!/usr/bin/env python
"""
Problem definition
Print out the powerset of a given set. For example:
[1, 2, 3] => [[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
Each element is to be printed on a separate line, so the above example would be printed as:
[]
[1]
[2]
...
[1, 2, 3]
Example code (in D, python example here):
import std.stdio;
string[][] powerset(string[] set) {
if (set.length == 1) {
return [set, []];
}
string[][] ret;
foreach (item; powerset(set[1 .. $])) {
ret ~= set[0]~item;
ret ~= item;
}
return ret;
}
void main(string[] argv) {
foreach (set; powerset(argv[1 .. $]))
writeln(set);
}
Input
Elements will be passed as arguments. For example, the example provided above would be passed to a program called powerset as:
powerset 1 2 3
Arguments will be alphanumeric.
Rules
No libraries besides io
Output does not have to be ordered
Powerset does not have to be stored, only printed
Elements in the set must be delimited (e.g. 1,2,3, [1,2,3] and ['1','2','3'] are acceptable, but 123 is not
Trailing delimiters are fine (e.g. 1,2,3, == 1,2,3)
Best is determined based on number of bytes
The best solution will be decided no less than 10 days after the first submission.
"""
def powerset(a):
l = []
n = 1 << len(a)
for i in range(n):
p = []
for j in range(len(a)):
if i&(1<<j) != 0:
p.append(a[j])
l.append(p)
return l
def main():
print(powerset([1, 2, 3]))
print(powerset(['a', 'b']))
main()
|
7c8e09e94b69d6347bcd4941a08831cc576db965 | LP13972330215/algorithm010 | /Week06/不同路径.py | 429 | 3.671875 | 4 | #!/usr/bin/python3
#Author:pliu
class Solution:
'''动态规划。时间复杂度:O(n*m)、空间复杂度O(n)'''
def uniquePaths(self, m, n):
#m、n必须大于2且为正整数
cur = [1] * n #将两维压缩成一维
for i in range(1, m):
for j in range(1, n):
cur[j] += cur[j-1]
return cur[-1]
if __name__ == '__main__':
Solution().uniquePaths(6,5)
|
6f01e95207388c0cb69c11a0e83a19a9d69efd84 | MohammadAsif206/Revature | /PyDay1/function.py | 1,307 | 3.984375 | 4 | # function is a reusable chunk of code, they can have parameters where you pass in arguments
#def for define
# void functions do not return anything, if you do not return anything it returns None
# highly recommend for functions do type annotation
def hello():
print("This is a simple funciton")
print("it just says Hello")
def greet_person(name):
print("Hello " + name)
hello()
greet_person("Mohammad")
# I highly recommend using type annotation for your functions
def greater_number(num1:float, num2: float) -> float:
if num1 > num2:
return num1
else:
return num2
i = greater_number(90.1, 45.4)
print(i)
# take in
def num_caps(phrase: str) -> int:
pass # allows the code compile showing this function is not implemented yet
counter = 0
for c in phrase:
if c.isupper():
counter += 1
return counter
ups = num_caps("sldnDALCAlCATAC")
print(ups)
# in python you can pass argument in posionally like, java or js
def multi_print(phrase: str, times: int) -> None:
for i in range(times):
print(phrase)
multi_print("Hello Everyone", 10)
#f you can pass funciton using the named variables
# the below two lines of codes are identical
multi_print(times=10, phrase="Hello Everyone")
multi_print(phrase="Hello Everyone", times=10) |
ebd6810bfacde8e3bc08460de4ef6657641072ea | yordanivh/intro_to_cs_w_python | /chapter10/examples/writing_files/total.py | 1,098 | 3.90625 | 4 | from typing import TextIO
from io import StringIO
def sum_number_pairs(input_file: TextIO, output_file: TextIO) -> None:
"""Read the data from input_file, which contains two floats per line
separated by a space. output_file for writing and for each line in input_file
write a line to output_file that contains the two floats from the corresponding line of input_file plus a space and the sum of the two
floats.
>>> infile = StringIO('1.3 3.4\\n2 4.2\\n-1 1\\n')
>>> outfile = StringiO()
>>> sum_number_pairs(infile, outfile)
>>> outfile.getvalue()
'1.3 3.4 4.7\\n2 4.2 6.2\\n-1 1 0.0\\n'
"""
for number_pair in input_file:
number_pair = number_pair.strip()
operands = number_pair.split()
total = float(operands[0]) + float(operands[1])
new_line = '{0} {1}\n'.format(number_pair, total)
output_file.write(new_line)
if __name__ == '__main__':
with open('number_pairs.txt', 'r') as input_file, \
open('number_pairs_sums.txt', 'w') as output_file:
sum_number_pairs(input_file, output_file)
|
bac39338175d2628b70a62d99297e8b624613546 | puneethnr/Code | /Programs/Amazon/IsBSTValid.py | 1,385 | 3.53125 | 4 |
from Data_Structures.BinarySearchTrees.BinarySearchTree import (
BinarySearchTree
)
from Data_Structures.Utilities.BinarySearchTreeNode import BinarySearchTreeNode
def isBSTValid(binartSearchTree):
return valid(binartSearchTree, float("-inf"), float("inf"))
def valid(node, left, right):
if node is None:
return True
if not (node.value > left and node.value < right):
return False
return valid(node.left, left, node.value) and valid(node.right, node.value, right)
def isBSTValidInOrderTraversal(binartSearchTree):
q = []
return valid(binartSearchTree, q)
def valid(node, q):
if node is None:
return True
lenght = len(q)
if lenght > 1 and not (q[lenght-1] > q[lenght - 2]):
return False
leftRes = valid(node.leftSubNode, q)
q.append(node.value)
rightRes = valid(node.rightSubNode, q)
return leftRes and rightRes
# root = BinarySearchTreeNode("M", 123)
# root.leftSubNode = BinarySearchTreeNode("K", 120)
# root.rightSubNode = BinarySearchTreeNode("R", 234)
# print(isBSTValid(root))
root = BinarySearchTreeNode("M", 123)
root.leftSubNode = BinarySearchTreeNode("K", 120)
root.leftSubNode.leftSubNode = BinarySearchTreeNode("K", 100)
root.leftSubNode.rightSubNode = BinarySearchTreeNode("K", 121)
root.rightSubNode = BinarySearchTreeNode("R", 234)
print(isBSTValidInOrderTraversal(root)) |
c8e8e6d94c8081be0c1c47c98b955ce70b5e0719 | rodolfosgarcia/CodingChallenges | /Twitter-NewStack.py | 730 | 3.9375 | 4 | """
Implement a class for a stack that supports all the regular functions (push, pop) and an additional function of max() which returns the maximum element in the stack
(return None if the stack is empty). Each method should run in constant time.
"""
class MaxStack:
def __init__(self):
self.s = []
self.max_s = 0
def push(self, val):
self.s.append(val)
self.max_s = max(self.max_s, val)
def pop(self):
if s.max():
self.s.pop()
self.max_s = max(self.s)
def max(self):
return self.max_s if self.max_s else None
s = MaxStack()
print (s.max())
s.push(1)
s.push(2)
s.push(3)
s.push(2)
print (s.max())
# 3
s.pop()
s.pop()
print (s.max())
# 2 |
06651ec07844894ed03c15434920489767559f7e | Bwh50h3n/Year9designpythonLJ | /Year10codingLJ/Sudo_code/Fraction_action.py | 1,629 | 3.890625 | 4 |
def getWholeNumAndFraction(numerator,denominator):
remainder = numerator%denominator
wholenum = (numerator-remainder)/denominator
return([int(wholenum),remainder,denominator])
def findGCF(numerator,denominator):
result = False
while result == False:
if numerator > denominator:
numerator = numerator-denominator
if numerator < denominator:
denominator = denominator-numerator
if numerator == denominator:
result = True
return numerator
def simplifyFraction(numerator,denominator):
GCF = findGCF(numerator,denominator)
return([int(numerator/GCF),int(denominator/GCF)])
def getAnswer():
numerator = int(input("numerator"))
denominator = int(input("denom"))
if getWholeNumAndFraction(numerator,denominator)[1]==0:
print(str(getWholeNumAndFraction(numerator,denominator)[0]))
elif getWholeNumAndFraction(numerator,denominator)[0]==0:
new_numerator = simplifyFraction(getWholeNumAndFraction(numerator,denominator)[1],getWholeNumAndFraction(numerator,denominator)[2])[0]
new_denominator = simplifyFraction(getWholeNumAndFraction(numerator,denominator)[1],getWholeNumAndFraction(numerator,denominator)[2])[1]
print(str(new_numerator)+"/" +str(new_denominator))
else:
new_numerator = simplifyFraction(getWholeNumAndFraction(numerator,denominator)[1],getWholeNumAndFraction(numerator,denominator)[2])[0]
new_denominator = simplifyFraction(getWholeNumAndFraction(numerator,denominator)[1],getWholeNumAndFraction(numerator,denominator)[2])[1]
print(str(getWholeNumAndFraction(numerator,denominator)[0])+" "+str(new_numerator)+"/" +str(new_denominator))
while(True):
getAnswer()
|
11a772d226543c8f72ac7c87e04e2f4c19a5905c | pritam1997/python | /game_with_AI.py | 687 | 4.09375 | 4 | import random
print("Rock Paper Scissor Game :\n")
ai = random.randint(1,3)
if ai == 1:
p1 = "rock"
elif ai == 2:
p1 = "paper"
else:
p1 ="scissor"
# print(f"Player 1, choice of computer is : {p1}")
p2 = str(input("Player 2 Enter your choice :")).lower()
if p1 == p2:
print("Tie")
elif p1 == "rock":
if p2 == "scissor":
print("Player 1 win")
elif p2 == "paper":
print("Player 2 win")
elif p1 == "paper":
if p2 == "scissor":
print("Player 2 win")
elif p2 == "rock":
print("Player 1 win")
elif p1 == "scissor":
if p2 == "rock":
print("Player 2 win")
elif p2 == "paper":
print("Player 1 win")
else:
print("something went wrong ") |
023ddceb2ac6552e6958878de35015f5224d7915 | serdarcw/my_workings | /Python/Konu anlatımları Python_dosya /f-string.py | 610 | 3.5625 | 4 | #fruit = 'Orange'
#vegetable = 'Tomato'
#amount = 6
#output = f"The amount of {fruit} and {vegetable} we bought are totally {amount} pounds"
#print(output)
#my_name = 'SERKAN'
#output = f"My name is {my_name.capitalize()}"
#print(output)
#name = "Joseph"
#job = "teachers"
#domain = "Data Science"
#message = (
#f"Hi {name}. "
#f"You are one of the {job} "
#f"in the {domain} section."
#)
#print(message)
#name = "Zahir"
#durum ="caliskan"
#soylenti ="bilinir"
#massage = f"{name}'in " \
# f"cok {durum} bir " \
# f"ogrenci oldugu {soylenti}."
#print(massage)
|
40e40e4720497110d1e541cf64f83cfe9ece022b | Harry12901/Hangman_ | /hangman.py | 800 | 3.828125 | 4 | from random import choice
def word_generator():
with open("wordlist.txt","r") as f:
lines = f.readlines()
#print(lines)
f.close()
lines = [i.strip("\n") for i in lines]
#print(lines)
return choice(lines)
word = word_generator()
print("LENGTH : {}".format(len(word)))
guess = ""
turns = int(len(word)*1.5)
unguessed=0
while True:
print("You are left with {} turns".format(turns))
inp = input("\nMake a guess: ")
turns-=1
unguessed=0
if inp in word:
guess = guess+inp
for i in word:
if i in guess:
print(i,end="")
else:
unguessed+=1
print('*',end="")
if unguessed==0:
print("\nWOn")
break
if turns ==0:
print("\nRan out of turns")
break
|
1528d5e248d8a25d43f6ebcd4ecc1348c73ee3d5 | boknowswiki/mytraning | /lintcode/python/0034_n_queens_II.py | 1,059 | 3.78125 | 4 | #!/usr/bin/python -t
# dfs
class Solution:
"""
@param n: The number of queens.
@return: The total number of distinct solutions.
"""
def totalNQueens(self, n):
# write your code here
if not n:
return 0
self.sum = set()
self.diff = set()
self.col = set()
self.ret = 0
self.dfs(0, n)
return self.ret
def dfs(self, row, n):
if row == n:
self.ret += 1
return
for i in range(n):
if i not in self.col and (row+i) not in self.sum and (row-i) not in self.diff:
self.col.add(i)
self.sum.add(row+i)
self.diff.add(row-i)
self.dfs(row+1, n)
self.col.remove(i)
self.sum.remove(row+i)
self.diff.remove(row-i)
return
if __name__ == '__main__':
s= 2
ss = Solution()
print "answer is %s" % ss.totalNQueens(s)
|
499b77e727ee2b826a2b29d4f9baa9f930f2cbdf | JohnC3/Misc-Projects | /sorts_from_memory/staturday/quicksort.py | 1,085 | 4 | 4 | import random
def shuffle_around(array, left, right):
print("INPUT", array, array[left: right])
pivot_idx = left
pivot = array[pivot_idx]
print("INPUT", array, array[left: right], "pivot value", pivot)
# array[pivot_idx], array[left] = array[left], array[pivot_idx]
lesser_idx = left + 1
for i in range(left + 1, right):
if array[i] < pivot:
array[i], array[lesser_idx] = array[lesser_idx], array[i]
lesser_idx += 1
# Now swap lesser_idx with piv lesser_idx is 1 more then the idex of the number less then pivot
array[lesser_idx - 1], array[pivot_idx] = array[pivot_idx], array[lesser_idx - 1]
print(array)
return lesser_idx - 1
def quick_sort(array, left, right):
if left < right:
partition_location = shuffle_around(array, left, right)
quick_sort(array, left, partition_location)
quick_sort(array, partition_location + 1, right)
if __name__ == "__main__":
pass
tc = [5, 3, 1, 77, 51, 2]
quick_sort(tc, 0, len(tc))
print(tc)
print(tc == sorted(tc)) |
0d9e502b96c5692087825c94af9fb6a58c534fc0 | Oracy/curso_em_video | /Exercicios/017.py | 221 | 3.53125 | 4 | import math
cat_op = float(input('Cateto Oposto: '))
cat_ad = float(input('Cateto Adjacente: '))
hipotenusa = round(math.hypot(cat_op, cat_ad), 2)
print('Hipotenusa de {0} e {1} = {2}'.format(cat_op, cat_ad, hipotenusa)) |
d08f73067ef06fa2590045e1cec3d0d5fe709333 | gabriellaec/desoft-analise-exercicios | /backup/user_148/ch131_2020_04_01_18_30_03_600234.py | 543 | 3.828125 | 4 | import random
#Fase de dicas
d1 = random.randint(1, 10)
d2 = random.randint(1, 10)
s = d1+d2
print('Inicialmnete você possui 10 dinheiros!')
n1 = int(input('Digite o primeiro número: '))
n2 = int(input('Digite o segundo número: '))
if s<n1:
print('Soma menor')
elif s>n2:
print('Soma maior')
else:
print('Soma no meio')
#Fase de chutes
di = 10
qc = int(input('Quantos chutes você gostaria de comprar?'))
chute = int(input('Chuve um valor para a soma: '))
while chute!=s:
chute = int(input('Chuve um valor para a soma: ')) |
d9bc3016a040ecb9b68e404cf4a9244ed6ee81a6 | spettigrew/cs2-codesignal-practice-tests | /anagrams.py | 2,712 | 4.46875 | 4 | """
A student is taking a cryptography class and has found anagrams to be very useful. Two strings are anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency. For example, bacdc and dcbac are anagrams, but bacdc and dcbad are not.
The student decides on an encryption scheme that involves two large strings. The encryption is dependent on the minimum number of character deletions required to make the two strings anagrams. Determine this number.
Given two strings, a and b, that may or may not be of the same length, determine the minimum number of character deletions required to make a and a anagrams. Any characters can be deleted from either of the strings.
Example
a = 'cde'
b = 'dcf'
Delete e from a and f from b so that the remaining strings are cd and dc which are anagrams. This takes 2 character deletions.
Function Description
Complete the makeAnagram function in the editor below.
makeAnagram has the following parameter(s):
string a: a string
string b: another string
Returns
int: the minimum total characters that must be deleted
Input Format
The first line contains a single string, a.
The second line contains a single string, b.
Constraints
1 <= |a|, |b| < = 10^4
The strings a and b consist of lowercase English alphabetic letters, ascii[a-z].
Sample Input
cde
abc
Sample Output
4
Explanation
Delete the following characters from the strings make them anagrams:
Remove d and e from cde to get c.
Remove a and b from abc to get c.
It takes 4 deletions to make both strings anagrams.
"""
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the makeAnagram function below.
def makeAnagram(a, b):
letters = {}
for letter in letters(a):
if letter not in letter:
createLetter()
incrementLetter()
for letter in letters(b):
if letter in letters:
if letter > 0:
matchLetter()
else:
incrementLetter()
else:
createLetter()
incrementLetter()
result = 0
for letter in letter:
result += letters[letter]
def createLetter():
letters: {
letter: 0
}
def incrementLetter():
letters: {
letter: + 1
}
def matchLetter():
letters: {
letter: - 1
}
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
a = input()
b = input()
res = makeAnagram(a, b)
fptr.write(str(res) + '\n')
fptr.close()
|
3aeb54c85b8848f39186ae55a552cbd287a563a6 | yangzongwu/leetcode | /20200215Python-China/0830. Positions of Large Groups.py | 1,029 | 4.125 | 4 | '''
In a string S of lowercase letters, these letters form consecutive groups of the same character.
For example, a string like S = "abbxxxxzyy" has the groups "a", "bb", "xxxx", "z" and "yy".
Call a group large if it has 3 or more characters. We would like the starting and ending positions of every large group.
The final answer should be in lexicographic order.
Example 1:
Input: "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is the single large group with starting 3 and ending positions 6.
Example 2:
Input: "abc"
Output: []
Explanation: We have "a","b" and "c" but no large group.
Example 3:
Input: "abcdddeeeeaabbbcd"
Output: [[3,5],[6,9],[12,14]]
Note: 1 <= S.length <= 1000
'''
class Solution:
def largeGroupPositions(self, S: str) -> List[List[int]]:
rep=[]
k=0
while k<len(S):
i=1
while k+i<len(S) and S[k+i]==S[k]:
i+=1
if i-1>=2:
rep.append([k,k+i-1])
k=k+i
return rep
|
4e57507ccee7127f5dcc50efaf68d82461836b92 | diogomattos/python.classes | /extras/btc_read.py | 631 | 3.5 | 4 | import urllib.request
import json
with urllib.request.urlopen("https://www.mercadobitcoin.net/api/BTC/ticker/") as url:
data = json.loads(url.read())
tb = dict(data['ticker'])
sell = (float(tb['sell']))
valorCompra = float(input("Digite o valor de Compra: "))
qtdBTC = float(input("Digite o Quantidade de Bitcoin: "))
investimento = valorCompra * qtdBTC / 1
valorAtual = sell * qtdBTC / 1
lucroEstimado = valorAtual / investimento - 1
print ("Você investiu R$",round(investimento,2),"e o seu valor bruto atual está em R$",round(valorAtual,2),", o seu lucro estimado é",'{:.1%}'.format(lucroEstimado))
|
49126c3b9a5b22cba3d355174fac761aa7bc0610 | livz/project-euler-pb | /p51.py | 1,145 | 3.65625 | 4 | # Project Euler problem 51
# Find the smallest prime which, by replacing part of the number (not necessarily
# adjacent digits) with the same digit, is part of an eight prime value family.
import math
import time
primes = {}
def is_prime(n):
for i in range(2, int(math.sqrt(n))+1):
if n%i == 0 :
return 0
return 1
def build():
for i in range(2, 1000000):
primes[i] = is_prime(i)
def test_nr(n):
# how many primes can be obtained by replacing all 0's, all 1's and all 2's
if primes[n] == 0 :
return 0
list_d = []
while n>0:
list_d.append(n%10)
n /= 10
list_d.reverse()
f_sum = lambda x,y: x*10+y
max_cnt = 1
for i in range(0,3):
cnt_primes = 1
for j in range(i+1, 10):
# replace all 'i' with 'j'
n_j=map(lambda x:x if x!=i else j, list_d)
if n_j == list_d:
break
nj = reduce(f_sum, n_j)
if primes[nj] == 1:
cnt_primes += 1
if cnt_primes>max_cnt:
max_cnt = cnt_primes
return max_cnt
def solve():
build()
nbr = 2
while test_nr(nbr) < 8 :
nbr += 1
print nbr
if __name__=="__main__":
start = time.time()
solve()
print "Elapsed Time:", (time.time() - start), "sec"
|
654a2fb997ec66e2992363eee33d119c32288d1b | Lisa-Hsu/Python_Practice | /clock.py | 902 | 3.953125 | 4 | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
Dictionary - key: value
d = {key1 : value1, key2 : value2 }
"""
import time
import os
class Clock(object):
def __init__(self, hour=0 , minute=0 , second=0 ):
self._hour = hour
self._minute = minute
self._second = second
def show(self):
return '%02d:%02d:%02d' % (self._hour,self._minute,self._second)
def run(self):
self._second += 1
if self._second == 60:
self._second = 0
self._minute += 1
if self._minute == 60:
self._minute = 0
self._hour += 1
if self._hour == 24:
self._hour = 0
def main():
clock = Clock(22,5,30)
while True:
os.system('clear')
print(clock.show())
time.sleep (1)
clock.run()
if __name__ == "__main__":
main() |
15524fa59b224a7145a70658b110ec6c2539592f | Ron-Chang/MyNotebook | /Coding/Python/Morvan/tkinter/tkinter_6_scale.py | 722 | 3.65625 | 4 | import tkinter as tk
window = tk.Tk()
window.title('Radio BTN by Ron')
window.geometry('300x200')
l = tk.Label(window, bg='yellow', text='What would you like for dinner?')
l.pack()
def print_selection(v):
l.config(text='吃 (Have)' + v)
s = tk.Scale(window,
label='Height',
from_=200, to=140,
orient=tk.VERTICAL,
length=360, resolution=1,
tickinterval=3,
showvalue=0,
command=print_selection)
'''
數值(注意底線)
從from_
到to
-orient(方向)
垂直VERTICAL
水平HORIZONTAL
-length(長度單位為 pixel)
-showvalue(拖動時是否顯示數值 布林表示 [1,0])
-tickinterval(尺標單位),
-resolution(1為整數, 0.1保留小數下一位)
'''
s.pack()
window.mainloop()
|
963567032c2016d1ec855d1fc9f0eeeffcc068f1 | arguiot/Project-Euler | /src/py/euler19.py | 386 | 3.71875 | 4 | from datetime import date
import time
sundays = 0
for year in range(1901, 2001):
for month in range(1, 13):
if date(year, month, 1).weekday() == 6:
sundays += 1
start = time.time()
answer = sundays
end = time.time()
total = end - start
print('Problem 19: ' + str(answer) + '\nDone in ' + str(total) + ' seconds.')
# Problem 19: 171
# Done in 7.152557373046875e-07 seconds.
|
f4bbd480012d25553ef960855958e85bb0b895fa | fabriciohenning/aula-pec-2020 | /06-1_ex05.py | 416 | 3.828125 | 4 | salario = float(input('Salário inicial: '))
divida = float(input('Forneça o valor da dívida: '))
mes = 10
ano = 2016
while True:
mes += 1
divida = divida + 0.15 * divida
if mes == 3:
salario = salario + 0.05 * salario
if mes > 12:
mes = 1
ano += 1
if divida > salario:
break
print(f'O valor da dívida irá superar o salário em {mes}/{ano}.')
|
95160956b8a562ec249924e5bf0c90ff3430e3f8 | medamer/cs-module-project-recursive-sorting | /iterative_sorting.py | 2,908 | 4.40625 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort(arr):
# loop through n-1 elements
for i in range(0, len(arr) - 1):
smallest_index = i
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
# Your code here
# loop through every elem to the right of the
# boundary, and keep track of the smallest
# elem we've seen so far until we get to the end
for j in range(i+1, len(arr)):
if arr[j] < arr[smallest_index]:
smallest_index = j
# TO-DO: swap
# Your code here
arr[smallest_index], arr[i] = arr[i], arr[smallest_index]
return arr
# TO-DO: implement the Bubble Sort function below
def bubble_sort(arr):
# Your code here
# keep a flag that tracks whether any swaps occurred
swaps_occurred = True
while swaps_occurred:
swaps_occurred = False
for i in range(len(arr)-1):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
swaps_occurred = True
return arr
'''
STRETCH: implement the Counting Sort function below
Counting sort is a sorting algorithm that works on a set of data where
we specifically know the maximum value that can exist in that set of
data. The idea behind this algorithm then is that we can create "buckets"
from 0 up to the max value. This is most easily done by initializing an
array of 0s whose length is the max value + 1 (why do we need this "+ 1"?).
Each buckets[i] then is responsible for keeping track of how many times
we've seen `i` in the input set of data as we iterate through it.
Once we know exactly how many times each piece of data in the input set
showed up, we can construct a sorted set of the input data from the
buckets.
What is the time and space complexity of the counting sort algorithm?
'''
# overall runtime: O(n + m)
# space complexity: O(n + m)
def counting_sort(arr, maximum=None):
# Your code here
if len(arr) == 0:
return arr
if maximum is None:
maximum = max(arr)
buckets = [0 for i in range(maximum+1)]
# loop through our arr
# O(n) since we're running through every element in the input array
for value in arr:
if value < 0:
return "Error, negative numbers not allowed in Count Sort"
# for each distinct arr value, increment arr[value] by 1
buckets[value] += 1
# at this point, our buckets array has all of the counts of
# every distinct value in our input array
output = []
# loop through our buckets array
# length of buckets can be at most 0..m where m is our m possible value
for index, count in enumerate(buckets):
# for the current count
output.extend([index for i in range(count)])
# add that many values to an output array
return output
|
ea886243e382202f13784926b58275b01bd6ae1f | AaronNolan/College-Lab-Sheets | /sum-numbers.py | 96 | 3.625 | 4 | #!/usr/bin/env python
n = input()
x = 0
while n != 0:
x = x + n
n = input()
print(x)
|
7c7450d1f04a085f56b3c5b0eaa2af4103e85dac | zakidane/Simple-Python-Games | /tictactoe.py | 3,864 | 3.828125 | 4 | import random
def printBoard(board):
print(board[6]+' | '+board[7]+' | '+board[8])
print('---------------')
print(board[3]+' | '+board[4]+' | '+board[5])
print('---------------')
print(board[0]+' | '+board[1]+' | '+board[2])
def checkifwon(board, choice):
if(
(board[0]==choice and board[1]==choice and board[2]==choice)or
(board[3]==choice and board[4]==choice and board[5]==choice)or
(board[6]==choice and board[7]==choice and board[8]==choice)or
(board[0]==choice and board[3]==choice and board[6]==choice)or
(board[1]==choice and board[4]==choice and board[7]==choice)or
(board[2]==choice and board[5]==choice and board[8]==choice)or
(board[2]==choice and board[4]==choice and board[6]==choice)or
(board[0]==choice and board[4]==choice and board[8]==choice)
):
return True
def checkiflost(board, choice):
if(
(board[0]==choice and board[1]==choice and board[2]==choice)or
(board[3]==choice and board[4]==choice and board[5]==choice)or
(board[6]==choice and board[7]==choice and board[8]==choice)or
(board[0]==choice and board[3]==choice and board[6]==choice)or
(board[1]==choice and board[4]==choice and board[7]==choice)or
(board[2]==choice and board[5]==choice and board[8]==choice)or
(board[2]==choice and board[4]==choice and board[6]==choice)or
(board[0]==choice and board[4]==choice and board[8]==choice)
):
return True
def checkIfTableFull(board):
for i in range(len(board)):
if(board[i] == ' '):
return False
else:
return True
num_list = '1 2 3 4 5 6 7 8 9'.split()
print('Welcome to Tic-Tac-Toe')
print('would you like to be X or O?')
choice = input()
while(choice != 'X' and choice != 'O'):
print('pick either "X" or "O"')
choice = input()
gamewon = False
gamelost = False
tablefull = False
gamechoice = ''
if(choice == 'X'):
gamechoice = 'O'
else:
gamechoice = 'X'
board = list(' '*9)
gameIsPlaying = True
print('The table looks as follows')
print('7 '+' | '+' 8 '+' | '+' 9')
print('---------------')
print('4 '+' | '+' 5 '+' | '+' 6')
print('---------------')
print('1 '+' | '+' 2 '+' | '+' 3')
print('')
print('You can pick a number to fill in the corresponding block.')
print('////////////////////////////////////////////////////')
while gameIsPlaying:
print('Pick a number and enter here: ',end=' ')
num = input()
while(num not in num_list):
print('Pick a valid number.')
for i in range(len(num_list)):
print(num_list[i],end=' ')
num = input()
num_list.remove(num)
board[int(num)-1] = choice
printBoard(board)
gamewon = checkifwon(board, choice)
gamelost = checkiflost(board, gamechoice)
if gamewon == False and gamelost == False:
tablefull = checkIfTableFull(board)
if gamewon or gamelost or tablefull:
gameIsPlaying = False
if gamewon == True:
print('You won.')
elif gamelost == True:
print('Suck on that. I won.')
elif tablefull == True:
print('We tied.')
if gameIsPlaying == False:
break
randomNumber = num_list[random.randint(0, len(num_list)-1)]
num_list.remove(randomNumber)
board[int(randomNumber)-1] = gamechoice
print('My turn:')
printBoard(board)
gamewon = checkifwon(board, choice)
gamelost = checkiflost(board, gamechoice)
if gamewon == False and gamelost == False:
tablefull = checkIfTableFull(board)
if gamewon == True:
print('You won.')
elif gamelost == True:
print('Suck on that. I won.')
elif tablefull == True:
print('We tied.')
if gamewon or gamelost or tablefull:
gameIsPlaying = False
if gameIsPlaying == False:
break
|
a076e70f32550451400a80e8bf7ac238c94bf3cc | KojiAomatsu/Project-Euler | /problem-006.py | 165 | 3.5 | 4 | def calc(n):
square = 0
the_sum = 0
for i in range(1, n+1):
square += i
the_sum += i**2
return square**2 - the_sum
print(calc(100))
|
f4566ab40b05a3f2ddb04a31d832eb0571e7890c | Rhomi/The-Complete-Python | /Books/Practice Python Online/Quiz 03 - List Less Than Ten.py | 349 | 4.125 | 4 | def main():
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
def list_less_than_num(list, num):
print('The resulting list is {}'.format([item for item in a if item<num]))
num = int(input('Enter an arbitrary number : '))
if num != None:
list_less_than_num(a, num)
if __name__ == "__main__":
main() |
a2c512ed9e8df09d61353fe6b035aa7cecf799ec | ootz0rz/tinkering-and-hacking | /2022/LeetCode/Two Pointers/986 - Interval List Intersections.py | 1,150 | 3.65625 | 4 | # https://leetcode.com/problems/interval-list-intersections/
from typing import List
class Solution:
def intervalIntersection(
self, firstList: List[List[int]], secondList: List[List[int]]
) -> List[List[int]]:
res = []
i = 0
j = 0
while i < len(firstList) and j < len(secondList):
left = max(firstList[i][0], secondList[j][0])
right = min(firstList[i][1], secondList[j][1])
if left <= right:
res.append([left, right])
if firstList[i][1] < secondList[j][1]:
i = i + 1
else:
j = j + 1
return res
if __name__ == "__main__":
s = Solution()
def checkSolution(
firstList, secondList, expected, msg="Expected `{0}` but got `{1}`"
):
r = s.intervalIntersection(firstList, secondList)
assert r == expected, msg.format(expected, r)
checkSolution(
firstList=[[0, 2], [5, 10], [13, 23], [24, 25]],
secondList=[[1, 5], [8, 12], [15, 24], [25, 26]],
expected=[[1, 2], [5, 5], [8, 10], [15, 23], [24, 24], [25, 25]],
)
|
5155f55bd748c285a603d51644ee4f4e775e8670 | piyush09/LeetCode | /Pow (x,n).py | 729 | 3.9375 | 4 | """
Algo: Recursive Solution
If power(n) becomes 0, then return 1 in the recursion.
If power(n) is not divisible by 2, then multiply with x and do recursive call for power as (n-1).
If power(n) is divisible by 2, then do recursive call for power as (n/2).
"""
def myPow(x, n):
if not n: # If n. is equal to 0, return 1
return 1
if n < 0: # If n is negative, then return Pow() for negative of input 'n' value.
return 1 / myPow(x, -n)
if n % 2: # If n is not divisible by 2, then recursively call with (n-1) as power.
return x * myPow(x, n - 1)
return myPow(x * x, n / 2) # Otherwise recursively call with (n/2) as power.
x = 2.0
n = -2
print (myPow(x,n))
|
479e73bb98edb81f632f1c52ee33de88261ca496 | GuHuY/R_peak_from_ECG | /R_detection.py | 5,449 | 3.609375 | 4 | # ECG的R波检测
# 仅需调用select_R方法
from scipy.signal import find_peaks
import numpy as np
# import matplotlib.pyplot as plt
R_N = 9 # Size of R_Peak_Value_List
R_Peak_Value_List = [0] * R_N
R_Moment_List = [0]
R_Interval_List = [0]
middel_peak = 0
middel_interval = 0
samp_freq = 0
raw_data = []
def select_R(ecg, sampling_frequency, plot=False):
"""
Call this function to utilize all functions in this file.
Parameters:
raw_data(np.array): ECG data.
samp_freq(int): Sampling frequency.
plot_result(bool): Whether draw the plot of the result
Returns:
R_Moment_List(np.array): An arrary that contain all moments of R
R_Interval_List(np.array): An array that contain all intervals of R
"""
global samp_freq, R_Moment_List, raw_data
samp_freq = sampling_frequency
raw_data = ecg
(filter1, filter_result) = filtrate_raw_ECG()
RPS_1 = R_Primary_Selection(filter_result, 10)
RPS_2 = R_Primary_Selection(filter_result, 15)
RSS_1 = R_Senior_Selection(RPS_1, 0.1)
RSS_2 = R_Senior_Selection(RPS_2, 0.1)
R_Moment_List = sorted(set(RSS_1).union(RSS_2))
R_Interval_List = generate_interval_list(R_Moment_List)
return np.array(R_Moment_List), np.array(R_Interval_List)
def R_Senior_Selection(RSS_in, period):
"""
There will be a slightly error in R moment due to mean filter.
Adjusting R_Moment_List by finding local maximum in a samll range
to eliminate this error.
Parameters:
raw_data(np.array): ECG data.
"""
inspection_range = int(period*samp_freq)
for index_RML in range(1, len(RSS_in)):
temp = RSS_in[index_RML]
max_index = np.argmax(np.array([raw_data[x] for x in
range(temp-inspection_range,
temp+inspection_range)]))
RSS_in[index_RML] = temp-inspection_range+max_index
return RSS_in
# def Union(l1, l2):
# i = 0
# j = 0
# l_out = [0]
# len1 = len(l1)
# len2 = len(l2)
# while True:
# cur_out = l_out[-1]
# if i
# while (i < len1-1) and (l1[i] <= cur_out):
# i = i + 1
# while (j < len2-1) and (l2[j] <= cur_out):
# j = j + 1
# l_out.append(min(l1[i], l2[j]))
# return l_out
def R_Primary_Selection(filter_result, start_point):
"""
R波初选,每十秒做一次筛选
parameters:
raw_data(np.array): ECG data.
filter_result(list): The result of filtrate_raw_ECG()
"""
global R_Peak_Value_List, R_Interval_List
R_Interval_List = [0]
RPS_out = [0]
delay = -1 # Filters delay compensation
# If the last section of data less than 10 seconds, discard it
for index in range(start_point*samp_freq, len(raw_data), 10*samp_freq):
start = index - 10 * samp_freq
update_middel_peak_and_interval() # Update threshold
local_maxima_position, _ = find_peaks(filter_result[start:index],
distance=max(middel_interval*0.8,
samp_freq/3),
height=middel_peak*0.2)
R_num = len(local_maxima_position)
# Make local_maxima_position in line with R_Moment_List in time
local_maxima_position = (np.array([start]*R_num)+local_maxima_position)
# Add local_maxima_position to R_Moment_Lis
RPS_out = (RPS_out +
list(local_maxima_position-np.array([delay]*R_num)))
# Updarte R_Peak_Value_List
R_Peak_Value_List = [filter_result[x] for x in local_maxima_position]
R_Interval_List = (np.array(RPS_out[1:]) -
np.array(RPS_out[:-1]))
return RPS_out
def generate_interval_list(gil_in):
return list(np.append(np.array(gil_in[1:]), [0]) - np.array(gil_in))
def update_middel_peak_and_interval():
"""
Calculate middel value of past nine R peak value and R interval.
"""
global middel_peak, middel_interval
middel_peak = np.median(R_Peak_Value_List)
middel_interval = np.median(R_Interval_List)
def filtrate_raw_ECG():
"""
Go through all filters.
Return:
(list): A list that contain filtered data
"""
filter1 = Moving_Mean_Filter(raw_data)
filter2 = Derivative_Filter_and_Square(filter1)
filter3 = Moving_Mean_Filter(filter2)
return filter2, filter3
def Derivative_Filter_and_Square(Der_in):
"""
A optimized derivative filter.
Parameter:
Der_in(float): Input data.
Return:
(float): Filter output.
"""
Der_out = []
last_item = Der_in[0]
for item in Der_in:
temp = item - last_item
if temp > 0:
Der_out.append(np.square(temp))
else:
Der_out.append(0)
last_item = item
return Der_out
def Moving_Mean_Filter(Mov_in, n=3):
"""
A moving mean filter.
Parameter:
Mov_in(float): Input data.
Return:
(float): Filter output.
"""
Mov_in = list(Mov_in)
# 边缘填充
filling = [Mov_in[0]]*int(1+(n-1)/2) + Mov_in + [Mov_in[-1]]*int((n-1)/2)
Mean_Value_Buff = filling[:n]
Mov_Out = []
for item in filling[n:]:
Mean_Value_Buff = Mean_Value_Buff[1:]+[item]
Mov_Out.append(sum(Mean_Value_Buff)/n)
return Mov_Out
|
52554aaa3bf88d3eda5c3c76a72867427f7e2de4 | dampython/PythonGit | /clases5.py | 684 | 3.625 | 4 | class Usuario:
#__init__ :python maneja internamente este metodo init,mediante este metodo se podra
#inicializar objetos.Dice que no hace falta hacer la funcion inicializar, es repetitivo
#pero es buen ejemplo.
def inicializar(self,username,password):#mediante este metodo seremos capaces de inicializar los attr de nuestros objetos
#por convencion el parametro se llamara self.
self.username = username
self.password = password
#estos attr se añaden a los objetos
user1 = Usuario()
user2 = Usuario()
user1.inicializar('User1','pass1')
user2.inicializar('user2','pass2')
print(user1.__dict__)
print(user2.__dict__)
|
f77ef4e8ad52ef5f365f935044b291e53727eba0 | onestarshang/leetcode | /spiral-matrix.py | 1,214 | 4.21875 | 4 | #coding: utf-8
'''
http://oj.leetcode.com/problems/spiral-matrix/
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
'''
class Solution:
# @param matrix, a list of lists of integers
# @return a list of integers
def spiralOrder(self, matrix):
m = len(matrix)
if m == 0:
return []
n = len(matrix[0])
result = []
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
b = [[False for j in range(n)] for i in range(m)]
x = y = d = 0
for i in range(n * m):
result.append(matrix[x][y])
b[x][y] = True
tx = x + directions[d][0]
ty = y + directions[d][1]
if tx < 0 or ty < 0 or tx >= m or ty >= n or b[tx][ty]:
d = (d + 1) % 4
x += directions[d][0]
y += directions[d][1]
return result
if __name__ == "__main__":
print Solution().spiralOrder([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
|
543bcc7081a73d76aa4a3acbf1fe24bdc93a6a65 | btroisi/PythonProjects | /Project8/turtle_interpreter.py | 3,847 | 3.953125 | 4 | #Brandon Troisi
#4/6/16
#turtle_interpreter.py
#version 2
import turtle
import random
import sys
class TurtleInterpreter:
def __init__(self, dx=800, dy=800 ):
turtle.setup()
turtle.tracer(False)
def drawString(self, dstring, distance, angle ):
"""
Interpret the characters in string dstring as a series
of turtle commands. Distance specifies the distance
to travel for each forward command. Angle specifies the
angle (in degrees) for each right or left command. The list of
turtle supported turtle commands is:
F : forward
- : turn right
+ : turn left
[ : save position, heading
] : restore position, heading
< : saves color
> : restore color
g : set color to green
y : set color to light yellow
r : set color to light red
B : set color to brown
L : draws a filled in semicircular leaf
f : fills in shape
n : ends filling in shape
R : set color to brightest red possible
b : set color to black
s : set color to light blue
"""
stack=[]
colorstack=[]
for c in dstring:
turtle.tracer(False)
if c=='F':
turtle.forward(distance)
elif c =='+':
turtle.left(angle)
elif c=='-':
turtle.right(angle)
elif c =='[':
stack.append(turtle.position())
stack.append(turtle.heading())
elif c == ']':
turtle.up()
turtle.setheading(stack.pop())
turtle.goto(stack.pop())
turtle.down()
elif c == 'B':
turtle.color('brown')
elif c == '<':
colorstack.append(turtle.color()[0])
elif c == '>':
turtle.color(colorstack.pop())
elif c == 'g':
turtle.color((0.15,0.5,0.2))
elif c == 'y':
turtle.color((0.8,0.8,0.3))
elif c == 'r':
turtle.color((0.7,0.2,0.3))
elif c == 'L':
turtle.fill(True)
turtle.circle(distance,180)
turtle.fill(False)
elif c == 'f':
turtle.fill(True)
elif c == 'n':
turtle.fill(False)
elif c == 'R':
turtle.color('red')
elif c == 'b':
turtle.color('black')
elif c == 's':
turtle.color('lightblue')
def hold(self):
""" holds the screen open until the user clicks or types 'q' """
# have the turtle listen for events
turtle.listen()
# hide the turtle and update the screen
turtle.ht()
turtle.update()
# have the turtle listen for 'q'
turtle.onkey( turtle.bye, 'q' )
# have the turtle listen for a click
turtle.onscreenclick( lambda x,y: turtle.bye() )
# start the main loop until an event happens, then exit
turtle.mainloop()
exit()
def place(self, xpos, ypos, angle=None):
'''
This places the turtle at a certain position (xpos,ypos) and if the value of
angle is not equal to none, the turtle is oriented that angle.
'''
turtle.up()
turtle.goto(xpos,ypos)
if angle!=None:
turtle.setheading(angle)
turtle.down()
def orient(self, angle):
'''
Orients turtle in a certain direction
'''
turtle.setheading(angle)
def goto(self, xpos,ypos):
'''
This moves the turtle to position (xpos,ypos) without drawing anything
'''
turtle.up()
turtle.goto(xpos,ypos)
turtle.down()
def color(self, color):
'''
Sets the color for which the turtle to draw
'''
turtle.color(color)
def width(self, w):
'''
Sets the width of the line turtle draws to w
'''
turtle.width(w)
def sun(self, x, y, r):
'''
Creates a yellow circular sun at position (x,y) with radius r
'''
turtle.fill(True)
self.color('yellow')
self.place(x,y,0)
turtle.circle(r)
turtle.fill(False)
|
4ffb814e30b81b1d18889c2c57a8ec276b4b0d0c | junjongwook/programmers | /Skill Check/Level3/s12978.py | 1,343 | 3.828125 | 4 | # -*- coding: utf-8 -*-
"""
배달 : https://programmers.co.kr/learn/courses/30/lessons/12978?language=python3
"""
def solution(N, road, K):
answer = 0
result = set()
graph = dict()
for v1, v2, d in road:
graph.setdefault(v1, dict())
graph.setdefault(v2, dict())
if v1 in graph and v2 in graph[v1]:
graph[v1][v2] = min(graph[v1][v2], d)
graph[v2][v1] = min(graph[v2][v1], d)
else:
graph[v1][v2] = d
graph[v2][v1] = d
distances = [float('inf')] * (N + 1)
distances[1] = 0
result.add(1)
import heapq
queue = []
heapq.heappush(queue, (distances[1], 1))
while queue:
_distance, _node = heapq.heappop(queue)
if distances[_node] < _distance:
continue
for adjacent, weight in graph[_node].items():
distance = distances[_node] + weight
if distance < distances[adjacent]:
distances[adjacent] = distance
if distance <= K:
result.add(adjacent)
heapq.heappush(queue, (distance, adjacent))
answer = len(result)
return answer
if __name__ == '__main__':
result = solution(5, [[1,2,1],[2,3,3],[5,2,2],[1,4,2],[5,3,1],[5,4,2]], 3)
print(f'result = {result}')
assert result == 4
|
5f203c82f013fe5b44ff0578e5fb411a1bad4976 | jeremykid/FunAlgorithm | /python_practice/graph/Graph/undirectedGraphTest.py | 1,863 | 3.984375 | 4 | from undirectedGraph import undirectedGraph
def main():
test1 = undirectedGraph(6)
print "==== Empyh Graph ===="
print test1
test1.addEdge(1,2)
print "Add edge 1-2"
print "==== Graph with 1 edge ===="
print test1
test1.addEdge(1,3)
test1.addEdge(3,4)
test1.addEdge(2,5)
print "==== Graph with 4 edge ===="
print test1
#todo test depthFirstSearch
# 1->2
# 2->5
# 1->3
# 3->4
result = test1.depthFirstSearch(1,[])
print "=== Depth First Search ==="
print result
#todo test breathFirstSearch
# 1->2
# 1->3
# 2->5
# 3->4
result = test1.breathFirstSearch(1,[])
print "=== Breath First Search ==="
print result
#todo test get all edges
result = test1.getAllEdges()
print "=== Get All Edges ==="
print result
result = test1.Dijkstra(1)
print "=== Dijkstra ==="
print result
#todo test is tree (is it a cycle)
test2 = undirectedGraph(6)
#0->1
#0->4
#1->2
#1->3
#3->5
#2->5
#4->5
test2.addEdge(0,1)
test2.addEdge(0,4)
test2.addEdge(1,2)
test2.addEdge(1,3)
test2.addEdge(3,5)
test2.addEdge(2,5)
test2.addEdge(4,5)
print "==== 2nd Graph with 7 edges ===="
print test2
test3 = undirectedGraph(6)
#0->1 2
#0->4 4
#1->2 5
#1->3 6
#3->5 2
#2->5 1
#4->5 7
test3.addEdge(0,1,2)
test3.addEdge(0,4,4)
test3.addEdge(1,2,5)
test3.addEdge(1,3,6)
test3.addEdge(3,5,2)
test3.addEdge(2,5,1)
test3.addEdge(4,5,7)
print "==== 3rd weight Graph with 7 edges ===="
print test3
print "==== 3rd weight Graph with get min Weight() ===="
result = test3.getOneMiniWeight()
print result
result_adjacent_matrix = []
for i in range(self.degrees):
result_adjacent_matrix.append([0]*6)
result = test3.minimum_spanning_tree(result_adjacent_matrix, linked_vertexs = [0]*self.degrees, test3.adjacent_matrix)
print result
result = test3.minimum_spanning_tree_recursion()
print result
main()
|
96b79803dd5eae8537b13e8a2ce43a896fc0e226 | conapps/Devops-101 | /Devnet Express/devnet/code/soluciones/03-tercer-script.py | 189 | 3.796875 | 4 | """
Script #3
"""
import sys
NUM = int(sys.argv[1])
if NUM < 1:
print("I'm less than 1!")
elif NUM > 1:
print("I'm bigger than 1!")
else:
print("I'm the default statement!")
|
a771aaf4a3ced86d69340d98fce1bf72e6481c77 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/leap/2f0754d8ce9a46a6965572ee6443dc3a.py | 446 | 4.1875 | 4 | def is_leap_year(yr):
'''
Accepts a year as input and returns True or False if it is or is not a leap year.
'''
# only evaluate valid input
try:
yr = int(yr)
except ValueError:
return False
if yr % 4 != 0:
return False
elif yr % 400 == 0:
return True
elif yr % 100 == 0:
return False
# must be divisible by just 4
else:
return True
|
fc6e1361561a4fff7107e208bbfc650d631aebb8 | nabilarbouz/DataStructuresAndAlgorithms | /max_convex_points.py | 1,623 | 3.71875 | 4 | #This algorithm will find the maximum x-coordinate and y-coordinate in a convex polygon
def max_x(x_list, low, high):
n_value = len(x_list)
while low <= high:
mid = low + (high - low) // 2
if x_list[low] > x_list[(low + 1) % n_value] and \
x_list[low] > x_list[(low - 1) % n_value]:
return x_list[low]
else:
if x_list[mid] > x_list[mid + 1] and \
x_list[mid] > x_list[mid - 1]:
return x_list[mid]
elif x_list[mid + 1] < x_list[mid] < x_list[mid - 1]:
high = mid - 1
low = low + 1
else:
low = mid + 1
def max_y(y_list, low, high):
n_value = len(y_list)
while low <= high:
mid = low + (high - low) // 2
if y_list[low] > y_list[(low + 1) % n_value] \
and y_list[low] > y_list[(low - 1) % n_value]:
return y_list[low]
else:
if y_list[mid] > y_list[mid + 1] and \
y_list[mid] > y_list[mid - 1]:
return y_list[mid]
elif y_list[mid + 1] < y_list[mid] < y_list[mid - 1]:
high = mid - 1
low = low + 1
else:
low = mid + 1
def main():
input_x_list = [0.9, 1.9, 4.2, 5.71, 4.62, 2.43]
input_y_list = [3.4, 1.83, 1.4, 2.65, 4.18, 4.54]
print("largest x value: " + str(max_x(input_x_list, 0, len(input_x_list) - 1)))
print("largest y value: " + str(max_y(input_y_list, 0, len(input_y_list) - 1)))
main()
|
3dba3f96cda2b18fb32471f908e8cdaa0be70dca | Acheros/Dotfiles | /practice/practice27.py | 291 | 3.890625 | 4 | #!/usr/bin/python3
r_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])
def make_more_word():
new_list=[]
for i in r_list_1:
if any(i in word for word in color_list_2):
new_list.append(i)
return new_list
print(make_more_word())
|
02634ac8bdf8101352337a9e82ccf97b62af6cf0 | asadugalib/URI-Solution | /Python3/uri 1151 Easy Fibonacci.py | 220 | 3.890625 | 4 | #1151 Easy Fibonacci
number = int(input())
term1 = 0
term2 = 1
line = ""
for i in range(number):
line += str(term1)+" "
next_term = term1 + term2
term1 = term2
term2 = next_term
print(line[:-1])
|
938304e7a5cf061ebf5e515d439e227e5d0b02fd | wmwassmann/pythonWorkshop | /pythonwork.py | 1,776 | 4.03125 | 4 | # print('hello world')
# Booleans, Numbers, Int, Strings, Tuples, Lists (Array), Dictionary (Object),
# {} Bye {} No {brackets}
# if 1==1:
# print('hi')
# lead = 'My name is '
# name = 'Bob'
# combined = lead + name
# print(combined)
# print(colors)
# numberOne = 11
# numberTwo = 2
# if numberOne==numberOne:
# print('wtf no they aren\'t')
# elif numberOne==numberTwo:
# print('Goooooood')
# if numberOne < numberTwo:
# print('numberOne is lesser')
# else:
# print('numberOne is greater')
# if numberOne > numberTwo and numberOne < 25:
# print('correct!')
# else:
# print('Incorrect')
# # for color in colors:
# # print(color)
# for number in range(1, 6):
# print(number)
# colors = ['red', 'blue', 'green', 'purple?', 'yellow', 'orange', 'pink!', 'black', 'other blue', 'sad blue']
# i=0
# while colors[i] !='black':
# print(colors[i])
# i+=1
word = 'buffalo'
# for letter in word:
# print(letter)
# if letter=='f':
# pass
def addFunction(numOne, numTwo):
sum = numOne + numTwo
return sum
add = addFunction(10, 191)
# print(add)
# ALGO ONE print 1-255
# for number in range(1, 256):
# print(number)
# ALGO TWO print every other number from 1-255
# for number in range(1, 256):
# if number % 2!=0:
# print(number)
# This test is to see if I can make a function that counts
num = input('Enter a number: ')
direction = input('Count \'up\' or count \'down\': ')
def counter(direction, num):
if direction == 'up':
return int(num) + 1
else:
return int(num) - 1
print(counter(direction, num))
|
9ae6b678195ce2f326a1b9e87853a1887b24236b | jayeshvijayan/SuventureTask | /task_1_readcsv.py | 839 | 3.75 | 4 | ord_dct={}
def arrange_state(col_sep,lst_data):
"""
Output of this function will be country name and its population of
the year 2015. From highest to lowest of estimated population of 2015
"""
dct_state = {}
for lines in lst_data[1:len(lst_data)]:
lst_lines = lines.split(col_sep)
dct_state[lst_lines[4]] = lst_lines[12]
ord_dct = OrderedDict(sorted(dct_state.items(),key=lambda x: int(x[1]),reverse=True))
for key,value in ord_dct.items():
print(key+":"+value)
def readcsv(col_sep,file_full_path):
fp = open(file_full_path,"r")
lst_data = fp.readlines()
fp.close()
arrange_state(col_sep,lst_data)
pass
if __name__ == "__main__":
from collections import OrderedDict
file_full_path = "NST-EST2015-alldata.csv"
readcsv(",",file_full_path)
|
4e5fd2e2a4fc8fdaefa3f337ad70b5187ba81d52 | DenisPitsul/SoftServe_PythonCore | /video4/Ex1.py | 607 | 4.125 | 4 | import random
randomNumber = random.randint(1, 100)
attempt = 1
while attempt <= 10:
number = int(input("Guess the number from 1 to 100: "))
if 1 > number >= 100:
print("input number from 1 to 100")
elif number == randomNumber:
break
elif number > randomNumber:
print("less ")
elif number < randomNumber:
print("more ")
attempt += 1
if number == randomNumber:
print("You guessed the number from {} attempts! Right number: {}".format(attempt, randomNumber))
else:
print("You have not guessed the number! Right number: {}".format(randomNumber)) |
7e4fa35f90fece9ba19e5ffade0521eba5a1dd48 | bryan234-ca/trabajos-clase | /programacion deber.py | 409 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 20 22:58:53 2020
@author: Bryan Carpio
"""
lista = []
cantidad = int(input('cantidad'))
mayor = 0
menor = 0
i=1
while(cantidad > 0):
numero = float(input('numero #' + str(i) + ':'))
lista.append(numero)
i = i + 1
cantidad = cantidad - 1
mayor = max(lista)
menor = min(lista)
print('lista:',lista)
print('mayor:',mayor)
print('menor:',menor)
|
f775d82c62eff76455e2c05e8489975a9c7c8249 | TomHam2021/Python2a_week3 | /exercise3a.py | 1,540 | 4.25 | 4 | '''
Exercise 3a – A queue to the rescue
Background
Whenever there’s a “first in, first out” thing going on, queues tend to be useful as a data structure.
For example, a game may use a queue to process the players’ actions in order, a supercomputer may use
a queue to execute tasks in the order that they arrive, and a logging tool may use a queue to store
log messages for a while before writing them to a file.
Let’s demonstrate how a queue can help us. Here is a function fifo_list that creates a list and then
empties it by repeatedly removing its first element. We can measure the time it takes to execute:
'''
from timeit import timeit
from collections import deque
def measure(function):
time = timeit(function, number=TIMES)
time_str = f"Execution time: {time/TIMES:.7f} seconds"
settings = f"(SIZE: {SIZE}, TIMES: {TIMES}, {function.__name__})"
print(time_str, settings)
def fifo_list():
a_list = list(range(SIZE))
while a_list:
a_list.pop(0)
def deque_test():
# skapa en FIFO kö
a_queue = deque(range(SIZE))
while a_queue:
a_queue.popleft()
SIZE = 100000
TIMES = 10
print()
measure(fifo_list)
measure(deque_test)
print()
'''
Tasks
1. Define a function fifo_deque which creates a deque:
a_queue = deque(range(SIZE))
and empties it:
a_queue.popleft()
It should be similar to fifo_list above
2. Compare the execution times and try different sizes of the queue and list.
You will notice that one is significantly faster when SIZE is big. Why is this?
'''
|
453e6d34915afb7033e838e97b1a2be35504a1cd | t-dawei/Interview | /算法/自定义排序.py | 346 | 3.765625 | 4 | from functools import cmp_to_key
dic={'and': 2, 'are': 2, 'the':4, 'is':2, 'it':3, 'you':3, 'a':1}
def cmp(a,b):
if a[1] < b[1]:
return 1
elif a[1] > b[1]:
return -1
else:
if a[0] > b[0]:
return 1
else:
return -1
print(sorted(dic.items(), key=cmp_to_key(cmp), reverse=True))
|
7ba2365d24f43064d79d622f080e34229c30efc7 | epifanovmd/gos | /Материалы/Программирование/Алгоритмы/Invers/Kol_Invers.py | 1,480 | 3.640625 | 4 | from random import randint
from time import time
def rnd_mass(n):
return [randint(0,10) for i in range(0, n)]
def merge(a, lb, split, ub):
cur_jmp1 = 0
pos1 = lb
pos2 = split+1
pos3 = 0
temp = [i for i in range(0, ub-lb+1)]
while pos1 <= split and pos2 <= ub:
if a[pos1] < a[pos2]:
temp[pos3] = a[pos1]
pos1 += 1
pos3 += 1
else:
temp[pos3] = a[pos2]
pos2 += 1
pos3 += 1
cur_jmp1 += split - pos1 + 1
while pos2 <= ub:
temp[pos3] = a[pos2]
pos3 += 1
pos2 += 1
while pos1 <= split:
temp[pos3] = a[pos1]
pos3 += 1
pos1 += 1
a[lb:ub+1] = temp
del(temp)
return cur_jmp1
def mergeSort(a, lb, ub):
cur_jmp = 0
if lb == ub:
return cur_jmp
split = (lb + ub) >> 1
cur_jmp += mergeSort(a, lb, split)
cur_jmp += mergeSort(a, split+1, ub)
cur_jmp += merge(a, lb, split, ub)
print("Сортировка массива методом слияний")
n = int(input("Введите кол-во элементов: "))
A = rnd_mass(n)
B = [A[i] for i in range(0, n)]
a = time()
k = mergeSort(A, 0, n - 1)
print("Время алгоритма =", time() - a)
print("Исходный массив")
print(B)
print("Количество инверсий =", k)
|
c3b9921f107ec67a889ff3ffe7717aa42e21cfa5 | Darrenrodricks/EdabitPythonPractice | /EdabitPractice/factorial.py | 252 | 4.375 | 4 | # Create a function that takes an integer and returns the factorial of that integer.
# That is, the integer multiplied by all positive lower integers.
def factorial(x):
if x == 0:
return 1
return x * factorial(x-1)
print(factorial(5)) |
0dab7128d5a03cc7ea6f225c07cb1c3f725a952a | bam6076/PythonEdX | /quiz3_part7.py | 483 | 4.21875 | 4 | ## Write a function that accepts two positive integers as function parameters
## and returns their least common multiple (LCM). The LCM of two integers a
## and b is the smallest (non zero) positive integer that is divisible by
## both a and b. For example, the LCM of 4 and 6 is 12,
## the LCM of 10 and 5 is 10.
def _lcm(a, b):
for i in range (1, a*b+1):
if i%a == 0:
if i%b == 0:
break
return i
print (_lcm(1,1))
print (_lcm(4,6))
|
9d761f3454d5a3d7ea2a14b45f1c03458503ca02 | katharinameislitzer/smartninjacourse | /Class2_Python3/__secret number_try.py | 278 | 4.0625 | 4 | secret_number = 5
guess= None
while guess != secret_number:
guess = int(input("Please guess the secret number: "))
if guess == secret_number:
print("You have guessed the secret number")
else:
print("Sorry, the secret number is not " + str(guess)) |
f2bdeefee61a16f7eae3bfe2e58cc2bf37f017f8 | EduardoSantos7/Algorithms4fun | /Leetcode/551. Student Attendance Record I/solution.py | 484 | 3.515625 | 4 | class Solution:
def checkRecord(self, s: str) -> bool:
count_l = 0
count_a = 0
prev = ''
max_l = 0
for c in s:
if c == 'A':
count_a += 1
elif c == 'L' and prev == 'L':
count_l += 1
elif c == 'L':
count_l = 1
else:
count_l = 0
prev = c
max_l = max(max_l, count_l)
return count_a < 2 and max_l < 3
|
d0ccddead0aeb2bf40c69d3741f0979d002b1131 | DanielAndrews43/Scripts | /amazon_book_profit.py | 1,070 | 3.734375 | 4 | #all costs are in dollars, and all times are in decimal-minutes
shipping_cost = 2.68 #media mail 9" x 11"
container_cost = 0.40 #b-flute method
paid_shipping = 3.99
time_to_list_item = 2.00 #take book, make sure pic is good, put cost, put in stack
time_to_find_item = 0.50 #find item after it was sold
time_to_package_item = 3.00 #b-flute method (food wrap -> cardboard -> tape -> staple -> write address)
percent_books_sold = 0.5 #assume 50% of books wont be bought due to competition
average_book_price = 0.99 #hardcovers sell for quite a bit, while most paperbacks are cheap
minutes = 60.00
def profit_per_book():
return average_book_price + paid_shipping - shipping_cost - container_cost
def operations_per_hour():
return minutes / (time_to_list_item + time_to_ship_item())
def time_to_ship_item():
#You only need to package books that are sold
return percent_books_sold * (time_to_list_item + time_to_find_item)
def profit():
wage = operations_per_hour() * profit_per_book()
return "In {0} minutes you make {1}".format(minutes, wage)
print profit() |
03b8ea0552ab1ac6ed00603b475a82bdf31ab7b6 | nryoung/ctci | /1/1-2.py | 581 | 3.953125 | 4 | """
Q: Implement a function void reverse(char* str) in C or C++ which reverses a
null terminated string.
NOTE: While this question is specific to C/C++ it can be accomplished serveral
ways in Python.
"""
def reverse_list_slicing(s):
"""
Uses list slicing to reverse the string.
"""
return s[::-1]
def reverse_builtin(s):
"""
Uses the builtin `reversed` method to reverse s
"""
return ''.join(reversed(s))
if __name__ == '__main__':
s = 'The string that should be reversed'
print(reverse_list_slicing(s))
print(reverse_builtin(s))
|
81deaf5f7658f24bb076f6d4b661324e478c7511 | 2wiki/Python-programming | /5week/while()활용.py | 552 | 3.984375 | 4 |
#이르믕ㄹ 입력 받아서 성이 김 최 이 이면 통과
#아니면 다시 입력받음
#입력받는 횟수가 5회 이상이면
#더이상 입력받지않고 종료
firstname = int(input("성을 입력하세요"))
count=1
while firstname != 김 or 이 or 최 and count<=5:
firstname = int(input("성을 입력하시오:"))
count = count + 1
if count>5:
print("비밀번호 입력 오류가 3번 발생하여 처리할수 없습니다")
else:
print("비밀번호가 정확합니다!")
|
304136528a09d0a663093520804d773619e819a2 | fkokosinski/tomograph | /tomograph/transform.py | 1,035 | 3.5 | 4 | import numpy as np
def projective(coords):
""" Convert 2D cartesian coordinates to homogeneus/projective. """
num = np.shape(coords)[0]
w = np.array([[1], ]*num)
return np.append(coords, w, axis=1)
def cartesian(coords):
""" Convert 2D homogeneus/projective coordinates to cartesian. """
return coords[:, :2]
def translate(x, y):
""" Return translation matrix. """
return np.array([
[1, 0, x],
[0, 1, y],
[0, 0, 1],
])
def rotate(a):
""" Return rotation matrix. """
return np.array([
[np.cos(a), -np.sin(a), 0],
[np.sin(a), np.cos(a), 0],
[0, 0, 1]
])
def transform_list(coords, matrix):
""" Apply transformation to a list of coordinates. """
return matrix.dot(coords.T).T
def transform_apply(coords, transforms):
""" Apply list of transformations to a list of coordinates. """
out = projective(coords)
for transform in transforms:
out = transform_list(out, transform)
return cartesian(out)
|
98c26635774d2f68d3169cb1dc0da76d635105b0 | Aasthaengg/IBMdataset | /Python_codes/p03937/s870560236.py | 289 | 3.5 | 4 | h, w = map(int, input().split())
L = [input() for _ in range(h)]
r = 0
for i in range(h):
for j in range(w):
if L[i][j] == '#':
if j < r:
print('Impossible')
exit()
else:
r = j
else:
print('Possible')
|
e15613d217337815f8f52b3a123898b7bd25cb34 | arpitanand89/MyCode | /Coursera/test2.py | 142 | 3.703125 | 4 | k=None
v=0
dic = {'arpit':30, 'jas':29, 'ashok':60, 'anita':58}
for keys, value in dic.items():
if v<value:
v=value
k=keys
print(k,v)
|
a8846fa968a9771667b8e9439ae846c9b138f9cc | sametdlsk/python_Tutorial | /pythonHello.py | 1,974 | 3.875 | 4 | # The comment line starts with hashtag. This is a comment line examples
# yorum satırı hashtag ile başlar. Bu bir örnek yorumdur.
"""
We can show comments with three double quote if they have more than one line.
Birden fazla yorum satırı için üç adet çift tırnak işaretini kullanabilir
"""
print("Hello Python") # Bu Python'da yazdırma komutudur.
# This is the command to write the text on the screen.
print("Hello Python", "I am a", 1, "person")
"""
String expressions, that is, textual expressions, must be specified in double quotation marks.
But there is no need for this for numbers, because the numbers are defined by Python.
String ifadeler yani Metinsel ifadeler çift tırnak işareti içerisinde belirtilmelidir.
Ancak sayılar için buna gerek yoktur çünkü sayılar Python tarafından tanımlanmıştır.
"""
print("Samet\nDlsk") # Alt alta yazdırmak istediğimiz ifadeleri \n kullanarak yazdırırız.
print("1\n2") # Bu satırdaki de sayılar için bir örnektir. Alt alta yazırabiliriz.
"""
\n we put it next to the expressions we want to print on the bottom line. Such as the above example.
We must specify with double quotes the numbers that we have customized and that are not variable.
Alt alta yazdırmak istediğimiz ifadeleri \n kullanarak yazdırırız. Yukarıdaki örnekteki gibi alt alta yazırabiliriz.
Ancak spesifik ve değişken olarak tanımlamadığımız sayılarımızı print fonksiyonunda kullanırken çif tırnak ile
kullanmalıyız.
"""
print("01", "01", "2021")
print("01", "01", "2021", sep="/")
"""
We use the sep function to put a / between them dec. Such as the above example.
And we can also put any character instead of / (example: + - ? and more}.
Tarihleri yazdırmak için sep fonskiyonu ile aralarında / bırakabiliriz.
Yukardaki örneği bakınız sep ile + - ? gibi bir çok elemanı aralarda kullanabiliriz
""" |
e41f6075b19b1c4bcf1dabdbf16969ec66f1fa2c | linhto1211/Learning-Python | /substring.py | 412 | 4.15625 | 4 | # Define function here:
def substring_between_letters(word,start,end):
find_start=word.find(start)
find_end=word.find(end)
if (find_start == -1) or (find_end ==-1):
return word
else:
return word[find_start+1:find_end]
# Check if function work:
print(substring_between_letters("apple", "p", "e"))
# should print "pl"
print(substring_between_letters("apple", "p", "c"))
# should print "apple"
|
14670d9b6f3049d9780423cc8a39a1ea07c5d126 | GRV96/PythonLearning | /PythonTests.py | 1,855 | 3.6875 | 4 | # File: PythonTests.py
from os import system
import CustomFunctions
floatNbr = 3.999999999
print("{0} will be converted to a string.".format(floatNbr))
print("Precision -1: {0}".format(CustomFunctions.floatNumberToString(floatNbr, -1)))
print("Precision 0: {0}".format(CustomFunctions.floatNumberToString(floatNbr)))
print("Precision 1: {0}".format(CustomFunctions.floatNumberToString(floatNbr, 1)))
print("Precision 3: {0}".format(CustomFunctions.floatNumberToString(floatNbr, 3)))
print("Precision 5: {0}".format(CustomFunctions.floatNumberToString(floatNbr, 5)))
floatNbr = 11.0
print("\n{0} will be converted to a string.".format(floatNbr))
print("Precision 0: {0}".format(CustomFunctions.floatNumberToString(floatNbr)))
print("Precision 1: {0}".format(CustomFunctions.floatNumberToString(floatNbr, 1)))
print("Precision 2: {0}".format(CustomFunctions.floatNumberToString(floatNbr, 2)))
year = input("\nEnter a year: ")
year = int(year)
try:
if CustomFunctions.isLeapYear(year):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
except ValueError as ve:
print(ve)
a = input("\nEnter integer a: ")
a = int(a)
b = input("Enter integer b: ")
b = int(b)
print("Greatest common divisor of a and b: {0}".format(CustomFunctions.greatestCommonDivisor(a, b)))
c = input("\nEnter integer c: ")
c = int(c)
d = input("Enter integer d: ")
d = int(d)
print("Least common multiple of c and d: {0}".format(CustomFunctions.leastCommonMultiple(c, d)))
position = input("\nCalculate the Fibonacci number at position: ")
position = int(position)
try:
fibonacciNumber = CustomFunctions.fibonacci(position)
print("Term {0} of the Fibonacci sequence is {1}.\n".format(position, fibonacciNumber))
except ValueError as ve:
print("{0}\n".format(ve))
system("pause")
|
5e17cb7e165f7d300d5395cadf79c5605a5d4669 | RohithPrasanna/Machine-Learning | /university_type_predictor.py | 778 | 3.90625 | 4 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import KMeans
#Reading the Data
data = pd.read_csv('College_Data',index_col=0)
#Exploratory Data analysis
data.head()
data.describe()
data.info()
#Exploratory Data Visualisation; Exploring the relationships across the entire data set
sns.scatterplot(x='Grad.Rate',y='Room.Board',data=data,hue='Private')
sns.scatterplot(x='F.Undergrad',y='Outstate',data=data,hue='Private')
#K means model with 2 clusters
kmeans_model = KMeans(n_clusters=2)
#Fitting the model
kmeans_model.fit(data.drop('Private',axis=1))
#Predicting the outcome
predictions = kmeans_model.predict(data.drop('Private',axis=1))
#Cluster center vectors
print(kmeans_model.cluster_centers_)
|
88e822f7234cfbb122e66136fda6d5635231c0e5 | ed04rdo/PythonForEverybodyUM | /Fundamentals/Tuples.py | 797 | 4.3125 | 4 | # items() method in dictionary returnslist of tuples
# sorted() sorts by key
"""
tuple comparison:
>>> (0, 1, 2) < (5, 1, 2) # left to right Most Significant Value check
True
>>> (0, 1, 20000) < (0, 3, 4) # if first is the same, checks with next
True
>>> ('Jones', 'Sally') > ('Adams', 'Sam')
True
"""
def sortByKey(dict):
for key, val in sorted(dict.items()):
print(key, val)
def sortByVal(dict):
tmp = []
for key, val in dict.items():
tmp.append((val,key))
print(sorted(tmp))
def main():
(x, y) = (4, 'Fred')
(a, b) = (99, 98)
d = {'a':10, 'f':1, 'e':22, 'b':3, 'd':7, 'c':4}
sortByKey(d)
sortByVal(d)
if __name__ == "__main__":
main()
|
73fa2c9b1e9e799c9fdc1d082e4bf8dfa229e8ca | vusanthiya/pr | /numrev.py | 111 | 3.578125 | 4 | numbers=int(input())
rev=0
while(numbers>0):
rem=numbers%10
rev=(rev*10)+rem
numbers=numbers//10
print(rev)
|
075d94de0e879f84e8bcbb4225eef05047796a8b | raunaklakhwani/Algorithms | /Arrays/KLargestElemetsInAnArray.py | 515 | 3.9375 | 4 | # URL : http://www.geeksforgeeks.org/k-largestor-smallest-elements-in-an-array/
from heapq import heappop, heappush
inp = [1, 23, 12, 9, 30, 2, 50]
k = 3
def getLargestKElement(inp, k):
heap = []
for i in xrange(len(inp)):
if i < k:
heappush(heap, inp[i])
else:
if inp[i] > heap[0]:
heappop(heap)
heappush(heap, inp[i])
return heap
if __name__ == '__main__':
print getLargestKElement(inp, k)
|
ffddfeec98d2c9da1c9a1ac3eea7c4485c314294 | aditya23-1994/runtime_analyzer | /analysis.py | 762 | 3.921875 | 4 | import random, time
from code import selection_sort, insertion_sort, bubble_sort
def create_rand_list(size, max_val):
rand = random.randint(1,max_val)
rand_list= []
for number in range(size):
rand=random.randint(1,max_val)
rand_list.append(rand)
return rand_list
# size = int(input("What sixe list do you want to create? "))
# max = int(input("What is the max value of the range? "))
# print(type(size), type(max))
arr = create_rand_list(100,100)
def analyze_time(func_name,arr ):
toc = time.time()
func_name(arr)
tic = time.time()
seconds = tic - toc
print(f"{func_name} elapsed time is ---> {seconds}")
analyze_time(selection_sort,arr)
analyze_time(insertion_sort,arr)
analyze_time(bubble_sort,arr)
|
9df0100778f2d6382ad92192358e42de0d38ce58 | diljara/mipt-py | /2021-09-13/8.py | 267 | 4.03125 | 4 | # во сем (спирал квадратб)
import turtle
turtle.shape('turtle')
turtle.speed('fastest')
def spiral(a, dphi):
for i in range(1, 30, 1):
turtle.forward(a * dphi * (1 + (i * dphi)**2)**0.5)
turtle.left(dphi)
spiral(0.001, 90)
|
2c3395fea186c450fa0feee53d174a591599d83a | Quintus-Zhang/Lynx | /cubicSpline.py | 5,230 | 3.75 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 31 02:01:14 2017
@author: Quintus
"""
import numpy as np
def cubicSpline(f, x):
''' calculate coefficients of each cubic curve and output a constrained cubic spline passing given node points
args:
f is a 2-by-n numpy array that stores nodes (xi, yi)
x is a numpy array that stores time in years
return:
y is a numpy array that stores instantaneous forward rate corresponding to given time(x)
'''
xDiff = np.diff(f[0])
yDiff = np.diff(f[1])
rSlopeLeft = xDiff[0:-1] / yDiff[0:-1] # reciprocal of the slope on the leftside
rSlopeRight = xDiff[1:] / yDiff[1:]
x_i = f[0][1:]
x_im1 = f[0][0:-1]
y_im1 = f[1][0:-1]
# calculate first derivatives of f
# first derivative of f is a harmonic average of slope on each side if slope keep same sign at point, otherwise 0
f1 = 2 / (rSlopeLeft + rSlopeRight) * (np.sign(rSlopeLeft) == np.sign(rSlopeRight))
f1_0 = 1.5 * yDiff[0] / xDiff[0] - 0.5 * f1[0]
f1_n = 1.5 * yDiff[-1] / xDiff[-1] - 0.5 * f1[-1]
f1 = np.insert(f1, 0, f1_0)
f1 = np.append(f1, f1_n)
# calculate second derivatives of f
f2_im1 = -2 * (f1[1:] + 2*f1[0:-1]) / xDiff + 6 * yDiff / xDiff**2
f2_i = 2 * (2*f1[1:] + f1[0:-1]) / xDiff - 6 * yDiff / xDiff**2
# calculate coefficients for each segment of the curve
d = (f2_i - f2_im1) / (6*xDiff)
c = (x_i*f2_im1 - x_im1*f2_i) / (2*xDiff)
b = (yDiff - c*(x_i**2-x_im1**2) - d*(x_i**3-x_im1**3)) / xDiff
a = y_im1 - b*x_im1 - c*x_im1**2 - d*x_im1**3
coeffList = np.array(list(zip(a, b, c, d)))
# for each x, find the interval it belongs to
pos = np.searchsorted(f[0], x, side = 'right')
y = np.zeros(len(x))
for i in range(len(x)):
# Use constant forward rates before the first node and after the last node
if pos[i] == 0:
y[i] = np.sum(coeffList[0] * np.array([1, f[0][0], f[0][0]**2, f[0][0]**3]))
elif pos[i] == len(f[0]):
y[i] = np.sum(coeffList[-1] * np.array([1, f[0][-1], f[0][-1]**2, f[0][-1]**3]))
else:
y[i] = np.sum(coeffList[pos[i]-1] * np.array([1, x[i], x[i]**2, x[i]**3]))
return y
def cubicSplineIntg(f, x, var, ind):
''' calculate coefficients of each cubic curve and integral of instantaneous forward curve between any given point and origin
args:
f is a 2-by-n numpy array that stores nodes (xi, yi)
x is a numpy array that stores time in years
return:
Y is a numpy array that stores integral of instantaneous forward curve between any given point and origin
'''
f[1][ind] = var
xDiff = np.diff(f[0])
yDiff = np.diff(f[1])
rSlopeLeft = xDiff[0:-1] / yDiff[0:-1] # reciprocal of the slope on the leftside
rSlopeRight = xDiff[1:] / yDiff[1:]
x_i = f[0][1:]
x_im1 = f[0][0:-1]
y_im1 = f[1][0:-1]
# calculate first derivatives of f
# first derivative of f is a harmonic average of slope on each side if slope keep same sign at point, otherwise 0
f1 = 2 / (rSlopeLeft + rSlopeRight) * (np.sign(rSlopeLeft) == np.sign(rSlopeRight))
f1_0 = 1.5 * yDiff[0] / xDiff[0] - 0.5 * f1[0]
f1_n = 1.5 * yDiff[-1] / xDiff[-1] - 0.5 * f1[-1]
f1 = np.insert(f1, 0, f1_0)
f1 = np.append(f1, f1_n)
# calculate second derivatives of f
f2_im1 = -2 * (f1[1:] + 2*f1[0:-1]) / xDiff + 6 * yDiff / xDiff**2
f2_i = 2 * (2*f1[1:] + f1[0:-1]) / xDiff - 6 * yDiff / xDiff**2
# calculate coefficients for each segment of the curve
d = (f2_i - f2_im1) / (6*xDiff)
c = (x_i*f2_im1 - x_im1*f2_i) / (2*xDiff)
b = (yDiff - c*(x_i**2-x_im1**2) - d*(x_i**3-x_im1**3)) / xDiff
a = y_im1 - b*x_im1 - c*x_im1**2 - d*x_im1**3
coeffList = np.array(list(zip(a, b, c, d)))
# integral between given nodes(f)
yIntg = np.zeros(f.shape[1])
for i in range(len(f[0])):
if i == 0:
yIntg[0] = np.sum(coeffList[0] * np.array([1, f[0][0], f[0][0]**2, f[0][0]**3])) * f[0][0]
else:
yIntg[i] = np.sum(coeffList[i-1] * np.array([f[0][i], f[0][i]**2/2, f[0][i]**3/3, f[0][i]**4/4])) \
- np.sum(coeffList[i-1] * np.array([f[0][i-1], f[0][i-1]**2/2, f[0][i-1]**3/3, f[0][i-1]**4/4]))
# integral before each node
yIntg = np.cumsum(yIntg)
# integral of instantaneous forward curve between any given point(x) and origin
pos = np.searchsorted(f[0], x, side = 'right')
Y = np.zeros(len(x))
for i in range(len(x)):
# x is on the left-hand side of x0
if pos[i] == 0:
Y[i] = yIntg[0] * x[i] / f[0][0]
# x is on the right-hand side of xn
elif pos[i] == len(f[0]):
Y[i] = yIntg[-1] + \
np.sum(coeffList[-1] * np.array([1, f[0][-1], f[0][-1]**2, f[0][-1]**3])) * (x[i] - f[0][-1])
else:
Y[i] = yIntg[pos[i]-1] + \
np.sum(coeffList[pos[i]-1] * np.array([x[i], x[i]**2/2, x[i]**3/3, x[i]**4/4])) \
- np.sum(coeffList[pos[i]-1] * np.array([f[0][pos[i]-1], f[0][pos[i]-1]**2/2, f[0][pos[i]-1]**3/3, f[0][pos[i]-1]**4/4]))
return Y
|
1b3bbbf694699bda56338a14db2223ae6cb91209 | LuanCantalice/lista6prog | /questao1l6.py | 84 | 3.5625 | 4 | for i in range(200, 0, -1):
print("O quadrado do número ", i, " é: ", i**2)
|
974a157d0f6f2839148182d6027db7e8cb44151a | Ludmylla28/PythonFundamentos | /MeusCodigos/cap05/cap05-03.py | 714 | 4.0625 | 4 | #aqui vamos aprender metodos
#criando uma classe chamada Circulo
class Circulo():
#o valor de pi é constante
pi = 3.14
#criando o metodo para definirmos o valor do raio (default)que será executado no inicio
def __init__(self, raio = 5):
self.raio = raio
# criando o metodo para calcular a area do circulo
def area(self):
return(self.raio * self.raio) * Circulo.pi
#metodo para criar um novo raio
def setRaio(self, novoRaio):
self.raio = novoRaio
#metodo para obter o raio do circulo
def getRaio(self):
return self.raio
cir = Circulo()
cir.getRaio()
cir.area()
cir1 = Circulo(7)
cir1.getRaio()
cir1.area()
cir1.setRaio(3)
|
c3c279b029b60bf6534fbb30c7133ac9dc6dfc86 | rafaelperazzo/programacao-web | /moodledata/vpl_data/59/usersdata/195/48680/submittedfiles/testes.py | 145 | 4.03125 | 4 | # -*- coding: utf-8 -*-
a=int(input('digite a:'))
if a>0:
print('positivo')
elif a<0:
print('negativo')
else:
print('nulo')
|
36048650181ac434e34e50454bb71d46fa0dfab6 | Lonakshi/Python | /DATA STRUCTURES/Linkedlistdelete.py | 1,302 | 3.859375 | 4 | class node:
def __init__(self, data= None):
self.data = data
self.next = None
class linked_list:
def __init__(self):
self.head = node()
def append(self, data):
new_node = node(data)
cur= self.head
while cur.next!=None:
cur = cur.next
cur.next= new_node
def length(self):
cur = self.head
total = 0
while cur.next!= None:
total +=1
cur= cur.next
return total
def display(self):
elems =[]
cur_node = self.head
while cur_node.next!=None:
cur_node = cur_node.next
elems.append(cur_node.data)
print(elems)
def erase(self,index):
if index >= self.length():
print("ERROR: 'Erase' index of out range")
return
cur_idx=0
cur_node= self.head
while True:
last_node = cur_node
cur_node = cur_node.next
if cur_idx==index:
last_node.next = cur_node.next
return
cur_idx+=1
#Driver function
my_list = linked_list()
my_list.append(1)
my_list.append(2)
my_list.append(3)
my_list.append(4)
my_list.display()
my_list.erase(2)
my_list.display()
|
abccc217694d4c2bcb741cb5052f60b32b795bc5 | duochen/Python-Beginner | /Lecture05/Homework/solution02.py | 213 | 3.9375 | 4 | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("John", 36)
print(p.name) # => John
print(p.age) # => 36
p.age = 40
print(p.age) # => 40 |
d22dfecdc2aebc7050d872ed115b9c1a86d5580b | suraj19/Python-Assignments | /program9.py | 238 | 3.828125 | 4 | #Date: 26-07-18
#Author: A.Suraj Kumar
#Roll Number: 181046037
#Assignment 9
#Python Program to Reverse a Given Number.
n=int(input('Enter any Number:'))
rev=0
reminder=''
while(n>0):
reminder=n%10
rev=(rev*10)+reminder
n=n//10
print(rev)
|
ba93123681d0f142834736b4f8997660e97aac76 | daniel-zm-fang/High-school | /Contest Problems/Python/CCC/CCC_2011_J3.py | 155 | 3.578125 | 4 | t1 = int(input())
t2 = int(input())
len = 2
while t2 <= t1:
temp = t2
t2 = t1 - t2
t1 = temp
len += 1
# print(len, t1, t2)
print(len)
|
5e756297f7a6bd44b614da28c3378b321cbd718c | SKalantan/LearnPython | /data.py | 392 | 3.875 | 4 | import numpy as np
import matplotlib.pyplot as plt
m = np.array([1.0,2.0,4.0,6.0,9.0,11.0])
V = np.array([0.13,0.26,0.50,0.77,1.15,1.36])
print(m[0]) # Print first element in array m
print(m[3]) # Print forth element in array m
print(V[0]) # Print first element in array V
print(V[3]) # Print forth element in array V
plt.plot(m,V,'o')
plt.xlabel('m (kg)')
plt.ylabel('V (l)')
plt.show()
|
3a772fdc0f59eb50fc6cbb3235ae1f65e43aa937 | rpalo/advent-of-code-2018 | /python/src/day23.py | 2,504 | 4 | 4 | """Day 23: Experimental Emergency Teleportation
Find optimal locations for strong connections to nanobots in 3D space.
"""
from collections import Counter
from dataclasses import dataclass
from itertools import permutations
import re
from typing import List
@dataclass(frozen=True)
class Nanobot:
"""A nanobot in 3D space"""
x: int
y: int
z: int
r: int
def parse(text: str) -> List[Nanobot]:
"""Parses text where each line specifies a Nanobot."""
bots = []
pattern = re.compile(r"pos=<(-?\d+),(-?\d+),(-?\d+)>, r=(\d+)")
for line in text.splitlines():
match = pattern.match(line)
if not match:
raise ValueError(f"Invalid line: {line}")
x, y, z, r = match.group(1, 2, 3, 4)
bots.append(Nanobot(int(x), int(y), int(z), int(r)))
return bots
def manhattan_distance(b1: Nanobot, b2: Nanobot) -> int:
"""The Manhattan Distance between two points is sum of steps required
in X, Y, and Z (perpendicular movements only).
"""
return abs(b1.x - b2.x) + abs(b1.y - b2.y) + abs(b1.z - b2.z)
def distance_from_radius_to_origin(bot: Nanobot) -> int:
"""Find the smallest distance from the surface of a sphere to the origin."""
return max(bot.x + bot.y + bot.z - bot.r, 0)
def in_range_of_strongest(bots: List[Nanobot]) -> int:
"""Count how many bots are in range of the strongest (by radius) bot. Include itself."""
strongest = max(bots, key=lambda bot: bot.r)
return sum(manhattan_distance(strongest, bot) <= strongest.r for bot in bots)
def best_point_distance(bots: List[Nanobot]) -> int:
"""Find the point in range of the most bots, breaking ties by closest to the origin.
Return the manhattan distance from the origin to that point.
"""
overlaps = []
for b1 in bots:
touching = frozenset(b2 for b2 in bots if b1.r + b2.r >= manhattan_distance(b1, b2))
overlaps.append(touching)
counts = Counter(a & b for a, b in permutations(overlaps, 2) if (a & b))
biggest_group, _occurrences = counts.most_common(1)[0]
return max(distance_from_radius_to_origin(bot) for bot in biggest_group)
if __name__ == "__main__":
with open("data/day23.txt", "r") as f:
text = f.read()
bots = parse(text)
print("Number in range of strongest:", in_range_of_strongest(bots))
print("Distance from best point to origin:", best_point_distance(bots))
|
137b38bbc683d01f5321bc343eceaef67b143f3a | Ridam-Loo/Reindeer-Game | /reindeerV2.py | 2,569 | 3.640625 | 4 | # Computer Science CPT - Reindeer Game
# @author Ridam Loomba
# @date 2017/01/09
# @course ICS3C
# Main Program
import pygame
import random
# Define some colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN= (79,183,69)
GREY= (178,176,183)
#Define some variable
tree_x=20
tree_y=-300
class Gift(pygame.sprite.Sprite):
#creates the imag eof the gift
def __init__ (self, colour, width, height):
super().__init__()
self.image= pygame.Surface([width, height])
self.rect = self.image.get_rect()
self.colour= (random.randrange (0,255), random.randrange(0,255), random.randrange(0,255))
def move_down (self):
self.rectY= self.rectY+ random.randrange(2,4)
if self.rectY >500:
self.place_top
def place_top(self):
self.rectY = random.randrange(-300, -20)
self.rectX = random.randrange(0, screen_width)
# Call this function so the Pygame library can initialize itself
pygame.init()
# Create screen
screen_width=1000
screen_height=600
screen = pygame.display.set_mode([screen_width, screen_height])
#List of gift sprites
gift_list= pygame.sprite.Group()
#List of all sprites
every_Sprite_list= pygame.sprite.Group()
for i in range (20):
gift=Gift(WHITE,50,50)
gift.rectX = random.randrange(300,400)
gift.rectY = 0
# Add the gift to the list of objects
gift_list.add(gift)
every_Sprite_list.add(gift)
#Set caption of game
pygame.display.set_caption("Reindeer Game")
clock = pygame.time.Clock()
# Load and set up graphics.
# image taken from https://upload.wikimedia.org/wikipedia/commons/8/83/Christmas_trees.png
tree_image = pygame.image.load("tree02.png").convert()
tree_image.set_colorkey(WHITE)
done = False
#-----Main-----
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill (GREY)
# Update every sprite in sprite list
every_Sprite_list.update()
#Loop to draw grass on both sides of the screen
y_offset= 0
while y_offset<1000:
pygame.draw.rect(screen, GREEN, [0+y_offset,0,250,600])
y_offset= y_offset + 750
# Draw the tree
for i in range (random.randrange (2,4)):
tree_y=tree_y+1
screen.blit(tree_image, [tree_x, tree_y])
if tree_y>600:
tree_y=-300
# Draw all the spites
every_Sprite_list.draw(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
|
eacfa8df36eeb0f39ab6a2fe25dcf21d9e903dbf | seryogasx/VUZ | /maths/math/7sem/Петров_лаб2(runge).py | 1,757 | 3.796875 | 4 | from numpy import arange
from matplotlib import pyplot
from math import fabs
print("Метод Рунге-Кутты:\n")
left, right = 1, 2
func = lambda x, y: -y/x - x**2 # определение данной функции (производная из варианта 3)
originFunc = lambda x: (1 - 0.25*x**4)/x # точное решение
def runge(h):
x = arange(left, right+h, h) # определение точек x
# определение коэффициентов K
K1 = lambda x, y: func(x, y)
K2 = lambda x, y, h: func(x + h/2, y + h*K1(x, y)/2)
K3 = lambda x, y, h: func(x + h/2, y + h*K2(x, y, h)/2)
K4 = lambda x, y, h: func(x + h, y + h*K3(x, y, h))
yk_plus_1 = 0.75 # начальное значение
y = [yk_plus_1] # список с значениями y
mx = 0 # переменная для поиска отклонения
# рассчет согласно формулам
for i in x[1:]:
yk_plus_1 = yk_plus_1 + (h/6) * (K1(i, yk_plus_1) + 2*K2(i, yk_plus_1, h) + 2*K3(i, yk_plus_1, h) + K4(i, yk_plus_1, h))
y.append(yk_plus_1) # добавление значения
mx = max(mx, fabs(yk_plus_1 - originFunc(i))) # поиск максимального отклонения
print("Максимальное отклонение от исходной функции (шаг {}): {}".format(h, mx))
pyplot.grid(True)
pyplot.plot(x, y, label="Метод Рунге-Кутты 4 порядка с шагом {}".format(h)) # результирующий график
runge(0.1)
runge(0.01)
# график исходной функции
x = arange(left, right+0.01, 0.01) # определение точек x
pyplot.plot(x, [originFunc(i) for i in x], label='Точное решение')
pyplot.legend()
pyplot.show() |
e40ccde30a5757f957b1be65c507a886eb7e5faf | JPunter/The-Python-Bible | /P4.py | 962 | 3.890625 | 4 | #Travis the ridiculous security system
knownUsers = ["Alice", "Bob", "Charlie", "David", "Ed", "Frank", "Gary", "Henry"]
while True:
print("Hi! My name is Travis")
name = input("What is your name?: ").strip().capitalize()
if name in knownUsers:
print("Hello {}! Welcome!".format(name))
remove = input("Would you like to be removed from the system (y/n)?: ").strip().lower()
if remove == "y":
knownUsers.remove(name)
print("Thanks {}! You have been removed from the system".format(name))
else:
print("I hope you enjoy your continued membership!")
else:
print("I don't think we've met yet {}".format(name))
add = input("Would you like to be added to the system (y/n)?: ").strip().lower()
if add == "y":
knownUsers.append(name)
print("You have been added to our system!")
else:
print("OK")
|
676068c8cbd80f81a2e37a1bcb1b9c99a6c15599 | roy2020china/BingDemo | /1_compare_numbers.py | 858 | 3.9375 | 4 | # A procedure named "bigger". Find out the bigger of out two radom numbers.
# 名为bigger的函数。在两个随机数字当中找出较大的那个数字。
def bigger(a,b):
if a > b:
return a
else:
return b
# A procedure named "biggest". Find out the biggest of out three random numbers. I like this one very much.
# 名为biggest的函数。在三个随机数字当中找出最大的那个数字。我非常喜欢这一个。
def biggest(a,b,c):
return bigger(a,bigger(b,c))
# A procedure named "median". Find out the median one of out three random numbers.
# 名为median的函数。在三个随机数字当中找出中间的那个数字。
def median(a,b,c):
if bigger(a,b) <= c:
return bigger(a,b)
if bigger(a,c) <= b:
return bigger(a,c)
if bigger(b,c) <= a:
return bigger(b,c)
|
05cbf10f9f57b4968c60c2c9250f317ccae6996c | yukkiball/Python-Algorithm | /查找/二分查找.py | 1,013 | 3.875 | 4 | def search_rec(list, x, lo, hi):
"""递归版二分查找返回小于等于该元素的最大秩"""
if lo > hi:
return lo - 1
mid = (lo + hi) // 2
# if list[mid] > x:
# return search_rec(list, x, lo, mid - 1)
# elif list[mid] < x:
# return search_rec(list, x, mid + 1, hi)
# else:
# return mid
if list[mid] > x:
return search_rec(list, x, lo, mid - 1)
else:
return search_rec(list, x, mid + 1, hi)
def search_iter(list, x, lo, hi):
"""二分查找迭代版返回小于等于该元素的最大秩"""
while lo <= hi:
mid = (lo + hi) >> 1
# if list[mid] < x:
# lo = mid + 1
# elif list[mid] > x:
# hi = mid - 1
# else:
# return mid
if list[mid] > x:
hi = mid - 1
else:
lo = mid + 1
return lo - 1
#测试
l1 = [1, 3, 4, 5, 6, 7]
print(search_rec(l1, 7, 0, len(l1) - 1))
print(search_iter(l1, 3, 0, len(l1) - 1))
|
fe8454a6c15899456473f1d21b5091ea86e72a81 | QTAnt/Python | /Python入门3/Python15.py | 2,291 | 4.15625 | 4 | # 11/15###################################################################################
# if/else/elif
'''
if a>b:
do_soming()
if expression:
do_something1 # ÿ4ո(ܶ/)
do_something2
next_something # һӡ
if expression:
do_something1
else:
do_something2
result = input('What to eat today? 1 Cold 0 Hot')
if result == '1':
print('ice cream')
else:
print('huoguo')
result = input('What to eat today? 1 Cold 0 Hot')
if result == '1':
print('ice cream')
print('ice cream')
if result == '1': # ֹǶ
print('rice')
if result == '1':
print('rice')
elif result == '0':
print('huoguo')
print('huoguo')
else:
print('salad')
while expression:
do_something
# ѭִprint
counter = 0
while counter < 3:
print 'loop %d' % counter
counter += 1
'''
"""
# Python1ӡ10
# 1
num = 1
while num <= 10:
print(num)
num += 1
# 2
for num in range(1,11):
print(num)
"""
"""
a = [3,7,1,9] # ַеÿһԪ
a = 'holdon' # ַеÿһַ
for num in a: # ȡaе
print(num)
a = {'ip':'127.0.0.1','port':'80'}
for key in a:
print(key,a[key])
# ڽrangerangeIJǰʾҿʾ
# forѭִ10δӡ1ʼ10[1,11)
for num in range(1,11):
print(num)
# [0, 100)еż
for i in range(0, 100, 2):
print i
# breakcontinue
for num in range(1,10):
if num % 3 == 0:
# break
continue
print(num)
for i in range(1,30):
if i % 3 != 0:
continue
print(i)
# pass()
if a == 10:
pass
else:
print('hello')
"""
# ͳд
'''
a = [1,2,3,4,5]
b = []
for num in a:
b.append(num ** 2) # **ʾ˷
print(b)
# бƵ
a = [1,2,3,4,5]
# b = [x ** 2 for x in a]
b = [x ** 2 for x in a if x % 2 == 1] #
print(b)
# [0, 4) ֵƽ
squared = [x ** 2 for x in range(4)]
print(squared)
# ȡ [0, 8) ее
evens = [x for x in range(0, 8) if x % 2 == 1]
print evens
''' |
9a2f42b9f0f065ccf142a486b298da34da639ba2 | mehtasahil31/CSC-591-ASE | /hw/7/Num.py | 1,207 | 3.765625 | 4 | from Col import Col
class Num(Col):
"Num class as a subclass of Col"
def __init__(self, column_name="", position=0, weight=1):
super().__init__(column_name, position, weight)
self.mu = 0
self.m2 = 0
self.lo = 10 ** 32
self.hi = -1 * 10 ** 32
self.sd = 0
def add_new_value(self, number):
"Add new value to the list and update the paramaters"
self.all_values.append(number)
if number < self.lo:
self.lo = number
if number > self.hi:
self.hi = number
self.n += 1
d = number - self.mu
self.mu += d / self.n
self.m2 += d * (number - self.mu)
self.sd = 0 if self.n < 2 else (self.m2 / (self.n - 1 + 10 ** -32)) ** 0.5
def dist(self, x, y):
"Calculate distance between 2 rows"
norm = lambda z: (z - self.lo) / (self.hi - self.lo + 10 ** -32)
if x == "?":
if y == "?": return 1
y = norm(y)
x = 0 if y > 0.5 else 1
else:
x = norm(x)
if y == "?":
y = 0 if x > 0.5 else 1
else:
y = norm(y)
return abs(x - y)
|
12aca3b0aa5483e54f6543ff0dfb4147d52ee6f8 | BC-csc226-masters/a03-fall-2021-master | /a03_qasema.py | 5,167 | 3.984375 | 4 | # Author Ala Qasem
#
# A03 Assignment.
#
# username:qasema
# goog Doc: https://docs.google.com/document/d/1KmxGDSYlMvPw7RvxMy8dhalMqZi-Sm9sydeMn83LnY0/edit?usp=sharing
################################################################################################
# in this cos e i will draw a shark. I hope you like. it does not look perfect but i spent a lot of time building it
"""first i will import the turtle library. """
import turtle
"""working on the window and importing an image as a background AND then name a turtle """
wn = turtle.Screen()
wn.colormode(250)
wn.bgpic("ocean.gif")
wn.bgcolor("#006994")
shark = turtle.Turtle()
turtle.colormode(250)
def function_1():
shark.speed(0)
shark.pensize(120)
shark.pencolor("#006994")
shark.forward(83)
shark.left(90)
shark.forward(24)
shark.left(90)
shark.forward(148)
shark.left(90)
shark.forward(20)
shark.left(90)
shark.forward(100)
shark.left(90)
shark.pensize(45)
shark.forward(125)
shark.pensize(10)
shark.right(90)
shark.right(90)
shark.forward(10)
shark.left(90)
shark.pensize(17)
shark.forward(30)
shark.right(90)
shark.forward(30)
shark.left(90)
shark.penup()
shark.goto(0.00, 0.00)
shark.pendown()
shark.pensize(4)
shark.color("black")
shark.left(90)
shark.forward(170)
print(shark.pos())
shark.penup()
shark.left(90)
shark.forward(90)
shark.pendown()
shark.left(75)
shark.forward(90)
print(shark.pos())
shark.left(105)
shark.forward(170)
print(shark.pos())
"""draw the shape of the eyes"""
def function_2():
shark.begin_fill()
shark.fillcolor("white")
for i in range(36):
shark.forward(3)
shark.right(10)
shark.penup()
shark.forward(35)
shark.pendown()
for i in range(36):
shark.forward(3)
shark.right(10)
shark.end_fill()
shark.penup()
shark.goto(56.71, 83.07)
shark.fillcolor("#006994")
shark.forward(45)
shark.pendown()
shark.forward(130)
shark.right(115)
shark.forward(40)
# draw the mouth
def function_3():
shark.begin_fill()
shark.fillcolor("#006994")
for i in range(5):
shark.right(14)
shark.forward(25)
for i in range(5):
shark.forward(20)
shark.right(5)
shark.end_fill()
'''draw fins'''
def function_4():
shark.begin_fill()
shark.fillcolor("#006994")
shark.penup()
shark.goto(0.00, 0.00)
shark.left(45)
shark.forward(30)
shark.pendown()
for i in range(40):
shark.left(3)
shark.forward(3)
shark.left(60)
for i in range(40):
shark.left(2.5)
shark.forward(2.5)
shark.end_fill()
'''draw the rest of the body'''
def function_5():
shark.begin_fill()
shark.penup()
shark.goto(-113.29, 83.07)
shark.left(130)
shark.forward(33)
shark.pendown()
shark.end_fill()
print(shark.pos())
for i in range(9):
shark.left(10)
shark.forward(15)
shark.penup()
shark.left(15)
shark.forward(62)
shark.pendown()
shark.right(5)
for i in range(13):
shark.left(5)
shark.forward(16)
shark.left(30)
shark.forward(5)
'''draw the tale'''
def function_6():
shark.penup()
shark.goto(-127.24, 53.16)
shark.pendown()
shark.left(125)
shark.forward(86)
shark.left(-152)
shark.forward(185)
shark.penup()
shark.goto(0.00, 170.00)
shark.pendown()
shark.right(60)
for i in range(13):
shark.forward(10.5)
shark.right(8)
'''draw eyes'''
def function_7():
shark.penup()
shark.forward(15)
shark.right(170)
shark.pendown()
shark.circle(5)
shark.penup()
shark.right(90)
shark.forward(30)
shark.pendown()
shark.circle(5)
def shark_coloring():
shark.penup()
shark.goto(50, 30)
shark.pendown()
shark.pensize(29)
shark.pencolor("#006994")
shark.left(17)
shark.forward(145)
shark.left(55)
shark.forward(27)
shark.pensize(20)
shark.left(117)
shark.forward(85)
shark.left(90)
shark.forward(20)
shark.left(90)
shark.forward(60)
shark.penup()
shark.goto(50, 30)
shark.left(130)
shark.pendown()
shark.forward(50)
shark.pensize(28)
shark.left(140)
shark.forward(38)
shark.penup()
shark.goto(-127.24, 53.16)
shark.pendown()
shark.begin_fill()
shark.pensize(3)
shark.left(180)
shark.forward(64)
shark.right(35)
shark.forward(48)
shark.right(180)
shark.forward(170)
shark.left(160)
shark.end_fill()
shark.forward(90)
shark.begin_fill()
shark.left(40)
shark.forward(80)
shark.left(165)
shark.forward(80)
shark.end_fill()
def main():
function_1()
function_2()
function_3()
function_4()
function_5()
function_6()
function_7()
shark_coloring()
shark.hideturtle()
shark.color("red")
shark.write("Hello Shark", move=False, align='right', font=("Arial", 30, ("bold","normal")))
main()
wn.exitonclick()
|
7c190c46fd5bbe61355096fbb118976ea00dd3c4 | ningwho/algorithms- | /my_dictionary.py | 1,954 | 3.890625 | 4 | class MyDictionary:
def __init__(self):
self.keys = []
self.values = []
def insert_element(self, key, value):
#Insert the element into the dictionary.
self.keys.append(key)
self.values.append(value)
def find_element(self, key):
# finds the element associated with the keyself.
# returns none if key doesn't exist
for x in range (len(self.key)):
if self.key[i] == key:
return self.values[i]
break
# look through all our keys. once found the key will stop looking after loop
return None
def remove_element(self, key):
# finds element associated with key
# removes element if element is found
for x in range(len(self.keys)):
if self.keys[i] == key:
del self.values[i]
del self.keys[i]
def get_keys(self):
# returns all keys
return self.keys
def elements(self):
#returns all elements
return self.values
def isEmpty(self):
#returns if the element list is empty
if self.size() == 0:
return True
else:
return False
def size(self):
#returns the size of the elements list
return len(self.values)
dictionary = MyDictionary()
dictionary.insert_element('email','hamburger@gmail.com')
dictionary.insert_element('password','spaghetti')
dictionary.insert_element('phone','770-555-5555')
# child_dictionary = MyDictionary()
# child_dictionary.insert_element('another_value', 'test')
# dictionary.insert_element('child', dictionary)
# if dictionary.find_element('email') == 'tamby@hirewire.com':
# print('yay')
for key in dictionary.get_keys():
print(key + "\t\t" + dictionary.find_element(key))
# dictionary.remove_element('phone')
print("=======\n\n")
for key in dictionary.get_keys():
print(key + "\t\t" + dictionary.find_element(key))
|
d0096d4aaba027db7e535d104a304dbea259f514 | iamtariqueanjum/p4e_coursera | /strfindreplace.py | 195 | 3.703125 | 4 | fruit = 'banana'
pos = fruit.find('na')
print(pos)
pos1 = fruit.find('z')
print(pos1)
greet = 'Hello Bob'
nstr = greet.replace('Bob','Adam')
print(nstr)
nstr = greet.replace('o','x')
print(nstr)
|
53bd39ba006bba425d547416112063a755f8c8f4 | gmeluski/Projects | /Numbers/answers/calc.py | 563 | 4.4375 | 4 | # -*- coding: cp1252 -*-
"""
Calculator - A simple calculator to do basic operators.
"""
if __name__ == '__main__':
num1 = input("Number 1: ")
num2 = input("Number 2: ")
op = raw_input("Operation (+, -, /, *): ")
if op not in '+-/*':
print "Invalid operator"
else:
if op == '+':
res = num1 + num2
elif op == '-':
res = num1 - num2
elif op == '/':
res = num1 / num2
elif op == '*':
res = num1 * num2
print "%d %s %d = %d" % (num1, op, num2, res)
|
60645f75e66979a709c6369fd4e9bd871ee94def | SanjaySantokee/Algorithms-Implementation | /Knapsack/BeadsDP.py | 1,813 | 3.84375 | 4 | """
/*
Full Name: Sanjay Santokee
Email: sanjay.santokee@my.uwi.edu
*/
Given a number of beads on a wire, bw, sequenced 1, 2, 3, .., etc. and boxes to place the beads, bx, sequenced 1,
2, 3, 4, ..., etc., where bx ≥ bw, such that placing the beads in certain boxes increases the aesthetic value.
The beads must be placed sequentially in the boxes up until the last box. """
def bead_DP(A: list):
for i in range(1, beads + 1):
for j in range(1, boxes + 1):
if i == 0 or j == 0:
A[i][j] = 0
if i == j and i > 0 and j > 0:
A[i][j] = A[i - 1][j - 1] + A[i][j]
if j > i > 0 and j > 0:
A[i][j] = max(A[i][j - 1], A[i - 1][j - 1] + A[i][j])
return A
def backtrack_beads(i: int, j: int, B: list):
if i == 0 or j == 0:
return
if i == j:
backtrack_beads(i - 1, j - 1, B)
print('The Bead ', i, ' is put into the Box ', j)
elif B[i][j] > B[i][j - 1] and B[i][j] > B[i][j - 1]:
backtrack_beads(i - 1, j - 1, B)
print('The Bead ', i, ' is put into the Box ', j)
elif B[i][j] == B[i][j - 1]:
backtrack_beads(i, j - 1, B)
if __name__ == "__main__":
with open('beads.txt') as file:
beads, boxes = list(map(int, file.readline().strip('\n').split()))
aesthetics = []
for row in range(beads + 1):
aesthetics.append([0 for col in range(boxes + 1)])
row = 1
for line in file:
data = line.split()
for col in range(1, boxes + 1):
aesthetics[row][col] = int(data[col - 1])
row += 1
# Computing beads table
B_table = bead_DP(aesthetics)
# Backtracking to output beads and its placement
backtrack_beads(beads, boxes, B_table)
|
8cbd2475c3ce2e7272b928d089c69ca80efb2c06 | 1769778682/python06 | /class1/x_text01.py | 236 | 3.90625 | 4 | # hash()":可以帮助验证一个数据的特征码
# 内容相同,得到的结果一致
# 不同内容,得到的结果不一致
print(hash('123456'))
print(hash('123456'))
# print("*" * 50)
# print(hash(100))
# print(hash(100))
|
3dc77013db1fe70e1b21e6ec80c01bd020ef1cf2 | gabrielsimongianotti/curso-em-video-Python | /TiposPrimitvoseSaidaDeDados.py | 168 | 3.859375 | 4 | n1 = int(input('digita um numero '))
n2 = int(input('digita outro numero '))
soma = n1 + n2
print('a soma de {0} mais {1} numeros é igual a {2}'.format(n1,n2,soma)) |
ee36bc8f703c293383ee42aa3649fe81db78546b | grodrig6/Caso_clasifica_bases | /Conexion/Conexion_empleado.py | 1,354 | 3.59375 | 4 | import sqlite3
import Funciones.Desencripta
class Empleado:
def __init__(self):
self.conexion_empleado = sqlite3.connect("EMPLEADO.db")
def buscar(self, usuario, contrasenia):
try:
#Encripta contraseña pasada por parametro desde interfaz grafica
self.pass_enc = Funciones.Desencripta.Desencripta_pass().ejecuta_encriptado(contrasenia)
#Genera cursor y realiza consulta a tabla
self.cursor_busca=self.conexion_empleado.cursor()
self.cursor_busca.execute("SELECT TR_USUARIO, TR_CONTRASENIA FROM TRABAJADORES WHERE TR_USUARIO = '" + usuario + "'")
#Asigna elresultado se la consulta a una variable
self.resultado=self.cursor_busca.fetchone()
#Evalua si usuario y contraseña retornada de la base de datos coincide con los datos ingresados
if self.resultado == None:
return False
else:
if str(self.pass_enc) == self.resultado[1].strip():
return True
else:
return False
self.cierra_conexion()
except sqlite3.OperationalError:
#servidor.quit()
return "Error en conexion"
def cierra_conexion(self):
self.conexion_empleado.close()
|
0ae7c95833e9b112f6c42fb280abfc19ece8280b | fulinke/ichw | /pyassign2/currency.py | 2,524 | 3.953125 | 4 | """This is a module for currency exchange
This module provides several string parsing functions to implement a
simple currency exchange routine using an online currency service.
The primary function in this module is exchange."""
def exchange(currency_from, currency_to, amount_from ):
"""generate a URL and use it to get datas from the website"""
d = 'http://cs1110.cs.cornell.edu/2016fa/a1server.php?from=x&to=y&amt=z'
e = d.replace('x', currency_from)
f = e.replace('y', currency_to)
g = f.replace('z', amount_from)
from urllib.request import urlopen
doc=urlopen(g)
docstr=doc.read()
doc.close()
jstr = docstr.decode('ascii')
return jstr
def test_exchange():
"""test the function 'exchange' """
a = "USD"
b = "EUR"
c = "2.5"
t1=exchange(a, b, c)
tt1 = '{ "from" : "2.5 United States Dollars", "to" : "2.1589225 Euros", "success" : true, "error" : "" }'
assert (t1 == tt1)
a = "BWP"
b = "NZD"
c = "4.73"
t2 = exchange(a, b, c)
tt2 = '{ "from" : "4.73 Botswanan Pula", "to" : "0.66796788832763 New Zealand Dollars", "success" : true, "error" : "" }'
assert (t2 == tt2)
a = "CAD"
b = "CAD"
c = "10.8"
t3 = exchange(a, b, c)
tt3 = '{ "from" : "10.8 Canadian Dollars", "to" : "10.8 Canadian Dollars", "success" : true, "error" : "" }'
assert (t3 == tt3)
def extract(m):
"""output the result in a proper way"""
i = m.split('"')
h = i[7]
"""amount and currency symbols"""
j = h.partition(' ')
k = j[0]
"""amount only"""
return k
def test_extract():
"""test the function 'extract' """
"""test 1"""
a = "USD"
b = "EUR"
c = "2.5"
t1 = exchange(a,b,c)
i1 = extract(t1)
ii1 = '2.1589225'
assert (i1 == ii1)
a = "BWP"
b = "NZD"
c = "4.73"
t2 = exchange(a,b,c)
i2 = extract(t2)
ii2 = '0.66796788832763'
assert (i2 == ii2)
"""test 3"""
a = "CAD"
b = "CAD"
c = "10.8"
t3 = exchange(a,b,c)
i3 = extract(t3)
ii3 = '10.8'
assert (i3 == ii3)
def testAll():
"""test all cases"""
test_exchange()
test_extract()
print("All tests passed")
def main():
"""get the inputs, test all cases, and then output"""
x = input()
y = input()
z = input()
q = exchange(x,y,z)
s = extract(q)
print(s)
testAll()
if __name__ == "__main__":
main()
|
f2ed7dabbb32e035b55ccf492cbbf582e7575119 | piumallick/Python-Codes | /LeetCode/Problems/0733_floodFill.py | 2,297 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 11 10:52:56 2020
@author: piumallick
"""
# Problem 733: Flood Fill
'''
An image is represented by a 2-D array of integers,
each integer representing the pixel value of the image (from 0 to 65535).
Given a coordinate (sr, sc) representing the starting pixel (row and column)
\of the flood fill, and a pixel value newColor, "flood fill" the image.
To perform a "flood fill", consider the starting pixel,
plus any pixels connected 4-directionally to the starting pixel o
f the same color as the starting pixel, plus any pixels connected 4-directionally
to those pixels (also with the same color as the starting pixel), and so on.
Replace the color of all of the aforementioned pixels with the newColor.
At the end, return the modified image.
Example 1:
Input:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation:
From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
by a path of the same color as the starting pixel are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected
to the starting pixel.
Note:
The length of image and image[0] will be in the range [1, 50].
The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length.
The value of each color in image[i][j] and newColor will be an integer in [0, 65535].
'''
def floodFill(image, sr, sc, newColor):
row_length = len(image)
col_length = len(image[0])
color = image[sr][sc]
if (color == newColor):
return image
def floodFillConditions(row, col):
if (image[row][col] == color):
image[row][col] = newColor
if (row >= 1):
floodFillConditions(row - 1, col)
if (row + 1 < row_length):
floodFillConditions(row + 1, col)
if (col >= 1):
floodFillConditions(row, col - 1)
if (col + 1 < col_length):
floodFillConditions(row, col + 1)
floodFillConditions(sr, sc)
return image
# Testing
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1
sc = 1
newColor = 2
print(floodFill(image, sr, sc, newColor)) |
e90dbf76112b0720ba6e97e615a8b95bc1c4ef62 | ksrntheja/08-Python-Core | /venv/strings/String030Count.py | 794 | 3.546875 | 4 | s = 'learning python is very easy'
print("s.count('y') ->", s.count('y'))
print("s.count('y', 22, 30) ->", s.count('y', 22, 30))
print("s.count('y', 23, 30) ->", s.count('y', 23, 30))
print("s.count('y', -1, -5) ->", s.count('y', -1, -5))
print("s.count('y', -5, -1) ->", s.count('y', -5, -1))
print("s.count('y', -5, 0) ->", s.count('y', -5, 0))
print("s.count('y', -28, -1) ->", s.count('y', -28, -1))
print("s.count('e', -5, -1) ->", s.count('e', -5, -1))
print("s.count('e', -1, -5) ->", s.count('e', -1, -5))
# s.count('y') -> 3
# s.count('y', 22, 30) -> 2
# s.count('y', 23, 30) -> 1
# s.count('y', -1, -5) -> 0
# s.count('y', -5, -1) -> 0
# s.count('y', -5, 0) -> 0
# s.count('y', -28, -1) -> 2
# s.count('e', -5, -1) -> 1
# s.count('e', -1, -5) -> 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.