blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
07e215d9b5600c3d700f224fc2b61524dbd591c2 | ZacJoffe/crackme-scripts | /save_scooby.py | 446 | 3.625 | 4 | #!/usr/bin/env python3
import os
cwd = os.getcwd()
# cwd = cwd.replace("/", "$")
newStr = ""
for char in cwd:
if char == "/":
char = "$"
else:
if ord(char) < ord('a') or ord('z') < ord(char):
if ord('@') < ord(char) and ord(char) < ord('['):
char = chr(ord(char) + 30)
# chr(ord('a')+1)
else:
char = chr(ord(char) - 30)
newStr += char
print(newStr)
|
987c7587fafe205422aea44fb11a6a26b7d46880 | Bal-Mukund/openCV | /cartoon.py | 1,029 | 3.609375 | 4 | import cv2
def nothing(x): #quite does nothing
pass
img = cv2.imread("C:\\Users\\balmu\\OneDrive\\Pictures\\cartoon.jpg") #path of the image
img = cv2.resize(img,None,fx=0.1,fy=0.1)
# creating a trackbar
cv2.namedWindow("cartoon")
cv2.createTrackbar("trackbar","cartoon",1,255,nothing)
while True:
value = cv2.getTrackbarPos("trackbar","cartoon")
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # BGR to gray
gray_blur = cv2.medianBlur(gray,9) # bluring gray image
color_blur = cv2.bilateralFilter(img,9,value,value) #bluring color image
# finding edge of the image
edge = cv2.adaptiveThreshold(gray_blur,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,9,value)
# merging edge and blur image
carton = cv2.bitwise_and(color_blur,color_blur,mask=edge)
# showing all the images
cv2.imshow("image",img)
cv2.imshow("cartoon",carton)
key = cv2.waitKey(100)
if key == ord(" "):
break
cv2.destroyAllWindows()
|
c80352f2d78eb2afa5b55f913e9c35c999bf73bf | Arup276/365Days_Challenge | /#Day_4/codebat.py | 1,315 | 3.625 | 4 | def front_back(str):
len_str = len(str)
if len_str <= 1:
return str
else:
return str[len_str-1]+str[1:len_str-1]+str[0]
def front3(str):
#ln = len(str)
#if ln < 3:
# return str
#else:
return 3*str[:3]
###############################################################################
def string_times(str, n):
return n*str
def front_times(str, n):
return n*str[:3]
def string_bits(str):
#1.############
new_str = ''
len_str = len(str)
i = 0
while len_str > 0:
new_str = new_str+str[i]
i+=2
len_str -=2
return new_str
#2.#############
new_str = ''
len_str = len(str)
for i in range(0,len_str,2):
new_str = new_str + str[i]
return new_str
#3.#############
new_str = ''
len_str = len(str)
for i in range(len_str):
if i%2 == 0:
new_str = new_str +str[i]
return new_str
def string_splosion(str):
new_str = ''
for i in range(len(str)):
new_str = new_str+str[0:i+1]
return new_str
def last2(str):
count = 0
len_str = len(str)
if len_str < 2:
return 0
else:
for i in range(len_str-2):
sub = str[i:i+2]
if sub == str[-2:]:
count +=1
return count
|
da95084765ac532143fcde5ecf6805b3d7736300 | huhuzwxy/leetcode | /Dynamic Programming/53_maximum_subarray.py | 619 | 4.0625 | 4 | # 给定一个数组,返回其最大子数组的和
# Input: [-2,1,-3,4,-1,2,1,-5,4]
# Output: 6
# 思路:
# 加完之后小于当前值,则从该值重新开始加,前面的放弃
# 维护一个max_sum记录当前最大值
class Solution:
def maxSubarray1(self, nums):
sum = max_sum = nums[0]
for i in range(1, len(nums)):
sum = sum + nums[i]
sum = max(sum, nums[i])
max_sum = max(sum, max_sum)
return max_sum
if __name__ == '__main__':
nums = [-2,1,-3,4,-1,2,1,-5,4]
s = Solution()
result = s.maxSubarray1(nums)
print(result)
|
14d7f30c07f8136345c20cd181742ce904b3fd1c | kdrag0n/aoc2020 | /python/day23.py | 1,285 | 3.5 | 4 | #!/usr/bin/env python3
import sys
def ints(itr):
return [int(i) for i in itr]
with open(sys.argv[1], "r") as f:
cups = ints(f.read().replace("\n", ""))
ilist = []
imap = {}
total = 0
result = 0
other = 0
def idx(l, v):
try:
return l.index(v)
except ValueError:
return -1
while True:
for m in range(100):
print(f'-- move {m+1} --')
cur = cups[0]
print('cups:', ' '.join(f'({c})' if c == cur else str(c) for c in cups))
pickup = cups[1:4]
print('pick up:', ', '.join(str(c) for c in pickup))
destl = cups[0] - 1
print(' init dest', destl)
while idx(cups, destl) == -1 or destl in pickup:
print(' cand dest', destl)
if destl in pickup:
destl -= 1
else:
destl = max(cups)
print('destination:', destl)
desti = cups.index(destl)
cups.insert(desti + 1, pickup[2])
cups.insert(desti + 1, pickup[1])
cups.insert(desti + 1, pickup[0])
cups = cups[4:]
cups += [cur]
print()
print("".join(str(c) for c in [*cups[cups.index(1)+1:], *cups[:cups.index(1)]]))
break
print(f"Total: {total}")
print(f"Result: {result}")
print(f"Other: {other}")
|
740c41b1f12bc87e8885a5e511f059f3694ac20c | pamekasancode/Code-Forces-Algorithm | /Python/Helpfull Math.py | 238 | 3.828125 | 4 | def solve():
chars = str(input())
signs = ["+", "-", "/", "*"]
sign = [sign for sign in signs if sign in chars]
if not sign:
return chars
return sign[0].join(sorted(chars.split(sign[0])))
print(solve())
|
2f6ce759502d77f8121c09a014daceebcfd3915a | joestalker1/leetcode | /src/main/scala/common_lounge/Variation.py | 457 | 3.921875 | 4 | def find_pairs(arr, diff):
pairs = 0
i = 0
j = 0
while i < len(arr) and j < len(arr):
while j < len(arr) and abs(arr[j] - arr[i]) < diff:
j += 1
if j < len(arr):
pairs += (len(arr) - j)
i += 1
return pairs
s = input()
arr = s.split()
n = int(arr[0])
k = int(arr[1])
s = input()
arr = s.split()
#arr = [3,1,3]
#k = 1
arr = list([int(a) for a in arr])
arr.sort()
print(find_pairs(arr, k))
|
56482b6d1b784b6135ca00e3fc90e78b34dc3766 | SujanMaga/Python-prac-for-ref. | /test/Conditional_Expression/01_conditional.py | 255 | 4.25 | 4 | a = 45
if(a>4):
print("The value of a is greater than 4")
elif(a>7):
print("The value of a is greater than 7")
else:
print("The value of a is not greater nor lesser than 3 or 7")
# demo syntax
# to check all the statement if if if can be used |
00220f8264c6609477cb8617797664111f9362bd | skyyyylark/hw4_Magomedov_G | /main.py | 641 | 3.734375 | 4 | import random
import calculator
rand_list = []
for i in range(20):
number1 = random.randint(0, 100)
rand_list.append(number1)
num1 = random.choice(rand_list)
num2 = random.choice(rand_list)
num_of_user = int(input())
sum_list = []
for i in range(num_of_user):
num = random.choice(rand_list)
sum_list.append(num)
print(sum_list)
sub = calculator.Substraction()
add = calculator.Addition()
div = calculator.Div()
mul = calculator.Mult()
sub = sub.sub(num1, num2)
div = div.div(num1, num2)
mul = mul.mult(num1, num2)
add = add.add(sum(sum_list))
print(add)
print(sub)
print(div)
print(mul) |
ad8014a1865f256f92244b772a1f833ad84a580d | lorryzhai/test7 | /oh-my-python-master/oh-my-python-master/target_offer/009-用两个栈实现队列(两个队列实现栈)/QueueWithTwoStacks.py | 919 | 3.625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/12/29 16:06
# @Author : WIX
# @File : QueueWithTwoStacks.py
"""
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail
和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。
"""
class Solution:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, node):
self.stack1.append(node)
def pop(self):
if not self.stack2 and not self.stack1:
return None
elif not self.stack2:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
else:
return self.stack2.pop()
s = Solution()
s.push(1)
s.push(2)
s.push(3)
print(s.pop())
s.push(4)
print(s.pop())
print(s.pop())
s.push(5)
print(s.pop())
print(s.pop())
|
dde0844ace3e4dd133ee23ab580fc969d6458e85 | dborski/code_challenges | /camel_case/camel_case_solution.py | 572 | 3.953125 | 4 | def to_camel_case(text):
dash = text.find('-')
underscore = text.find('_')
if dash == -1 and underscore == -1:
return text
elif dash > -1:
new_text = text.replace('-' + text[dash + 1], f'{text[dash + 1]}'.upper(), 1)
return to_camel_case(new_text)
elif underscore > -1:
new_text = text.replace('_' + text[underscore + 1], f'{text[underscore + 1]}'.upper(), 1)
return to_camel_case(new_text)
print(to_camel_case("the-stealth-warrior"))
# returns "theStealthWarrior"
print(to_camel_case("The_Stealth_Warrior"))
# returns "TheStealthWarrior"
|
6c9f0fe9769a0dfd3f7056e975907d1a6f5c305a | RCTom168/Intro-to-Python-1 | /Intro-Python-I-master/src/07_slices.py | 1,128 | 4.53125 | 5 | """
Python exposes a terse and intuitive syntax for performing
slicing on lists and strings. This makes it easy to reference
only a portion of a list or string.
This Stack Overflow answer provides a brief but thorough
overview: https://stackoverflow.com/a/509295
Use Python's slice syntax to achieve the following:
"""
a = [2, 4, 1, 7, 9, 6]
# Output the second element: 4:
print(a[1]) # The number 4 is in the 1 slot
# Output the second-to-last element: 9
print(a[4]) # The number 9 is in the 4 slot
print(a[-2]) # This is more specific to "second-to-last"
# Output the last three elements in the array: [7, 9, 6]
print(a[3:]) # 7, 9, & 6 are in the last 3 slots
# Output the two middle elements in the array: [1, 7]
print(a[2:4]) # 1 & 7 are in slots 2 & 3, 4 isn't counted
# Output every element except the first one: [4, 1, 7, 9, 6]
print(a[1:]) #Starts at the 1 slot and moves forward
# Output every element except the last one: [2, 4, 1, 7, 9]
print(a[:5]) # Starts at the front and stops before the last one
# For string s...
s = "Hello, world!"
# Output just the 8th-12th characters: "world"
print(s[7:12]) |
3724cae8f98320b9e3b16752eb552c06e6987d1e | p4zzz/gitTest | /helloWorld.py | 131 | 3.703125 | 4 | s = "Hello World"
arr = []
for letter in s:
arr.append(letter)
arr = arr[::-1]
r = ''
for item in arr:
r += item
print(r)
|
d2c86733ad4cbb7bc53263c8173eee74c09c4ab7 | SimonGideon/Touch | /Classes.py | 1,067 | 4.15625 | 4 | class Polygon:
def __init__(self, sides, name):
self.sides = sides
self.name = name
square = Polygon(4, "Square")
print(square.sides)
class People:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Heloo my name is " + self.name)
S1 = People("Jayson", 12)
S1.age = 20
print(S1.myfunc())
print(S1.name)
print(S1.age)
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
# Child and parent class.
#Parent Class.
def printname(self):
print(self.firstname, self.lastname)
x = Person("John", "Doe")
x.printname()
# Child class.
class Student(Person):
pass
# 'Pass' used when you do not add any other properties or method to the class.
x = Student("Mike", "Sonko")
x.printname()
"""'__init__() is called automatically every time the class is being used to
create a new object"""
class Student(Person):
def __init__(self, frame, lname):
class Student(Person):
def __init__(self):
|
31d46ac0b438c1435e1a7518bef00cbec740d607 | CafeYuzuHuang/coding | /SameTree.py | 2,248 | 3.78125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
# 2021.03.16
# 1st solution: naive, recursive
"""
if p is None and q is None:
return True
elif p is None or q is None:
return False
if p.val != q.val:
return False
else:
return self.isSameTree(p.right, q.right) and \
self.isSameTree(p.left, q.left)
"""
# 2nd solution: iteration
# https://leetcode.com/problems/same-tree/solution/
# About collections.deque: https://desolve.medium.com/%E5%BE%9E%E9%9B%B6%E9%96%8B%E5%A7%8B%E5%AD%B8python-23-588d3d7475d6
data = deque([(p,q), ])
while data:
p, q = data.popleft()
if not self.checkBTree(p, q):
return False
if p:
data.append((p.left, q.left))
data.append((p.right, q.right))
return True
# 3rd solution: iteration
# Use list instead of deque
"""
data = list([(p,q), ])
while data:
p, q = data.pop(0) # pop the 1st element; i.e. (p, q)
if not self.checkBTree(p, q):
return False
if p:
data.append((p.left, q.left))
data.append((p.right, q.right))
return True
"""
def checkBTree(self, p, q):
if p is None and q is None:
return True
elif p is None or q is None:
return False
if p.val != q.val:
return False
else:
return True
# 1st solution: 28 ms (85%) and 14.2 MB (88%)
# 2nd solution: 32 ms (62%) and 14.1 MB (88%)
# 3rd solution: 28 ms (85%) and 14.4 MB (35%)
# Note:
# Time complexity: O(N) in worst case.
# Space complexity: O(logN) for "balanced tree" and O(N) in worst case.
# Structure to ensure balance: AVL tree, red-black tree, ...
|
83da99625db591e0573c34a75a3b17030b1d9c39 | Thalisson01/Python | /Exercício Python #079 - Valores únicos em uma Lista.py | 585 | 3.84375 | 4 | n = list()
cont = 0
while True:
nv = int(input('Digite um valor: '))
if cont == 0:
n.append(nv)
else:
while nv in n:
print('Este valor já existe na lista, tente novamente!')
nv = int(input('Digite um valor: '))
n.append(nv)
escolha = str(input('Deseja digitar outro valor? [S/N]: ')).strip()
while escolha not in 'SsNn':
print('Opção inválida!')
escolha = str(input('Deseja digitar outro valor? [S/N]: ')).strip()
if escolha in 'Nn':
break
cont += 1
n.sort()
print(f'{n}') |
671ac59582797037b7c19d0bee325d56d2e781c6 | ssbbkk/Python-scripts | /words.py | 449 | 4.0625 | 4 | import scrabble
letters = "abcdefghijklmnopqrstquwxyz"
def has_a_double(letter):
for word in scrabble.wordlist:
if letter + letter in word:
return True
return False
for letter in letters:
if not has_a_double(letter):
print(letter + " never appeard doubbled")
# Print all words containing letters in " " statement
#for word in scrabble.wordlist:
# if "aa" in word and "ee" in word:
# print(word)
|
ff06dd9d854d0c636d79599ded1e62c2be153700 | pedestrianlove/10901_Python_THU | /HW/HW3/3.2/30.py | 551 | 3.671875 | 4 | # for formatting purpose
class underline:
start = '\033[04m'
end = '\033[0m'
# input
hourly_wage = eval ( input ("Enter hourly wage: " + underline.start))
print (underline.end, end='')
working_hours = eval ( input ("Enter number of hours worked: " + underline.start))
print (underline.end, end='')
# output
print ("Gross pay for week is ", end='')
if (working_hours <= 40) :
print ("${:.2f}.".format (working_hours * hourly_wage))
else :
print ("${:.2f}.".format ((40 * hourly_wage) + (1.5 * (working_hours - 40) * hourly_wage)))
|
b0cde6b41bb5500669ebce30cfd2a977ca19c3c1 | joschi127/tugger | /lib/tugger-container-init/json-merge.py | 833 | 3.515625 | 4 | #!/usr/bin/python2.7
# merge two json files, given as command line arguments, and output merged json data
import sys
from pprint import pprint
import json
def merge_recursively(a, b, path=None):
"merges b into a"
if path is None: path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge_recursively(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
pass # same leaf value
else:
a[key] = b[key]
else:
a[key] = b[key]
return a
json_file=open(sys.argv[1])
data = json.load(json_file)
json_file2=open(sys.argv[2])
data2 = json.load(json_file2)
merged = merge_recursively(data, data2)
json.dump(merged, sys.stdout)
json_file.close()
json_file2.close()
|
723fc61188d10a22d09fceb9c5b4fbdbacad720a | jsourabh1/Striver-s_sheet_Solution | /Day-16_String2/question1_z_function.py | 547 | 3.5 | 4 | def solve(string):
# print(string)
z=[0]*len(string)
n=len(string)
first=end=0
for i in range(1,len(string)):
flag=False
if i<=end:
z[i]=min(end-i+1,z[i-first])
while i+z[i]<n and string[z[i]]==string[z[i]+i]:
flag=True
z[i]+=1
if i+z[i]-1>end and flag:
first=i
end=i+z[i]-1
# print(z)
return z
def helper(text):
string=text
n=len(string)
arr=solve(string)
for i in range(n):
if (arr[i] + i == n and n % (n - arr[i]) == 0):return True
return False
text = "abcabcabcabc"
print(helper(text))
|
d98722c8416a1ca2880eda4ebb4418767066e22d | OWAISIDRISI53/Password-Cracker-by-Owais-Idrisi | /PasswordCracker.py | 1,234 | 3.796875 | 4 | # PASSWORD CRACKER
from random import *
import time
time.sleep(1)
print("""
░█████╗░░██╗░░░░░░░██╗░█████╗░██╗░██████╗
██╔══██╗░██║░░██╗░░██║██╔══██╗██║██╔════╝
██║░░██║░╚██╗████╗██╔╝███████║██║╚█████╗░
██║░░██║░░████╔═████║░██╔══██║██║░╚═══██╗
╚█████╔╝░░╚██╔╝░╚██╔╝░██║░░██║██║██████╔╝
░╚════╝░░░░╚═╝░░░╚═╝░░╚═╝░░╚═╝╚═╝╚═════╝░
""")
time.sleep(0.5)
user_pass =input("Enter Your Password : ")
Password = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
guess = ""
while(guess!=user_pass) :
guess = ""
for letter in range(len(user_pass)) :
guess_letter = Password[randint(0,25)]
guess = str(guess_letter)+ str(guess)
print(guess)
print("Yuor Password is ",guess)
|
e39d00a8d6e7bdc06478e8b4bf31c1a1d9c02b29 | TheRenegadeCoder/sample-programs | /archive/p/python/duplicate_character_counter.py | 424 | 3.703125 | 4 | import sys
if len(sys.argv) != 2 or not sys.argv[1]:
print("Usage: please provide a string")
sys.exit()
counter = dict()
dupes = False
for char in sys.argv[1]:
counter.setdefault(char, 0)
counter[char] += 1
if counter[char] > 1:
dupes = True
if dupes:
for key, value in counter.items():
if value > 1:
print(f"{key}: {value}")
else:
print("No duplicate characters")
|
db0d979c785c24607f9674740544b9c77586174f | Blossomyyh/leetcode | /Permutation.py | 3,231 | 4.125 | 4 | """
46 permutations
first of all there is no efficient way to do it
it has to be brute force
we're just going to generate every single combination
let's take look at this one
[1,2,3]
you have 3 spots
and the first element/ scenario you can have up to 3 different numbers
second - 2, last position - only one number
this is known as *factorial*
then it's like N times N minus 1 times N-2 ... until you get to one
we gonna do here is use backtracking
traversal this path and get the combination
then we have to go back and try
first and another branch and go back to the top and go down to the next value
likewise go up and down
so the code to write this out is that you just do an iteration
So we need to take just one of the values and then remove that
from the set of potential candidates for the next iteration
for..... one way we can do this is we could swap a value -- perform swap, right?
swap(start, i) and swap the index at, say the start index and index of i
and then we just call f(n) again, and we pass the start and the index + 1 right?
so we move the start index up by 1.
and then at the end of that, we swap it back.
that's pretty much what the algorithms looks like in pseudo-code
you just go through each element, transfer up into the front
and then you need to call[f(n)] for the subsequent elements, processing the rest of the array
tying to swap those elements and then for the base case, you would say,
if ever the start index equals the end, so you reach the end of the array, then you found one combination and you are just
return the array you have
so the return value of this is going to be an array of these numbers.
"""
class Solution:
# swap / get list / swap
# backtracking
""" distinct integers"""
"""interation version"""
def permutationHelper(self, nums, start=0):
if start == len(nums) - 1:
return [nums[:]]
res = []
for i in range(start, len(nums)):
# self.swap(nums, start, i)
nums[start], nums[i] = nums[i], nums[start]
res += self.permutationHelper(nums, start + 1)
nums[start], nums[i] = nums[i], nums[start]
return res
def permutation1(self, nums):
return self.permutationHelper(nums, 0)
"""
choose from left numbers
"""
# principle is pretty similar but for this, you pass in the numbers that are valid for use
# then you constructing this value array that you go through
"""iteration version"""
def permutation1noswap(self, nums, values=[]):
if not nums:
return [values]
res = []
for i in range(len(nums)):
res += self.permutation1noswap(nums[:i] + nums[i+1:],values + [nums[i]] )
return res
"""recursive version"""
def permutation1noswaprec(self, nums):
res = []
stack = [(nums, [])]
while(len(stack)):
nums, values = stack.pop()
if not nums:
res += [values]
"""range(len(nums)) not nums!!!!"""
for i in range(len(nums)):
stack.append((nums[:i]+nums[i+1:], values + [nums[i]]))
return res
print( Solution().permutation1noswaprec([1, 2, 3]))
|
d330c1d5f73c1b612342234bc90c3f2be4b45e81 | ShahShailavi/Back-End-MicroService-Using-Load-Balancer | /comment_database.py | 614 | 3.609375 | 4 | import sqlite3
connection = sqlite3.connect('comment_database.db')
c=connection.cursor()
c.execute("""create table if not exists comments_table (comment_id INTEGER PRIMARY KEY AUTOINCREMENT,
comment text,
username TEXT,
article_id INTEGER,
article_title TEXT,
article_author TEXT,
createdDate text)""")
connection.commit()
connection.close()
|
34746a351b278858661170b6fda6eb4568f709ee | busterguy26/devpy | /base_type/Example.py | 885 | 4.09375 | 4 | def simple_sort(data: object) -> object:
"""
Sort list of ints without using built-in methods.
Examples:
simple_sort([2, 9, 6, 7, 3, 2, 1])
>>> [1, 2, 2, 3, 6, 7, 9]
Returns:
"""
sorted_list = []
if isinstance(data, list):
for i in data:
if not isinstance(i, int):
# print(i)
raise ValueError("You have a wrong value")
if isinstance(data, list):
if isinstance(data, list):
if isinstance(data, list):
if isinstance(data, list):
del data[k]
print(data)
print(sorted_list)
#else:
#n = 0
#while
print(sorted_list)
return sorted_list if isinstance(data, list): if isinstance(data, list):
print(simple_sort([1, 2, 10, 6, 50, 20, 2]))
|
58418906ff38095da3f8fe3bcaa84dfc3cdaef98 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4153/codes/1674_1100.py | 632 | 3.734375 | 4 | # Teste seu código aos poucos.
# Não teste tudo no final, pois fica mais difícil de identificar erros.
# Ao testar sua solução, não se limite ao caso de exemplo.
vdc = int(input("Insira o valor da cedula: "))
print("Entrada:", vdc)
if((vdc != 2) and (vdc != 5) and (vdc != 10) and (vdc != 20) and (vdc != 50) and (vdc != 100)):
print("Animal: Invalido")
elif(vdc == 2):
print("Animal: Tartaruga")
elif(vdc == 5):
print("Animal: Garca")
elif(vdc == 10):
print("Animal: Arara")
elif(vdc == 20):
print("Animal: Mico-leao-dourado")
elif(vdc == 50):
print("Animal: Onca-pintada")
elif(vdc == 100):
print("Animal: Garoupa")
|
b787d5796db4ef7cfaf71d448bf81c2e6fe55582 | akerem16/basic-calculator-git-en-tr | /main.py | 1,543 | 4.3125 | 4 | # Basic calculator in python 3.6
# Made in Turkey
# By akerem16
# [EN] First we will get number of operations. We will run the code block according to what action will be taken.
# [TR] ilk önce işlem numarasını almamız gerekiyor. Hangi işlem yapılacaksa ona göre kod bloğu çalıştıracağız.
operationnumber = str(input("""
[EN]
Hello i am a basic calculator!
Thanks to me, you can quickly do the following:
1- Addition (+)
2- Subtraction (-)
3- Multiplication (*)
4- Division (/)
5- Get power (^^)
0- Exit code
[TR]
Merhaba. Ben basit bir hesap makinesiyim!
Benim sayemde aşağıdakileri işlemleri hızlıca yapabilirsiniz:
1- Toplama (+)
2- Çıkarma (-)
3- Çarpma (*)
4- Bölme (/)
5- Üssünü alma (^^)
0- Çıkış
Your choice: """))
# [EN] Now we define operations according to the selection made.
# [TR] Şimdi yapılan seçime göre işlemleri tanımlıyoruz.
if operationnumber == "1":
print("Result:", int(input("Number 1: ")) + int(input("Number 2: ")))
elif operationnumber == "2":
print("Result:", int(input("Number 1: ")) - int(input("Number 2: ")))
elif operationnumber == "3":
print("Result:", int(input("Number 1: ")) * int(input("Number 2: ")))
elif operationnumber == "4":
print("Result:", int(input("Number 1: ")) / int(input("Number 2: ")))
elif operationnumber == "5":
print("Result:", int(input("Number 1: ")) ** int(input("Number 2: ")))
elif operationnumber == "0":
exit()
else:
print("[EN] Wrong choice entered.")
print("[TR] Hatalı giriş yapıldı.")
exit() |
2859d064b6a5630856dfe99220f4428063876fb3 | Danielcormar/programaci-n-python | /laboratorio3/ejercicio4.py | 89 | 3.8125 | 4 | x=input("dame un numero ")
if x%2==0:
print "es par"
else:
print "es impar"
|
48af33aac0268086658157aecf14351010172ef7 | worthurlove/python_work | /SA18225511-zhengjie-2.1.py | 611 | 4.0625 | 4 | # Function:accept a quiz score as an input and prints out the corresponding grade
#Author:worthurlove
#Date:2018.10.8
score_grade = {5: 'A', 4: 'B', 3: 'C', 2: 'D', 1: 'E', 0: 'F'}
'''
定义数据字典,将测试分数与成绩一一对应
'''
def get_grade(score_grade):
score = int(input('请输入0到5之间的测试分数:'))
if (score < 0 | score > 5):
print("请输入合法分数")
'''
对输入进行合法性判断
'''
else:
print('成绩为:' + score_grade[score])
'''
输出对应成绩
'''
get_grade(score_grade) |
8150a81a72c29fad6b8101b2129acdee547d29ab | wenxinjie/leetcode | /String/python/leetcode14_Longest_Common_Prefix.py | 870 | 3.921875 | 4 | # Write a function to find the longest common prefix string amongst an array of strings.
# If there is no common prefix, return an empty string "".
# Example 1:
# Input: ["flower","flow","flight"]
# Output: "fl"
# Example 2:
# Input: ["dog","racecar","car"]
# Output: ""
# Explanation: There is no common prefix among the input strings.
class Solution(object):
def longestCommonPrefix(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
if not strs:
return ""
strs.sort()
a, b = strs[0], strs[-1]
for i in range(len(a)):
if b[i]!=a[i]:
return a[:i]
return a
# Time: O(1)
# Space: O(1)
# Difficulty: easy
# you only need to compare the first one and the last one after sorting, since there are most difference between those two. |
185eb00177e3cc58c2d62ef33ba8589688ea8993 | uvenil/PythonKurs201806 | /___Python/Carsten/p07_file_io/m01_count_files.py | 431 | 3.578125 | 4 | from pathlib import Path
# Zähle die Anzahl Ordner in einerm Ordner (inkl. aller Unterordner)
def count_dirs(path):
subdirs = [subdir for subdir in path.iterdir() if subdir.is_dir()] # Bestimme die direkten Unterordner des Ordners path
print(subdirs)
count = 0
for subdir in subdirs:
count += count_dirs(subdir)
return count + 1
count = count_dirs(Path("O:\___python"))
print(count)
|
730d258c6f4821206d8abff023f5ad58e0736502 | BerilBBJ/scraperwiki-scraper-vault | /Users/P/pathipati/ukcartaxband.py | 2,740 | 3.578125 | 4 | import scraperwiki
from BeautifulSoup import BeautifulSoup
def scrape_table(soup):
#to define coloumns name used in table
scraperwiki.sqlite.save('data_columns', ['Authority', 'Avg sync speed (Mbit/s)',\
' % not rece - iving 2Mbit/s ',\
'Super fast broad - band availa - bility (%)','Take -up (excluding super - fast broad - band) (%)','Overall score'])
table = soup.find("table", {"class": "in-article sortable"})
#To each row of table is selected
rows = table.findAll("tr")
for row in rows:
record = {}
#To select table row cells
table_td = row.findAll("td")
#Each row include six cells
if len(table_td) == 6:#Cross checking
record['Authority'] = table_td[0].text
record['Overall score'] = table_td[5].text
print record,
print "-" * 10
#Save data step by step
scraperwiki.sqlite.save(["Authority"], record)
#website link
Website = 'http://www.guardian.co.uk/news/datablog/2011/jul/06/uk-broadband-internet-speed-by-area'
html = scraperwiki.scrape(Website)
soup = BeautifulSoup(html)
scrape_table(soup)
import scraperwiki
from BeautifulSoup import BeautifulSoup
def scrape_table(soup):
#to define coloumns name used in table
scraperwiki.sqlite.save('data_columns', ['Authority', 'Avg sync speed (Mbit/s)',\
' % not rece - iving 2Mbit/s ',\
'Super fast broad - band availa - bility (%)','Take -up (excluding super - fast broad - band) (%)','Overall score'])
table = soup.find("table", {"class": "in-article sortable"})
#To each row of table is selected
rows = table.findAll("tr")
for row in rows:
record = {}
#To select table row cells
table_td = row.findAll("td")
#Each row include six cells
if len(table_td) == 6:#Cross checking
record['Authority'] = table_td[0].text
record['Overall score'] = table_td[5].text
print record,
print "-" * 10
#Save data step by step
scraperwiki.sqlite.save(["Authority"], record)
#website link
Website = 'http://www.guardian.co.uk/news/datablog/2011/jul/06/uk-broadband-internet-speed-by-area'
html = scraperwiki.scrape(Website)
soup = BeautifulSoup(html)
scrape_table(soup)
|
01943ae3760b723e61111f4add3ee3da3c2e5315 | forget726/PythonBase | /画图实例.py | 266 | 3.796875 | 4 | import turtle
p = turtle.Pen()
turtle.bgcolor("black")
sides = 7
colors = ["red","orange","yellow","green","cyan","blue","purple"]
for x in range(360):
p.pencolor(colors[x%sides])
p.forward(x*3/sides+x)
p.left(360/sides+1)
p.width(x*sides/200)
done() |
7818a58b12e6d72299d277f6871b8982f0a23ae7 | samsepiolc64/codewars | /uniqueinorder/uniqueinorder.py | 612 | 3.59375 | 4 | def unique_in_order(iterable):
#print(sorted(set(list(li))))
iterable = list(iterable)
dl = len(iterable)
new = []
i = 0
j = 1
while j <= dl:
tmp = iterable[i]
if j < dl:
if (tmp != iterable[j]) :
new.append(tmp)
i = j
else:
new.append(tmp)
j += 1
print(new)
#result = []
#prev = None
#for char in iterable[0:]:
# if char != prev:
# result.append(char)
# prev = char
#print(result)
order = "AAAABBBCCDAABBB"
unique_in_order(order) |
1ccc9715499668c4b22b62e294f6998c34df9e39 | hkristof03/GoogleFooBar | /lvl2/Task2.2/solution.py | 1,255 | 3.578125 | 4 | from collections import Counter
def numberToBase(n, b):
""""""
if n == 0:
return [0]
digits = []
while n:
digits.append(str(int(n % b)))
n //= b
return digits[::-1]
def assign_tasks(n, b):
""""""
k = len(n)
x = sorted(n, reverse=True, key=int)
x = ''.join(x)
y = sorted(n, key=int)
y = ''.join(y)
x_int = int(x, b)
y_int = int(y, b)
z = x_int - y_int
z = ''.join(numberToBase(z, b))
diff = k - len(z)
if diff:
z = '0'* diff + z
return z
def solution(n, b):
""""""
assert (b >= 2) and (b <= 10)
assert (len(n) >= 2) and (len(n) <= 9)
if len(set(n)) == 1:
return 1
l = []
while True:
n = assign_tasks(n, b)
l.append(n)
d_ = dict(Counter(l))
frequencies = sorted(d_.values(), reverse=True)
if frequencies[0] > 2:
length = frequencies.count(2)
cycle_length = length + 1 if length else 1
return cycle_length
if __name__ == '__main__':
assert solution('210022', 3) == 3
assert solution('1211', 10) == 1
assert solution('1111', 10) == 1
assert solution('0000', 10) == 1
assert solution('210022', 3) == 3
|
8776b5691db0f6e6796cf9505ee769eff8acb44c | Neal5580/python_exercises | /capitalize/index.py | 849 | 3.796875 | 4 | # Solution 1
# def capitalize(str):
# words = []
# for item in str.split():
# firstChar = item[0].upper()
# # if len(item) > 1:
# # words.append(firstChar + item[1::])
# # else:
# # words.append(firstChar)
# words.append(firstChar + item[1::] if len(item) > 1 else firstChar)
# p = ' '.join(words)
# print(p)
# return
#Solution 2
def capitalize(str):
words = [str[0].upper()]
index = 1
while index < len(str):
# if str[index - 1] == ' ':
# words.append(str[index].upper())
# else:
# words.append(str[index])
words.append(str[index].upper() if str[index - 1] == ' ' else str[index])
index += 1
p = ''.join(words)
print(p)
return
capitalize('a short sentence') |
a725aa2dbe87f4bfb8480c519a6db75f3fb155f8 | adamh17/ca318-Advanced-Algorithms-and-AI-Search | /Week 3 - Improving Brute Force/heuristic.py | 519 | 3.90625 | 4 | def h(start, goal):
assert "".join(sorted(start)) == " 12345678" and "".join(sorted(goal)) == " 12345678"
# Work out the manhattah distance of each tile from its eventual goal
sboard = [int(num) if num != " " else 0 for num in start]
gboard = [int(num) if num != " " else 0 for num in goal]
manhattan_distance = 0
for s,g in ((sboard.index(i), gboard.index(i)) for i in range (1,9)):
manhattan_distance += abs(s % 3 - g % 3) + abs(s // 3 - g // 3)
return manhattan_distance
|
fc6d1a25f50df37ab3ca2520effb126a1654ffa9 | mindful-ai/oracle | /amstar-03/day_02/code/loop_else_block_demo.py | 1,055 | 4.125 | 4 | # PROJECT A
# Detecting if a number is prime or not
'''
for <var> in <iter>:
<statements>
else:
<statements>
while <condition>:
<statements>
else:
<statements>
Loop exits because of two scenarios:
1. elements in the <iter> is exhausted, or
<condition> becomes false (NATURAL EXIT)
2. Loop can also exit because of the break statement
If the loop exits naturally, statements under else
block will execute once
If the loop exits because of a break statement,
then statements under else block will not be executed
'''
# Program to find out if a number is prime
# input
n = int(input('Enter a number: '))
'''
# process
prime = True
for i in range(2, n):
if(n % i == 0):
prime = False
break
# output
if(prime): # prime == True
print('The number is prime')
else:
print('The number is not prime')
'''
for i in range(2, n):
if(n % i == 0):
print('The number is not prime')
break
else:
print('The number is prime')
|
8ad654321cceeeb0b61178d7580a23d26281ef41 | Larissa-D-Gomes/CursoPython | /introducao/exercicio040.py | 989 | 4.0625 | 4 | """
EXERCÍCIO 040: Aquele Clássico da Média
Crie um programa que leia duas notas de um aluno e calcule sua média,
mostrando uma mensagem no final, de acordo com a média atingida:
- Média abaixo de 5.0: REPROVADO
- Média entre 5.0 e 6.9: RECUPERAÇÃO
- Média 7.0 ou superior: APROVADO
"""
def main():
try:
primeira_nota = float(input('Digite a primeira nota: ').replace(',','.'))
segunda_nota = float(input('Digite a segunda nota: ').replace(',','.'))
if primeira_nota >= 0.0 and segunda_nota >= 0.0:
media = (primeira_nota + segunda_nota)/2.0
if media < 5.0:
print('Media abaixo de 5.0: REPROVADO')
elif media >= 7.0:
print('Media 7.0 ou superior: APROVADO')
else:
print('Media entre 5.0 e 6.9: RECUPERAÇÃO')
else:
raise ValueError
except ValueError:
print('Dado invalido.')
if __name__ == '__main__':
main()
|
eb9270b2b5d6acd78bd896cf367accc9d57989a0 | allisonlynnbasore14/SlotGame | /slotmachine.py | 2,377 | 3.859375 | 4 |
import random
def main():
#pygame.init()
slot_machine = SlotMachine()
slot_machine.startGame()
class SlotMachine:
def __init__(self):
# Make the starting information like possible bets icons jackpot etc.
self.icons = []
self.createIcons()
def startGame(self):
self.setStartingValues()
gameisGoing = True
while(gameisGoing):
print("The Game is starting")
print("1: Set Bet")
print("2: Spin")
print("3: Quit")
selection = raw_input(">>> ")
if (selection == "1"):
self.setBet()
elif (selection == "2"):
self.spin()
elif (selection == "3"):
gameisGoing = False
else:
print("Invalid Value entered")
def setStartingValues(self):
self.bet = 0
self.money = 1000
self.JackPot = 1000000
self.numberOfWheels = 10
self.numberOfIcons = 10
def setBet(self):
# setting a bet with 6 options
# Take money out of account
# Keep track of the amount for bet in game state?
betSelected = False;
betOptions = [1 , 10, 25, 50, 100, 200]
print("What would you like to bet?")
for i in range(len(betOptions)):
print(str(betOptions[i]))
selection = raw_input(">>> ")
for i in range(len(betOptions)):
if (selection == str(betOptions[i])):
self.bet = selection
betSelected = True
if(betSelected == False):
print("Invalid Value entered")
def spin(self):
# pay
# change the jackpot
# spin for things
self.pay()
self.increasePot()
spinResults = []
payouts = {}
for i in range(self.numberOfWheels):
val = random.randint(1, self.numberOfIcons)
spinResults.append(val)
if(val in payouts):
payouts[val] = payouts[val] + 1
else:
payouts[val] = 0
total = 0
for m in payouts:
total += payouts[m]
self.money += total*int(self.bet)
# For now, if any values match each other then it is 1 buck times thier bet
def pay(self):
self.money = self.money - int(self.bet)
def increasePot(self):
self.JackPot = self.JackPot + random.randint(100, 1000)
def createIcons(self):
self.icons.append(Icon("Bob","blue")) # make the icon with an icon object
self.icons.append(Icon("Sam","red")) # make the icon with an icon object
self.icons.append(Icon("Kim","yellow")) # make the icon with an icon object
class Icon:
def __init__(self, name, color):
self.name = name
self.color = color
if __name__ == "__main__": main() |
6c514831626be7f8efba510eb7d0f1a5a5e4dcfa | JoshuaPMallory/DS-Unit-3-Sprint-2-SQL-and-Databases | /module5-sprint2-sql-and-databases/northwind.py | 2,323 | 3.78125 | 4 | import sqlite3
import SQL
parttwo = SQL.SQL('northwind_small.sqlite3')
questions = ['What are the ten most expensive items (per unit price) in the database?'
,'What is the average age of an employee at the time of their hiring?'
,'What are the ten most expensive items (per unit price) in the database *and* their suppliers?'
,'What is the largest category (by number of unique products in it)?'
]
answers = []
# What are the ten most expensive items (per unit price) in the database?
answers.append(parttwo.query('''
SELECT
UnitPrice
FROM
Product
ORDER BY
UnitPrice DESC
LIMIT
10
'''))
# What is the average age of an employee at the time of their hiring?
# (Hint: a lot of arithmetic works with dates.)
answers.append(parttwo.query('''
SELECT
AVG(HireDate - BirthDate)
FROM
Employee
''')[0][0])
num = 0
running = True
# What are the ten most expensive items (per unit price) in the database *and* their suppliers?
answers.append(partthree.query('''
SELECT
UnitPrice, ProductName, CompanyName
FROM
Product
INNER JOIN
Supplier on Product.SupplierID
GROUP BY
ProductName
ORDER BY
UnitPrice DESC
LIMIT
10
'''))
# What is the largest category (by number of unique products in it)?
# After all my work, all I can concluse after searching dozens of questions online is that SQL has no built in method of grabbing the fucking headers
# SQL also doens't understand that I can't to grab CategoryID, which is somehow both listed inside the table, yet also is ungrabbable
# What this is doing is multiplying all of the category data across all other information, whcih makes it impossible to get anything but exactly the same information everywhere.
# The only way then to actually grab the headers is to go outside the code and look it up either inside the file or in a database viewer.
# SQL is an awful language and needs to be replaced.
answers.append(partthree.query('''
SELECT
CategoryName, COUNT(ProductName)
FROM
Product
LEFT JOIN
Category on Product.CategoryID = Category.ID
GROUP BY
CategoryName
ORDER BY
COUNT(ProductName) DESC
LIMIT 1
''')[0])
while running:
print(questions[num], '\n', answers[num], '\n')
num += 1
if num == len(questions):
running = False
|
1ffb4bc2c39bddeaab891cad34c01fb3c9ee7324 | aliceKatkout/ExoCode | /niveau1.py | 216 | 3.828125 | 4 | mot = input("Ecris un mot :")
def solution(mot):
lettres = list(mot)
lettres.reverse()
mirror ="".join(lettres)
return mirror
resultat =solution(mot)
print("le mot à l'envers est "+resultat+" !")
|
41d0d1116ee62f9152ef29a392f07e4f1b0ee12b | Sivaramkrishna1/Python_basic_programms | /valid_email.py | 266 | 3.59375 | 4 | import re
regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'
n=int(input('enter num:'))
print(n)
guess_count=0
while guess_count < n:
valid_email=input('')
guess_count+=1
if (re.search(regex,valid_email)):
print(valid_email)
|
987d231d0cc82ea9167342a7a1cff6cd65abe304 | jaehyun02px2021/PythonGrammar | /Class/hotandcold.py | 1,042 | 3.875 | 4 | #working code 1 : problem is that we don't check if the value is in the range once we put a right input.
# answer = 63
# inputNumber = int(input())
#
# if inputNumber > 0 and inputNumber < 100:
# if inputNumber == answer:
# print ("Correct Answer")
# while inputNumber - answer:
# if answer - inputNumber < 0:
# print ("hot")
# elif answer - inputNumber > 0:
# print ("cold")
# inputNumber = int(input())
# if inputNumber == answer:
# print ("Correct Answer")
# else:
# print ("Wrong Input")
# Working Code 2: Problem Solved...
answer = 63
inputNumber = int(input())
while inputNumber - answer:
if inputNumber > 0 and inputNumber < 100:
if answer - inputNumber < 0:
print ("hot")
elif answer - inputNumber > 0:
print ("cold")
inputNumber = int(input())
if inputNumber == answer:
print ("Correct Answer")
else:
print ("Wrong Input")
inputNumber = int(input())
|
82209e19ec217ef054ceec745a085fc78f880889 | gjw199513/mkw-pythonsz | /chapter3/4.demo.py | 913 | 3.921875 | 4 | # -*- coding:utf-8 -*-
__author__ = 'gjw'
__time__ = '2018/1/18 0018 下午 4:32'
# 3-4 如何进行反向迭代以及如何实现反向迭代
l = [1, 2, 3, 4, 5]
"""
使用reverse方法实现改变原来的列表
使用反向切片浪费空间
使用revered内置函数较为合适
"""
for x in reversed(l):
print(x)
print()
print()
class FloatRange:
def __init__(self, start, end, step=0.1):
self.start = start
self.end = end
self.step = step
# 正向迭代
def __iter__(self):
t = self.start
while t <= self.end:
yield t
t += self.step
# 反向迭代
def __reversed__(self):
t = self.end
while t >= self.start:
yield t
t -= self.step
for x in FloatRange(1.0, 4.0, 0.5):
print(x)
print()
print()
for x in reversed(FloatRange(1.0, 4.0, 0.5)):
print(x) |
181b324a8d592953290bd28ec9a56369053597c0 | tymancjo/Game-Of-Life | /GOL.py | 5,537 | 4.03125 | 4 | # This is my quick project idea
# A Game Of Life implementation
# Done just for fun andPython training
# the general idea comes form classic:
# https://pl.wikipedia.org/wiki/Gra_w_%C5%BCycie
# plan to work it out as pythonic as possible :)
# one: play around with numpy arrays to understood it deeply
# pygame: used for the visual presentation of the system
# let's import the numpy library
import numpy as np
# and stuff for drawing
import pygame, sys
from pygame.locals import *
from datetime import datetime as dt
# pre start stuff
NOW = dt.now()
# some variables for general setup
# sizes of the world:
sizeX = 128 // 3
sizeY = 60 // 3
# display resolution
width = 1280
height = 720
# height = int((sizeY / sizeX) * width) + 100
# size for the drawed rectangle
size = int(min(width / sizeX, height / sizeY))
# centering display
offsetX = int((width - size*sizeX) / 2)
offsetY = int((height - size*sizeY) / 2)
# generating the start status of the world
world_now = np.random.randint(2, size=(sizeY, sizeX))
generation = 0
# print('Initial world state:')
# print(world_now)
# getting the size of the world array
R, C = world_now.shape
# now lets go thru the world array
# and proceed with the GOL algorithm
# sum 2 or 3 - keep alive if alive
# sum 3 - born if death
# defined functions
def subarraysum(array, x, y):
'''This is summing the value around given place in array
for the game of life algorithm
Inputs:
array - 2D the array we are working on
x,y - col, row coordinates of theanalyzed point
return:
sum of point neighbors
'''
# limiting to the array size
r, c = array.shape
x = min(max(x,0),c - 1)
y = min(max(y,0),r - 1)
return sum(sum(array[max(y-1,0):min(y+2,r), max(x-1,0):min(x+2,c)])) - array[y,x]
def gen(world_now):
'''This is the Game Of Life single generation function.
Input:
world_now - the 2D numpy array of the current world status
Output:
numpy array of the world status after single generation'''
global generation
# lets keep the current state as next one
world_next = np.array(world_now)
# lets normalize world_now
world_now = np.nan_to_num(world_now / world_now)
# lets analyze
for x in range(C):
for y in range(R):
suma = subarraysum(world_now, x, y)
current = world_next[y,x]
if current and 2 <= suma <= 3: # we survive
world_next[y,x] = min(255, world_next[y,x]+1)
elif not current and suma == 3: # we get born
world_next[y,x] = 1
else: # we die
world_next[y,x] = 0
# we bring back the world status to world now
world_now = np.array(world_next)
generation += 1
return world_now
# print(f'World of {generation}:')
# print(world_now)
def main():
global world_now,NOW
pygame.init()
DISPLAY=pygame.display.set_mode((width,height),0,32)
BCK=(128,128,128)
BLUE=(0,0,255)
active = True
setOnMouse = False
mouseValue = 1
drawstep = 1
step = 0
while True:
step += 1
if not active:
BCK = (25,25,25)
else:
BCK = (128,128,128)
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
NOW = (dt.now() - NOW).total_seconds()
print(f'Genertions: {generation}, in {NOW}, so: {generation / NOW} gen/s')
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mx, my = event.pos
mc = int((mx - offsetX)/(size))
mr = int((my - offsetY)/(size))
if 0 <= mc < C and 0 <= mr < R:
setOnMouse= True
pressed1, pressed2, pressed3 = pygame.mouse.get_pressed()
if pressed1:
mouseValue = 1
else:
mouseValue = 0
elif mr >= R:
active = not active
else:
if not active:
world_now = np.zeros((R,C))
elif event.type == pygame.MOUSEBUTTONUP:
setOnMouse = False
elif event.type == pygame.KEYDOWN:
if not active and event.key == pygame.K_SPACE:
world_now = gen(world_now)
elif event.key == pygame.K_r:
world_now = np.zeros((R,C))
active= False
elif event.key in [pygame.K_s, pygame.K_g]:
active = not active
if setOnMouse:
mmx, mmy = pygame.mouse.get_pos()
mmc = max(0,min(C-1,int((mmx - offsetX)/(size))))
mmr = max(0,min(R-1,int((mmy - offsetY)/(size))))
world_now[mmr, mmc] = mouseValue
if not (step % drawstep):
step = 0
DISPLAY.fill((BCK))
for x in range(C):
for y in range(R):
color = (166,166,166)
if world_now[y,x]:
color = (255-world_now[y,x],255-int(world_now[y,x]/2),world_now[y,x])
pygame.draw.rect(DISPLAY,color,(offsetX + size*x+1, offsetY + size*y+1,size-1,size-1))
if active:
world_now = gen(world_now)
pygame.display.update()
main()
|
2d089d9d2eb46d07f1f16097417b5286e70cf1b9 | nuydev/my_python | /Basic_Data_Type_Variable.py | 364 | 3.859375 | 4 | #DataType & Variable
#ชื่อตัวแปร = ค่าที่เก็บในตัวแปร
x = 10
print(x)
print('ผลลัพธ์ =', x)
print(type(x))
print('ผลลัพธ์ ='+ str(x)) #แปลง String
y=3.645
z=True
print(y)
print(type(y))
print(z)
print(type(z))
a = 'Teerawat'
print(a)
print(a,a)
print(a+a)
print(type(a)) |
eb489b2f313f4517c9593eb06b9a36e34de5c4f9 | frankad/python | /python/Dra.py | 10,735 | 3.953125 | 4 | # Name: Fentahun Reta
# Date: 10/15/15
# Dicription: This program demonstrates drawing shapes on a canvas using
# some Gui tools. It is not interactive. It draws the same picture
# every time it is executed. To run this program, you must save the
# file Gui3.py in the same folder as this program.
# Required import statement for Gui tools
import Gui3
# Named Constants
CANVAS_WIDTH = 640
CANVAS_HEIGHT = 480
# Function Definition Section
# Draws one sky. The parmeters base_x and base_y specify
# the location point at the bottom edge
# of the sky. hus, all the other parameters have units of pixels.
def sky (base_x, base_y, height):
# the sky picture is obtained by assuming a circle that has a
# center outside the scene space
sky_bottom_x = base_x
sky_bottom_y = base_y
canvas.circle([sky_bottom_x, sky_bottom_y + (10/20)*height], (10/20)*height,\
fill='skyblue')
# Draws a car. The parmeters x and y specify for the coordinate point for the
# center of the bottom edge of the car. The last parameter is the "height" of
# the car, the distance from the bottom part of the tayer to the top of the car.
# All other measurments in pixels unit.
def car(base_x, base_y, height):
# main body
# The body of the car has trapizoid shape. we can use the digonal points.
# car left bottom corner (clbc) and car right top corner (wrtc)
clbc_x = base_x - (6/5)*height
crbc_x = base_x + (6/5)*height
cltc_x = base_x - (3/5)*height
crtc_x = base_x + (6/5)*height
clbc_y = base_y + (1/5)*height
crbc_y = base_y + (1/5)*height
cltc_y = base_y + height
crtc_y = base_y + height
canvas.polygon([[clbc_x, clbc_y], [cltc_x, cltc_y], [crtc_x, crtc_y], [crbc_x, crbc_y]],\
fill='red')
# rare tayer
rare_tayer_x = base_x + (4/5)*height
rare_tayer_y = base_y + (1/5)*height
canvas.circle([rare_tayer_x, rare_tayer_y], (1/5)*height, fill='black')
# front tayer
front_tayer_x = base_x - (3/5)*height
front_tayer_y = base_y + (1/5)*height
canvas.circle([front_tayer_x, front_tayer_y], (1/5)*height, fill='black')
# line on the side body of the car
x1 = base_x - height
y1 = base_y + (2/5)*height
x2 = base_x + (6/5)*height
y2 = base_y + (2/5)*height
canvas.line([[x1, y1], [x2, y2]], width=4)
# Draw a tree. The parmeters base_x and base_y specify the location of a point at the center
# of the bottom edge of the tree trunk. The last parameter is the height of the tree. All
# other parameters are in units of pixels.
def draw_tree(base_x, base_y, height):
# draw trunk
# The trunk has lower left (TLL) and top right (TTR) points to get the stem or the trunk
TLL_x = base_x - (0.5/5)*height
TTR_x = base_x + (0.5/5)*height
TLL_y = base_y
TTR_y = base_y + (3/5)*height
canvas.rectangle([[TLL_x, TLL_y], [TTR_x, TTR_y]], fill='brown', width = 0)
# draw top part of the tree or leaf
# It has has one peak (leaf Peak) and two lower parts, left bottom(LLB) and right bottom (LRB)
LP_x = base_x
LP_Y = base_y + height
LLB_x = base_x - (2/5)* height
LRB_x = base_x + (2/5)* height
LLB_y = LRB_y = base_y + (3/5)*height
canvas.polygon([[LP_x, LP_Y], [LLB_x, LLB_y], [LRB_x, LRB_y]], fill='darkgreen', width=0)
# Draws a cluster of three trees. The parmeters x and y specify
# the location of a point at the center of the bottom edge
# of the tree trunk of the largest tree in the cluster.
# The last parameter is the "size" of the cluster -- the distance
# in pixels from the bottom to the top of the cluster.
def draw_tree_cluster(x, y, height):
draw_tree(x - (0.8/5)*height, y + (1/5)*height, (2/5)* height)
draw_tree(x + (0.8/5)*height, y + (1/5)*height, (2/5)*height)
draw_tree(x, y, (2.5/5)*height)
# Draw a bigsnowman. The parmeters x and y specify the point or coordinate
# of for the center of the bottom edge of the big snowman, and the last parameter
# is the "height" of the big snowman: the distance from the bottom to the top of
# the big snowman. All parameters have units of pixels.
def big_snowman(base_x,base_y,height):
#bottom
bottom_part_x = base_x
bottom_part_y = base_y
canvas.circle([ bottom_part_x, bottom_part_y + (2.8/9.5)*height], (2.8/9.5)*height, \
fill='white')
#abdomen
#abdomen represents all the middle body of the snowman
abdomen_x = base_x
abdomen_y = base_y +(4/9.5)*height
canvas.circle([abdomen_x, abdomen_y + (2.5/9.5)*height], (2.5/9.5)*height, fill='white')
#face
big_face_x = base_x
big_face_y = base_y + (7.5/9.5)*height
canvas.circle([big_face_x, big_face_y + (1.5/9.5)*height], (1.5/9.5)*height, fill='white')
#nose
big_nose_x = base_x
big_nose_y = base_y + (8.5/9.5)*height
canvas.circle([big_nose_x, big_nose_y], (0.25/9.5)*height, fill='black')
#eyes
big_left_eye_x = base_x - (0.5/9.5)*height
big_left_eye_y = base_y + (9/9.5)*height
canvas.circle([big_left_eye_x, big_left_eye_y +(0.2/9.5)*height], (0.2/9.5)*height,\
fill='black')
big_right_eye_x = base_x + (0.5/9.5)*height
big_right_eye_y = base_y + (9/9.5)*height
canvas.circle([big_right_eye_x, big_right_eye_y +(0.2/9.5)*height], (0.2/9.5)*height,\
fill='black')
#button_1
big_button_X = base_x
big_button_y = base_y + (6/9.5)*height
canvas.circle([big_button_X, big_button_y], (0.25/9.5)*height, fill='blue')
#button_2
big_button_X = base_x
big_button_y = base_y + (5/9.5)*height
canvas.circle([big_button_X, big_button_y], (0.25/9.5)*height, fill='blue')
#button_3
big_button_X = base_x
big_button_y = base_y + (4/9.5)*height
canvas.circle([big_button_X, big_button_y], (0.25/9.5)*height, fill='blue')
#hat
hat_top_x = base_x
hat_top_y = base_y + (12/9.5)*height
hat_left_x = base_x -(1.5/9.5)*height
hat_left_y = base_y + height
hat_right_x = base_x + (1.5/9.5)* height
hat_right_y = base_y + height
canvas.polygon([[hat_top_x ,hat_top_y], [hat_left_x, hat_left_y], \
[hat_right_x, hat_right_y]], fill='red')
def small_snowman(base_x,base_y,height):
#bottom
small_bottom_x = base_x
small_bottom_y = base_y
canvas.circle([small_bottom_x, small_bottom_y + 2.8/8*height], (2.8/8)*height, fill='white')
#small snowman face
small_face_x = base_x
small_face_y = base_y + (4/8)*height
canvas.circle([small_face_x, small_face_y + (2/8)*height], (2/8)*height, fill='white')
#nose
small_nose_x = base_x
small_nose_y = base_y + (5/8)*height
canvas.circle([small_nose_x, small_nose_y], (0.2/8)*height, fill='black')
#eyes
small_left_eye_x = base_x - (0.5/8)*height
small_left_eye_y = base_y + (6/8)*height
canvas.circle([small_left_eye_x, small_left_eye_y], (0.15/8)*height, fill='black')
small_right_eye_x = base_x + (0.5/8)*height
small_right_eye_y = base_y + (6/8)*height
canvas.circle([small_right_eye_x, small_right_eye_y], (0.15/8)*height, fill='black')
#button_1
small_button_x = base_x
small_button_y = base_y + (4/8)*height
canvas.circle([small_button_x, small_button_y], (0.25/8)*height, fill='blue')
#button_2
bsmall_button_x = base_x
small_button_y = base_y + (3/8)*height
canvas.circle([small_button_x, small_button_y], (0.25/8)*height, fill='blue')
#hat
hat_top_x = base_x
hat_top_y = base_y + (9/8)*height
hat_left_x = base_x -(1.8/8)*height
hat_left_y = base_y + (7/8)*height
hat_right_x = base_x + (1.8/8)*height
hat_right_y = base_y + (7/8)*height
canvas.polygon([[hat_top_x ,hat_top_y], [hat_left_x, hat_left_y], \
[hat_right_x, hat_right_y]], fill='red')
# Draws a house. The parmeters x and y specify for the coordinate point at the
# center of the bottom edge of the house. The last parameter is the "height" of
# the house, the distance from the bottom to the top of the house. All measurments
# have in pixels unit.
def draw_house(base_x, base_y, height):
#House Ceiling, the upper part (above the wall) of the house.
#ceiling_left_top/bottom_corner_x is abrevated as CLTC_x/CLBC-x
#ceiling_right_top/bottom_corner_x is CLRT_x/CRTC-y/CRBC_y
ceiling_house_x = base_x
ceiling_house_y = base_y + (8/5)*height
CLTC_x = base_x - (4.5/5)*height
CLTC_y = base_y + (8/5)*height
CLBC_x = base_x - (7.5/5)*height
CLBC_y = base_y + height
CRTC_x = base_x + (4.5/5)*height
CRTC_y = base_y + (8/5)*height
CRBC_x = base_x + (7.5/5)*height
CRBC_y = base_y + height
canvas.polygon([[CLTC_x, CLTC_y], [CRTC_x, CRTC_y], [CRBC_x, CRBC_y], [CLBC_x, CLBC_y]],\
fill='brown')
#wall
# The face of the house wall has rectangular shape. we can use the digonal points.
# wall left bottom corner (wlbc) and wall right top corner (wrtc)
wlbc_x = base_x - (4.5/5)*height
wrtc_x = base_x + (4.5/5)*height
wlbc_y = base_y
wrtc_y = base_y + height
canvas.rectangle([[wlbc_x,wlbc_y], [wrtc_x,wrtc_y]], fill='gray')
# The house door has also rectangular shape
# door left bottom corner (dlbc) and door right top corner (drtc)
dlbc_x = base_x - (1/5)*height
drtc_x = base_x + (1/5)*height
dlbc_y = base_y
drtc_y = base_y + (2/5)*height
canvas.rectangle([[dlbc_x,dlbc_y], [drtc_x,drtc_y]], fill='red')
def main():
#draw things on the canvas
sky(-260,170,600)
sky(-60,180,600)
sky(40,180,500)
sky(300,210,500)
sky(140,180,450)
sky(280,180,400)
car(-160,-220, 100)
draw_tree(40, 60, 120)
draw_tree_cluster(260, 100,80)
draw_tree_cluster(160, 40, 80)
draw_house(-150,-40,100)
snow_man()
def snow_man():
big_snowman(60,-220,190)
big_snowman(130,-220,190)
small_snowman(250,-220,160)
#####################################################################
#
# DO NOT CHANGE ANYTHING BELOW THIS LINE
#
#####################################################################
# Setup the canvas -- canvas is the drawing area
# Note that 'win' and 'canvas' are GLOBAL VARIABLES in this program
win = Gui3.Gui()
win.title('Playing around with Gui')
canvas = win.ca(width = CANVAS_WIDTH, height = CANVAS_HEIGHT)
# run the main function
main()
# show the window
win.mainloop()
# Here are some colors you can use: 'white', 'gray', 'black', 'red',
# 'green', 'blue', 'cyan', 'yellow', 'magenta', 'brown', 'darkgreen'
# Hundreds of colors here: http://tmml.sourceforge.net/doc/tk/colors.html
|
964496a57617e462e640640faccd9173f1b9124d | xiaohai0520/Algorithm | /algorithms/1373. Maximum Sum BST in Binary Tree.py | 712 | 3.53125 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxSumBST(self, root: TreeNode) -> int:
self.res = 0
def dfs(node):
if not node:
return float('inf'),float('-inf'),0,True
ll,lh,ls,lv = dfs(node.left)
rl,rh,rs,rv = dfs(node.right)
v = lv and rv and lh < node.val < rl
s = ls + rs + node.val if v else -1
self.res = max(self.res,s)
return (min(ll,node.val),max(rh,node.val),s,v)
dfs(root)
return self.res
|
eea4b73ba5ae1137ca469e4f8c7d47e96640ccb8 | TimBossuyt/5WWIPython | /06-Condities/Trolleyprobleem.py | 530 | 3.75 | 4 | antwoord_1 = input('Trek aan de hendel van de wissel? ')
antwoord_2 = input('Man van de brug duwen? ')
if antwoord_1 == 'ja' and antwoord_2 == 'ja':
doden = 2
elif antwoord_1 == 'ja' and antwoord_2 == 'nee':
doden = 1
elif antwoord_1 == 'nee' and antwoord_2 == 'ja':
doden = 1
elif antwoord_1 == 'nee' and antwoord_2 == 'nee':
doden = 5
print(doden)
#dit is gemakkelijker
if antwoord_1 != antwoord_2:
doden = 1
elif antwoord_1 == 'ja':
doden = 2
else:
doden = 5
|
0ffeb640c4c731ccebe44b3c2ba5cb07f518fc0f | AP-MI-2021/lab-4-VargaIonut23 | /main.py | 3,424 | 3.765625 | 4 | def citire_lista():
l = []
listasstring = input("Dati lista ")
numberasstring = listasstring.split(",")
for x in numberasstring:
l.append(str(x))
return l
def print_menu():
print (" 1. Citire lista ")
def se_gaseste_in_lista(l , l2):
'''
:param l: un sir de caractere
:param l2: lista str care corespunde cerintei 2 si cu ajutorul careia se va verifica
:return: 0 daca l2 nu este in l si 1 in caz constrar
'''
ok = 0
for i in l:
if i == l2:
ok = 1
if ok == 1 :
return "DA"
else:
return "NU"
def repetare(l):
'''
:param l: un sir de caractere
:return: returneaza o lista cu elementele care se regasesc de mai multe ori sau afiseaza unic in cazul in care toate elementele apar o data
'''
l2 = []
ok = 0
for i in l:
if aparitii(i , l) > 1 and repetare2(i , l2) == 1:
l2.append(i)
ok = 1
if ok == 1:
return l2
else:
return "UNIC"
def repetare2(i , l2):
#determina daca acel sir se repeta in l2
for x in l2:
if str(x) == str(i):
return 0
return 1
def aparitii(x , l):
#determina numarul de aparitii a lui x in lista l
nr_aparitii = 0
for i in l:
if str(x) == str(i):
nr_aparitii = nr_aparitii + 1
return nr_aparitii
def palindrom (l):
'''
:param l: un sir de caractere
:return: va returna toate sirurile de caractere care sunt un palindrom
'''
l2 = []
for i in l:
xStr = str(i)
if xStr == xStr[::-1]:
l2.append(i)
return l2
# 5.vom gasi caracterul care are cele mai multe aparitii ,iar apoi vom strabate lista iar sirurile care contin acel caracter le vom inlocui cu aparitia sa
def print_menu():
print (" 1. Citire lista ")
print (" 2. Se afiseaza daca o lista data se gaseste in cea initiala")
print (" 3. Se afiseaza o lista care contine toate elementele care apar de mai multe ori in lista principala si unic daca nu se repeta niciun element")
print (" 4. Se afiseaza acele siruri de caractere din lista care sunt un palindrom ")
print (" 5. Oprire")
def test_se_gaseste_in_lista():
assert se_gaseste_in_lista(["aaa", "bbbbb" , "ccc"] , "aaa") == "DA"
assert se_gaseste_in_lista(["abc" , "bac"] , "cde") == "NU"
assert se_gaseste_in_lista(["asd" , "asd" , "cme"] , "cme") == "DA"
def test_palindrom():
assert palindrom(["aaa" , "bbb"]) == ["aaa" , "bbb"]
assert palindrom(["abc" , "aba" , "vcv"]) == ["aba" , "vcv"]
assert palindrom(["aa" , "ca" ]) == ["aa"]
def test_repetare():
assert repetare(["aaa" , "aaa"]) == ["aaa"]
assert repetare(["aba", "aaa" , "aba"]) == ["aba"]
assert repetare(["aaa", "aac"]) == "UNIC"
def main():
l = []
test_se_gaseste_in_lista()
test_palindrom()
test_repetare()
while True:
print_menu()
optiune = input("Dati optiunea ")
if optiune == "1":
l = citire_lista()
elif optiune == "2":
l2 = str(input())
print(se_gaseste_in_lista(l,l2))
elif optiune == "3":
print(repetare(l))
elif optiune == "4":
print(palindrom(l))
elif optiune == "5":
break
else:
print("Optiune gresita! Reincercati: ")
if __name__ == "__main__":
main() |
488048012d9bffaf0fd795aaba7059c4d4688a59 | jzijin/leetcode | /606.根据二叉树创建字符串.py | 2,640 | 3.640625 | 4 | #
# @lc app=leetcode.cn id=606 lang=python
#
# [606] 根据二叉树创建字符串
#
# https://leetcode-cn.com/problems/construct-string-from-binary-tree/description/
#
# algorithms
# Easy (47.83%)
# Total Accepted: 2.4K
# Total Submissions: 5.1K
# Testcase Example: '[1,2,3,4]'
#
# 你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。
#
# 空节点则用一对空括号 "()" 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
#
# 示例 1:
#
#
# 输入: 二叉树: [1,2,3,4]
# 1
# / \
# 2 3
# /
# 4
#
# 输出: "1(2(4))(3)"
#
# 解释: 原本将是“1(2(4)())(3())”,
# 在你省略所有不必要的空括号对之后,
# 它将是“1(2(4))(3)”。
#
#
# 示例 2:
#
#
# 输入: 二叉树: [1,2,3,null,4]
# 1
# / \
# 2 3
# \
# 4
#
# 输出: "1(2()(4))(3)"
#
# 解释: 和第一个示例相似,
# 除了我们不能省略第一个对括号来中断输入和输出之间的一对一映射关系。
#
#
#
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
if not t:
return ''
left_str = '(' + self.tree2str(t.left) + ')' if t.left else None
right_str = '(' + self.tree2str(t.right) + ')' if t.right else None
if left_str and right_str: # 如果叶子节点都不是None
return str(t.val) + left_str + right_str
if not left_str and right_str: # 如果左子节点是None 那么应该加上一对括号
return str(t.val) + '()' + right_str
if left_str and not right_str: # 如果右子节点是None 那么不需要加上括号
return str(t.val) + left_str
else: # 如果叶子节点都不是None 那么直接返回
return str(t.val)
# if not t:
# return ""
# res = str(t.val)
# if t.left or t.right:
# res += "(" + self.tree2str(t.left) + ")"
# if t.right:
# res += "(" + self.tree2str(t.right) + ")"
# return res
|
9dc39abe32ef7bda1c6f08a0f3c3ec23b5e67c4c | anilectjose/S1-A-Anilect-Jose | /Python Lab/03-02-2021/1.factorial.py | 459 | 4.28125 | 4 | num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, num + 1):
factorial = factorial * i
print("The factorial of", num, "is", factorial)
# OUTPUT
#
# Enter a number: 2
# The factorial of 2 is 2
#
# Enter a number: 5
# The factorial of 5 is 120
|
57a9956fd68636043a5de5b35dd707c4d6b2251f | aslamdien/Random_Number | /age_determine.py | 1,586 | 3.921875 | 4 | from tkinter import *
from tkinter import messagebox
from datetime import date
root = Tk()
root.title("How Old Are You")
root.geometry("500x500")
year = StringVar()
month = StringVar()
day = StringVar()
lab1 = Label(root, text = "Year Your Were Born:")
lab1.place(x=50, y=10)
ent1 = Entry(root, textvariable = year)
ent1.place(x=200, y=10)
lab2 = Label(root, text = "Month:")
lab2.place(x=50, y=50)
ent2 = Entry(root, textvariable = month)
ent2.place(x=200, y=50)
lab3 = Label(root, text = "Date:")
lab3.place(x=50, y=90)
ent3 = Entry(root, textvariable = day)
ent3.place(x=200, y=90)
def calculateAge():
today = date.today()
birthDate = date(int(year.get()), int(month.get()), int(day.get()))
age = today.year - birthDate.year - ((today.month, today.day) < (birthDate.month, birthDate.day))
if age < 18:
messagebox.showinfo("SORRY", "You Are " + str(age) + ", Too Young, Try Again In A Few Years")
root.destroy()
import tkinter_challenge_random_number
if age >= 18:
messagebox.showinfo("CONGRATULATIONS", "You Are " + str(age)+ ", You Can Enter")
root.destroy()
import random_number
def clear():
ent1.delete(0, END)
ent2.delete(0, END)
ent3.delete(0, END)
def exit():
root.destroy()
import tkinter_challenge_random_number
btn1 = Button(root, text = "And You Are", command = calculateAge)
btn1.place(x=50, y=150)
btn2 = Button(root, text = "Clear", command = clear)
btn2.place(x=200, y=150)
btn3 = Button(root, text = "Exit", command = exit)
btn3.place(x=300, y=150)
root.mainloop()
|
6c3d121109f9f919ec6a2aee1aa50849a59cebff | bigMARAC/cco | /INE5402-01208B/prova-02/2473.py | 602 | 3.671875 | 4 | values = list(map(int, input().split(' ')))
winning = list(map(int, input().split(' ')))
count = 0
# Esse problema é bastante simples, basta fazer um loop
# nos números apostados e dentro desse, fazer um loop nos
# números certos, depois é só comporar o número X com os N
# números certos, e incrementar o 'count' toda vez que algum
# número for igual
for item in values:
for number in winning:
if item == number:
count += 1
if count == 3:
print("terno")
elif count == 4:
print("quadra")
elif count == 5:
print("quina")
elif count == 6:
print("sena")
else:
print("azar") |
8e23cda823c275dc1b30be7b6dc3a57d9fdd17a0 | maikelwever/simplecryptodome | /simplecrypto/hashes.py | 1,277 | 3.828125 | 4 | """
Module for standard hash algorithms, always returning the hash in hexadecimal
string format.
"""
import hashlib
from Crypto.Hash import HMAC, SHA256
from .formats import to_bytes
def md5(message):
"""
Returns the hexadecimal representation of the MD5 hash digest.
"""
return hashlib.md5(to_bytes(message)).hexdigest()
def sha1(message):
"""
Returns the hexadecimal representation of the SHA1 hash digest.
"""
return hashlib.sha1(to_bytes(message)).hexdigest()
def sha256(message):
"""
Returns the hexadecimal representation of the SHA256 hash digest.
"""
return hashlib.sha256(to_bytes(message)).hexdigest()
def sha512(message):
"""
Returns the hexadecimal representation of the SHA512 hash digest.
"""
return hashlib.sha512(to_bytes(message)).hexdigest()
def hmac(message, key):
"""
Returns the Hash Message Authentication Code for a given message, providing
integrity and authenticity assurances.
"""
h = HMAC.new(to_bytes(key), to_bytes(message), digestmod=SHA256)
return h.hexdigest()
# Available hash functions.
hashes = [sha1, md5, sha256, sha512]
# Default MAC algorithm.
mac = hmac
# Default hash function.
hash = sha256
|
55ddc8e4f14956fa560f7305ca7ccfba9258eab1 | Alhzz/Python3 | /Align.py | 431 | 3.890625 | 4 | """ Align """
def main():
""" Print text """
size = int(input())
locate = input()
word = input()
if locate == "left":
pass
elif locate == "right":
print(" "*(size - len(word)), end="")
else:
if (size - len(word)) % 2 == 0:
print(" "*((size - len(word))//2), end="")
else:
print(" "*(((size - len(word))//2) + 1), end="")
print(word)
main()
|
886c2c29f6ba3a4eeba5c818f56b4f8dfdcda1a1 | wonheejeong/Algorithm_No_1 | /2주차/python/1번_정원희.py | 213 | 3.6875 | 4 | def solution(n):
answer =[]
while n >0:
if n %2 ==1:
answer.insert(0,"수")
else:
answer.insert(0,"박")
n-=1
return ''.join(answer)
print(solution(3)) |
577df6cc31f95c40a0bc3ad82b6271781e528fed | GunalanD95/Technical-Interview-Guide | /HackerRank/StrangeCounter.py | 381 | 3.75 | 4 | # https://www.hackerrank.com/challenges/strange-code/problem
# Easy
def strangeCounter(t):
rem = 3 # The time upward
while(rem < t):
t = t - rem # Subtract from the original
rem *= 2 # Follow the condition and increment
return(rem - t + 1) # The difference between time upward and original + 1
print(strangeCounter(8))
# TAGS: revise, time, modulus
|
9767b5307a7d416b6806bc07cb9b848789a82507 | samuelklam/rabin-miller-primality-test | /rabin-miller.py | 1,184 | 3.609375 | 4 | from random import randrange
import math
def mod_e(base, expo, n):
val1 = 1
while expo > 0:
# the case that expo is odd, make sure to multiply by 1 base
if expo % 2 == 1:
val1 = (val1 * base) % n
# repeated squaring
base = (base * base) % n
expo = math.floor(expo / 2)
return val1 % n
def probably_prime(n, k):
"""
Return True if n passes k rounds of the Miller-Rabin primality
test (and is probably prime). Return False if n is proved to be
composite.
"""
small_primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
if n < 2:
return False
for p in small_primes:
if n < p * p:
return True
if n % p == 0:
return False
r, s = 0, n - 1
while s % 2 == 0:
r += 1
s //= 2
print s
for _ in range(k):
a = randrange(2, n - 1)
x = mod_e(a, s, n)
if x == 1 or x == n - 1:
continue
for _ in range(r - 1):
x = mod_e(x, 2, n)
if x == n - 1:
break
else:
return False
return True
print probably_prime(967, 30)
|
d9f4ee2336aad65df24a3d6942641c8cd83a5d40 | tanya9779/lab20 | /6.py | 4,568 | 3.65625 | 4 | # coding: utf-8
# Отобразить кратчайший путь между двумя вершинами (восстановление пути)
import matplotlib.pyplot as plt
import networkx as nx
def LoadGraph(f_name): # из файла прочитаем ребра и их вес
with open (f_name, 'r') as f :
line = f.readline()
while line:
u,v,w = line.split()
w = float(w)
labels[u]='$'+u+'$' # значки $ в начале и в конце слов нужны (проверено!)
labels[v]='$'+v+'$'
G.add_edge(u,v,weight=int(w/100)) # Опытно проверено, что рисунок лучше, когда weight небольшие
line = f.readline()
# реализация алгоритма Дейкстры для конкретного маршрута
def dejkstra (start, finish):
shortest_path={vertex:float('+inf') for vertex in G.nodes()}
shortest_path[start]=0
queue=[start]
p = {} # словарь вида {текущая:предыдущая к ней} вершины
while queue:
current=queue.pop(0)
for neighbour in G.neighbors(current):
Visited[neighbour] = True
offering_shortest_path=shortest_path[current]+G.get_edge_data(current, neighbour)['weight']
if offering_shortest_path < shortest_path[neighbour]:
shortest_path[neighbour]=offering_shortest_path
queue.append(neighbour)
p[neighbour] = current
# сначала пометим старт и финиш
node_list.append(start)
node_list.append(finish)
# теперь построим маршрут - заполним edge_list
if finish in p.keys(): # идем от конечной точки к начальной
while finish != start:
edge_list.append( (finish, p[finish]) )
if finish not in node_list:
node_list.append(finish)
if p[finish] not in node_list:
node_list.append(p[finish])
finish = p[finish] # перейдем к предшественнику
#----- main --------
G = nx.Graph()
labels={} # граф и названия городов заполнятся в LoadGraph()
LoadGraph('map.txt')
COLORS = ['black','red','green','blue','brown','orange']
# список длин дорог для нанесения на ребра
edge_labels=dict([((u,v,),d['weight']) # ключем является кортеж из вершин (u,v) а значением длина
for u,v,d in G.edges(data=True)]) # просим G вернуть ребра со всеми свойствами (data=True)
# возвращается d как список свойств, а нам нужно только длины
Visited = {i:False for i in G.nodes()} # все вершины пока не посещенные - при посещении вершины помечаем как True
cityes = ','.join(G.node)
print ('доступные: '+cityes)
start = input('Начальный город: ')
finish = input('Конечный город: ')
edge_list = [] # список ребер для очередной раскраски
node_list = [] # список вершин для очередной раскраски
pos=nx.spring_layout(G,weight='weight') # positions for all nodes
nx.draw_networkx_edges(G,pos,alpha=0.5) # нарисуем все дороги черным
nx.draw_networkx_labels(G,pos,labels,font_size=10) # нанесем все названия городов
# нанесем длины ребер
nx.draw_networkx_edge_labels(G,pos,edge_labels,font_size=8)
count = 1 # просто поменяем цвет
dejkstra(start, finish)
# раскрасим очередной компонент связности своим цветом
nx.draw_networkx_edges(G, pos, edgelist=edge_list, alpha=0.5,edge_color=COLORS[count%len(COLORS)] )
nx.draw_networkx_nodes(G, pos, nodelist=node_list, node_color=COLORS[count%len(COLORS)], node_size=200, alpha=0.5)
# start-вершину и финиш-вершину выделим цветом
nx.draw_networkx_nodes(G, pos, nodelist=[start], node_color=COLORS[len(COLORS)-1], node_size=200, alpha=0.5)
nx.draw_networkx_nodes(G, pos, nodelist=[finish], node_color=COLORS[len(COLORS)-1], node_size=200, alpha=0.5)
plt.axis('off')
plt.savefig("dejkstra2.png") # save as png
plt.show() # display
|
9be91dff0d65d1e8fc4764b2e6c80d17c80778fe | jholgado/text-adventure | /src/my_pkg/game.py | 1,783 | 3.671875 | 4 | from my_pkg.player import Player, userinput
from my_pkg import level, items
# main game driving code including text intro and short explanation
def play():
print("Welcome to the Tower of Trials")
print("Do you wish to enter and test your might? (yes/no)")
select = userinput("", ["yes", "no"])
if select == "no":
print("You walk away from the tower and return home")
return
i = 1
weapons = [items.Dagger(), items.Sword(), items.Spear(), items.Axe()]
magic = [items.Fire(), items.Lightning(), items.Ice()]
player = Player()
print("A few things to note before you start:")
print("enemies have different weaknesses to weapons and magic")
print("their magic weaknesses will be determined by color (hint: try to match colors)")
print("their weapon weaknesses are determined by the enemy type")
print("finally, your power will increase for each floor you climb, but so will that of your enemies\n")
print("when you are ready to begin, type 'yes'")
userinput("", ["yes"])
while player.is_alive():
current_lvl = level.Level(i)
print("you enter floor " + str(i))
current_lvl.battle(player)
if player.is_alive():
print("Floor " + str(i) + " cleared!\n")
player.lvl_up()
player.hp = player.max_hp
if 1 <= i <= 4:
print("You received a {}\n".format(weapons[i - 1].name))
player.weapons[weapons[i - 1].name.lower()] = weapons[i - 1]
if 3 <= i <= 5:
print("You received a {} spell\n".format(magic[i - 3].name))
player.magic[magic[i - 3].name.lower()] = magic[i - 3]
i += 1
print("YOU DIED")
print("Floors Completed: " + str(i-1))
play()
|
6ec7fe721587c1e0de55bb41db492dcd8838b62b | vaios84/Python-Tutorial | /remove-duplicates-in-list.py | 162 | 4 | 4 | numbers = [1,5,7,5,8,1,9,6,4,7,13,9,7,1,36,3,5]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
print(uniques)
|
87edd16fb4a10e704a51177ef41e8db3f5d94397 | cbare/data-science-from-scratch | /chapter_07/population_mean_vs_sample_mean.py | 1,027 | 3.546875 | 4 | """
Compare population mean with sample mean
"""
import random
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from stats import *
from normal import normal_pdf
# a population of 1 million
pop = [random.random() for _ in range(1000000)]
population_mean = sum(pop)/len(pop)
print('population mean = ', population_mean)
n = 100
sample_means = np.fromiter((sum(random.sample(pop, k=n))/n for _ in range(1000)), float)
# make a pretty picture
sns.kdeplot(sample_means, shade=True, color='skyblue',
label='probability density of sampling distribution')
# estimate the standard deviation of the sampling distribution
sd = standard_deviation(pop)/math.sqrt(n)
xs = [x/500 + 0.4 for x in range(100)]
plt.plot(xs,
[normal_pdf(x, mu=population_mean, sigma=sd) for x in xs],
'--',
color='#30336699',
label=f'normal mu={population_mean:0.3} sigma={sd:0.3}')
plt.axvline(x=population_mean)
plt.title('Probability density of sample means vs. population mean')
plt.legend(loc=2)
plt.show()
|
240dc8f3be157f31acb374dc440bb413b1e3d3c6 | greenday8426/big_data_web | /5일차 20180201/계산기 프로그램.py | 685 | 3.71875 | 4 | ##변수 선언 부분
a,b,ch=0,0,""
##메인(main) 코드 부분
a=int(input("첫 번째 수를 입력하세요:"))
ch=input("계산할 연산자를 입력하세요:")
b=int(input("두 번째 수를 입력하세요:"))
if ch=="+":
print("%d+%d=%d 입니다. "%(a,b,a+b))
elif ch=="-":
print("%d-%d=%d 입니다. "%(a,b,a-b))
elif ch=="*":
print("%d*%d=%d 입니다. "%(a,b,a*b))
elif ch=="-":
print("%d/%d=%d 입니다. "%(a,b,a/b))
elif ch=="%":
print("%d%%d=%d 입니다. "%(a,b,a%b))
elif ch=="-":
print("%d//%d=%d 입니다. "%(a,b,a//b))
elif ch=="**":
print("%d**%d=%d 입니다. "%(a,b,a**b))
else:
print("알 수 없는 연산자입니다.")
|
f66ed1dcc518d14bb5d3f9d977eba79e26e2108c | rafaelperazzo/programacao-web | /moodledata/vpl_data/12/usersdata/71/5304/submittedfiles/impedimento.py | 181 | 3.71875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
L = input("L: ")
R = input("R: ")
D = input("D: ")
if L>50 and L<R and R>D:
print("S")
else:
print("N") |
927368235a08540c72c289154a1915abf3eb4964 | nitendragautam/python_apps | /python_core/pythontutorials/files.py | 552 | 3.96875 | 4 | #Open a file
#Open the file in write mode
fo = open('test.txt', 'w')
#Info of File
print('Name: ',fo.name)
print('Is Closed: ', fo.closed)
print('File Opening mode: ',fo.mode)
fo.write('This is a test')
fo.write('\n I repeat')
fo.close()
#Open and Append File
fo = open('test.txt', 'a') #Open file in Append Mode
fo.write('\n Still Testing')
fo.close()
#Read from File
fo = open('test.txt', 'rt')
text = fo.read(10)
print(text)
#Create a file
fo = open('test2.txt', 'w+')
fo.write('This is a new File')
fo.close()
|
932b539e320bc00c94ccb3686a6ba0f0f0869ff7 | kitfair/kitspython | /swaplist.py | 276 | 3.953125 | 4 |
def swap(val):
"""
:param val: a list of object
:return: new order list
"""
m = len(val)//2
return val[m:]+val[:m]
def main():
val = [9,13,21,4,11,7,1,3]
print(val)
val = swap(val)
print(val)
if __name__ == '__main__':
main() |
12e1ed64a52807a910d07af82beece0aa81fc643 | Antonio2401/t08_ballena.custodio | /ramos_flores/busqueda.py | 19,089 | 3.65625 | 4 | # Busquedas de cadenas
# Ejercicio (PARSER)
# Ingresar el codigo numerico
# 1 -> hola
# 2 -> como estas
# 3 -> te quiero
# Ingresar un comando de 4 codigos numerico
comando="12333"
cmd1=comando[0]
cmd2=comando[1]
cmd3=comando[2]
cmd4=comando[3]
code=""
# 1 2
# 01234567890123456789012345678
sentencias="hola como estas te quiero"
print(sentencias.find("quiero"))
hola=sentencias[0:4]
como_estas=sentencias[5:15]
te_quiero=sentencias[16:]
# Primer Bloque para el Codigo
if (cmd1 == '1'):
code=hola
if (cmd1 == '2'):
code=como_estas
if (cmd1 == '3'):
code=te_quiero
# 2do bloque para el codigo
if (cmd2 == '1'):
code += "\n" + hola
if (cmd2 == '2'):
code += "\n" + como_estas
if (cmd2 == '3'):
code += "\n" + te_quiero
# 3cer bloque para el codigo
if (cmd3 == '1'):
code += "\n" + hola
if (cmd3 == '2'):
code += "\n" + como_estas
if (cmd3 == '3'):
code += "\n" + te_quiero
# 4to bloque para el codigo
if (cmd4 == '1'):
code += "\n" + hola
if (cmd4 == '2'):
code += "\n" + como_estas
if (cmd4 == '3'):
code += "\n" + te_quiero
print(code)
print("")
# ejercicio 2
comando = "13254"
cmd1 = comando[0]
cmd2 = comando[1]
cmd3 = comando[2]
cmd4 = comando[3]
cmd5 = comando[4]
code = ""
# 1 2 3 4
# 01234567890123456789012345678901234567890123
sentencias ="papa y tu mama no te quieren y ellos viajaran"
papa= sentencias[0:4]
y= sentencias[4:6]
tu = sentencias[7:9]
mama=sentencias[10:14]
quieren=sentencias[21:29]
# Primer Bloque para el Codigo
if (cmd1 == '1'):
code = papa
if (cmd1 == '2'):
code = mama
if (cmd1 == '3'):
code = tu
if(cmd1 == '4'):
code= y
if(cmd1 =='5'):
code = quieren
# 2do bloque para el codigo
if (cmd2 == '1'):
code += "\n" + papa
if (cmd2 == '2'):
code += "\n" + mama
if (cmd2 == '3'):
code += "\n" + tu
if(cmd2 == '4'):
code+="\n"+ y
if(cmd2 =='5'):
code +="\n"+ quieren
# 3cer bloque para el codigo
if (cmd3 == '1'):
code += "\n" + hola
if (cmd3 == '2'):
code += "\n" + como_estas
if (cmd3 == '3'):
code += "\n" + te_quiero
if(cmd3 == '4'):
code+="\n"+ y
if(cmd3 =='5'):
code +="\n"+ quieren
# 4to bloque para el codigo
if (cmd4 == '1'):
code += "\n" + hola
if (cmd4 == '2'):
code += "\n" + como_estas
if (cmd4 == '3'):
code += "\n" + te_quiero
if(cmd4 == '4'):
code+="\n"+ y
if(cmd4 =='5'):
code +="\n"+ quieren
# 5to bloque para el codigo
if (cmd5 == '1'):
code += "\n" + hola
if (cmd5 == '2'):
code += "\n" + como_estas
if (cmd5 == '3'):
code += "\n" + te_quiero
if(cmd5 == '4'):
code+="\n"+ y
if(cmd5 =='5'):
code +="\n"+ quieren
print(code)
# ejercicio 3
comando="3411"
cmd1=comando[0]
cmd2=comando[1]
cmd3=comando[2]
cmd4=comando[3]
code=""
# 1 2
# 01234567890123456789012345678
sentencias="si no vas conmigo con el"
x=sentencias[0:2]
y=sentencias[3:5]
z=sentencias[6:9]
w=sentencias[10:17]
v=sentencias[18:21]
# Primer Bloque para el Codigo
if (cmd1 == '1'):
code+=x
if (cmd1 == '2'):
code+=y
if (cmd1 == '3'):
code+=z
if(cmd1 =='4'):
code+=w
if(cmd1 =='5'):
code +=v
#2do bloque para el codigo
if (cmd2 == '1'):
code += "\n" + x
if (cmd2 == '2'):
code += "\n" + y
if (cmd2 == '3'):
code += "\n" + z
if (cmd2 == '4'):
code += "\n" + w
if (cmd2 == '5'):
code += "\n" + v
# 3cer bloque para el codigo
if (cmd3 == '1'):
code += "\n" + x
if (cmd3 == '2'):
code += "\n"+ y
if (cmd3 == '3'):
code += "\n" + z
if (cmd3 == '4'):
code += "\n" + w
if (cmd3 == '5'):
code += "\n" + v
# 4to bloque para el codigo
if (cmd4 == '1'):
code += "\n" + x
if (cmd4 == '2'):
code += "\n" + y
if (cmd4 == '3'):
code += "\n" + z
if (cmd4 == '4'):
code += "\n" + w
if (cmd4 == '3'):
code += "\n" + v
print(code)
print("")
# ejercicio 4
comando="1423"
cmd1=comando[0]
cmd2=comando[1]
cmd3=comando[2]
cmd4=comando[3]
code=""
# 1 2
# 01234567890123456789012345678
sentencias="perro y gato gallina "
x=sentencias[0:5]
y=sentencias[6:7]
z=sentencias[8:12]
w=sentencias[13:]
# Primer Bloque para el Codigo
if (cmd1 == '1'):
code+=x
if (cmd1 == '2'):
code+=y
if (cmd1 == '3'):
code+=z
if(cmd1 =='4'):
code+=w
#2do bloque para el codigo
if (cmd2 == '1'):
code += "\n" + x
if (cmd2 == '2'):
code += "\n" + y
if (cmd2 == '3'):
code += "\n" + z
if (cmd2 == '4'):
code += "\n" + w
# 3cer bloque para el codigo
if (cmd3 == '1'):
code += "\n" + x
if (cmd3 == '2'):
code += "\n"+ y
if (cmd3 == '3'):
code += "\n" + z
# 4to bloque para el codigo
if (cmd4 == '1'):
code += "\n" + x
if (cmd4 == '2'):
code += "\n" + y
if (cmd4 == '3'):
code += "\n" + z
if (cmd4 == '4'):
code += "\n" + w
print(code)
print("")
# ejercicio 5
comando="12345"
cmd1=comando[0]
cmd2=comando[1]
cmd3=comando[2]
cmd4=comando[3]
cmd5=comando[4]
code=""
# 1
# 012345678901234
sentencias="200 + 300 = 500"
x=sentencias[0:3]
y=sentencias[4:5]
z=sentencias[6:9]
w=sentencias[10:11]
v=sentencias[12:]
# Primer Bloque para el Codigo
if (cmd1 == '1'):
code+=x
if (cmd1 == '2'):
code+=y
if (cmd1 == '3'):
code+=z
if(cmd1 =='4'):
code+=w
if(cmd1 =='5'):
code +=v
#2do bloque para el codigo
if (cmd2 == '1'):
code += "\n" + x
if (cmd2 == '2'):
code += "\n" + y
if (cmd2 == '3'):
code += "\n" + z
if (cmd2 == '4'):
code += "\n" + w
if (cmd2 == '5'):
code += "\n" + v
# 3cer bloque para el codigo
if (cmd3 == '1'):
code += "\n" + x
if (cmd3 == '2'):
code += "\n"+ y
if (cmd3 == '3'):
code += "\n" + z
if (cmd3 == '4'):
code += "\n" + w
if (cmd3 == '5'):
code += "\n" + v
# 4to bloque para el codigo
if (cmd4 == '1'):
code += "\n" + x
if (cmd4 == '2'):
code += "\n" + y
if (cmd4 == '3'):
code += "\n" + z
if (cmd4 == '4'):
code += "\n" + w
if (cmd4 == '3'):
code += "\n" + v
# 5to bloque para el codigo
if (cmd5 == '1'):
code += "\n" + x
if (cmd5 == '2'):
code += "\n" + y
if (cmd5 == '3'):
code += "\n" + z
if (cmd5 == '4'):
code += "\n" + w
if (cmd5 == '5'):
code += "\n" + v
print(code)
print("")
# ejercicio 6
comando="14532"
cmd1=comando[0]
cmd2=comando[1]
cmd3=comando[2]
cmd4=comando[3]
cmd5=comando[4]
code=""
# 1 2
# 0123456789012345678901234
sentencias="feliz navidad y año nuevo"
x=sentencias[0:5]
y=sentencias[6:13]
z=sentencias[14:15]
w=sentencias[16:19]
v=sentencias[20:]
# Primer Bloque para el Codigo
if (cmd1 == '1'):
code+=x
if (cmd1 == '2'):
code+=y
if (cmd1 == '3'):
code+=z
if(cmd1 =='4'):
code+=w
if(cmd1 =='5'):
code +=v
#2do bloque para el codigo
if (cmd2 == '1'):
code += "\n" + x
if (cmd2 == '2'):
code += "\n" + y
if (cmd2 == '3'):
code += "\n" + z
if (cmd2 == '4'):
code += "\n" + w
if (cmd2 == '5'):
code += "\n" + v
# 3cer bloque para el codigo
if (cmd3 == '1'):
code += "\n" + x
if (cmd3 == '2'):
code += "\n"+ y
if (cmd3 == '3'):
code += "\n" + z
if (cmd3 == '4'):
code += "\n" + w
if (cmd3 == '5'):
code += "\n" + v
# 4to bloque para el codigo
if (cmd4 == '1'):
code += "\n" + x
if (cmd4 == '2'):
code += "\n" + y
if (cmd4 == '3'):
code += "\n" + z
if (cmd4 == '4'):
code += "\n" + w
if (cmd4 == '5'):
code += "\n" + v
# 5to bloque para el codigo
if (cmd5 == '1'):
code += "\n" + x
if (cmd5 == '2'):
code += "\n" + y
if (cmd5 == '3'):
code += "\n" + z
if (cmd5 == '4'):
code += "\n" + w
if (cmd5 == '5'):
code += "\n" + v
print(code)
print("")
# ejercicio 7
comando="15423"
cmd1=comando[0]
cmd2=comando[1]
cmd3=comando[2]
cmd4=comando[3]
cmd5=comando[4]
code=""
# 1
# 012345678901234567890
sentencias="no por favor dejes me "
x=sentencias[0:2]
y=sentencias[3:6]
z=sentencias[7:12]
w=sentencias[13:18]
v=sentencias[19:]
# Primer Bloque para el Codigo
if (cmd1 == '1'):
code+=x
if (cmd1 == '2'):
code+=y
if (cmd1 == '3'):
code+=z
if(cmd1 =='4'):
code+=w
if(cmd1 =='5'):
code +=v
#2do bloque para el codigo
if (cmd2 == '1'):
code += "\n" + x
if (cmd2 == '2'):
code += "\n" + y
if (cmd2 == '3'):
code += "\n" + z
if (cmd2 == '4'):
code += "\n" + w
if (cmd2 == '5'):
code += "\n" + v
# 3cer bloque para el codigo
if (cmd3 == '1'):
code += "\n" + x
if (cmd3 == '2'):
code += "\n"+ y
if (cmd3 == '3'):
code += "\n" + z
if (cmd3 == '4'):
code += "\n" + w
if (cmd3 == '5'):
code += "\n" + v
# 4to bloque para el codigo
if (cmd4 == '1'):
code += "\n" + x
if (cmd4 == '2'):
code += "\n" + y
if (cmd4 == '3'):
code += "\n" + z
if (cmd4 == '4'):
code += "\n" + w
if (cmd4 == '5'):
code += "\n" + v
# 5to bloque para el codigo
if (cmd5 == '1'):
code += "\n" + x
if (cmd5 == '2'):
code += "\n" + y
if (cmd5 == '3'):
code += "\n" + z
if (cmd5 == '4'):
code += "\n" + w
if (cmd5 == '5'):
code += "\n" + v
print(code)
print("")
# ejercicio 8
comando="12345"
cmd1=comando[0]
cmd2=comando[1]
cmd3=comando[2]
cmd4=comando[3]
cmd5=comando[4]
code=""
# 1
# 012345678901234567890
sentencias="amor y odio dos pasos"
x=sentencias[0:4] #amor
y=sentencias[3::-1] #roma
z=sentencias[5:6] # y
w=sentencias[7:11] #odio
v=sentencias[10:6:-1] # oido
# Primer Bloque para el Codigo
if (cmd1 == '1'):
code+=x
if (cmd1 == '2'):
code+=y
if (cmd1 == '3'):
code+=z
if(cmd1 =='4'):
code+=w
if(cmd1 =='5'):
code +=v
#2do bloque para el codigo
if (cmd2 == '1'):
code += "\n" + x
if (cmd2 == '2'):
code += "\n" + y
if (cmd2 == '3'):
code += "\n" + z
if (cmd2 == '4'):
code += "\n" + w
if (cmd2 == '5'):
code += "\n" + v
# 3cer bloque para el codigo
if (cmd3 == '1'):
code += "\n" + x
if (cmd3 == '2'):
code += "\n"+ y
if (cmd3 == '3'):
code += "\n" + z
if (cmd3 == '4'):
code += "\n" + w
if (cmd3 == '5'):
code += "\n" + v
# 4to bloque para el codigo
if (cmd4 == '1'):
code += "\n" + x
if (cmd4 == '2'):
code += "\n" + y
if (cmd4 == '3'):
code += "\n" + z
if (cmd4 == '4'):
code += "\n" + w
if (cmd4 == '5'):
code += "\n" + v
# 5to bloque para el codigo
if (cmd5 == '1'):
code += "\n" + x
if (cmd5 == '2'):
code += "\n" + y
if (cmd5 == '3'):
code += "\n" + z
if (cmd5 == '4'):
code += "\n" + w
if (cmd5 == '5'):
code += "\n" + v
print(code)
print("")
# ejercicio 9
comando="13524"
cmd1=comando[0]
cmd2=comando[1]
cmd3=comando[2]
cmd4=comando[3]
cmd5=comando[4]
code=""
# 1 2
# 01234567890123456789012345678
sentencias="buenas tardes dias noches bye"
x=sentencias[0:6] # buenos
y=sentencias[7:13] # dias
z=sentencias[14:18] # bye
w=sentencias[19:25] # tardes
v=sentencias[26:] # noches
# Primer Bloque para el Codigo
if (cmd1 == '1'):
code+=x
if (cmd1 == '2'):
code+=y
if (cmd1 == '3'):
code+=z
if(cmd1 =='4'):
code+=w
if(cmd1 =='5'):
code +=v
#2do bloque para el codigo
if (cmd2 == '1'):
code += "\n" + x
if (cmd2 == '2'):
code += "\n" + y
if (cmd2 == '3'):
code += "\n" + z
if (cmd2 == '4'):
code += "\n" + w
if (cmd2 == '5'):
code += "\n" + v
# 3cer bloque para el codigo
if (cmd3 == '1'):
code += "\n" + x
if (cmd3 == '2'):
code += "\n"+ y
if (cmd3 == '3'):
code += "\n" + z
if (cmd3 == '4'):
code += "\n" + w
if (cmd3 == '5'):
code += "\n" + v
# 4to bloque para el codigo
if (cmd4 == '1'):
code += "\n" + x
if (cmd4 == '2'):
code += "\n" + y
if (cmd4 == '3'):
code += "\n" + z
if (cmd4 == '4'):
code += "\n" + w
if (cmd4 == '5'):
code += "\n" + v
# 5to bloque para el codigo
if (cmd5 == '1'):
code += "\n" + x
if (cmd5 == '2'):
code += "\n" + y
if (cmd5 == '3'):
code += "\n" + z
if (cmd5 == '4'):
code += "\n" + w
if (cmd5 == '5'):
code += "\n" + v
print(code)
print("")
# ejercicio 10
comando="12345"
cmd1=comando[0]
cmd2=comando[1]
cmd3=comando[2]
cmd4=comando[3]
cmd5=comando[4]
code=""
# 1
# 012345678901234
sentencias="f(X)=x+500"
x=sentencias[0:4] # f(x)
y=sentencias[4:5] # =
z=sentencias[5:6] # x
w=sentencias[6:7] # +
v=sentencias[7:] # 500
# Primer Bloque para el Codigo
if (cmd1 == '1'):
code+=x
if (cmd1 == '2'):
code+=y
if (cmd1 == '3'):
code+=z
if(cmd1 =='4'):
code+=w
if(cmd1 =='5'):
code +=v
#2do bloque para el codigo
if (cmd2 == '1'):
code += "\n" + x
if (cmd2 == '2'):
code += "\n" + y
if (cmd2 == '3'):
code += "\n" + z
if (cmd2 == '4'):
code += "\n" + w
if (cmd2 == '5'):
code += "\n" + v
# 3cer bloque para el codigo
if (cmd3 == '1'):
code += "\n" + x
if (cmd3 == '2'):
code += "\n"+ y
if (cmd3 == '3'):
code += "\n" + z
if (cmd3 == '4'):
code += "\n" + w
if (cmd3 == '5'):
code += "\n" + v
# 4to bloque para el codigo
if (cmd4 == '1'):
code += "\n" + x
if (cmd4 == '2'):
code += "\n" + y
if (cmd4 == '3'):
code += "\n" + z
if (cmd4 == '4'):
code += "\n" + w
if (cmd4 == '5'):
code += "\n" + v
# 5to bloque para el codigo
if (cmd5 == '1'):
code += "\n" + x
if (cmd5 == '2'):
code += "\n" + y
if (cmd5 == '3'):
code += "\n" + z
if (cmd5 == '4'):
code += "\n" + w
if (cmd5 == '5'):
code += "\n" + v
print(code)
print("")
# ejercicio 11
comando="12345"
cmd1=comando[0]
cmd2=comando[1]
cmd3=comando[2]
cmd4=comando[3]
cmd5=comando[4]
code=""
# 1
# 01234567890123456789012345
sentencias="() int float input str"
x=sentencias[0:2]
y=sentencias[3:6]
z=sentencias[7:12]
w=sentencias[13:18]
v=sentencias[19:]
# Primer Bloque para el Codigo
if (cmd1 == '1'):
code+=x
if (cmd1 == '2'):
code+=y
if (cmd1 == '3'):
code+=z
if(cmd1 =='4'):
code+=w
if(cmd1 =='5'):
code +=v
#2do bloque para el codigo
if (cmd2 == '1'):
code += "\n" + x
if (cmd2 == '2'):
code += "\n" + y
if (cmd2 == '3'):
code += "\n" + z
if (cmd2 == '4'):
code += "\n" + w
if (cmd2 == '5'):
code += "\n" + v
# 3cer bloque para el codigo
if (cmd3 == '1'):
code += "\n" + x
if (cmd3 == '2'):
code += "\n"+ y
if (cmd3 == '3'):
code += "\n" + z
if (cmd3 == '4'):
code += "\n" + w
if (cmd3 == '5'):
code += "\n" + v
# 4to bloque para el codigo
if (cmd4 == '1'):
code += "\n" + x
if (cmd4 == '2'):
code += "\n" + y
if (cmd4 == '3'):
code += "\n" + z
if (cmd4 == '4'):
code += "\n" + w
if (cmd4 == '5'):
code += "\n" + v
# 5to bloque para el codigo
if (cmd5 == '1'):
code += "\n" + x
if (cmd5 == '2'):
code += "\n" + y
if (cmd5 == '3'):
code += "\n" + z
if (cmd5 == '4'):
code += "\n" + w
if (cmd5 == '5'):
code += "\n" + v
print(code)
print("")
# ejercicio 13
comando="12345"
cmd1=comando[0]
cmd2=comando[1]
cmd3=comando[2]
cmd4=comando[3]
cmd5=comando[4]
code=""
# 1
# 012345678901234
sentencias="200 + 300 = 500"
x=sentencias[0:3]
y=sentencias[4:5]
z=sentencias[6:9]
w=sentencias[10:11]
v=sentencias[12:]
# Primer Bloque para el Codigo
if (cmd1 == '1'):
code+=x
if (cmd1 == '2'):
code+=y
if (cmd1 == '3'):
code+=z
if(cmd1 =='4'):
code+=w
if(cmd1 =='5'):
code +=v
#2do bloque para el codigo
if (cmd2 == '1'):
code += "\n" + x
if (cmd2 == '2'):
code += "\n" + y
if (cmd2 == '3'):
code += "\n" + z
if (cmd2 == '4'):
code += "\n" + w
if (cmd2 == '5'):
code += "\n" + v
# 3cer bloque para el codigo
if (cmd3 == '1'):
code += "\n" + x
if (cmd3 == '2'):
code += "\n"+ y
if (cmd3 == '3'):
code += "\n" + z
if (cmd3 == '4'):
code += "\n" + w
if (cmd3 == '5'):
code += "\n" + v
# 4to bloque para el codigo
if (cmd4 == '1'):
code += "\n" + x
if (cmd4 == '2'):
code += "\n" + y
if (cmd4 == '3'):
code += "\n" + z
if (cmd4 == '4'):
code += "\n" + w
if (cmd4 == '5'):
code += "\n" + v
# 5to bloque para el codigo
if (cmd5 == '1'):
code += "\n" + x
if (cmd5 == '2'):
code += "\n" + y
if (cmd5 == '3'):
code += "\n" + z
if (cmd5 == '4'):
code += "\n" + w
if (cmd5 == '5'):
code += "\n" + v
print(code)
print("")
# ejercicio 14
comando="54321"
cmd1=comando[0]
cmd2=comando[1]
cmd3=comando[2]
cmd4=comando[3]
cmd5=comando[4]
code=""
# 1
# 0123456789012345678901234567890
sentencias="las aves con sin nido "
x=sentencias[0:3]
y=sentencias[4:8]
z=sentencias[9:12]
w=sentencias[13:16]
v=sentencias[17:]
# Primer Bloque para el Codigo
if (cmd1 == '1'):
code+=x
if (cmd1 == '2'):
code+=y
if (cmd1 == '3'):
code+=z
if(cmd1 =='4'):
code+=w
if(cmd1 =='5'):
code +=v
#2do bloque para el codigo
if (cmd2 == '1'):
code += "\n" + x
if (cmd2 == '2'):
code += "\n" + y
if (cmd2 == '3'):
code += "\n" + z
if (cmd2 == '4'):
code += "\n" + w
if (cmd2 == '5'):
code += "\n" + v
# 3cer bloque para el codigo
if (cmd3 == '1'):
code += "\n" + x
if (cmd3 == '2'):
code += "\n"+ y
if (cmd3 == '3'):
code += "\n" + z
if (cmd3 == '4'):
code += "\n" + w
if (cmd3 == '5'):
code += "\n" + v
# 4to bloque para el codigo
if (cmd4 == '1'):
code += "\n" + x
if (cmd4 == '2'):
code += "\n" + y
if (cmd4 == '3'):
code += "\n" + z
if (cmd4 == '4'):
code += "\n" + w
if (cmd4 == '5'):
code += "\n" + v
# 5to bloque para el codigo
if (cmd5 == '1'):
code += "\n" + x
if (cmd5 == '2'):
code += "\n" + y
if (cmd5 == '3'):
code += "\n" + z
if (cmd5 == '4'):
code += "\n" + w
if (cmd5 == '5'):
code += "\n" + v
print(code)
print("")
# ejercicio 15
comando="32145"
cmd1=comando[0]
cmd2=comando[1]
cmd3=comando[2]
cmd4=comando[3]
cmd5=comando[4]
code=""
# 1
# 0123456789012345678901234567
sentencias="no podras robar si llevas eso "
x=sentencias[0:9]
y=sentencias[14:9:-1]
z=sentencias[16:18]
w=sentencias[19:25]
v=sentencias[26::-1]
# Primer Bloque para el Codigo
if (cmd1 == '1'):
code+=x
if (cmd1 == '2'):
code+=y
if (cmd1 == '3'):
code+=z
if(cmd1 =='4'):
code+=w
if(cmd1 =='5'):
code +=v
#2do bloque para el codigo
if (cmd2 == '1'):
code += "\n" + x
if (cmd2 == '2'):
code += "\n" + y
if (cmd2 == '3'):
code += "\n" + z
if (cmd2 == '4'):
code += "\n" + w
if (cmd2 == '5'):
code += "\n" + v
# 3cer bloque para el codigo
if (cmd3 == '1'):
code += "\n" + x
if (cmd3 == '2'):
code += "\n"+ y
if (cmd3 == '3'):
code += "\n" + z
if (cmd3 == '4'):
code += "\n" + w
if (cmd3 == '5'):
code += "\n" + v
# 4to bloque para el codigo
if (cmd4 == '1'):
code += "\n" + x
if (cmd4 == '2'):
code += "\n" + y
if (cmd4 == '3'):
code += "\n" + z
if (cmd4 == '4'):
code += "\n" + w
if (cmd4 == '5'):
code += "\n" + v
# 5to bloque para el codigo
if (cmd5 == '1'):
code += "\n" + x
if (cmd5 == '2'):
code += "\n" + y
if (cmd5 == '3'):
code += "\n" + z
if (cmd5 == '4'):
code += "\n" + w
if (cmd5 == '5'):
code += "\n" + v
print(code)
print("")
# FIN_BUSQUEDA |
426b08fe06904d662aaa13f140bae9d6726d3316 | M-Elteibi/udemyCourse-CompletePythonDeveloper | /guessNumber.py | 920 | 4 | 4 | import numpy as np
studentList = []
def create_student():
name = input("Please enter the name of the new student: ")
studentData = {
'name': name,
'marks': []
}
return studentData
def add_marks(student, mark):
student['marks'].append(mark)
def calculate_average_mark(student):
if len(student['marks']) > 0:
return sum(student['marks']) / len(student['marks'])
def print_student_details(student):
print('''The Students Name is : {0},
whose marks are {1}, with an Average of {2}
'''.format(student['name'], student['marks'], calculate_average_mark(student))
)
def print_student_list(students):
for stud in students:
print_student_details(stud)
student = create_student()
print(calculate_average_mark(student))
add_marks(student, 70)
print(calculate_average_mark(student))
|
b240d5a7ed2e4250f31ab9aee92eeb4a1586fc31 | swayamsaikar/Data-Sampling-In-Python | /main.py | 2,681 | 4.0625 | 4 | import pandas
import statistics
import plotly.figure_factory as ff
import plotly.graph_objects as go
import random
# !! IN THIS PROGRAM WE HAVE TAKEN 30 RANDOM SAMPLES FROM THE CLAPDATA AND FIND THEIR MEAN AND RETURN IT
# !! WE ALSO HAVE WRITTEN STANDARD_DEVIATION FUNCTION REPEAT THE ABOVE LINE 100 TIMES SO TYHAT IT WILL GET 100 DIFFERENT MEANS AND STORE IT IN THE MEAN_LIST VARIABLE
# !! AND WE ARE ONLY PLOTING GRAPH
# reading the csv data
data = pandas.read_csv("medium_data.csv")
# extracting the claps column and converting it to a list
clapData = data["claps"].tolist()
print(f"Mean of the clapData is -> {statistics.mean(clapData)}")
print(f"Standard Deviation of the clapData is -> {statistics.stdev(clapData)}")
def random_mean_generator(counter):
dataset = []
# The code inside will run for 30 times
for i in range(0, counter):
# here i have to find a random number between 0 to total length of clapData
random_index = random.randint(0, len(clapData)-1)
# here i have to find the value on that particular random index and append it in the dataset list
random_index_value = clapData[random_index]
# appending the index value
dataset.append(random_index_value)
mean = statistics.mean(dataset)
return mean
def standard_Deviation():
mean_list = []
# The code inside this loop will run for 100 times
for i in range(0, 100):
# so this piece of code will find 30 random indexs between 0 and length of clapData-1 and its values and find the mean of them and return it
set_of_means = random_mean_generator(30)
# and we will append each mean to mean_list array
mean_list.append(set_of_means)
print(f"Length of the mean_list is -> {len(mean_list)}") # length -> 100
print(
f"Standard Deviation of the sample distribution -> {statistics.stdev(mean_list)}")
print(
f"Mean of the distribution is -> {statistics.mean(mean_list)}")
# and then we will plot a graph on the list of mean
plotgraph(mean_list)
def plotgraph(meanList):
# here we are find the
df = meanList
mean = statistics.mean(meanList)
# we will create a distplot with the list of means
figure = ff.create_distplot([df], ["clapData"], show_hist=True)
# we have to draw a line to indicate the location of the mean (the mean will always be in a random position whenever you will run this program because we are take random 30 samples in the random_mean_generator() function)
figure.add_trace(go.Scatter(x=[mean, mean], y=[0, 1], mode="lines"))
# and here we have to show the figure
figure.show()
standard_Deviation()
|
00a2e8ef58de2da0de62f9fb58aecf79aa9666dc | bonicim/technical_interviews_exposed | /src/algorithms/misc/daily_temperatures.py | 1,284 | 4.5 | 4 | def get_days_to_warmer_temp(temperatures):
"""
Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
"""
def next_future_day_temp():
return increasing_temps_stack[-1][1]
def next_future_day_index():
return increasing_temps_stack[-1][0]
days_till_increase = [0] * len(temperatures)
increasing_temps_stack = []
for index in range(
len(temperatures) - 1, -1, -1
): # loop through list of temps from right to left
current_temp = temperatures[index]
while increasing_temps_stack and current_temp >= next_future_day_temp():
increasing_temps_stack.pop()
if increasing_temps_stack:
days_till_increase[index] = next_future_day_index() - index
increasing_temps_stack.append((index, current_temp))
return days_till_increase
|
e8acdf823445de2c1c2a7ec9205a8ee0e9a709be | tangx/python36project | /randpass/使用string模块的randpass.py | 1,192 | 3.875 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
@author: tangxin@haowan123.com
@python_version: python2.7
@python_version: python3.6
@file: 使用string模块的randpass.py
@time: 2017/8/16 11:43
"""
import os
import sys
import string
import random
# print(string.ascii_letters) # 所有字母
# print(string.ascii_lowercase) # 小写字母
# print(string.ascii_uppercase) # 大写字母
# print(string.digits) # 数字
# print(string.hexdigits) # 16进制符号(大写)
# print(string.octdigits) # 8进制符号
# print("whitespace: ", string.whitespace) # 空白字符,含换行符
# print("punctuation: ", string.punctuation) # 符号
#
# print("printable: ", string.printable, " : end") # 上面的所有的并集
def randpass(size=20, chars="", upper=False, lower=False, digit=False, punc=False):
if upper is True:
chars += string.ascii_uppercase
if lower is True:
chars += string.ascii_lowercase
if digit is True:
chars += string.digits
if punc is True:
chars += string.punctuation
return ''.join([random.choice(chars) for _ in range(size)])
if __name__ == '__main__':
print("x"*20)
print(randpass(chars='iloveyou'))
|
e8457fc37ef41a062547d89cbda1d03eaffe2eb6 | ckronber/PythonExamples | /Intermediate/mapFunction.py | 248 | 4.03125 | 4 | #Map Function
li = {1,2,3,4,5,6,7,8,9,10}
def func(x):
return x**x
#map function printed
print(list(map(func,li)))
#list comprehension
print([func(x) for x in li])
#list comprehension for even numbers
print([func(x) for x in li if x%2==0]) |
7a8a86d333562ba5dc0c84b1c93be57b68aa0f66 | chunweiliu/leetcode | /problems/valid-palindrome/valid_palindrome.py | 657 | 3.625 | 4 | class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
# s = ''.join([c.lower() for c in s if c.isalnum()])
# return s == s[::-1]
i, j = 0, len(s) - 1
while i <= j:
if s[i].lower() == s[j].lower():
i += 1
j -= 1
elif not s[i].isalnum():
i += 1
elif not s[j].isalnum():
j -= 1
else:
break
if i > j:
return True
return False
if __name__ == '__main__':
s = '1a2'
print Solution().isPalindrome(s)
|
e33e3163cbab057c86941590a7de2f89dfbd0cc8 | BasavaG/python_sandbox | /numericpy.py | 981 | 4.5 | 4 | #Creating arrays with numpy
import numpy as np
arr1 = np.array([1,2,3,4,5])
print(f"{arr1} and type is {type(arr1)}" )
#2- D array
arr2 = np.array([[1,2,3],[4,5,6]])
print(arr2)
# 3 D array
arr3 = np.array([[[1,2,3], [4,5,6]],[[7,8,9],[10,11,12]]])
print(arr3)
# To check the dimensions of the array use "ndim" attribute which returns integer.
print("dimesnion of array1", arr1.ndim)
print("dimesnion of array2", arr2.ndim)
print("dimesnion of array3", arr3.ndim)
# creating N dimensional array. can be created using ndmin attribute
arrn= np.array([1,2,3,4,5], ndmin=5)
print(arrn)
# Accesing array elements
r1= arr1[0]
r2= arr1[4]
print("0th element of array1 is ", r1)
print("4th element of array1 is ", r2)
# Accesing 2-D or matrices elements
print(arr2)
print("Access 2nd rows 3rd element", arr2[1,2])
# Accessing 3-D array elements
print(arr3)
print("Access 3rd row 2nd element", arr3[1,0,1])
# Negative indexing
print("Access last element of 3-D array", arr3[1,1,-1]) |
406095543cfb04ce273b07c2d05cb692088d6367 | achristopher4/Recipe-Scaler | /CMPSC HW4.py | 2,436 | 4.15625 | 4 | """
Alex Christopher
abc5885@psu.edu
HW4
"""
import math
##Introduction/Instructions
print("This is a recipe scaler for serving large crowds!")
print("Enter one ingredient per line, with a numeric value first.")
print("Indicate the end of input with an empty line.")
##dictionary and saved values
savedValues = {}
count = 0
##Record user input
while True:
save = input(" ")
if save == "":
break
amount, unit, item = save.split(' ', 2)
savedValues[count] = amount, unit, item
count += 1
##Repeat recipe list
print("Here is the recipe that has been recorded: ")
repeatCount = 0
while repeatCount < count:
amount = savedValues[repeatCount][0]
unit = savedValues[repeatCount][1]
item = savedValues[repeatCount][2]
print("%-10s%-10s%-10s"%(amount, unit, item))
repeatCount += 1
##Serving Size Input
servingSize = int(input("How many does this recipe serve? "))
mustServe = int(input("How many people must be served? "))
##Serving Size Algorthim
if mustServe <= servingSize:
print(f'The recipe will serve all the guests')
elif (mustServe / servingSize) % 2 == 0:
newServingSize = mustServe // servingSize
print(f'Multiplying the recipe by {newServingSize}')
else:
findNewServing = mustServe // servingSize
newServingSize = findNewServing + 1
print(f'Multiplying the recipe by {newServingSize}')
##Creating new recipe to support the amount of guest
repeatCount = 0
remainder = ''
while repeatCount < count:
amount = savedValues[repeatCount][0]
unit = savedValues[repeatCount][1]
item = savedValues[repeatCount][2]
if '/' in amount:
number, slash, denom = amount.partition('/')
number = int(number)
setNumber = int(number)
denom = int(denom)
number *= newServingSize
##Extra Credit
if number % denom != 0:
gcd = math.gcd(number, denom)
number = number // gcd
denom = denom // gcd
if number / denom > 1:
remainder = number // denom
number = number - (remainder * denom)
remainder = str(remainder) + ' '
amount = remainder + str(number) + '/' + str(denom)
else:
amount = int(amount)
amount *= newServingSize
print("%-10s%-10s%-10s"%(amount, unit, item))
repeatCount += 1
##New Serving Size
totalServings = servingSize * newServingSize
print(f'Serves {totalServings}')
|
700ff77bc10c700b79885ac017ee2d10326aba73 | kathytbui/mythical_creatures_python | /src/mythical_creatures/direwolf.py | 806 | 3.5 | 4 | class Direwolf:
def __init__(self, name, home = 'Beyond the Wall', size = 'Massive'):
self.name = name
self.home = home
self.size = size
self.starks_to_protect = []
self.hunts_white_walkers = True
def protects(self, stark):
if stark.location == self.home:
stark.protected()
self.starks_to_protect.append(stark)
def leaves(self, stark):
if self.starks_to_protect
self.starks_to_protect.remove(stark)
class Stark:
def __init__(self, name, location = 'Winterfell'):
self.name = name
self.location = location
self.safe = False
self.house_words = 'Winter is Coming'
def is_safe(self):
return self.safe
def protected(self):
self.safe = True
|
c8812ed95984048b2964fdcc399f7093c8cd5859 | markomamic22/PSU_LV | /LV1/Drugi.py | 368 | 3.90625 | 4 | ocjena = -1.0
while ((ocjena < 0.0) or (ocjena > 1.0)):
ocjena = float(input("Unesite broj između 0 i 1: "))
def cases(ocjena):
if(ocjena >= 0.9):
print('A')
elif(ocjena >= 0.8):
print('B')
elif(ocjena >= 0.7):
print('C')
elif(ocjena >= 0.6):
print('D')
elif(ocjena < 0.5):
print('F')
cases(ocjena)
|
fccd7f7a94edae00503b01293b1cefed64396a40 | gogeekness/Pygames_Tiles | /Py_tiles/Gtiles_Class.py | 1,572 | 3.53125 | 4 | # Tile class
# This will setup the graphical displaying of the tiles
#
# It will pull the color and status from teh board class
#
# --------------------------------------------------------
import os, pygame, random, math
import Tile_Config as config
# import Board_Class as board
def load_image(subfile, tcolor):
try:
# this code loads the specific color for the tile.
image = pygame.image.load(os.path.join(config.data_dir, (subfile + tcolor)))
except pygame.error:
raise SystemExit('Could not load tile image.', os.path.join(config.data_dir, (subfile + tcolor)))
return image
# constructor for class Tile
class Tile(pygame.sprite.Sprite):
image = None
# Construct the tiles
def __init__(self, pos, tcolor):
pygame.sprite.Sprite.__init__(self, self.containers)
self.image = load_image('Tiles_01_', (tcolor + '.png'))
self.rect = self.image.get_rect()
self.pos = pos
self.rect.x = pos[0]
self.rect.y = pos[1]
self.speedx = config.speed
self.speedy = config.speed
def update(self):
self.rect.move_ip(self.speedx, self.speedy)
# if hit edge reverse direction
if self.rect.left < 0 or self.rect.right > config.width:
self.speedx = -self.speedx
self.rect.x += self.speedx
if self.rect.top < 0 or self.rect.bottom > config.height:
self.speedy = -self.speedy
self.rect.y += self.speedy
#follow cursor
# shift up
# shift down
# shift left
# shift right |
2cd96408c1cf249f4595dea257ff936bc252b8e4 | bhuvanjs25/Python-Basics | /for4.py | 420 | 4.0625 | 4 | #print("searching for a value 3")
#or i in[9,41,12,3,74,15]:
# if i==3:
# print("true",i)
# elif i!=3:
# print(i)1x
print("find the smallest value")
small= None
for i in[9,41,12,3,74,15]:
#if small is none replace it with i
if small is None:
small=i
#if i is smaller than small replace small with i
elif i<small:
small=i
print("smallest value is: ",small)
|
5409cb2ddb690e2bdc967850ca25651155358714 | rafajob/Python-beginner | /contanumero.py | 173 | 3.875 | 4 | numero = int(input("Digite o valor de n: "))
soma = 0
while (numero != 0) :
resto = numero % 10
soma = soma + resto
numero = numero // 10
print(soma)
|
6411b286f9d19b077dbcc3c03988ddb8bc5360f7 | JavaRod/SP_Python220B_2019 | /students/shodges/lesson01/calculator/test.py | 1,079 | 3.734375 | 4 | from unittest import TestCase
from adder import Adder
from subtracter import Subtracter
from multiplier import Multiplier
from divider import Divider
from calculator import Calculator
class AdderTests(TestCase):
def test_adding(self):
adder = Adder()
for i in range(-10, 10):
for j in range(-10, 10):
self.assertEqual(i + j, adder.calc(i, j))
class SubtracterTests(TestCase):
def test_subtracting(self):
subtracter = Subtracter()
for i in range(-10, 10):
for j in range(-10, 10):
self.assertEqual(i - j, subtracter.calc(i, j))
class MultiplierTest(TestCase):
def test_multiplying(self):
multiplier = Multiplier()
for i in range(-10, 10):
for j in range(-10, 10):
self.assertEqual(i * j, multiplier.calc(i, j))
class DividerTest(TestCase):
def test_dividing(self):
divider = Divider()
for i in range(-10, 10):
for j in range(-10, 10):
self.assertEqual(i / j, divider.calc(i, j))
|
3497bd42bcce0d8560d58ddf8597489c0afcb330 | blackwings001/algorithm | /leetcode/1-50/_29_divide.py | 1,304 | 3.578125 | 4 | class Solution(object):
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
if dividend == 0:
return 0
# 先判断dividend和divisor是否同号,结果1先按两个正数来做,如果两者异号,结果为(-结果1 - 1)(LEETCODE的结果不一样,他认为结果为-结果1)
negative = dividend ^ divisor < 0
dividend = abs(dividend)
divisor = abs(divisor)
# 主循环,找到diviend大于等于divisor右移最大的位数,此时说明diviend至少包含1 << i个divisor, 则dividend -= divisor << i和result += 1 << i
result = 0
while dividend >= divisor:
for i in range(31, -1, -1):
if dividend >> i >= divisor:
result += 1 << i
dividend -= divisor << i
break
# 判断result范围
if (result >= 1 << 31 and not negative) or (result > 1 << 31 + 1 and negative):
return (1 << 31) - 1
return -result if negative else result
if __name__ == '__main__':
dividend = -2147483648
divisor = -1
result = Solution().divide(dividend, divisor)
print(dividend//divisor)
print(result) |
e7632595390b3f3ec81d1d16696dcc18c351a286 | mernaadell/ProblemSolving | /Easy/Mars Exploration.py | 407 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 5 22:09:15 2019
@author: merna
"""
if __name__ == '__main__':
count=0
s = input()
x=len(s)/3
s2="SOS"
j=0
for i in range(len(s)):
if j==3:
j=0
if s[i]!=s2[j] :
count+=1
j+=1
else:
j+=1
print(count)
|
e684e5498ad1624b683960f7cb87f12979ab26ad | BZAghalarov/Hackerrank-tasks | /Cracking coding interview/19 DP Coin Change.py | 1,396 | 3.640625 | 4 |
'''
https://www.hackerrank.com/challenges/ctci-coin-change/problem
'''
'''
#!/bin/python3
# Complete the ways function below.
def ways(n, coins):
# Complete this function
n_perms = [1]+[0]*n
for coin in coins:
for i in range(coin, n+1):
n_perms[i] += n_perms[i-coin]
return n_perms[n]
if __name__ == '__main__':
n, m = map(int,input().split())
coins = list(map(int, input().rstrip().split()))
res = ways(n, coins)
print(res)
'''
# !/bin/python3
import sys
def make_change(S, m, n):
# We need n+1 rows as the table is constructed
# in bottom up manner using the base case 0 value
# case (n = 0)
table = [[0 for x in range(m)] for x in range( n +1)]
# Fill the entries for 0 value case (n = 0)
for i in range(m):
table[0][i] = 1
# Fill rest of the table entries in bottom up manner
for i in range(1, n+ 1):
for j in range(m):
# Count of solutions including S[j]
x = table[i - S[j]][j] if i - S[j] >= 0 else 0
# Count of solutions excluding S[j]
y = table[i][j - 1] if j >= 1 else 0
# total count
table[i][j] = x + y
return table[n][m - 1]
n, m = input().strip().split(' ')
n, m = [int(n), int(m)]
coins = [int(coins_temp) for coins_temp in input().strip().split(' ')]
print(make_change(coins, m, n))
|
a910a948044945645ee74b58856324b9474a8d7e | Ternt/Algorithms | /Algorithms/Binary Search.py | 766 | 4.09375 | 4 | arrayData = [1,10,21,35,36,50,69,70,74,98]
searchItem = int(input("Input search item: "))
def binarySearch(searchItem):
Found = False
searchFailed = False
First = 0
Last = len(arrayData) - 1
while Found == False and searchFailed == False:
middle = (First + Last) // 2
if arrayData[middle] == searchItem:
Found = True
else:
if First >= Last:
searchFailed = True
else:
if arrayData[middle] > searchItem:
Last = middle - 1
First = middle + 1
if Found == True:
print(middle)
else:
print("Item is not in array")
binarySearch(searchItem)
|
57d72d573f5b41cd8153feb6afec1b7334f5e3e9 | diderot-edu/diderot-cafe | /python/asymptotics.py | 1,298 | 3.703125 | 4 | from sympy import *
from sympy.parsing.sympy_parser import parse_expr
def grade_bigoh(ans, sol, x):
'''
Check that ans and sol of the variable x have the same order of magnitude.
Examples:
grade_bigoh('n', 'n', 'n')
grade_bigoh('log(n)', 'n', 'n')
grade_bigoh('logn(log(n))', 'log(n)', 'n')
'''
n = Symbol(x)
ans = parse_expr(ans, evaluate=False)
# unwrap if inside big-oh.
if ans.is_Order:
ans = ans.expr
sol = parse_expr(sol, evaluate=False)
l = limit(ans/sol, n, oo)
if l.is_infinite:
response = {"is_error": False, "is_correct": False, "ratio": 0.0, "feedback": "Your answer dominates the correct solution."}
elif l.evalf() == 0.0:
print(f"result = {l.evalf()}")
response = {"is_error": False, "is_correct": False, "ratio": 0.0, "feedback": "Your answer is dominated by the correct solution"}
elif l.evalf() > 0.0:
print(f"result = {l.evalf()}")
response = {"is_error": False, "is_correct": True, "ratio": 1.0, "feedback": "Your answer has the same asymptotic order as the solution."}
else:
response = {"is_error": True, "is_correct": False, "ratio": 0.0, "feedback": "Sorry I do not have useful feedback."}
return response
|
5205b37f8c2b3adbdd438b90ccc331c0097aa4e1 | nehamjain10/EE2703_Assignments | /Week 4/EE2703_ASSIGN4_EE19B084.py | 8,477 | 3.859375 | 4 | ##**********************************************************************************************************************************************************************
# EE2703 Applied Programming Lab 2021
# Assignment 4
#
# Purpose : To calculate the Fourier Series Coefficients for the given signals and verify the results using graphs.
# Author : Neham Jain (EE19B084)
# Input : Program requires no input
# Output : Plots different graphs as specified in the report
#
# NOTE: While plotting, we have tried to reduce the code redundancy as much as possible to minimize the size of the code
##**********************************************************************************************************************************************************************
#Importing the necessary libraries to be used in our program
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate
import os
import math
#Defining the exponential function
def exponential(x):
return np.exp(x)
#Defining the cos(cos(x)) function
def cos_cos(x):
return np.cos(np.cos(x))
#extending exponential function to be periodic with given time period
def exp_extension(x):
time_period=2*np.pi
return exponential(x%time_period)
#Defining the function f(x)*cos(kx) to calculate fourier coefficients
def mul_by_cos(x,func,k):
return func(x)*np.cos(k*x)
#Defining the function f(x)*sin(kx) to calculate fourier coefficients
def mul_by_sin(x,func,k):
return func(x)*np.sin(k*x)
#This function returns the first n Fourier Series Coefficients of the function f using the integration method
def calculate_fourier_series_coefffs(n,function):
a = np.zeros(n) #List which stores all the coefficients
a[0] = scipy.integrate.quad(function,0,2*math.pi)[0]/(2*math.pi) #Calculating a0
for i in range(1,n):
if(i%2==1):
a[i] = scipy.integrate.quad(mul_by_cos,0,2*math.pi,args=(function,int(i/2)+1))[0]/math.pi #Calculating an
else:
a[i] = scipy.integrate.quad(mul_by_sin,0,2*math.pi,args=(function,int(i/2)+1))[0]/math.pi #Calculating bn
return a
#Plots the Fourier Coefficients in semilogy and loglog scale
def plot_fourier_coeffs(coeffs,type,ylabel,title,xlabel="Fourier Series Coefficients"):
plt.figure()
if type=="semilogy":
plt.semilogy(np.abs(coeffs),'ro',label=r"Fourier Series Coefficients")
if type=="loglog":
plt.loglog(np.abs(coeffs),'ro',label=r"Fourier Series Coefficients")
plt.legend()
plt.grid(True)
plt.title(title)
plt.ylabel(xlabel)
plt.xlabel(ylabel)
plt.savefig(f"plots/{title}.jpg")
#using lstsq for finding value of matrix c that best fits the equation Ac=b
def matrix_method(A,f,x):
return scipy.linalg.lstsq(A,f(x))[0]
#Function for plotting general functions
def general_func_plot(x_vals,y_vals,title,fmt,type="semilogy",xlabel="x",ylabel="y"):
plt.figure()
plt.grid(True)
if type =="semilogy":
plt.semilogy(x_vals,y_vals,fmt)
elif type =='log':
plt.loglog(x_vals,y_vals,fmt)
elif type =="normal_scale":
plt.plot(x_vals,y_vals,fmt)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
plt.savefig(f"plots/{title}.jpg")
#Plotting aperiodic e^x and periodically extended e^x in log scale from x = -2pi to +4pi by splitting the x range into 10000 points from -2pi to 4pi
def plot_exponential(x_vals):
plt.figure(1) #figure-1
plt.semilogy(x_vals,exponential(x_vals),'m',label='Aperiodic Exponential')
plt.semilogy(x_vals,exp_extension(x_vals),'g',label='Periodically Extended Exponential')
plt.grid(True)
plt.ylabel(r'$log(e^{x})$',fontsize=15)
plt.xlabel(r'$x$',fontsize=15)
plt.legend()
plt.savefig("plots/exponential.jpg")
#Plotting the coefficents obtained by matrix method and integration method and see deviation between the two approaches
def comparing_coeffs(coeffs_int,coeffs_mat,type,ylabel,title,xlabel="Magnitude Value"):
plt.figure()
if type=="semilogy":
plt.semilogy(np.abs(coeffs_int),'go',label=r'Integration Approach')
plt.semilogy(np.abs(coeffs_mat),'bo',label=r"Least Squares Approach")
if type=="loglog":
plt.loglog(np.abs(coeffs_int),'go',label=r'Integration Approach')
plt.loglog(np.abs(coeffs_mat),'bo',label=r'Least Squares Approach')
plt.legend()
plt.grid(True)
plt.title(title)
plt.ylabel(xlabel)
plt.xlabel(ylabel)
plt.savefig(f"plots/{title}.jpg")
#Function to plot the values of coefficients found by the 2 methods to see the deviations between the two functions
def plotting_convergence(fourier_func,f,x_vals,title,xlabel,ylabel):
plt.figure()
plt.semilogy(fourier_func, 'm', label = 'Fourier representation')
plt.semilogy(f(x_vals), 'c', label = 'Original function')
plt.grid(True)
plt.legend(loc='upper right')
plt.title(title)
plt.ylabel(xlabel)
plt.xlabel(ylabel)
plt.savefig(f"plots/{title}.jpg")
#Main function from which all other functions are called
def main():
#Create directory for storing plots
os.makedirs("plots",exist_ok=True)
#Question 1
x_vals=np.linspace(-2*np.pi,4*np.pi,10000)
plot_exponential(x_vals) #Plotting exponential plot
y_vals=cos_cos(x_vals)
general_func_plot(x_vals,y_vals,"Cos_Cos_Plot","r-",type="normal_scale") #Plottting cos_cos plot
#Question 2, Calculating Fourier Coefficients
cos_cos_fsc = calculate_fourier_series_coefffs(51,cos_cos)
exp_fsc = calculate_fourier_series_coefffs(51,exp_extension)
#Question3, Plotting Fourier Series Coeffs in different scales
plot_fourier_coeffs(cos_cos_fsc,type="semilogy",ylabel=r'$n$',title=r'Magnitude spectrum of coefficients in log scale for $cos(cos(x))$')
plot_fourier_coeffs(cos_cos_fsc,type="loglog",ylabel=r'$n$',title=r'Magnitude spectrum of coefficients in loglog scale for $cos(cos(x))$')
plot_fourier_coeffs(exp_fsc,type="loglog",ylabel=r'$n$',title=r'Magnitude spectrum of coefficients in loglog scale for $e^x$')
plot_fourier_coeffs(exp_fsc,type="semilogy",ylabel=r'$n$',title=r'Magnitude spectrum of coefficients in log scale for $e^x$')
#Question4, Least Squares Approach
x = np.linspace(0,2*np.pi,401)
x=x[:-1]
A = np.zeros((400,51))
A[:,0]=1
for k in range(1,26):
A[:,2*k-1] = np.cos(k*x)
A[:,2*k] = np.sin(k*x)
#Question5, Finding the best fit of coefficients using matrix method
coeffs_exp_lstsq = matrix_method(A,exponential,x)
coeffs_cos_cos_lstsq = matrix_method(A,cos_cos,x)
#Question6, Comparing deviation of coefficients between the two methods
comparing_coeffs(exp_fsc,coeffs_exp_lstsq,type="semilogy",ylabel=r'$n$',title=r'Comparing magnitude spectrum of coefficients in log scale for $e^x$',xlabel="Magnitude Value")
comparing_coeffs(exp_fsc,coeffs_exp_lstsq,type="loglog",ylabel=r'$n$',title=r'Comparing magnitude spectrum of coefficients in loglog scale for $e^x$',xlabel="Magnitude Value")
comparing_coeffs(cos_cos_fsc,coeffs_cos_cos_lstsq,type="semilogy",ylabel=r'$n$',title=r'Comparing magnitude spectrum of coefficients in log scale for $cos(cos(x))$',xlabel="Magnitude Value")
comparing_coeffs(cos_cos_fsc,coeffs_cos_cos_lstsq,type="loglog",ylabel=r'$n$',title=r'Comparing magnitude spectrum of coefficients in loglog scale for $cos(cos(x))$',xlabel="Magnitude Value")
max_error_f1 = np.max(np.abs(exp_fsc - coeffs_exp_lstsq))
max_error_f2 = np.max(np.abs(cos_cos_fsc - coeffs_cos_cos_lstsq))
print("Maximum error for coefficients of e^x is ",max_error_f1)
print("Maximum error for coefficients of cos(cos(x)) is ",max_error_f2)
#Question7, Comparing deviation of functions between the two methods
fourier_func_exp = np.matmul(A,coeffs_exp_lstsq)
plotting_convergence(fourier_func_exp,exp_extension,x,title=r'Convergence of Fourier Series representation to actual function for e^x',xlabel=r'$x$',ylabel=r'Value in log scale')
fourier_func_cos = np.matmul(A,coeffs_cos_cos_lstsq)
plotting_convergence(fourier_func_cos,cos_cos,x,title=r'Convergence of Fourier Series representation to actual function for cos(cos(x))',xlabel=r'$x$',ylabel=r'Value in log scale')
main() |
cd896d21abc66cfff2e380b6d6506987a3640394 | sakinaiz/dsp | /python/q8_parsing.py | 892 | 4.28125 | 4 | # The football.csv file contains the results from the English Premier League.
# The columns labeled ‘Goals’ and ‘Goals Allowed’ contain the total number of
# goals scored for and against each team in that season (so Arsenal scored 79 goals
# against opponents, and had 36 goals scored against them). Write a program to read the file,
# then print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
# Pre-work: Question 8
# Author: Sakina Zabuawala
import csv
with open("football.csv") as fid:
reader = csv.reader(fid)
team_goaldiff = {}
next(reader, None)
for row in reader:
team_goaldiff[row[0]] = abs(int(row[5]) - int(row[6]))
print('Team: ' + min(team_goaldiff, key=team_goaldiff.get))
# min(team_goaldiff, key=lambda k: team_goaldiff.get(k) if team_goaldiff.get(k)>=0 else float("inf"))
|
b01534bb410456508ac34a2e4215a0d4aa351650 | Akshay-Chandelkar/PythonTraining2019 | /Ex69_LongestShortestLine.py | 742 | 4.3125 | 4 |
def LongestShortestLine(file_name):
fd = open(file_name)
if fd != None:
line = fd.readline()
max_line = line
min_line = line
while line != '':
line = fd.readline()
if line == '':
break
if len(line) > len(max_line):
max_line = line
if len(line) < len(min_line):
min_line = line
return max_line, min_line
def main():
file_name = input("Enter the filename to find longest and shortest line :: ")
res1, res2 = LongestShortestLine(file_name)
print("\nThe longest line is :: {} \nThe shortest line is :: {}".format(res1, res2))
#print(res1,res2)
if __name__ == '__main__':
main()
|
a660da234b02f6bc0c546ca68781ccab5c84891b | p-s-vishnu/udacity | /machine-learning-project/svm/svm_author_id.py | 1,675 | 3.765625 | 4 | #!/usr/bin/python
"""
This is the code to accompany the Lesson 2 (SVM) mini-project.
Use a SVM to identify emails from the Enron corpus by their authors:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
from sklearn import svm
from sklearn.metrics import accuracy_score
sys.path.append("/Users/Focus/Documents/GitHub/udacity/machine-learning-project/tools/")
from email_preprocess import preprocess
# features_train and features_test are the features for the training
# and testing data sets, respectively
# labels_train and labels_test are the corresponding item labels
features_train, features_test, labels_train, labels_test = preprocess()
#########################################################
# your code goes here ###
clf = svm.SVC(C=10000, kernel='rbf')
# Slicing training set
features_train = features_train[:len(features_train) / 100]
labels_train = labels_train[:len(labels_train) / 100]
t0 = time()
clf.fit(features_train, labels_train)
t1 = time()
print 'training time:', round(t1 - t0, 3), 's'
pred = clf.predict(features_test)
score = accuracy_score(labels_test, pred)
print 'accuracy:', score
t2 = time()
print 'testing time:', round(t2 - t1, 3), 's'
print 'test samples size:', len(pred)
# 0 is for Sara
# 1 is for Chris
names = {
0: 'Sara',
1: 'Chris'
}
# Given it is a zero indexed list
# hence prediction for 10th
# print '10th prediction:', names[pred[10]]
# prediction for 26th
# print '26th prediction:', names[pred[26]]
# prediction for 50th
# print '50th prediction:', names[pred[50]]
print 'Total number of Chris(1) mail', sum(pred)
#########################################################
|
b0aab40a70aa6d20572a7f357aa7c87364de3ffc | kuldeep7688/Algorithms-Design-and-Analysis-Part-1 | /week_1/problem_assignment/count_inversion_solution.py | 2,502 | 4.21875 | 4 | import time
import math
import random
def count_inversion_routine(array_a, array_b):
"""
Count split inversions and merge arrays routine.
Args:
array_a (list): sorted array
array_b (list): sorted array
Returns:
list, count : sorted merged list, count of split inversion
"""
array_a_idx = 0
array_b_idx = 0
final_array = [None]*(len(array_a) + len(array_b))
final_array_idx = 0
total_split_inversions = 0
while array_a_idx < len(array_a) and array_b_idx < len(array_b):
if array_a[array_a_idx] <= array_b[array_b_idx]:
final_array[final_array_idx] = array_a[array_a_idx]
final_array_idx += 1
array_a_idx += 1
else:
final_array[final_array_idx] = array_b[array_b_idx]
total_split_inversions += len(array_a) - 1 - array_a_idx + 1
final_array_idx += 1
array_b_idx += 1
# if left items in array_b
while array_b_idx < len(array_b):
final_array[final_array_idx] = array_b[array_b_idx]
final_array_idx += 1
array_b_idx += 1
# if left items in array_a
while array_a_idx < len(array_a):
final_array[final_array_idx] = array_a[array_a_idx]
final_array_idx += 1
array_a_idx += 1
return final_array, total_split_inversions
def count_inversions(array):
"""
Implementation of count inversions using merge sort algorithm.
Args:
array (list): array
Returns:
list, int: sorted array, count of total inversion
"""
if len(array) == 1:
return array, 0
else:
array_a, left_inversions = count_inversions(array[: len(array) // 2])
array_b, right_inversions = count_inversions(array[len(array) // 2: ])
merged_array, split_inversions = count_inversion_routine(array_a, array_b)
return merged_array, left_inversions + right_inversions + split_inversions
if __name__ == "__main__":
file_path = "IntegerArray.txt"
with open(file_path) as i:
input_data = i.readlines()
input_data = [int(inp.strip()) for inp in input_data]
print("Total length of the input array is {}.".format(len(input_data)))
start_time = time.time()
sorted_array, num_of_inversions = count_inversions(input_data)
end_time = time.time()
print("Number of total inversions are : {}".format(num_of_inversions))
print("Time Required for sorting == {} seconds".format(end_time - start_time))
|
e3faecd3cdcce51263aaa109022c2a239166dc01 | jonahhill/mlprojects-py | /TimeSeriesRegression/data_explore/__init__.py | 1,402 | 3.625 | 4 | import matplotlib.pyplot as plt
from matplotlib import colors
def create_fig():
fig_number = create_fig.fig_number + 1
plt.figure(fig_number, figsize=(20,10))
create_fig.fig_number = 0
def draw_simple_scatterplot(x,y , x_title, subplotnum):
print x.shape,y.shape , x_title, subplotnum
plt.subplot(subplotnum)
plt.xlabel(x_title, fontsize=18)
plt.scatter(x, y, alpha=0.3)
def draw_scatterplot_one(x,y , x_title, subplotnum, y_title=None, c=None):
draw_scatterplot([(x,y)], x_title, subplotnum, y_title=y_title, c=c)
def draw_scatterplot(data_sets, x_title, subplotnum, y_title=None, c=None):
plt.subplot(subplotnum)
plt.xlabel(x_title, fontsize=18)
plt.ylabel(y_title, fontsize=18)
#if c is None:
# c = range(len(data_sets))
for i, d in enumerate(data_sets):
point_size = 30 if len(d[0]) < 100 else 8
if c is None:
plt.scatter(d[0], d[1], alpha=0.3, s=point_size)
else:
plt.scatter(d[0], d[1], alpha=0.3, s=point_size, c=c[i])
def draw_error_bars(pltnum, x, mean, ulimit, llimit, x_label, y_label=None, do_log=True):
ax = plt.subplot(pltnum)
plt.xlabel(x_label, fontsize=18)
if y_label is not None:
plt.ylabel(y_label, fontsize=18)
if do_log:
ax.set_yscale('log')
plt.errorbar(x, mean, yerr=[llimit, ulimit],
ms=5, mew=2, fmt='--o')
|
b4a180b632612162d0607cc7b0f3ea2ec3d6a5ae | akaliutau/cs-problems-python | /problems/tree/Solution199.py | 585 | 3.5625 | 4 | """ Given a binary tree, imagine yourself standing on the right side of it,
return the values of the nodes you can see ordered from top to bottom.
Example:
Input: [1,2,3,null,5,null,4] Output: [1, 3, 4]
Explanation:
1 <--- bfs level 0
/ \
2 3 <--- bfs level 1
\ \
5 4 <--- bfs level 2
IDEA:
1) use BFS traversing type for tree (i.e. by layers)
2) in this type of traversal the last element in layer obviously will be the rightmost
"""
class Solution199:
pass
|
4f54d02fbf4029b734daa4e36193f4d7c72447a4 | zzploveyou/predict_knockout | /knockout_result.py | 3,638 | 3.578125 | 4 | # coding:utf-8
from collections import defaultdict
from copy import deepcopy
WIN_SCORE = 1
LOSS_SCORE = 0
TIE_SCORE = 0
class Team:
def __init__(self, name, score):
self.name = name
self.score = score
def win(self):
global WIN_SCORE
self.score += WIN_SCORE
def loss(self):
global LOSS_SCORE
self.score += LOSS_SCORE
def tie(self):
global TIE_SCORE
self.score += TIE_SCORE
def __str__(self):
return "{}: {}".format(self.name, self.score)
class Match:
def __init__(self, names, scores):
self.teams = []
for name, score in zip(names, scores):
self.teams.append(Team(name, score))
def getind(self, name):
for idx, team in enumerate(self.teams):
if name == team.name:
return idx
def one_defeat(self, name1, name2):
self.teams[self.getind(name1)].win()
self.teams[self.getind(name2)].loss()
def one_tie(self, name1, name2):
self.teams[self.getind(name1)].tie()
self.teams[self.getind(name1)].tie()
def pairs(self):
names, scores = [], []
for team in self.teams:
names.append(team.name)
scores.append(team.score)
return names, scores
def __str__(self):
self.teams.sort(key=lambda team:team.score, reverse=True)
res = ""
for team in self.teams:
res += "{}: {}\t".format(team.name, team.score)
res += "\n"
return res
def top(self, n=2):
self.teams.sort(key=lambda team:team.score, reverse=True)
res = []
for i in range(n):
res.append(self.teams[i].name)
for i in range(n, len(self.teams)):
# 与第二名同积分
if self.teams[i].score == self.teams[n-1].score:
res.append(self.teams[i].name)
return res
def com(names):
# 产生比赛对.
from itertools import combinations
# return combinations(names, 2)
coms = [
#('SSG', 'FB'),
('SSG', 'G2'),
('FB', 'RNG'),
('FB', 'G2'),
('RNG', 'SSG'),
]
return coms
def predict(names, scores, coms, predict_team, n=2, tag="win"):
print("predict {}:\n".format(tag))
match = Match(names, scores)
matchs = defaultdict(lambda : [])
matchs[match] = []
for name1, name2 in coms:
now_matchs = deepcopy(matchs.keys())
for m in matchs.keys():
tmp = deepcopy(m)
m.one_defeat(name1, name2)
tmp.one_defeat(name2, name1)
matchs[tmp] = deepcopy(matchs[m])
matchs[m].append("{} > {}".format(name1, name2))
matchs[tmp].append("{} > {}".format(name2, name1))
idx = 1
for m, winteams in matchs.items():
res = m.top(n)
if tag == "win":
# 预测某队在所有比赛结束后积分居前n名的可能性
res = res
elif tag == "loss":
res = set([i.name for i in m.teams]) - set(res)
else:
res = []
if predict_team in res:
print "可能性: {}".format(idx)
idx += 1
print str(m).strip()
for wt in winteams:
print wt
print
def main():
# 对名
names = ["RNG", "SSG", "G2", "FB"]
# 目前积分
scores = [3, 3, 2, 0]
coms = com(names)
predict_team = "RNG"
n = 2
predict(names, scores, coms, predict_team, n=2, tag="win")
predict(names, scores, coms, predict_team, n=2, tag="loss")
if __name__ == '__main__':
main()
|
b2dc061718edc18aed81120c2f3981d793be6fd7 | sumanes4u/Anaconda-Projects | /vehicle reservation/CreditCardCalc.py | 3,550 | 4.25 | 4 | # Credit Card Calculation Program (Final Version)
def displayWelcome():
print('This program will determine the time to pay off a credit')
print('card and the interest paid based on the current balance,')
print('the interest rate, and the monthly payments made.')
def displayPayments(balance, int_rate, monthly_payment):
# init
num_months = 0
total_int_paid = 0
payment_num = 1
empty_year_field = format(' ', '8')
# display heading
print('\n', format('PAYOFF SCHEDULE','>20'))
print(format('Year','>10') + format('Balance','>10') +
format('Payment Num', '>14') + format('Interest Paid','>16'))
# display year-by-year account status
while balance > 0:
monthly_int = balance * int_rate
total_int_paid = total_int_paid + monthly_int
balance = balance + monthly_int - monthly_payment
if balance < 0:
balance = 0
if num_months % 12 == 0:
year_field = format(num_months // 12 + 1, '>8')
else:
year_field = empty_year_field
print(year_field + format(balance, '>12,.2f') +
format(payment_num, '>9') +
format(total_int_paid, '>17,.2f'))
payment_num = payment_num + 1
num_months = num_months + 1
# ---- main
# display welcome screen
displayWelcome()
# get current balance and APR
balance = int(input('\nEnter the balance on your credit card: '))
apr = int(input('Enter the interest rate (APR) on the card: '))
monthly_int_rate = apr/1200
yes_response = ('y','Y')
no_response = ('n','N')
calc = True
while calc:
# calc minimum monthly payment
if balance < 1000:
min_monthly_payment = 20
else:
min_monthly_payment = balance * .02
# get monthly payment
print('\nAssuming a minimum payment of 2% of the balance ($20 min)')
print('Your minimum payment would be',
format(min_monthly_payment, '.2f'),'\n')
response = input('Use the minimum monthly payment? (y/n): ')
while response not in yes_response + no_response:
response = input('Use the minimum monthly payment? (y/n): ')
if response in yes_response:
monthly_payment = min_monthly_payment
else:
acceptable_payment = False
while not acceptable_payment:
monthly_payment = int(input('\nEnter monthly payment: '))
if monthly_payment < balance * .02:
print('Minimum payment of 2% of balance required ($' +
str(balance * .02) + ')')
elif monthly_payment < 20:
print('Minimum payment of $20 required')
else:
acceptable_payment = True
# check if single payment pays off balance
if monthly_payment >= balance:
print('* This payment amount would pay off your balance *')
else:
# display month-by-month balance payoff
displayPayments(balance, monthly_int_rate, monthly_payment)
# calculate again with another monthly payment?
again = input('\nRecalculate with another payment? (y/n): ')
while again not in yes_response + no_response:
again = input('Recalculate with another payment? (y/n): ')
if again in yes_response:
calc = True # continue program
print('\n\nFor your current balance of $' + str(balance))
else:
calc = False # terminate program
|
913037b885af99cea7057e32ecb441420e39d482 | bowlofbap/PingPongTrackerPython | /elo.py | 4,582 | 3.8125 | 4 | # Python 3 program for Elo Rating
import psycopg2
import math
import sys
# Function to calculate the Probability
def Probability(rating1, rating2):
return 1.0 * 1.0 / (1 + 1.0 * math.pow(10, 1.0 * (rating1 - rating2) / 400))
# Function to calculate Elo rating
# K is a constant.
# d determines whether
# Player A wins or Player B.
def EloRating(Ra, Rb, Sa, Sb, K):
Sa = int(Sa)
Sb = int(Sb)
# To calculate the Winning
# Probability of Player B
Pb = Probability(Ra, Rb)
# To calculate the Winning
# Probability of Player A
Pa = Probability(Rb, Ra)
# Case -1 When Player A wins
# Updating the Elo Ratings
if (Sa > Sb):
print("player 1 won the game")
Ra = Ra + K * (1 - Pa)
Rb = Rb + K * (0 - Pb)
# Case -2 When Player B wins
# Updating the Elo Ratings
else :
print("player 2 won the game")
Ra = Ra + K * (0 - Pa)
Rb = Rb + K * (1 - Pb)
print("Updated Ratings:-")
print("Ra =", round(Ra, 6)," Rb =", round(Rb, 6))
return Ra, Rb
# Driver code
# Ra and Rb are current ELO ratings
K = 30
def getPlayerFromUsername(username):
sqlString = "SELECT * FROM players WHERE username = %s"
player = None
try:
connection = psycopg2.connect(user = "postgres",
password = "postgres1",
host = "localhost",
port = "5432",
database = "ratingTest")
cursor = connection.cursor()
cursor.execute(sqlString, (username,))
player = cursor.fetchone()
except (Exception, psycopg2.Error) as error :
print ("Error while connecting to PostgreSQL", error)
finally:
#closing database connection.
if(connection):
cursor.close()
connection.close()
return player
def insertNewPlayer(username, name):
sqlString = "INSERT INTO players (username, name) values(%s, %s)"
playerToInsert = (username, name)
try:
connection = psycopg2.connect(user = "postgres",
password = "postgres1",
host = "localhost",
port = "5432",
database = "ratingTest")
cursor = connection.cursor()
cursor.execute(sqlString, playerToInsert)
connection.commit()
except (Exception, psycopg2.Error) as error :
print ("Error while connecting to PostgreSQL", error)
finally:
#closing database connection.
if(connection):
cursor.close()
connection.close()
def postNewMatch(score1, score2, oldElo1, oldElo2, newElo1, newElo2, player1Id, player2Id):
try:
connection = psycopg2.connect(user = "postgres",
password = "postgres1",
host = "localhost",
port = "5432",
database = "ratingTest")
sqlString = "INSERT INTO matches (p1score, p2score, p1ratinginit, p2ratinginit, p1ratingend, p2ratingend) values(%s, %s, %s, %s, %s, %s) RETURNING id"
matchToInsert = (score1, score2, oldElo1, oldElo2, newElo1, newElo2)
cursor = connection.cursor()
cursor.execute(sqlString, matchToInsert)
matchId = cursor.fetchone()[0]
sqlString2 = "INSERT INTO player_match(p1id, p2id, matchid) values(%s, %s, %s)"
playersToInsert = (player1Id, player2Id, matchId)
cursor.execute(sqlString2, playersToInsert)
sqlPlayerString = "UPDATE players SET rating = %s WHERE id = %s"
cursor.execute(sqlPlayerString, (newElo1, player1Id))
cursor.execute(sqlPlayerString, (newElo2, player2Id))
connection.commit()
except (Exception, psycopg2.Error) as error :
print ("Error while connecting to PostgreSQL", error)
finally:
#closing database connection.
if(connection):
cursor.close()
connection.close()
if __name__ == '__main__':
player1=getPlayerFromUsername(sys.argv[1])
player2=getPlayerFromUsername(sys.argv[2])
score1=sys.argv[3]
score2=sys.argv[4]
oldElo1=float(player1[3])
oldElo2=float(player2[3])
newElo1, newElo2 = EloRating(oldElo1, oldElo2, score1, score2, K)
postNewMatch(score1, score2, oldElo1, oldElo2, newElo1, newElo2, player1[0], player2[0])
|
76651f4059bbd69cbc52ceb1cb71fad5a0943b97 | ethanmyers92/90COS_IQT_Labs | /Lab 2H.py | 1,172 | 4.125 | 4 | #Lab 2H
print "Enter the grades for your four students into your gradebook! Enter grade first then name!"
student_dict = {raw_input("Enter first student's name: ") : int(raw_input("Enter first student's grade: "))}
student_dict[raw_input("Enter second student's name: ")] = int(raw_input("Enter second student's grade: "))
student_dict[raw_input("Enter third student's name: ")] = int(raw_input("Enter third student's grade: "))
student_dict[raw_input("Enter fourth student's name: ")] = int(raw_input("Enter fourth student's grade: "))
print student_dict
print ""
print "Grades, High to low: "
print sorted(student_dict.items(), key=lambda x:x[1], reverse=True)
print ""
print "The average grade is : "
class_average = sum(student_dict.values()) / len(student_dict.values())
print class_average
#NOTES:
#for key, value in sorted(student_dict.items()):
# print key, value
#print sorted(student_dict.values()
#print sorted(student_dict, key=student_dict.get, reverse=True)
#To get a list of tuples ordered by value
#Print sorted(student_dict.items(), key=lambda x:x[1])
#student_dict = {"Alice" : 99, "Thomas" : 67, "Betty" : 75, "Dexter" : 83}
|
d902683dd52743ec53197e53c91514512c80b7d9 | nvidda-hub/Leet-Code-Programs | /Maximum Product of Two Elements in an Array.py | 615 | 3.796875 | 4 | num_list = []
n = int(input("Enter number of elements:- "))
for i in range(n):
print("Enter", i + 1, "th element :- ", end="")
ele_input = int(input())
num_list.append(ele_input)
print("list : ", num_list)
count = 0
max_value = 0
for i in range(n):
for j in range(n):
if i != j:
max_value_new = (num_list[i] - 1)*(num_list[j] - 1)
count = count + 1
else:
continue
if max_value_new > max_value:
max_value = max_value_new
else:
continue
print("maximum product in list : ", max_value) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.