blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 3.06M | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 3.06M |
|---|---|---|---|---|---|---|
17ed1954aef7212bf33317ee7e8c174d7f26ca65 | AnnMokhova/PROGA | /hw10/hw10.py | 839 | 3.5625 | 4 | #вариант 2
import re
def open_file(file):
with open(file, 'rb') as f:
f = f.read()
return f
def search_write():
ask = input('Введите название города, часовой пояс которого вы хотите узнать ') #Москва Берлин Нью-Йорк
if ask == 'Москва':
doc = 'Moscow.html'
if ask == 'Берлин':
doc = 'Berlin.html'
if ask == 'Нью-Йорк':
doc = 'NY.html'
text = open_file(doc)
result = re.search(r'Часовой пояс (\S+\s+\S+)', text.decode('utf-8'), re.I | re.U)
with open('text.txt', 'w') as empty_file:
empty_file.write(result.group())
print('Откройте файл text.txt, чтобы узнать часовой пояс указанного города')
search_write()
|
fc7534418fb1b55e1b4aa92c6718bb2553b8efc7 | AnnMokhova/PROGA | /hw2.py | 225 | 3.921875 | 4 | word = str(input('введите слово для задания 2 варианта: '))
for i in range(len(word)):
if (i % 2 == 0) and (word[i] == 'п' or word[i] == 'о' or word[i] == 'е'):
print(word[i])
|
47e84bf4f6a9c1479c1a5ecfd96a983f3f083698 | HarrisonMc555/exercism | /python/isogram/isogram.py | 327 | 3.609375 | 4 | def is_isogram(s):
sletters = list(filter(str.isalpha, s.lower()))
return len(set(sletters)) == len(sletters)
def is_isogram_(s):
seen = set()
for c in s.lower():
if not c.isalpha():
continue
if c in seen:
return False
seen.add(c)
else:
return True
|
a391e811b9248b693273f996d670b5e45cb0c55f | HarrisonMc555/exercism | /python/allergies/test.py | 476 | 3.515625 | 4 | import unittest
from allergies import Allergies
class AllergiesTests(unittest.TestCase):
def test_allergic_to_eggs_in_addition_to_other_stuff(self):
allergies = Allergies(5)
# print('lst:', allergies.lst)
self.assertIs(allergies.is_allergic_to('eggs'), True)
self.assertIs(allergies.is_allergic_to('shellfish'), True)
self.assertIs(allergies.is_allergic_to('strawberries'), False)
if __name__ == '__main__':
unittest.main()
|
52c4f2131fa1b0380b9d3e1c6abdfac944a0e254 | HarrisonMc555/exercism | /python/bob/bob.py | 840 | 3.828125 | 4 | import string
def hey(phrase):
if is_yelling_question(phrase):
return 'Calm down, I know what I\'m doing!'
elif is_question(phrase):
return 'Sure.'
elif is_yelling(phrase):
return 'Whoa, chill out!'
elif is_saying_nothing(phrase):
return 'Fine. Be that way!'
else:
return 'Whatever.'
def is_question(phrase):
phrase = phrase.strip()
if not phrase:
return False
return phrase[-1] == '?'
def is_yelling(phrase):
phrase = phrase.strip()
if not any(letter in phrase for letter in string.ascii_letters):
return False
return not any(letter in phrase for letter in string.ascii_lowercase)
def is_yelling_question(phrase):
return is_question(phrase) and is_yelling(phrase)
def is_saying_nothing(phrase):
return not phrase.strip()
|
a62cde765969fc2327e8149a08492313436b201b | viniciusrogerio/lista_controle_2 | /4.py | 672 | 4.09375 | 4 | '''4. Faca um programa que solicite ao usuário 10 números inteiros e, ao final, informe a
quantidade de números impares e pares lidos. Calcule também a soma dos números pares e a
media dos números impares.
'''
i=1
qtdpares=0
qtdimpares=0
somapares=0
mediaimpares=0
while(True):
if i>10:
break
num=int(input(f'Digite o {i}° numero: '))
if num % 2 == 0:
qtdpares+=1
somapares+=num
else:
qtdimpares+=1
mediaimpares+=num
i+=1
mediaimpares=mediaimpares/qtdimpares
print(f'Quantidade de numeros pares: {qtdpares}')
print(f'Quantidade de numeros impares: {qtdimpares}')
print(f'Soma dos pares: {somapares}')
print(f'Media dos impares: {mediaimpares}') |
b037f4057f2ab8c9c74c1eb697b9d31b598b2565 | booler/spatial-interpolators | /spatial_interpolators/legendre.py | 3,694 | 3.578125 | 4 | #!/usr/bin/env python
u"""
legendre.py (03/2019)
Computes associated Legendre functions of degree n evaluated for each element x
n must be a scalar integer and X must contain real values ranging -1 <= x <= 1
Program is based on a Fortran program by Robert L. Parker, Scripps Institution
of Oceanography, Institute for Geophysics and Planetary Physics, UCSD. 1993.
Parallels the MATLAB legendre function
INPUTS:
l: maximum degree of Legrendre polynomials
x: elements ranging from -1 to 1 (e.g. cos(theta))
PYTHON DEPENDENCIES:
numpy: Scientific Computing Tools For Python (http://www.numpy.org)
REFERENCES:
M. Abramowitz and I.A. Stegun, "Handbook of Mathematical Functions",
Dover Publications, 1965, Ch. 8.
J. A. Jacobs, "Geomagnetism", Academic Press, 1987, Ch.4.
UPDATE HISTORY:
Updated 03/2019: calculate twocot separately to avoid divide warning
Written 08/2016
"""
import numpy as np
def legendre(n,x):
#-- Convert x to a single row vector
x = np.squeeze(x).flatten()
#-- for the n = 0 case
if (n == 0):
Pl = np.ones((1,len(x)), dtype=np.float)
return Pl
#-- for all other degrees
rootn = np.sqrt(np.arange(0,2*n+1))#-- +1 to include 2*n
s = np.sqrt(1 - x**2)
P = np.zeros((n+3,len(x)), dtype=np.float)
#-- Find values of x,s for which there will be underflow
sn = (-s)**n
tol = np.sqrt(np.finfo(np.float).tiny)
count = np.count_nonzero((s > 0) & (np.abs(sn) <= tol))
if (count > 0):
ind, = np.nonzero((s > 0) & (np.abs(sn) <= tol))
#-- Approx solution of x*ln(x) = Pl
v = 9.2 - np.log(tol)/(n*s[ind])
w = 1.0/np.log(v)
m1 = 1+n*s[ind]*v*w*(1.0058+ w*(3.819 - w*12.173))
m1 = np.min([n, np.floor(m1)]).astype(np.int)
#-- Column-by-column recursion
for k,mm1 in enumerate(m1):
col = ind[k]
#-- Calculate twocot for underflow case
twocot = -2.0*x[col]/s[col]
P[mm1-1:n+1,col] = 0.0
#-- Start recursion with proper sign
tstart = np.finfo(np.float).eps
P[mm1-1,col] = np.sign(np.fmod(mm1,2)-0.5)*tstart
if (x[col] < 0):
P[mm1-1,col] = np.sign(np.fmod(n+1,2)-0.5)*tstart
#-- Recur from m1 to m = 0, accumulating normalizing factor.
sumsq = tol.copy()
for m in range(mm1-2,-1,-1):
P[m,col] = ((m+1)*twocot*P[m+1,col] - \
rootn[n+m+2]*rootn[n-m-1]*P[m+2,col]) / \
(rootn[n+m+1]*rootn[n-m])
sumsq += P[m,col]**2
#-- calculate scale
scale = 1.0/np.sqrt(2.0*sumsq - P[0,col]**2)
P[0:mm1+1,col] = scale*P[0:mm1+1,col]
#-- Find the values of x,s for which there is no underflow, and (x != +/-1)
count = np.count_nonzero((x != 1) & (np.abs(sn) >= tol))
if (count > 0):
nind, = np.nonzero((x != 1) & (np.abs(sn) >= tol))
#-- Calculate twocot for normal case
twocot = -2.0*x[nind]/s[nind]
#-- Produce normalization constant for the m = n function
d = np.arange(2,2*n+2,2)
c = np.prod(1.0 - 1.0/d)
#-- Use sn = (-s)**n (written above) to write the m = n function
P[n,nind] = np.sqrt(c)*sn[nind]
P[n-1,nind] = P[n,nind]*twocot*n/rootn[-1]
#-- Recur downwards to m = 0
for m in range(n-2,-1,-1):
P[m,nind] = (P[m+1,nind]*twocot*(m+1) - \
P[m+2,nind]*rootn[n+m+2]*rootn[n-m-1])/(rootn[n+m+1]*rootn[n-m])
#-- calculate Pl from P
Pl = P[0:n+1,:]
#-- Polar argument (x == +/-1)
count = np.count_nonzero(s == 0)
if (count > 0):
s0, = np.nonzero(s == 0)
Pl[0,s0] = x[s0]**n
#-- Calculate the unnormalized Legendre functions by multiplying each row
#-- by: sqrt((n+m)!/(n-m)!) = sqrt(prod(n-m+1:n+m))
#-- following Abramowitz and Stegun
for m in range(1,n):
Pl[m,:] = np.prod(rootn[n-m+1:n+m+1])*Pl[m,:]
#-- Last row (m = n) must be done separately to handle 0!
#-- NOTE: the coefficient for (m = n) overflows for n>150
Pl[n,:] = np.prod(rootn[1:])*Pl[n,:]
return Pl
|
7972dcd1ccb20497b56dde4ee725bb1e833b43c8 | xuhyang/practice | /solution/heap.py | 596 | 3.625 | 4 | class Heap:
def heapify(self, nums):
# (len(nums) - 1) // 2 or len(nums) // 2 or len(nums) // 2 - 1 all okay
for i in range(len(nums) // 2, -1, -1):
self.siftDown(nums, i)
def siftDown(self, nums, i):
#check if left child will be out of index, not i < len(nums)
while i * 2 + 1 < len(nums):
son = i * 2 + 1
if son + 1 < len(nums) and nums[son + 1] < nums[son]:
son += 1
if nums[i] <= nums[son]:
break
nums[i], nums[son] = nums[son], nums[i]
i = son
|
009209f32d917829d0a5ee111fdc3cbc8cddaec3 | ruthraprabhu89/Hiku-tester | /hiker1.py | 1,143 | 4 | 4 | class hiker:
def haiku(self,line):
print("line{}".format(line))
lines = line.split('/')
print("no of lines {}".format (len(lines)))
if not len(lines)<3:
raise ValueError('Haiku should contain three lines. No of lines found:{}'.format(len(lines)))
return
syl = [0,0,0]
for i in range(len(lines)):
words = lines[i].split()
print("line no {}: no of words {}".format (i, len(words)))
for j in range(len(words)):
#print("word no {}.{}".format (j,words[j]))
is_vow = False
cur_word = words[j]
for k in range(len(cur_word)):
letter = cur_word[k]
if letter in ('a','e','i','o','u','y'):
if not is_vow == True:
syl[i] += 1
is_vow = True
else:
is_vow = False
print("no of syllable: {}".format(syl[i]))
if (syl[0] == 5 and syl[1] == 7 and syl[2] == 5):
result = 'Yes'
else:
result = 'No'
print("{}/{}/{},{}".format(syl[0],syl[1],syl[2],result))
if __name__ == "__main__":
filepath = 'test.txt'
with open(filepath) as fp:
for cnt,line in enumerate(fp):
haiku(line)
|
a5de4f9c3abf4ce25c5353680f63d4d2bed21a63 | Crazyinfo/Python-learn | /basis/错误、调试和测试/调试.py | 1,426 | 4.0625 | 4 | # 第一种方法将错误打印出来,用print()
# 第二种方法,凡是用print()来辅助查看的地方,都可以用断言(assert)来替代
def foo(s):
n = int(s)
assert n != 0,'n is zero' # ssert的意思是,表达式n != 0应该是True,否则,根据程序运行的逻辑,后面的代码肯定会出错。
return 10 / n
def main():
foo('0')
if __name__ == '__main__':
main()
# 第三种方法,把print()替换为logging是第3种方式,和assert比,logging不会抛出错误,而且可以输出到文件。
import logging
x = '0'
y = int(x)
logging.info('y = %d' % y)
print(10 / y)
import logging
logging.basicConfig(level=logging.INFO)
# logging的好处,它允许你指定记录信息的级别,有debug,info,warning,error等几个级别,
# 当我们指定level=INFO时,logging.debug就不起作用了。
# 第四种方法是启动Python的调试器pdb,让程序以单步方式运行,可以随时查看运行状态。
# pdb.set_trace()
# 这个方法也是用pdb,但是不需要单步执行,我们只需要import pdb,然后,在可能出错的地方放一个pdb.set_trace(),就可以设置一个断点
import pdb
k = '0'
g = int(k)
pdb.set_trace() # 运行到这里会自动暂停
print(10 / g)
# 运行代码,程序会自动在pdb.set_trace()暂停并进入pdb调试环境,可以用命令p查看变量,或者用命令c继续运行 |
aeb8f28c7c87fcf9df9f60e1a0b65786b9910beb | Crazyinfo/Python-learn | /basis/基础/偏函数.py | 766 | 4.3125 | 4 | print(int('12345'))
print(int('12345',base = 8)) # int()中还有一个参数base,默认为10,可以做进制转换
def int2(x,base=2):
return int(x,base) # 定义一个方便转化大量二进制的函数
print(int2('11011'))
# functools.partial就是帮助我们创建一个偏函数的,不需要我们自己定义int2(),可以直接使用下面的代码创建一个新的函数int3:
import functools
int3 = functools.partial(int , base = 2) # 固定了int()函数的关键字参数base
print(int3('11000111'))
# functools.partial的作用就是,把一个函数的某些参数给固定住(也就是设置默认值),返回一个新的函数,调用这个新函数会更简单。
print(int3('110101',base = 8)) # base = 2可以重新定义 |
e1fefe2ea38f94fda67111e127d82109902e2dea | Crazyinfo/Python-learn | /try/习题/珊.py | 744 | 4 | 4 | '''
# 第二题
class Time():
def __init__(self,hour,minute,second):
self.hour = hour
self.minute = minute
self.second = second
# 第三题
class Date():
def __init__(self,year,month,day):
self.year = year
self.month = month
self.day = day
# 第四题
class Datetime(Date,Time):
pass
'''
'''
# 第五题
class Time():
def __str__(self):
pass
class Date():
def __str__(self):
pass
class Datetime(Date,Time):
pass
print(Time,Date,Datetime)
'''
# 第六题
class Time():
def __str__(self):
pass
class Date():
def __str__(self):
pass
class Datetime(Date,Time):
def Date(self):
pass
def Time(self):
pass
|
4a993902e7e1412bce1c4edffbf397a426a400eb | Crazyinfo/Python-learn | /basis/基础/dict.py | 194 | 3.96875 | 4 | m = {5 : 1, 9 : 2, 4: 3}
if 1 in m:
print('Yes')
else:
print('No')
if 5 in m:
print('Yes')
else:
print('No')
m[8] = 4
if 8 in m:
print(m.items())
else:
print('No')
|
5199e375852e970c925414edd8f6ceea3be216d8 | Crazyinfo/Python-learn | /basis/高级特性/迭代.py | 330 | 3.921875 | 4 | d = {'a': 1,'b': 2,'c': 2}
for m in d:
print(m)
for n in d.values():
print(n)
for x,y in d.items():
print(x,y)
from collections import Iterable
h = isinstance(1233,Iterable) #判断一个对象是否可以迭代
print(h)
for m,n in enumerate([1,2,3,4]):
print(m,n)
for x,y in [(1,2),(3,4),(5,6)]:
print(x,y) |
9e0314bd94c25a0a1b012545cb2047d796a949b1 | true-false-try/Python | /A_Byte_of_Python/lambda_/natural_number.py | 1,551 | 4.21875 | 4 | """
Дано натуральне число n та послідовність натуральних чисел a1, a2,
…, an. Показати всі елементи послідовності, які є
а) повними квадратами;
б) степенями п’ятірки;
в) простими числами.
Визначити відповідні функції для перевірки, чи є число: повним квадратом,
степенню п’ятірки, простим числом.
"""
import random as rn
n = int(input('Write one number for create a length list:'))
lst_step = [rn.randint(1, 11) for i in range(1, n + 1)]
square_number = list(filter(lambda x: (x ** 0.5).is_integer() == True, lst_step))
fifth_power = list(filter(lambda x: (x ** 0.2).is_integer() == True, lst_step))
# this function shows simple numbers
def simple_number():
lst_simple = []
count = 0
for i in range(len(lst_step)):
for j in range(2, lst_step[i] + 1):
if lst_step[i] % j == 0:
count += 1
if count == 1:
lst_simple.append(lst_step[i])
else:
count = 0
continue
count = 0
return lst_simple
print('This is list with random numbers:', lst_step, sep='\n')
print('This is a list of square numbers:', square_number, sep='\n')
print('This is a list of fifth power numbers:', fifth_power, sep='\n')
print('This is a list of simple numbers:', simple_number(), sep='\n')
|
65ed9bd112ebeab025d2f9c3bb6177bdab0f050d | true-false-try/Python | /A_Byte_of_Python/OOP/inheritance/passanger/main.py | 1,869 | 3.671875 | 4 | from random import randint
class Person:
def __init__(self):
self.name = None
self.byear = None
def input(self):
self.name = input('Прізвище: ')
self.byear = input('Рік народження: ')
def print(self):
print(self.name, self.byear, end=' ')
class Passanger(Person):
def __init__(self):
Person.__init__(self)
self.departure_city = None
self.arrival_city = None
self.list_person = []
self.total_list_person = []
def input(self):
Person.input(self)
self.departure_city = input('Місто з якого ви прямуєте: ')
self.arrival_city = input('Місто куди ви прямуєте: ')
# noinspection PyAttributeOutsideInit
self.distance = randint(100, 2001)
self.list_person.extend((self.departure_city, self.arrival_city, self.distance))
def print(self):
print(self.name, self.byear, self.departure_city, self.arrival_city, self.distance)
def price(self):
price_1_km = 0.5
for i in range(len(self.list_person)):
if i == 2:
price_ticket = round((self.list_person[i] * price_1_km), 2)
self.total_list_person.extend([self.name, self.byear, self.departure_city,
self.arrival_city, self.distance, price_ticket])
print('Price is:', price_ticket)
self.list_person.clear()
if __name__ == '__main__':
n = int(input('Введіть скільки пасажірів будуть їхати: '))
for i in range(n):
p = Passanger()
p.input()
p.print()
p.price()
print('List all passanger: ', p.total_list_person, sep='\n')
|
1bc85861d977bb4312e0ff8ed5de02265ad9eb95 | true-false-try/Python | /A_Byte_of_Python/set_()/find_char.py | 1,406 | 3.96875 | 4 | """
Дано рядок з малих латинських літер.
Надрукувати:
a) перші входження літер до рядка, зберігаючи початковий взаємний порядок;
b) всі літери,що входять до рядка не менше двох раз в порядку збіьшення (a - z);
c) всі літери, що входять до рядка по одному разу
"""
string = 'abc abs sda faj'
words = string.split()
together = ''.join(words)
list_couple, list_one, list_first_letter = [], [], []
# a)
def first_letter():
for i in together:
for j in range(97, 123):
if chr(j) == i and i not in list_first_letter:
list_first_letter.append(chr(j))
return list_first_letter
# b) and c)
def couple_and_one():
for i in range(97, 123):
count = 0
for j in together:
if chr(i) == j:
count += 1
if count >= 2:
list_couple.append(chr(i))
if count == 1:
list_one.append(chr(i))
return 'Letters that occur at least 2 times:', \
sorted(list(set(list_couple))), \
'Letters that occur once:', list_one
print('The first occurrence of letters in a line:', first_letter(), sep='\n')
print(*couple_and_one(), sep='\n')
|
19cf04b25a91f1e0ccfe8023cc925cba97bb31dd | true-false-try/Python | /A_Byte_of_Python/file_/file_tasks/real_number/main.py | 1,520 | 3.5625 | 4 | file = open('file_numbers.txt', 'r')
x = [i.rstrip() for i in file]
string = ' '.join(x)
lst = string.split()
convert = [int(i) for i in lst]
# a)
def total():
global lst
return sum([int(i) for i in lst])
# b)
def minus():
global convert
return sum([1 for i in convert if i < 0])
# c)
def last_numb():
global convert
return convert[len(convert) - 1]
# d)
def max_numb():
global convert
return max(convert)
# e)
def min_couple_numb():
global convert
return min([i for i in convert if i > 9])
# f)
def sum_min_max_numb():
global convert
return min([i for i in convert]) + max(i for i in convert if i)
# j)
def first_last():
global convert
return convert[0] - convert[len(convert) - 1]
# h)
def middle_aref():
global convert
return sum([1 for i in convert if i < round(total() / (len(convert) + 1))])
print('sum file:',
total(), sep='\n')
print('count minus:',
minus(), sep='\n')
print('last number:',
last_numb(), sep='\n')
print('max number:',
max_numb(), sep='\n')
print('min couple number:',
min_couple_numb(), sep='\n')
print('min - max:',
sum_min_max_numb(), sep='\n')
print('degree first numb and last numb:',
first_last(), sep='\n')
print('the number of components of a file that are less than the arithmetic mean of all its components:',
middle_aref(), sep='\n')
file.close()
|
6d4671b842d2780d0a28998d856e9663129e0d6f | true-false-try/Python | /A_Byte_of_Python/dictionary_()/dictionary_tasks/car.py | 2,137 | 4.03125 | 4 | """
Відомості про автомобіль складаються з його марки, унікального
номера і прізвища власника. Дано словник, який містить відомості про
декілька автомобілей. Скласти процедури знаходження
a) прізвищ власниківі номерів автомобілей даної марки;
b) кількості автомобілей кожної марки.
"""
cars_dictionary = {'AA3321BE': ['Volvo', 'Solopov'], 'AR33921IO': ['Volvo', 'Korney'],
'AO3312LP': ['Porsche', 'Alehiienko'], 'KA3330II': ['Porsche', 'Dunar'],
'LS3345NP': ['BMW', 'Korney'], 'LM3241PO': ['Mercedes', 'Solopov'],
'LO2234IO': ['Volvo', 'Lopkin'], 'AK4657VS': ['Toyota', 'Volohina'],
'AM33893BI': ['Volga', 'Anroniana'], 'AL4532LO': ['Honda', 'Kanoval']}
# a) this function find last name and number car from input values call car
def find_by_brand():
car_brands = str(input('Enter valid values about brand car: ').lower())
found_car = [(key, value[1]) for key, value in cars_dictionary.items() if value[0].lower() == car_brands]
if any(found_car):
print("I'm finding:", sep='\n')
return found_car
else:
return 'Have not found this brand'
print(find_by_brand(), sep=', ')
print()
# b) this function count how many cars each brand
def count_car():
lst_brands = [cars_dictionary[i][0] for i in cars_dictionary]
lst_all_brands = list(set([cars_dictionary[i][0] for i in cars_dictionary]))
count = [(i, lst_brands.count(i)) for i in lst_all_brands]
n = str(input('Enter "count" if do you want count all brand cars in the dictionary, or "no" if you do not:'))
while n != 'count' or n != 'no':
if 'count' == n.lower():
return count
elif 'no' == n.lower():
return 'End'
else:
n = str(input('Enter correct answer please:'))
print(*count_car(), sep='\n')
|
ee3c93fb3f3b9307aad80df30ca8b2a66007f551 | priiperes/IntroPython | /Aula1.py | 3,357 | 4.0625 | 4 |
#Aula 1
#exercío 1
print('Exercício 1')
print('Se você fizer uma corrida de 10 quilômetros em 43 minutos e 30 segundos, qual será seu tempo médio por milha?')
km=10
milha = km/1.61
tempo=43*60+30
hora= tempo/3600
resultado = hora/milha
print('resultado =',resultado,'h/milha')
print('\n')
print('Qual é a sua velocidade média em milhas por hora?')
velocidade = 1/resultado
print('velocidade =',velocidade,'milha/h')
print('\n')
print('\n')
#exercicio 2
print('Exercício 2')
print('Desde sua varanda você escuta o som do primeiro fogo artificial do reveillon 3 segundos depois de ver a luz, qual a distância?')
#Calcalamos primeiro a distância que os fogos de artificios estão localizados pelo tempo que o som chega
print('\n')
Vsom=343
Vluz=3*10**8
tempo=3
distancia = Vsom*tempo
print('Distancia =', distancia, 'm')
#Agora calculamos o tempo que a luz demora para chegar, baseado na distancia encontrada acima
print('\n')
TempoDaLuz=distancia/Vluz
print('Tempo da Luz =', TempoDaLuz, 's')
print('\n')
print('\n')
#exercicio 3
print('Exercício 3')
print('Ache os zeros da função: y= 3x^2 - 4x -10')
#Para realizar esse calculo, definimos as contantes a, b e c para realizar a formula de baskara
a=3
b=-4
c=-10
#Calculamos Delta
Delta=b*b-(4*a*c)
print('\n')
print('Delta =',Delta)
print('\n')
#calculo das raizes
x1=float((-b + (Delta)**(1/2))/(2*a))
x2=(-b - (Delta)**(1/2))/(2*a)
print('Raiz 1 =',x1)
print('Raiz 2 =',x2)
print('\n')
print('confirmando as raizes encontradas')
print('\n')
y1=a*x1**2+b*x1+c
print('y1= ',y1)
y2=a*x2**2+b*x2+c
print('y2= ',y2)
print('como são proximos de 0, o resultado é compatível')
print('\n')
print('\n')
#exercicio 4
print('Exercício 4')
print('Se, ao meio dia, a sombra de um poste de 5 m de altura tem apenas 50 cm de comprimento no chão, qual o ângulo zenital do sol?')
#O ângulo formado é calculado pelo arcotangente
a=0.5
b=5
AnguloTheta = b/a
print('Angulo Azimute =', AnguloTheta)
print('\n')
print('\n')
#exercicio 5
print('Exercício 5')
print('calcule o seu IMC = M/A^2 (com a massa em Kg e a altura em metros).\n Um valor saudável estara --em geral-- entre 20-25. \n Um bebê de 6 meses gorducho tem 70 cm de comprimento e 11 kg de massa,\n qual o IMC dele?')
#Calculo de Priscyla Peres
M=51
A=1.71
IMC=M/A**A
print('\n')
print('IMC de Priscyla Peres')
print('\n')
print('IMC=', IMC)
print('Como o valor precisa estar entre 20 e 25, o seu IMC está bom e é uma pessoa saudável')
print('\n')
print('IMC do bebê gorducho')
M=11
A=0.7
IMCG=M/A**A
print('IMCG= ', IMCG)
print('\n')
print('\n')
#exercicio
print('Exercício 6')
print('Calcule a velocidade final de um objeto em queda livre a partir de 3 metros de altura \n (sem resistencia do ar). Calcule o tempo que esse objeto demora para cair. \n')
print('Vamos calcular a velocidade final pela equação de Torrichelli independente do tempo \n')
print('Vf^2=V0^2 + 2gd, onde d é a distância e assumimos que g está no sentindo positivo da direção de propagação da particula e V0^2=0\n')
V=0
g=9.8
d=3
Vf=(V**V + 2*g*d)**(1/2)
print('Vf=', Vf, 'm/s \n')
print('Usando a formula, Vf=V0+gt \n')
t=Vf/g
print('t=', t, 's') |
64d01a920fcf73ad8e0e2f55d894029593dc559d | zitorelova/python-classes | /competition-questions/2012/J1-2012.py | 971 | 4.34375 | 4 | # Input Specification
# The user will be prompted to enter two integers. First, the user will be prompted to enter the speed
# limit. Second, the user will be prompted to enter the recorded speed of the car.
# Output Specification
# If the driver is not speeding, the output should be:
# Congratulations, you are within the speed limit!
# If the driver is speeding, the output should be:
# You are speeding and your fine is $F .
# where F is the amount of the fine as described in the table above.
'''
1 to 20 -> 100
21 to 30 -> 270
31 and above -> 500
'''
speed_limit = int(input('Enter the speed limit: '))
speed = int(input('Enter the recorded speed of the car: '))
if speed <= speed_limit:
print('Congratulations, you are within the speed limit!')
else:
if speed - speed_limit <= 20:
fine = 100
elif speed - speed_limit <= 30:
fine = 270
else:
fine = 500
print('You are speeding and your fine is $' + str(fine) + '.')
|
0a58f6868af57dcba6babf48ed32c1a31f8350eb | zitorelova/python-classes | /competition-questions/2017/S2-2017.py | 1,287 | 3.890625 | 4 | """
Input Specification
The first line contains the integer N (1 ≤ N ≤ 100). The next line contains N distinct space-
separated positive integers, where each integer is at most 1 000 000.
Output Specification
Output the N integers in the unique order that Joe originally took the measurements.
Sample Input
8
10 50 40 7 3 110 90 2
Output for Sample Input
10 40 7 50 3 90 2 110
• He started measuring water levels at a low tide, his second measurement was of the water
level at high tide, and after that the measurements continued to alternate between low and
high tides.
• All high tide measurements were higher than all low tide measurements.
• Joe noticed that as time passed, the high tides only became higher and the low tides only
became lower.
"""
N = int(input())
m = [int(x) for x in input().split()]
m.sort()
# # After sorting
# # [2, 3, 7, 10, 40, 50, 90, 110]
if N % 2 == 0:
middle = int(N/2)
else:
middle = int((N+1)/2)
lows = m[:middle][::-1]
highs = m[middle:]
answer = []
for i in range(middle):
try:
answer.append(str(lows[i]))
except:
pass
try:
answer.append(str(highs[i]))
except:
pass
print(' '.join(answer))
# # l = [10, 40, 7, 50, 3, 90, 2, 110]
# # print(l[::-1])
# l = [1, 2, 3, 4, 5] |
b43877784392fe97c441f2998172bd7765d8d1ff | zitorelova/python-classes | /competition-questions/2010/S2-2010.py | 1,893 | 3.53125 | 4 | # Input Specification
# The first line of input will be an integer k (1 ≤ k ≤ 20), representing the number of characters and
# associated codes. The next k lines each contain a single character, followed by a space, followed
# by the binary sequence (of length at most 10) representing the associated code of that character.
# You may assume that the character is an alphabet character (i.e., ‘a’...‘z’ and ‘A’..‘Z’). You may
# assume that the sequence of binary codes has the prefix-free property. On the k + 2nd line is the
# binary sequence which is to be decoded. You may assume the binary sequence contains codes
# associated with the given characters, and that the k + 2nd line contains no more than 250 binary
# digits.
# Output Specification
# On one line, output the characters that correspond to the given binary sequence.
# Sample Input
# 5
# A 00
# B 01
# C 10
# D 110
# E 111
# 00000101111
# Output for Sample Input
# AABBE
# a = int(input())
# decoder = []
# for i in range(a):
# decoder.append(input().split())
# huffmancode = (input())
# huffmancode = [char for char in huffmancode]
# decoded = []
# end = 1
# while len(huffmancode) > 0:
# substr = huffmancode[:end]
# substr = ''.join(substr)
# for i in decoder:
# if substr == i[1]:
# decoded.append(i[0])
# huffmancode = huffmancode[end:]
# end = 0
# end += 1
# print(decoded)
# for i in range(len(decoder)):
k = int(input())
huffman_dict = {}
for i in range(k):
letter = input().split()
huffman_dict[letter[1]] = letter[0]
huffman_code = input()
huffman_decoded = ''
end = 1
while len(huffman_code) > 0:
substr = huffman_code[:end]
if substr in huffman_dict:
huffman_decoded += huffman_dict[substr]
huffman_code = huffman_code[end:]
end = 0
end += 1
print(huffman_decoded)
|
a6a74f456b6c6b484e577de6aefdd5a6e6a4b799 | zitorelova/python-classes | /J1-2020.py | 559 | 3.75 | 4 | """
Input Specification
There are three lines of input. Each line contains a non-negative integer less than 10. The first line
contains the number of small treats, S, the second line contains the number of medium treats, M ,
and the third line contains the number of large treats, L, that Barley receives in a day.
Output Specification
If Barley’s happiness score is 10 or greater, output happy. Otherwise, output sad.
"""
S = int(input())
M = int(input())
L = int(input())
happy = (1*S) + (2*M) + (3*L)
if happy >= 10: print("happy")
else: print("sad") |
6bfea6232f02b525708f2c88cb7a3ad64cb6b13b | Halfkeyboard567/M_mathews_84706_project01_Paint.py | /Paint_C.py | 6,833 | 3.640625 | 4 | #Part C
from graphics import *
class Shape:
def __init__(self, win):
self.win = win
def line(self):
T1 = Text(Point(400, 50), "Line: Enter 2 points")
T1.setSize(8)
T1.draw(self.win)
p1 = self.win.getMouse()
p1.draw(self.win)
p2 = self.win.getMouse()
p2.draw(self.win)
l = Line(p1, p2)
l.draw(self.win)
T1.undraw()
p1.undraw()
p2.undraw()
T2 = Text(Point(400, 50), "Line: Color Line(A-J), u to undo, and q to break")
T2.setSize(8)
T2.draw(self.win)
while True:
k = self.win.checkKey()
if k == "q":
break
elif k == "u":
l.undraw()
break
elif k:
ColorO(k, l)
T2.undraw()
def rectangle(self):
T1 = Text(Point(400, 50), "Rectangle: Enter 2 points")
T1.setSize(8)
T1.draw(self.win)
p1 = self.win.getMouse()
p1.draw(self.win)
p2 = self.win.getMouse()
p2.draw(self.win)
r = Rectangle(p1, p2)
r.draw(self.win)
T1.undraw()
p1.undraw()
p2.undraw()
T2 = Text(Point(400, 50), "Rectangle: Color Shape(0-9), Color Line(A-J), u to undo, and q to break")
T2.setSize(8)
T2.draw(self.win)
while True:
k = self.win.checkKey()
if k == "q":
break
elif k == "u":
r.undraw()
break
elif k:
ColorS(k, r)
ColorO(k, r)
T2.undraw()
def circle(self):
T1 = Text(Point(400, 50), "Circle: Enter point")
T1.setSize(8)
T1.draw(self.win)
p1 = self.win.getMouse()
c = Circle(p1, 50)
c.draw(self.win)
T1.undraw()
T2 = Text(Point(400, 50), "Circle:Color Shape(0-9), Color Line(A-J), u to undo, and q to break")
T2.setSize(8)
T2.draw(self.win)
while True:
k = self.win.checkKey()
if k == "q":
break
elif k == "u":
c.undraw()
elif k:
ColorS(k, c)
ColorO(k, c)
T2.undraw()
def oval(self):
T1 = Text(Point(400, 50), "Oval: Enter 2 points")
T1.setSize(8)
T1.draw(self.win)
p1 = self.win.getMouse()
p2 = self.win.getMouse()
p1.draw(self.win)
p2.draw(self.win)
O = Oval(p1, p2)
O.draw(self.win)
T1.undraw()
p1.undraw()
p2.undraw()
T2 = Text(Point(400, 50), "Oval: Color Shape(0-9), Color Line(A-J), u to undo, and q to break")
T2.setSize(8)
T2.draw(self.win)
while True:
k = self.win.checkKey()
if k == "q":
break
elif k == "u":
c.undraw()
elif k:
ColorS(k, O)
ColorO(k, O)
T2.undraw()
def triangle(self):
T1 = Text(Point(400, 50), "Triangle: Enter 3 points")
T1.setSize(8)
T1.draw(self.win)
p1 = self.win.getMouse()
p1.draw(self.win)
p2 = self.win.getMouse()
p2.draw(self.win)
p3 = self.win.getMouse()
p3.draw(self.win)
t = Polygon(p1, p2, p3)
t.draw(self.win)
T1.undraw()
p1.undraw()
p2.undraw()
p3.undraw()
T2 = Text(Point(400, 50), "Triangle: Color Shape(0-9), Color Line(A-J), u to undo, and q to break")
T2.setSize(8)
T2.draw(self.win)
while True:
k = self.win.checkKey()
if k == "q":
break
elif k == "u":
t.undraw()
elif k:
ColorS(k, t)
ColorO(k, t)
T2.undraw()
def ColorS(C, win):
if C == "0":
win.setFill("white")
elif C == "1":
win.setFill("black")
elif C == "2":
win.setFill("red")
elif C == "3":
win.setFill("blue")
elif C == "4":
win.setFill("yellow")
elif C == "5":
win.setFill("green")
elif C == "6":
win.setFill("orange")
elif C == "7":
win.setFill("purple")
elif C == "8":
win.setFill("pink")
elif C == "9":
win.setFill("gray")
def ColorO(C, win):
if C == "A":
win.setOutline("white")
elif C == "B":
win.setOutline("black")
elif C == "C":
win.setOutline("red")
elif C == "D":
win.setOutline("blue")
elif C == "E":
win.setOutline("yellow")
elif C == "F":
win.setOutline("green")
elif C == "G":
win.setOutline("orange")
elif C == "H":
win.setOutline("purple")
elif C == "I":
win.setOutline("pink")
elif C == "J":
win.setOutline("gray")
def Color(C, win):
if C == "A":
win.setBackground("white")
elif C == "B":
win.setBackground("black")
elif C == "C":
win.setBackground("red")
elif C == "D":
win.setBackground("blue")
elif C == "E":
win.setBackground("yellow")
elif C == "F":
win.setBackground("green")
elif C == "G":
win.setBackground("orange")
elif C == "H":
win.setBackground("purple")
elif C == "I":
win.setBackground("pink")
elif C == "J":
win.setBackground("gray")
def TextS(pt, win):
entry = Entry(pt, 10)
entry.draw(win)
# Go modal: wait until user types Return or Escape Key
while True:
key = win.getKey()
if key == "Return":
break
# undraw the entry and draw Text
entry.undraw()
Text(pt, entry.getText()).draw(win)
win.checkMouse()
def main():
win = GraphWin('Paint', 800, 800)
T1 = Text(Point(400, 25), "keys: l - line, r - rectangle, c - circle, o - oval, t - triangle, q - quit")
T1.setSize(8)
T1.draw(win)
S = Shape(win)
while True:
key = win.checkKey()
if key == "q": # loop exit
break
elif key == "l":
S.line()
elif key == "r":
S.rectangle()
elif key == "c":
S.circle()
elif key == "o":
S.oval()
elif key == "t" :
S.triangle()
elif key:
Color(key, win)
pt = win.checkMouse()
if pt:
TextS(pt, win)
win.close()
if __name__ == '__main__': main()
|
84674ce996ed3ae5e0b13032b05c2803ab6508cd | naveenshukla/OpenQA | /question_processing/question_phrases.py | 326 | 3.875 | 4 | #!/usr/bin/python3 -tt
question_words = ['who','why','where','what','when','how','which','whose','whom', '?', '.', ':', ';', '"', '\'']
def remove(text):
text = text.lower().strip()
if text in question_words:
text = ''
return text
def main():
print(remove(input()))
if __name__ == '__main__':
main()
|
cbbcbf765114f341b973c55c30490ed8984f98bf | zyq507/Pythoncore | /Dict_Test.py | 1,248 | 3.65625 | 4 | phonebook = {'Alice':'2341','Beth':'9102','Cecil':'3258'}
items = [('name','FCK'),('age','21')]
d =dict(items)
print(d)
print(d['name'])#其中的key相当于索引
print(len(d))
print('age' in d)
d['job'] = 'worker'
print(d)
del d['job']
print(d)
k = 'my name is %(name)s, I\'m %(age)s years old'% d
print(k)#字典的key可以做为%s的说明符
x = {'key':'value'}
y = x
x.clear()
print(y)#clear方法会清空x关联的存储空间,y也映射到此存储空间,故亦空
#copy和deepcopy
aa = {'username':'admin','machines':['foo','bar','baz']}
bb = aa.copy()#shallow copy
bb['username'] = 'mlh'
bb['machines'].remove('bar')#原地修改浅复制的内容,原文也会改变
print(aa,'\n',bb)
#使用deepcopy可以解决问题
print({}.fromkeys(['a', 'bb']))#参数是一个list
print(dict.fromkeys(['f','g'],'Hello'))#可以添加一个缺省的参数
print(d.get('name'))#无key时,不会报错
print(d.get('job','N/A'))#可以添加一个参数来赋予缺省值的返回
print(list(d.items()))
print(list(d.keys()))
aaa = {}
aaa.setdefault('name','N/A')#setdefault可以在没有该key时设定默认值
print(aaa)#也可以同get方法在存在该key时获得该值
aaa['name'] = 'Boy'
print(aaa.setdefault('name','N/A'))
|
c7f4cc528ed6497a05e435e7ef3f5ee47e5b3dfc | dechevh/SoftwareUniversity | /Python-Fundamentals/softUni_reception.py | 405 | 3.71875 | 4 | efficiency_one = int(input())
efficiency_two = int(input())
efficiency_three = int(input())
students_count = int(input())
all_employees_per_hour = efficiency_one + efficiency_two + efficiency_three
time_needed = 0
while students_count > 0:
time_needed += 1
if time_needed % 4 == 0:
pass
else:
students_count -= all_employees_per_hour
print(f"Time needed: {time_needed}h.")
|
e64c96b39f822ce75b5b92d0c843248903f9c0ff | University-Assignment/PythonProgramming | /2018037010_7.py | 4,088 | 4.03125 | 4 | '''
# 미션1: 연락처 관리 프로그램
menu = 0
friends = []
while menu != 9:
print("--------------------")
print("1. 친구 리스트 출력")
print("2. 친구추가")
print("3. 친구삭제")
print("4. 이름변경")
print("9. 종료")
menu = int(input("메뉴를 선택하시오: "))
if menu == 1:
print(friends)
elif menu== 2:
name = input("이름을 입력하시오: ")
friends.append(name)
elif menu == 3:
del_name = input("삭제하고 싶은 이름을 입력하시오: ")
if del_name in friends:
friends.remove(del_name)
else:
print("이름이 발견되지 않았음")
elif menu == 4:
old_name = input("변경하고 싶은 이름을 입력하시오: ")
if old_name in friends:
index = friends.index(old_name)
new_name = input("새로운 이름을 입력하시오: ")
friends[index] = new_name
else:
print("이름이 발견되지 않았음")
# 미션2: 연락처 관리 프로그램
def printOption():
print("--------------------")
print("1. 친구 리스트 출력")
print("2. 친구추가")
print("3. 친구삭제")
print("4. 이름변경")
print("9. 종료")
def printList():
global friends
print(friends)
def addFriend():
global friends
name = input("이름을 입력하시오: ")
friends.append(name)
def removeFriend():
global friends
del_name = input("삭제하고 싶은 이름을 입력하시오: ")
if del_name in friends:
friends.remove(del_name)
else:
print("이름이 발견되지 않았음")
def changeName():
global friends
old_name = input("변경하고 싶은 이름을 입력하시오: ")
if old_name in friends:
index = friends.index(old_name)
new_name = input("새로운 이름을 입력하시오: ")
friends[index] = new_name
else:
print("이름이 발견되지 않았음")
menu = 0
friends = []
while menu != 9:
print("--------------------")
printOption()
menu = int(input("메뉴를 선택하시오: "))
if menu == 1:
printList()
elif menu== 2:
addFriend()
elif menu == 3:
removeFriend()
elif menu == 4:
changeName()
# 미션3: tic-tac-toe 게임
board= [[' ' for x in range (3)] for y in range(3)]
while True:
# 게임 보드를 그린다.
for r in range(3):
print(" " + board[r][0] + "| " + board[r][1] + "| " + board[r][2])
if r != 2:
print("---|---|---")
# 사용자로부터 좌표를 입력받는다.
x = int(input("다음 수의 x좌표를 입력하시오: "))
y = int(input("다음 수의 y좌표를 입력하시오: "))
# 사용자가 입력한 좌표를 검사한다.
if board[x][y] != ' ':
print("잘못된 위치입니다. ")
continue
else:
board[x][y] = 'X'
# 컴퓨터가 놓을 위치를 결정한다. 첫 번째로 발견하는 비어있는 칸에 놓는다.
done =False
for i in range(3):
for j in range(3):
if board[i][j] == ' ' and not done:
board[i][j] = 'O';
done = True
break;
# 미션4: 순차탐색 프로그램
data = []
f = open("data.txt", "r") #data가 저장된 디렉토리에서 파일을 읽는다.
# #파일에 저장된 모든 줄을 읽는다.
for line in f.readlines():
#줄바꿈 문자를 삭제한 후에 리스트에 추가한다.
data.append(line.strip())
fileName = input('검색할 파일명을 입력하시오 : ')
success = False
for name in data[0].split(','):
if name == fileName:
success = True
break
print(success)
'''
# Zoom
def selection_sort2(x):
for i in range(len(x) - 1):
x.insert(i, x.pop(x.index(min(x[i: len(x)]))))
return x
array = [180, 165, 175, 170, 160, 171, 150, 162]
selection_sort2(array)
print(array) |
c1507b325a379d1b386e4592e546ec6306ee38a1 | University-Assignment/PythonProgramming | /test.py | 833 | 3.5 | 4 | #변수 x는 원소의 수가 100개인 1차원 배열이다. 변수 x의 원소는 0에서 255까지의 정수를 랜덤하게 갖는다.
# 변수 x를 파이선의 random 모듈을 이용하여 구하시오.
import random
x = []
for i in range(100):
x.append(random.randint(0, 256))
print(x)
# a=[1, 2, 3, 2, 1, 0, -1, -2, -3, -2, -1, 0]로 정의된 벡터의 FFT 출력
import numpy as np
import matplotlib.pyplot as plt
a = [1, 2, 3, 2, 1, 0, -1, -2, -3, -2, -1, 0]
t = range(len(a))
signal = a
ori_fft = np.fft.fft(signal)
print('original fft', ori_fft)
nomal_fft = ori_fft / len(signal)
print('nomalization fft', nomal_fft)
fft_magnitude = abs(nomal_fft)
print('magnitude fft ', fft_magnitude)
plt.subplot(2, 1, 1)
plt.plot(t, signal)
plt.grid()
plt.subplot(2, 1, 2)
plt.stem(fft_magnitude)
plt.grid()
plt.show() |
5693de8003cd127a82c42b5ee8bb2985a79f045b | shreyasbapat/Astronomy-Code-Camp-Slides | /one.py | 206 | 3.921875 | 4 | def check(num):
if num <= 9:
print("Single Digit")
elif num >9 and num <=99:
print("Double Digit")
else:
print("Others")
if __name__ == "__main__":
num = int(input("Input a number:"))
check(num) |
fbe4f97912ae394e43a5d2b2928ab20297c4fcf8 | escnqh/PracticesWhenLearnPython | /math.py | 516 | 3.796875 | 4 | #在Python中,有两种除法,一种除法是/:
print(10/3)
#/除法计算结果是浮点数,即使是两个整数恰好整除,结果也是浮点数:
print(9/3)
#还有一种除法是//,称为地板除,两个整数的除法仍然是整数:
print(10 // 3)
#整数的地板除//永远是整数,即使除不尽。要做精确的除法,使用/就可以。
#因为//除法只取结果的整数部分,所以Python还提供一个余数运算,可以得到两个整数相除的余数:
print(10%3) |
e85612854387fb68172ad444981ca2590a40d1e3 | escnqh/PracticesWhenLearnPython | /formatting.py | 1,285 | 3.953125 | 4 | #格式化
#最后一个常见的问题是如何输出格式化的字符串。我们经常会输出类似'亲爱的xxx你好!你xx月的话费是xx,余额是xx'之类的字符串,而xxx的内容都是根据变量变化的,所以,需要一种简便的格式化字符串的方式。
#在Python中,采用的格式化方式和C语言是一致的,用%实现,举例如下:
print('hello,%s'%'world')
print('Hi, %s, you have $%d.' % ('Michael', 1000000))
#你可能猜到了,%运算符就是用来格式化字符串的。在字符串内部,%s表示用字符串替换,%d表示用整数替换,有几个%?占位符,后面就跟几个变量或者值,顺序要对应好。如果只有一个%?,括号可以省略。
#常见的占位符有:
# %d 整数
# %f 浮点数
# %s 字符串
# %x 十六进制整数
#其中,格式化整数和浮点数还可以指定是否补0和整数与小数的位数:
print('%2d-%02d' % (3, 1))
print('%.2f' % 3.1415926)
#如果你不太确定应该用什么,%s永远起作用,它会把任何数据类型转换为字符串:
print('Age: %s. Gender: %s' % (25, True))
#有些时候,字符串里面的%是一个普通字符怎么办?这个时候就需要转义,用%%来表示一个%:
print( 'growth rate: %d %%' % 7) |
83e3c6fb686616a919d2e28037e1e02cc97fd6cf | x64x6a/ircbot | /ircbot/standard_io.py | 831 | 3.578125 | 4 | '''
This is used to handle stdin and stdout input and output for the library
'''
import time
import sys
import threading
STDOUT_BUFFER = []
def print_stdout_buffer():
'''Continously flushes the stdout buffer'''
global STDOUT_BUFFER
try:
while 1:
if STDOUT_BUFFER:
out = STDOUT_BUFFER[0]
STDOUT_BUFFER = STDOUT_BUFFER[1:]
print >>sys.stdout, out
time.sleep(.001)
except Exception,e:
print >>sys.stderr,"Error in printing to stdout:",e
os._exit(1)
def stdout_print(string):
'''Appends given string to the print/stdout buffer.
To print a string: io.stdout_print
or
standard_io.stdout_print'''
STDOUT_BUFFER.append(string)
def start_io():
'''Starts the input/output buffer flushing'''
t = threading.Thread(target=print_stdout_buffer)
t.start()
|
497835d4aed9639a52e9b17ce039d6f7e2584cc6 | Pasquale-Silv/Bit4id_course | /Some_function/SF1_poppaLista.py | 260 | 3.515625 | 4 | def poppaLista(lista):
"""Poppa l'intera lista passata come argomento."""
for i in range(0, len(lista)):
val_poppato = lista.pop()
print(val_poppato)
print(lista)
list1 = [3, 4, 5, 8]
print(list1)
poppaLista(list1)
|
693c554c403602ca49fb6a852648c4e9547723d7 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/ThirdDay/Loop_ex1.py | 711 | 4.40625 | 4 | items = ["Python", 23, "Napoli", "Pasquale"]
for item in items:
print(item)
print()
for item in items:
print("Mi chiamo {}, vivo a {}, ho {} anni e sto imparando il linguaggio di programmazione '{}'.".format(items[-1],
items[-2],
items[-3],
items[0]))
print()
for item in items:
print("Vediamo ciclicamente cosa abbiamo nella nostra lista:", item)
|
1b6ca4e89dd7d1082eb7d9aba899748ff51c8421 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/SecondDay/es2_numParioDisp.py | 153 | 4.03125 | 4 | num = int(input("Inserisci un numero: "))
if(num % 2 == 0):
print("Il numero", num, " è pari")
else:
print("Il numero", num, " è dispari!") |
52b7ab845ddcc63afb61d533148e64e2077da353 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/TwelfthDay/LC_and_lists/ex5_cifratura.py | 2,149 | 3.859375 | 4 | # Prendi stringa e inverti caratteri della stringa. Per ogni stringa, la ribaltiamo.
# Associare un numero intero a ogni carattere della stringa e separarli con una |pipe| o altro carattere speciale.
# Per associare il numero usa la funzione ord() che restituisce l'equivalente in codice ASCII.
# pipe anche all'inizio e alla fine
import random
# Associazione di un carattere casuale per tutti gli interi generati e per il carattere che li separa.
cifratura = {
111: "ABC", # o
97: "FDS", # a
105: "PQL", # i
99: "OIM", # c
124: "ZNK", # Pipe |
32: "poi", # " "
80: "uyt", # P
115: "rew", # s
113: "qas", # q
117: "dfg", # u
108: "hjk", # l
101: "lmn" # e
}
def inverti_stringa(stringa):
return stringa[::-1]
def cifra(stringa):
stringa2 = ""
for el in stringa:
stringa2 += str(ord(el)) + "|"
return "|" + stringa2
def cifra_random(messaggioConPipe):
mess = messaggioConPipe[1:-1]
daCifrare = mess.split("|")
listaCifrata = []
for elemento in daCifrare:
elemento2 = int(elemento)
if elemento2 in cifratura:
listaCifrata.append(random.choice(cifratura[elemento2]))
return "|" + "|".join(listaCifrata) + "|"
def decifraMess(messCifrato2):
messDec = ""
for lettera in messCifrato2:
for k, v in cifratura.items():
if lettera in v:
messDec += chr(k)
messDec = messDec.replace("|", "")
messDec = inverti_stringa(messDec)
return messDec
def rimuoviPipe(stringa):
return stringa.replace("|", '')
if __name__ == "__main__":
parola = "ciao Pasquale"
parolaRev = inverti_stringa(parola)
messaggioConPipe = cifra(parolaRev)
print(messaggioConPipe)
messCifrato = cifra_random(messaggioConPipe)
print(messCifrato)
print("Messaggio cifrato:", rimuoviPipe(messCifrato))
messDecifrato = decifraMess(messCifrato)
print("Messaggio decifrato:", messDecifrato)
|
4895a53522b4957765e61b27e10239f729b2c2bb | Pasquale-Silv/Bit4id_course | /Some_function/SF9_genNumPrimiDivisa.py | 616 | 3.6875 | 4 | def isPrimo(numInt):
"Restituisce True se un numero è primo, altrimenti False."
for i in range(2, numInt):
if(numInt % i == 0):
return False
return True
def genNumPrimi2func(inizio, fine):
"Raccoglie in un generatore tutti i numeri primi compresi nel range specificato."
while(inizio <= fine):
if(isPrimo(inizio)):
yield inizio
inizio += 1
gen1 = genNumPrimi2func(23, 43)
print(gen1)
print(type(gen1))
for i in gen1:
print(i, end=" ")
print()
gen2 = genNumPrimi2func(100, 201)
for i in gen2:
print(i, end=" ")
|
35a9c81798a968e5306deb13d4587650c65c7e7d | Pasquale-Silv/Bit4id_course | /Course_Bit4id/EleventhDay/Giochi_di_parole/ClasseGiochiDiParole.py | 1,834 | 3.796875 | 4 | class GiochiDiParole():
lista_parole = ["fare", "giocare", "dormire", "fittizio", "lira", "sirena", "fulmine", "polizia", "carabinieri",
"luce", "oscuro", "siluro", "razzo", "pazzo", "sillaba", "tono", "oro", "argento", "moneta",
"panna", "zanna", "simulare", "creare", "mangiare", "rubare", "ridere"]
lista_anagramma = [list(parola) for parola in lista_parole]
def __init__(self, parola):
self.parola = parola
def isPalindroma(self):
parola = self.parola.lower()
parolaContrario = parola[::-1]
if parola == parolaContrario:
return True
else:
return False
def rimario(self):
rime = []
parola = self.parola.lower()
for elemento in self.lista_parole:
if elemento[-3:] == parola[-3:]:
rime.append(elemento)
if (not rime):
print("Non sono state trovate rime corrispondenti alla parola '{}'!".format(self.parola))
else:
print(f"Le rime corrispondenti alla parola '{parola}' sono le seguenti: {rime}")
# def anagramma(self):
# parola = list(self.parola.lower())
# anagrammi = []
# for lettera in parola:
# for
#
# print(f"La parola{self.parola} e {elemento} sono anagrammi!")
# else:
# print("Nessun anagramma!")
if __name__ == "__main__":
parola1 = GiochiDiParole("Salvare")
print(parola1.isPalindroma())
parola1.rimario()
parola2 = GiochiDiParole("AnNA")
print(parola2.isPalindroma())
parola2.rimario()
parola3 = GiochiDiParole("Scarpa")
print(parola3.isPalindroma())
parola3.rimario()
print(GiochiDiParole.lista_anagramma) |
56ce5b83d5ed2b0fb6807d22e52cc0dc9514a9d6 | Pasquale-Silv/Bit4id_course | /Some_function/SF6_factorialWithoutRec.py | 822 | 4.28125 | 4 | def factorial_WithoutRec(numInt):
"""Ritorna il fattoriale del numero inserito come argomento."""
if (numInt <= 0):
return 1
factorial = 1
while(numInt > 0):
factorial *= numInt
numInt -= 1
return factorial
factorial5 = factorial_WithoutRec(5)
print("5! =", factorial5)
factorial4 = factorial_WithoutRec(4)
print("4! =", factorial4)
factorial3 = factorial_WithoutRec(3)
print("3! =", factorial3)
while(True):
num = int(input("Inserisci il numero di cui vuoi vedere il fattoriale:\n"))
factorialNum = factorial_WithoutRec(num)
print("{}! = {}".format(num, factorialNum))
risposta = input("Desideri ripetere l'operazione?\nPremi S per confermare, qualunque altra cosa per annullare.\n").upper()
if(risposta != "S"):
break
|
878f5bb5efec177a0ae72b5a33eca20889dabb05 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/FifthDay/DictComprehension_DC.py | 107 | 3.84375 | 4 | word = 'dictionary'
letter_count = {letter:word.count(letter) for letter in word}
print(letter_count)
|
d1a68267f5fa87fcaf1726fc05579e5db9965380 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/SeventhDay/Gestione_delle_eccezioni/ecc1.py | 645 | 4 | 4 | # try
# except
# else This executes ONLY if no exception is raised
# finally Viene eseguito sempre
print("Devi dividere due numeri")
num1 = int(input("Scegli il primo numero:\n"))
num2 = int(input("Scegli il secondo numero:\n"))
try:
res = num1 / num2
print(res)
except (ZeroDivisionError):
print("Eccezione:", ZeroDivisionError, ", completamente gestita! Bravo!")
else:
print("else: Solo se va tutto bene")
finally:
print("finally sempre presente !")
print("poichè hai gestito l'eccezione il programma continua la sua esecuzione fin qui!")
print("Complimenti!")
|
c66f129442daf2ee1efacb2a1549dabcde4018c3 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/FifthDay/ifAssign.py | 334 | 3.765625 | 4 | # if ternario
età = int(input("Qual è la tua età?"))
stato = "maggiorenne" if (età >= 18) else "minorenne, vai dalla mammina"
print("Hai", età, "anni...", stato)
# ("no", "yes")[True] ------> (0, 1) nella tupla, quindi accedi al valore corrispondente a False(0) o True(1)
print("Ciao Pasquale" if(True) else "")
|
716636aa9bcd32032127d3c4be3050b98d876481 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/FourthDay/funz_alt_print.py | 574 | 3.71875 | 4 | animal = "dog"
animals = ["dog", "cat", "mouse", "horse", "turtle"]
# Sono placeholder
# %s s sta per string
# %d d sta per digit(cifra)
print("I have a %s" % animal)
print("I have a %s, a %s and a %s." % (animals[0], animals[1], animals[-1])) # Passi gli argomenti come tuple
number = 23
numbers = [23, 25, 26, 44, 33, 3.8]
print("My age is %d years old." % number)
print("My age is %d, my favourite number is %d and a float is like %f.Good luck by now." %(numbers[0], numbers[2], numbers[-1]))
# Puoi anche mischiare i vari placeholder %s, %d
|
ed1208ad2fadaa5406721bf32b38179cef46e1bf | Pasquale-Silv/Bit4id_course | /Course_Bit4id/SeventhDay/Gestione_delle_eccezioni/ecc4.py | 712 | 3.8125 | 4 | nomi = ["Pasquale", "Alfonso", "Luca"]
for nome in nomi:
print(nome)
risp = int(input("\nQuanti nomi presenti nella lista vuoi vedere?\n"))
try:
for i in range(0, risp):
print(nomi[i])
except (IndexError): # Se non specifichi nessun tipo di errore, Python catturerà tutti i tipi d'errore sollevabili(portata generale)
print("Sei andato fuori dal range degli indici della lista!")
print("Numero massimo di nomi in lista:", len(nomi))
else:
print("Qua ci arrivi solo se va tutto bene !")
finally:
print("Io sono l'onnipresente finally ! mi vedrai sempre!")
print("\nQua non ci arrivi se non gestisci tutte le possibili eccezioni verificabili!")
|
54ceb93532b9046a2474e55a4de058c4c20d4b53 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/FourthDay/ex1_List.py | 288 | 4.0625 | 4 | names = ["Pasquale", "Bruno", "Lucia", "Antonio", "Giacomo"]
while(len(names) >= 3):
print("La stanza è affollata, liberare!")
print("Via", names.pop())
if(len(names) < 3):
print("La stanza non è affollata!")
print("\nPersone in stanza:", names, ", ottimo!")
|
ceb9862e7d277490de90854f070afe9daab3d9e8 | Pasquale-Silv/Bit4id_course | /Some_function/kata2_reverseWords2.py | 301 | 3.6875 | 4 | def reverse_words(str):
newStr = []
for i in str.split(' '):
newStr.append(i[::-1])
return ' '.join(newStr)
primo = reverse_words("La vita è bella! vero?")
print(primo)
secondo = reverse_words('double spaced words') #, 'elbuod decaps sdrow')
print(secondo)
|
c32334bce0e237b3ad2dac4de7efeb73cdbfb123 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/FourthDay/ex5_SortingIntList.py | 808 | 4.5 | 4 | nums = [100, -80, 3, 8, 0]
print("Lista sulla quale effettueremo le operazioni:", nums)
print("\nOriginal order:")
for num in nums:
print(num)
print("\nIncreasing order::")
for num in sorted(nums):
print(num)
print("\nOriginal order:")
for num in nums:
print(num)
print("\nDecreasing order:")
for num in sorted(nums,reverse=True):
print(num)
print("\nOriginal order:")
for num in nums:
print(num)
print("\nReverse-positional order:")
nums.reverse()
for num in nums:
print(num)
nums.reverse()
print("\nOriginal order:")
for num in nums:
print(num)
print("\nPermanent increasing order:")
nums.sort()
for num in nums:
print(num)
print("\nPermanent decreasing order:")
nums.sort(reverse=True)
for num in nums:
print(num)
|
1215b573ac6647498439014f1d3b6062d0966c7c | Pasquale-Silv/Bit4id_course | /Course_Bit4id/TenthDay/OOP7.py | 1,237 | 3.5 | 4 | class Gatto():
tipo="felino" # Variabile/Attributo di classe
def __init__(self, nome, anni, fidanzato=False, padrone=None):
self.nome = nome
self.anni = anni
self.fidanzato = fidanzato
self.padrone = padrone
g1 = Gatto("Fuffy", 3)
g2 = Gatto("Ciccy", 6, fidanzato=True)
g3 = Gatto("Annabelle", 2, False, "Giulio")
print(Gatto.tipo)
print(g1.tipo)
print(g2.tipo)
print(g3.tipo)
print("\nMutando la variabile di classe mediante istanza, essa muterà solo per l'oggetto in questione:")
g2.tipo = "tuccino"
print(Gatto.tipo)
print(g1.tipo)
print(g2.tipo)
print(g3.tipo)
print("\nMutando la variabile di classe utilizzando la classe stessa, "
"cambierò anche tutte le variabili di tutte le istanze future e già presenti,"
"tranne di quelle sovrascritte già, come nel precedente caso di g2:")
Gatto.tipo = "cluster"
print(Gatto.tipo)
print(g1.tipo)
print(g2.tipo)
print(g3.tipo)
print("\nAdesso vediamo se i gatti sono fidanzati:")
print(g1.fidanzato)
print(g2.fidanzato)
print(g3.fidanzato)
print("\nAdesso vediamo chi sono i padroni dei gatti:")
print(g1.padrone)
print(g2.padrone)
print(g3.padrone)
|
82c05807574232ec277e3779dfea98b9f1f251f1 | Pasquale-Silv/Bit4id_course | /Course_Bit4id/FifthDay/FunctionsIntro/ex_func2.py | 444 | 3.78125 | 4 | def writeFullName(firstname, lastname):
print("Hello %s %s, are you ok?" % (firstname, lastname))
writeFullName("Pasquale", "Silvestre")
writeFullName("Giulio", "Di Clemente")
writeFullName("Armando", "Schiano di Cola")
print("------------------------------------------------------")
def sum2num(num1, num2):
sum = num1 + num2
print("The sum of the inserted numbers is %d" % sum)
sum2num(8, 10)
sum2num(10, 11)
sum2num(30,71)
|
5329f13a9b2a3d52451e79d8ece8b90512aaf037 | Pasquale-Silv/Bit4id_course | /Some_function/SF7_factorialWithRec.py | 274 | 4 | 4 | def factorialWithRec(numInt):
if(numInt <= 1):
return 1
factorial = numInt * factorialWithRec(numInt - 1)
return factorial
factorial5 = factorialWithRec(5)
print("5! =", factorial5)
factorial4 = factorialWithRec(4)
print("4! =", factorial4)
|
94fd34899c3c92b34e5fdcae999928a0573b9c1f | mariahfernnn/udemy-python | /copying.py | 230 | 4.03125 | 4 | # EXERCISE: Stop Copying Me - While Loop
# Repeat user input until they say the magic word/phrase
copy = input("Are we there yet? ")
while copy != "I'll let you know when":
print(copy)
copy = input()
print("Yes, we're here!") |
35dc8158e1cecf78e95b9ea0ea23f3da26f3355a | nj137/Fee-estimation | /fee_estimate.py | 2,868 | 4 | 4 | #Program to estimate the fees for a course
print "Fees to be paid:"
#List of fees to be paid
fees=['application fees','exam fees']
#Exam fee structure
exam_fees={'Nationality':['Indian','Foreign','NRI','SAARC'],'Courses':['Ayurveda','Dental','Medical'],'Level':['UG','UG-Diploma','PG']}
#Application fee structure
application_fees={'Nationality':['Indian','Foreign'],'Courses':['Ayurveda','Dental','Medical'],'Level':['UG','UG-Diploma','PG']}
print "1."+fees[0]+"\n"+"2."+fees[1]
#select fees to be paid
select=int(raw_input("Select the type:"))
#j - initialization variable used for printing
j=0
if select == 2:
#Exam fees
#select nationality and print the choices
for i in exam_fees['Nationality']:
j=j+1
print str(j)+"."+str(i)
nation=int(raw_input("Select the type:"))
j=0
#select course and print the choices
for i in exam_fees['Courses']:
j=j+1
print str(j)+"."+str(i)
j=0
#select level and print the choices
course=int(raw_input("Select:"))
for i in exam_fees['Level']:
j=j+1
print str(j)+"."+str(i)
level=int(raw_input("Select the type:"))
if nation == 1 :
amount=400
elif nation == 2:
amount=100
elif nation == 3:
amount=600
else:
amount=600
print "Exam fees to be paid:"+str(amount)
elif select == 1:
#Application fees
#select nationality and print the choices
for i in application_fees['Nationality']:
j=j+1
print str(j)+"."+str(i)
nation=int(raw_input("Select the type:"))
j=0
if nation == 1:
#Indian
#select course and print the choices
for i in exam_fees['Courses']
j=j+1
print str(j)+"."+str(i)
course=int(raw_input("Select:"))
j=0
#select level and print the choices
for i in exam_fees['Level']:
j=j+1
print str(j)+"."+str(i)
level=int(raw_input("Select the type:"))
if level == 1:
amount=200
elif level == 2:
amount=300
else:
amount=500
else:
#Foreign
#select course and print the choices
for i in exam_fees['Courses']:
j=j+1
print str(j)+"."+str(i)
course=int(raw_input("Select:"))
j=0
#select level and print the choices
for i in exam_fees['Level']:
j=j+1
print str(j)+"."+str(i)
level=int(raw_input("Select the type:"))
if level == 1:
amount=400
elif level == 2:
amount=400
else:
amount=700
print "Application fees to be paid is:"+str(amount)
else:
#Invalid choice
#Start selection again
print "Invalid choice made.Start selection again!"
|
88cb690799b6fd6aa32ced1feab805eec6aaefd6 | Azureki/LeetCode | /lc19.py | 615 | 3.703125 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
if not head.next:
return None
hk = west = head
for i in range(n):
hk = hk.next
if not hk:
return head.next
while hk.next:
hk = hk.next
west = west.next
west.next = west.next.next
return head
|
4309f01c9e87cf50157393eeaea2857980856d77 | Azureki/LeetCode | /lc892.py | 1,187 | 3.859375 | 4 | '''
之前有道题求投影,这个是求表面积,因此需要考虑凹的情况。
上下(也就是平行于xy平面)容易,依然是投影。
平行于yz、xz平面的分成两部分:
1. 先求周围一圈
2. 再求被挡住的
'''
class Solution:
def surfaceArea(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n = len(grid[0])
xy = sum(v > 0 for row in grid for v in row) * 2
front = sum(x for x in grid[n - 1])
back = sum(x for x in grid[0])
left = sum(grid[i][0] for i in range(n))
right = sum(grid[i][n - 1] for i in range(n))
for i in range(n - 1):
# front to back
front += sum(max(grid[i][j] - grid[i + 1][j], 0) for j in range(n))
# back to front
back += sum(max(grid[i + 1][j] - grid[i][j], 0) for j in range(n))
left += sum(max(grid[j][i + 1] - grid[j][i], 0) for j in range(n))
right += sum(max(grid[j][i] - grid[j][i + 1], 0) for j in range(n))
return xy + front + back + left + right
s = Solution()
grid = [[1, 1, 1], [1, 0, 1], [1, 1, 1]]
print(s.surfaceArea(grid))
|
101e3174916e5959999f8dc9aeb9f63d6e058415 | Azureki/LeetCode | /lc938. Range Sum of BST.py | 871 | 3.546875 | 4 | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from bisect import bisect_left
class Solution:
def dfs(self, root, lst):
if not root:
return
self.dfs(root.left, lst)
lst.append(root.val)
self.dfs(root.right, lst)
def rangeSumBST(self, root, L, R):
"""
:type root: TreeNode
:type L: int
:type R: int
:rtype: int
"""
lst = []
self.dfs(root, lst)
lo = bisect_left(lst, L)
hi = bisect_left(lst, R)
return sum(lst[lo:hi + 1])
root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(15)
root.left.left = TreeNode(3)
root.left.right = TreeNode(7)
L = 7
R = 15
s = Solution()
print(s.rangeSumBST(root, L, R))
|
74274ba211d24f26d6056d52df0ebe385434af5b | Azureki/LeetCode | /lc888.py | 416 | 3.5625 | 4 | class Solution:
def fairCandySwap(self, A, B):
"""
:type A: List[int]
:type B: List[int]
:rtype: List[int]
"""
sumA=sum(A)
sumB=sum(B)
dif=sumA-sumB
tem=int(dif/2)
A=set(A)
B=set(B)
for a in A:
if a-tem in B:
return [a,a-tem]
A = [1,2]
B = [2,3]
s=Solution()
res=s.fairCandySwap(A,B)
print(res) |
895c3d7d11a6584c5eb83c6ea1519b25988c48c8 | Azureki/LeetCode | /lc167. Two Sum II - Input array is sorted.py | 547 | 3.546875 | 4 | class Solution:
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
left = 0
right = len(numbers) - 1
while left < right:
tem = numbers[left] + numbers[right]
if tem > target:
right -= 1
elif tem < target:
left += 1
else:
return [left + 1, right + 1]
nums = [2, 7, 11, 15]
target = 9
s = Solution()
print(s.twoSum(nums, target))
|
b8cb0d6f5da2b6177bbb78304070827be4d6f6e1 | rachelyeshurun/papercutting | /connect.py | 10,035 | 3.5 | 4 | ''' connect all the black components of the image and thicken the connecting paths
'''
import errno
import os
import sys
import numpy as np
import cv2
from utils import show_image
import numpy as np
import cv2
from pprint import pprint
# The following class is based on answer by Boaz Yaniv here: https://stackoverflow.com/questions/5997189/how-can-i-make-a-unique-value-priority-queue-in-python
# I need to wrap the simple heap q with a set so that I can update priority. So we implement a 'priority set'
import heapq
class PrioritySet(object):
def __init__(self):
self.heap = []
self.set = set()
def add(self, d, pri):
if not d in self.set:
heapq.heappush(self.heap, (pri, d))
self.set.add(d)
else:
# if pixel is already in the unvisited queue, just update its priority
prevpri, d = heapq.heappop(self.heap)
heapq.heappush(self.heap, (pri, d))
def get(self):
pri, d = heapq.heappop(self.heap)
self.set.remove(d)
return d, pri
def is_empty(self):
return len(self.set) == 0
def print(self):
print ('currently unvisited pixels with their priority (distance):')
pprint(self.heap)
# Using some of this code as a basis, but need to change a lot of things
# http://www.bogotobogo.com/python/python_Dijkstras_Shortest_Path_Algorithm.php
# Create 'distance' (sum of intensities) image - inf
# Create 'prev' image (to get path)
# Find the smallest component, store the label number of the smallest component - call it the current component
# Get border pixels of current component
# Create a list of tuples: (coordinates
# Heapify border pixels (this is the Q) with infinite distance
# heapq to store unvisited vertices (pixels) with their distance (sum of intensities).
# while Q is not empty
# extract the minimum distance unvisited pixel (call it the 'current pixel')
# for each of the 8 neighboring pixels:
# if neigbouur belongs to another component - stop algorithm! we found the path.
# if neighbour belongs to current component - skip
# calculate the neighbour's distance from the current pixel by adding the current pixel's distance with the neighbour's intensity value
# if the neighbour's calculated distance is less than its current distance, then update its distance.
# also add to the priority set (update if already there)
class ComponentConnector(object):
def __init__(self, binary_image, intensity_image):
self.current_image = binary_image
self.intensities = intensity_image
self.rows = binary_image.shape[0]
self.cols = binary_image.shape[1]
self.distances = np.ndarray((self.rows, self.cols, 2), dtype = np.uint64)
self.prev_array = np.ndarray((self.rows, self.cols, 2), dtype = np.uint64)
self.current_component_mask = np.zeros_like(intensity_image)
self.other_component_mask = np.zeros_like(intensity_image)
self.unvisited = PrioritySet()
self.path_end = (0,0)
def connect_and_thicken(self):
num_components = self.connect_smallest_component()
while num_components > 1:
num_components = self.connect_smallest_component()
return self.current_image
def connect_smallest_component(self):
# inspired by https://stackoverflow.com/questions/47055771/how-to-extract-the-largest-connected-component-using-opencv-and-python
# initialize the distance and prev_array (for the path)
self.distances = np.ones((self.rows, self.cols), np.uint64) * sys.maxsize
self.prev_array = np.zeros((self.rows, self.cols, 2), dtype = np.uint64)
while True:
num_labels, labels, stats, centroids = cv2.connectedComponentsWithStats(cv2.bitwise_not(self.current_image),
connectivity=8, ltype=cv2.CV_32S)
print('num_labels\n', num_labels)
# print('labels\n', labels, labels.shape)
print('stats\n', stats, stats.shape)
# print('centroids\n', centroids, centroids.shape)
# get label of smallest componenent (note - the first stat is the background, so look at rows starting from 1)
smallest_label = 1 + np.argmin(stats[1:, cv2.CC_STAT_AREA])
print('smallest label: ', smallest_label)
area = stats[smallest_label, cv2.CC_STAT_AREA]
x = stats[smallest_label, cv2.CC_STAT_LEFT]
y = stats[smallest_label, cv2.CC_STAT_TOP]
if area == 1:
# fill in any components with area 1
self.current_image[y, x] = 0
show_image(self.current_image, 'filled hole?')
else:
break
if num_labels < 3:
print('done')
return 1
# get border pixels of smallest label -
self.other_component_mask = np.zeros_like(self.intensities)
self.other_component_mask[np.logical_and(labels != smallest_label, labels != 0)] = 255
self.current_component_mask = np.zeros_like(self.intensities)
self.current_component_mask[labels == smallest_label] = 255
# show_image(self.other_component_mask, 'other_components_mask')
# show_image(self.current_component_mask, 'current_components_mask')
contourImg, contours, hierarchy = cv2.findContours(self.current_component_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
# mask = np.zeros_like(bin_inverted)
# cv2.drawContours(mask, contours, -1, (255), 1)
# show_image(mask, 'contourImg')
# add the component border pixels to the unvisited set of vertices (pixels)
# todo: get a run time error here if the area is 1 pixel ..
borderList = [tuple(c) for c in np.vstack(contours).squeeze()]
self.unvisited = PrioritySet()
for coord in borderList:
self.unvisited.add((coord[1], coord[0]), self.intensities[coord[1], coord[0]])
self.unvisited.print()
while not self.unvisited.is_empty():
current_pixel, distance = self.unvisited.get()
row, col = current_pixel # coordinates from contour are col, row not row, col ...
# print('current pixel (row, col, distance):', row, col, distance)
# check out the neighbours
if row > 0 and col > 0:
other_component = self.evaluate_neighbour(row, col, distance, row - 1, col - 1)
if other_component:
break
if row > 0:
other_component = self.evaluate_neighbour(row, col, distance, row - 1, col)
if other_component:
break
if row > 0 and col < self.cols - 1:
other_component = self.evaluate_neighbour(row, col, distance, row - 1, col + 1)
if other_component:
break
if col < self.cols - 1:
other_component = self.evaluate_neighbour(row, col, distance, row, col + 1)
if other_component:
break
if row < self.rows - 1 and col < self.cols - 1:
other_component = self.evaluate_neighbour(row, col, distance, row + 1, col + 1)
if other_component:
break
if row < self.rows - 1:
other_component = self.evaluate_neighbour(row, col, distance, row + 1, col)
if other_component:
break
if row < self.rows - 1 and col > 0:
other_component = self.evaluate_neighbour(row, col, distance, row + 1, col - 1)
if other_component:
break
if col > 0:
other_component = self.evaluate_neighbour(row, col, distance, row, col - 1)
if other_component:
break
r, c = self.path_end
print ('path end:', r, c)
# print ('prev array', self.prev_array)
# todo: colour the path pixels in black (update the current image)
while not self.current_component_mask[r, c]:
# print('current comp mask', self.current_component_mask[r, c])
self.current_image[r, c] = 0
r, c = self.prev_array[r, c]
# print('prev (row, col)', r, c)
# show_image(self.current_image, 'updated with path')
print ('prev array', self.prev_array)
# todo: thicken the path .. (update the current image)
return num_labels - 2
def evaluate_neighbour(self, row, col, distance, neighbour_row, neighbour_col):
# print('eval neighbour', row,col, neighbour_row, neighbour_col)
if self.current_component_mask[neighbour_row, neighbour_col]:
# print('not a neighbour.. on same component', neighbour_row, neighbour_col)
return False
if self.other_component_mask[neighbour_row, neighbour_col]:
print('reached another component!!', neighbour_row, neighbour_col)
self.path_end = (row, col)
return True
# print('distance: ', distance, self.intensities[neighbour_row, neighbour_col])
sum = distance + np.uint64(self.intensities[neighbour_row, neighbour_col])
# print ('sum, current distance of neighbour', sum, self.distances[neighbour_row, neighbour_col])
if sum < self.distances[neighbour_row, neighbour_col]:
self.distances[neighbour_row, neighbour_col] = sum
# print('adding row, col to path', row, col)
self.prev_array[neighbour_row, neighbour_col] = (row, col)
self.unvisited.add((neighbour_row, neighbour_col), sum)
# print('updated path', neighbour_row, neighbour_col, '<--:', self.prev_array[neighbour_row, neighbour_col])
return False
|
d67ecfdeaa6a10e83058d5bf4a2d160abaa8a5a0 | odiepus/PLP6 | /p6.py | 3,234 | 3.71875 | 4 | import re
str = "( + (+ 3 2) (- 7 3))"
global lastLeftParen
lastLeftParen = 0
global lastRightParen
lastRightParen = 0
class Error(Exception):
pass
class OperationError(Error):
pass
class OperandError(Error):
pass
def tokenize_str(input_str):
new_str = input_str.replace(" ", "")
new_str = new_str.replace("or", "|")
new_str = new_str.replace("and", "&")
temp_tok = re.findall(r"([^.])|[.]", new_str)
return temp_tok
def prefixEval(op, op1, op2):
if op is "+":
return int(op1) + int(op2)
elif op is "-":
return int(op1) - int(op2)
elif op is "*":
return int(op1) * int(op2)
elif op is "/":
return int(op1) / int(op2)
elif op is "&":
x = int(op1)
y = int(op2)
return x & y
elif op is "|":
x = int(op1)
y = int(op2)
return x | y
elif op is ">":
return int(op1) > int(op2)
elif op is "<":
return int(op1) < int(op2)
def parseTokList(tok_list):
global answer
global lastLeftParen
global lastRightParen
for i in tok_list:
if i is "(":
lastLeftParen += 1
tok_list.pop(0)
answer = parseTokList(tok_list)
elif i is "-":
op = tok_list.pop(0)
op1 = parseTokList(tok_list)
tok_list.pop(0)
op2 = parseTokList(tok_list)
tok_list.pop(0)
return prefixEval(op, op1, op2)
elif i is "+":
op = tok_list.pop(0)
op1 = parseTokList(tok_list)
tok_list.pop(0)
op2 = parseTokList(tok_list)
tok_list.pop(0)
return prefixEval(op, op1, op2)
elif i is "*":
op = tok_list.pop(0)
op1 = parseTokList(tok_list)
tok_list.pop(0)
op2 = parseTokList(tok_list)
tok_list.pop(0)
return prefixEval(op, op1, op2)
elif i is "/":
op = tok_list.pop(0)
op1 = parseTokList(tok_list)
tok_list.pop(0)
op2 = parseTokList(tok_list)
tok_list.pop(0)
return prefixEval(op, op1, op2)
elif i is "&":
op = tok_list.pop(0)
op1 = parseTokList(tok_list)
tok_list.pop(0)
op2 = parseTokList(tok_list)
tok_list.pop(0)
return prefixEval(op, op1, op2)
elif i is "|":
op = tok_list.pop(0)
op1 = parseTokList(tok_list)
tok_list.pop(0)
op2 = parseTokList(tok_list)
tok_list.pop(0)
return prefixEval(op, op1, op2)
elif i.isdigit():
return i
elif i is ")":
lastRightParen += 1
tok_list.pop(0)
return answer
def prefixReader(str):
print(">", str)
str = str.replace(" ", "")
parens = re.search(r"\(\(", str)
if parens is not None:
try:
raise OperandError
except OperandError:
print("Expect operator after each left parenthesis")
else:
tok_list = tokenize_str(str)
result = parseTokList(tok_list)
print(result)
print(3 | 4)
prefixReader(str)
|
5670d0bec92648eea1b37bc852ec858de9dce2dd | a1ip/python-learning | /lutz.LearningPython/script1.py | 307 | 3.609375 | 4 | #!/usr/bin/env python3
# Первый сценарий на языке Python
import sys # Загружает библиотечный модуль
print(sys.platform)
print(2 ** 100) # Возводит число 2 в степень 100
x = 'Spam!'
print(x * 8) # Дублирует строку
input ()
|
6da48b1d055c81f33d761c13c3ceef41133231bb | a1ip/python-learning | /phyton3programming/1ex4.awfulpoetry2_ans.py | 1,576 | 4.1875 | 4 | #!/usr/bin/env python3
"""
добавьте в нее программный код, дающий пользователю возможность определить количество выводимых строк (от 1 до 10 включительно),
передавая число в виде аргумента командной строки. Если программа вызывается без аргумента,
она должна по умолчанию выводить пять строк, как и раньше.
"""
import random
#tuple (кортежи) - относятся к разряду неизменяемых объектов
t_art=('the','a','an') #article, артикли
t_noun=('cat', 'dog', 'man', 'woman') #существительные
t_verb=('sang', 'ran', 'jumped') #глагол
t_adv=('loudly', 'quietly', 'well', 'badly') #adverb, наречие
max=5
while True:
line = input("enter a number of row or Enter to finish: ")
if line:
try:
max = int(line)
except ValueError as err:
print(err)
continue
else:
break
print ("max=",max)
if max == 0:
max=5
i = 0
l=()
while i < max:
if (random.randint(1,2))==1:
l=random.choice(t_art)
l=l+" "+random.choice(t_noun)
l=l+" "+random.choice(t_verb)
l=l+" "+random.choice(t_adv)
else:
l=random.choice(t_art)
l=l+" "+random.choice(t_noun)
l=l+" "+random.choice(t_verb)
print(l)
i+=1
|
2fbbc1a17133c74dd37c612200ddee48a0b2c4ca | a1ip/python-learning | /lutz.LearningPython/P1129.py | 923 | 3.890625 | 4 | #!/usr/bin/env python3
registry = {}
def register(obj): # Декоратор функций и классов
registry[obj.__name__] = obj # Добавить в реестр
return obj # Возвращает сам объект obj, а не обертку
@register
def spam(x):
return(x ** 2) # spam = register(spam)
@register
def ham(x):
return(x ** 3)
@register
class Eggs: # Eggs = register(Eggs)
def __init__(self, x):
self.data = x ** 4
def __str__(self):
return str(self.data)
print('Registry:')
for name in registry:
print(name, '=>', registry[name], type(registry[name]))
print('\nManual calls:')
print(spam(2)) # Вызов объекта вручную
print(ham(2)) # Вызовы не перехватываются декоратором
X = Eggs(2)
print(X)
print('\nRegistry calls:')
for name in registry:
print(name, '=>', registry[name](3)) # Вызов из реестра
|
9a261241acebb6fe2d50116cd6227f22c9571b1b | a1ip/python-learning | /empireofcode.com/adamantite_mine_1MostNumbers.py | 1,034 | 3.71875 | 4 | #!/usr/bin/env python3
def most_difference(*args):
if len(args) > 0:
nums=sorted(args)
min=nums[0]
max=nums[-1]
print (max,'-',min,'=',round(max-min,3))
return round(max-min,3)
return 0
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
##def almost_equal(checked, correct, significant_digits):
## precision = 0.1 ** significant_digits
## return correct - precision < checked < correct + precision
##assert almost_equal(most_difference(1, 2, 3), 2, 3), "3-1=2"
##assert almost_equal(most_difference(5, 5), 0, 3), "5-5=0"
##assert almost_equal(most_difference(10.2, 2.2, 0.00001, 1.1, 0.5), 10.199, 3), "10.2-(0.00001)=10.19999"
##assert almost_equal(most_difference(), 0, 3), "Empty"
assert most_difference(1, 2, 3) == 2
assert most_difference(5, -5) == 10
assert most_difference(10.2, -2.2, 0, 1.1, 0.5) == 12.4
assert most_difference() == 0
assert most_difference(-0.036, -0.11, -0.55, -64.0)
|
445aafce7f87fa1181a00366875fe06bb8ea8a24 | a1ip/python-learning | /phyton3programming/sort.py | 347 | 3.796875 | 4 | #!/usr/bin/env python3
numbers = [9,6,2,4,5,1]
print(numbers)
#Сортировка
i=0
while i<len(numbers):
j=0
print("")
while j<len(numbers)-i-1:
print(i,j)
#
if numbers[j]>numbers[j+1]:
#
tmp=numbers[j]
numbers[j]=numbers[j+1]
numbers[j+1]=tmp
print(numbers)
j+=1
#
i+=1
print(numbers)
|
ecad1b1fc73e3f4a21f139b7702cca8f2a293045 | a1ip/python-learning | /lutz.LearningPython/tester.py | 1,436 | 3.796875 | 4 | ##tester func
"""
def tester(start):
state = start # Обращение к нелокальным переменным
def nested(label): # действует как обычно
nonlocal state
print(label, state) # Извлекает значение state из области
state += 1
return nested
"""
#tester class
"""
class tester: # Альтернативное решение на основе классов (Часть VI)
def __init__(self, start): # Конструктор объекта,
self.state = start # сохранение информации в новом объекте
def nested(self, label):
print(label, self.state) # Явное обращение к информации
self.state += 1 # Изменения всегда допустимы
"""
#tester class as func
"""
class tester:
def __init__(self, start):
self.state = start
def __call__(self, label): # Вызывается при вызове экземпляра
print(label, self.state) # Благодаря этому отпадает
self.state += 1
"""
#tester func as user func
def tester(start):
def nested(label):
print(label, nested.state) # nested – объемлющая область видимости
nested.state += 1 # Изменит атрибут, а не значение имени nested
nested.state = start # Инициализация после создания функции
return nested
|
a3982626451b29e21a6077cbf8c0b7be10fbc31b | a1ip/python-learning | /lutz.LearningPython/part3ex1c.py | 181 | 3.59375 | 4 | #!/usr/bin/env python3
S='t s'
L=[]
for x in S:
print ('ASCII code for symbol', x, '=', ord(x))
L.append(ord(x))
print ("\nlist for S as ASCII code:", L)
#or list(map(ord, S))
|
efba9a36610e4837f4723d08518a5255da5a881a | TonyZaitsev/Codewars | /8kyu/Remove First and Last Character/Remove First and Last Character.py | 680 | 4.3125 | 4 | /*
https://www.codewars.com/kata/56bc28ad5bdaeb48760009b0/train/python
Remove First and Last Character
It's pretty straightforward. Your goal is to create a function that removes the first and last characters of a string. You're given one parameter, the original string. You don't have to worry with strings with less than two characters.
*/
def remove_char(s):
return s[1:][:-1]
/*
Sample Tests
Test.describe("Tests")
Test.assert_equals(remove_char('eloquent'), 'loquen')
Test.assert_equals(remove_char('country'), 'ountr')
Test.assert_equals(remove_char('person'), 'erso')
Test.assert_equals(remove_char('place'), 'lac')
Test.assert_equals(remove_char('ok'), '')
*/
|
0c17db71399217a47698554852206d60743ef93e | TonyZaitsev/Codewars | /7kyu/Reverse Factorials/Reverse Factorials.py | 968 | 4.375 | 4 | """
https://www.codewars.com/kata/58067088c27998b119000451/train/python
Reverse Factorials
I'm sure you're familiar with factorials – that is, the product of an integer and all the integers below it.
For example, 5! = 120, as 5 * 4 * 3 * 2 * 1 = 120
Your challenge is to create a function that takes any number and returns the number that it is a factorial of. So, if your function receives 120, it should return "5!" (as a string).
Of course, not every number is a factorial of another. In this case, your function would return "None" (as a string).
Examples
120 will return "5!"
24 will return "4!"
150 will return "None"
"""
def reverse_factorial(num):
f = num
n = 1
while n <= f:
f /= n
n += 1
return "None" if f != 1 else str(n-1) + "!"
"""
Sample Tests
test.assert_equals(reverse_factorial(120), '5!')
test.assert_equals(reverse_factorial(3628800), '10!')
test.assert_equals(reverse_factorial(150), 'None')
"""
|
3d35471031ccadd2fc2e526881b71a7c8b55ddc0 | TonyZaitsev/Codewars | /8kyu/Is your period late?/Is your period late?.py | 1,599 | 4.28125 | 4 | """
https://www.codewars.com/kata/578a8a01e9fd1549e50001f1/train/python
Is your period late?
In this kata, we will make a function to test whether a period is late.
Our function will take three parameters:
last - The Date object with the date of the last period
today - The Date object with the date of the check
cycleLength - Integer representing the length of the cycle in days
If the today is later from last than the cycleLength, the function should return true. We consider it to be late if the number of passed days is larger than the cycleLength. Otherwise return false.
"""
from datetime import *
def period_is_late(last,today,cycle_length):
return last + timedelta(days = cycle_length) < today
"""
Sample Tests
Test.describe("Basic tests")
Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 7, 16), 35), False)
Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 7, 16), 28), True)
Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 7, 16), 35), False)
Test.assert_equals(period_is_late(date(2016, 6, 13), date(2016, 6, 29), 28), False)
Test.assert_equals(period_is_late(date(2016, 7, 12), date(2016, 8, 9), 28), False)
Test.assert_equals(period_is_late(date(2016, 7, 12), date(2016, 8, 10), 28), True)
Test.assert_equals(period_is_late(date(2016, 7, 1), date(2016, 8, 1), 30), True)
Test.assert_equals(period_is_late(date(2016, 6, 1), date(2016, 6, 30), 30), False)
Test.assert_equals(period_is_late(date(2016, 1, 1), date(2016, 1, 31), 30), False)
Test.assert_equals(period_is_late(date(2016, 1, 1), date(2016, 2, 1), 30), True)
"""
|
019b5d23d15f4b1b28ee9d89112921f4d325375e | TonyZaitsev/Codewars | /7kyu/Sum Factorial/Sum Factorial.py | 1,148 | 4.15625 | 4 | """
https://www.codewars.com/kata/56b0f6243196b9d42d000034/train/python
Sum Factorial
Factorials are often used in probability and are used as an introductory problem for looping constructs. In this kata you will be summing together multiple factorials.
Here are a few examples of factorials:
4 Factorial = 4! = 4 * 3 * 2 * 1 = 24
6 Factorial = 6! = 6 * 5 * 4 * 3 * 2 * 1 = 720
In this kata you will be given a list of values that you must first find the factorial, and then return their sum.
For example if you are passed the list [4, 6] the equivalent mathematical expression would be 4! + 6! which would equal 744.
Good Luck!
Note: Assume that all values in the list are positive integer values > 0 and each value in the list is unique.
Also, you must write your own implementation of factorial, as you cannot use the built-in math.factorial() method.
"""
def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)
def sum_factorial(lst):
return sum(list(map(lambda x: factorial(x), lst)))
"""
Sample Tests
test.assert_equals(sum_factorial([4,6]), 744)
test.assert_equals(sum_factorial([5,4,1]), 145)
"""
|
56be1dd38c46c57d5985d8c85b00895eeca5777d | TonyZaitsev/Codewars | /5kyu/The Hashtag Generator/The Hashtag Generator.py | 2,177 | 4.3125 | 4 | """
https://www.codewars.com/kata/52449b062fb80683ec000024/train/python
The Hashtag Generator
The marketing team is spending way too much time typing in hashtags.
Let's help them with our own Hashtag Generator!
Here's the deal:
It must start with a hashtag (#).
All words must have their first letter capitalized.
If the final result is longer than 140 chars it must return false.
If the input or the result is an empty string it must return false.
Examples
" Hello there thanks for trying my Kata" => "#HelloThereThanksForTryingMyKata"
" Hello World " => "#HelloWorld"
"" => false
"""
def generate_hashtag(s):
hashtag = "#" + "".join(list(map(lambda x: x.capitalize(), s.split(" "))))
return hashtag if 1< len(hashtag) < 140 else False
"""
Sample Tests
Test.describe("Basic tests")
Test.assert_equals(generate_hashtag(''), False, 'Expected an empty string to return False')
Test.assert_equals(generate_hashtag('Do We have A Hashtag')[0], '#', 'Expeted a Hashtag (#) at the beginning.')
Test.assert_equals(generate_hashtag('Codewars'), '#Codewars', 'Should handle a single word.')
Test.assert_equals(generate_hashtag('Codewars '), '#Codewars', 'Should handle trailing whitespace.')
Test.assert_equals(generate_hashtag('Codewars Is Nice'), '#CodewarsIsNice', 'Should remove spaces.')
Test.assert_equals(generate_hashtag('codewars is nice'), '#CodewarsIsNice', 'Should capitalize first letters of words.')
Test.assert_equals(generate_hashtag('CodeWars is nice'), '#CodewarsIsNice', 'Should capitalize all letters of words - all lower case but the first.')
Test.assert_equals(generate_hashtag('c i n'), '#CIN', 'Should capitalize first letters of words even when single letters.')
Test.assert_equals(generate_hashtag('codewars is nice'), '#CodewarsIsNice', 'Should deal with unnecessary middle spaces.')
Test.assert_equals(generate_hashtag('Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong Cat'), False, 'Should return False if the final word is longer than 140 chars.')
"""
|
a5ebb27b3e709396ad81c482ff164bf372e9bf96 | kepler471/katas | /esolangInterpreter/ministring.py | 202 | 3.5625 | 4 | def interpreter(code):
count = 0
accum = ''
for i in code:
if i == '+':
count = (count + 1) % 256
elif i == '.':
accum += chr(count)
return accum
|
ef2c835a3bcefbf4b26cea5291d3478014f877fd | uzunovavera/learnPythonTheHardWay | /venv/ex13.py | 593 | 3.875 | 4 | from sys import argv
#read the WYSS section for how to run this
script, first, second, third = argv
age = input("What is your age?")
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
# To execute this you need to open CMD from the folder with the scripts and write:
# python ex13.py one_thing another_thing the last_thing
# You will get result:
# The script is called: ex13.py
# Your first variable is: 1thing
# Your second variable is: 2things
# Your third variable is: 3things
|
7cc9db5d288ce69ff8d87079d92ad899ac52026b | mehedieh/dice | /dice.py | 2,997 | 3.75 | 4 | import random
import time
import getpass
import hashlib
HASHED_PASSWORD = "b109f3bbbc244eb82441917ed06d618b9008dd09b3befd1b5e07394c706a8bb980b1d7785e5976ec049b46df5f1326af5a2ea6d103fd07c95385ffab0cacbc86"
USERS = ('User1', 'User2', 'User3', 'User4', 'User5')
def login(max_attempts=5):
attempts = 0
while attempts < max_attempts:
username = input('What is your username? ')
password = getpass.getpass('What is your password? ')
# [OPTIONAL] add a salt
if username not in USERS or HASHED_PASSWORD != hashlib.sha512(password.encode()).hexdigest():
print('Something went wrong, try again')
attempts += 1
continue
print(f'Welcome, {username} you have been successfully logged in.')
return username
print("Too many tries, exiting")
exit()
if __name__ == '__main__':
user = login()
def roll():
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
change = 10 if (die1 + die2) % 2 == 0 else -5
points = die1 + die2 + change
if die1 == die2:
points += random.randint(1, 6)
return points
def game(user1, user2):
player1_points = 0
player2_points = 0
for i in range(1,5):
player1_points += roll()
print(f'After this round {user1} you now have: {player1_points} Points')
time.sleep(1)
player2_points += roll()
print(f'After this round {user2} you now have: {player2_points} Points')
time.sleep(1)
player1_tiebreaker = 0
player2_tiebreaker = 0
if player1_points == player2_tiebreaker:
while player1_tiebreaker == player2_tiebreaker:
player1_tiebreaker = random.randint(1,6)
player2_tiebreaker = random.randint(1,6)
player1_win = (player1_points + player1_tiebreaker) > (player2_points, player2_tiebreaker)
return (player1_points, player1_win), (player2_points, not player2_win)
def add_winner(winner):
with open('Winner.txt', 'a') as f:
f.write('{winner[0]},{winner[1]}\n')
def get_leaderboard():
with open('Leaderboard.txt', 'r') as f:
return [line.replace('\n','') for line in f.readlines()]
def update_leaderboard(leaderboard, winner):
for idx, item in enumerate(leaderboard):
if item.split(', ')[1] == winner[1] and int(item.split(', ')[0]) < int(winner[0]):
leaderboard[idx] = '{}, {}'.format(winner[0], winner[1])
else:
pass
leaderboard.sort(reverse=True)
def save_leaderboard(leaderboard):
with open('Leaderboard.txt', 'w') as f:
for item in leaderboard:
f.write(f'{item}\n')
def main():
user1 = login()
user2 = login()
(player1, player1_win), (player2, player2_win) = game(user1, user2)
if player1_win:
winner = (player1, user1)
else:
winner = (player2, user2)
print('Well done, {winner[1]} you won with {winner[0]} Points')
add_winner(winner)
leaderboard = get_leaderboard()
update_leaderboard(leaderboard, winner)
save_leaderboard(leaderboard)
if __name__ == '__main__':
main()
|
d78ad76a67dfa6b320a78cf88427b8ef791bb814 | movingpictures83/MATria | /networkx_mod/generators/stochastic.py | 1,433 | 3.6875 | 4 | """Stocastic graph."""
# Copyright (C) 2010-2013 by
# Aric Hagberg <hagberg@lanl.gov>
# Dan Schult <dschult@colgate.edu>
# Pieter Swart <swart@lanl.gov>
# All rights reserved.
# BSD license.
import networkx as nx
from networkx.utils import not_implemented_for
__author__ = "Aric Hagberg <aric.hagberg@gmail.com>"
__all__ = ['stochastic_graph']
@not_implemented_for('multigraph')
@not_implemented_for('undirected')
def stochastic_graph(G, copy=True, weight='weight'):
"""Return a right-stochastic representation of G.
A right-stochastic graph is a weighted digraph in which all of
the node (out) neighbors edge weights sum to 1.
Parameters
-----------
G : directed graph
A NetworkX DiGraph
copy : boolean, optional
If True make a copy of the graph, otherwise modify the original graph
weight : edge attribute key (optional, default='weight')
Edge data key used for weight. If no attribute is found for an edge
the edge weight is set to 1. Weights must be positive numbers.
"""
import warnings
if copy:
W = nx.DiGraph(G)
else:
W = G # reference original graph, no copy
#degree = W.out_degree(weight=weight)
degree = W.degree(weight=weight)
for (u,v,d) in W.edges(data=True):
if degree[u] == 0:
warnings.warn('zero out-degree for node %s'%u)
d[weight] = 0.0
else:
d[weight] = float(d.get(weight,1.0))/degree[u]
return W
|
285505ccfb2e2dbd706c6ef6f884c92f1fa0214c | LiamTHCH/Boids-Simulation | /Test Version/main (0).py | 1,974 | 3.53125 | 4 | import random
import time
from tkinter import *
master = Tk()
master.title("Points")
canvas_width = 1000
canvas_height = 800
w = Canvas(master, width=canvas_width, height=canvas_height)
w.pack(expand=YES, fill=BOTH)
w.pack()
##definir les variables
Ox = (random.randint(100, 900))
Oy = (random.randint(100, 700))
m = 30
dt = 0.1
t = 0
size = 10
nb = 10
def paint(x, y, color): ##la fonction paint cree les points
color
x1, y1 = (x - size), (y - size)
x2, y2 = (x + size), (y + size)
w.create_oval(x1, y1, x2, y2, fill=color)
class point(): ##cree la fonction point
def __init__(self,m,dt): ##initialisation (self = lui meme) tout les variable sont propres a luis
self.Ox = (random.randint(0, 800))
self.Oy = (random.randint(0, 1000))
self.m = m
self.dt = dt
self.Mx = (random.randint(0, 800))
self.My = (random.randint(0, 1000))
self.OMx = 0
self.OMy = 0
self.fx = 0
self.fy = 0
self.ax = 0
self.ay = 0
self.vx = 100
self.vy = 50
def calcule(self): ## calcule de son prochain point
self.OMx = self.Mx - self.Ox
self.OMy = self.My - self.Oy
self.fx = m * (-self.OMx)
self.fy = m * (-self.OMy)
self.ax = (1 / self.m) * self.fx
self.ay = (1 / self.m) * self.fy
self.vx = self.vx + (self.ax * self.dt)
self.vy = self.vy + (self.ay * self.dt)
self.Mx = self.Mx + (self.vx * self.dt)
self.My = self.My + (self.vy * self.dt)
def show(self): ## met le point sur la carte
paint(self.Mx,self.My,"#FF0000")
flock = [point(m,dt) for _ in range(nb)] ## cree nb de point dans la liste
while True:
for p in flock: ##fais un par un les commande pour chaque elements de la liste
p.calcule()
p.show()
paint(Ox, Oy, "#000000")
master.update()
time.sleep(0.05)
w.delete("all")
mainloop() |
74e2b19f5933103ad676852617eb303038fbe3ce | ckasper21/CS265 | /lab04/s1.py | 591 | 3.671875 | 4 | #!/usr/bin/python
# s1.py
# Author: Chris Kasper
# Purpose: Breakdown students input file, outputs name and average
import sys
if len(sys.argv)==1: # Check to make sure theres an arg (other then the script)
sys.exit()
f = open(str(sys.argv[1]), 'r') # Open the file from arg
l=f.readline()
while l :
total=0
l=l.strip() # Get rid of newlines, trailing spaces, etc
l=l.split(" ") # Split the line by spaces
for x in range(1,len(l)): # Index through grades. l[0] is the name
total+=int(l[x])
average=(float(total)/(len(l)-1))
print "%s %.2f" % (l[0],average)
l=f.readline()
f.close()
|
f9df830f5502a1652f458cfa5f3d25832a27fc54 | caohanlu/test | /阶段01/08 类与类之间的调用、继承.py | 9,933 | 4.78125 | 5 |
"""
类与类之间的调用:
需求:老张开车去东北
类:承担行为 【行为一样的,划分成一个类】【按照行为,划分成类,就叫做封装】
对象:承担数据 【每个对象的数据不一样,但是每个对象的行为是一样的】
1. 识别对象
老张 车
2. 分配职责
去() 行驶()
3. 建立交互
老张调用车
4.东北没有动作,所以不用划分成类
"""
# 写法1:直接创建对象
# 语义: 老张去东北用一辆新车
# class Person:
# def __init__(self, name=""):
# self.name = name
#
# def go_to(self, position):
# print(self.name, "去", position)
# car = Car() # 调用类Car(),创建了对象car
# car.run() # 对象car,调用了类Car()里的函数run
# #这种写法,每去一个地方,都会执行一次car = Car(),即都会创建一个car对象,不太合适
#
#
# class Car:
# # 实例方法
# def run(self):
# print("汽车在行驶")
#
#
# lw = Person("老王")
# lw.go_to("东北")
# lw.go_to("西北")
# 写法2:在构造函数中创建对象
# 语义: 老张开车自己的车去东北
# class Person:
# def __init__(self, name=""):
# self.name = name
# self.car = Car() #在构造函数中,通过类class Car,创建对象car
#
# def go_to(self, position):
# print(self.name, "去", position)
# # 第一次.: 从栈帧到人对象
# # 第二次.: 从人到车对象
# self.car.run() #通过self.car调用实例方法run()
#
#
# class Car:
# # 实例方法
# def run(self):
# print("汽车在行驶")
#
#
# lw = Person("老王")
# lw.go_to("东北")
# lw.go_to("西北")
# 写法3:通过参数传递对象
# 语义:人通过交通工具(参数传递而来)去东北
# class Person:
# def __init__(self, name=""):
# self.name = name
#
# def go_to(self, position, vehicle): #vehicle是参数名
# print(self.name, "去", position)
# vehicle.run() #vehicle是参数名,vehicle这个对象,调用函数run()
#
#
# class Car:
# # 实例方法
# def run(self):
# print("汽车在行驶")
#
#
# lw = Person("老王")
# c01 = Car()
# lw.go_to("东北", c01)#c01这个Car对象,通过参数,传递给go_to函数
"""
练习:
需求:小明请保洁打扫卫生
1. 识别对象
小明【客户类】 保洁【保洁类】
2. 分配职责
通知 打扫卫生
3. 建立交互
小明调用保洁的打扫卫生方法
"""
# 写法1:类里的动作函数,创建别的类的对象,然后通过对象调用别的类的实例方法
# 每次请一个新保洁
# class Client:
# def __init__(self, name=""):
# self.name=name
# def notify(self):
# cleaner=Cleaner()
# cleaner.clean()
#
# class Cleaner:
# def __init__(self, name=""):
# self.name=name
# def clean(self):
# print("保洁在打扫卫生")
#
# client=Client("小明")
# client.notify()
# 写法2:类里的构造函数,创建别的类的对象,然后通过对象调用别的类的实例方法
# 每次请同一个保洁
# class Client:
# def __init__(self, name=""):
# self.name=name
# self.cleaner=Cleaner()
# def notify(self):
# self.cleaner.clean()
#
# class Cleaner:
# def __init__(self, name=""):
# self.name=name
# def clean(self):
# print("保洁在打扫卫生")
#
# client=Client("小明")
# client.notify()
# 写法3:通过参数,调用别的类的实例方法
# class Client:
# def __init__(self, name=""):
# self.name=name
# def notify(self,cleaner):
# cleaner.clean()
#
#
# class Cleaner:
# def __init__(self, name=""):
# self.name=name
# def clean(self):
# print("保洁在打扫卫生")
#
# client=Client("小明")
# cleaner01=Cleaner()
# client.notify(cleaner01)
"""
练习
1. 玩家攻击敌人,敌人受伤(播放动画)
2. 玩家(攻击力)攻击敌人(血量),
敌人受伤(播放动画,血量减少)
3. 敌人(攻击力)还能攻击玩家(血量),
玩家受伤(碎屏,血量减少)
"""
#
#
# class GamePlayer:
# def __init__(self, name="", power=0, blood=0):
# self.name = name
# self.power = power
# self.blood = blood
#
# def attack(self, enemy):
# enemy.injured(self.power)
#
# def injured(self, value):
# print("玩家受伤")
# self.blood -= value
# print(self.blood)
#
#
# class Enemy:
# def __init__(self, name="", power=0, blood=0):
# self.name = name
# self.power = power
# self.blood = blood
#
# def attack(self, gameplayer):
# gameplayer.injured(self.power)
#
# def injured(self, value):
# print("敌人受伤了")
# self.blood -= value
# print(self.blood)
#
#
# gameplayer01 = GamePlayer("玩家01", 10, 100)
# enemy01 = Enemy("敌人01", 10, 100)
# gameplayer01.attack(enemy01)
# enemy01.attack(gameplayer01)
"""
继承
编程:代码不用子类写,但是子类能使用
多个类有代码的共性,且属于共同一个概念。
下面继承父类的实例方法【即函数】
"""
# 从思想讲:先有子再有父
# 从编码讲:先有父再有子
# 多个类有代码的共性,且属于共同一个概念。
# 比如学生会说话,老师也会说话,则把说话这段代码 抽象成人这个类,人会说话
# class Person:
# def say(self):
# print("说话")
#
# class Student(Person): #(Person),表示继承父类Person
# def study(self):
# self.say() #可以调用父类的实例方法
# print("学习")
#
# class Teacher(Person):
# def teach(self):
# print("教学")
#
#
# # 创建子类对象,可以调用父类方法和子类方法
# s01 = Student()
# s01.say() #这个就是父类方法
# s01.study()
#
# # 创建父类对象,只能调用父类方法
# p01 = Person()
# p01.say()
"""
父类、子类,关系的判断方法,三种
【兼容性判断】
"""
#
# # isinstance(对象,类) 判断关系,python内置函数
#
# # 学生对象 是一种 学生类型
# print(isinstance(s01, Student)) # True
# # 学生对象 是一种 人类型
# print(isinstance(s01, Person)) # True
# # 学生对象 是一种 老师类型
# print(isinstance(s01, Teacher)) # False
# # 人对象 是一种 学生类型
# print(isinstance(p01, Student)) # False
#
#
#
#
# # issubclass(类型,类型) 判断关系
#
# # 学生类型 是一种 学生类型
# print(issubclass(Student, Student)) # True
# # 学生类型 是一种 人类型
# print(issubclass(Student, Person)) # True
# # 学生类型 是一种 老师类型
# print(issubclass(Student, Teacher)) # False
# # 人类型 是一种 学生类型
# print(issubclass(Person, Student)) # False
#
#
#
#
#
# # Type
# # type(对象) == 类型 相等/相同/一模一样
#
# # 学生对象的类型 是 学生类型
# print(type(s01) == Student) # True
# # 学生对象的类型 是 人类型
# print(type(s01) == Person) # False
# # 学生对象的类型 是 老师类型
# print(type(s01) == Teacher) # False
# # 人对象的类型 是 学生类型
# print(type(p01) == Student) # False
"""
继承数据【继承的是父类的实例变量】
class 儿子(爸爸):
def __init__(self, 爸爸构造函数参数,儿子构造函数参数):
super().__init__(爸爸构造函数参数)
self.数据 = 儿子构造函数参数
"""
# class Person:
# def __init__(self, name="", age=0):
# self.name = name
# self.age = age
#
#
# class Student(Person):
# def __init__(self, name="", age=0, score=0):
# super().__init__(name, age) # 通过super()调用父类__init__函数,自己的__init__需要给父类的__init__传递参数
# self.score = score
#
#
# # 1. 子类可以没有构造函数,可以直接使用父类的__init__函数
# s01 = Student()
#
# # 2. 子类有构造函数,会覆盖父类构造函数(好像他不存在)
# # 所以子类必须通过super()调用父类构造函数
# s01 = Student("小明", 24, 100)
# print(s01.name)
# print(s01.age)
# print(s01.score)
#
"""
练习:继承数据【即继承实例变量】
创建父类:车(品牌,速度)
创建子类:电动车(电池容量,充电功率)
创建子类对象并画出内存图。
"""
# class Car:
# def __init__(self, brand="", speed=0):
# self.brand=brand
# self.speed=speed
#
# class ElectricVehicle(Car):
# def __init__(self,brand="", speed=0,capacity=0,power=0):
# super().__init__(brand,speed)
# self.capacity=capacity
# self.power=power
#
# ElectricVehicle01=ElectricVehicle("速派奇",100,200,200)
# print(ElectricVehicle01.brand)
# print(ElectricVehicle01.speed)
# print(ElectricVehicle01.capacity)
# print(ElectricVehicle01.power)
"""
多继承
同名方法解析顺序
类.mro()
"""
#
# class A:
# def func01(self):
# print("A -- func01")
#
#
# class B(A):
# def func01(self):
# print("B -- func01")
#
#
# class C(A):
# def func01(self):
# print("C -- func01")
#
#
# class D(B, C):
# def func01(self):
# super().func01() # 继承列表第一个父类B的func01()方法
# print("D -- func01")
#
#
# d = D()
# d.func01()
# 具体的解析顺序:使用 类名字.mro()方法,可以print出来
# [<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
# print(D.mro())
|
3afc1ab7a0de2bb6dc837084dd461865a2c34089 | mirpulatov/racial_bias | /IMAN/utils.py | 651 | 4.15625 | 4 | def zip_longest(iterable1, iterable2):
"""
The .next() method continues until the longest iterable is exhausted.
Till then the shorter iterable starts over.
"""
iter1, iter2 = iter(iterable1), iter(iterable2)
iter1_exhausted = iter2_exhausted = False
while not (iter1_exhausted and iter2_exhausted):
try:
el1 = next(iter1)
except StopIteration:
iter1_exhausted = True
iter1 = iter(iterable1)
continue
try:
el2 = next(iter2)
except StopIteration:
iter2_exhausted = True
if iter1_exhausted:
break
iter2 = iter(iterable2)
el2 = next(iter2)
yield el1, el2
|
410c378f69b9d4b2ff43c1ec249bb2bf63d94589 | organisciak/programming-puzzles | /finished/euler/001-multiples-of-3-5.py | 336 | 3.859375 | 4 | # Find the sum of all the multiples of 3 or 5 below 1000.
x = 10
# Simple solution
print sum([n for n in range(0, x) if n % 3 == 0 or n % 5 == 0])
# Adding the sums of iterate by 3 and iterate by 5 ranges, then subtract
# the iterate by 15 range. No comparisons!
print sum(range(0, x, 3)) + sum(range(0, x, 5)) + sum(range(0, x, 15))
|
821e12b328bc80de48c097fd78617807d1430bdd | django/django-localflavor | /localflavor/uy/util.py | 324 | 3.921875 | 4 | def get_validation_digit(number):
"""Calculates the validation digit for the given number."""
weighted_sum = 0
dvs = [4, 3, 6, 7, 8, 9, 2]
number = str(number)
for i in range(0, len(number)):
weighted_sum = (int(number[-1 - i]) * dvs[i] + weighted_sum) % 10
return (10 - weighted_sum) % 10
|
1d5d793833094834c00371b46286e3057187a968 | vampire7414/bin_dec_hexa | /binary_to_hexa.py | 210 | 4.09375 | 4 | print('hello I can change the number from binary to hexa')
binary=input('enter a binary number:')
decimalsolution=int(binary,base=2)
hexasolution=hex(decimalsolution)
print('the answer is')
print(hexasolution)
|
c155a4b2a15f2934639592340350320d40367904 | shiny0510/DataStructure_Python | /Algorithm analysis/graph.py | 688 | 3.828125 | 4 | import matplotlib.pyplot as plt
import numpy as np
n = np.arange(1, 1000)
m = np.arange(1, 31)
plt.figure(figsize=(10, 6))
# set new range m, because 2^1000 is to big to show
plt.plot(n, np.log(n), label="$\log_{2} n$") # 수의 subscribt를 나타내는 LaTeX
plt.plot(n, n, label="n")
plt.plot(n, n*np.log(n), label="$n \log_{2} n$")
plt.plot(n, n**2, label="n**2")
plt.plot(n, n**3, label="n**3")
plt.plot(m, 2**m, label="2**m")
# for better looking graph
plt.xscale("log")
plt.yscale("log")
plt.xlim(3, 1000)
plt.ylim(1, 1000000)
plt.xlabel("size")
plt.ylabel("time")
# show legend and grid
plt.legend(loc="upper left")
plt.grid(True)
plt.show()
|
ea3fb234b041a3eabf8a459e23de7a777d34e109 | james122823/DivideAndConquer | /week03/local_min.py | 4,294 | 3.734375 | 4 | def local_min(matrix):
"""
Assume matrix as a list of lists containing integer or floating point
values with NxN values.
"""
if len(matrix) == 2:
a = matrix[0][0]
b = matrix[0][1]
c = matrix[1][0]
d = matrix[1][1]
sort = sorted([a, b, c, d])
return sort[0] != sort[3]
mid = int(len(matrix)/2.0)
min_window_val = float("inf")
min_window_index = (0,0)
top_row = matrix[0]
mid_row = matrix[mid]
bottom_row = matrix[len(matrix)-1]
for c in range(len(matrix[0])):
if top_row[c] < min_window_val:
min_window_val = top_row[c]
min_window_index = (0, c)
if mid_row[c] < min_window_val:
min_window_val = mid_row[c]
min_window_index = (mid, c)
if bottom_row[c] < min_window_val:
min_window_val = bottom_row[c]
min_window_index = (len(matrix)-1, c)
for r in range(1, mid-1):
if matrix[r][0] < min_window_val:
min_window_val = matrix[r][0]
min_window_index = (r, 0)
if matrix[r][mid] < min_window_val:
min_window_val = matrix[r][mid]
min_window_index = (r, mid)
if matrix[r][len(matrix[r])-1] < min_window_val:
min_window_val = matirx[r][len(matrix[r])-1]
min_window_index = (r, len(matrix[r])-1)
for r in matrix[mid+1:len(matrix)-1]:
if matrix[r][0] < min_window_val:
min_window_val = matrix[r][0]
min_window_index = (r, 0)
if matrix[r][mid] < min_window_val:
min_window_val = matrix[r][mid]
min_window_index = (r, mid)
if matrix[r][len(matrix[r])-1] < min_window_val:
min_window_val = matirx[r][len(matrix[r])-1]
min_window_index = (r, len(matrix[r])-1)
is_top = min_window_index[0] == 0
is_bottom = min_window_index[0] == (len(matrix[0])-1)
is_left = min_window_index[1] == 0
is_right = min_window_index[1] == (len(matrix)-1)
in_topleft = (min_window_index[0] <= mid) and (min_window_index[1] <= mid)
in_topright = (min_window_index[0] <= mid) and (min_window_index[1] >= mid)
in_bottomleft = (min_window_index[0] >= mid) and (min_window_index[1] <= mid)
in_bottomright = (min_window_index[0] >= mid) and (min_window_index[1] >= mid)
if not is_top and\
matrix[min_window_index[0]-1][min_window_index[1]] < min_window_val:
# Look at the value one row above minimum
return recursive_call_matrix(in_topleft, in_topright, in_bottomleft,\
mid, len(matrix[0]))
elif not is_bottom and\
matrix[min_window_index[0]+1][min_window_index[1]] < min_window_val:
# Look at the value one row below minimum
return recursive_call_matrix(in_topleft, in_topright, in_bottomleft,\
mid, len(matrix[0]))
elif not is_left and\
matrix[min_window_index[0]][min_window_index[1]-1] < min_window_val:
# Look at the value one column left of minimum
return recursive_call_matrix(in_topleft, in_topright, in_bottomleft,\
mid, len(matrix[0]))
elif not is_right and\
matrix[min_window_index[0]][min_window_index[1]+1] < min_window_val:
# Look at the value one one column right of minimum
return recursive_call_matrix(in_topleft, in_topright, in_bottomleft,\
mid, len(matrix[0]))
else:
return True
def recursive_call_matrix(in_topleft, in_topright, in_bottomleft,\
in_bottomright, mid, rownums):
quadrants = [in_topleft, in_topright, in_bottomleft, in_bottomright]
row_splices = [(0, mid+1), (0, mid+1), (mid, rownums), (mid, rownums)]
col_splices = [(0, mid+1), (mid, rownums), (0, mid+1), (mid, rownums)]
for (quadrant, row_splice, col_splice) in\
zip(quadrants, row_splices, col_splices):
rec_matrix = []
if quadrant:
for row in matrix[row_splice[0]:row_splice[1]]:
rec_matrix.append(row[col_splice[0]:col_splice[1]])
if local_min(rec_matrix):
return True
return False
a = [[5, 4, 3, 4], [2, 1, 0, 1], [1, 2, 3, 4], [5, 6, 7, 8]]
print local_min(a)
b = [[0]*4]*4
print local_min(b)
|
cd73a1f2faa6aa7c4c7f39a12133b1a34f45ad81 | zhihao0040/CodingPractice | /sort/InsertionSort/insertionSort.py | 1,308 | 4.09375 | 4 | import sys # to get command line arguments
sys.path.append("C:/Users/61491/Desktop/Youtube/Code/CodingPractice/sort")
import sortAuxiliary
# print(sys.path)
# print(len(sys.path))
fileName = sys.argv[1]
fileDataTuple = sortAuxiliary.getFileData(fileName)
# print(fileDataTuple)
# Insertion Sort
j = 0
key = 0
for i in range(1, fileDataTuple[0]):
j = i - 1
key = fileDataTuple[1][i]
while (j >= 0 and fileDataTuple[1][j] > key):
fileDataTuple[1][j + 1] = fileDataTuple[1][j]
j -= 1
fileDataTuple[1][j + 1] = key
# insertion sort is basically saying
# "hey we have sorted the first x elements/cards, now looking at my x + 1th element/card
# ask myself, where should I put it between my first x elements.
# Imagine having a 1,2,5,7 in your hand and now you are dealt a 4, you will scan through your cards
# and realize, 2 is biggest number smaller than 4, that's where you will put it.
# Since it is already sorted, the first number you find that is smaller than the number you want to insert is the
# biggest number smaller than the 'key'"
sortAuxiliary.writeToFile("insertionSortPyOutput.txt", fileDataTuple)
# print(myTextList)
# f = open("selectionSortPyOutput.txt", "w")
# for i in range(numOfElems):
# f.write(myTextList[i] + "\n")
|
e95ce9ca229634753a9e4815b556d56b6d1e6d84 | joemac51/expense_tracker | /main.py | 597 | 3.78125 | 4 | import matplotlib.pyplot as plt
from random import randint
def main():
total = 1000
monthly_total = []
net_income = 0
months = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
for i in range(12):
income = randint(800,1000)
bills = randint(800,1050)
net_income += (income - bills)
monthly_total.append(total + net_income)
plt.xticks([i for i in range(12)],months)
plt.plot([i for i in range(12)],monthly_total)
plt.show()
main() |
2ce9b6b91689544425656cf62e63a1db0fa6c804 | EkajaSowmya/SravanClass | /Oct5/PythonOperators/ArithmeticOperators.py | 482 | 4.0625 | 4 | a = 8
b = 2
add = a + b
sub = a - b
mul = a * b
div = a / b
mod = a % b
pow = a ** b
print("addition of {0} and {1} is {2}" .format(a, b, add))
print("subtraction of {0} and {1} is {2}" .format(a, b, sub))
print("multiplication of {0} and {1} is {2}" .format(a, b, mul))
print("division of {0} and {1} is {2}" .format(a, b, div))
print("modulus of {0} and {1} is {2}" .format(a, b, mod))
print("power of {0} and {1} is {2}" .format(a, b, pow))
#print(add, sub, mul, div, mod, pow)
|
3a1566cb54285e6f282a6e871ec37ff22caba743 | EkajaSowmya/SravanClass | /conditionalStatements/ifStatement.py | 295 | 4.25 | 4 | n1 = int(input("enter first number"))
n2 = int(input("enter second number"))
n3 = int(input("enter third number"))
if n1 > n2 and n1 > n3:
print("n1 is largest", n1)
if n2 > n3 and n2 > n3:
print("n2 is largest number", n2)
if n3 > n1 and n3 > n2:
print("n3 is largest number", n3)
|
84b07291c22afde33416f88cde4351fb0d601b97 | EkajaSowmya/SravanClass | /MyworkSpace/sqrtOfNumber.py | 662 | 3.984375 | 4 | import math # this function will import only to this file
x = math.sqrt(25)
print(x)
#math round up to nearest number..
# between 2.1 to 2.4 will be round upto to 2
# between 2.5 to 2.9 will be round upto to 3
print(math.floor(2.9)) #floor func will always rounds up to least value
print(math.ceil(2.2)) #ceil func will always rounds upto to highest value
print(math.pow(3, 2))
print(math.pi)
print(math.e)
#to print the value of entered expression 1+2+3-2=4
result = eval(input("enter the expression")) #using eval func
print(result)
"""command line argument not working for me
import sys
x = int(sys.argv[1])
y = int(sys.argv[2])
z = x + y
print(z)"""
|
b05456fa275f9e3df3f2d381607ee3efbd3d2fa8 | EkajaSowmya/SravanClass | /conditionalStatements/forLoopDemo/assign3.py | 321 | 4.0625 | 4 | """1.WAP to print the following pattern below by skipping even number rows
* * * * *
* * *
*
"""
rows = int(input("Enter the number of rows: "))
for i in reversed(range(0, rows+1)):
for j in range(0, i+1):
if i % 2 == 0:
print("*", end=' ')
else:
print(end=' ')
print() |
4cd5b2b9b4c6764e849cb01e653b9c7de4e23545 | fredcallaway/hci | /python/gui.py | 3,972 | 3.703125 | 4 | #!/usr/bin/python
"""Gui is a Tkinter Entry object cmd line interface coupled with a Tkinter Canvas object
for display and Text object for history. The cmd line accepts natural language input
and the Canvas serves as the graphical interface. """
from Tkinter import *
"""
class ObjInfo:
def __init__(self, id, name, color, width, height):
self.id = id
self.name = name
self.color = color
self.width = width
self.height = height
"""
class Gui:
def __init__(self, width=400, height=400):
self.canvasWidth = width
self.canvasHeight = height
self.Wcenter = self.canvasWidth/2
self.Hcenter = self.canvasHeight/2
self.window = Tk()
self.canvas = Canvas(self.window, width = self.canvasWidth, height = self.canvasHeight) #canvas widget
self.canvas.pack() #arranges window components in a certain way. Alternatively, can use grid
self.objectList = []
def oval(self,name,color="cyan",Xdiam=120,Ydiam=80):
halfX=Xdiam/2
halfY=Ydiam/2
ovalId = self.canvas.create_oval(self.Wcenter-halfX,self.Hcenter-halfY,self.Wcenter+halfX,self.Hcenter+halfY,fill=color,tag=name)
self.objectList.append(ovalId)
self.canvas.update()
def circle(self, name, color="green", diameter=80):
radius = diameter/2
circleId = self.canvas.create_oval(self.Wcenter - radius, self.Hcenter - radius, self.Wcenter+ radius, self.Hcenter + radius, fill=color, tag=name)
self.objectList.append(circleId)
self.canvas.update()
def rectangle(self,name,color="orange",sideX=120,sideY=80):
halfX=sideX/2
halfY=sideY/2
rectID = self.canvas.create_rectangle(self.Wcenter-halfX,self.Hcenter-halfY,self.Wcenter+halfX,self.Hcenter+halfY,fill=color,tag=name)
self.objectList.append(rectID)
self.canvas.update()
def square(self, name, color="red",side=80):
radius = side/2
squareID = self.canvas.create_rectangle(self.Wcenter - radius, self.Hcenter - radius, self.Wcenter + radius, self.Hcenter + radius, fill=color, tag=name)
self.objectList.append(squareID)
self.canvas.update()
def changeColor(self,name,color):
self.canvas.itemconfig(name,fill=color)
self.canvas.update()
#positions object A next to object B, on the right by default
def positionNextTo(self,nameA,nameB,where="right"):
acoord = self.canvas.coords(nameA)
bcoord = self.canvas.coords(nameB)
wha = (acoord[2]-acoord[0])/2 #half-width
hha = (acoord[3]-acoord[1])/2 #half-height
wcb = (bcoord[2]-bcoord[0])/2 + bcoord[0] #center width
hcb = (bcoord[3]-bcoord[1])/2 + bcoord[1] #center height
if where=='right':
self.canvas.coords(nameA,bcoord[2],hcb-hha,bcoord[2]+2*wha,hcb+hha)
elif where=='left':
self.canvas.coords(nameA,bcoord[0]-2*wha,hcb-hha,bcoord[0],hcb+hha)
elif where=='below':
self.canvas.coords(nameA,wcb-wha,bcoord[3],wcb+wha,bcoord[3]+2*hha)
elif where=='above':
self.canvas.coords(nameA,wcb-wha,bcoord[1]-2*hha,wcb+wha,bcoord[1])
else:
print "I don't know that position!"
self.canvas.update()
def moveExactly(self,name,dx,dy):
coord = self.canvas.move(name,dx,dy)
self.canvas.update()
#for moving abstractly
def move(self,name,dir):
dx = self.canvasWidth*0.1
dy = self.canvasHeight*0.1
if dir=='right':
self.canvas.move(name,dx,0)
elif dir=='left':
self.canvas.move(name,-dx,0)
elif dir=='up':
self.canvas.move(name,0,dy)
elif dir=='down':
self.canvas.move(name,0,-dy)
else:
print "I don't understand that direction!"
def hide(self,name):
self.canvas.itemconfig(name,state=HIDDEN)
self.canvas.update()
def unhide(self,name):
self.canvas.itemconfig(name,state=NORMAL)
#bring to top so the user can see it
#self.canvas.tag_raise(name) #?? do we want to do it this way
self.canvas.update()
def setBackground(self,color='white'):
self.canvas.config(background=color)
self.canvas.update()
def layer(self,name,upordown,of=None):
if of==None:
if upordown=='ab'
self.canvas.tag_raise(name)
self.canvas.update()
else:
print "I don't know how to do that yet."
|
9c8ff15b91ab3900f5007c33f615ccc06a50f740 | miljimo/pymvvm | /mvvm/argsvalidator.py | 796 | 3.703125 | 4 |
class ArgsValidator(object):
'''
@ArgValidator : this validate the argument given to make sure
that unexpected argument is given.
'''
def __init__(self,name, expected_args:list):
if(type(expected_args) != list):
raise TypeError("@ArgValidator: expecting a first object of the variable names expected.");
self.__expected_args = expected_args
self.__Name = name;
@property
def Name(self):
return self.__Name;
@property
def Args(self):
return self.__expected_args;
def Valid(self, **kwargs):
for key in kwargs:
if( key in self.__expected_args) is not True:
raise ValueError("{1} : Unknown '{0}' argument provided".format(key, self.Name))
return True;
|
86f5185710ab26a4789b844911a16e8399444ead | vivinraj/python4e | /ex_08/ex_08_05.py | 314 | 3.96875 | 4 | fname = input("Enter file name: ")
fh = open(fname)
count = 0
words=list()
for line in fh:
words=line.split()
if len(words)>1 :
if words[0] != 'From' :
continue
else:
word=words[1]
print(word)
count=count+1
print("There were", count, "lines in the file with From as the first word")
|
fe84ca931af6ee9ebce2b0d4013b01ea42275728 | crystal2001/U4Lesson5 | /problem5.py | 420 | 3.9375 | 4 | from turtle import *
bean = Turtle()
bean.color("black")
bean.pensize(5)
bean.speed(9)
bean.shape("turtle")
def drawStar():
for x in range(5):
bean.forward(50)
bean.left(144)
def row():
for x in range(3):
drawStar()
bean.penup()
bean.forward(70)
bean.pendown()
for y in range(4):
row()
bean.penup()
bean.backward(210)
bean.right(90)
bean.forward(60)
bean.left(90)
bean.pendown()
mainloop()
|
22377fd49f81c618e0d106af62e713383c03ac44 | soldierloko/Fiap | /Sprint1/Socket_IP.py | 218 | 3.8125 | 4 | import socket
resp ='S'
while (resp == 'S'):
url = input("DIgite um URL: ")
ip=socket.gethostbyname(url)
print("O IP referente à URL informada é: ", ip)
resp=input("Digite <S> para continuar: ").upper |
2d2deb268503beaefa09a399ea35fab09deaa86c | rahulremanan/akash_ganga | /src/create_video.py | 1,949 | 3.78125 | 4 | """
Dependencies:
pip install opencv - python
pngs_to_avi.py
Makes all the PNGs from one dir into a video .avi file
usage: pngs_to_avi.py [-h] [-d] png_dir
Author: Avi Vajpeyi and Rahul Remanan
"""
import sys
import argparse
import glob
import cv2
import os
def make_movie_from_png(png_dir, delete_pngs=False):
"""
Takes PNG image files from a dir and combines them to make a movie
:param png_dir: The dir with the PNG
:return:
"""
vid_filename = png_dir.split("/")[-1] + ".avi"
vid_filepath = os.path.join(png_dir, vid_filename)
images = glob.glob(os.path.join(png_dir, "*.png"))
if images:
frame = cv2.imread(images[0])
height, width, layers = frame.shape
video = cv2.VideoWriter(vid_filepath, -1, 25, (width, height))
for image in images:
video.write(cv2.imread(image))
video.release()
if delete_pngs:
for f in images:
os.remove(f)
return True
return False
def main():
"""
Takes command line arguments to combine all the PNGs in dir into a .avi
Positional parameters
[STRING] png_dir: the dir containing the png files
Optional parameters
[BOOL] delete: to delete the PNG files once converted into a video
:return: None
"""
parser = argparse.ArgumentParser(description='Process PNG files.')
# Positional parameters
parser.add_argument("png_dir", help="dir where png files located")
# Optional parameters
parser.add_argument("-d", "--delete",
help="delete PNG files after .avi creation",
action="store_true")
args = parser.parse_args()
if os.path.isdir(args.fits_dir):
make_movie_from_png(png_dir=args.png_dir,
delete_pngs=args.delete)
else:
print("Error: Invalid png dir")
sys.exit(1)
pass
if __name__ == "__main__":
main()
|
bb6d7d12aef583ea46f13c948dc52c61416225ac | yuyaxiong/interveiw_algorithm | /剑指offer/表示数值的字符串.py | 1,361 | 3.8125 | 4 | """
请实现一个函数用来判断字符串是否表示数值(包括:整数和小数)。
例如,字符串“+100”、“5e2”、“-123”,"3.1416"及“-1E-16”都
表示数值,但“12e”,"la3.14","1.2.3", '+-5'及’12e+5.4’
"""
class Solution(object):
def is_numeric(self, n):
num_str = [str(i) for i in range(1, 11)]
if len(n)<=0:
return False
if n[0] in ['+', '-']:
n = n[1:]
if n[0] == '.':
n = n[1:]
for num in n:
if num not in num_str:
return False
else:
if 'e' in n or 'E' in n:
n_list = n.split('e') if 'e' in n else n.split('E')
front, end = n_list[0], n_list[1]
for i in front:
if i not in num_str + ['.']:
return False
if len(end) == 0:
return False
if end[0] in ['+', '-']:
end = end[1:]
for i in end:
if i not in num_str:
return False
else:
for i in n:
if i not in num_str:
return False
return True
if __name__ == "__main__":
s = Solution()
print(s.is_numeric('12e+5.4')) |
f2f78e6d9900affeec2f38188471d95f25ed009a | yuyaxiong/interveiw_algorithm | /LeetCode/二叉树/652.py | 981 | 3.90625 | 4 | # Definition for a binary tree node.
# 652. 寻找重复的子树
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def findDuplicateSubtrees(self, root: Optional[TreeNode]) -> List[Optional[TreeNode]]:
if root is None:
return []
self.subtree_dict = dict()
self.result = []
self.traverse(root)
return self.result
def traverse(self, root):
if root is None:
return "#"
left, right = self.traverse(root.left), self.traverse(root.right)
subtree = left + "," + right + "," + str(root.val)
if self.subtree_dict.get(subtree) is None:
self.subtree_dict[subtree] = 1
else:
self.subtree_dict[subtree] += 1
if self.subtree_dict.get(subtree) == 2:
self.result.append(root)
return subtree |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.