blob_id stringlengths 40 40 | repo_name stringlengths 5 119 | path stringlengths 2 424 | length_bytes int64 36 888k | score float64 3.5 5.22 | int_score int64 4 5 | text stringlengths 27 888k |
|---|---|---|---|---|---|---|
43c9ff8d595097a1efa90f5e7d8b748ebc88c8ad | fatezy/Algorithm | /leetCode/easyCollection/array/moveZero.py | 726 | 3.875 | 4 | # 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
#
# 示例:
#
# 输入: [0,1,0,3,12]
# 输出: [1,3,12,0,0]
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
# for i in range(len(nums)):
# if nums[i] == 0:
# nums.remove(0)
# nums.append(0)
# return nums
for i in nums:
if i == 0:
nums.remove(0)
nums.append(0)
return nums
if __name__ == '__main__':
print(Solution().moveZeroes([0,1,0,3,12])) |
9730c6b61c671eeedf11eba9610e94b34f36ab0b | monkeylyf/interviewjam | /hackerrank/pythonista/hackerrank_xml2_find_the_maximum_depth.py | 758 | 3.5625 | 4 | """hackerrank_xml2_find_the_maximum_depth
https://www.hackerrank.com/contests/pythonista-practice-session/challenges/xml2-find-the-maximum-depth
"""
try:
from lxml import etree as ET
except ImportError:
import xml.etree.ElementTree as ET
def main():
n = int(raw_input())
xml = []
for _ in xrange(n):
xml.append(raw_input())
content = '\n'.join(xml)
root = ET.fromstring(content)
depth = 0
queue = [root]
nex_lvl = []
while queue:
node = queue.pop()
for child in node:
nex_lvl.append(child)
if not queue:
queue = nex_lvl
nex_lvl = []
if queue:
depth += 1
print depth
if __name__ == '__main__':
main()
|
156ecc3d784f176ea8eb532e6fdcaa49d1ee4da6 | jsochacki/Google_Foo_Bar_Solutions | /Paying_Henchman.py | 1,126 | 3.53125 | 4 | def answer(total_lambs):
try:
assert isinstance(total_lambs, int)
except AssertionError as e:
raise SystemExit('You need to enter and integer'
'for this function to work')
else:
try:
assert ( 10 <= total_lambs <= 1000000000 )
except AssertionError as e:
raise SystemExit('This function only accepts integers'
'between and including 10 and 10e9')
LAMS = total_lambs
level = 0
while int(total_lambs) >= 0:
total_lambs = int(total_lambs - (0b1 << level))
if int(total_lambs) >= 0:
level = level + 1
least_henchmen = level
total_lambs = LAMS
level = 0
hench_pay = []
while int(total_lambs) >= 0:
if level >= 2:
hench_pay.extend([hench_pay[level - 2] + hench_pay[level - 1]])
else:
hench_pay.extend([1])
total_lambs = int(total_lambs - hench_pay[level])
if int(total_lambs) >= 0:
level = level + 1
most_henchmen = level
return (most_henchmen - least_henchmen)
# %%
|
169748ba736b19cd845ad854441f91fcb8300177 | Lojdquist/Problem14ProjectEuler | /algorithm/collatz.py | 1,056 | 3.6875 | 4 | #problem 14 project euler
import time
from collatzSeqString import genCollatzString
hasDict={}
def collatz(current, steps, seq):
current = int(current)
seq.append(current)
if current == 1 or current in hasDict:
if current in hasDict:
addSequence(seq, hasDict[current])
return steps + hasDict[current]
else:
addSequence(seq, 0)
return steps
elif current % 2 == 0:
return collatz(current/2, steps + 1, seq)
else:
return collatz(current*3 + 1, steps + 1, seq)
def addSequence(seq, steps):
steps = steps
for i in range(len(seq) - 1, 0, -1):
hasDict[seq[i]] = steps
steps += 1
maxSteps = 0
maxIndex = 0
start=time.time()
for i in range(1, 1000000, 1):
c = collatz(i, 0, [])
if c > maxSteps:
maxIndex = i
maxSteps=c
elapsed = (time.time() - start)
print("Max value is ", maxSteps, " optimized took", elapsed, "seconds to execute. Value that generated sequence: ", maxIndex)
print(genCollatzString(maxIndex))
|
93b2c6fb2d3388edf782c02c05c6a36127d05ec2 | Pavanyeluri11/LeetCode-Problems-Python | /defanging_ip_address.py | 229 | 3.71875 | 4 | def defanging(address):
s=''
for i in range(len(address)):
if address[i] == '.':
s+='[.]'
else:
s+=address[i]
del address
return s
print(defanging('1.1.1.1'))
|
86c4748c79e07c1aa9ded7e8edd6b5a62b70f0c7 | anjaligr05/TechInterviews | /grokking_algorithms/recursiveSumArr.py | 118 | 3.75 | 4 | def sum(arr):
if len(arr) == 0:
return 0
else:
return arr[0] + sum(arr[1:])
print sum([1,2,4,3])
print sum([])
|
b95188798aaf2ff1918e319d9abdded2a5cf1269 | dtekluva/cohort7 | /CLASS-ATHA/datastructures/ds2.py | 3,243 | 3.953125 | 4 | # file = open("datastructures/financials.csv", "r")
# # print(file.readline()[12:20]) # GET TAX TYPE VIA SLICING
# # heading_list = file.readline().split(",")
# # print(heading_list)
# # print(heading_list[5])
# cash_transactions = []
# for line in file.readlines():
# transaction_type = line.split(",")[7]
# if transaction_type == "Own Bank Che...":
# print(line.split(",")[5], line.split(",")[8])
#####################
#### DICTIONARIES####
## CREATING DICTIONARIES ##
# DIRECT CREATION
# MY_DICT = {
# "john":["singing", "dancing"],
# "ali":["jumping", "dancing"],
# "simbi":["ten ten", "eating"]
# }
# print(MY_DICT)
# scores = {
# "math": 90,
# "english":77,
# "physics": 68
# }
# print(scores)
# names = ["samuel", "lucas", "mary"]
# ages = [34, 21,19]
# print(list(zip(names, ages)))
my_dict = dict() # empty dictionaries can be created using the dict builtin function
# new_dict = (dict(zip(names, ages))) # dictionaries can also be created using a list of list or list of tuples
# print(new_dict)
# print(my_dict)
# print(list(enumerate(names)))
# UPDATING DICTIONARIES
# print(my_dict)
# my_dict["laptops"] = ["hp", "acer", "dell", "toshiba"]
# my_dict["phones"] = ["apple", "samsung", "nokia"]
# my_dict["sneakers"] = ["nike air", "jordans", "jeezy's", 12]
# my_dict[12] = "INVALID ..OOUPS..!!!"
# print(my_dict)
# print(my_dict.keys())
# print(my_dict.values())
# print(my_dict.items())
# UPDATING DICTIONARY VALUES
import datetime
# print(datetime.date.today())
# print(datetime.datetime.now())
time_now = datetime.datetime.now()
# print("day : ", time_now.day, " Day name : ", time_now.strftime("%A"))
# print("month : ", time_now.month)
# print("year : ", time_now.year)
# print("hour : ", time_now.hour)
# print("min : ", time_now.minute)
# print("second : ", time_now.second)
# print("micro : ", time_now.microsecond)
# print(time_now.strftime("%A"))
# print(time_now.strftime("%b %d, %Y %I:%M%p")) # (-STRPTIME()-) CONVERT TIME FROM DATE OBJECT TO STRING FORMAT OF CHOICE
# sample_date = "2020-20-12"
# print(datetime.datetime.strptime(sample_date, "%Y-%d-%m").strftime("%b %d, %Y %I:%M%p"))
# single add
# bio_dict = dict()
# name = input("Please enter your name : ")
# age = input("Please enter your age : ")
# small_talk = input("Please enter a small talk : ")
# time_created = datetime.datetime.now().strftime("%b %d, %Y %I:%M%p")
# bio_dict[name] = {
# "age": age,
# "small_talk": small_talk,
# "time_created": time_created
# }
# # print(name, age)
# # print(small_talk)
# # print("created at : ", time_created)
# print(bio_dict.values())
import pprint
bio_dict = dict()
while True:
name = input("Please enter your name : ")
age = input("Please enter your age : ")
small_talk = input("Please enter a small talk : ")
time_created = datetime.datetime.now().strftime("%b %d, %Y %I:%M%p")
bio_dict[name] = {
"age": age,
"small_talk": small_talk,
"time_created": time_created
}
action = input("Please do you want to add another ?? y/n : ")
if action == "n":
break
# print(name, age)
# print(small_talk)
# print("created at : ", time_created)
pprint.pprint(bio_dict) |
dcf7d32f100886c7930668cba5fc76b5309eb86e | hoginogithub/python_kiso_dorill | /q05_06.py | 723 | 3.71875 | 4 | import re
def print_double_words(file_content):
doubled = re.compile(r'\b(\w+) (\1\b)+', re.IGNORECASE)
for result in doubled.findall(file_content[0]):
print(f'{result} on line {1}')
for i in range(1, len(file_content)):
for result in doubled.findall(file_content[i]):
print(f'{result} on line {i + 1}')
last_word = file_content[i -1].split(' ')[-1]
if last_word == file_content[i].split(' ')[0]:
print(f'{last_word} repeated on lines {i} and {i + 1}')
content = [
'I have a dream.',
'The the story was not an happy one one.',
'It started on a cold evening of winter in',
'in a small town named Kongrad.'
]
print_double_words(content) |
79f879674530c603faa710400bc96efaf35ff29a | javacode123/oj | /leetcode/middle/backTrack/subsets.py | 762 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# @Time : 2019-08-25 15:29
# @Author : Zhangjialuo
# @mail : zhang_jia_luo@foxmail.com
# @File : subsets.py
# @Software: PyCharm
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def back_tarck(combination, next_nums, size):
if len(combination) == size:
res.append(combination)
else:
for i in range(len(next_nums)):
back_tarck(combination+[next_nums[i]], next_nums[i+1:], size)
res = [[]]
for size in range(1, len(nums)+1):
back_tarck([], nums, size)
return res
if __name__ == '__main__':
print(Solution().subsets([1, 2, 3]))
|
d445120d70d91a4dc3c8dbfb7cd1767d30783d3a | Naisargee/hackerrank-challenges | /largest_permutation.py | 502 | 3.53125 | 4 | N,K = map(int,input().split())
nums=list(map(int,input().split()))
dic={}
for i in range(0,N): dic[nums[i]]=i
def exchange(num1,num2):
num1_pos=dic[num1]
num2_pos=dic[num2]
nums[num1_pos]=num2
nums[num2_pos]=num1
dic[num1]=num2_pos
dic[num2]=num1_pos
k=0
n=0
num=N
while k<K and n<N:
if nums[n]==num:
n=n+1
num=num-1
continue
exchange(num,nums[n])
n=n+1
num=num-1
k=k+1
#print(nums)
for i in nums: print(i,end=" ")
print()
|
41e323d976684dd6fabfe7952256249d776d9515 | BYRans/LeetCode | /Python/ZigZagConversion.py | 869 | 4.28125 | 4 | #ZigZag Conversion
#The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
#And then read line by line: "PAHNAPLSIIGYIR"
#Write the code that will take a string and make this conversion given a number of rows:
#convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
class Solution:
# @param {string} s
# @param {integer} numRows
# @return {string}
def convert(self, s, numRows):
if numRows == 1:
return s
step = 2 * numRows - 2
result = ''
result += s[::step]
for i in range(1,numRows-1):
for j in range(i,len(s),step):
result += s[j]
if j+(step - i*2) < len(s):
result += s[j+(step - i*2)]
result += s[numRows-1::step]
return result
solution = Solution()
result = solution.convert('ABC',3)
print result
|
6b2ea075b60dfc4ee00e21d5d7b0682f0ee766d3 | renmengye/tfplus | /tfplus/utils/progress_bar.py | 2,072 | 4.09375 | 4 | """
A python progress bar.
Example 1:
N = 1000
pb = progress_bar.get(N)
for i in xrange(N):
do_something(i)
pb.increment()
Example 2:
N = 1000
for i in progress_bar.get(N):
do_something(i)
Example 3:
l = ['a', 'b', 'c']
for c in progress_bar.get_iter(l):
do_something(c)
"""
from __future__ import division
import sys
def get(length):
"""Returns a ProgressBar object.
Args:
length: number, total number of objects to count.
"""
return ProgressBar(length)
def get_iter(iterable):
"""Returns a progress bar from iterable."""
return ProgressBar(len(iterable), iterable=iter(iterable))
class ProgressBar(object):
"""Prints a dotted line in a standard terminal."""
def __init__(self, length, iterable=None, width=80):
"""Constructs a ProgressBar object.
Args:
length: number, total number of objects to count.
width: number, width of the progress bar.
"""
self.length = length
self.value = 0
self.progress = 0
if iterable is None:
self.iterable = iter(range(length))
else:
self.iterable = iterable
self.width = width
self._finished = False
pass
def __iter__(self):
"""Get iterable object."""
return self
def next(self):
"""Iterate next."""
self.increment()
return self.iterable.next()
def increment(self, value=1):
"""Increments the progress bar.
Args:
value: number, value to be incremented, default 1.
"""
self.value += value
while not self._finished and \
self.value / self.length > self.progress / self.width:
sys.stdout.write('.')
sys.stdout.flush()
self.progress = self.progress + 1
if self.progress == self.width and not self._finished:
sys.stdout.write('\n')
sys.stdout.flush()
self._finished = True
pass
|
3b5cb96198dd24ebd64dfc6db2dc6ac14a681f4e | dataaroom/Lulus | /uc.py | 8,040 | 4.09375 | 4 | #! python3
"""
Create a data structure for all units.
build a class "Units" to convert unit as required.
"""
class Units:
'''
类属性保存所有单位,和单位间的转换系数。megic method 用来定义 +-*/, 建立函数进行相应的单位转换计算。
'''
def __init__(self, value = 0.0, unit = 'm', type = 'L'): # 默认格式:(0.0, 'm', 'L') 参数均可选。 TODO: 考虑是否将 type 设置成必要参数, 也许这样程序更明确。
self.value = value
self.unit = unit
self.type = type
# Convert the unit to SI unit and return the SI value. And the SI unit is considered as an instance attribute and "ready only". (Verifed)
@property
def SI_value(self):
if self.type == 'T':
result = Units._convert_T(self, 'K').value
return result
else:
in_factor = 1.0
for i, j in getattr(self,self.type).items():
if self.unit == i:
in_factor = j[0]
value = self.value / in_factor
return value
# Convert the unit to SI unit and return the SI unit. SI unit is considered as an instance attribute and "ready only". (verifed)
@property
def SI_unit(self):
for i, j in getattr(self,self.type).items():
if j[0] == 1.0:
std = i
return std
# 两个相同单位相加,返回值的单位和第一个相同。 比如: 2 in + 2.54 cm = 3 in
def __add__(self, other):
sum = self.value + Units.convert(other, self.unit).value
result = Units(sum, self.unit, self.type)
return result
# 两个单位相减,返回值的单位和第一个相同。 比如: 22 in - 2.54 cm = 21 in
def __sub__(self, other):
sub = self.value - Units.convert(other, self.unit).value
result = Units(sub, self.unit, self.type)
return result
# 一个量纲常数乘以一个无量纲数, 没有单位变化。 TODO: 两个单位相除,遍历已有单位,赋值新的单位。
def __mul__(self, other):
mul = self.value * other
return Units(mul, self.unit, self.type)
# 一个量纲常数除以一个无量纲数, 没有单位变化。 TODO: 两个单位相除,遍历已有单位,赋值新的单位。
def __truediv__(self, other):
mul = self.value / other
return Units(mul, self.unit, self.type)
#单位主列表, 在单位转换时使用。
def __dir__(self):
return ['L', 'M', 'A','V','P','W','Q','v','p','density','t','T','mol']
# length
L = {'m': [1.0, 1], # For second parameter, 1 means SI unit, 2 means english Unit, 3 means UK unit.
'km': [1e-3, 1],
'cm': [100, 1],
'mm': [1e3, 1],
'ft': [3.2808399, 2],
'in': [39.3700788, 2],
'yard': [1.093613298, 2]
}
# mass
M = {'kg': [1.0, 1],
'g': [1e3, 1],
'pound': [2.20462262, 2],
'ounce': [35.27396192, 2],
'ton-SI': [0.001, 1],
'ton-US': [0.001102311, 2],
'ton-UK': [0.000984207, 3]
}
# area
A = {'m2': [1.0, 1],
'km2': [1e-6, 1],
'cm2': [1e4, 1],
'mm2': [1e6, 1],
'ft2': [10.76391045, 2],
'in2': [1550.003105, 2],
'acre': [0.000247105, 2],
'are': [0.01, 1]
}
# volume
V = {'m3': [1.0, 1],
'km3': [1e-9, 1],
'liter': [1e3, 1],
'cm3': [1e6, 1],
'mm3': [1e9, 1],
'ft3': [35.31466672,2],
'in3':[61023.74437,2],
'bbl': [0.158987295, 2],
'gallon-US liquid': [264.172524, 2],
'gallon-US dry': [227.0207446, 2],
'quart-US liquid': [1056.688209, 2],
'quart-US dry': [908.0829783,2]
}
# pressure
p = {'Pa': [1.0, 1],
'kPa': [1e-3, 1],
'MPa': [1e-6, 1],
'psi': [1.45037738e-4, 2],
'bar': [1e-5, 1],
'mmHg(°C)': [7.500615613e-3, 1],
'mmH2O(4°C)': [1.019716213e-1, 1]
}
# mass_flow_rate
W = {'kg/s': [1.0, 1],
'kg/m': [60, 1],
'kg/hr': [3600, 1],
'lbs/s': [2.20462262, 2],
'lbs/hr': [7936.641432, 2],
'ton/day': [216, 1]
}
# mole_flow_rate
MF = {'kgmol/s': [1.0,1],
'kgmol/hr': [3600.0, 1],
'lbmol/hr': [7937.0, 2]
}
# Volume flow rate
Q = {'m3/s': [1.0, 1],
'm3/min': [60, 1],
'm3/hr': [3600, 1],
'liter/s': [1000, 1],
'gpm': [15850.32314,2,'gallon per minutes']
}
# Heat Flow Rate
HF = {'j/s': [1.0, 1, 'joule per second'],
'MMBTU/hr': [3.412e6, 2, 'Million British thermal Units per hour'],
'kj/hr': [3.6, 1, 'kilojoule per hour']
}
# velocity
v = {'m/s': [1.0, 1, 'Meter per Second'],
'km/hr': [3.6, 1],
'ft/s': [3.280839895, 2],
'mph': [2.236936292, 2, 'Miles per Hour'],
'in/s': [39.37007874, 2],
'knot': [1.943844493, 2]
}
# energy
E = {'j': [1.0, 1, 'joule'],
'w.s': [1.0, 1, 'watt.second'],
'cal': [0.23846, 2, 'calorie [I.T]'],
'BTU': [9.47817e-4, 2, 'British Thermal Units'],
'MMBTU': [9.47817e-10, 2, 'Million British Thermal Units'],
'kj': [1000, 1, 'Kilojoule'],
'Cal': [0.00023846, 2, 'Kilocalorie [I.T]']
}
# power
P = {'kw': [1.0, 1, 'Kilowatt'],
'w': [1000, 1],
'hp': [1.34102, 2, 'Horsepower']
}
# density
density = {'kg/m3': [1.0, 1],
'g/mm3': [1e-6, 1],
'water(4°C)': [0.001, 1],
'lbs/gallon':[0.008345404, 2]
}
# time
t = {'s': [1.0, 1, 'Seconds'],
'min.': [0.01666667, 1, 'Minutes'],
'hr.': [0.000277778, 1, 'Hours'],
'd': [4.62963e-6, 1, 'Days']
}
# temperature
T = {'°C': [1.1, 1, 'degree Centigrade'],
'°F': [1.6, 2, 'degree Fahrenheit'],
'K': [1.0, 1, 'Kelvin degree']
}
# Amount of substance
mol = {'kmol': [1.0, 1, 'KiloMole'],
'mol': [1000, 1, 'Mole']
}
# electric current
A = {'A': [1.0, 1, 'ampere'],
'mA': [1000.0, 1, 'microampere'],
'kA': [0.001,1, 'kiloampere']
}
# luminous intensity
I = {'cd': [1.0, 1, 'candela']
}
# 单位换算主函数,根据输入的单位,数值 计算要求单位下的值。Return is an instance of Units class.
def convert(self, outUnit):
if self.type == 'T':
return self._convert_T(outUnit)
else:
in_factor = 1.0
out_factor = 1.0
catg = getattr(self, self.type).items()
for i,j in catg: # 调取用户所选的单位参数表,搜索输入和输出,并进行计算。返回计算结果。
if self.unit == i:
in_factor = j[0]
if outUnit == i:
out_factor = j[0]
result = Units(self.value * out_factor / in_factor, outUnit, self.type)
return result
# 温度转换公式 private method, It is not recommended to use it from external. 温度单位不成线性比例,公式计算不同,单独设置函数计算。TODO: 以后有时间思考是否可以合并成一个函数。
def _convert_T(self, outputUnit):
if self.unit == '°F' and outputUnit == '°C':
output = (self.value - 32) * (5 / 9)
elif self.unit == '°C' and outputUnit == '°F':
output = (self.value * 1.8) + 32
elif self.unit == '°C' and outputUnit == 'K':
output = self.value + 273.15
elif self.unit == 'K' and outputUnit == '°C':
output = self.value - 273.15
elif self.unit == '°F' and outputUnit == 'K':
output = (self.value + 459.67) * (5 / 9)
elif self.unit == 'K' and outputUnit == '°F':
output = (self.value * 1.8) - 459.67
else:
output = self.value
result = Units(output, outputUnit, 'T')
return result
if __name__== "__main__":
unit1= Units(2,'°C', 'T')
unit2 = unit1 / 2
print(unit1.SI_value)
print(unit2.value)
|
f409f261135059eb14d3003db0b4408b4bae6cf8 | Caiocolas/-Exercicios-Python- | /PycharmProjects/pythonProject/venv/ex013.py | 256 | 3.65625 | 4 | salario = float(input("Qual é o salário de um funcionário:"))
novo = (salario * 15 / 100)
a = salario + novo
print ('o novo salário de um funcionário com 15% de aumento sai de {} reais para {} reais com um aumento de {} reais'.format(salario,a,novo)) |
4abed32d81a745d2ec69f513a7d6ef535a5e184a | SudhaDevi17/PythonCodingPractice | /Beatiful Arrangement.py | 258 | 3.78125 | 4 |
n = 3
arr = [i for i in range(1, n+1)]
visited = []
def dfs(num , arr , temp: list):
for n in arr:
if n!=num:
temp.append(n)
visited.append(temp)
print(temp, visited)
return temp
for i in arr :
dfs(i , arr , [i])
|
c5137068d805ccc487569d6d199871a1d0db5be6 | ronald0807/Running-python | /python_list_practice1/문제2.py | 344 | 4.03125 | 4 |
# 문제 2.
# 10개의 문자를 입력받아서 첫 번째 네 번째 일곱 번째 입력받은 문자를 차례로 출력하는 프로그램을 작성하시오.
# 입력 예: A B C D E F G H I J
# 출력 예: A D G
list = []
for i in range(10) :
list.append(input("문자 10개를 입력하시오."))
print(list[0], list[3], list[6])
|
90ba32800ecf8a48c25bcda732642af228230c57 | kpurdom/space-invaders | /main.py | 2,444 | 3.859375 | 4 | from turtle import Screen
from border import Border
from player import Player
from shoot import Shoot
from enemy import Enemy
from scoreboard import Scoreboard
FIRE_STATE = "ready"
# set up screen
screen = Screen()
screen.bgcolor("black")
screen.setup(width=800, height=800)
screen.title("Space Invaders")
screen.tracer(0)
border = Border()
scoreboard = Scoreboard()
player = Player((0, -260))
shoot = Shoot()
enemy = Enemy()
def fire_shot():
# function to set bullet start point equal to just above player's position (only when in 'ready' state)
global FIRE_STATE
if FIRE_STATE == "ready":
FIRE_STATE = "fire"
x = player.xcor()
y = player.ycor() + 10
shoot.setposition(x, y)
shoot.showturtle()
# define keys to control functions
screen.listen()
screen.onkeypress(player.move_left, "Left")
screen.onkeypress(player.move_right, "Right")
screen.onkeypress(fire_shot, "space")
# start game and make aliens move
game_is_on = True
while game_is_on:
screen.update()
enemy.move()
if FIRE_STATE == "fire":
# fire bullet straight up from player's position
new_y = shoot.ycor() + shoot.move_speed
shoot.sety(new_y)
if shoot.ycor() > 275:
# when bullet reaches the top of the screen, hide the bullet and return to 'ready' state
shoot.hideturtle()
FIRE_STATE = "ready"
if not enemy.enemies:
# When there are no aliens left on the screen, declare 'Game over - You Win'
scoreboard.game_over("Game Over - You Win!")
game_is_on = False
else:
# Otherwise, check if there have been any collisions
for e in enemy.enemies:
# Check for collisions between the bullet and each alien
if shoot.distance(e["alien"]) < 10:
e["alien"].hideturtle()
shoot.hideturtle()
shoot.setposition(player.xcor(), player.ycor())
# Add points to the score board if collision occurs and return to 'ready' state
scoreboard.update_score(e["points"])
enemy.enemies.remove(e)
FIRE_STATE = "ready"
# Check for collision between the player and each alien. If collision, then game over.
if player.distance(e["alien"]) < 10:
scoreboard.game_over("Game Over - You Lose!")
game_is_on = False
screen.exitonclick()
|
3bfc2670a52bab2e7220abf8f282d17d2c300551 | tomasbm07/IPRP---FCTUC | /4/4_12.py | 166 | 3.828125 | 4 | linhas = int(input('Digite o nº de linhas da tabela: '))
print('Numero | Quadrado')
for i in range(linhas):
x = (i+1)**2
print('{0:6} {1:6}'.format(i+1, x)) |
e443811197bfe77a7ebabbf737c389df6ba5af3b | JerinPaulS/Python-Programs | /CountTriplets.py | 1,939 | 4.03125 | 4 | '''
You are given an array and you need to find number of tripets of indices such that the elements at those indices are in geometric progression for a given common ratio and .
Example
There are and at indices and . Return .
Function Description
Complete the countTriplets function in the editor below.
countTriplets has the following parameter(s):
int arr[n]: an array of integers
int r: the common ratio
Returns
int: the number of triplets
Input Format
The first line contains two space-separated integers and , the size of and the common ratio.
The next line contains space-seperated integers .
Constraints
Sample Input 0
4 2
1 2 2 4
Sample Output 0
2
Explanation 0
There are triplets in satisfying our criteria, whose indices are and
Sample Input 1
6 3
1 3 9 9 27 81
Sample Output 1
6
Explanation 1
The triplets satisfying are index , , , , and .
Sample Input 2
5 5
1 5 5 25 125
Sample Output 2
4
Explanation 2
The triplets satisfying are index , , , .
'''
import math
import os
import random
import re
import sys
import collections
# Complete the countTriplets function below.
def countTriplets(arr, r):
num_freq = collections.defaultdict(list)
max_val = max(arr)
expected = [1]
val = r
expected.append(val)
while val <= max_val:
val *= r
expected.append(val)
for index, num in enumerate(arr):
if num in expected:
num_freq[num].append(index)
keys = num_freq.keys()
result = 0
keys.sort()
print keys, num_freq
for index, key in enumerate(keys):
if index == 0 or index == len(keys) - 1:
continue
if (key // r) in num_freq and (key * r) in num_freq:
result += len(num_freq[key // r]) * len(num_freq[key]) * len(num_freq[key * r])
return result
print(countTriplets([1, 5, 5, 25, 125], 5))
'''
v2 = defaultdict(int)
v3 = defaultdict(int)
count = 0
for k in arr:
count += v3[k]
v3[k*r] += v2[k]
v2[k*r] += 1
return count
''' |
243e795217a21c79e3be76fc2784a047e3f8ec6d | lw2533315/leetcode | /setMatrixZeroes.py | 756 | 3.890625 | 4 | # Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
row = set();
col = set();
for i in range (len(matrix)):
for j in range (len(matrix[i])):
if matrix[i][j] == 0:
row.add(i)
col.add(j)
for i in row:
print ("row item is ", i)
matrix[i] = [0]*len(matrix[0])
for i in col:
for j in range (len(matrix)):
matrix[j][i] = 0
|
b0c67bb2da86ae946764d066deaf3f091ad92eca | Niemaly/python_tutorial_java_academy_and_w3 | /zad_1-10/zad10.py | 173 | 3.796875 | 4 | number = int(input("podaj liczbę"))
divisor = 8
if number % divisor == 0:
print("liczba podzielna przez", divisor)
else:
print("liczba niepodzielna przez", divisor) |
4eb5e6849965f47321b9a80df68f959c5d3e0dc7 | ankitagupta820/LeetCode | /Count_univalue_subtrees.py | 681 | 3.546875 | 4 | class Solution:
def countUnivalSubtrees(self, root):
if root is None:
return 0
self.count = 0
self.is_uni(root)
return self.count
def is_uni(self, node):
if node.left is None and node.right is None:
self.count += 1
return True
is_uni = True
if node.left is not None:
is_uni = self.is_uni(node.left) and is_uni and node.left.val == node.val
if node.right is not None:
is_uni = self.is_uni(node.right) and is_uni and node.right.val == node.val
self.count += is_uni
return is_uni
|
91bfcb3a2b44260b42c06c05987a6e3d6a1030e3 | labarreto/Python | /ex9.py | 357 | 3.84375 | 4 | #Jan 13, 2016
#Learning Python the Hard Way Exercise 9
days = "Mon Tue Wed Thurs Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\nSept\nOct\nNov\nDec"
print "Here are the days: ", days
print "Here are the months: ", months
print """
there is something going on here, typing as
many lines as we want
type type type
pandas pandas pandas
"""
|
ba48bb1b264255b7005b3714d57097dcae8c59af | Repicmi/201801643_TareasLFP | /Tarea5/main.py | 1,003 | 3.5 | 4 | prueba1 = "_servidor1"
prueba2 = "3servidor"
abecedario = ["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"]
digitos = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
def afd(entrada):
letrasAFD = []
contador_fase = 0
contador_letra = 0
for letter in entrada:
letrasAFD.append(letter)
if letrasAFD[contador_letra] == "_":
contador_letra = contador_letra+1
while contador_fase != 4:
letra = abecedario.count(letrasAFD[contador_letra])
if letra >= 1:
contador_letra = contador_letra +1
elif letra == 0 and (digitos.count(letrasAFD[contador_letra])):
contador_fase = 4
print("CADENA ACEPTADA %s" %entrada)
else:
print("CADENA NO VALIDA %s" %entrada)
break
else:
print("CADENA NO VALIDA %s" %entrada)
afd(prueba1)
afd(prueba2)
|
b27adcc7c73c63812130f8510c4d61241e6eca7a | sinasab/cse5914 | /src/brutus-module-weather/brutus_module_weather/tests/windQuestion_test.py | 927 | 3.515625 | 4 | import unittest
from flask import json
from .common import BrutusTestCase
class WindTestCase(BrutusTestCase):
"""
Simple tests for the weather module
Check that questions about wind returns the correct answers
"""
windQuestions = ['Is it windy',
'is it WINDY',
'I bet there is a lot of wind today',
'I heard it is windy',
'Is the wind blowing hard']
def test_basic_wind_questions(self):
"""
Ask a wind question and make sure the answer is wind related
"""
# register open weather map URLs with generic data
wind = 10
self.register_open_weather_map_urls(
temp=300, humidity=10, wind=wind, clouds=45)
for question in self.windQuestions:
answer = self.windAnswer(wind)
assert self.get_result(question) == answer, question
|
7a8b3cdea6954bc8d45c0ab4af0394f8f2d26958 | FredC94/MOOC-Python3 | /UpyLab/UpyLaB 3.13 - Boucle While.py | 1,321 | 4.34375 | 4 | """ Auteur: Frédéric Castel
Date : Avril 2020
Projet : MOOC Python 3 - France Université Numérique
Objectif:
Écrire un programme qui additionne des valeurs naturelles lues sur entrée et affiche le résultat.
La première donnée lue ne fait pas partie des valeurs à sommer.
Elle détermine si la liste contient un nombre déterminé à l’avance de valeurs à lire ou non :
si cette valeur est un nombre positif ou nul, elle donne le nombre de valeurs à lire et à sommer ;
si elle est négative, cela signifie qu’elle est suivie d’une liste de données à lire qui sera terminée par le caractère "F" signifiant que la liste est terminée.
Consignes:
Ne mettez pas d'argument dans les input :
data = input() et pas
data = input("Donnée suivante :") par exemple ;
Le résultat doit juste faire l’objet d’un print(res) sans texte supplémentaire (pas de print("résultat =", res) par exemple).
"""
lst = []
num = int(input())
if num >=0:
for n in range(num):
numbers = int(input())
lst.append(numbers)
print(sum(lst))
elif num < 0:
somme = 0
numbers = 0
while numbers != 'F':
numbers = input()
if numbers == 'F':
print(int(somme))
else:
somme = int(numbers) + somme |
a68829830647834c0372ce8f7ff76219e715c874 | gimquokka/problem-solving | /CodeUp/Basic_100 (기초100제)/cu_1064.py | 158 | 3.640625 | 4 | # Find a minimum value using ternery operation
a, b, c = input().split()
a = int(a)
b = int(b)
a1 = (a if a>b else b)
a2 = (a1 if a1 > c else c)
print(a2)
|
38610fd136b53199debfe2f8f35ab69361b21145 | charleslee94/CardGames | /Deck/Deck.py | 1,786 | 3.859375 | 4 | from collections import OrderedDict
from Card import Card
import pprint
from random import shuffle
class Deck():
"""
This is the deck class
can have as many cards as you want, but the default will be 52 of 4 suits
"""
def __init__(self, ruleset=None):
self.drawCount = 0
self.cardsDrawn = 0
if ruleset is None:
self.cardList = self.buildDefaultDeck()
# self.shuffleCards()
def buildDefaultDeck(self):
cardList = []
suitCount = 4
cardCount = 13
for suit in range(0, suitCount):
for value in range(1, cardCount + 1):
cardList.append(Card(suit, value))
return cardList
def getCardList(self):
return self.cardList
def setCardList(self, newCardList):
self.cardList = newCardList
def printCardList(self):
pp = pprint.PrettyPrinter(indent=4)
cardList = self.getCardList()
for card in cardList:
pp.pprint((card.suit, card.value))
self.getDeckInfo()
def getDeckInfo(self):
remaining = str(len(self.getCardList())) + " are remaining."
drawCount = str(self.drawCount) + " times drawn."
cardsDrawn = str(self.cardsDrawn) + " cards drawn."
print(remaining)
print(drawCount)
print(cardsDrawn)
def shuffleCards(self):
cardList = self.cardList
return shuffle(cardList)
def draw(self, number, countDraws=True):
cardList = self.getCardList()
drawnCards = cardList[0:number]
restOfDeck = cardList[number: len(cardList)]
if (countDraws):
self.drawCount += 1
self.cardsDrawn += number
self.setCardList(restOfDeck)
return drawnCards
|
b10d66afe764ce59198c71e999f141250c6ccefb | TeddyFirman/lenDen | /leapyear.py | 213 | 4.21875 | 4 | def leapyear():
year = int(input("Insert Year: "))
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print("This year is leap")
else:
print("This year is not leap")
leapyear()
|
58d943c7b96846e6eac58a3f010d31572d4c331b | LYASDF/NTNU_TextProcessing_2021 | /week02/week02_40992022m.py | 478 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
def main(inputSTR):
myNameSTR = inputSTR[0:7]
myIdSTR = inputSTR[8:17]
myInfoSTR = myNameSTR + " " + myIdSTR
print(myInfoSTR)
inputLIST = inputSTR.split(" ")
print(inputLIST)
print("私の名前:{}".format(inputLIST[0]))
print("私の学籍番号:{}".format(inputLIST[1]))
if __name__ == "__main__":
nameSTR= "林·イーノック 40992022M"
main(nameSTR)
|
a87d952e69c91c14f1762a75260c7ac4a5d49049 | Shanyao-HEU/PTA-PAT | /pat-b/1079.py | 431 | 3.9375 | 4 | num = input()
step = 0
def is_palin(number):
n = str(number)
m = n[::-1]
return m == n
while step < 10:
num_rev = num[::-1]
temp = str(int(num)+int(num_rev))
print("{} + {} = {}".format(num, num_rev, temp))
if is_palin(temp):
print("{} is a palindromic number.".format(temp))
break
else:
num = temp
step += 1
if step >= 10:
print("Not found in 10 iterations.") |
c5abb65f3bc95e52054df6819df26fe505efc35c | cdallasanta/Python-projects | /coin estimator.py | 615 | 3.640625 | 4 | import pandas as pd
#print('Please select "g" or "oz"')
metric = input()
dict = {'Coin':['pennies', 'nickles', 'dimes', 'quarters'],
'Grams':[2.5, 5, 2.268, 5.67],
'Ounces':[0,0,0,0],
'Number':[0,0,0,0],
'In Each Wrapper':[50,40,50,40],
'Wrappers Needed':[0,0,0,0],
'Total Value':[0,0,0,0]
}
pd_dict = pd.DataFrame(dict)
print(pd_dict.loc['pennies','grams'])
#for key in dict:
# print('What is the weight of your ' + key + '?')
# userWeight[key] = input()
#weight_pd = pd.DataFrame(ouncesWeight)
#print(weight_pd) |
021d3aef7f6783f230bbd5d0671fc015ebb5fe11 | shishir-umesh/TSP-SimulatedAnnealing | /main.py | 889 | 3.5625 | 4 | import pandas
import math
import random
import numpy as np
import matplotlib.pyplot as plt
from data import *
from simulatedAnnealing import *
from helperFunctions import *
def randomTour(df):
dfNew = df.copy()
arr = np.random.permutation(len(df))
print(arr)
j=0
for i in range(2,len(df)-1):
if(arr[j] == 0):
j = j+1
if(arr[j] == len(df)-1):
j = j+1
df.iloc[i] = dfNew.iloc[arr[j]+1]
j = j+1
return df
def plot_cities(df):
plt.plot(df[:]['x'], df[:]['y'])
plt.show()
if __name__ == '__main__':
df,optimalCost = dataInitialization()
df = randomTour(df)
print(df)
print("-*-*-*-*-*-*-*-*-*-*-*-*-*")
initialCost = initialCostCalc(df)
#plot_cities(df)
simulateAnnealing(df, optimalCost, initialCost)
plot_cities(df)
#naiveHillClimbing(df, optimalCost, initialCost)
|
be773d01a8c55aaf620db11271afc67f8ec0af2b | GaureeshAnvekar/ProblemSolving | /UCSDProblems/week3/money_change_dp.py | 1,039 | 3.953125 | 4 | #Uses python3
'''
The money change problem has the property of optimal substructure i.e. least no.of
coins required for an input 'm' can be the sum of least coins for subproblem of 'm' +
least coins for another subproblem of 'm'.
The following uses it and is done using dynamic programming through memoization.
'''
import sys
def get_change(m, storage):
#write your code here
if m == 0:
return 0;
if m == 1 or m == 5 or m == 10:
return 1;
if m < 0:
return float("inf"); #to represent infinity as 'm' is negative so that case shouldn't be considered.
change = min(storage[m-1] + 1 if storage.get(m-1) else get_change(m-1,storage)+1, storage[m-5] + 1 if storage.get(m-5) else get_change(m-5,storage)+1, storage[m-10] + 1 if storage.get(m-10) else get_change(m-10,storage)+1); #This is because if we take coin 1, then remainder will be m-1, if coin 5 then m-5.
storage[m] = change;
return change;
if __name__ == '__main__':
m = int(sys.stdin.read())
print(get_change(m,{}))
|
e6ac57a3687086bdf6b362d739ef7919f1faf425 | DilipBDabahde/PythonExample | /Assignment_4/Square_find_using_F_M_R.py | 1,326 | 4.09375 | 4 | '''
4.Write a program which contains filter(), map() and reduce() in it. Python application whichontains one list of
numbers. List contains the numbers which are accepted from user. Filter should filter out all such numbers which are
even. Map function will calculate its square. Reduce will return addition of all that numbers.
Input List = [5, 2, 3, 4, 3, 4, 1, 2, 8, 10]
List after filter = [2, 4, 4, 2, 8, 10]
List after map = [4, 16, 16, 4, 64, 100]
Output of reduce = 204
'''
from functools import reduce
def Acceptlist():
size = input("enter size of list: ");
print("Enter vlaues for list");
arr = list();
for i in range(int(size)): #typecasted
no = input("Num :");
arr.append(int(no)); # appending values in list
print("Our list is---> ",arr);
return arr;
def main():
arr = Acceptlist();
#using Lambda function for above give task
list_filter = list(filter(lambda no : (no%2==0),arr)); # filtering our even and storing in list_filter
print("After filter out even list is: ",list_filter);
#now processing for square
list_map = list(map(lambda no: (no*no),list_filter)); #mapped data
print("square of even values is: ",list_map);
list_reduce = reduce(lambda no1,no2: (no1+no2),list_map);
print("Final result is : ",list_reduce);
if __name__ == "__main__":
main();
|
a16adf8ea349a6593bf9d251a3331ea3d106fe79 | Daniel-VDM/Intro-CS-projects | /Program_Structure_and_Interpretation/Labs_and_Hwks/hw/hw04/hw04.py | 5,316 | 4 | 4 | HW_SOURCE_FILE = 'hw04.py'
###############
# Questions #
###############
def intersection(st, ave):
"""Represent an intersection using the Cantor pairing function."""
return (st+ave)*(st+ave+1)//2 + ave
def street(inter):
return w(inter) - avenue(inter)
def avenue(inter):
return inter - (w(inter) ** 2 + w(inter)) // 2
w = lambda z: int(((8*z+1)**0.5-1)/2)
def taxicab(a, b):
"""Return the taxicab distance between two intersections.
>>> times_square = intersection(46, 7)
>>> ess_a_bagel = intersection(51, 3)
>>> taxicab(times_square, ess_a_bagel)
9
>>> taxicab(ess_a_bagel, times_square)
9
"""
st1 , st2 = abs(street(a)), abs(street(b))
ave1, ave2 = abs(avenue(a)), abs(avenue(b))
return (max(st1,st2) - min(st1,st2)) + (max(ave1,ave2) - min(ave1,ave2))
from math import sqrt, floor
def squares(s):
"""Returns a new list containing square roots of the elements of the
original list that are perfect squares.
>>> seq = [8, 49, 8, 9, 2, 1, 100, 102]
>>> squares(seq)
[7, 3, 1, 10]
>>> seq = [500, 30]
>>> squares(seq)
[]
"""
#recall doing this step by step. Missed the part where i evaluate what goes into the list
return [floor(sqrt(x)) for x in s if floor(sqrt(x)) == sqrt(x)]
def g(n):
"""Return the value of G(n), computed recursively.
>>> g(1)
1
>>> g(2)
2
>>> g(3)
3
>>> g(4)
10
>>> g(5)
22
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'g', ['While', 'For'])
True
"""
assert n > 0
if n <= 3:
return n
return g(n-1) + 2 * g(n-2) + 3 * g(n-3)
def g_iter(n):
"""Return the value of G(n), computed iteratively.
>>> g_iter(1)
1
>>> g_iter(2)
2
>>> g_iter(3)
3
>>> g_iter(4)
10
>>> g_iter(5)
22
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'g_iter', ['Recursion'])
True
"""
assert n > 0
g = {1:1, 2:2, 3:3}
if n > 3:
for i in range(4,n+1):
#note the syntax for adding a new key to the dictionary
g[i] = g[i-1] + 2 * g[i-2] + 3 * g[i-3]
return g[n]
def pingpong(n):
"""Return the nth element of the ping-pong sequence.
>>> pingpong(7)
7
>>> pingpong(8)
6
>>> pingpong(15)
1
>>> pingpong(21)
-1
>>> pingpong(22)
0
>>> pingpong(30)
6
>>> pingpong(68)
2
>>> pingpong(69)
1
>>> pingpong(70)
0
>>> pingpong(71)
1
>>> pingpong(72)
0
>>> pingpong(100)
2
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'pingpong', ['Assign', 'AugAssign'])
True
"""
#recall that inorder to concatenate lists, the two arguments must also be lists
#recall that recursion requires a return on the recursive call if you dont want anything to print through each recursion
#base case is always what is the simplest case, test what happens when you want 0
def pong(i, direction, lst):
if i >= n:
return lst[i-1]
if has_seven(i) or i % 7 == 0:
return pong( i+1, direction * -1,
lst + [lst[i-1]+(direction * -1)] )
return pong( i+1, direction,
lst + [lst[i-1]+direction] )
return pong(1,1,[1])
def has_seven(k):
"""Returns True if at least one of the digits of k is a 7, False otherwise.
>>> has_seven(3)
False
>>> has_seven(7)
True
>>> has_seven(2734)
True
>>> has_seven(2634)
False
>>> has_seven(734)
True
>>> has_seven(7777)
True
"""
if k % 10 == 7:
return True
elif k < 10:
return False
else:
return has_seven(k // 10)
def count_change(amount):
"""Return the number of ways to make change for amount.
>>> count_change(7)
6
>>> count_change(10)
14
>>> count_change(20)
60
>>> count_change(100)
9828
"""
#this is a version of count partitions - a form of tree recursion
def count(n, cent_Pwr = 0):
#if you hit 0, you have found a way to take everything in a whole amount
if n == 0:
return 1
#if you go lower than n, it is an invalid combination
#if your cent value is bigger than the remaining amount, there is no way to successfully take away from the amount
if n < 0 or 2**cent_Pwr > n:
return 0
#Try taking out the current max amount of cents.
#Then at each recursive step you could take away 2 time more.
#Add the ways in which each way would work
return count(n-(2**cent_Pwr), cent_Pwr) + count(n, cent_Pwr + 1)
return count(amount)
###################
# Extra Questions #
###################
from operator import sub, mul
def make_anonymous_factorial():
"""Return the value of an expression that computes factorial.
>>> make_anonymous_factorial()(5)
120
>>> from construct_check import check
>>> check(HW_SOURCE_FILE, 'make_anonymous_factorial', ['Assign', 'AugAssign', 'FunctionDef', 'Recursion'])
True
"""
#uses the recude function for lists. Not sure how else to do it
from functools import reduce
return lambda n: reduce(lambda x,y:x*y,[1]+list(range(1,n+1)))
|
b1de2e26abff0a05f163e21c9c2de4edd9d4eaaf | pahisan/python-exp | /main.py | 194 | 3.765625 | 4 | import datetime
def timeofCity ():
return datetime.datetime.now()
print(timeofCity())
a = 1
b = 1
print(a + b)
w = 1
x = 2
print(w * x)
c = 3
g = 3
print(c/g)
y = 5
z = 5
print(y - z) |
fa1f110dec8610c2df834ed2ef10c48405833133 | js-yoo/CheckiO | /Home/sun-angle.py | 341 | 3.609375 | 4 | # https://py.checkio.org/en/mission/sun-angle/
# Difficulty : Elementary
def sun_angle(time):
h,m=map(int,time.split(':'))
dtime=60*h+m-360
if -1<dtime<721:
return dtime/4
else:
return "I don't see the sun!"
# Example)
# sun_angle("07:00") == 15
# sun_angle("12:15"] == 93.75
# sun_angle("01:23") == "I don't see the sun!"
|
879f90a2549d165c36bcf4e124ffed3498fc882f | diegocolombo1989/Exercicios_templo | /elevador-mais-proximo/start.py | 537 | 3.890625 | 4 |
def elevador(left,right,call) -> int:
call_1 = 'Elevador da esquerda esta vindo'
call_2 = 'Elevador da direita esta vindo'
if left == call: return print(call_1)
elif right == call: return print(call_2)
elif left == right: return print(call_2)
elif left > right: return print(call_2)
elif right > left: return print(call_2)
elevador(2,1,2)
elevador(1,2,2)
elevador(1,1,2)
elevador(2,1,0)
elevador(2,0,0)
elevador(1,1,0)
elevador(1,0,1)
elevador(2,0,1)
elevador(1,2,2)
elevador(1,0,0)
|
74ceea22f8b70fa774cf396a3f882b36483b4f05 | bhuvanakundumani/Python | /Src/decimaltobinary.py | 185 | 4.15625 | 4 |
def decimal_to_binary(num):
""" This function converts a decimal number (num ) to a binary number"""
if (num > 1):
decimal_to_binary(num // 2)
print(num % 2, end ='') |
1409167f2f04d8b3e080034abea8b40b22a68ef8 | hwang033/job_algorithm | /py/reverse_linked_list_ii.py | 1,481 | 4 | 4 | import pdb
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a ListNode
# @param m, an integer
# @param n, an integer
# @return a ListNode
def reverseBetween(self, head, m, n):
if m == n:
return head
prev_start = start = end = end_next = None
fn1 = ListNode(0)
fn1.next = head
i = 0
h = fn1
while i <= n - 1 and h:
if i == m - 1:
prev_start = h
start = h.next
#prev_start.next = None
h = h.next
i += 1
if h:
end = h
end_next = h.next
end.next = None
if not start:
return head
fn = ListNode(0)
fn.next = start
p, q, r = fn, start, start.next
while q is not None:
q.next = p
p = q
q = r
if r is not None:
r = r.next
prev_start.next = p
fn.next.next = end_next
return fn1.next
if __name__ == "__main__":
L1 = ListNode(3)
L2 = ListNode(5)
L1.next = L2
L2.next = None
rl = Solution()
h = rl.reverseBetween(L1, 1, 2)
while h is not None:
print h.val
h = h.next
|
e2a20e955edaccd9d89b14593257aa24877d3e33 | Sheyin/advent-of-code-2020 | /day5.py | 2,719 | 3.8125 | 4 | F = "F"
R = "R"
L = "L"
B = "B"
def main():
# Get file input
filename = "./data/day5input.txt"
input = open(filename, "r")
boarding_passes = []
for _ in input:
line = _.rstrip()
boarding_passes.append(line)
# boarding_passes should now be a tidy array of data
highest_seat_id = 0
all_seat_info = []
for boarding_pass in boarding_passes:
seat_info = {}
seat = findSeatID(boarding_pass)
seat_info["row"] = seat[0]
seat_info["col"] = seat[1]
seat_info["id"] = (seat[0] * 8) + seat[1]
seat_info["pattern"] = boarding_pass
if seat_info["id"] > highest_seat_id:
highest_seat_id = seat_info["id"]
all_seat_info.append(seat_info)
print(f"Part One: Highest Seat ID is: {highest_seat_id}")
missing_seat = locateSeat(all_seat_info, highest_seat_id)
print(f"Part Two: The missing Seat ID is: {missing_seat}")
# Part two - find a seat for which a seat id exists before and after (+/- 1)
# Return the seat id
def locateSeat(seat_info, highest_seat_id):
for id in range(0, highest_seat_id):
# If a boarding pass w/ this ID exists, it can't be the seat
if not findSeatId(id, seat_info):
if (findSeatId(id - 1, seat_info) and findSeatId(id + 1, seat_info)):
return id
return "Failed to find the seat!"
# return True if the requested seat # is found, False otherwise
def findSeatId(id, seat_info):
for seat in seat_info:
if id == seat["id"]:
return True
return False
# Calculates the seat's row/col position based on rules.
# Return a tuple (row, column)
def findSeatID(boarding_pass):
row_pattern = boarding_pass[:-3]
col_pattern = boarding_pass[-3:]
row_range = (0, 127)
for char in row_pattern:
row_range = splitSeat(char, row_range)
col_range = (0, 7)
for char in col_pattern:
col_range = splitSeat(char, col_range)
return (row_range[0], col_range[0])
# Helper function for locateSeat.
# Splits maxSeat(highest row/col) based on letter
# Expects a tuple of (lowestPossibleSeat, highestPossibleSeat)
# Returns resulting tuple of new min/max possible positions
def splitSeat(letter, range):
minSeat = range[0]
maxSeat = range[1]
difference = int((maxSeat - minSeat) / 2)
lowerHalf = (minSeat, minSeat + difference)
upperHalf = (maxSeat - difference, maxSeat)
# Keep upper half
if letter == "B" or letter == "R":
return upperHalf
# Keep lower half
elif letter == "F" or letter == "L":
return lowerHalf
else:
print("Some error occurred - neither F/B/L/R")
if __name__ == "__main__":
main()
|
87b65c36f0123150f5f867e648f2be76f8694b4c | LukeHufnagle/BankAccount_Assignment | /BankAccount.py | 977 | 3.859375 | 4 | class BankAccount:
balance = 0
def __init__(self, interest_rate, balance):
self.interest_rate = interest_rate
self.balance = balance
def makeDeposit(self, amount):
self.balance += amount
return self
def makeWithdrawal(self, amount):
self.balance -= amount
return self
def display_account_info(self):
print(f"Your balance is: " + str(self.balance))
return self
def yield_interest(self):
self.balance += self.balance * self.interest_rate
return self
Jake = BankAccount(0.01, 100)
Jake.makeDeposit(100).makeDeposit(100).makeDeposit(100).makeWithdrawal(100).yield_interest().display_account_info()
print("-------------------------------------------------------------")
John= BankAccount(0.02, 200)
John.makeDeposit(200).makeDeposit(200).makeWithdrawal(100).makeWithdrawal(100).makeWithdrawal(100).makeWithdrawal(100).yield_interest().display_account_info()
|
eb83856e0974a5ad63e58c0e54ae97e83dc04733 | zuchunlei/leamon | /patteraless/src/thread/main.py | 706 | 3.546875 | 4 | #-*- encoding: utf-8 -*-
"""
多单线程运行一段程序
"""
import time
import thread
def loop0():
"""
睡上几秒
"""
print 'start loop 0 at: ', time.ctime()
time.sleep(4)
print 'loop 0 done at: ', time.ctime()
def loop1():
"""
再睡上几秒
"""
print 'start loop 1 at: ', time.ctime()
time.sleep(2)
print 'loop 1 done at: ', time.ctime()
def main():
print 'starting at:', time.ctime()
# 启动一个新的线程对loop函数进行执行
thread.start_new_thread(loop0, ())
thread.start_new_thread(loop1, ())
print 'all Done at: ', time.ctime()
if __name__ == '__main__':
main()
|
a949cab73eed36616eed9f8b873df4c54fcf74e0 | laurenchow/algorithms | /reverse_linked_list.py | 659 | 4.3125 | 4 | #reverse linked list
class Node:
def __init__(self, data):
self.data = None
self.next = None
# class LinkedList:
#step through or traverse the linked list
#for each node, create a new pointer going backwards pointing to previous node .last
#return a linked list such that node.next is node.last
def reverse(node):
while node.next is not None:
temp = node.data
next_node = node.next
next_node.last = temp
node = next_node
return node
# this will give us back c, where node.last is =
while node.last is not None:
node.next = node.last
node = node.next
node.next = None
return head
if __name__=="__main__":
Node(5)
reverse(5) |
545485f0e95ba066dbd05f522d0539bbdf2f3020 | patrykpalej/weather-forecast-accuracy-assessment | /functions/convertTimestampFormat.py | 1,264 | 3.625 | 4 | from dateutil import parser
from datetime import datetime
def convert_from_str_timestamps(original_timestamps, target_format):
"""
Converts list of timestapms from string format to datetime or unix
"""
if target_format == "datetime":
output_timestamps = [parser.parse(elem)
for elem in original_timestamps]
elif target_format == "unix":
output_timestamps \
= [round(datetime.strptime(elem, "%Y-%m-%d %H:%M:%S")
.timestamp())
for elem in original_timestamps]
else:
raise ValueError("Invalid target_format name")
return output_timestamps
def convert_from_unix_timestamps(original_timestamps, target_format):
"""
Converts list of timestapms from unix format to datetime or string
"""
if target_format == "datetime":
output_timestamps = [datetime.fromtimestamp(elem)
for elem in original_timestamps]
elif target_format == "str":
output_timestamps \
= [datetime.fromtimestamp(elem).strftime("%Y-%m-%d %H:%M:%S")
for elem in original_timestamps]
else:
raise ValueError("Invalid target_format name")
return output_timestamps
|
b15da86a9da1f20dfcd6c304e578ae1e9c838a30 | claudiodornelles/CursoEmVideo-Python | /Exercicios/ex087 - Mais sobre Matriz em Python.py | 1,306 | 4 | 4 | """
Aprimorar o desafio anterior, mostrando no final:
1 - A soma de todos os valores pares digitados.
2 - A soma dos valores da terceira coluna.
3 - O maior valor da segunda linha.
"""
matriz = [[],[],[]]
soma_pares = soma_terceira_coluna = maior_valor_segunda_linha = 0
for i in range(0,3):
for j in range(0,3):
while True:
try:
valor = int(input(f'Digite um valor para [{i}, {j}]: '))
except:
print('Não entendi... ', end='')
continue
if valor % 2 == 0:
soma_pares += valor
break
matriz[i].append(valor)
print('-='*30)
for i in range(0,3):
for j in range(0,3):
if j != 2:
print(f'[ {matriz[i][j]:^6} ]', end='')
else:
print(f'[ {matriz[i][j]:^6} ]')
print('-='*30)
print(f'A soma de todos os valores pares digitados é {soma_pares}.')
print(f'A soma dos valores da terceira coluna é ', end='')
for i in range(0,3):
soma_terceira_coluna += matriz[i][2]
print(f'{soma_terceira_coluna}.')
print(f'O maior valor da segunda linha é ', end='')
for j in range(0,3):
if matriz[1][j] > maior_valor_segunda_linha:
maior_valor_segunda_linha = matriz[1][j]
print(f'{maior_valor_segunda_linha}.')
|
4f5704da66b3fa0bd12023eabc466e361ab74170 | guoguanglu/leetcode | /mycode/array/Search Insert Position.py | 320 | 3.53125 | 4 | class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
for i,each in enumerate(nums+[0]):
if each < target:
continue
else:
break
return i |
41687f34ba6cc949848f6ce1f0f3260ec76d4a64 | myleslangston/Data22 | /Inheritance/main.py | 540 | 3.78125 | 4 | class Car: #parent class
def __init__(self, name, mileage):
self.name = name
self.mileage = mileage
def description(self):
return f"The {self.name} car gives the mileage of {self.mileage}km/l"
class BMW(Car): #child class
pass
class Audi(Car): #child class
def audi_desc(self):
return "This is the description method of class Audi."
obj1 = BMW("BMW 7-series",39.53)
print(obj1.description())
obj2 = Audi("Audi A8 L",14)
print(obj2.description())
print(obj2.audi_desc())
|
a603277baf1581b2d35552e7df0c17378131195d | RodrigoMSCruz/CursoEmVideo.com-Python | /Desafios/desafio095.py | 1,599 | 4 | 4 | # Aprimoramento do desafio 93 para que ele funcione com vários jogadores, incluindo um sistema de
# visualização de detalhes do aproveitamento de cada jogador.
time = []
jogador = {}
partidas = []
while True:
jogador.clear()
jogador['nome'] = str(input('Nome do Jogador: '))
njogos = int(input(f'Quantas partidas {jogador["nome"]} jogou? '))
for i in range(1, njogos + 1, 1):
gols = int(input(f'Quantos gols na partida {i}? '))
partidas.append(gols)
jogador['gols'] = partidas[:]
jogador['total'] = sum(partidas)
partidas.clear()
time.append(jogador.copy())
while True:
resposta = str(input('Quer cadastrar mais jogadores? [S/N]: ')).upper()[0]
if resposta in 'SN':
break
print('Resposta inválida. Responda com S ou N.')
# end-while True
if resposta == 'N':
break
# end-while True
print('-='*50)
print('Cod ', end='')
for i in jogador.keys():
print(f'{i:<15}', end= '')
print()
print('-='*50)
for k, v in enumerate(time):
print(f'{k:>3}', end='')
for d in v.values():
print(f'{str(d):<15}', end='')
print()
print('-='*50)
while True:
busca = int(input('Digite o código do jogador para mais dados. (999 para sair.) '))
if busca == 999:
break
if busca > len(time):
print(f'Erro! Código para jogador {busca} inexistente.')
else:
print(f'Mostrando dado do jogador {time[busca]["nome"]}')
for i, g in enumerate(time[busca]["gols"]):
print(f' No jogo {i+1} fez {g} gols.')
print('-='*50)
# nd-while
|
1a4214c24781eeb7de1267d6dd841328272ff56e | twardoch/robofab | /Docs/Examples/talks/interpol_07.py | 788 | 3.640625 | 4 | # glyphmath example, using glyphs in math
# in the test font: two interpolatable, different glyphs
# on positions A and B.
from robofab.world import CurrentFont
f = CurrentFont()
# glyphmath
a = f["A"]
b = f["B"]
# multiply works as scaling up
d = a * 2
# or
d = 2 * a
# note: as of robofab svn version 200,
# the "as" argument in insertGlyph has changed to "name"
f.insertGlyph(d, name="A.A_times_2")
# division works as scaling down
d = a / 2
f.insertGlyph(d, name="A.A_divide_2")
# addition: add coordinates of each point
d = a + b
f.insertGlyph(d, name="A.A_plus_B")
# subtraction: subtract coordinates of each point
d = a - b
f.insertGlyph(d, name="A.A_minus_B")
# combination: interpolation!
d = a + .5 * (b-a)
f.insertGlyph(d, name="A.A_interpolate_B")
f.update() |
c329a6e1edab4825a52dd5576bdfbc119bb6badf | Jayvee1413/AOC2020 | /aoc2020/day2/main.py | 2,050 | 3.5625 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import re
def read_file(file_name):
with open(file_name, "r") as f:
input = [x.strip() for x in f.readlines()]
return input
def get_numbers(line):
first_number_pattern = re.compile(r"^\d*[^-]")
first_number = first_number_pattern.search(line)[0]
second_number_pattern = re.compile(r"(?<=-)\d+(?= )")
second_number = second_number_pattern.search(line)[0]
return int(first_number), int(second_number)
def get_letter(line):
letter_pattern = re.compile(r"(?<= )\w+(?=:)")
letter = letter_pattern.search(line)[0]
return letter
def get_password(line):
password_pattern = re.compile(r"(?<=[: ])\w+$")
password = password_pattern.search(line)[0]
return password
def aoc2020_2_a(input: list):
valid_count = 0
for data in input:
password = get_password(data)
policy_letter = get_letter(data)
policy_count_min, policy_count_max = get_numbers(data)
policy_letter_count = password.count(policy_letter)
if policy_count_min <= policy_letter_count <= policy_count_max:
valid_count += 1
return valid_count
def aoc2020_2_b(input: list):
valid_count = 0
for data in input:
password = get_password(data)
policy_letter = get_letter(data)
policy_index_valid_1, policy_index_valid_2 = get_numbers(data)
if policy_letter == password[policy_index_valid_1 - 1] or policy_letter == password[policy_index_valid_2 - 1]:
if password[policy_index_valid_1 - 1] != password[policy_index_valid_2 - 1]:
valid_count += 1
return valid_count
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print(aoc2020_2_a(read_file("day2.txt")))
print(aoc2020_2_b(read_file("day2.txt")))
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
e6cfb66c9758874eec602e7a5d76e4c4c87784dd | fuyangchang/Practice_Programming | /IntroToComputerScience/PS2_payingdebtoffinayear.py | 857 | 4.1875 | 4 | #2-2. Paying Debt off in a Year
#Write a program calculating the minimum fixed monthly payment needed
#in order to pay off a credit card balance in 12 months.
#balance & annualInterestRate will be handled by the instructor.
balance = float(raw_input('balance = '))
annualInterestRate = float(raw_input('annual interest rate = '))
monthlyInterestRate = annualInterestRate/12.0
print 'monthlyInterestRate: ',monthlyInterestRate
monthlyPayment = 0
while True:
monthlyPayment += 10
remainingBalance = balance
for i in range(1, 13):
remainingBalance = remainingBalance - monthlyPayment
remainingBalance = remainingBalance * (1 + monthlyInterestRate)
print 'remaining balance: ', remainingBalance
print 'monthlyPayment =', monthlyPayment, 'balance =', remainingBalance
if remainingBalance <= 0:
break
print 'Lowest Payment:', monthlyPayment
|
996eedaa0cb4fab26949f5c001de626856d1d2a2 | CauchyPolymer/teaching_python | /python_intro/p3_hanoi.py | 1,639 | 3.671875 | 4 | disknum = input('Enter the number of disks : ')
def hanoi(n,start,to,other):
n == disknum
if n == 0:
return
hanoi(n - 1, start, other, to)
print('Disk Move {} => {}'.format(start, to))
hanoi(n - 1, other, to, start)
hanoi(4,'A','C','B')
# H(1,A,C) 1개의 디스크를 A B C에 해당하는 Pole A에서 C로 옮긴다. 재귀함수는 항상 논리를 먼저 설게해야 함
#대칭의 논리로 H(1,A,C) == H(1,A,B) == H(1,A,C) 하나의 디스크를 계속 옮기는건 쉬움
#디스크 1개짜리 H(2,A,C) == H(2,A,B) == H(2,B,C)
#디스크 2개짜리 H(3,A,C) == H(3,A,B) == H(3,B,C) 디스크 3개를 A에서 C로 보내거나 할 수 있음. 하지만 가장 큰 디스크가 가장 아래임.
#어떤 문제든 간에 첫번째 pole에 가장 큰 디스크가 있고, 가운데에 모든 디스크가 위에서 작은 크기 순서대로 배치 되어 있어야 함.
#H(4,A,C) 풀이법
#H(3,A,B) -> A에서 C로 보내기 -> H(3,B,C)-> B에서 C로 옮기기. 그런데 저것들은 다 위에서 할 수 있다고 적어 놓은 부분임.
# 크게 두번 옮긴다.
# 1. 일단 n-1까지를 출발 기둥(Start)에서 중간 기둥(Waypoint)을 거쳐 도착 기동(Destination)으로 옮긴다.
# 2. 그리고 출발 기둥(Start)에 남아있는 n번째(제일 큰) 원판을 도착 기동(Destination)기둥으로 바로 옯긴다.
# 3. 중간 기둥(Waypoint)에 남아있는 n-1까지들을 다시 출발 기둥(Start)를 겨처 도착 기동(Destination)으로 옮긴다.
# 하노이 타워를 점화식으로 표현한 것이다.
# -> H(n,A,C)
# 1. H(n-1,A,B)
# 2. A -> C
# 3. H(n-1,B,C)
|
f15aed5f9393d5c73fe1cc1bd2936513c77e287e | Alejandro-15/python | /python/python programa 1.py | 120 | 3.734375 | 4 | def fib_r(n):
if n < 2:
return n
return fib_r(n-1)+ fib_r(n-2)
for x in range(20):
print(fib_r(x))
|
f6379ef74da0697f46deec07a40ef04f14d57961 | Henok-Matheas/RSA-Encryption | /RSA4.py | 2,251 | 3.8125 | 4 | """Group Members
1. Henok Matheas UGR/2553/12
2. Kaleab Taye UGR/0490/12
3. Kaleab Tekalign UGR/3664/12
4. Betel Tagesse UGR/5409/12
5. Beka Dessalegn UGR/4605/12
6. Bethlehem Alula UGR/0462/12
7. Tsega Yakob UGR/8465/12 """
p=721960629061904110756973047896820529650646626913987914193058081946869300323505631503613785147235083747598529092067962512605338801581684234964490805070294572618497933653948906694134011361476095650659862416376029070102910970128990995504864728056436234936733309062195718092793663000312918831684212336353
q=991983977971967953947941937929919911907887883881877863859857853839829827823821811809797787773769761757751743739733727719709701691683677673661659653647643641631619617613607601599593587577571569563557547541523521509503499491487479467463461457449443439433431421419409401397389383379373367359353349347337
e=57
n=p*q
phi_n=(p-1)*(q-1)
def rel_prime(p,q):
if min(p,q)==1:
return True
elif min(p,q)==0:
return False
else:
return rel_prime(min(p,q),max(p,q)%min(p,q))
print(rel_prime(e,phi_n))
d=(pow(e,-1,phi_n))
message=input("input a string: ")
print(f"\n public key e: {e}"
f"\n and n={n}")
def m_num(message):
"converts the string message into numeric format"
number=""
for i in message.upper():
number+=str(ord(i))
return int(number)
def int_to_string(number,word):
"converts the numeric form into string format"
if number<=90:
word=str(chr(number))+word
return word
else:
word=str(chr(number%100))+word
return int_to_string(number//100,word)
def simplifier(message,e,n):
if not rel_prime(message,n):
return "message and n are not relatively prime, could you change your wording and try again."
rem=1
while(e>2):
rem*=message**(e%2)
e=e//2
message=pow(message,2,n)
return pow(message*rem,e,n)
def encrypt(message,e,n):
enc = (simplifier(m_num(message),e,n))
return enc
def decrypt(encrypted,d,n):
dec=(simplifier(encrypted,d,n))
return int_to_string(dec,"")
enc=encrypt(message,e,n)
print(enc)
dec=decrypt(enc,d,n)
print(dec,"this is the decrypted")
|
c1df45fe33a8c149919019aa5caf3fa3980f8c81 | WuLC/LeetCode | /Algorithm/Python/133. Clone Graph.py | 1,354 | 3.8125 | 4 | # -*- coding: utf-8 -*-
# @Author: WuLC
# @Date: 2016-08-21 10:25:30
# @Last modified by: WuLC
# @Last Modified time: 2016-08-21 10:26:16
# @Email: liangchaowu5@gmail.com
# Definition for a undirected graph node
# class UndirectedGraphNode(object):
# def __init__(self, x):
# self.label = x
# self.neighbors = []
# hash table and BFS
# O(n) time complexity, O(n) space, AC
class Solution(object):
def cloneGraph(self, node):
"""
:type node: UndirectedGraphNode
:rtype: UndirectedGraphNode
"""
if node == None:
return None
visited = set()
que = collections.deque()
nodes = {}
que.append(node)
visited.add(node)
idx = 0
while idx != len(que):
curr = que[idx]
idx += 1
nodes[curr] = UndirectedGraphNode(curr.label)
for node in curr.neighbors:
if node not in visited:
visited.add(node)
que.append(node)
start_node = None
for node in que:
curr = nodes[node]
for neighbor in node.neighbors:
curr.neighbors.append(nodes[neighbor])
if start_node == None:
start_node = curr
return start_node
|
122b34553c558107a37ab33bbd3134102f1dcaef | AaronVelasco93/Prueba_Python | /Clase 1404218/prueba2.py | 235 | 3.90625 | 4 | print("Suma de numeros")
num1=int (input("Dame un numero: "))
num2=int (input("Dame otro nummero"))
resultado=num1+num2
print("El resultado de la suma es",resultado)
input("Preciona cualquier tecla para continuar...")
|
629aa48734f202872ff8d6488f9e72e7aa18ae62 | 0ashu0/Python-Tutorial | /Lynda Course/0406_using functions.py | 810 | 4.3125 | 4 | def main():
print("this is main function")
fu()
func(-5)
func(3)
func(5)
funck(1)
funck(3)
funckers()
def fu():
for i in range(13):
print(i, end=' ')
print()
def func(a):
for i in range(a, 10):
print(i, end=' ')
print()
def funck(b):
for i in range(b, 10 ,2):
print(i, end=' ')
print()
def funckers(a=7):
for i in range(a, 10):
print(i, end=' ')
print()
main()
# The range() function has two sets of parameters, as follows:
# range(stop)
# stop: Number of integers (whole numbers) to generate, starting from zero. eg. range(3) == [0, 1, 2].
# range([start], stop[, step])
# start: Starting number of the sequence.
# stop: Generate numbers up to, but not including this number.
# step: Difference between each number in the sequence.
# range(): by default will start with 0 |
385479a3a0803c6ff64acb3152dbd2197c343d56 | hemanth-007/Path-Finding-Visualizer | /buttons_class.py | 1,009 | 3.5625 | 4 | import pygame
from settings import *
class Buttons:
def __init__(self, app, color, x, y, width, height, text=""):
self.app = app
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
def draw_button(self):
pygame.draw.rect(self.app.WIN, self.color,
(self.x, self.y, self.width, self.height), 0)
if self.text != "":
font = pygame.font.SysFont(FONT, 24)
IMG = font.render(self.text, 1, (0, 0, 0))
self.app.WIN.blit(
IMG, (self.x + (self.width // 2 - IMG.get_width() // 2),
self.y + (self.height // 2 - IMG.get_height() // 2)))
# To check if cursor is on any button
def is_over(self, pos):
x, y = pos[0], pos[1]
if x > self.x and x < self.x + self.width:
if y > self.y and y < self.y + self.height:
return True
return False
|
b0008ad66262e873f0ca20c0b04bb10ce8086e14 | Lilwash333/APCS | /GuessingGame.py | 333 | 3.953125 | 4 | #Julius Washington
import random
rand = random.randint(1,10)
give = 0
print("Give me a number from 1 - 10")
while(give != rand):
give = int(input())
if(give > rand):
print("Your number is too high!\n Try again!")
elif(give < rand):
print("Your number is too low!\n Try again!")
else:
print("That's it!")
|
37525d690fffd2812e06a76dacfc223f1038fbfd | stnorling/Rice-Programming | /iipp/Week 3/Mini_Project_2_Guess_The_Number.py | 2,468 | 4.375 | 4 | # template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
guesses = 7
count = 0
rg1000 = False
secret_number = 0
numrange = 100
# helper function to start and restart the game
def remaining_guesses():
global guesses, count
count = count + 1
guesses = guesses - 1
if guesses == 0:
print "You are out of guesses. Game over! \nThe number was", secret_number, "\n"
if rg1000 == False:
new_game()
else:
range1000()
else:
print "You have " + str(guesses) + " guesses left.\n"
def new_game():
# initialize global variables used in your code here
global secret_number, count, rg1000
count = 0
secret_number = random.randrange(0, numrange)
if rg1000 == False:
print "New game - pick a number between 0 and 99"
else:
print "New game - pick a number between 0 and 999"
print "You have " + str(guesses) + " remaining guesses.\n"
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
global numrange, guesses, rg1000
rg1000 = False
numrange = 100
guesses = 7
new_game()
def range1000():
# button that changes the range to [0,1000) and starts a new game
global numrange, guesses, rg1000
rg1000 = True
numrange = 1000
guesses = 10
new_game()
def input_guess(guess):
# main game logic goes here
num_guess = int(guess)
if num_guess < secret_number:
print "You picked " + str(num_guess) + ". Higher!"
remaining_guesses()
elif num_guess > secret_number:
print "You picked " + str(num_guess) + ". Lower!"
remaining_guesses()
else:
print "You picked " + str(num_guess) + ". Correct!!!\n"
if count == 0:
print "First guess! What a legend!!!\n"
new_game()
# create frame
f = simplegui.create_frame("Guess the number", 200, 200)
# register event handlers for control elements and start frame
f.add_button("New game range is [0, 100)", range100)
f.add_button("New game range is [0, 1000)", range1000)
f.add_input("Enter guess here", input_guess, 50)
f.start()
# call new_game
new_game()
# always remember to check your completed program against the grading rubric
|
cdb63d9a8fab0f37095981716f1997c412808b33 | SirCipher/EvolutionaryComputation | /Assignment/snakePlay.py | 4,876 | 3.8125 | 4 | # This version of the snake game allows you to play the same yourself using the arrow keys.
# Be sure to run the game from a terminal, and not within a text editor!
import curses
from curses import KEY_RIGHT, KEY_LEFT, KEY_UP, KEY_DOWN
import random
import math
curses.initscr()
XSIZE, YSIZE = 18, 18
NFOOD = 1
win = curses.newwin(YSIZE, XSIZE, 0, 0)
win.keypad(1)
curses.noecho()
curses.curs_set(0)
win.border(0)
win.nodelay(1)
def placeFood(snake, food):
for last in food:
win.addch(last[0], last[1], ' ')
food = []
while len(food) < NFOOD:
potentialfood = [random.randint(1, (YSIZE - 2)), random.randint(1, (XSIZE - 2))]
if not (potentialfood in snake) and not (potentialfood in food):
food.append(potentialfood)
win.addch(potentialfood[0], potentialfood[1], '*')
return (food)
def translate(snake):
grid = []
for i in range(XSIZE):
grid.append(['.'] * YSIZE)
for i in snake.body:
grid[i[0]][i[1]] = '#'
return grid
def point_difference(snake, point):
if not point:
return -1
h = snake.body[0]
a = math.pow((point[0] - h[0]), 2)
b = math.pow((point[1] - h[1]), 2)
return math.sqrt(a + b)
def flood_fill(grid, x, y, old_character, new_char, info=None):
if info is None:
info = ((), [])
grid_width = len(grid)
grid_height = len(grid[0])
if old_character is None:
old_character = grid[x][y]
if grid[x][y] != old_character:
return info
grid[x][y] = new_char
t = info[1]
t.append((x, y))
if point_difference(snake, (x, y)) == 1:
coord_next_to_head = (x, y)
info = (coord_next_to_head, t)
else:
info = (info[0], t)
if x > 0: # left
info = flood_fill(grid, x - 1, y, old_character, new_char, info)
if y > 0: # up
info = flood_fill(grid, x, y - 1, old_character, new_char, info)
if x < grid_width - 1: # right
info = flood_fill(grid, x + 1, y, old_character, new_char, info)
if y < grid_height - 1: # down
info = flood_fill(grid, x, y + 1, old_character, new_char, info)
return info
def find_number_of_rooms(snake, grid):
grid_width = len(grid)
grid_height = len(grid[0])
rooms_found = -1
results = []
for x in range(grid_width):
for y in range(grid_height):
if grid[x][y] == '.':
coord_next_to_head, coords = flood_fill(grid, x, y, '.', 'x')
results.append((coord_next_to_head, coords))
rooms_found += 1
room_info = None
for ival in results:
for jval in results:
if (XSIZE * YSIZE) - len(ival[1]) - len(jval[1]) - len(snake.body) == 0:
if point_difference(snake, ival[0]) == 1:
# (point closest to head, room coordinates)
room_info = (ival[0], ival[1])
return rooms_found, room_info
def playGame():
score = 0
key = KEY_RIGHT
snake = [[4, 10], [4, 9], [4, 8], [4, 7], [4, 6], [4, 5], [4, 4], [4, 3], [4, 2], [4, 1],
[4, 0]] # Initial snake co-ordinates
food = []
food = placeFood(snake, food)
win.timeout(150)
wasAhead = []
ahead = []
A = "NO"
while True:
win.border(0)
prevKey = key # Previous key pressed
event = win.getch()
key = key if event == -1 else event
if key not in [KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN, 27]: # If an invalid key is pressed
key = prevKey
# Calculates the new coordinates of the head of the snake. NOTE: len(snake) increases
# This is taken care of later at [1] (where we pop the tail)
snake.insert(0, [snake[0][0] + (key == KEY_DOWN and 1) + (key == KEY_UP and -1),
snake[0][1] + (key == KEY_LEFT and -1) + (key == KEY_RIGHT and 1)])
# Game over if the snake goes through a wall
if snake[0][0] == 0 or snake[0][0] == (YSIZE - 1) or snake[0][1] == 0 or snake[0][1] == (XSIZE - 1): break
ahead = [snake[0][0] + (key == KEY_DOWN and 1) + (key == KEY_UP and -1),
snake[0][1] + (key == KEY_LEFT and -1) + (key == KEY_RIGHT and 1)]
if ahead in snake:
A = "YES"
# Game over if the snake runs over itself
if snake[0] in snake[1:]: break
if snake[0] in food: # When snake eats the food
score += 1
food = placeFood(snake, food)
else:
last = snake.pop() # [1] If it does not eat the food, it moves forward and so last tail item is removed
win.addch(last[0], last[1], ' ')
win.addch(snake[0][0], snake[0][1], '#')
input("Press to continue")
curses.endwin()
print
A
print("\nFinal score - " + str(score))
print
print
wasAhead
playGame()
|
966ca259273bd40eafea65463d32bdc36d4d0c99 | pragatirahul123/list | /Harshad_Number.py | 232 | 3.703125 | 4 | user=int(input("enter a number"))
sum=0
var=user
while var>0:
rem=var%10
sum=sum+rem
var=var//10
print(sum)
if(user%sum==0):
print("Harshad number")
else:
print("Not harshad number")
|
01484ceaa23e2c4fd650212ccb528210598c6c2d | Devansh-ops/HashCode2021 | /stupidV2.py | 1,841 | 3.859375 | 4 | # Hashcode 2021
# Team Depresso
# Problem - Traffic Signaling
## Data Containers
class Street:
def __init__(self,start,end,name,L):
self.start = start
self.end = end
self.name = name
self.time = L
def show(self):
print(self.start,self.end,self.name,self.time)
class Car:
def __init__(self,P, path):
self.P = P # the number of streets that the car wants to travel
self.path = path # names of the streets
# the car starts at the end of first street
def show(self):
print(self.P, self.path)
#Just getting data
with open('c.txt') as f:
D, I, S, V, F = list(map(int, f.readline()[:-1].split(" ")))
'''
l1 = f.readline()[:-1].split(' ')
D = int(l1[0]) # Duration of simulation 1 <D<10^4
I = int(l1[1]) # The number of intersections 2 ≤ I ≤ 10^5
S = int(l1[2]) # The number of streets 2 ≤ S ≤ 10 5
V = int(l1[3]) # The number of cars 1 ≤ V ≤ 10 3
F = int(l1[4]) # The bonus points for each car that reaches
# its destination before time D1 ≤ F ≤ 10 3
'''
# B, E, streets_descriptions = [], [], []
streets = [0]*S
for i in range(S):
line = f.readline()[:-1].split(' ')
street = Street(int(line[0]), int(line[1]), line[2], int(line[3]))
streets[i] = street
#street.show()
cars = [0]*V
for i in range(V):
line = f.readline()[:-1].split(' ')
car = Car(int(line[0]), line[1:])
cars[i] = car
#car.show()
o= open("c-output-try-stupid-v2.txt","w+")
o.write(str(I)+'\n')
for i in range(I):
o.write(str(i)+'\n')
num_roads_ending = 0
str_ending = []
for j in range(S):
if streets[j].end == i:
num_roads_ending += 1
str_ending.append(streets[j].name)
o.write(str(num_roads_ending)+'\n')
for k in range(num_roads_ending):
o.write(str_ending[k]+" "+ str(1)+'\n') |
ec0edfd7914077fc213524fe65fae3df4740008c | jesuprofun/python_problems | /functions/ex8.py | 199 | 4.25 | 4 |
def fact(num):
if num == 0:
return 1
else:
return num * fact(num - 1)
number = int(input("Enter the number to find factorial: "))
factorial = fact(number)
print(factorial)
|
6b2a4eff39228deffe0b7bc8217c5b7c8cd57a4a | yarik335/GeekPy | /HT_2/task3.py | 1,350 | 3.8125 | 4 | '''
Створіть 3 різних функції(на ваш вибір), кожна з цих функцій повинна повертати
якийсь результат. Також створіть четверу ф-цію, яка в тілі викликає 3
попередніб обробляє повернутий ними результат та також повертає результат.
Таким чином ми будемо викликати 1 функцію, а вона в своєму тілі ще 3
'''
def func1(n, x = 0, y = 0): #correcting x and y in loop
for i in range(0,n):
x = x + 0.1
y = y - 0.1
return (x,y)
def func2(a = "hello ", b = "new Legioner!"): #return string username + id or defaults
if(not(a == 'hello ' and b == 'new Legioner')):
c ="username: " + a + " userId: " + b
return c
def func3(s,c,p): #just some simple calculating
return str(s+c/p)
def func4(info = {},*args,**kwargs): #join functions before and add args + kwargs
if(info == {}):
func1(5)
func2()
func3(1, 220, 3.14)
else:
print(info)
s = str(func1(args[0])) + func2(args[1],args[2]) + func3(kwargs['sprint'], kwargs['charley'], kwargs['Pi'])
return s
print(func4({},2,"yarik","335 ",sprint=5,charley=8,Pi=3.14))
|
2f11e7bd7981e67437e4dd30b4882e78e84de586 | Ellieli78/LearnMorePython3theHardWay | /Ex5/Ex5cat.py | 608 | 3.6875 | 4 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", metavar = 'E',type = str,nargs = '+',
help = "display a square of a given number")
parser.add_argument("-n", '--numbers', action='store_true',
help = 'Print line numbers')
args = parser.parse_args()
print(">>>", args)
i = 1
for in_square_name in args.square: # read the file name from Terminal input
in_file = open(in_square_name)
if args.numbers:
for line in in_file.readlines():
print(f"{i} {line}", end='')
i += 1
else:
print(in_file.read())
|
dc97b6dd04d6b8e0daf57bdacab3fb883427beff | Gunny-Lee/chatbot | /lotto.py | 831 | 3.5 | 4 | """
requests를 통해 동행복권 API 요청을 보내어, 1등 번호를 가져와 python list로 만듬
"""
import requests
# 1. requests 통해 요청 보내기
url = "https://www.dhlottery.co.kr/common.do?method=getLottoNumber&drwNo=873"
response = requests.get(url)
# print(response) # 200뜨면 됩니다
# 콘솔에서 python lotto.py 입력해서 확인
# print(response.text) # 내용이 나옴
res_dict = response.json() # dictionary타입으로 가져옴
# print(res_dict)
# print(res_dict['drwtNo1'])
result = []
# result.append(res_dict['drwtNo1'])
# result.append(res_dict['drwtNo2'])
# result.append(res_dict['drwtNo3'])
# result.append(res_dict['drwtNo4'])
# result.append(res_dict['drwtNo5'])
# result.append(res_dict['drwtNo6'])
# print(result)
for i in range(1,7):
result.append(res_dict[f'drwtNo{i}']) |
158c2c9c4439634f5dda7358bf9816a7462b26df | huiup/python_notes | /function/装饰器/c1.py | 383 | 3.515625 | 4 | import time
# 不使用装饰器时
# 开闭原则:对修改是封闭的,对扩展是开放的
# 新加业务逻辑:添加运行函数时打印运行时间的功能
# 允许向一个现有的对象添加新的功能,同时又不改变其结构。
def print_time(func):
print(time.time())
func()
def f1():
print('this is a function')
print_time(f1)
|
4d5ed3f3a9dc5d90419621a90d9ff8a9c48afaa9 | gabrielnhn/snake | /snake.py | 979 | 4.09375 | 4 | """Snake class and methods implementation:"""
class Snake:
def __init__(self, size, lines, columns, char, color):
"""
Initializes the snake in the center of the board,
With an initial 'size'
"""
if size > columns:
raise ValueError("Snake's size is too large")
self.coords = [(lines//2 - 1, columns//2 + x - 1) for x in range(-size + 1, 1) ]
self.char = char
self.color = color
def move_to(self, line, column):
"""Move the snake to (line, column)."""
self.coords.pop(0)
self.coords.append((line, column))
def grow_to(self, line, column):
"""Move the snake to (line, column) increasing its size by 1."""
self.coords.append((line, column))
def get_head(self):
"""Return the last coordinate."""
return self.coords[-1]
def __repr__(self):
return self.char
def __str__(self):
return self.__repr__() |
ebd71f19b842cade340b112aff24f95838499d90 | cnsapril/JZAlgo | /Ch 1 - Introduction & Subsets/permutations.py | 597 | 3.859375 | 4 | """
Given a list of numbers, return all possible permutations.
You can assume that there is no duplicate numbers in the list.
"""
class Solution(object):
def permute(self, nums):
def _permute(result, temp, nums):
if not nums:
result += [temp]
else:
for i in range(len(nums)):
_permute(result, temp + [nums[i]], nums[:i] + nums[i+1:])
if nums is None:
return []
result = []
_permute(result, [], nums)
return result
sol = Solution()
print sol.permute([1, 3, 2])
|
3ba96b004e67087b033f0f075c98630ffb891892 | miriamlam1/csc349 | /asgn3-miriamlam1/two_colorable.py | 1,895 | 4.03125 | 4 | # two colorable / bipartite / no odd cycles
# input: a graph given in a list of edges connecting vertices
# output: lists of each color if 2-colorable, else false
from collections import *
import sys
class Graph():
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self,v1,v2):
self.graph[v1].append(v2)
def bipartite(G):
red = []
blue = []
for start in sorted(G.graph): # checking all paths
if start not in red and start not in blue: # to make sure we hit disconnected parts
red.append(start)
queue = []
queue.append(start)
while queue:
current_vertex = queue.pop()
for neighbor in G.graph[current_vertex]:
if neighbor not in red and neighbor not in blue:
queue.append(neighbor)
if current_vertex in red:
blue.append(neighbor)
else:
red.append(neighbor)
elif (current_vertex in red and neighbor in red) or\
(current_vertex in blue and neighbor in blue):
print ("Is not 2-colorable.")
return
print("Is 2-colorable:")
print(", ".join(red))
print(", ".join(blue))
def get_graph(file):
f = open(file, "r")
g = Graph()
for line in f:
line = line.split()
g.add_edge(line[0], line[1])
f.close()
return g
def main():
g = get_graph(sys.argv[1])
bipartite(g)
if __name__ == "__main__":
main()
|
86dc179c42dd6c4e3ab083e17062b149b4ec8202 | JBPelzner/Termite | /webscrapers/web_scraper_v1.py | 962 | 3.640625 | 4 | ## Source: https://pythonspot.com/extract-links-from-webpage-beautifulsoup/
### THE PACKAGES IN THIS LINK ARE OUTDATED
"""Note: this version is somewhat functional, although it does not return even the relative links
from the footer of the HTML page that are returned in the v2 scraper
"""
from bs4 import BeautifulSoup
from urllib.request import urlopen
# import urllib.request
import re
def getLinks(url):
print(url, '\n ----------')
html_page = urlopen(url)
soup = BeautifulSoup(html_page, features="lxml")
# soup = BeautifulSoup(html_page, 'html.parser')
links = []
for link in soup.findAll('a', attrs={'href': re.compile("^https://")}): ##original code
# for link in soup.findAll('a', attrs={'class': 'Fx4vi'}):
links.append(link.get('href'))
for link in links:
print(link, '\n')
# print( getLinks("https://www.google.com" ) )
print( getLinks("https://www." + input("Enter website URL here: ")) ) |
ee18a8ed6c732aa87c2527e449587aea26b38252 | ZhaoYun17/sql | /car_sql3.py | 472 | 3.9375 | 4 | # use COUNT() calculate total number of orders for each make and model
# Output car's make and model
# output quantity
# output order count
import sqlite3
with sqlite3.connect("cars.db") as connection:
c = connection.cursor()
c.execute("SELECT * FROM inventory")
rows = c.fetchall()
for r in rows:
print r[0], r[1]
print "Quantity of car: " + str(r[2])
c.execute("SELECT count(order_date) FROM orders WHERE model=?",(r[1],))
print c.fetchone()[0]
print |
868345620ebf25c4a37043e0a31579dac1e0fea7 | MrHamdulay/csc3-capstone | /examples/data/Assignment_8/hlncec001/question3.py | 956 | 4.15625 | 4 | #HLNCEC001
#Question3
#Assignment8
#program that uses a recursive function to encrypt a message
l = []
def encrypt(s):
global l
if s == s.lower():
if ord(s[0]) == 122:
a = 122 - 26
s =chr(a)+s[1:]
return encrypt(s)
elif s[0] != ' ' and (s[0] != '.') and len(s)!=1:
new_word = chr(ord(str(s[0]))+1)
l.append(new_word)
return encrypt(s[1:])
elif len(s) == 1:
if s[0] !='.':
l.append(chr(ord(str(s[0]))+1))
print('Encrypted message:\n',''.join(l),sep="")
else:
l.append(s[0])
print('Encrypted message:\n',''.join(l),sep="")
else:
l.append(s[0])
return encrypt(s[1:])
else:
print("Encrypted message:\n",s,sep='')
encrypt(s=input('Enter a message:\n')) |
ad10751cb94853670a2a77e0a44027bcea3f5bfd | Dissssy/AdventOfCode2020 | /03/2/code.py | 1,180 | 3.703125 | 4 | import time
start_time = time.time()
#open the file and parse it into a list of strings on newlines
text_file = open("input.txt", "r")
lines = text_file.read().split('\n')
#every input text file has an empty newline at the end, delete it
lines.pop(-1)
#define the checkslope function that i will be using to check each slope
def checkslope(slope,trees):
j = 0
count = 0
for i in range(0, len(trees), slope[0]):
if trees[i][j % len(trees[0])]:
count += 1
j += slope[1]
return(count)
#convert our input to a 2d list of bools rather than a list of strings
formatted = [[None for i in range(len(lines[0]))] for j in range((len(lines)))]
for i in range(0, len(lines)):
for j in range(0, len(lines[0])):
if(lines[i][j] == '#'):
formatted[i][j] = True
else:
formatted[i][j] = False
#calculate and print the output
output = ((checkslope([1,1],formatted)) *
(checkslope([1,3],formatted)) *
(checkslope([1,5],formatted)) *
(checkslope([1,7],formatted)) *
(checkslope([2,1],formatted)))
print(output)
print("--- %s seconds ---" % (time.time() - start_time))
|
5ea4bf263ae6550766a96ff1b86af63d67ed4b0f | posuna19/pythonBasicCourse | /course2/week3/03_regex_wildcards.py | 2,612 | 4.15625 | 4 | import re
regex = r"[Pp]"
text = "Python, python, ruby, Xython, papa"
result = re.search(regex, text)
print("Result: ", result)
result = re.match(regex, text)
print("Result: ", result)
result = re.findall(regex, text)
print("Result: ", result)
regex = r'[a-z]way'
text = 'The end of the highway'
result = re.search(regex, text)
print("Result: ", result)
text = 'What a way to go'
result = re.search(regex, text)
print("Result: ", result) #It is None because the way word is preceding by a space which is not considered
# a letter in the range a-z from the regex
regex = r"cloud[a-zA-Z0-9]"
text = "cloudy"
result = re.search(regex, text)
print("Result: ", result)
text = "cloud9"
result = re.search(regex, text)
print("Result: ", result)
#In-lesson exercise
def check_punctuation (text):
result = re.search(r"[,.:;?!]", text)
return result != None
print(check_punctuation("This is a sentence that ends with a period.")) # True
print(check_punctuation("This is a sentence fragment without a period")) # False
print(check_punctuation("Aren't regular expressions awesome?")) # True
print(check_punctuation("Wow! We're really picking up some steam now!")) # True
print(check_punctuation("End of the line")) # False
#By using the circunflex special char inside the brackets we can set a negation regex
regex = r"[^a-zA-Z]" #This regex matches only non-letter chars
text = "This is a sentence with spaces."
result = re.search(regex, text)
print("Result: ", result) #It matches to the 5th char(index 4) in the string
regex = r"[^a-zA-Z ]" #This matches any char that is not a letter or nor a space
text = "This is a sentence with spaces."
result = re.search(regex, text)
print("Result: ", result) #It matches to last char of the string, which is the period(.)
regex = r"cat|dog"
text = "I like cats"
result = re.search(regex, text)
print("Result: ", result)
text = "I like dogs"
result = re.search(regex, text)
print("Result: ", result)
text = "I like both dogs and cats"
result = re.findall(regex, text)
print("Result: ", result) # Find all functions is used to find several matches, while the search function is used to find
# only the first match
regex = r"\d"
text = "I like cats213 dasdasd"
result = re.search(regex, text)
print("Result: ", result)
text = "I like cats213 dasdasd"
result = re.findall(regex, text)
print("Result: ", result)
regex = r"\d+"
text = "I like cats213 dasdasd"
result = re.search(regex, text)
print("Result: ", result)
text = "I like cats213 dasdasd"
result = re.findall(regex, text)
print("Result: ", result) |
75696936ead8d45fc5351e28466946047b4b8959 | MariaSun/Algebraic-Montgomery-multiplication | /montgomery_multiplication.py | 1,312 | 3.796875 | 4 | ##########################################################
#08/12/2021 -- Maria Solyanik-Gorgone #
#Exact algebraic algorithm for Montgomery multiplication.#
##########################################################
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import cmath
import math
import cv2
def check_if_prime(num):
if num > 1:
for i in range(2, int(num/2)+1):
if (num % i) == 0:
print(num, "is not a prime number, must be a prime!")
break
def hcfnaive(a,b):
if(b==0):
return a
else:
return hcfnaive(b,a%b)
def find_inverse(a, mod):
for i in range(1,10000000):
if (i*a) % mod == 1:
res = i
break
return res
def bar_calculation(num, res, mod):
return (num * res) % mod
a = 28510
b = 38672
m = 36057
r = 2**(17)
if hcfnaive(m,r)!=1: print('gcd(m, r)==1 and it is not, pick m as relative prime of r!')
R = find_inverse(r, m)
M = find_inverse(-m, r)
if (r*R) - (m*M)!=1: print('The inverse of m and r produced errors. Check!')
a_bar = bar_calculation(a, r, m)
b_bar = bar_calculation(b, r, m)
second = ((a_bar*b_bar*M) % r) * m
c_bar = ((a_bar*b_bar) + second)/r
c = bar_calculation(c_bar, R, m)
if c % 1 != 0: print('Result must be integer! Check the algorithm!')
print(int(c))
|
a51d19421472e22969ea8e086131ff3fff0b72c7 | Anton-L-GitHub/Learning | /Python/1_PROJECTS/Python_bok/Uppgifter/Kap8/uppg8-5.py | 244 | 3.65625 | 4 | def är_perfekt(n):
sum = 0
for k in range(1, n):
if n % k == 0:
sum = sum + k
return sum == n
tal = int(input('Skriv ett tal: '))
if är_perfekt(tal):
print('Talet är perfekt')
else:
print('Talet är inte perfekt') |
82f3c685b4137be5f99fd411a09869e36702ba1e | vivianvivi1993/X-Village-2018-Exercise | /周蔚Analysis/30.py | 2,593 | 3.546875 | 4 | # data visualization
# 關於API獲得json檔案的資料
# 選擇豆瓣圖書
import json
import pandas as pd
import requests
import matplotlib.pyplot as plt
plt.rcdefaults()
from requests_html import HTMLSession
import re
url = 'https://api.douban.com/v2/book/4238362'
r = requests.get(url)
r.encoding = "utf-8"
r=r.json()
count=[]
name=[]
for i in r['tags']:
count.append(i['count'])
name.append(i['name'])
colors=['b','r','g','y','k','#9999ff','#ff9999','#7777aa']
plt.axes(aspect = 'equal')
plt.xlim(0,4)
plt.ylim(0,4)
plt.rcParams['font.sans-serif'] = ['simhei']
plt.rcParams['axes.unicode_minus'] = False
plt.pie(x = count,labels = name,colors=colors,autopct = '%.1f%%',pctdistance = 0.8,radius=1.5,counterclock = False,
center = (1.8,1.8),frame = 2)
plt.xticks(())
plt.yticks(())
plt.title('《送你一顆子彈》標籤分析')
plt.show()
# ==================================================
session = HTMLSession()
response = session.get('https://book.douban.com/')
element_rating = response.html.find('p.entry-star-small .average-rating')
element_bookname = response.html.find('li div.info h4.title a')
element_ratinglist=[]
element_booknamelist=[]
for i in element_rating:
element_ratinglist.append(i.text)
list_to_float = list(map(lambda x:float(x), element_ratinglist))
for j in element_bookname:
element_booknamelist.append(j.text)
# print(list_to_float,element_booknamelist)
plt.ylabel(u'熱門圖書名稱')
plt.xlabel(u'熱門圖書評分')
plt.title(u'最受關注圖書榜評分數據')
plt.rcParams['font.sans-serif'] = ['simhei']
plt.rcParams['axes.unicode_minus'] = False
plt.barh(range(len(element_booknamelist)),list_to_float,fc='b',align = 'center',alpha = 0.41,left = 0,)
plt.yticks(range(len(element_booknamelist)),element_booknamelist)
series_1 = pd.Series(list_to_float,index=element_booknamelist)
print(series_1)
plt.show()
# ======================
session = HTMLSession()
response = session.get('https://book.douban.com/tag/?view=type&icn=index-sorttags-all')
review_num = response.html.find('div#content td')
a = []
b = []
c = []
d = []
for i in review_num:
a.append(re.findall(r'\d+',i.text))
c.append(i.text)
for j in a:
for ii in j:
b.append(int(ii))
plt.figure(figsize=(160,200))
plt.xlim((0,10000000))
plt.ylim((0,150))
plt.grid(True, linestyle = "-", color = "grey", linewidth = "0.5",alpha = 0.3)
plt.rcParams['font.sans-serif'] = ['simhei']
plt.rcParams['axes.unicode_minus'] = False
plt.barh(range(len(c)),b,fc='blue',align = 'center',alpha = 0.6,left = 0)
plt.yticks(range(len(c)),c)
plt.show()
|
a8564ed0c6650c793ce40329bc378c7982ee47fa | deepikanagalakshmi/python | /4for_loop.py | 258 | 3.859375 | 4 | import turtle
my_turtle = turtle.Turtle()
my_turtle.speed(1)
#triangle
def triangle():
my_turtle.forward(100)
my_turtle.left(90)
my_turtle.forward(100)
my_turtle.left(135)
my_turtle.forward(142)
for count in range(3):
triangle()
|
5a5083d54ea68e863e32c90678cc8f42982ee73f | Vanyali/100-Python-challenging-programming-exercises | /Question24.py | 773 | 4.125 | 4 | '''
Question:
Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books.
But Python has a built-in document function for every built-in functions.
Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input()
And add document for your own function
'''
#for example....
print(abs.__doc__)
print(int.__doc__)
print(float.__doc__)
print(isinstance.__doc__)
print(InterruptedError.__doc__)
print(str.__doc__)
print(sorted.__doc__)
print(reversed.__doc__)
#On my own
def squarefunc(n):
'''
Just simply function to square the number given.
'''
return n**2
#Gonna show up the triple string above, inside the function!
print(squarefunc.__doc__)
|
613132ab909da8cc94e52454695070735e3fc59c | zhangwang0537/LeetCode-Notebook | /source/Clarification/Array/44.通配符匹配.py | 1,166 | 3.84375 | 4 | # 给定一个字符串 (s) 和一个字符模式 (p) ,实现一个支持 '?' 和 '*' 的通配符匹配。
#
# '?' 可以匹配任何单个字符。
# '*' 可以匹配任意字符串(包括空字符串)。
# 两个字符串完全匹配才算匹配成功。
#
# 说明:
#
# s 可能为空,且只包含从 a-z 的小写字母。
# p 可能为空,且只包含从 a-z 的小写字母,以及字符 ? 和 *。
# 示例 1:
#
# 输入:
# s = "aa"
# p = "a"
# 输出: false
# 解释: "a" 无法匹配 "aa" 整个字符串。
class Solution:
def isMatch(self, s: str, p: str) -> bool:
i = 0
j = 0
start = -1
match = 0
while i < len(s):
if j < len(p) and (s[i] == p[j] or p[j] == "?"):
i += 1
j += 1
elif j < len(p) and p[j] == "*":
start = j
match = i
j += 1
elif start != -1:
j = start + 1
match += 1
i = match
else:
return False
return all(x=="*" for x in p[j:]) |
d2dbf5e8ecd342cd1ee46aa4e79da37505c64b7d | weipanchang/FUHSD | /list-swap-element.py | 233 | 3.96875 | 4 | #!/usr/bin/env python
def swap(l,i,j):
l[i], l[j] = l[j], l[i]
bag=[]
for i in range(10):
item=int(input("Enter the next item: "))
bag.append(item)
print bag
print""
print "after swap:"
swap(bag,2,8)
print ""
print bag
|
d956a3f65838eec912867ebe5325d60e89957d8f | sudhasr/DS-and-Algorithms-Practice | /CheckStraigntLine.py | 1,115 | 4.03125 | 4 | # 1232. Check If It Is a Straight Line
"""
You are given an array coordinates, coordinates[i] = [x, y], where [x, y] represents the coordinate of a point. Check if these points make a straight line in the XY plane.
Example 1:
Input: coordinates = [[1,2],[2,3],[3,4],[4,5],[5,6],[6,7]]
Output: true
Example 2:
Input: coordinates = [[1,1],[2,2],[3,4],[4,5],[5,6],[7,7]]
Output: false
Constraints:
2 <= coordinates.length <= 1000
coordinates[i].length == 2
-10^4 <= coordinates[i][0], coordinates[i][1] <= 10^4
coordinates contains no duplicate point.
"""
"""
Approach:
"""
# Time Complexity - O(N)
# Space Complexity - O(1)
class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
# Edge Case
if len(coordinates) == 2:
return True
(x0, y0), (x1, y1) = coordinates[0], coordinates[1]
for i in range(2, len(coordinates)):
x, y = coordinates[i]
if (x1 - x0) * (y - y1) != (x - x1) * (y1 - y0):
return False
return True |
5c6397795cdec74db136bee2f236e15297051085 | AChen24562/Python-QCC | /Week-3-Lists/ListsExamples_I/5_list_modify.py | 237 | 4.125 | 4 | # s. trowbridge 2020
vehicles = ['car', 'truck', 'motorcycle', 'plane', 'boat']
# modify the first list element
vehicles[0] = 'bike'
print(vehicles)
print("")
# modify the third list element
vehicles[2] = 'scooter'
print(vehicles)
print("")
|
fc1c43e065320e5f1701c57e07c2878370ed9712 | amirmojarad/maze | /models/main.py | 1,053 | 3.609375 | 4 | import map_generator
import astar
import path_drawer
import time
def main():
# Reading maze from file
print('Loading file...')
with open('examples/normal.txt') as file:
text_maze = file.read()
print('File loaded')
# Generate graph from raw text in file
print('Creating maze graph')
t1 = time.time()
maze_graph = map_generator.MapGenerator(text_maze)
t2 = time.time()
print('Graph created in:', t2 - t1, 'seconds')
print('nodes:', maze_graph.node_count)
# Solve and fine path in maze by a* algorithm
print('Start solving maze')
t1 = time.time()
result = astar.solve(maze_graph)
t2 = time.time()
print('Maze solved in:', t2 - t1, 'seconds')
print('node visited:', result.get('node_visited'))
print('path length:', result.get('path_length'))
print('path founded:', result.get('completed'))
solved = path_drawer.draw(result.get('path'), text_maze)
with open('answer.txt', 'w') as file:
file.write(solved)
if __name__ == '__main__':
main()
|
825560c8d4e9ac7d00e089242565494656aea8d9 | GabrielTrentino/Python_Basico | /02 - Curso Em Video/Aula 16/E - 077.py | 291 | 3.703125 | 4 | palavras = ('AVIÃO', 'CARRO' , 'FUTEBOL', 'SKATE','PYTHON','JAVA','CHUVA','ARVORE','NATUREZA')
for i in palavras:
print("Na palavra {}, temos: ".format(i), end = '')
for letra in i:
if letra.lower() in 'aeiou':
print(letra.lower(), end = ' ')
print('') |
bf1fa8daebe674fae8c5e879bd04e9e303ef4289 | moaoh/algorithm | /baekjoon/1673번 - 치킨 쿠폰/main.py | 285 | 3.59375 | 4 | def count(chicken, n, k):
if n >= k:
coupon = n // k
chicken += n // k
n = n % k
n += coupon
return count(chicken, n, k)
return chicken
while True:
try:
n, k = map(int, input().split())
chicken = n
chicken = count(chicken, n, k)
print(chicken)
except:
break
|
a25f2328c4bdf587a5f2a08201d4c5e9550bd057 | sainad2222/my_cp_codes | /codeforces/1038/B.py | 292 | 3.5 | 4 | n = int(input())
if n<=2:
print("No")
exit()
print("Yes")
print(n//2,end=" ")
lis = [x for x in range(2,n+1,2)]
print(' '.join(map(str,lis)))
if n&1:
print((n//2)+1,end=" ")
else:
print(n//2,end=" ")
lis = [x for x in range(1,n+1,2)]
print(' '.join(map(str,lis))) |
eb0a9974c5d3c105b44026c5f96c14be4168cbb6 | Lyuflora/test | /classed.py | 505 | 3.703125 | 4 | # 类和对象
class Student(object):
def __init__(self, name, score):
self.name = name
self.__score = score
def print_score(self):
print('%s, %s' % (self.name, self.__score))
def get_score(self):
return self.__score
def set_score(self, mark):
self.__score = mark
# "__"开头的变量是私有的 private
bart = Student('Bart', 99)
print(bart)
bart.print_score()
bart.name
# 前后双下划线的是特殊变量,是可以直接访问的
|
0b2ad8323ac3e5958812becab7af0dc7643a6b64 | JeonghoonWon/Eclipse_Pydev | /HELLOPYTHON/day01/myholl.py | 291 | 3.578125 | 4 | import random
com = ""
mine = input("홀/짝을 선택하세요.")
result = ""
rnd = random.random()
if rnd > 0.5:
com = "홀"
else:
com = "짝"
if com == mine :
result = "승리"
else :
result = "패배"
print("컴 : ", com)
print("나 : ",mine)
print("결과 :",result) |
86757049b020781019b68e36e007c89c3d4e49ef | Barshon-git/Test | /Try Except.py | 183 | 3.953125 | 4 | try:
value=10/0
number= int(input("Enter a number: "))
print(number)
except ZeroDivisionError :
print("Division by zero")
except ValueError:
print("Invalid input") |
784d053765e5e95f93c307b671df8e515d42e758 | Taeg92/Problem_solving | /SWEA/D2/SWEA_1948.py | 879 | 3.5625 | 4 | # Problem [1948] : 날짜 계산기
# 입력 : 월 일로 이루어진 날짜 2개
# 두 번째 날짜가 첫 번째 날짜의 몇칠째 인지 출력
# 두 번째 날짜 > 첫 번쨰 날짜
calendar = {1 : 31, 2 : 28, 3 : 31, 4 : 30, 5 : 31, 6 : 30, 7 : 31, 8 : 31, 9 : 30, 10 : 31, 11 : 30, 12 : 31}
test_cnt = int(input())
for test in range(1,test_cnt+1) :
result = 0
calc_date = list(map(int,input().split()))
month1 = calc_date[0]
date1 = calc_date[1]
month2 = calc_date[2]
date2 = calc_date[3]
date_sum1 = 0
date_sum2 = 0
if month1 == month2:
result = date2 - date1 + 1
else :
for i in range(1,month1) :
date_sum1 += calendar[i]
for i in range(1,month2) :
date_sum2 += calendar[i]
result = (date_sum2+date2) - (date_sum1 + date1) + 1
print('#{} {}'.format(test,result)) |
1220a27f56bbc2f55e28e17f3c6b435a7df827b0 | EmersonDantas/SI-UFPB-IP-P1 | /Python Brasil - Exercícios/Estrutura Sequencial/Q15ES-Salário-Horas-Impostos.py | 419 | 3.75 | 4 | gh = float(input('Quanto você ganha por hora: '))
nhtm= float(input('Número de horas trabalhadas no mês: '))
salarioTotal = gh * nhtm
ir = salarioTotal * 0.11
inss = salarioTotal * 0.08
sindi = salarioTotal * 0.05
salarioLiquido = salarioTotal - (inss + sindi + ir)
print('Salário bruto: R${0}\nINSS: R${1}\nSindicato: R${2}\nSalário liquido: R${3}'
.format(salarioTotal,inss,sindi,salarioLiquido))
|
cf82bb27c03d521111e449f589064441a9ec3583 | massadraza/Python-Learning | /dictionary_calculations.py | 422 | 3.953125 | 4 | Stock = {
'NASDAQ': 10680.36,
'NYSE': 12508.68,
'Dow Jones': 26840.40,
'APPL': 388.00,
'SBUX': 75.44,
'NKE': 98.36,
'TMUS': 105.58,
'AMZN': 3138.29,
}
min_price = min(zip(Stock.values(), Stock.keys()))
max_price = max(zip(Stock.values(), Stock.keys()))
print(min_price)
print(max_price)
# Learning how to print the min and max values from a list.
|
31444eab42be319c3d709b195fe86028b477f38d | Behzodbek777/Python_darslari | /02.07.2021/massivlar(ro'yxat).py | 472 | 3.671875 | 4 | oquchilar = ["Abduvaliyeva", "Abdusalomova", "Aliqulova", "Jabborov", "Sattorov", "Xudoyorov" ]
print(oquchilar)
oquchilar.append("Xudoyberdiyev")
print(oquchilar)
oquchilar.insert(3,"Bo'ribekova")
print(oquchilar)
print(len(oquchilar))
oquchilar.append("Aliqulova")
print(oquchilar.count("Aliqulova"))
oquchilar1 = ["Boboyeva", "Ro'ziqulov", "Jo'rayeva"]
oquchilar.extend(oquchilar1)
print(oquchilar)
print(oquchilar.index("Jo'rayeva"))
oquchilar.clear()
print(oquchilar) |
f00d8d0bd44dc8f52538f79c8955398d60ce6f9b | Near-River/leet_code | /181_190/190_reverse_bits.py | 933 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100),
return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
"""
class Solution(object):
def reverseBits(self, n):
"""
:type n: int
:rtype: int
"""
# solution one
binary = ''
temp = 1
for i in range(32):
binary += '1' if n & temp != 0 else '0'
temp <<= 1
ret = int(binary, 2)
# return ret
# solution two
ret = 0
for i in range(32):
ret = ret << 1 | (n & 1)
n >>= 1
return ret
if __name__ == '__main__':
solution = Solution()
print(solution.reverseBits(43261596))
|
634fcca82968a83826828abb30f19dffcd1bf285 | Christy538/Hacktoberfest-2021 | /PYTHON/Gui calculator.py | 6,784 | 3.90625 | 4 | from tkinter import *
root = Tk()
#button_9 = Button(label_key,text='9',height=3,width=5,font=('Helvetica','12'))
#button_9.grid(row=0,column=0)
class Calculator:
def click_button(self,numbers):
global operator
global var
self.operator = self.operator + str(numbers)
self.var.set(self.operator)
def clear(self):
self.entry.delete(0,END)
self.operator =""
''' def delete(self):
self.operator = str(self.entry.delete(len(self.entry.get())-1))
'''
def evaluate(self):
self.answer =eval(self.entry.get())
self.var.set(self.answer)
self.operator = str(self.answer)
def __init__(self,master):
self.operator = ""
self.var = StringVar()
frame_s = Frame(master, height=400, width=45 )
frame_s.pack(side=TOP, fill=BOTH, expand=True)
self.entry = Entry(frame_s,textvariable=self.var,bg='black',width=45,bd=20,insertwidth=4,justify='right',font=('arial',10,'bold'))
self.entry.pack()
self.t = Text(self.entry,height=40)
label_key = Label(root, height=15, width=30,bd=10,bg='black')
label_key.pack(side=LEFT, fill=BOTH, expand=True)
label_fkey = Label(root, height=15, width=15, bg='black')
label_fkey.pack(fill=BOTH, expand=True)
label_7 = Label(label_key, bg='black')
label_7.grid(row=0, column=0)
button_7 = Button(label_7, text='7', font=('Helvetica', '16'),command= lambda : self.click_button(7),bg='black',fg='yellow')
button_7.pack()
label_8 = Label(label_key, bg='black')
label_8.grid(row=0, column=1, padx=20)
button_8 = Button(label_8, text='8', font=('Helvetica', '16'),command= lambda: self.click_button(8),bg='black',fg='yellow')
button_8.pack()
label_9 = Label(label_key, bg='black')
label_9.grid(row=0, column=2, padx=10)
button_9 = Button(label_9, text='9', font=('Helvetica', '16'),command= lambda: self.click_button(9),bg='black',fg='yellow')
button_9.pack()
label_4 = Label(label_key, bg='black')
label_4.grid(row=1, column=0, padx=10, pady=10)
button_4 = Button(label_4, text='4', font=('Helvetica', '16'),command= lambda: self.click_button(4),bg='black',fg='yellow')
button_4.pack()
label_5 = Label(label_key, bg='black')
label_5.grid(row=1, column=1, padx=10, pady=10)
button_5 = Button(label_5, text='5', font=('Helvetica', '16'),command= lambda: self.click_button(5),bg='black',fg='yellow')
button_5.pack()
label_6 = Label(label_key, bg='black')
label_6.grid(row=1, column=2, padx=10, pady=10)
button_6 = Button(label_6, text='6', font=('Helvetica', '16'),command= lambda: self.click_button(6),bg='black',fg='yellow')
button_6.pack()
label_1 = Label(label_key, bg='black')
label_1.grid(row=2, column=0, padx=10)
button_1 = Button(label_1, text='1', font=('Helvetica', '16'),command= lambda: self.click_button(1),bg='black',fg='yellow')
button_1.pack()
label_2 = Label(label_key, bg='black')
label_2.grid(row=2, column=1, padx=10)
button_2 = Button(label_2, text='2', font=('Helvetica', '16'),command= lambda: self.click_button(2),bg='black',fg='yellow')
button_2.pack()
label_3 = Label(label_key, bg='black')
label_3.grid(row=2, column=2, padx=10)
button_3 = Button(label_3, text='3', font=('Helvetica', '16'),command= lambda: self.click_button(3),bg='black',fg='yellow')
button_3.pack()
label_0 = Label(label_key, bg='black')
label_0.grid(row=3, column=0, padx=10, pady=10)
button_0 = Button(label_0, text='0', font=('Helvetica', '16'),command= lambda: self.click_button(0),bg='black',fg='yellow')
button_0.pack()
label_deci = Label(label_key, bg='black')
label_deci.grid(row=3, column=1, padx=10, pady=10)
button_deci = Button(label_deci, text='.', font=('Helvetica', '16'),command= lambda: self.click_button('.'),bg='black',fg='yellow')
button_deci.pack()
label_equal = Label(label_key, bg='black')
label_equal.grid(row=3, column=2, padx=10, pady=10)
button_equal = Button(label_equal, text='=', font=('Helvetica', '16'),command= self.evaluate,bg='black',fg='yellow')
button_equal.pack()
label_C = Label(label_fkey, bg='black')
label_C.grid(row=0, column=0,columnspan=2)
button_C = Button(label_C, text='C', font=('Helvetica', '16'), height=1, width=10,command= self.clear,bg='black',fg='yellow')
button_C.pack(side=LEFT)
'''label_del = Label(label_fkey, bg ='black')
label_del.grid(row=0,column=1,sticky=E)
button_del = Button(label_del, text='del', font=('Helvetica', '16'),bd=3, height=1, width=3,command= self.delete)
button_del.pack()'''
label_sub = Label(label_fkey, bg='black')
label_sub.grid(row=1, column=0, sticky=W, pady=10)
button_sub = Button(label_sub, text='-', font=('Helvetica', '16'), height=1, width=3,command= lambda: self.click_button('-'),bg='black',fg='yellow')
button_sub.pack(side=LEFT)
label_mul = Label(label_fkey, bg='black')
label_mul.grid(row=1, column=1, sticky=E)
button_mul = Button(label_mul, text='x', font=('Helvetica', '16'), height=1, width=3,command= lambda: self.click_button('*'),bg='black',fg='yellow')
button_mul.pack()
label_div = Label(label_fkey, bg='black')
label_div.grid(row=2, column=0, sticky=W)
button_div = Button(label_div, text='/', font=('Helvetica', '16'), height=1, width=3,command= lambda: self.click_button('/'),bg='black',fg='yellow')
button_div.pack()
label_add = Label(label_fkey, bg='black')
label_add.grid(row=2, column=1, sticky=E)
button_add = Button(label_add, text='+', font=('Helvetica', '16'), height=1, width=3,command= lambda: self.click_button('+'),bg='black',fg='yellow')
button_add.pack()
label_lbrace = Label(label_fkey, bg='black')
label_lbrace.grid(row=3,column=0,sticky=W,pady=10)
button_lbrace = Button(label_lbrace,text='(', font=('Helvetica', '16'), height=1, width=3,command= lambda: self.click_button('('),bg='black',fg='yellow')
button_lbrace.pack()
label_rbrace = Label(label_fkey, bg='black')
label_rbrace.grid(row=3, column=1, sticky=E, pady=10)
button_rbrace = Button(label_rbrace, text=')', font=('Helvetica', '16'), height=1, width=3,
command=lambda: self.click_button(')'),bg='black',fg='yellow')
button_rbrace.pack()
c = Calculator(root)
root.title("Calculator")
root.mainloop()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.