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 |
|---|---|---|---|---|---|---|
e69df271cf93261e900111446f4654aa30da3523 | YoonSungLee/Algorithm_python | /programmers-코딩테스트 고득점 Kit/level_01/3진법 뒤집기.py | 325 | 3.53125 | 4 | # 7 min
# my sol
def solution(n):
number_3 = ''
while True:
if n < 3:
number_3 = str(n) + number_3
break
number_3 = str(n % 3) + number_3
n = n // 3
answer = 0
for idx, num in enumerate(number_3):
answer += int(num) * (3 ** int(idx))
return answer |
0a359a8ec8e3c65b77b947c7cf710a875401e543 | TarenGorman/ivybranch | /ivybranch/core/map.py | 1,115 | 3.6875 | 4 | """
Simple String Hash Map Implementation
"""
class Hashmap:
"""
O(n) build of indices, O(1) insert/get/delete
"""
def __init__(self):
self.size = 9973
self.values = [0 for i in range(0, self.size)]
self.keys = [0 for i in range(0, self.size)]
def put_item(self, key, value, delete=False):
index = self._hash_item(key)
if self.values[index] != 0:
raise KeyError
else:
self.values[index] = value
if delete:
self.keys[index] = 0
else:
self.keys[index] = key
return None
def get_item(self, key):
try:
item = self.values[self._hash_item(key)]
except:
raise KeyError
return item
def del_item(self, key):
self.put_item(key, 0, delete=True)
return None
def _hash_item(self, item):
"""
Custom basic hash function, sum of ords
"""
total = 0
for i in list(item):
total = total + ord(i)
return total % self.size
|
d271b0423eeaca6b1de9c1bf097246d22e3f0514 | anderson-br-ti/python | /Projetos/Lista IV exercício 3.py | 231 | 3.6875 | 4 | from random import randint
v1 = [ ]
v2 = [ ]
v3 = [ ]
for k in range(10):
x = randint(1, 100)
v1.append(x)
v3.append(x)
x = randint(1, 100)
v2.append(x)
v3.append(x)
print('v1:', v1)
print('v2:', v2)
print('v3:', v3)
|
327b61a1988b3b6581187805261dc0aefb4a2086 | jeannieyeliu/leetcode | /linkedList.py | 652 | 3.765625 | 4 | class ListNode:
def __init__(self, val: int = 0, next=None):
self.val = val
self.next = next
def create_linklist(self, arr: list):
self.val = arr.pop(0)
currNode = self;
for val in arr:
nextNodde = ListNode(val)
currNode.next = nextNodde;
currNode = nextNodde
def printLL(self):
head = self
while (head):
print(head.val, end=", ")
head = head.next
print("")
def append(self, arr):
curr = self
for a in arr:
node = ListNode(a)
curr.next = node
curr = node
|
af565262be78536d0b149dbb47aabff19f5a7c02 | Weless/leetcode | /python/树/101. 对称二叉树.py | 2,076 | 3.6875 | 4 | class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return False
from collections import deque
queue = deque()
queue.append(root)
res = [[root.val]]
while queue:
tmp = []
for _ in range(len(queue)):
node = queue.popleft()
if node.left:
queue.append(node.left)
tmp.append(node.left.val)
else:
tmp.append(None)
if node.right:
queue.append(node.right)
tmp.append(node.right.val)
else:
tmp.append(None)
res.append(tmp)
for items in res:
if len(items) > 1:
i,j = 0,len(items)-1
while i<j:
if items[i] != items[j]:
return False
i+=1
j-=1
return True
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
return self.isMirror(root,root)
def isMirror(self,t1:TreeNode,t2:TreeNode):
if not t1 and not t2: return True
if t1 or t2: return False
return t1.val == t2.val and self.isMirror(t1.right,t2.left) and self.isMirror(t1.left,t2.right)
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
from collections import deque
queue = deque()
queue.append(root)
queue.append(root)
while queue:
t1 = queue.popleft()
t2 = queue.popleft()
if not t1 and not t2:
continue
if not t1 or not t2:
return False
if t1.val != t2.val:
return False
queue.append(t1.left)
queue.append(t2.right)
queue.append(t1.right)
queue.append(t2.left)
return True |
63a7097ce2988a5b6c1c5ca2524719229b04b94c | adeelnasimsyed/Interview-Prep | /kSmallestNum.py | 206 | 3.734375 | 4 | #returns the k smallest num in array
def kSmallestNum(array, k):
array.sort()
if k > len(array):
return array[-1]
else:
return array[k-1]
array = [1,10,2,9,22,3,4]
print(kSmallestNum(array,3))
|
3b8384c5dd41b5424337a3f5d24536517e787e7c | GamingBaron/OverWatch-Heros | /OverWatch Hero classes/OverWatch Hazo.py | 915 | 3.71875 | 4 | class Hazo():
def __init__(self, name, age):
"""Initalize name and age attibutes."""
self.name = name
self.age = age
def Storm_Bow(self):
"""sulate a caricter shotting a Arrow from a Storm Bow in a responce to commond."""
print(self.name.title() + " is now shotting.")
def Soic_Arrow(self):
"""simulate a caricter shotting a Sonic arrow in a responce to command."""
print(self.name.Title() + " Soic Arrow!")
def Scatter_arrow(self):
"""simulate a caricter Shotting a Scatter arrow in a responce to command."""
print(self.name.Title() + " Scatter arrow!")
def DragenStrick(self):
"""simulate a caricter shotting DragenStrick in a responce to command."""
print(self.name.Title() + " DragenStrick!")
my_Caricte = Caricter('Hazo', 38 years)
print("My caricter's name is " + my_caricter.name.title() + ".")
print("My caricter is " + str(my_caricter.age) + "38 years old.")
|
438b5f5ac9f5e50db1891c742aeb8c501432ca88 | c-yan/yukicoder | /9009.py | 89 | 3.53125 | 4 | N = int(input())
result = 0
for _ in range(N):
result += int(input())
print(result)
|
f15e6db19385d9b2602e56ee8a5327d390e0777e | bethanymbaker/arch | /tutorials/shapes_0.py | 327 | 3.875 | 4 | import numpy as np
class Square:
def __init__(self, length):
self.length = length
def area(self):
return self.length ** 2
def perimeter(self):
return self.length * 4
square = Square(length=3)
print(square.__class__)
print(f'length = {square.length}')
print(f'area = {square.area()}')
|
a57583e81cabd668d826b7b5c683a643219a7b7f | Rupali-Bajwa/Python | /idle files/even_odd.py | 140 | 4.15625 | 4 | for num in range(2,10):
if num%2==0:
print(num," is even number")
continue
print(num,"is not even number")
|
d72cd3239e8e601ad6c499a48ced1e6491f1b255 | ashokbezawada/Python-Scripts | /Winter break/dynamic_approach_v1.py | 1,995 | 3.75 | 4 | import sys
#The main goal of the function is to print the maximum coins required for given denomination
#The function takes argument as the required number which is x and returns the final list
# def minimum_denom(x):
# coins = [1,3,4]
# y = x + 1
# lst = [sys.maxsize]*y
# lst[0] = 0
# for i in coins:
# lst[i] = 1
# for i in range(y):
# if(i != 0 and i!= 1 and i!=3 and i!=4):
# no_of_coins = sys.maxsize
# for coin in coins:
# if(coin <= i):
# min = i - coin
# y = lst[min] + 1
# if(y < no_of_coins):
# no_of_coins = y
# lst[i] = no_of_coins
# return lst
def minimum_denom_coins(x):
coins = [1,3,4]
y = x + 1
coins_lst = [sys.maxsize]*y
lst = [sys.maxsize]*y
lst[0] = 0
for i in coins:
lst[i] = 1
for i in range(y):
coins_lst[i] = []
if(i == 0):
coins_lst[i].append(0)
if(i == 1):
coins_lst[i].append(1)
if(i == 3):
coins_lst[i].append(3)
if(i == 4):
coins_lst[i].append(4)
for i in range(y):
if(i != 0 and i!= 1 and i!=3 and i!=4):
no_of_coins = sys.maxsize
for coin in coins:
if(coin <= i):
min = i - coin
y = lst[min] + 1
if(y < no_of_coins):
no_of_coins = y
new_min = min
new_coin = coin
lst[i] = no_of_coins
coins_lst[i] = coins_lst[new_min] + coins_lst[new_coin]
return (lst,coins_lst)
#main
x = 17
(final_list,final_coins) = minimum_denom_coins(x)
print(final_list)
print("The minimum coins required for" ,x, "is :" ,final_list[x])
print(final_coins)
print("The minimum denominations required for" ,x, "is :" ,final_coins[x]) |
5f23e7516155716a3bb8ec2a3a1e957b6452f001 | lnk1729/simple-data-structures | /CrackingCodingInterview/Arrays_and_strings/Q2.py | 1,732 | 4 | 4 | def ToString(list):
return ''.join(list)
def ReverseString(text):
return text[::-1]
def GetPosiblePermutations(text, permutationStructure, l, r):
if(l==r):
permutationStructure.append(ToString(text))
else:
for i in range(l, r+1):
text[l],text[i] = text[i],text[l]
GetPosiblePermutations(text, permutationStructure, l+1, r)
text[l],text[i] = text[i],text[l]
def GetPalindromePermutations(text, length):
text = ''.join(text.split())
length = len(text)
countDict = dict()
# Create countDict to filter letter occurences
for i in range(0,length):
key = ord(text[i])
if key in countDict:
countDict[key] += 1
else:
countDict[key] = 1
odd = 0
oddChar = ""
strHalfPal = ""
# Find number of odd characters and last odd character
for key in countDict:
if(countDict[key]%2 != 0):
odd+=1
oddChar = key
# Not a palindrome condition
if(not((length%2 == 0 and odd == 0) or (length%2 == 1 and odd == 1))):
print("Not a palindrome")
# It is a palindrome
else:
# Create half palindrome without odd character
for key in countDict:
if(countDict[key]%2 == 0):
strHalfPal += chr(key)
# Find permutations of one half
palPermutations = list()
GetPosiblePermutations(list(strHalfPal), palPermutations, 0, len(strHalfPal)-1)
# Fix first half + middle letter + last half
for halfpal in palPermutations:
print(halfpal + chr(oddChar) + ReverseString(halfpal))
text = " r ace car "
GetPalindromePermutations(text, len(text)) |
0514215125ba444990b19ef380a1a9e704a6773b | bkuk69/HelloPython | /Ch01/PCH01EX04.py | 272 | 3.578125 | 4 | import turtle
t = turtle.Turtle()
t.shape("turtle")
distanceMeter = 50
gak = 144
t.forward(_distance)
t.left(gak)
t.forward(_distance)
t.right(gak)
t.forward(_distance)
t.right(gak)
t.forward(_distance)
t.up()
t.goto(100,100)
t.down()
t.circle(50)
|
ca0c952769fcc6c56e42c3757837de4068b62e5f | QimanWang/excel-file-comparer | /random_stuff/order_analyzer.py | 1,157 | 3.65625 | 4 | import sys
import pandas as pd
import re
order_data = pd.read_csv(sys.argv[1])
print(order_data.head())
# check state
def validate_state(state):
invalid_states = ['CT', 'ID', 'IL', 'MA', 'NJ', 'OR', 'PA']
if state in invalid_states:
return False
else:
return True
# check zipcode
def validate_zipcode(zipcode):
if len(str(zipcode)) == 5 or len(str(zipcode)) == 9:
if sum(int(digit) for digit in str(zipcode)) <= 20:
return True
else:
return False
else:
return False
# check email
def validate_email(email):
email_format = re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
if email_format.match(email):
return True
else:
return False
# iterate through every row to calculate validity and print
for row in range(0, len(order_data)):
if (validate_state(order_data.loc[row, 'state']) &
validate_zipcode(order_data.loc[row, 'zipcode']) &
validate_email(order_data.loc[row, 'email'])):
print(order_data.loc[row, 'name'], 'valid')
else:
print(order_data.loc[row, 'name'], 'invalid')
|
ceb70306e4a36d3fbceb0b62d6e7cc401c730645 | infinious/intern | /task6.py | 459 | 3.96875 | 4 | #2
def covid(patient_name,body_temperature=98):
print("patien name is",patient_name)
print("body temperature is",body_temperature)
a = input("enter patient name:")
b = input("enter body temperature")
covid(a,b)
#1
def y(c,d):
print("ADDITION=",c+d)
print("SUBTRACTION=",c-d)
print("MULTIPLICATION=",c*d)
print("DIVISON=",c//d)
c = int(input("enter the first number:"))
d = int(input("enter the second number:"))
y(c,d) |
a0d6a6e5f5d4f3bdc2c08dd472b50e74a43e5d7b | misaka-umi/Software-Foundamentals | /01 混杂/04 打印范围内被五整除的数,用逗号隔开.py | 94 | 3.6875 | 4 | for i in range(200,295):
if i%5 == 0 and i%3 != 0 :
print(i,end = ',')
print(295)
|
89af8134c4e1cedba13db3599a826dd417379549 | kielejocain/AM_2015_06_15 | /StudentWork/arielkaplan/Week2-3/positions.py | 3,611 | 3.859375 | 4 | from math import sqrt
data = [[531, 408, 'A'], [225, 52, 'B'], [594, 242, 'C'], [351, 102, 'D'], [371, 15, 'E'], [569, 353, 'F'],
[342, 39, 'G'], [218, 304, 'H'], [428, 260, 'I'], [329, 158, 'J'], [585, 530, 'K'], [71, 114, 'L'],
[587, 88, 'M'], [347, 180, 'N'], [180, 332, 'O'], [250, 522, 'P'], [88, 475, 'Q'], [260, 128, 'R'],
[328, 505, 'S'], [381, 201, 'T'], [360, 192, 'U'], [414, 313, 'V'], [525, 293, 'W'], [240, 563, 'X'],
[117, 546, 'Y'], [507, 127, 'Z']]
letter_dict = {}
for item in data:
letter = item[2]
x = item[0]
y = item[1]
letter_dict[letter] = [x, y]
print letter_dict
square_size = 600
style = """
<style>
#box { background:blue; position:relative; }
#box span { color:silver; position:absolute; }
</style>
"""
# TODO NEAREST "STARBUCKS"
# 1. Define a function that for arbitrary value e.g. "J" find the nearest N items e.g. 5
# a. calculate the distance to each neighbor
# b. sort the list by that distance
# c. return the top N from the sorted list
# 2. Modify the draw code to highlight "top" items
# a. add a style property for color
# b. determine if this item is in the top 5
# c. conditionally set the color bases on if its the top 5
# d. also indicate the selected position e.g. "J" with another color
# OUTPUT html for "J" and 5 would show R D N U and T highlighted.
def distance(current_position, neighbor):
"""takes two lists. returns distance"""
X_COORD = 0
Y_COORD = 1
diff_x = abs(current_position[X_COORD] - neighbor[X_COORD]) # abs() --> make sure # is positive
diff_y = abs(current_position[Y_COORD] - neighbor[Y_COORD])
# distance = pythag(diff_x, diff_y) # options
# distance = math.hypot(diff_x, diff_y) # options
hypot = sqrt((diff_x **2) + (diff_y **2))
return hypot
def all_distances(current_position, data):
neighbor_distances = []
for coord in data:
LETTER_INDEX = 2
distance_from_current = distance(current_position, coord)
# create new tuple with (distance, letter)
neighbor_distances.append((distance_from_current, coord[LETTER_INDEX]))
return neighbor_distances
# print(all_distances([347, 180, 'N'], data))
def nearest_starbucks(current_pos_letter, data, how_many):
LETTER_INDEX = 2
for item in data:
if item[LETTER_INDEX] == current_pos_letter:
current_position = item[:]
break
distances = all_distances(current_position, data)
ordered_by_distance = sorted(distances)
# return closest #, not including self
top_locations = ordered_by_distance[1:how_many + 1]
top = {}
for loc in top_locations:
letter = loc[1]
distance = loc[0]
top[letter] = distance
return top # as dictionary {letter: distance}
# print nearest_starbucks("J", data, 5)
# output to html file
my_location = "J"
top_locations = nearest_starbucks(my_location, data, 5)
print top_locations
f = open("positions.html", "w")
f.write(style)
f.write('<div id="box" style="width:{0}px;height:{0}px;">\n'.format(square_size))
for item in data:
if item[2] in top_locations.keys():
color = "color:white;"
border = "border:1px solid white;"
elif item[2] == my_location:
color = "color:red; background-color:white;"
border = "border:3px solid white;"
else:
color = ""
border = ""
f.write('<span style="left:{x}px; top:{y}px; {c} {b}"> {v} </span>'.format(
x=item[0], y=item[1], v=item[2], c=color, b=border))
f.write("</div>\n")
f.close()
# EXTRA CREDIT: draw a circle |
549fd0196b1236d9d65bdeac4e0ea6cdc9accd47 | landron/Project-Euler | /Python/problems_7_10_nst_prime.py | 5,942 | 3.703125 | 4 | '''
http://projecteuler.net/problem=7
What is the 10 001st prime number?
http://projecteuler.net/problem=10
Problem 10. Sum all primes below N million
Version: 2023.04.14
TODO: hackerrank_10
'''
from datetime import datetime
from math import log
import sys
from time import time
from project_euler.proj_euler import get_primes
HARD_VALIDATE = False
def find_primes_number_count(limit, position=1):
"""find the number of prime numbers below the given limit"""
assert position > 0
primes = get_primes(limit)
if position-1 < len(primes):
return (len(primes), primes[position-1])
return (len(primes), 0)
def find_prime_number2(position):
"""
Purpose
find the nth prime number; version 2, in production
this time we know approximately where to search for
Performance
get_primes_limits(limitInf, limitSup) doesn't work as there are more primes in the interval
[2016-05-01 16:22] Total time: 2.50 seconds / HARD_VALIDATE, both problems
"""
if position < 6:
return find_prime_number1(position)
# Consequence Two: The nth prime is about n (ln n + ln (ln n))
limit_sup = int(position * (log(position)+log(log(position))))
result = find_primes_number_count(limit_sup, position)[1]
assert result != 0
return result
def find_prime_number1(position):
"""
Purpose
find the nth prime number; version 1, deprecated
[2016-05-01 16:21] Total time: 2.98 seconds / HARD_VALIDATE, both problems
"""
limit = 100
prime = 0
while prime == 0:
(_, prime) = find_primes_number_count(limit, position)
limit *= 10
return prime
def find_prime_number(position):
"""the function to find the nth prime number"""
# return find_prime_number1(position)
return find_prime_number2(position)
def find_primes_sum(limit):
"""calculate the sum of all the prime numbers smaller than the given limit"""
primes = get_primes(limit)
# print(primes)
return sum(primes)
def validate_primes_number_count():
"""module's assertions: count primes"""
assert find_primes_number_count(100)[0] == 25
assert find_primes_number_count(1000)[0] == 168
assert find_primes_number_count(10000)[0] == 1229
if HARD_VALIDATE:
assert find_primes_number_count(100000)[0] == 9592
assert find_primes_number_count(1000000)[0] == 78498
assert find_prime_number(3) == 5
assert find_prime_number(6) == 13
assert find_prime_number(15) == 47
assert find_prime_number(16) == 53
assert find_prime_number(20) == 71
assert find_prime_number(25) == 97
assert find_prime_number(168) == 997
def validate_find_primes_sum():
"""module's assertions: primes sum"""
assert find_primes_sum(9) == 17
assert find_primes_sum(10) == 17
assert find_primes_sum(11) == 17
assert find_primes_sum(12) == 28
assert find_primes_sum(29) == 100
assert find_primes_sum(30) == 129
assert find_primes_sum(100) == 1060
assert find_primes_sum(1000) == 76127
assert find_primes_sum(10000) == 5736396
assert find_primes_sum(25000) == 32405717
if HARD_VALIDATE:
assert find_primes_sum(2000000) == 142913828922
def problem_7():
"""
Purpose
solve the problem 7, print the needed time
Performance
0.5 - 0.6 seconds
"""
start = time()
result = find_prime_number(10001)
assert result == 104743
print(f"Problem 7 - result {result:d} in {time()-start:.2f} seconds")
def problem_10():
"""
Purpose
solve the problem 10, print the needed time
Performance
around 1 second, be aware of the validations
"""
start = time()
result = find_primes_sum(2000000)
assert result == 142913828922
print(f"Problem 10 - result {result:d} in {time()-start:.2f} seconds")
def hackerrank_7():
'''
https://www.hackerrank.com/contests/projecteuler/challenges/euler007
Nth prime
'''
limit = 1000
primes = get_primes(limit)
test_cases = int(sys.stdin.readline())
for _ in range(test_cases):
position = int(sys.stdin.readline())
while position > len(primes):
limit *= 2
primes = get_primes(limit)
print(primes[position-1])
def hackerrank_10():
'''
https://www.hackerrank.com/contests/projecteuler/challenges/euler010
sum of the primes below the given limit
timeout: 6,7
wrong results: the rest, except 0 and 4
Idea: keep a list with all the numbers < limit and their calculated sums
'''
limit = 1000
primes = get_primes(limit)
sums = {}
test_cases = int(sys.stdin.readline())
for _ in range(test_cases):
new_limit = int(sys.stdin.readline())
sum_of = 0
last_index = 0
if new_limit > limit:
limit = 1+new_limit
primes = get_primes(limit)
# TODO: wrong result
if 0: # pylint: disable=using-constant-test
for key, val in sums.items():
if last_index < key < new_limit:
last_index = val[0]
sum_of = val[1]
# print(sum_of, last_index)
for i, val in enumerate(primes[last_index:]):
if val > new_limit:
last_index = i
break
sum_of += val
sums[new_limit] = (last_index, sum_of)
print(sum_of)
def main():
"""main"""
start = time()
validate_primes_number_count()
validate_find_primes_sum()
problem_7()
# problem_10()
# for i in range(1,100):
# print(find_prime_number(i))
print(f'[{datetime.now().strftime("%Y-%m-%d %H:%M")}] '
f'Total time: {time()-start:.2f} seconds')
if __name__ == "__main__":
main()
# hackerrank_10()
|
27c34078a9b145fa9d37c467d73f2d2cd7fbd03f | josh-m/HackerRank | /sorting/insertion2.py | 536 | 3.890625 | 4 |
def main():
ar_size = int(raw_input())
ar_str = raw_input().split()
ar = map(int, ar_str)
insertionSort(ar_size,ar)
def print_arr(sz, ar):
for n in ar[:-1]:
print '%i' % n,
print ar[-1]
def insertionSort(sz, ar):
for j in range(1,sz):
v = ar[j]
i = j-1
while v < ar[i] and i>-1:
ar[i+1] = ar[i]
i-=1
ar[i+1] = v
print_arr(sz, ar)
if __name__ == '__main__':
main()
|
9eb6d08afffe8c5680b8931b15a7a499d321236a | SamRoehrich/PythonClass | /mod2/cube.py | 229 | 4.3125 | 4 | # Given the length of one edge of a cube, find the surface area of the cube
length = int(input("Enter the length of the edge: "))
surfaceArea = str(6 * length ** 2)
print("The surface area is " + surfaceArea + " square units.")
|
460a7fd75c23bd50e6b69b24ed3b99bc3b4ae4fe | Rashmi-278/CODE_solvedproblems | /countLeaves.py | 420 | 3.5 | 4 |
#Initial Template for Python 3
class Node:
def __init__(self, val):
self.right = None
self.data = val
self.left = None
def countLeaves(root):
if root is None:
return 0
elif (root.left is None) and (root.right is None):
return 1
else :
return countLeaves(root.left) + countLeaves(root.right)
#Implement driver code on your own
|
562c2a6547057bebbfb68633ae989e15d34b95d7 | DyadushkaArchi/python_hw | /Python_hw_11.py | 427 | 4.25 | 4 | import math
#=======================================================================
#task 11
#=======================================================================
def radian (degree):
result = (degree * math.pi) / 180
return result
angle = 60
result = radian(angle)
print(math.cos(result))
angle = 45
result = radian(angle)
print(math.cos(result))
angle = 40
result = radian(angle)
print(math.cos(result))
|
dd712e5f8685030dd900a03f74209448116636da | diggerdu/VGGish_Genre_Classification | /graphs/models/example.py | 649 | 3.546875 | 4 | """
An example for the model class
"""
import torch.nn as nn
from graphs.weights_initializer import weights_init
class Example(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
# define layers
self.relu = nn.ReLU(inplace=True)
self.conv = nn.Conv2d(in_channels=self.config.input_channels, out_channels=self.config.num_filters, kernel_size=3, stride=1, padding=1, bias=False)
# initialize weights
self.apply(weights_init)
def forward(self, x):
x = self.conv(x)
x = self.relu(x)
out = x.view(x.size(0), -1)
return out
|
637867460378e0676c5742a8874da269a78a0fa8 | dtliao/Starting-Out-With-Python | /chap.5/24 p.231 ex.14.py | 249 | 3.953125 | 4 | def kinetic_energy(m,v):
KE=(1/2)*m*v**2
return KE
m=float(input('Enter the mass(in kilograms):'))
v=float(input('Enter the velocity(in meters per second):'))
x=kinetic_energy(m,v)
print('The kinetic energy is', format(x, ',.0f'), 'joules') |
3d0889f06b71336a55a0c78dd1de9c2ceb4338b8 | alexforcode/leetcode | /200-299/217.py | 1,166 | 3.765625 | 4 | """
Given an integer array nums, return true if any value appears at least twice in the array,
and return false if every element is distinct.
Constraints:
1 <= nums.length <= 10**5
-10**9 <= nums[i] <= 10**9
"""
from typing import List, Set
def contains_duplicate_1(nums: List[int]) -> bool:
# Time: O(n*log(n)) + O(n)
# Space: O(1)
if len(nums) == 1:
return False
nums.sort()
for i in range(len(nums)-1):
if nums[i] == nums[i+1]:
return True
return False
def contains_duplicate_2(nums: List[int]) -> bool:
# Time: O(n)
# Space: O(n)
unique: Set[int] = set(nums)
return len(nums) != len(unique)
if __name__ == '__main__':
assert contains_duplicate_1([1, 2, 3, 1]) is True
assert contains_duplicate_1([1, 2, 3, 4]) is False
assert contains_duplicate_1([1, 1, 1, 3, 3, 4, 3, 2, 4, 2]) is True
assert contains_duplicate_1([1]) is False
assert contains_duplicate_2([1, 2, 3, 1]) is True
assert contains_duplicate_2([1, 2, 3, 4]) is False
assert contains_duplicate_2([1, 1, 1, 3, 3, 4, 3, 2, 4, 2]) is True
assert contains_duplicate_2([1]) is False
|
bad7a302d3278786f579d8a720d99dfc80274ad0 | wjbeshore/100DaysOfPython | /QuizGame/quiz_brain.py | 719 | 3.515625 | 4 | class QuizBrain:
def __init__(self, q_list):
self.questions = q_list
self.q_right = 0
self.q_wrong = 0
self.q_number = 0
def next_question(self):
current_question = self.questions[self.q_number]
print("Q" + str(self.q_number+1) + ": " + current_question.text)
answer = input("True or false?")
if answer == current_question.answer:
print("Correct!")
self.q_right += 1
else:
print("I'm sorry, that's incorrect.")
self.q_wrong += 1
self.q_number += 1
print("You've answered " + str(self.q_right) + " questions correct out of " + str(self.q_number))
self.next_question() |
dacec5e2df5c26cc737ef1f3190cff42b1c9c248 | MmHydra/LearnPython3 | /exercises/younglinux_7.py | 206 | 3.734375 | 4 | n = input("pls enter the degree ")
m = input("pls enter the number ")
n, m = [int(n), int(m)]
b = 0
if n == 0:
b = 1
else:
while n > 0:
if b == 0:
b = m
else:
b = b * m
n = n - 1
print(b)
|
c9a1611336f1403ec14c56e623ec2a22b169ec5c | Amath-SARR/projetPython1 | /projet1/genieCivilOuvrage2D.py | 2,390 | 3.84375 | 4 | """
Module de dessein intitulé genieCivilOuvrage2D.py de plusiers figure
géometrique à l'aide de du module turtle
"""
from turtle import *
from math import *
# Programme d'implémentation pour dessiner du carré
def carre(taille):
for i in range(4):
forward(taille)
left(90)
# Programme d'implémentation pour dessiner un cercle
def cercle(taille,couleur):
fillcolor(couleur)
begin_fill()
circle(taille)
left(90)
end_fill()
# Programme d'implémentation pour dessiner un demiCercle
def demiCercle(taille,couleur):
fillcolor(couleur)
begin_fill()
left(90)
circle(taille,180)
end_fill()
# Programme d'implémentation pour dessiner un triangle quelconque
# Selon le théorie de Al khasi
def triangle(a, b, c, couleur):
fillcolor(couleur)
begin_fill()
vare = degrees(acos(((b**2)+(c**2) - (a**2))/(2*c*b)))
forward(c)
left(180-vare)
forward(b)
vare = degrees(acos(((a**2)+(b**2) - (c**2))/(2*a*b)))
left(180-vare)
forward(a)
end_fill()
# Programme d'implémentation pour tester les fonctions
def trapeze(grandBase,h1,petitBase,h2,couleur):
fillcolor(couleur)
begin_fill()
forward(grandBase)
right(120)
forward(h1)
right(60)
forward(petitBase)
right(60)
forward(h2)
end_fill()
# Programme d'implémentation pour dessiner un rectangle
def rectangle(long, larg, couleur):
fillcolor(couleur)
begin_fill()
for i in range(2):
forward(long)
left(90)
forward(larg)
left(90)
end_fill()
# Programme d'implémentation pour dessiner un polygone
def polygone(nombreCote, couleur):
for i in range(nombreCote):
fillcolor(couleur)
forward(100)
left(360/nombreCote)
end_fill()
# Programme d'implémentation pour dessiner un losange
def losange(couleur):
fillcolor(couleur)
for i in range(4):
forward(100)
left(180/4)
end_fill()
# Programme d'implémentation pour dessiner un ellipse
def ellipse(taille,couleur):
fillcolor(couleur)
begin_fill()
for i in range(2):
circle(taille,90)
circle(taille//2,90)
seth(-45)
end_fill()
|
ae7afbecbee82a896d0d5f7355f1f6371e455175 | saipoojavr/saipoojacodekata | /lowerupper.py | 187 | 4.21875 | 4 | astr=str(input())
for iter in range(0,len(astr)):
if(astr[iter].islower()==True):
print(astr[iter].upper(),end="")
elif(astr[iter].isupper()==True):
print(astr[iter].lower(),end="") |
9a959f65d5a62111f93e9080dcd8815cb052ae27 | 2226171237/Algorithmpractice | /Tencent/easy/多数元素_S.py | 966 | 3.921875 | 4 | '''
给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [3,2,3]
输出: 3
示例 2:
输入: [2,2,1,1,1,2,2]
输出: 2
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/majority-element
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution(object):
def majorityElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
m=0
res=nums[0]
for x in nums:
if 0==m:
m+=1
res=x
elif x==res:
m+=1
elif x!=res:
m-=1
return res
if __name__ == '__main__':
s=Solution()
print(s.majorityElement([2,2,1,1,2,2,1])) |
cabc2bddfde4a33c10ba9753716b17dfbe53b955 | tobynboudreaux/machine-learning-regression-practice | /mlinear_regression.py | 1,218 | 3.578125 | 4 | # Data Preprocessing Template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('../Machine Learning A-Z (Codes and Datasets)/Part 2 - Regression/Section 5 - Multiple Linear Regression/Python/50_Startups.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
# Encode catagorical data
# Encode Independant Var
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder
ct = ColumnTransformer(transformers=[('encoder', OneHotEncoder(), [3])], remainder='passthrough')
X = np.array(ct.fit_transform(X))
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
# Train Multiple Linear Regression (MLR) model on Training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# Predict the Test set results
y_pred = regressor.predict(X_test)
np.set_printoptions(precision=2)
print(np.concatenate((y_pred.reshape(len(y_pred), 1), y_test.reshape(len(y_test), 1)), 1))
|
9d12fbd790ad9ea872a2b77746529d062c3f4e36 | Sharuk06/Python | /Loops/Fibonacci.py | 241 | 4.09375 | 4 | #SOURCE CODE TO IMPLEMENT FIBONACCI SERIES Python V3
#Declaring list to store fibonacci series
list = [0,1]
#Using for loop to iterate
for i in xrange(2,10):
a = list[i-1] + list[i-2]
list.append(a)
#Printing the result
print list
|
44ecc9744cfb1d335e755deec99df03d4d0bd4a9 | TestowanieAutomatyczneUG/laboratorium-5-bozimkiewicz | /src/tests_zad03.py | 4,077 | 3.65625 | 4 | import unittest
from zad03 import Song
class SongTest(unittest.TestCase):
def setUp(self):
self.temp = Song()
def test_print_one_line(self):
self.assertEqual(self.temp.one_line(1), 'On the first day of Christmas my true love gave to me: a Partridge in a Pear Tree.')
def test_print_section(self):
self.assertEqual(self.temp.section(1, 3), ['On the first day of Christmas my true love gave to me: a Partridge in a Pear Tree.', 'On the second day of Christmas my true love gave to me: two Turtle Doves, and a Partridge in a Pear Tree.', 'On the third day of Christmas my true love gave to me: three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.'])
def test_print_whole_song(self):
self.assertEqual(self.temp.whole_song(), ['On the first day of Christmas my true love gave to me: a Partridge in a Pear Tree.',
'On the second day of Christmas my true love gave to me: two Turtle Doves, and a Partridge in a Pear Tree.',
'On the third day of Christmas my true love gave to me: three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.',
'On the fourth day of Christmas my true love gave to me: four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.',
'On the fifth day of Christmas my true love gave to me: five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.',
'On the sixth day of Christmas my true love gave to me: six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.',
'On the seventh day of Christmas my true love gave to me: seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.',
'On the eighth day of Christmas my true love gave to me: eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.',
'On the ninth day of Christmas my true love gave to me: nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.',
'On the tenth day of Christmas my true love gave to me: ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.',
'On the eleventh day of Christmas my true love gave to me: eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.',
'On the twelfth day of Christmas my true love gave to me: twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree.'])
def test_disallow_number_of_verse_negative(self):
with self.assertRaises(ValueError):
self.temp.one_line(-1)
def test_disallow_bigger_number_of_verse(self):
with self.assertRaises(ValueError):
self.temp.one_line(15)
def test_disallow_bigger_second_number_of_verse(self):
with self.assertRaises(ValueError):
self.temp.section(1, 15)
def test_disallow_first_verse_bigger_than_second(self):
with self.assertRaises(ValueError):
self.temp.section(3, 1)
def tearDown(self):
self.temp = None
if __name__ == '__main__':
unittest.main()
|
8664f4ed135aa0ee1990669f86b588e535101922 | afsanehshu/tamrin | /practice +/key/2.py | 294 | 3.96875 | 4 | List = []
for i in range(5):
num = float(input("Enter float Num : "))
List.append(num)
print()
List.sort()
L = List[::-1]
print("sort List : ",L)
print()
print("mid : ",sum(L)/5)
Max=L[0]
Min=L[4]
print("max : ",Max)
print("min : ",Min)
print()
print("List : ",tuple(L))
|
6e3c9048da04bba89650b76a03a9a7e98fe94055 | SybelBlue/SybelBlue | /main/GraphMaker.py | 2,736 | 3.609375 | 4 | def read_file(file):
with open(file, 'r') as text:
print(file + " loaded...")
return [x.replace('\n', '').split(' ') for x in text.readlines()]
def parse_file(lines):
for line in lines:
parse_cmd(line)
def add_node(node):
if node not in graph[0]:
graph[0] += node
def add_undirected(edge):
add_edge(edge)
add_edge(edge[::-1])
def add_edge(edge):
[add_node(item) for item in edge]
if edge not in graph[1]:
graph[1] += [edge]
def remove_node(node):
graph[0] -= node
def remove_edge(edge):
graph[1] -= edge
graph = [[], []]
def neighbors(start):
return [x[1] for x in graph[1] if x[0] == start]
def find_cycle():
path = set()
path_list = []
def visit(vertex):
path.add(vertex)
for neighbour in neighbors(vertex):
if neighbour in path or visit(neighbour):
if path not in path_list:
return True
path.remove(vertex)
return False
while any(visit(v) for v in graph[0]):
path_list += [path]
path = set()
return not not len(path_list), path_list
def in_degree(node):
return len([x for x in graph[1] if x[1] == node])
def out_degree(node):
return len([x for x in graph[1] if x[0] == node])
def degree_map():
return {node: (in_degree(node), out_degree(node)) for node in graph[0]}
def check():
if len(graph[0]) > 0:
print(find_cycle())
print(degree_map())
def parse_cmd(cmd):
i = 0
while i < len(cmd):
# block, args = None, None
if cmd[i] == "load":
i += 1
lines = read_file(cmd[i])
parse_file(lines)
elif cmd[i] == 'node':
i += 1
add_node(cmd[i])
elif cmd[i] == '->':
i += 1
add_edge((cmd[i - 2], cmd[i]))
elif cmd[i] == '<-':
i += 1
add_edge((cmd[i], cmd[i - 2]))
elif cmd[i] == '<->':
i += 1
add_undirected((cmd[i - 2], cmd[i]))
elif cmd[i] == 'edge':
directed = 'directed' in cmd
if directed:
if cmd.index('directed') < i:
i -= 1
cmd.remove('directed')
i += 2
edge = (cmd[i - 1], cmd[i])
if directed:
add_edge(edge)
else:
add_undirected(edge)
elif cmd[i] == 'check':
check()
i += 1
if __name__ == '__main__':
# parse_file(read_file('temp.txt')); print(graph)
cmd = input("> ").split()
while "stop" not in cmd:
parse_cmd(cmd)
print(graph)
cmd = input("> ").split(' ') |
a7a39f9656f708a0fbe7013f4a6e26ee9da8fadc | PriyankaGawali/Python | /Basic/Dictionary/count_conse_char_in_dict.py | 630 | 4.03125 | 4 | # WAP to count how many times a character is consecutive
# input - aabbcccddab
# output - {a:3, b:3, c:3, d:2 }
def generate_dict_of_count(input_str):
ans_dict = {}
i = 0
while i < len(input_str):
count = 0
char_to_check = input_str[i]
for ch in input_str:
if ch == input_str[i]:
count += 1
ans_dict[char_to_check] = count
i = i + 1
return ans_dict
def main():
input_str = input("Enter string : ")
ans_dict = generate_dict_of_count(input_str)
print(ans_dict)
if __name__ == '__main__':
main()
|
a16ab78e3a453d0daac2c1e9cc8095da283aff44 | adithyalingisetty/Sudoku-in-pytthon | /sudoku.py | 2,761 | 3.59375 | 4 | from tkinter import *
from functools import partial
l=[]
#--------------------------Solve Button Module-----------------------------------------
def s1(l1):
k=[]
for i in l1:
k+=i
for i in range(81):
l[i].set(k[i])
return
#---------------------------------------------------------------------------------------
def possible(y,x,n,l1):
for i in range(9):
if l1[i][x]==str(n):
return False
for i in range(9):
if l1[y][i]==str(n):
return False
x1=(x//3)*3
y1=(y//3)*3
for i in range(3):
for j in range(3):
if l1[y1+i][x1+j] == str(n):
return False
return True
#----------------------------------------------------------------------------------------
def solve(l1):
for i in range(9):
for j in range(9):
if l1[i][j] == '':
for n in range(1,10):
if possible(i,j,n,l1):
l1[i][j]=str(n)
solve(l1)
l1[i][j]=''
return
#print(l1)
s1(l1)
#-----------------------------------------------------------------------------------------
def read():
l1=[]
for i in range(9):
l1.append([l[j].get() for j in range(9*i,(9*i)+9)])
solve(l1)
#-----------------------------Reset Button Module-----------------------------------------
def rem():
for i in range(81):
l[i].set('')
#------------------------------------------------------------------------------------------
c1=partial(read)
c2=partial(rem)
c=Tk()
c.geometry('500x500')
c.title('SUDOKU SOLVER')
c.configure(background="SteelBlue1")
w=Canvas(c)
#------------------------------- Label declaration-------------------------------------------
s= Label(c,text='Sudoku Solving',bg='SteelBlue1',font=('times new roman',30,'bold'))
s.pack(side=TOP)
a="""Note: Fill given numbers at exact positions"""
s= Label(c,text=a,bg='SteelBlue1',font=('times new roman',13,'bold'))
s.pack(side=BOTTOM)
#------------------------------ Entry declaration---------------------------------------------
for i in range(81):
l.append(StringVar())
p=1
q=1
for i in range(1,82):
e1=Entry(c,width=8,font=('calibre',13,'normal'),justify=CENTER,textvariable=l[i-1]).place(x=35+(40*p),y=30+(q*40),height=32,width=32)
q+=1
if(q%10==0):
p+=1
q=1
for i in range(81):
l[i].set('')
#----------------------------- Button declaration---------------------------------------------
b1= Button(c,width=13,text='Solve',command=c1,font=('',10,'bold'),cursor='hand2')
b1.place(x=150,y=440,height=30,width=50)
b2= Button(c,width=13,text='Reset',command=c2,font=('',10,'bold'),cursor='hand2')
b2.place(x=250,y=440,height=30,width=50)
c.mainloop()
|
8b09384ff0d003eeb50fe9a3d12e96ca4eebf81e | PressureandTime/Sorting | /src/iterative_sorting/iterative_sorting.py | 971 | 4.03125 | 4 | # TO-DO: Complete the selection_sort() function below
def selection_sort(arr):
indexing_length = range(0, len(arr) - 1)
for i in indexing_length:
min_value = i
for j in range(i + 1, len(arr)):
if arr[j] < arr[min_value]:
min_value = j
if min_value != i:
arr[min_value], arr[i] = arr[i], arr[min_value]
return arr
print(selection_sort([5, 43, 456, 1, 6, 6757, 32, 87, 98]))
# TO-DO: implement the Bubble Sort function below
def bubble_sort(arr):
indexing_length = len(arr) - 1
sorted = False
while not sorted:
sorted = True
for i in range(0, indexing_length):
if arr[i] > arr[i + 1]:
sorted = False
arr[i], arr[i + 1] = arr[i + 1], arr[i]
return arr
print(bubble_sort([4, 6, 8, 7, 24, 54, 87, 98, 5, 3]))
# STRETCH: implement the Count Sort function below
def count_sort(arr, maximum=-1):
return arr
|
dc6f6ed8cfb3462e572f0b09ee46f23bbd8bd8f3 | Meengkko/bigdata_python2019 | /01_jump_to_python/Final_practice/q10.py | 362 | 3.6875 | 4 | class Calculator:
def __init__(self, input_list):
self.num_list = input_list
def sum(self):
return sum(self.num_list)
def avg(self):
return sum(self.num_list)/len(self.num_list)
cal1 = Calculator([1, 2, 3, 4, 5])
print(cal1.sum())
print(cal1.avg())
cal2 = Calculator([6, 7, 8, 9, 10])
print(cal2.sum())
print(cal2.avg())
|
ee4bd7d8f090a8d27039ef02e6e5064ef07651a3 | Mansurjon1112/CASE-Tanlash-operatoriga-oid-masalalar | /12-dan_20-gacha.py | 4,921 | 3.640625 | 4 | #12
'''
n=int(input('1-Radius, 2-Diametr , 3-Uzunligi , 4-Yuzasi'))
x=float(input('Qiymatini kiriting: '))
if n == 1 :
d=2*x
c=2*3.14*x
s=3.14*x*x
print('D=',d,'C=',c,'S=',s)
elif n==2:
r=x/2
c=6.28*r
s=3.14*r*r
print('R=',r,'C=',c,'S=',s)
elif n==3:
r=x/6.28
d=2*r
s=3.14*r*r
print(r,d,s)
elif n==4:
r=(x/3.14)**0.5
d=2*r
c=6.28*r
print(r,d,c)
'''
#13-14 Mustaqil ish
#15
'''
n=int(input('1 dan 4 gacha son kiriting: '))
k=int(input('6 dan 14 gacha son kiriting: '))
if 1<=n<=4 and 6<=k<=14:
if k==6:
natija = 'olti '
elif k==7 :
natija = 'yetti '
elif k==8 :
natija = 'sakkiz '
elif k==9 :
natija = 'to`qqiz '
elif k==10:
natija = 'o`n '
elif k==11:
natija = 'valet '
elif k==12:
natija = 'dama '
elif k==13:
natija = 'qirol '
else:
natija = 'tuz'
if n==1:
natija += 'g`isht'
elif n== 2:
natija += 'olma'
elif n== 3:
natija += 'chillak'
else:
natija += 'qarg\'a'
print(natija)
else:
print("Masala shartiga mos son kiriting!")
'''
#16
'''
n=int(input('20 - 69 oraliq'))
if 20<=n<=69:
unlar = n//10
birlar = n%10
if unlar == 2 :
nat = 'yigirma '
elif unlar == 3:
nat = "o'ttiz "
elif unlar == 4:
nat = "qirq "
elif unlar == 5:
nat = 'ellik '
else:
nat = "oltmish"
if birlar == 1:
nat = nat + 'bir '
elif birlar == 2:
nat = nat + 'ikki '
elif birlar == 3:
nat = nat + 'uch '
elif birlar == 4:
nat = nat + "to'rt "
#..... Davomi bor ..... 9 gacha tekshirish kerak
nat += 'yosh'
print(nat)
else:
print("Masala shartiga mos son kiriting!")
'''
#17-18 Mustaqil ish
#19
'''
yil = int(input('Yilni kiriting: '))
muchal = yil % 12
rang = yil % 60
if 4<=rang<=15:
nat = 'yashil '
elif 16<=rang <=27 :
nat = 'qizil '
elif 28<=rang <=39 :
nat = 'sariq '
elif 40<=rang <=51 :
nat = 'oq '
else:
nat = 'qora '
if muchal == 4 :
nat += 'sichqon '
elif muchal == 5 :
nat += 'sigir '
elif muchal == 6 :
nat += "yo'lbars "
elif muchal == 7 :
nat += "quyon "
elif muchal == 8 :
nat += "ajdar "
elif muchal == 9 :
nat += "ilon "
elif muchal == 10 :
nat += "ot "
elif muchal == 11 :
nat += "qo'y "
elif muchal == 0 :
nat += "maymun "
elif muchal == 1 :
nat += "tovuq "
elif muchal == 2 :
nat += "it "
elif muchal == 3 :
nat += "to'ng'iz "
nat += 'yil'
print(nat)
'''
#20
'''
d=int(input('d='))
m=int(input('m='))
if m == 1:
if 1<=d<=19:
print('Echki')
elif 20<=d<=31:
print("qovg'a")
elif m == 2:
if 1<=d<=18:
print("qovg'a")
elif 19<=d<=29:
print('Baliq')
elif m == 3:
if 1<=d<=20:
print("Baliq")
elif 21<=d<=31:
print("Qo'y")
elif m == 4:
if 1<=d<=19:
print("Qo'y")
elif 20<=d<=30:
print("Buzoq")
elif m == 5:
if 1<=d<=20:
print("Buzoq")
elif 21<=d<=31:
print("Egizaklar")
elif m == 6:
if 1<=d<=21:
print("Egizaklar")
elif 22<=d<=30:
print("Qisqichbaqa")
elif m == 7:
if 1<=d<=22:
print("Qisqichbaqa")
elif 23<=d<=31:
print("Arslon")
elif m == 8:
if 1<=d<=22:
print("Arslon")
elif 23<=d<=31:
print("Parizod")
elif m == 9:
if 1<=d<=22:
print("Parizod")
elif 23<=d<=30:
print("Tarozi")
elif m == 10:
if 1<=d<=22:
print("Tarozi")
elif 23<=d<=31:
print("Chayon")
elif m == 11:
if 1<=d<=22:
print("Chayon")
elif 23<=d<=30:
print("O'q otar")
elif m == 12:
if 1<=d<=21:
print("O'q otar")
elif 22<=d<=31:
print("Echki")
# 2-usul
nat = m*100 + d
if 120<= nat <= 218:
print("qovg'a")
elif 219<= nat <=320:
print('Baliq')
elif 321<= nat <=419:
print('Qo\'y')
elif 420<= nat <=520:
print("Buzoq")
elif 521<= nat <=621:
print("Egizaklar")
elif 622<= nat <=722:
print("Qisqichbaqa")
elif 723<= nat <=822:
print("Arslon")
elif 823<= nat <=922:
print("Parizod")
elif 923<= nat <=1022:
print("Tarozi")
elif 1023<= nat <=1122:
print("Chayon")
elif 1123<= nat <=1221:
print("O'qotar")
elif 1221<= nat <=1231 or (101<=nat<=119):
print("Echki")
'''
|
27852a6bfa0b0387c25168490f20657a4a12f560 | AncientTree/for_simulation | /test.py | 1,919 | 3.71875 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2018-04-10 16:21
# @Author : PengZhw
# @FileName: test.py
# @Software: PyCharm
import math
class Point:
def __init__(self, x, z, y):
self.x = x
self.z = z
self.y = y
self.coordinate = [x, z, y]
class Flat: # 认为平面一定平行于XOZ平面
def __init__(self, p1, p2, p3, p4):
"""
四个点必须按相邻顺序传入
"""
self.y = (p1.y + p2.y + p3.y + p4.y) / 4 # y坐标的平均值作为平板的y
self.p1, self.p2, self.p3, self.p4 = p1, p2, p3, p4
self.p1.y, self.p2.y, self.p3.y, self.p4.y = self.y, self.y, self.y, self.y
def if_cover(self, p):
# 用余弦定理判断给定点的投影是否在平板内
def angle(p_a, p_b, p_c):
a = math.sqrt((p_b.x - p_c.x) ** 2 + (p_b.y - p_c.y) ** 2)
b = math.sqrt((p_c.x - p_a.x) ** 2 + (p_c.y - p_a.y) ** 2)
c = math.sqrt((p_b.x - p_a.x) ** 2 + (p_b.y - p_a.y) ** 2)
alpha = math.acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c))
return alpha
pass
def angle(p_a, p_b, p_c):
a = math.sqrt((p_b.x - p_c.x) ** 2 + (p_b.z - p_c.z) ** 2)
b = math.sqrt((p_c.x - p_a.x) ** 2 + (p_c.z - p_a.z) ** 2)
c = math.sqrt((p_b.x - p_a.x) ** 2 + (p_b.z - p_a.z) ** 2)
print(a, b, c)
alpha = math.acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c))
return alpha
p1 = Point(0, 0, 0)
p2 = Point(3, 0, 0)
p3 = Point(3, 2, 0)
p4 = Point(0, 2, 0)
p = Point(2, 1, 0)
bete = angle(p, p1, p2) + angle(p, p2, p3) + angle(p, p3, p4) + angle(p, p4, p1)
if round(bete, 5) == round(math.pi*2, 5):
print(round(bete, 5), round(math.pi*2, 5), "点的投影在平板范围内。")
else:
print(round(bete, 5), round(math.pi*2, 5), "点的投影不在平板范围内。")
for name in ['bob', 'sue', 'joe']:
print(name, n)
|
694ed9bb9602ebcff0f74fda442c326cd0a2eac9 | IANHUANGGG/Santonrini | /santorini/player/tree_strat.py | 4,984 | 3.78125 | 4 | """A game tree-based strategy to be used with a Player component in Santorini."""
import copy
from itertools import product
from santorini.player.strategy import TurnStrategy
from santorini.common.direction import Direction
from santorini.common.rulechecker import RuleChecker
class TreeStrategy(TurnStrategy):
"""A strategy implementation that uses a game tree to ensure that
the opponent cannot make a winning move given a depth to look-ahead
in the tree
"""
def __init__(self, depth=2):
"""Constructs a Game-tree turn strategy object with the
look-ahead depth
:param int depth: the amount of turns to lookahead (defaults to 2)
"""
self.depth = depth
@staticmethod
def next_turn(workers, board):
"""Creates a generator that yields the next possible
turn given a list of workers and board
:param list Worker workers: A list of workers belonging
to the same player
:param Board board: A game board
:rtype Generator[(Worker, Direction, Direction), None None]
"""
for worker in workers:
for move_dir, build_dir in product(Direction, Direction):
if (RuleChecker().can_move_build(board, worker.player, worker,
move_dir, build_dir)):
yield (worker, move_dir, build_dir)
@staticmethod
def do_survive(board, depth, from_op, player, opponent,
worker, move_dir, build_dir=None):
"""Given a game state, and a look-ahead depth and an
optional turn, return whether or not the given player name
survives up to the depth number of rounds.
:param Board board: A game board
:param str pname: A player name
:param int depth: the number of look-ahead rounds
:param Worker worker: an optional worker to move and/or build
:param Direction move_dir: The direction to move the given
worker if a worker was given
:param Dircetion build_dir: An optional direction the worker builds in
:param from_op: If this method is called from opponent' worker
:rtype bool: if we survived depth number of rounds
"""
if depth == 0:
return True
if TreeStrategy.perform_move_build(board, worker, move_dir, build_dir) == False:
return False
next_workers = TreeStrategy.set_workers(board, from_op, player, opponent)
next_turns = TreeStrategy.next_turn(next_workers, board)
depth = depth - 1
if depth == 0:
return True
for next_worker, next_move, next_build in next_turns:
if next_worker == None:
return False
board_copy = copy.deepcopy(board)
if from_op:
if TreeStrategy.do_survive(board_copy, depth, False, player, opponent,
next_worker, next_move, next_build):
return True
else:
if not TreeStrategy.do_survive(board_copy, depth, True, player, opponent,
next_worker, next_move, next_build):
return False
return not from_op
@staticmethod
def set_workers(board, from_op, player, opponent):
if from_op:
return [w for w in board.workers if opponent != w.player]
else:
return [w for w in board.workers if player != w.player]
@staticmethod
def perform_move_build(board, worker, move_dir, build_dir):
board.move_worker(worker, move_dir)
if RuleChecker().get_winner(board):
return False
board.build_floor(worker, build_dir)
return True
def get_turn(self, workers, board, player_id):
"""Return a valid turn for the list of player's worker on the board.
A valid turn is one of:
(None, None, None) - A no request if it couldn't find any move
(Worker, Direction, None) - Move request
(Worker, Direction, Direction). - Move+Build request
:param list Worker workers: A list of a player's worker
:param Board board: a game board
:rtype Union[str(Player_id), (Worker, Direction, None),
(Worker, Direction, Direction)]:
a valid turn as described above
"""
opponent = ''.join([x for x in board.players if x != player_id])
turn = player_id
for worker, move_dir, build_dir in TreeStrategy.next_turn(workers, board):
boadr_copy = copy.deepcopy(board)
if TreeStrategy.do_survive(boadr_copy, self.depth, False,
player_id, opponent,
worker, move_dir, build_dir):
turn = (worker, move_dir, build_dir)
break
return turn
|
0478654286b215902c229292037fa746bf668f17 | enygma/text-etp-s04e03 | /items/card_table.py | 1,557 | 3.5625 | 4 | from detail_item import *
import inventory
class Card_Table(Detail_Item):
def __init__(self, name, aliases):
Detail_Item.__init__(self, name, aliases)
self.takeable = False
self.fingerprints_found = False
self.description = """
Cards are set about the surface of the table as if midway through a game
whose rules you can't quite identify. Some cards are in stacks in the middle, others face
up or face down in front of the players' places. You don't see any markings or distinct
patterns in what cards are where, but they all seem to be part of a single, standard deck."""
def look(self):
# check their inventory for both the power and brush
if "powder" in inventory.inv and "brush" in inventory.inv:
print("""You grab a handful of the white powdery ash from the fireplace and scatter
it over the playing cards. Then you take your little brush and start dusting. And... fingerprints
start to become visible. Any given card only has one set of prints on it, but there are loads
of different prints on all the cards together.""")
if not "rifle":
print("You try to think of other places around you where you could also find fingerprints")
else:
print("""
You re-examine the rifle, using the powder and brush on it and find additional fingerprints.
You compare the prints you found there to the cards. The exact same fingerprints are on four of
the cards: the 7 of hearts, 2 of diamonds, 9 of clubs and 3 of spades.""") |
199d7ff9db373454ccbe5f6db2fc1755dfeca0ab | visw2290/Scripts-Practice | /Scripts-Pyc/falsey.py | 130 | 3.75 | 4 | print('Enter your age')
age = input()
if age:
print('You have entered your age')
else:
print('Dont cheat. Enter your age') |
2f17a65605755f9885df7bfbb141ff0f6cda40c8 | MatthewStuhr/Phrase-Hunters--Project-3 | /phrasehunter/character.py | 1,431 | 3.953125 | 4 | class Character:
"Defualting was_guessed to False as the character has not been guess before"
def __init__(self, original, was_guessed=False):
self.original = original
self.was_guessed = was_guessed
if len(original) != 1:
raise ValueError("Please enter 1 letter at a time.")
def new_guess(self, guess):
""" An instance method that will take a single string character guess as an argument when its
called. The job of this instance method is to update the instance attribute storing the boolean
value, if the guess character is an exact match to the instance attribute storing the original
char passed in when the Character object was created. """
if self.guess.upper() == self.original.upper():
self.was_guessed = True
def given_single_character(self):
character = '{}'
""" An instance method that when called, will show the original character if the instance
attribute was_guessed is True. Otherwise, the instance method should show an _ or underscore
character to act as a hidden placeholder character. """
if self.was_guessed == True:
return character.format(self.original)
elif self.original == ' ':
return character.format(' ')
else:
return character.format('_')
|
2a9beeb3d24d460fa6f21142e1ed24e29ade02a9 | pmisteliac/mmsr_repo_sim | /src/CorpusBuilder.py | 802 | 3.640625 | 4 | from gensim import corpora
from typing import List, Dict, Tuple
# Create a corpus for all termlists (source code features) and return a dictionary with all actual terms and a list of bags of words
# For input use a prepocessed list of term lists representing an entire repository
def buildCorpus(featureLists: List[List[str]]) -> Tuple[Dict[int, str], List[Tuple[int, int]]]:
# use this dictionary to lookup words based on their key in the bag of words
dictionary = corpora.Dictionary(featureLists)
# create a bag of words for each list of terms, a bag of words contains the amount of how often a term appears per document and a key for the actual term in the dictionary
bagsOfWords = [dictionary.doc2bow(features) for features in featureLists]
return (dictionary, bagsOfWords)
|
0078e8596a65b30ec0500d5b5300b0506ecd9950 | jvelez/source-allies-coding-challenge | /word_counter.py | 4,142 | 4.0625 | 4 |
import string
import operator
#_READ_STOP_WORD_FILE_=============================================================================#
# Read a given stop-word textfile and return a string array with the stop-words.
#==================================================================================================#
def Get_Stop_Word_List(file_name):
file = open(file_name,encoding='utf-8') #open the given file
words = file.read().lower().split("#")[-1].split() #split the file into an array of strings
file.close(); #close the file
return list(set(words)) #remove duplicate elements and return list
#==================================================================================================#
#_READ_BOOK_FILE_==================================================================================#
# Read a given book textfile and return a string array with the all words in the book.
# This excludes the header and footer sengments of the file. It will only work for text files
# with the following format [header *** header2 *** content *** footer... ].
# edit:
# lines = lines.translate(str.maketrans('', '', string.punctuation+"—“”")) works but is best to
# just exclude everything exept letters to avoid encountering any special case.
#==================================================================================================#
def Get_Book_Word_List(file_name):
file = open(file_name,encoding='utf-8') #open the given file
lines = file.read().split('***')[2].lower() # get element [2] the content of the book
#remove punctuation marks
lines2 = ""
for i in lines:
#Only include letters and if anything is not a letter replace it with whitespace.
#Remove "-’" to prevent hyphenated compound words, and abreviated words.
#Add +"0123456789" to include words like 1st, dates, years, or chapter numbers.
if i in "abcdefghijklmnopqrstuvwxyz’-":
lines2+=i
else:
lines2+=" "
lines2 = lines2.split() #split into an array of strings and return list
file.close(); #close the file
return [word for word in lines2 if word != "’"] #remove lone "’" elements and return the list
#==================================================================================================#
#_REMOVE_STOP_WORDS_===============================================================================#
# Given a content word list and a stop word list, remove the stop words from the content list.
#==================================================================================================#
def Remove_Stop_Words(content, stop_words):
words = [w for w in content if w not in stop_words] #create a new list without the stop-words
return words # return word list
#==================================================================================================#
#_PERFORM_WORD_COUNT===============================================================================#
# Given a content word list, counts the ocurrences of each word and returns list of tupples
# that contain (word, number_of_ocurrences), and is sorted by the number_of_ocurrences.
#==================================================================================================#
def Perform_Word_Count(content):
ocurrences = {}
for word in content:
if word not in ocurrences: #if this is a new key in the dict
ocurrences[word]=1 #set its value to 1
else:
ocurrences[word]+=1 #otherwise add 1 to the counter
return sorted(ocurrences.items(), key=operator.itemgetter(1), reverse=True) #turn dict into sorted list and return
#==================================================================================================#
#Load the stop-words and book files
stop_words = Get_Stop_Word_List("stop-words.txt")
book = Get_Book_Word_List("mobydick.txt")
#Test the function, create a book without stop-words
book2 = Remove_Stop_Words(book,stop_words)
#visual indication for information output
print("START TEST")
#Test the word count function
word_count = Perform_Word_Count(book2)
#Print the results
for pair in word_count:
print(pair[0], pair[1])
#visual indication for end of output
print("END TEST") |
d76d758d1d74d87d177d36a6055d39cf35255951 | UnderGrounder96/mastering-python | /07. Functions/3.kwargs.py | 830 | 4.28125 | 4 | # **kwargs (keywords arguments)
# It builds a Dictionary of key value pairs.
# EXAMPLE1
def myfunc(**kwargs):
if 'fruit' in kwargs:
print('My fruit of choice is {}'.format(kwargs['fruit']))
else:
print('I did not find any fruit here')
myfunc(fruit='apple')
myfunc(fruit='mongo', veggie="lettuce")
# EXAMPLE 2
# a) It returns a Dictionary
def myfunc(**kwargs):
if 'fruit' in kwargs:
print(kwargs)
myfunc(fruit='apple', veggie="lettuce")
# b)
def myfunc(*args, **kwargs):
print('I would like {}{}'.format(args[0],kwargs['fruit']))
print(args)
print(kwargs)
myfunc(10,20,30,fruit='orange', food="eggs", animal="dog")
# *args (arguments) and **kwargs (keywords arguments)
# EXAMPLE 3
def save_user(**user):
print(user)
print(user["id"])
print(user["name"])
save_user(id=1, name="John", age=22) |
1d3a36afd805a6c5b19ee3fb4323202ea952c11a | whereistanya/aoc | /2020/7.py | 2,582 | 3.6875 | 4 | #!/usr/bin/env python
# Day 7
class Bag(object):
def __init__(self, name):
self.name = name
self.contains = {} # {str: count} # TODO: change to Bag?
def __repr__(self):
return "Bag(%s -> %s)" % (self.name, self.contains.keys())
inputfile = "input7.txt"
lines = [
"light red bags contain 1 bright white bag, 2 muted yellow bags",
"dark orange bags contain 3 bright white bags, 4 muted yellow bags",
"bright white bags contain 1 shiny gold bag",
"muted yellow bags contain 2 shiny gold bags, 9 faded blue bags",
"shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags",
"dark olive bags contain 3 faded blue bags, 4 dotted black bags",
"vibrant plum bags contain 5 faded blue bags, 6 dotted black bags",
"faded blue bags contain no other bags",
"dotted black bags contain no other bags",
]
lines = [
"shiny gold bags contain 2 dark red bags",
"dark red bags contain 2 dark orange bags",
"dark orange bags contain 2 dark yellow bags",
"dark yellow bags contain 2 dark green bags",
"dark green bags contain 2 dark blue bags",
"dark blue bags contain 2 dark violet bags",
"dark violet bags contain no other bags",
]
with open(inputfile, "r") as f:
lines = [x.strip().strip(".") for x in f.readlines()]
bags = {} # {str: Bag, ...}
for line in lines:
outer_name, contained = line.replace("bags", "").replace("bag", "").strip().split(" contain ")
outer_name = outer_name.strip()
if outer_name in bags:
outer_bag = bags[outer_name]
else:
outer_bag = Bag(outer_name)
bags[outer_name] = outer_bag
inners = [x.strip() for x in contained.split(",")]
for inner in inners:
if inner == "no other":
continue
first = inner.split(" ")[0].strip()
bag_name = inner[len(first):].strip()
if bag_name not in bags:
bags[bag_name] = Bag(bag_name)
count = int(first)
outer_bag.contains[bag_name] = count
# Part one
seen = set()
can_reach_gold = set(["shiny gold"])
def look_inside(outer): # Bag
if outer.name in can_reach_gold:
return True
for bag_name in outer.contains.keys():
bag = bags[bag_name]
if look_inside(bag):
can_reach_gold.add(outer.name)
return True
return False
for bag in bags.values():
look_inside(bag)
print can_reach_gold
print len(can_reach_gold) - 1
# Part two
def count_inside(outer):
if not outer.contains:
return 0
count = 0
for bag, number in outer.contains.iteritems():
count += number
count += (number * count_inside(bags[bag]))
return count
current = bags["shiny gold"]
print count_inside(current)
|
7648935fc72fb6de8ebb30fdbf1430af14594475 | CommanderCode/Daily-Problems | /Daily-366-word funnel.py | 1,177 | 3.640625 | 4 | #Given two strings of letters, determine whether the second can be made from the first by removing one letter.
# The remaining letters must stay in the same order.
def funnel(a,b):
for i in range(len(a)):
a_list=list(a)
del a_list[i]
a_new="".join(a_list)
if a_new==b:
return True
break
return False
print (funnel("leave", "eave"))
print (funnel("reset", "rest"))
print (funnel("dragoon", "dragon"))
print (funnel("eave", "leave") )
print (funnel("sleet", "lets"))
print (funnel("skiff", "ski"))
#Given a string, find all words from the enable1 word list that can be made by removing one letter from the string.
# If there are two possible letters you can remove to make the same word, only count it once. Ordering of the output
# words doesn't matter.
def funnel_bonus_1(a):
F = open("C:\\Users\\ahaas\\PycharmProjects\\Daily Problems\\enable1.txt","r")
words=[]
for line in F:
line=line.replace("\n","")
if funnel(a,line):
words.append(line)
print (words)
F.close()
funnel_bonus_1("dragoon")
funnel_bonus_1("boats")
funnel_bonus_1("affidavit")
#BEN WUZ HERE |
bf299f78311eb56a5b91e12412633671de0c621d | JYleekr847/python_summer | /Chapter3/3.py | 1,194 | 3.515625 | 4 | # 스코핑 룰
a = [1,2,3]
def scoping():
a = [4,5,6]
# 이름 공간 : 프로그램에서 쓰이는 이름이 저장되는 공간 위에서는 a가 저장되는 공간
#위에서 변수를 선언하면 [1,2,3]이라는 객체가 메모리공간에 생성되고 , a라는 이름을 가진 레퍼런스가 가리키고 있다.
# 함수는 별도의 이름공간을 갖는다 . 함수 내부에서 사용되는 변수는 함수 내부의 이름공간을 참조한다.
# 하지만 함수내부(지역 영역)에서 이름을 찾지 못하게 되면 상위 공간(전역 영역)에서 이름을 찾는다.
x = 1
def func(a):
return a + x
print(func(1))
#함수 내부에서 x라는 변수를 찾지못해 전역영역에 있는 x = 1을 참조해 값을 반환
def func2(a):
x=2
return a+x
print(func(2))
#함수 내부에 x가 존재하여 함수내부의 x값을 참조하여 값을 반환
#이름을 검색하는 순서 L G B : Local Global Built-in
g = 1
def testScope(a) :
global g
g = 2
return g + a
print(testScope(1))
print(g)
# global로 변수를 선언하게되면 전역영역의 포함된 이름이라도 함수내부에서 변경이 가능하다.
|
1e0182dbf31d1f1d5adb220d81c67a5fc58e7c4e | frank-quoc/hackerrank_python | /python/numpy/min-and-max/answer.py | 247 | 3.671875 | 4 | import numpy
def min_and_max(N, M):
arr_2D = numpy.array([input().split() for _ in range(N)], int)
return numpy.min(arr_2D, axis=1).max()
if __name__ == '__main__':
N, M = map(int, input().split())
print(min_and_max(N, M))
|
d35c32b28f5e35cd725115758ecd20a8beb3172b | Daividao/interview | /bfs.py | 1,155 | 3.9375 | 4 | from collections import deque
# time complexity: O(N). We have to visit every node
# space complexity: O(N). Worst case happens when there is a level contains N - 1 nodes.
def bfs_level(source, tree_graph):
# return a list of lists. Each sublist contains all nodes within a level.
result = []
queue = deque([source])
while queue:
current_level_size = len(queue)
level = []
for i in range(current_level_size):
node = queue.popleft()
level.append(node)
for neighbor in tree_graph[node]:
queue.append(neighbor)
result.append(level)
return result
# time complexity: O(M + N) visit N nodes, and M neighbor edges.
# space complexity: O(N) to store N nodes in queue
def bfs(source, graph):
# return a list of nodes in visiting order
result = []
queue = deque([source])
visited = set()
while queue:
node = queue.popleft()
result.append(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
return result |
074a327a6bacfd4aeb8ee47f1aa6c8f1f274428c | Sajid305/Python-practice | /Source code/Lambda Expression/Lambda Expression.py | 289 | 4.0625 | 4 |
# Lambda Expression
# def add(a,b):
# return a+b
# print(add(3,4))
# ab = lambda a,b : a+b
# print(ab(1,2))
# we use lambda with some built in function like map,filter etc;
# multiply = lambda a,b : a*b
# print(multiply(2,3)) |
b9a8f3221d4fe6bf3a47a424fc65993250275277 | lakshay-saini-au8/PY_playground | /random/day09.py | 832 | 4.375 | 4 | '''
1. Write a Python function that takes a number as a parameter and checks if the
number is prime or not.
'''
import math
def is_prime(n):
for i in range(2, int(math.sqrt(n))):
if n % i == 0:
print(f"{n} is a not prime number")
return
else:
print(f"{n} is a prime number")
return
is_prime(11)
is_prime(12)
'''
2. Write a Python function that accepts a string and calculates the number of uppercase
letters and lowercase letters.
'''
def calc_ul_ll(str):
ul = 0
ll = 0
for ch in str:
if (ch.islower()):
ll = ll + 1
elif(ch.isupper()):
ul = ul+1
return ul, ll
ulc, llc = calc_ul_ll("Hello don HERE YOU")
print(f" Upper case character count is {ulc}")
print(f" Lower case character count is {llc}")
|
95711906405e660c000565216847ae73ba679ad3 | linwt/nowcoder-leetcode | /剑指Offer_Python/02.替换空格.py | 821 | 3.671875 | 4 | # 方法一:使用replace()方法
class Solution:
def replaceSpace(self, s):
return s.replace(' ', '%20')
# 方法二:使用列表,元素赋值
class Solution:
def replaceSpace(self, s):
l = list(s)
for i in range(len(l)):
if l[i] == ' ':
l[i] = '%20'
return ''.join(l)
# 方法三:使用列表,添加元素
class Solution:
def replaceSpace(self, s):
a = []
for i in s:
if i == ' ':
a.append('%20')
else:
a.append(i)
return ''.join(a)
# 方法四:使用字符串
class Solution:
def replaceSpace(self, s):
m = ''
for i in s:
if i == ' ':
m += '%20'
else:
m += i
return m |
887a8c8939cfad3f2b009dcbbedb2020b3db6e39 | srnit/codeon | /hackerearth/Modular.py | 132 | 3.828125 | 4 | import math;
n=int(raw_input());
m=int (raw_input());
if(n>m):
print m;
else:
x=2**n;
if(m<x):
print m;
else:
print (m%(x)); |
9fa9b5fb1c00cf2d5bf467a25d6f2682f5ee7888 | yuanpeigen/PythonLearn | /pythonLearn/data_structure.py | 197 | 4 | 4 | # 字符串
# 声明字符串
str1 = 'Hello World!'
print(str1)
# 访问字符内容
print('++++++++++++访问字符内容++++++++++++')
print('str1[0]:', str1[0])
print('str1[1:5]:', str1[1:5])
|
8efecd618b2924442e04ce4f4f57327283f4b135 | uoaid/note | /tkinter/test_08.py | 593 | 3.78125 | 4 | import tkinter
"""
scale : 刻度控件
"""
tk = tkinter.Tk()
# 默认刻度条竖向 刻度值 1-100
scale = tkinter.Scale(tk)
def show_scale(num): var.set('当前刻度:' + num)
# 刻度条水平 刻度值 0-50 滑动步长 : resolution
scale = tkinter.Scale(tk, label='try me', from_=0, to=50, orient=tkinter.HORIZONTAL, length=200,
showvalue=True,tickinterval=10, resolution=0.1, command = show_scale)
var = tkinter.StringVar()
var.set('当前刻度:' + str(scale.get()))
lable = tkinter.Label(tk, textvariable = var)
scale.pack()
lable.pack()
tk.mainloop() |
6bcf83defad22296e598716ea5799563eb42598b | gh102003/CipherChallenge2020 | /transposition_row_row.py | 247 | 3.734375 | 4 | # Fill in rows, reorder columns then read off rows
ciphertext = input("Enter ciphertext: ")
# key = RDF
plaintext = ""
for a, b, c in zip(ciphertext[0::3], ciphertext[1::3], ciphertext[2::3]):
plaintext += c + a + b
print()
print(plaintext) |
c17a2bcf72ef3c9af285c483253a3a325c81de54 | tinkle1129/Leetcode_Solution | /String/38. Count and Say.py | 1,262 | 3.953125 | 4 | ###########################################
# Author: Tinkle
# E-mail: shutingnupt@gmail.com
# Name: Count and Say.py
# Creation Time: 2018/1/21
###########################################
'''
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1
Output: "1"
Example 2:
Input: 4
Output: "1211"
'''
class Solution(object):
def show(self,s):
count=1
ret=''
flag=s[0]
for i in range(1,len(s)):
if s[i]!=flag:
ret=ret+str(count)+flag
flag=s[i]
count=1
else:
count=count+1
ret=ret+str(count)+flag
return ret
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
s='1'
if n==1:
return s
else:
for i in range(2,n+1):
s=self.show(s)
return s |
8c536065efb1c0fbe44f551d5eda6072ada51585 | yudhiesh/MonteCarloSimulation | /monte_carlo/estimate_pi.py | 1,230 | 3.96875 | 4 | import math
from typing import List, Tuple
import numpy as np
def generate_random_point() -> Tuple[float, float]:
x = np.random.uniform(-1, 1)
y = np.random.uniform(-1, 1)
return x, y
def run_simulation(points: int) -> Tuple[float, float, float]:
assert points > 0
success = 0
for _ in range(points):
x, y = generate_random_point()
if (x ** 2) + (y ** 2) < 1:
success += 1
pi_approx = 4 * (success) / (points)
error = 100 * abs((pi_approx - math.pi) / math.pi)
return pi_approx, error, points
def compare_simulations(
approx_pi_values: List[Tuple[float]],
errors: List[Tuple[float]],
list_points: List[int],
):
for approx_pi, error, points in zip(approx_pi_values, errors, list_points):
print(
f"Simulation ran for {points} points\n"
f"Approx pi value: {approx_pi}\n"
f"Error % : {error}%"
)
def run_simulations():
simulations = list(zip(*[run_simulation(i) for i in range(1, 100_000, 10_000)]))
compare_simulations(
approx_pi_values=simulations[0],
errors=simulations[1],
list_points=simulations[2],
)
if __name__ == "__main__":
run_simulations()
|
f7c630da7b80bb22fd107bc8cbb2a6d8de631470 | jewerlykim/python_Algorithm | /AlgorithmStudy/2503NumberBaseball.py | 1,433 | 3.671875 | 4 | import sys
from itertools import permutations
sys.stdin = open("AlgorithmStudy/2503.txt", 'r')
question_times = int(sys.stdin.readline())
answer_hints = list()
def get_hints(question_times):
for _ in range(question_times):
hint_num, strikes, balls = map(int, sys.stdin.readline().split())
answer_hints.append((hint_num, strikes, balls))
get_hints(question_times=question_times)
candidate_numbers = list()
def init_candidate():
one_to_nine = list()
for i in range(1, 10, 1):
one_to_nine.append(i)
candidate_numbers.extend(list(permutations(one_to_nine, 3)))
init_candidate()
def compare_numbers(candidates, hints, depth):
new_candidates = list()
hint_num, strikes, balls = hints
using_hint = str(hint_num)
for candidate_num in candidates:
strike_counts, ball_counts = 0, 0
for i in range(3):
if int(using_hint[i]) in candidate_num:
if int(using_hint[i]) == candidate_num[i]:
strike_counts += 1
else:
ball_counts += 1
if (strike_counts, ball_counts) == (strikes, balls):
new_candidates.append(candidate_num)
if depth < question_times - 1:
depth += 1
return compare_numbers(new_candidates, answer_hints[depth], depth)
else:
return len(new_candidates)
print(compare_numbers(candidate_numbers, answer_hints[0], 0))
|
445488cae5a29dc4ac105497148ec6402b4ee3e6 | Devil8899/Python_demo | /Day15/Demo3系统内置函数.py | 1,004 | 3.71875 | 4 | #_author: liuz
#date: 2017/12/8
#在python中内置了很多函数
#eval() 将字符串string对象转化为有效的表达式参与求值运算返回计算结果
print(eval('{"name":"jerry"}'))
print(eval('1+2*5'))
#filter(函数,序列) 过滤方法 循环遍历列表 有条件的过滤
def fun1(a):
if a!='d': #过滤d
return a
str=['a','b','c','d']
ret=filter(fun1,str) #ret 返回一个迭代器 <filter object at 0x000002186FC57080>
print(list(ret)) #['a', 'b', 'c'] 将迭代器转为一个list ['a', 'b', 'c']
#map(函数,序列)对序列做处理 比如拼接字符串
def fun2(a):
return a+'hi'
ret2=map(fun2,str) #ret2 是一个迭代器对象
print(list(ret2)) #['ahi', 'bhi', 'chi', 'dhi']
#reduce(函数,序列) 返回是一个值 使用前需要加下面一句话
from _functools import reduce
def add1(x,y):
return x + y
print(reduce(add1,[1,2,3,4,5]))#15
#lambda 匿名函数 无需定义函数名
add2=lambda a,b:a+b
print(add2(2,9))
|
6b4254e3c86fc27eda051db4fe4b241bbfe774db | henriquecl/Aprendendo_Python | /Exercícios/Lista 4 - Seção 7 - Coleções/Questão 16 - Enunciado nó código.py | 758 | 3.96875 | 4 | # Questão 16 - Faça um progrmama que leia 5 numeros reais, e depois um código inteiro.
# Se o código for 0: Para
# Se o código for 1: Mostre o vetor na ordem direta
# Se o código for 2: Mostre o vetor na ordem inversa
# Caso o código for diferente de 1 e 2 escreva uma mensagem informando q oc ódigo é invalido
lista = []
numero = 0
for i in range(5):
print(f'Digite {5 - i} numer(os)')
numero = float(input())
lista.append(numero)
i = int(input('Digite a operação que deseja\n'))
if i != 1 or i != 2 or i !=0:
print('Código inválido')
if i == 1:
print(f'Os valores inseridos foi: {lista}')
if i == 2:
lista.reverse()
print(f'Os valores interidos foi {lista}')
if i == 0:
print('O programa foi finalizado') |
2b804e450a245404d6922be2ab5d0cc9d28b9904 | malfageme/checkio | /Electronic-Station/08.three-points-circle.py | 757 | 3.703125 | 4 |
from math import sqrt
def checkio(data):
x1,y1,x2,y2,x3,y3 = [float(x) for x in data.replace("(","").replace(")","").split(",")]
d=2.0 * (x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2))
x0=( (x1**2+y1**2)*(y2-y3) + (x2**2+y2**2)*(y3-y1) + (x3**2+y3**2)*(y1-y2) ) / d
y0=( (x1**2+y1**2)*(x3-x2) + (x2**2+y2**2)*(x1-x3) + (x3**2+y3**2)*(x2-x1) ) / d
r= sqrt((x0-x1)**2+(y0-y1)**2)
#replace this for solution
return "(x{:+g})^2+(y{:+g})^2={:g}^2".format(round(-x0,2),round(-y0,2),round(r,2))
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(u"(2,2),(6,2),(2,6)") == "(x-4)^2+(y-4)^2=2.83^2"
assert checkio(u"(3,7),(6,9),(9,7)") == "(x-6)^2+(y-5.75)^2=3.25^2"
|
cef8df927025d547d7377f68e11d749e3f1c5f85 | anderson-0812/Python-Random | /Practicas Python/listas ejercicio.py | 335 | 3.953125 | 4 | print("Escribe el limite de palabras a ingresar")
limite = input()
limite = int(limite) #convierto el str a int
li = []
for i in range(limite): #doy limite al bucle
print("el rango es " + str(len(li)) )
print("Escribe la palabra")
li.append(raw_input(''))#leo los datos de entrada y gaurdo en la lista
print("la lista es ")
print li |
28595a56c8205f6d33c1a0c324724aae190ca3e7 | volat1977/byte_of_python | /classwork/9/2_class_with_attrs.py | 273 | 3.890625 | 4 | class MyList:
def append(self, item, item2):
self.attr1 = item
self.attr2 = item2
l = MyList()
l.append(1, 2)
print(l.attr1)
print(l.attr2)
l.append(3, 4)
print(l.attr1)
print(l.attr2)
l2 = MyList()
l2.append(5, 6)
print(l2.attr1)
print(l2.attr2)
|
4353271f6fa539d88a884e6e66a91e8c3c62df57 | preshathakkar/Intro-to-Computer-Programing---edX---6.00x | /4.py | 275 | 3.59375 | 4 | balance=4428
annualInterestRate=.18
newbalance=balance
x=10
nb = balance
while float(nb) > 0 :
nb = balance
for m in range(1,13):
rb = float(nb) - x
nb = float(rb) * (1 + float(annualInterestRate)/12)
x += 10
print('Lowest Payment :' + str(x))
|
7ef516dda9c1acf78efd2bedd583f5004f5558d1 | JulyKikuAkita/PythonPrac | /cs15211/SerializeAndDeserializeBST.py | 5,507 | 3.78125 | 4 | __source__ = 'https://leetcode.com/problems/serialize-and-deserialize-bst/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/serialize-and-deserialize-bst.py
# Time: O(n)
# Space: O(h)
#
# Description: Leetcode # 449. Serialize and Deserialize BST
#
# Serialization is the process of converting a data structure or
# object into a sequence of bits so that it can be stored in a file or
# memory buffer, or transmitted across a network connection link to be
# reconstructed later in the same or another computer environment.
#
# Design an algorithm to serialize and deserialize a binary search tree.
# There is no restriction on how your serialization/deserialization algorithm should work.
# You just need to ensure that a binary search tree can be serialized to a string and
# this string can be deserialized to the original tree structure.
#
# The encoded string should be as compact as possible.
#
# Note: Do not use class member/global/static variables to store states.
# Your serialize and deserialize algorithms should be stateless.
#
# Companies
# Amazon
# Related Topics
# Tree
# Similar Questions
# Serialize and Deserialize Binary Tree
import collections
import unittest
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
def serializeHelper(node, vals):
if node:
vals.append(node.val)
serializeHelper(node.left, vals)
serializeHelper(node.right, vals)
vals = []
serializeHelper(root, vals)
return ' '.join(map(str, vals))
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
def deserializeHelper(minVal, maxVal, vals):
if not vals:
return None
if minVal < vals[0] < maxVal:
val = vals.popleft()
node = TreeNode(val)
node.left = deserializeHelper(minVal, val, vals)
node.right = deserializeHelper(val, maxVal, vals)
return node
else:
return None
vals = collections.deque([int(val) for val in data.split()])
return deserializeHelper(float('-inf'), float('inf'), vals)
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
if __name__ == '__main__':
unittest.main()
Java = '''
# Thought:
Hi all, I think my solution is pretty straightforward and easy to understand,
not that efficient though. And the serialized tree is compact.
Pre order traversal of BST will output root node first, then left children, then right.
root left1 left2 leftX right1 rightX
If we look at the value of the pre-order traversal we get this:
rootValue (<rootValue) (<rootValue) (<rootValue) |separate line| (>rootValue) (>rootValue)
Because of BST's property: before the |separate line| all the node values are less than root value,
all the node values after |separate line| are greater than root value.
We will utilize this to build left and right tree.
Pre-order traversal is BST's serialized string. I am doing it iteratively.
To deserialized it, use a queue to recursively get root node, left subtree and right subtree.
I think time complexity is O(NlogN).
Errr, my bad, as @ray050899 put below, worst case complexity should be O(N^2),
when the tree is really unbalanced.
My implementation
# PreOrder + Queue solution
# 11ms 60.21%
class Codec {
private static final String SEP = ",";
private static final String NULL = "null";
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
if (root == null) return NULL;
//traverse it recursively if you want to, I am doing it iteratively here
Stack<TreeNode> st = new Stack<>();
st.push(root);
while (!st.empty()) {
root = st.pop();
sb.append(root.val).append(SEP);
if (root.right != null) st.push(root.right);
if (root.left != null) st.push(root.left);
}
return sb.toString();
}
// Decodes your encoded data to tree.
// pre-order traversal
public TreeNode deserialize(String data) {
if (data.equals(NULL)) return null;
String[] strs = data.split(SEP);
Queue<Integer> q = new LinkedList<>();
for (String e : strs) {
q.offer(Integer.parseInt(e));
}
return getNode(q);
}
// some notes:
// 5
// 3 6
// 2 7
private TreeNode getNode(Queue<Integer> q) { //q: 5,3,2,6,7
if (q.isEmpty()) return null;
TreeNode root = new TreeNode(q.poll());//root (5)
Queue<Integer> smallerQueue = new LinkedList<>();
while (!q.isEmpty() && q.peek() < root.val) {
smallerQueue.offer(q.poll());
}
//smallerQueue : 3,2 storing elements smaller than 5 (root)
root.left = getNode(samllerQueue);
//q: 6,7 storing elements bigger than 5 (root)
root.right = getNode(q);
return root;
}
}
'''
|
aaf57a9264d6e7e693c7ab42e7d43e71ab053954 | callumgedling/Pracs | /Prac_03/password_checker.py | 397 | 3.65625 | 4 | MIN_LENGTH = 4
def main():
password = get_password()
astericks_creation(password)
def astericks_creation(password):
for letters in password:
print("*", end="")
def get_password():
password = input("Please enter a password")
while len(password) < MIN_LENGTH:
password = input("Please enter a password with four or more letters")
return password
main()
|
de58484229834b743edb4407a051dc3fb4942ae6 | ridhoaryo/if_else_project | /day_translator_ina_to_eng.py | 325 | 4.09375 | 4 | days = {
'senin': 'monday', 'selasa': 'tuesday', 'rabu': 'wednesday', 'kamis': 'thursday', 'jumat': 'friday', 'sabtu': 'saturday',
'ahad': 'sunday'
}
days
day = input('Masukkan nama hari: ').lower()
day_translate = days.get(day, 'Not Found!')
print(f'Bahasa Inggris dari {day.upper()} adalah {day_translate.upper()}') |
30a54fe20cdd053d12aa86fae3a176a93f8f3735 | chapman-cpsc-230/hw4-benav115 | /histogram1.py | 295 | 4.1875 | 4 | """
File: histogram1.py
Copyright (c) 2016 Rachel Benavente
License: MIT
This code prints out a histogram based upon a list of numbers.
"""
def histogram(number):
for i in number:
string = ""
for h in range(i):
string += "*"
print string
histogram ([2,4,6,8])
|
43cc47b2c1341670d7c862aa76c021f6b2cd8f2a | apiwatc/coding-challenges | /product_except_self.py | 1,121 | 3.96875 | 4 | """
Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Example:
Input: [1,2,3,4]
Output: [24,12,8,6]
Constraint: It's guaranteed that the product of the elements of any prefix or suffix of the array (including the whole array) fits in a 32 bit integer.
Note: Please solve it without division and in O(n).
Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)
"""
def productExceptSelf(nums):
''' Left and Right product lists '''
ans = []
edge = 1
# add 1 to left of [1, 2, 3, 4] -> then result in [1, 1, 2, 6]
for num in nums:
ans.append(edge)
edge *= num
edge = 1
# add 1 to right of [1, 2, 3, 4] -> then result in [24, 12, 4, 1]
# then mulitply each at the same index, result in [24, 12, 8, 6]
for i in range(len(nums)-1, -1, -1):
ans[i] = (edge*ans[i])
edge *= nums[i]
return ans
nums = [0, 1]
print(productExceptSelf(nums))
|
c480f7ea3913787b36ee9990e54c497875ede57e | GitNickProgramming/CS3250 | /maze_generator.py | 3,301 | 3.71875 | 4 | import matplotlib.pyplot as plt
from numpy import zeros as npz
from random import shuffle
from random import choice
def main(dims=(10, 10), draw=False, rooms=False, save=False):
"""Generate a maze with 'rooms' on intersections, corners, and dead-ends.
Keyword Arguments:
dims {tuple, default: (x=10, y=10)} (where x + y % 2 == 0):
unit dimensions of maze
draw {bool, default: False}:
show maze as pyplot figure
rooms {bool, default: False}:
highlight rooms on figure
save {bool, default: False}:
save figure to working directory as png
Returns:
maze {list of list of int}:
a numpy integer matrix
rooms {list of tuple}:
a {list} of room coordinates as {tuple}
"""
moves = [
[(0, 2), (0, 1)], [(0, -2), (0, -1)],
[(-2, 0), (-1, 0)], [(2, 0), (1, 0)]
]
rules = [
[0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0],
[1, 1, 1, 0], [1, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1],
[1, 1, 1, 1], [1, 0, 1, 0], [1, 0, 0, 1], [0, 1, 1, 0],
[0, 1, 0, 1]
]
if dims[0] % 2 != 0 or dims[1] %2 != 0:
print("Maze dimensions must be even integers!")
maze, nodes = None, None
else:
maze, nodes = _generate_maze(dims, rooms, moves, rules)
print(f"Maze contains {len(nodes)} rooms")
if draw:
_draw_maze(maze, len(nodes), save)
return maze, nodes
def _generate_maze(dims, rooms, moves, rules):
x, y = dims
m = npz((x+1, y+1), dtype=int)
grid = [(a, b) for a in range(1, x+1, 2) for b in range(1, y+1, 2)]
visited = [choice(grid)]
k = visited[0]
grid.remove(k)
while len(grid) > 0:
n = len(visited)
nsew = []
for i in range(4):
probe = tuple(sum(x) for x in zip(moves[i][0], k))
link = tuple(sum(x) for x in zip(moves[i][1], k))
nsew.append([probe, link])
shuffle(nsew)
for a in nsew:
probe, link = a
if probe in grid:
m[probe], m[link] = 1, 1
grid.remove(probe)
visited.extend(a)
break
if n == len(visited):
k = visited[max(visited.index(k)-1, 1)]
else:
k = visited[-1]
return _get_rooms(m, visited, rooms, rules)
def _get_rooms(m, visited, rooms, rules):
nodes = []
m[visited[0]], m[visited[-2]] = 2, 2
for coord in visited:
i, j = coord
neighbors = [m[i-1, j], m[i+1, j], m[i, j-1], m[i, j+1]]
if neighbors in rules:
nodes.append(coord)
if rooms:
m[coord] = 2
return m, nodes
def _draw_maze(m, rooms, save):
fig, ax = plt.subplots(figsize=(10, 10))
ax.set_aspect(1.0)
plt.xticks([])
plt.yticks([])
plt.pcolormesh(m, cmap=plt.cm.tab20b)
if save:
fig.savefig(
f"{m.shape[0]-1}x{m.shape[1]-1}_{rooms}_rooms.png",
dpi=300,
bbox_inches="tight",
pad_inches=-0.1)
plt.show()
if __name__ == "__main__":
main(dims=(6, 20), draw=True, rooms=True, save=False)
|
d80ff0f4f4bcf6a1412c578ab9cf9b6234a72e64 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/223/users/4342/codes/1630_2921.py | 235 | 3.6875 | 4 | jogo1=float(input("digite o valor do jogo1:"))
jogo2=float(input("digite o valor do jogo2:"))
desconto=(jogo2*(25/100))
totaljogo2=(jogo2-desconto)
totalcompra=(jogo1+totaljogo2)
print(round(totaljogo2, 2))
print(round(totalcompra, 2)) |
745d23578c1d51e1c4847f21234be3374a4c923e | BaiLiping/ControllerBasedCoaching | /walker/break.py | 294 | 4 | 4 | print('break')
n=5
while n>0:
n-=1
if n==2:
break
print(n)
print('the end')
print('continue')
n=5
while n>0:
n-=1
if n==2:
continue
print(n)
print('the end')
print('pass')
n=5
while n>0:
n-=1
if n==2:
pass
print(n)
print('the end')
|
06862f0f115a1e35e397eb14065b6d3d03fe69a7 | KateUnger/frc-hw-submissions | /lesson4/HW4.py | 1,097 | 4.21875 | 4 |
age = int(raw_input("Your age? "))
if age < 14:
print "Sorry, you can't do anything... yet!"
elif age >= 14 and age < 16:
print "You can join the awesome 1678 team! "
elif age >= 16 and age < 18:
print "You can join the awesome 1678 team! "
print "You can drive and get a job!"
elif age >=18 and age <21:
print "You can join the awesome 1678 team! "
print "You can drive and get a job!"
print "You can attend college"
elif age >= 21 and age <35:
print "You can join the awesome 1678 team! "
print "You can drive and get a job! "
print "You can attend college! "
print "You are an adult! "
else:
print "You can join the awesome 1678 team! "
print "You can drive and get a job"
print "You can attend college! "
print "You are an adult! "
print "You can become president! "
print ""
print ""
print ""
patients = [[70, 1.8], [80, 1.9], [150, 1.7]]
def calculate_bmi(weight, height):
return weight / (height ** 2)
for patient in patients:
weight, height = patients[0]
#they switched height and weight
bmi = calculate_bmi(weight, height)
print "Patient's BMI is:" + str(bmi)
|
58ca6fc6d25cb2f2bd0348b097c6cb280cc42775 | JunDang/PythonStudy | /vowel2.py | 99 | 3.765625 | 4 | def isVowel2(char):
char = char.lower()
return char in ['a','e','i','o','u']
print isVowel2('M')
|
c97ffc78247c7503bf8dbbe8b3c7f37f5703abc3 | collin-clark/python | /ping-hosts.py | 1,446 | 3.859375 | 4 | ###############################################################################
# Task: Ping hosts listed in a text file and report up/down status. If it is
# up it will try and reverse DNS to get the hostname.
#
# Usage: 'python3 ping-hosts.py' The ping-hosts.txt file should be in the same
# directory as this script.
#
#
# Author: Collin Clark
# Date: 03MAY2018
# Version: 1.0
################################################################################
import os
import platform
import socket
# Open the ping-hosts.txt file and read each line as a string
with open("ping-hosts.txt") as fp:
hostname = fp.readline()
for hostname in fp:
# Lets remove /n from the string
hostname = hostname.rstrip()
# Ping based on Windows or Unix
if platform.system() == "Windows":
response = os.system("ping "+hostname+" -n 1")
else:
response = os.system("ping -c 1 " + hostname)
print(hostname)
# A boolean on whether or not the host responded to the ping
if response == 0:
# Let's grab the DNS info for the IP above
dns_raw = socket.gethostbyaddr(hostname)
# gethostbyaddr returns a tuple of information. All we need is the first one.
slice = dns_raw[0]
print("The host "+hostname+" is UP and its hostname is "+slice)
else:
print(hostname+" is down")
|
647fed1ba7da89b0ded9c11ddc32a8ced51e140f | leonardovenan/birkhoff | /birkhoff.py | 978 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Sep 5 16:50:28 2019
@author: Leonardo
"""
import matplotlib.pyplot as plt
def n2_2k_1 (x):
return 2**(2*(x-1))
lista1 = []
lista2 = []
lista23 = [2/3]
lista13 = [1/3]
soma = 0
j = 1
k = int(input('Digite o valor de k: '))
#for i in range(onde começa, até onde vai, em qual ondem ele cresce)
for i in range (j, (k+1)):
soma = soma + n2_2k_1(i)
lista1.append((1 + soma)/2**(2*(i)-1))
lista2.append((1 + soma)/2**(2*i))
print("ultimo termo 2k-1: ", lista1[k-1])
print("Ultimo termo 2k: ", lista2[k-1])
fig,ax = plt.subplots()
ax.plot(lista1)
ax.plot(k*lista23, 'r--')
plt.title('2k-1 -> 2/3')
fig2, bx = plt.subplots()
bx.plot(lista2)
bx.plot(k*lista13, 'r--')
plt.title('2k -> 1/3')
plt.show()
#res_n2_2k_1 = (1 + soma)/2**(2*(k)-1)
#res_n2_2k = (1 + soma)/2**(2*k)
#print ("ultimo termo 2k-1: ", res_n2_2k_1)
#print ("Ultimo termo 2k: ", res_n2_2k) |
4b2bfe7edb1801a2eae9609afef94f4a3655851d | jakegee/python-crash | /words2.py | 589 | 3.875 | 4 | newwords = {}
newwords['function'] = 'you know its like the whole block of code'
function = newwords['function']
newwords['method'] = 'its like a get on a dict key'
method = newwords['method']
newwords['dunno'] = 'do i really know any new words'
dunno = newwords['dunno']
newwords['sup'] = 'you know its like the whole block of code'
function = newwords['sup']
newwords['nup'] = 'its like a get on a dict key'
method = newwords['nup']
newwords['bup'] = 'do i really know any new words'
dunno = newwords['bup']
for key, value in newwords.items():
print(f"{key}")
print(f"{value}") |
3be63b972e23c502f337cc09e0cbe0f58adf08ee | antmdev/ML_Regression | /1_Simple_Linear_Regression/simple_linear_regression_ant.py | 1,664 | 4.28125 | 4 | # Simple Linear Regression
"""
# Data Preprocessing Template
"""
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
"""
#Importing the dataset
"""
dataset = pd.read_csv('pwd.csv')
X = dataset.iloc[:, :-1].values#setting independent variable
y = dataset.iloc[:, 1].values #settign dependent variable
"""
#Splitting the dataset into the Training set and Test set
"""
from sklearn.model_selection import train_test_split #library to split train and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
"""
#Fitting the Simple Linear Regression to the Training Set
"""
from sklearn.linear_model import LinearRegression #import LR class
regressor = LinearRegression() #Create and Object of the linear regression class called regressor
regressor.fit(X_train, y_train) #use the fit method to fit the training set
"""
#Predicting the Test set Results
"""
y_pred = regressor.predict(X_test)
"""
#Visualising the Training set Results! Woop!
"""
plt.scatter(X_train, y_train, color = 'red') #real year vs salary
plt.plot(X_train, regressor.predict(X_train), color = 'blue') #plotting the prediction line of the ML model
plt.title('Salary Vs Experience (Training Set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()
"""
#Visualising the Test set Results! Woop!
"""
plt.scatter(X_test, y_test, color = 'red') #real year vs salary
plt.plot(X_train, regressor.predict(X_train), color = 'blue') #plotting the prediction line of the ML model
plt.title('Salary Vs Experience (Test Set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()
|
c0f263a90801c90dcd4372405e9617a33676840c | XiongDanDanDAN/MachineLearning | /MachineLearning/RandomForest/running.py | 842 | 3.5 | 4 | from MachineLearning.RandomForest.randomForest import randomForest
from MachineLearning.RandomForest.tool import load_data
import matplotlib.pyplot as plt
def running():
'''entrance'''
data_train, text, target = load_data()
forest = randomForest()
predic = []
for i in range(1, 20):
trees, features = forest.random_forest(data_train, i)
predictions = forest.get_predict(trees, features, text)
accuracy = forest.cal_correct_rate(target, predictions)
print('The forest has ', i, 'tree', 'Accuracy : ' , accuracy)
predic.append(accuracy)
plt.xlabel('Number of tree')
plt.ylabel('Accuracy')
plt.title('The relationship between tree number and accuracy')
plt.plot(range(1, 20), predic, color = 'orange')
plt.show()
pass
if __name__ == '__main__':
running() |
3a64060232c8a159a51862cdf700806cd0a05ea7 | akhildn/Intro_to_Python | /Udacity/Shapes.py | 367 | 3.96875 | 4 | import turtle
def draw_square(cursor):
for i in range(4):
cursor.forward(100)
cursor.right(90)
def draw_circle_with_square():
window = turtle.Screen()
window.bgcolor("white")
cursor = turtle.Turtle()
for i in range(24):
draw_square(cursor)
cursor.right(15)
window.exitonclick()
draw_circle_with_square() |
57a83e11e5e150623a797aa0ab248de8518e36aa | Wreos/Python | /palindrom.py | 222 | 3.65625 | 4 | pal=input()
i=0
j=len(pal)-1
is_palindrom=True
while i<j:
if pal[i]!=pal[j]:
is_palindrom=False
print("Не палиндром")
break;
i+=1
j-=1
else:
print("yes")
|
11efa863d2a08e03d4b059c7f0a104a25253ef05 | TeggyYang/AlgorithmsByPython | /leetcode/t028_implementStrStr().py | 770 | 3.828125 | 4 | # --*-- coding:utf-8 --*--
# leetcode_028:https://leetcode.com/problems/implement-strstr/#/description
# lintcode_013:http://www.lintcode.com/zh-cn/problem/strstr/
class Solution(object):
def strStr(self, haystack, needle):
if source is None or target is None:
return -1
len_s = len(source)
len_t = len(target)
for i in range(len_s - len_t + 1):
j = 0
while (j < len_t):
if source[i + j] != target[j]:
break
j += 1
if j == len_t:
return i
return -1
if __name__ == "__main__":
solution = Solution()
source = ""
target = ""
ans = solution.strStr(source, target)
print ans
print "over" |
f8c7a30a1e20b9a59337a11e0ade249b17590782 | ersujalsharma/PythonPractice | /8_StringSlicing.py | 315 | 4.0625 | 4 | mystr = "Sujal is an engineer"
print(mystr) #MYSTR
print(mystr[2]) # print 2nd index character
print(mystr[0:4]) # print starting to 4 th character
print(len(mystr)) # print lngth of strings
print(mystr[0:80]) # Start to end
print(mystr[ : 12]) #start with 0 end with 13
print(mystr[3: ])#start with 3 end with end
|
3c153008c6c5e9d4750d4f7c2a72abc848d9afac | MohammadSalloum/firstRepository | /Script1.py | 294 | 4 | 4 | name =input("enter name\n")
age=input("enter age\n")
age=int(age)
print("Welcom "+ name + " , you are " + str(age) + " year old\n")
a=input("enter str1\n")
b=input("enter str2\n")
c=input("enter str3\n")
vars=[a,b,c]
vars_t=tuple(vars)
print (vars)
print (vars_t)
print(name.lower()) |
13c223dcdf5535d30296d71f4acd15cb6458d407 | kentxun/PythonBase | /LinkList/Palind.py | 1,598 | 3.859375 | 4 | '''
请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
'''
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# 额外空间复杂度为O(n)
class Palindrome:
def isPalindrome(self, pHead):
# write code here
stack = []
headNode = ListNode(0)
headNode.next=pHead
while pHead:
stack.append(pHead.val)
pHead = pHead.next
pHead = headNode.next
for i in range(len(stack)):
if pHead.val != stack.pop():
return False
else:
pHead = pHead.next
return True
# 额外空间复杂度为O(N/2)
class Palindrome1:
def isPalindrome(self, pHead):
# write code here
if pHead is None or pHead.next is None:
return True
stack = []
pHead1 = pHead
pHead2 = pHead
# 边界有先后顺序,奇偶情况的边界有别,当pHead已经为None时就直接退出
while pHead1 and pHead1.next:
stack.append(pHead2.val)
pHead2 = pHead2.next
pHead1 = pHead1.next.next if pHead1.next else None
if pHead1:
pHead2 = pHead2.next
while pHead2:
if pHead2.val != stack.pop():
return False
else:
pHead2= pHead2.next
return True if len(stack)==0 else False |
7e0203070e2f44c9df63ec167264055076147372 | leiyanghong/2004B-python-basics | /day1/python_1.py | 2,321 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# leiyh
'''
1、使用for循环反序输出字符串"abcdefghijklmnopqrstuvwxyz"
'''
def daoxu():
str = "abcdefghijklmnopqrstuvwxyz"
str2 = ''
for i in str:
str2 = i + str2
print(str2)
'''
写出下列递归函数的伪代码:
'''
d = {"name":"leiyh","sex":"男","age":"18","人物信息":['leiyh','男',18],"元组":(0,1,2,3,4)}
'''
第一次遍历:
search("leiyh")
search("男")
search("18")
search(['leiyh','男',18])
第二次遍历:
第二次遍历的是人物信息字段下的数组
search("leiyh")
search("男")
search(18)
'''
def search(d):
# 判断是否是字典,满足遍历
if isinstance(d,dict):
# 遍历获取key: 'name', 'sex', 'age', '人物信息' 用key值遍历获取value
for key in d:
# 每次遍历之后都会重新调用search()函数对里层的value重新判断是否是字典或者数组
search(d[key])
# if条件不满足,就判断d是否是数组
elif(isinstance(d,list)):
# 遍历获取d字典所有key
for i in d:
# 引用key 重新调用search()函数 重新判断d字典属性 d字典第二次判断的key是:人物信息
search(i)
# 判断是否是元组,满足获取该元组里面所有value
elif(isinstance(d,tuple)):
for i in d:
# 递归自调用遍历
search(i)
# 直到上述条件都不满足输出打印d字典
else:
print(d)
'''
编写一个过滤掉列表中空字符串和空值的方法 ,并返回过滤后的list
效果:
方法传入[’’,‘hello’,None,‘python’] 返回[‘hello’,‘python’]
'''
def lis(l):
s = []
# 遍历传入的参数,拿到每一个值
for i in l:
# 判断每个值是否为空 是否为None
if i == '' or i is None:
# 满足就通过,不打印
pass
else:
# 反之就追加到s数组里
s.append(i)
# 返回处理之后追加的s数组
return s
l = lis(['','hello',None,'python'])
print(l)
'''
4、编写一个计算一个元祖中所有数据和的方法,并把计算结果返回
'''
def sum_tuple(tu):
sum = 0
for i in tu:
sum += i
return sum
print(sum_tuple(tu = (1,2,3,4,5,6,7,8))) |
a99b7bb0aae2b46773c31d5a695b5f8959adc4aa | vahtras/util | /util/subblocked.py | 4,285 | 3.59375 | 4 | """
Module with blocked matrix class
"""
class SubBlockedMatrix:
"""
Blocked matrix class
>>> print(SubBlockedMatrix([2, 1], [2, 1]))
<BLANKLINE>
Block (1,1)
<BLANKLINE>
(2, 2)
Column 1 Column 2
<BLANKLINE>
Block (1,2)
<BLANKLINE>
(2, 1)
Column 1
<BLANKLINE>
Block (2,1)
<BLANKLINE>
(1, 2)
Column 1 Column 2
<BLANKLINE>
Block (2,2)
<BLANKLINE>
(1, 1)
Column 1
<BLANKLINE>
"""
def __init__(self, nrow, ncol):
"""Initialize blocked matrix instance
nrow: integer tuple, blocked row dimension
ncol: integer tuple, blocked column dimension
"""
from . import full
self.rowblocks = len(nrow)
self.colblocks = len(ncol)
self.nrow = nrow
self.ncol = ncol
self.subblock = []
self.irow = []
self.icol = []
for i in range(self.rowblocks):
self.subblock.append([])
self.irow.append(sum(self.nrow[:i]))
self.icol.append(sum(self.ncol[:i]))
for j in range(self.colblocks):
self.subblock[i].append([])
self.subblock[i][j] = full.matrix((nrow[i], ncol[j]))
def __str__(self):
"""
String representation of blocked matrix
"""
retstr = ""
for i in range(self.rowblocks):
for j in range(self.colblocks):
retstr += "\nBlock (%d,%d)\n" % (i + 1, j + 1) + str(
self.subblock[i][j]
)
return retstr
def __getitem__(self, args):
i, j = args
return self.subblock[i][j]
def T(self):
"""Transpose of blocked matrix"""
new = matrix(self.ncol, self.nrow)
for i in range(self.rowblocks):
for j in range(self.colblocks):
new.subblock[i][j] = self.subblock[j][i].transpose()
return new
def __mul__(self, other):
"""
Scalar multiplication
"""
bdm = self.__class__(self.nrow, self.ncol)
for row in bdm.subblock:
for block in row:
block *= other
return bdm
def __nextmul__(self, other):
"""
Addition of blocked matrices
"""
new = SubBlockedMatrix(self.nrow, other.ncol)
for i in range(self.rowblocks):
for j in range(self.colblocks):
new.subblock[i][j] = self.subblock[i][j] + other.subblock[i][j]
return new
def __matmul__(self, other):
"""
Multiplication of blocked matrices
"""
new = SubBlockedMatrix(self.nrow, other.ncol)
for i in range(self.rowblocks):
for j in range(other.colblocks):
if self.nrow[i] * other.ncol[j]:
for k in range(self.colblocks):
new.subblock[i][j] = self.subblock[i][k] @ other.subblock[k][j]
return new
def __add__(self, other):
"""
Addition of blocked matrices
"""
new = SubBlockedMatrix(self.nrow, other.ncol)
for i in range(self.rowblocks):
for j in range(self.colblocks):
new.subblock[i][j] = self.subblock[i][j] + other.subblock[i][j]
return new
def __sub__(self, other):
"""
Subtraction of blocked matrices
"""
new = SubBlockedMatrix(self.nrow, other.ncol)
for i in range(self.rowblocks):
for j in range(self.colblocks):
new.subblock[i][j] = self.subblock[i][j] - other.subblock[i][j]
return new
def unblock(self):
"""
Unblock to full matrix
"""
from . import full
nrows = sum(self.nrow)
ncols = sum(self.ncol)
new = full.matrix((nrows, ncols))
for i in range(self.rowblocks):
for j in range(self.colblocks):
new[
self.irow[i]: self.irow[i] + self.nrow[i],
self.icol[j]: self.icol[j] + self.ncol[j],
] = self.subblock[i][j]
return new
matrix = SubBlockedMatrix # alias for back compatibility
|
9292361fbf122ddc6d905938713a487c6ddfb944 | AlbinaGiliazova/HyperskillPythonProjects | /ChatBot.py | 1,476 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
A simple chat bot that asks name, guesses age, counts to a specified number and
asks a question about programming.
A project for hyperskill.org
@author: Giliazova
"""
# introduction
print("Hello! My name is Aid.")
print("I was created in 2020.")
# remind name
name = input("Please, remind me your name.\n")
print(f"What a great name you have, {name}!")
# guess age
print("Let me guess your age.")
print("Enter remainders of dividing your age by 3, 5 and 7.")
remainder3 = int(input())
remainder5 = int(input())
remainder7 = int(input())
age = (remainder3 * 70 + remainder5 * 21 + remainder7 * 15) % 105
print(f"Your age is {age}; that's a good time to start programming!")
# count
print("Now I will prove to you that I can count to any number you want.")
number = int(input())
for i in range(number + 1):
print(str(i) + " !")
# ask a question
print("Let's test your programming knowledge.")
print("Why do we use methods?")
print("1. To repeat a statement multiple times")
print("2. To decompose a program into several small subroutines.")
print("3. To determine the execution time of a program.")
print("4. To interrupt the execution of a program.")
while True:
s = input()
if s == "2":
print("Completed, have a nice day!")
break
else:
print("Please, try again.")
# bye
print("Congratulations, have a nice day!")
|
de8f7a2acda54f7245712dd04b6df688bdf7f439 | vantwoutmaarten/PracticeBasics | /pytorch_turtorials/autograd.py | 498 | 3.578125 | 4 | import torch
x = torch.randn(3, requires_grad=True)
print(x)
y = x + 2
print(y)
z = y*y*2
z = z.mean()
print(z)
z.backward() #this calculate the gradient of z with respect to x dz/dx
print(x.grad) # the attribute grad stores the gradients
weights = torch.ones(4, requires_grad=True)
for epoch in range(2):
model_output = (weights*3).sum()
model_output.backward()
print(weights.grad)
weights.grad_zero_() #this must be done so the grad from previous epochs do not accumalate |
4ee88659127b63f57b0cee3d315982f3d921c557 | JohnPaulGamo/JohnPaulGamo | /Activity_A_Gamo.py | 214 | 3.75 | 4 |
for x in range(1,20,3):
print (x)
for z in range(100,75,-7):
print (z)
for x in range(1,5):
if x % 4 == 3:
print("1" , end = "\t")
else:
print("0", end="\t")
|
c181fb04234b575f8539abf1647be1543ddb3021 | isaacrael/python | /Code Cademy/average_numbers_dict_challenge_exercise_practice.py | 868 | 4.375 | 4 | """Written By: Gil Rael
The following python program demonstrates the use
of a function called average that takes a list of numbers
as input and then prints out the average of the numbers.
Algorithm:
Step 1: Create list of numbers called lst = [80,90]
Step 2: total_values equals the length of the list
Step 3: total_homework equals the sum of the homework scores
Step 4: average_homework = float(total_homework / total_values)
Step 5: Define function called average
"""
# Initialize Variables
# Define Functions
lst = [80,90]
def average(lst):
for number in (lst):
total_values = float(len(lst))
total_homework = float(sum(lst))
average_homework = float(total_homework / total_values)
print "Lloyd's average homework score equals", average_homework
return average_homework
average(lst)
|
187e1b45780320a6b82df1285d4412ffa3ace32c | MiladDeveloper-Hub/Python-Course-Begginer | /Convertor.py | 321 | 4.125 | 4 | # a km to mile convertor
def hello():
print("\nHello User :)\n\nThis App Convert Km To Mile\n")
hello()
kmInput = float(input("Please enter mile to covert to km : "))
covertedNumber = float(kmInput) / 1.60934
mile = round(covertedNumber, 3)
print(f"\nOk, Converted : {kmInput} Km is {mile} Mile !") |
d3e5d193cf4837cb4a532a1a510f8f4f5a6216af | SivaBackendDeveloper/Python-Assessments | /6.Strings/8qs.py | 222 | 4.03125 | 4 | #startsWith(), endsWith() and compareTo()
str = "Python is high level programming langauge and scripting langauge"
# startswith()
print(str.startswith("Python"))
print("\n")
# endswith
print(str.endswith("langauge"))
|
4c665fe392837d08f795d619b657d695913a0268 | aragar/Python_2013 | /HW4/solution.py | 3,403 | 3.5 | 4 | class InvalidMove(Exception):
pass
class InvalidValue(Exception):
pass
class InvalidKey(Exception):
pass
class NotYourTurn(Exception):
pass
class TicTacToeBoard:
COLUMN_NUMBERS = '321'
ROW_LETTERS = 'ABC'
VALUES = ['X', 'O']
GAME_IN_PROGRESS = 'Game in progress.'
DRAW = 'Draw!'
X_WINS = 'X wins!'
O_WINS = 'O wins!'
BOARD_SIZE = 3
def __init__(self):
self.KEYS = [row + column
for column in self.COLUMN_NUMBERS
for row in self.ROW_LETTERS]
self.board = dict()
self.status = self.GAME_IN_PROGRESS
self.last_move = None
def __getitem__(self, key):
return self.board.get(key, ' ')
def __setitem__(self, key, value):
if key in self.board:
raise InvalidMove
elif key not in self.KEYS:
raise InvalidKey
elif value not in self.VALUES:
raise InvalidValue
elif value == self.last_move:
raise NotYourTurn
else:
self.board[key] = value
self.last_move = value
self.update_game_status()
def update_game_status(self):
if self.status == self.GAME_IN_PROGRESS:
for value in self.VALUES:
if any(len([row + column
for row in self.ROW_LETTERS
if self.board.get(row + column, None) == value]) ==
self.BOARD_SIZE
for column in self.COLUMN_NUMBERS):
self.status = getattr(self, value + '_WINS')
return
elif any(len([row + column
for column in self.COLUMN_NUMBERS
if self.board.get(row + column, None) == value]) ==
self.BOARD_SIZE
for row in self.ROW_LETTERS):
self.status = getattr(self, value + '_WINS')
return
elif len([row + column
for row, column
in zip(self.ROW_LETTERS,
reversed(self.COLUMN_NUMBERS))
if self.board.get(row + column, None) == value]) ==\
self.BOARD_SIZE:
self.status = getattr(self, value + '_WINS')
return
elif len([row + column
for row, column
in zip(self.ROW_LETTERS, self.COLUMN_NUMBERS)
if self.board.get(row + column, None) == value]) ==\
self.BOARD_SIZE:
self.status = getattr(self, value + '_WINS')
return
if len(self.board) == len(self.KEYS):
self.status = self.DRAW
def __str__(self):
return ('\n' +
' -------------\n' +
'3 | {} | {} | {} |\n' +
' -------------\n' +
'2 | {} | {} | {} |\n' +
' -------------\n' +
'1 | {} | {} | {} |\n' +
' -------------\n' +
' A B C \n').format(*[self.board.get(key, " ")
for key in self.KEYS])
def game_status(self):
return self.status
|
e5fc35b71cf3e92c8bc99d7ac5a1678ac97326fc | svetlana-strokova/GB_BigData_1055_Python | /1lesson/1les 5page.py | 808 | 3.921875 | 4 | # 5 Задание
revenue = float(input('Выручка, руб -')) # при вводе int - "обрезается конец" цифры, если есть сотые
loss = float(input('Издержки, руб -'))
profit = revenue - loss # Прибыль
if revenue > loss:
print(f'Фирма получает прибыль {profit}')
print(f'Рентабельность выручки - {profit / revenue:.3f}')
people: int = int(input('Количество сотрудников -'))
peop_prof = profit / people
print(f'Прибыль на одного сотрудника, руб - {peop_prof:.3f} руб')
elif revenue < loss:
print(f'Фирма терпит убытки {-profit}')
else:
print(f"Стабильность - признак мастерства")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.