blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
22e1556e651dbc2189aca730e65446ce7640c33b | leo-it/ejercicios-python-curso2020 | /ejercicios para entregar/ejerciciospyborrador.git/intro/hipoteca2.py | 621 | 3.515625 | 4 |
tasa = 0.05
saldo = 500000
pagoMensual = 2684.11 #mensual
totalPagado = 0.0
mes = 0
pagoExtra = 1000
while mes < 12:
saldo = saldo * (1+ tasa/12) - pagoMensual -pagoExtra
totalPagado = pagoMensual + totalPagado + pagoExtra
mes = mes + 1
print(f'Total Pagado: ${round(totalPagado, 2)} en el mes: {mes}')
while 0 < saldo :
saldo = saldo * (1+ tasa/12) - pagoMensual
totalPagado = pagoMensual +totalPagado
mes = mes + 1
print(f'Total Pagado: ${round(totalPagado, 2)} en el mes: {mes}')
print('Total Pagado', round(totalPagado, 2))
print(f"meses {mes}") |
4d02d9af5ebf1db8a65d3406df07c150c89d9c89 | leo-it/ejercicios-python-curso2020 | /ejercicios para entregar/ejerciciospyborrador.git/intro/vocales.py | 115 | 3.546875 | 4 | cadena = "Ejemplo con for"
for c in cadena:
f= cadena.split()
a= f[-1:]
print('caracter:', c, a) |
a443fdb4a4c5ccbd37ca65c518247ae35ce5ab4c | philthebeancounter/python | /holplanclass.py | 3,470 | 3.859375 | 4 | from datetime import date
from datetime import timedelta
from datetime import datetime
#def employee_entitlement_irreg_hours(result,company_entitlement):
#inputs
data=open('data.txt','a')
name_input = raw_input("name> ")
company_entitlement = input ("Annual entitlement >")
bh1 = date(2017,1,2)
bh2 = date(2017,4,14)
bh3 = date(2017,4,17)
bh4 = date(2017,5,1)
bh5 = date(2017,5,29)
bh6 = date(2017,8,28)
bh7 = date(2017,12,25)
bh8 = date(2017,12,26)
bank_holidays = [bh1,bh2,bh3,bh4,bh5,bh6,bh7,bh8]
#calculates hours per week and no of days workedk
#print "Hours per week", Hours
#print "No of days worked", Days_worked
#print "daily hours",Daily_hours
#bank holidays falling in working pattern
#bh_to_take = []
##for i in bank_holidays:
# day = i.weekday()
# if day==0 and Contracted_hours['Monday'] > 0:
# bh_to_take.append(i)
# elif day==1 and Contracted_hours['Tuesday'] > 0:
# bh_to_take.append(i)
# elif day == 2 and Contracted_hours['Wednesday'] > 0:
# bh_to_take.append(i)
# elif day == 3 and Contracted_hours['Thursday'] > 0:
# bh_to_take.append(i)
# elif day == 4 and Contracted_hours['Friday'] > 0:
# bh_to_take.append(i)
# elif day == 5 and Contracted_hours['Saturday'] > 0:
# bh_to_take.append(i)
# elif day == 6 and Contracted_hours['Sunday'] > 0:
# bh_to_take.append(i)
#print bh_to_take
#Hours = 0
class Employee(object):
def hours(self,uninque_daily_hours_count):
#Daily_hours = []
#self.Hours = Hours
self.uninque_daily_hours_count= uninque_daily_hours_count
Days_worked = 0
dw = 0
for i,v in self.Contracted_hours.iteritems():
self.Hours = self.Hours + v
Days_worked = Days_worked + dw
if v == 0:
dw = 0
else:
dw = 1
if v > 0:
self.Daily_hours.append(v)
#test whether the working week is reguar hours or irregular hours
uninque_daily_hours = set(self.Daily_hours)
self.uninque_daily_hours_count = len(uninque_daily_hours)
print uninque_daily_hours_count
if self.uninque_daily_hours_count == 1:
print "regular hours"
else:
print "irreguar hours"
return self.Hours,self.uninque_daily_hours_count
def __init__(self,name,company_entitlement):
Hours = 0
self.name = name
self.company_entitlement = company_entitlement
self.Hours = Hours
self.Daily_hours = []
self.Contracted_hours = {'Monday':7,'Tuesday':8.5,'Wednesday':8.5,'Thursday':8.5,'Friday':8.5,'Saturday':0,'Sunday':0}
#def add_hol(self,days):
#self.hol_allowance = self.hol_allowance - days
def employee_entitlement_irreg_hours(self):
#Hours = employee.hours()
#self.Hours = Hours
#self.company_entitlement = company_entitlement
return self.Hours * self.company_entitlement / 5.0 + self.uninque_daily_hours_count
#print employee.name
#data.write(employee.name)
#data.write(str(employee.hol_allowance))
#print employee.hol_allowance
f = open('import.txt',"r")
line = f.readline()
while line:
print line
line = f.readline()
f.close()
employee = Employee(name_input,company_entitlement)
print employee.name
print employee.Contracted_hours
print "hours", employee.hours(0)
print "class calculation", employee.employee_entitlement_irreg_hours()
|
8e0cca73aae903ff39b22bd14757374ca134b478 | marykamala/471 | /stringstask.py | 656 | 3.609375 | 4 | data="""
1.Forward indexing --->0 1 2 3 4 5 length
2.backward indexing(or)negative indexing
-1 -2 -3 -4 -5 -6 length of the string
a="good afternoon all"
"""
'''l=[1,22,36,25,663,265,145,2567,36]
output=[]
count=0
for i in l:
if len(str(i))==2:
output.append(i)
count+=1
avg=sum(output)/count
print(avg)'''
'''l=["srinivas","viswanth","lucky"]
print(min(l))'''
'''l=["srinivas","viswanth","lucky"]
length=[]
for i in l:
length.append(len(i))
print(length)
max_len=max(length)
print(max_len)
for i in l:
if max_len==len(i):
print(i)'''
l="A P S S D C"
s=l.replace()
print(s)
|
bdeab6a046d4236f6dd006dd5c44bdcdf62bf029 | amigojapan/amigojapan.github.io | /8_basics_of_programming/fruits.py | 580 | 4.71875 | 5 | fruits=["banana","apple","peach","pear"] # create a list
print(fruits[0]) # print first element of list
print(fruits[3]) # print last element
print("now reprinting all fruits")
for fruit in fruits: # loops thru the fruits list and assigns each values to th>
print(fruit) # prints current "iteration" of the fruit
print("now reprinting all fruits in reverse")
fruits.reverse() # reverses the list
for fruit in fruits:
print(fruit)
print("now printing fruits in alphabetical order")
fruits.sort() # sorts the list in alphabetical order
for fruit in fruits:
print(fruit)
|
a0c1a127f9d5ae377ea3d811f03e824b0d8ad0e3 | sshivashankar/Python | /aksing questions.py | 236 | 3.828125 | 4 | print("How old are you ?", end =' ')
age = input()
print("How tall are you?", end =' ')
height = input()
print("What do you like?", end=' ')
like = input()
print(f'you are {age} years old, {height} cm tall and you like {like} ') |
c087789647cad25fc983acd3bfceee19ab0a507f | Narfin/test_push | /controlFlows.py | 636 | 4.28125 | 4 | # if, elif, else
def pos_neg(n):
"""Prints whether int n is positive, negative, or zero."""
if n < 0:
print("Your number is Negative... But you already knew that.")
elif n > 0:
print("Your number is super positive! How nice.")
else:
print("Zero? Really? How boring.")
my_num = int(input("Enter a number: "))
pos_neg(my_num)
# for
def reverse_str(word):
"""Prints word in reverse"""
print(word[::-1], " lol") # [begin:end:step], in this case reversing word.
my_word = input("Enter a word to flip: ")
reverse_str(my_word)
# while
x = 8
while (x != 0):
print(x)
x -= 1
|
0d479a7cb6765e8f6fcf1f15b9de0eb7debc1f62 | duttmf/Scripts | /table.py | 156 | 3.890625 | 4 | #!/usr/bin/#!/usr/bin/env python
for x in range(1,11):
for y in range(1,11):
z = x * y
print(z, end="\t")
print()
|
a5fedfaa712bd4bde62918f22991523f9275a913 | davaponte/ProjectEuler | /0-50/000036.py | 374 | 3.53125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# 000036.py
#
def IsPalindrome(s):
for k in range(len(s) // 2):
if (s[k] != s[-k -1]):
return False
return True
Suma = 0
for n in range(1, 1000000):
b = str(bin(n))[2:]
if IsPalindrome(b) and IsPalindrome(str(n)):
Suma += n
print(n, b)
print('ANSWER: ', Suma)
|
71327ec9951aa23f76737bcdd4f37cf3affac324 | davaponte/ProjectEuler | /000104.py | 1,420 | 3.5 | 4 | # 000104.py
def Fib():
f0 = 1
yield f0
f1 = 1
yield f1
while True:
f0, f1 = f1, f1 + f0
yield f1
# def IsPandigital(s):
# l = list(s)
# l.sort()
# i = int(''.join(l))
# return 123456789 == i
def IsPandigital(s):
return set(s) == set('123456789')
# rt5 = 5**.5
# def check_first_digits(n):
# def mypow(x, n):
# res=1.0
# for i in range(n):
# res *= x
# # truncation to avoid overflow:
# if res > 1E20:
# res *= 1E-10
# return res
# # this is an approximation for large n:
# F = mypow((1 + rt5) / 2, n) / rt5
# s = '%f' % F
# if IsPandigital(s[:9]):
# print(n)
# return True
#
# a, b, n = 1, 1, 1
# while True:
# if IsPandigital(str(a)[-9:]):
# # Only when last digits are
# # pandigital check the first digits:
# # print('n: ', n)
# if check_first_digits(n):
# break
# a, b = b, a + b
# b = b % 1000000000
# n += 1
n = 0
for f in Fib():
n += 1
# if n < 329468: # 311434: # 272643: # 100583:
# continue
s = str(f)
if IsPandigital(s[-9:]):
print(n)
if IsPandigital(s[:9]):
print('ANSWER: ', n)
break
# 328733
# 329468
# ANSWER: 329468
#
# Process returned 0 (0x0) execution time : 9128.043 s
# Press [ENTER] to continue...
|
c3350f589f4411d1efcc4c4f8515a7f9aea850b1 | davaponte/ProjectEuler | /0-50/000035.py | 545 | 3.859375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# 000035.py
#
import math
def IsPrime(n):
for k in range(2, int(math.sqrt(n)) + 1):
if n % k == 0:
return False
return True
Count = 0
for n in range(2, 1000000):
s = str(n)
AllPrimes = True
for k in range(len(s)):
if not IsPrime(int(s)):
AllPrimes = False
break
# ~ print(s, end=' ')
s = s[1:] + s[0]
if AllPrimes:
# ~ print(n)
Count += 1
print('ANSWER: ', Count)
|
ed8ffbbf78433477812990eed3adbc402a7c65ae | davaponte/ProjectEuler | /0-50/000037.py | 704 | 3.8125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# 000037.py
#
import math
def IsPrime(n):
if (n == 1):
return False
for k in range(2, int(math.sqrt(n)) + 1):
if n % k == 0:
return False
return True
Acum = 0
limit = 11 #Dice el problema que solo hay 11
n = 11 #2, 3, 5 y 7 no cuentan
while True:
s = str(n)
AllPrimes = True
for k in range(len(s)):
r = s[k:]
l = s[:-k - 1]
if not IsPrime(int(r)) or ((l != '') and not IsPrime(int(l))):
AllPrimes = False
if AllPrimes:
Acum += n
limit -= 1
if (limit == 0):
break
n += 1
print('ANSWER: ', Acum)
|
f003d77993b9579e51df889fa49f5c08a45572f4 | davaponte/ProjectEuler | /0-50/000041.py | 704 | 3.84375 | 4 | #!/usr/bin/env python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# untitled.py
#
import math
from itertools import permutations as p
def IsPrime(n):
for k in range(2, int(math.sqrt(n)) + 1):
if n % k == 0:
return False
return True
Ans = 0
for k in range(9, 2, -1):
l = [(x + 1) for x in range(k)]
P = p(l)
ll = list(P)
ll.sort(reverse=True)
# ~ print(ll)
# ~ print(len(ll))
for i in ll:
s = str(i).replace('(', '').replace(')', '').replace(', ', '')
# ~ print(s, IsPrime(int(s)))
if IsPrime(int(s)):
Ans = int(s)
break
if Ans > 0:
break
print('ANSWER: ', Ans)
|
8320d0ff84c5e31926cf209eed93f4cf8d77cc9e | tsc9/SEclass | /Exceptions.py | 1,443 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 8 15:53:04 2019
@author: ttc
"""
# Case 1, an exception is caught
#%%
try:
items = ['a', 'b']
third = items[2]
print("This won't print")
except IndexError:
print("Index out of bound")
print("continuing")
# Case 2, a division by zero exception won't caught by IndexError
#%%
try:
x = 5
y = x/0
print("This won't print, either")
except IndexError:
print("Division by zero is handled by wrong exception")
print("continuing again")
# Case 3, a division by zero is caught correctly
#%%
try:
x = 5
y = x/0
print("This won't print, either")
except ZeroDivisionError:
print("Division by zero is handled correctly")
print("continuing again")
# Case 4, a division by zero is handled universaly
#%%
try:
x = 5
y = x/0
print("This won't print, either")
except Exception as e:
print("Division by zero is handled by a universal handler")
print(e)
print("continuing again")
# Case 5 more control on exceptions
#%%
try:
y = 5 / 0
except Exception as e:
print ("Exception ",e)
else:
print ("y is", y)
finally:
print ("executing finally clause")
# User defined exceptions
#%%
class MyError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr("MyError")
try:
raise MyError(4)
except MyError as e:
print ('My exception occurred, value:', e) |
a557323756f431312e585b84c9660d987bb5caeb | bell2lee/sw-proj-2-a | /fibonacci_임성원.py | 695 | 3.765625 | 4 | import time
#재귀함수를 이용한 방법
def fibo(num):
if num ==1 or num ==2:
return 1
else:
return fibo(num-1) + fibo(num-2)
#반복
def iterfibo(num):
if num == 0:
return 0
elif num == 1:
return 1
else:
a,b = 1,1
for i in range(num-1):
a,b = b,a+b
return a
nbr = 1
while (nbr>0):
nbr = int(input("Enter a number: "))
ts = time.time()
fibonumber = iterfibo(nbr)
ts = time.time() - ts
print("IterFibo(%d)=%d, time %.6f" %(nbr, fibonumber, ts))
ts = time.time()
fibonumber = fibo(nbr)
ts = time.time() - ts
print("Fibo(%d)=%d, time %.6f" %(nbr, fibonumber, ts))
|
d7fa96cee55aa9517c3ab5d02e30dc72f57b7d3b | nicholan/pygame-space-invaders | /space-invaders/bullet.py | 1,608 | 3.90625 | 4 | import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
def __init__(self, game):
"""Class for single bullet."""
super().__init__()
self.screen = game.screen
self.settings = game.settings
self.color = self.settings.bullet_color
self.speed = self.settings.bullet_speed
# Create bullet rect at (0, 0) and then set corrent position.
self.rect = pygame.Rect(0, 0, self.settings.bullet_width, self.settings.bullet_height)
self.rect.midtop = game.player.rect.midtop
# Store bullet's position as float
self.y = float(self.rect.y)
class BulletGroup:
def __init__(self, game):
"""A class to group bullets fired from the ship."""
self.bullets = pygame.sprite.Group()
self.screen = game.screen
self.settings = game.settings
self.player = game.player
def _create_bullet(self):
"""Create a new bullet and add it to the bullets group."""
new_bullet = Bullet(self)
self.bullets.add(new_bullet)
def _update(self):
"""Move the bullet up the screen."""
for bullet in self.bullets:
bullet.y -= bullet.speed
bullet.rect.y = bullet.y
# Delete out of bounds bullets.
if bullet.rect.bottom <= 0:
self.bullets.remove(bullet)
def draw_bullet(self):
"""Draw bullet to the screen"""
for bullet in self.bullets.sprites():
pygame.draw.rect(bullet.screen, bullet.color, bullet.rect)
|
24cecbe50a1744d99d40895ac146957a1c05f1ac | paulbible/tescas | /source/embedding_tools.py | 9,054 | 3.640625 | 4 | """
A tools file to collect some reusable embedding functions
"""
import numpy as np
from collections import defaultdict
import os
import nltk_tools
import string
import math
def load_embeddings(filename):
"""
This function loads the embedding from a file and returns 2 things
1) a word_map, this is a dictionary that maps words to an index.
2) a matrix of row vectors for each work, index the work using the vector.
:param filename:
:return: word_map, matrix
"""
count = 0
matrix = []
word_map = {}
with open(filename, encoding="utf8") as f:
# with open(filename) as f:
for line in f:
line = line.strip()
items = line.split()
word = items[0]
rest = items[1:]
# print("word:", word)
word_map[word] = count
count += 1
rest = list(map(float, rest))
matrix.append(rest)
matrix = np.array(matrix)
return word_map, matrix
def reduce_sum_word_list(words, word_map, matrix):
"""
Take a list of words and summarize them as a vector using 'mean'.
returns a numpy vector
:param words:
:param word_map:
:param matrix:
:return:
"""
vec = np.zeros(matrix.shape[1])
for word in words:
word = word.lower()
if word in word_map:
index = word_map[word]
vec = vec + matrix[index]
return vec
def reduce_sum_word_list_weighted(words, word_map, matrix, word_weight_map):
"""
Take a list of words and summarize them as a vector using 'mean'.
returns a numpy vector
:param words:
:param word_map:
:param matrix:
:param word_weight_map:
:return:
"""
vec = np.zeros(matrix.shape[1])
for word in words:
word = word.lower()
if word in word_map:
index = word_map[word]
if word in word_weight_map:
vec = vec + matrix[index]*word_weight_map[word]
else:
vec = vec + matrix[index]
return vec
def cossim(vA, vB):
"""
Calcuate the cosine similarity value.
Returns the similarity value, range: [-1, 1]
:param vA:
:param vB:
:return: similarity
"""
return np.dot(vA, vB) / (np.sqrt(np.dot(vA, vA)) * np.sqrt(np.dot(vB, vB)))
def calc_similar_values(word_map, matrix, query):
"""
Claculate the similarity of every word vector with the query word vector
:param word_map:
:param matrix:
:param query:
:return:
"""
if query not in word_map:
print(query, "not found")
return None
values = []
num_rows = matrix.shape[0]
vector = matrix[word_map[query]]
for i in range(num_rows):
test_vector = matrix[i]
values.append(cossim(test_vector, vector))
return values
def search_dissimilar(word_map, matrix, query, threshold=-0.90):
"""
Search through the matrix and get words that are similar to the give word
using the embedding vectors.
:param word_map:
:param matrix:
:param query:
:param threshold:
:return:
"""
if query not in word_map:
print(query, "not found")
return None
words = ['' for i in range(len(word_map))]
for word in word_map:
words[word_map[word]] = word
num_rows = matrix.shape[0]
vector = matrix[word_map[query]]
for i in range(num_rows):
test_vector = matrix[i]
if cossim(test_vector, vector) <= threshold:
print(words[i])
def search_similar(word_map, matrix, query, threshold=0.95):
"""
Search through the matrix and get words that are similar to the give word
using the embedding vectors.
:param word_map:
:param matrix:
:param query:
:param threshold:
:return:
"""
if query not in word_map:
print(query, "not found")
return None
words = ['' for i in range(len(word_map))]
for word in word_map:
words[word_map[word]] = word
num_rows = matrix.shape[0]
vector = matrix[word_map[query]]
for i in range(num_rows):
test_vector = matrix[i]
if cossim(test_vector, vector) >= threshold:
print(words[i])
def calculate_tf_weightings(input_folder):
sentence_db_temp = []
file_labels_temp = []
idf_counts = defaultdict(int)
# Document frequency loop
files_to_process = os.listdir(input_folder)
for filename in files_to_process:
full_filename = os.path.join(input_folder, filename)
with open(full_filename, encoding='utf-8', errors='ignore') as f:
data = f.read()
# get all sentences form the file
current_sentences = nltk_tools.tokenize(data, 'sentence')
for sentence in current_sentences:
sentence_db_temp.append(sentence)
file_labels_temp.append(filename)
# remove newlines
sentence = nltk_tools.clean_sentence(sentence)
word_list = nltk_tools.tokenize(sentence, 'word')
for word in set(word_list):
# add 1 for each sentence where the sentence is found.
idf_counts[word.lower()] += 1
idf_weights = {}
doc_count = len(sentence_db_temp)
for word in idf_counts:
# create a weight for very word that reflects how many sentences it appears in
# Words appearing in nearly every sentence will be near 0. Words that are uncommon get higher weighting.
idf_weights[word] = math.log(doc_count / idf_counts[word])
return idf_weights, doc_count
def parse_weight_map(filename):
weight_map = {}
with open(filename, encoding='utf-8', errors='ignore') as f:
for line in f:
line = line.strip()
if len(line) == 0:
continue
parts = line.split('\t')
# try:
# weight_map[parts[0]] = float(parts[1])
# except:
# print(line)
# print(parts)
# input()
return weight_map
def write_weight_map(filename, weight_map):
with open(filename, 'w', encoding='utf-8') as fout:
for word in weight_map:
outstr = word + '\t' + str(weight_map[word]) + '\n'
fout.write(outstr)
def build_sentence_database(input_folder):
sentence_db = []
file_labels = []
idf_counts = defaultdict(int)
# Document frequency loop
files_to_process = os.listdir(input_folder)
for filename in files_to_process:
full_filename = os.path.join(input_folder, filename)
# attempting to process a directory gives an error.
if os.path.isdir(full_filename):
continue
with open(full_filename, encoding='utf-8', errors='ignore') as f:
data = f.read()
# get all sentences form the file
current_sentences = nltk_tools.tokenize(data, 'sentence')
for sentence in current_sentences:
sentence_db.append(sentence)
file_labels.append(filename)
return sentence_db, file_labels
def calculate_sentence_vectors_tfidf(input_folder, weight_map, word_map, matrix):
"""
Maskes some use of these ideas
https://medium.com/analytics-vidhya/tf-idf-term-frequency-technique-easiest-explanation-for-text-classification-in-nlp-with-code-8ca3912e58c3
https://hackernoon.com/finding-the-most-important-sentences-using-nlp-tf-idf-3065028897a3
:param input_folder:
:param weight_map:
:param word_map:
:param matrix:
:return:
"""
sentence_db_raw, file_labels_raw = build_sentence_database(input_folder)
doc_count = len(sentence_db_raw)
sent_vectors_database = [] # database of sentence vectors
sentence_database= [] # database list of processed sentences
sentence_labels = [] # these file names will help identify sentences
# for each sentence
for i in range(doc_count):
sentence = sentence_db_raw[i]
sentence_label = file_labels_raw[i]
sentence = nltk_tools.clean_sentence(sentence)
word_list = nltk_tools.tokenize(sentence, 'word')
word_list = nltk_tools.filter_stopwords_list_to_list(word_list)
# discard any empty sentences (skip them)
if len(word_list) <= 0:
continue
# caculate word vector
sent_vec = reduce_sum_word_list_weighted(word_list, word_map, matrix, weight_map)
# discard sentences that contain no words from the embedding database, not much can be done here.
# examples 'H.R.3' and 'Janiyah'
if np.linalg.norm(sent_vec) < 1e-6:
continue
# add the transformed data to the data storage variables
sentence_database.append(sentence)
sent_vectors_database.append(sent_vec)
# add the filename to a list too
sentence_labels.append(sentence_label)
return sent_vectors_database, sentence_database, sentence_labels
# newline
|
10a144c4b71e34c1bf3680ca0c59f56e3fca6cef | brandonchamba/APITesting | /list1.py | 796 | 3.859375 | 4 | import random
cave_numbers = range(0,20)
caves = []
for i in cave_numbers:
caves.append([]) #create empty list
unvisited_caves = range(0,20)
visited_caves =[0]
unvisited_caves.remove(0)
while unvisited_caves != []:
i = random.choice(visited_caves)
if len(caves[i] ) >=3 :
continue
next_cave = random.choice(unvisited_caves)
caves[i].append(next_cave)
caves[next_cave].append(i)
visited_caves.append(next_cave)
unvisited_caves.remove(next_cave)
for number in cave_numbers:
print number, ":", caves[number]
print '-----'
for i in cave_numbers:
while len(caves[i]) <3 :
passage_to = random.choice(cave_numbers)
caves[i].append(passage_to)
for number in cave_numbers:
print number, ":", caves[number]
print ' --------'
|
4f7d8f04312ca464a475bf7aa297a0b99a3df646 | cmoroexpedia/leetcode | /longest-palindromic-substring/longest_palindromic_substring.py | 6,122 | 3.640625 | 4 | class Solution_Optimal(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
ans = ''
for i in range(len(s)):
palindrome = self.palinDrome(s,i,i)
if len(palindrome)>len(ans):
ans = palindrome
palindrome = self.palinDrome(s,i,i+1)
if len(palindrome)>len(ans):
ans = palindrome
return ans
def palinDrome(self,s,start,end):
while(start>=0 and end<len(s)) and s[start]==s[end]:
start = start-1
end = end+1
return s[start+1:end]
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
longest = ""
longest_size = 0
if len(s) > 0:
longest = s[0]
longest_size = 1
for index, char in enumerate(s):
# print("---------")
# print("current char (s[{}]): ".format(index) + char)
max_possible = min(index,len(s)-index-1)
# print("maximum palindrome size: " + str(max_possible))
for i in range(1,max_possible+1):
current_prefix = s[index-i]
# print("current prefix: " + str(current_prefix))
current_sufix = s[index+i]
# print("current sufix: " + str(current_sufix))
if current_prefix == current_sufix:
palindrome_size = i*2+1
# print("WE HAVE A MATCH OF SIZE: " + str(palindrome_size))
palindrome_str = s[index-i:index] + char + s[index+1:index+i+1]
# print("palindrome: " + palindrome_str)
if palindrome_size > longest_size:
longest_size = palindrome_size
longest = palindrome_str
else:
# print("break")
break
# print("now including the current char...")
max_possible = min(index+1,len(s)-index-1)
# print("maximum palindrome size: " + str(max_possible))
for i in range(1,max_possible+1):
current_prefix = s[index-i+1]
# print("current prefix: " + str(current_prefix))
current_sufix = s[index+i]
# print("current sufix: " + str(current_sufix))
if current_prefix == current_sufix:
palindrome_size = i*2
# print("WE HAVE A MATCH OF SIZE: " + str(palindrome_size))
palindrome_str = s[index-i+1:index+1] + s[index+1:index+i+1]
# print("palindrome: " + palindrome_str)
if palindrome_size > longest_size:
longest_size = palindrome_size
longest = palindrome_str
else:
# print("break")
break
return longest
class Solution_Slow(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
longest = ""
longest_size = 0
if len(s) > 0:
longest = s[0]
longest_size = 1
for index, char in enumerate(s):
# print("---------")
# print("current char (s[{}]): ".format(index) + char)
max_possible = min(index,len(s)-index-1)
# print("maximum palindrome size: " + str(max_possible))
for i in range(1,max_possible+1):
current_prefix = s[index-i:index]
# print("current prefix: " + str(current_prefix))
current_sufix = s[index+1:index+i+1]
# print("current sufix: " + str(current_sufix))
inverted_sufix = current_sufix[::-1]
# print("current inverted sufix: " + str(inverted_sufix))
if current_prefix == inverted_sufix:
palindrome_size = i*2+1
# print("WE HAVE A MATCH OF SIZE: " + str(palindrome_size))
palindrome_str = current_prefix + char + current_sufix
# print("palindrome: " + palindrome_str)
if palindrome_size > longest_size:
longest_size = palindrome_size
longest = palindrome_str
# print("now including the current char...")
max_possible = min(index+1,len(s)-index-1)
# print("maximum palindrome size: " + str(max_possible))
for i in range(1,max_possible+1):
current_prefix = s[index-i+1:index+1]
# print("current prefix: " + str(current_prefix))
current_sufix = s[index+1:index+i+1]
# print("current sufix: " + str(current_sufix))
inverted_sufix = current_sufix[::-1]
# print("current inverted sufix: " + str(inverted_sufix))
if current_prefix == inverted_sufix:
palindrome_size = i*2
# print("WE HAVE A MATCH OF SIZE: " + str(palindrome_size))
palindrome_str = current_prefix + current_sufix
# print("palindrome: " + palindrome_str)
if palindrome_size > longest_size:
longest_size = palindrome_size
longest = palindrome_str
return longest
def stringToString(input):
return input[1:-1].decode('string_escape')
def main():
import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines()
while True:
try:
print("**************************** start *******************************")
line = next(lines)
s = stringToString(line)
print("string to be processed: " + s)
ret = Solution().longestPalindrome(s)
out = (ret)
print(out)
except StopIteration:
break
if __name__ == '__main__':
main()
|
e01f1e15a4adcc69049d8eab44c9270a7206c765 | cmoroexpedia/leetcode | /merge-sorted-array/merge_sorted_array.py | 2,894 | 3.890625 | 4 | import json
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: None Do not return anything, modify nums1 in-place instead.
"""
# make a copy of nums1
nums1_copy = nums1[:m]
# print("nums1_copy: " + str(nums1_copy))
# create pointers to track position for nums1, nums2 and results
nums1_pointer = 0
nums2_pointer = 0
res_pointer = 0
while res_pointer < n+m:
# print("nums1_pointer: " + str(nums1_pointer))
# print("nums2_pointer: " + str(nums2_pointer))
# print("res_pointer: " + str(res_pointer))
if nums1_pointer == m:
# reached the end of nums1; just use nums2 for the remaining iterations
nums1[res_pointer] = nums2[nums2_pointer]
nums2_pointer += 1
res_pointer +=1
continue
if nums2_pointer == n:
# reached the end of nums2; just use nums1 for the remaining iterations
nums1[res_pointer] = nums1_copy[nums1_pointer]
nums1_pointer += 1
res_pointer +=1
continue
if nums1_copy[nums1_pointer] <= nums2[nums2_pointer]:
nums1[res_pointer] = nums1_copy[nums1_pointer]
nums1_pointer += 1
else:
nums1[res_pointer] = nums2[nums2_pointer]
nums2_pointer += 1
res_pointer +=1
def stringToIntegerList(input):
return json.loads(input)
def stringToInt(input):
return int(input)
def integerListToString(nums, len_of_list=None):
if not len_of_list:
len_of_list = len(nums)
return json.dumps(nums[:len_of_list])
def main():
import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines()
while True:
try:
print("********************** start ************************")
line = next(lines)
nums1 = stringToIntegerList(line)
print("nums1: " + str(nums1))
line = next(lines)
m = stringToInt(line)
print("m: " + str(m))
line = next(lines)
nums2 = stringToIntegerList(line)
print("nums2: " + str(nums2))
line = next(lines)
n = stringToInt(line)
print("n: " + str(n))
ret = Solution().merge(nums1, m, nums2, n)
out = integerListToString(nums1)
if ret is not None:
print("Do not return anything, modify nums1 in-place instead.")
else:
print(out)
except StopIteration:
break
if __name__ == '__main__':
main() |
62fe4bd668a1272480da30f00d68a084abdc87eb | cmoroexpedia/leetcode | /container-with-most-water/container_with_most_water.py | 2,617 | 3.6875 | 4 | import json
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
max_area = 0
iterations = 0
i = 0
j = len(height)-1
while i != j:
iterations +=1
print("---")
print("i:" + str(i) + ", j:" + str(j))
print("values: " + str(height[i]) + "," + str(height[j]))
min_height = min(height[i],height[j])
print("min height: " + str(min_height))
print("area = " + str(j-i) + " * " + str(min_height))
area = (j-i)*min_height
print("area = " + str(area))
if area > max_area:
max_area = area
if height[i] < height[j]:
i += 1
else:
j -= 1
print("iterations: " + str(iterations))
return max_area
class Solution_Slow(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
max_area = 0
iterations = 0
for i in range(0,len(height)):
print("------------")
if (len(height) - i) * height[i] <= max_area:
continue
for j in reversed(range(i+1,len(height))):
iterations +=1
print("---")
print("i:" + str(i) + ", j:" + str(j))
print("values: " + str(height[i]) + "," + str(height[j]))
min_height = min(height[i],height[j])
print("min height: " + str(min_height))
print("area = " + str(j-i) + " * " + str(min_height))
area = (j-i)*min_height
print("area = " + str(area))
if area > max_area:
max_area = area
print("iterations: " + str(iterations))
return max_area
def stringToIntegerList(input):
return json.loads(input)
def intToString(input):
if input is None:
input = 0
return str(input)
def main():
import sys
def readlines():
for line in sys.stdin:
yield line.strip('\n')
lines = readlines()
while True:
try:
print("**************************** start *******************************")
line = next(lines)
height = stringToIntegerList(line)
print("height: " + str(height))
ret = Solution().maxArea(height)
out = intToString(ret)
print(out)
except StopIteration:
break
if __name__ == '__main__':
main() |
3648fa2de607161b668429c213516b9acae74047 | ojjang1/learnPython | /python_tutorial/input_3.py | 656 | 3.75 | 4 | ## 주로 형식이 동일한 글들에
## 데이터만 넣어서 완성본을 만들어 주는 경우.
## 매물 정보를 입력해 보자.
street = input("주소 입력 : ")
type = input("종류 입력 : ")
number_of_rooms = int(input("방 갯수 : "))
price = int(input("가격 : "))
print("####################")
print("# #")
print("# 부동산 매물 광고 #")
print("# #")
print("####################")
print("")
print(street, "에 위치한 아주 좋은 ",type, "가 매물로 나왔습니다. 이 ",type,
"는 ", number_of_rooms, "개의 방을 가지고 있으며 가격은", price, "원 입니다")
|
4e667f24a2a46b0145b9bd41c72a44d451047a16 | ojjang1/learnPython | /python_tutorial/testtest.py | 227 | 3.75 | 4 | kg = int(input("물체의 무게를 입력하시오(킬로미터): "))
speed = int(input("물체의 속도를 입력하시오(미터/초): "))
print("물체는", 1/2 * kg * speed**2, "(줄)의 에너지를 가지고 있다.")
|
fc41935c4da6c703d5348afa6df59c0e2710b147 | JacobStephen9999/Bactracking-1 | /Palindrom.py | 1,048 | 3.609375 | 4 | #Time Complexity: O(N2^N) where N is number of elements in staring
# Space Complexity : O(N) where N is number of elemtns stored in stack
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
result = []
if len(s) == None:
return result
def backtrack(s,temp ,start):
def palindrome(s,l,r):
if l ==r:
return True
while l<r:
if s[l]!=s[r]:
return False
l+=1
r-=1
return True
if start == len(s):
result.append(temp[:])
for i in range(start,len(s)):
if (palindrome(s,start,i)) == True:
temp.append(s[start:i+1])
backtrack(s,temp,i+1)
temp.pop()
temp = []
backtrack(s,temp,0)
return result
|
f1d2f6890064cad59bb7ba2d6809090228f964fb | taehyundev/Python_tutorial | /University_study/Example Problem/ex10.py | 391 | 3.609375 | 4 | import turtle
t = turtle.Turtle()
t.shape('classic')
n1 = int(turtle.textinput('입력창', '변1: '))
n2 = int(turtle.textinput('입력창', '변2: '))
n3 = int(turtle.textinput('입력창', '변3: '))
if (n3*n3) == (n2*n2) + (n1 * n1):
t.forward(n1*100)
t.left(90)
t.forward(n2*100)
t.home()
else:
t.write('직각삼각형이 아님.', font=("Arial",10)) |
3583aa47742c4363eddff21bd06febf3a158a0dd | taehyundev/Python_tutorial | /Basic_Grammer/Chapter02/Py02_05.py | 149 | 3.890625 | 4 | for i in range(0, int(input("별찍기 : "))):
print('*' * (i+1))
# *의 갯수를 곱을 통해서 i+1만큼 추가
#Ex ) input = 3
#*
#**
#*** |
d9f5e5facae54a8b8902e84e422d613f02df5c43 | taehyundev/Python_tutorial | /University_study/Tkinter_example/drawing board_ex.py | 766 | 3.828125 | 4 | from tkinter import *
top = Tk()
top.title("Oval을 이용한 그림판")
penc = "blue"
def paint(event):
x1, y1 = (event.x - 1 ), (event.y -1)
x2, y2 = (event.x + 1), (event.y + 1)
cnvs.create_oval( x1, y1, x2,y2, outline=penc, fill=penc)
def redColor():
global penc
penc = "red"
def greenColor():
global penc
penc = "green"
def blueColor():
global penc
penc = "blue"
cnvs = Canvas(top, width=500, height=150)
cnvs.pack()
cnvs.bind("<B1-Motion>",paint)
bt1 = Button(top, text="빨강색", command=redColor)
bt2 = Button(top, text="초록색", command=greenColor)
bt3 = Button(top, text="파란색", command=blueColor)
bt1.pack(side=LEFT, ipadx=50)
bt2.pack(side=LEFT, ipadx=50)
bt3.pack(side=LEFT, ipadx=50)
top.mainloop()
|
b56ded4ed1205e9bb355a71f877ac4dcd4770105 | taehyundev/Python_tutorial | /University_study/Tkinter_example/checkbox.py | 798 | 3.78125 | 4 | from tkinter import *
top = Tk()
top.title("체크박스")
def result():
result = ""
if int(chk1c.get()):
result += "체크박스1 "
if int(chk2c.get()):
result += "체크박스2 "
if int(chk3c.get()):
result += "체크박스3 "
print(result)
lb1['text'] = result
chk1c = IntVar()
chk2c = IntVar()
chk3c = IntVar()
fr = Frame(top)
chk1 = Checkbutton(top, text="체크박스1", variable=chk1c)
chk2 = Checkbutton(top, text="체크박스2", variable=chk2c)
chk3 = Checkbutton(top, text="체크박스3", variable=chk3c)
btn = Button(top, text="제출",command=result)
chk1.grid(row=0, column=1)
chk2.grid(row=0, column=2)
chk3.grid(row=0, column=3)
btn.grid(row=0, column=4)
fr.grid(row=2,column=0)
lb1 = Label(fr,text="")
lb1.grid()
top.mainloop() |
eb716fb202e7e9013195ac37bf5127bf6adfce1f | Fhern1954/Python_Challenge | /PyPoll/main.py | 2,929 | 3.703125 | 4 | #Dependencies
import os
import csv
#Path to collect data from Resources folder
poll_csv = os.path.join('Resources', 'election_data.csv')
votes = []
candidates = []
occurance = []
percentage =[]
#Read in the csv file
with open(poll_csv, 'r') as csvfile:
poll_txt = os.path.join('election_results.txt')
with open(poll_txt, 'w') as datafile:
#Split the data on commas
csvreader = csv.reader(csvfile, delimiter=',')
#remove the header row
csv_header = next(csvreader)
for row in csvreader:
votes.append(row[2])
total_votes = len(votes)
print(" ")
print("Election Results")
print("---------------------------------------------")
print(f'Total Votes: {total_votes}')
print("---------------------------------------------")
#pull list of candidates
for name in votes:
if name not in candidates:
candidates.append(name)
# print(candidates)
#count votes for each candidate
#From "Kite" website https://www.kite.com/python/answers/how-to-count-the-number-of-occurrences-of-an-element-in-a-list-in-python
for x in (candidates):
occurance.append(votes.count(x))
# print(f'{occurance}')
#calculate percentages
total = sum(occurance)
# print(total)
for x in (occurance):
percent = x / total * 100
percentage.append(percent)
# print(f'{percentage}%')
# print("-----------------------------------------------")
#print results
for x in range(len(candidates)):
print(f'{candidates[x]}: {percentage[x]:.3f}% ({occurance[x]})')
print("-------------------------------------------------")
# determine and annouce the winner
win = max(occurance)
winner = (candidates[occurance.index(win)])
print(f'Winner: {winner}')
print("-------------------------------------------------")
#Works!!!!!
# Specify file to write to
# poll_txt = os.path.join('election_results.txt')
# Open the file using "write" mode. Specify the variable to hold the contents
# with open(poll_txt, 'w') as datafile:
# Initialize txt.writer
# Write rows
datafile.write(" \n")
datafile.write("Election Results\n")
datafile.write("---------------------------------------------\n")
datafile.write(f'Total Votes: {total_votes}\n')
datafile.write("---------------------------------------------\n")
for x in range(len(candidates)):
datafile.write(f'{candidates[x]}: {percentage[x]:.3f}% ({occurance[x]})\n')
datafile.write("-------------------------------------------------\n")
datafile.write(f'Winner: {winner}\n')
datafile.write("-------------------------------------------------")
|
dfa356aafc4fb15874999bb4a6eea57e843a4561 | cjoshmartin/AI-algorthims | /utils/priority_queue.py | 864 | 3.609375 | 4 | class priority_queue:
def __init__(self, priority='cost'):
self.queue = []
self.__size = 0
self.priority = priority
def __sorting_agl(self, item):
return item[self.priority]
def __sort(self):
self.queue.sort(key=self.__sorting_agl)
def __change_size(self, beta):
new_size = self.__size + beta
if new_size < 0:
raise Exception('Can not have a size less then 0')
self.__size = new_size
def __get(self):
item = self.queue[0]
del self.queue[0]
return item
def size(self):
return self.__size
def enqueue(self, item):
self.queue.append(item)
self.__change_size(1)
self.__sort()
def dequeue(self):
item = self.__get()
self.__change_size(-1)
self.__sort()
return item
|
34270e6d277d78a053003f18f590adba05ff1381 | cjoshmartin/AI-algorthims | /chapters/ch_5_adversarial_search/alpha_beta_pruning.py | 890 | 3.703125 | 4 | from utils.Node import infinity
from utils.Tree import tree_for_adv_search
def alpha_beta_pruning(tree):
v = max_value(tree, -infinity, infinity)
return v
def max_value(node, alpha, beta):
if node.is_leaf():
return node.value
v = - infinity
for child in node.children:
v = max(v, min_value(child, alpha, beta))
if v >= beta:
return v
alpha = max(alpha, v)
node.value = v
return v
def min_value(node, alpha, beta):
if node.is_leaf():
return node.value
v = infinity
for child in node.children:
v = min(v, max_value(child, alpha, beta))
if v <= alpha:
return v
beta = min(beta, v)
node.value = v
return v
tree = tree_for_adv_search()
output = alpha_beta_pruning(tree)
print('the output of this alpha beta pruning is {}'.format(output))
|
9e2aa85e904ba240187c5f9d42dcee8ceaafe74f | maxlvl/techdegree-project-2 | /keyword.py | 3,288 | 4.1875 | 4 | from ciphers import Cipher
class Keyword(Cipher):
def __init__(self):
self.plaintext = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 '
def encrypt(self, text, cipher_pad):
"""
Accepts an alphanumerical string object (text) and an alphanumerical string object (cipher_pad)
as arguments.
Uses 2 lists to encrypt the original text given.
Returns a string object containing alphanumerical characters
"""
# Converts all input to lists, adds the cipher_pad to the beginning of an alphanumerical list.
text = text.upper()
cipher_pad = cipher_pad.upper()
to_be_encrypted_message = list(text)
regular_alphabet = list(self.plaintext)
ciphered_alphabet = list(cipher_pad) + regular_alphabet
# The alphanumerical list containing the cipher_pad is sorted to remove duplicates
filtered_alphabet = []
for char in ciphered_alphabet:
if char not in filtered_alphabet:
filtered_alphabet.append(char)
cipher_dict = {}
# Dictionary is used to map the encoded list against a regular alphabet list.
for cipher_char in filtered_alphabet:
index = filtered_alphabet.index(cipher_char)
regular_char = regular_alphabet[index]
cipher_dict[regular_char] = cipher_char
# The mapped dictionary is used to encrypt the text message.
encrypted_message = []
for char in to_be_encrypted_message:
if char in cipher_dict.values():
encrypted_message.append(cipher_dict[char])
return ''.join(encrypted_message)
def decrypt(self, text, cipher_pad):
"""Accepts an alphanumerical string object (text) and an alphanumerical string object (cipher_pad)
as arguments.
Uses 2 lists to decrypt the encrypted text given.
Returns a string object containing alphanumerical characters"""
# Very similar logic to the encryption algorithm, but the dictionary is switched
# to contain the opposite order of characters.
# Converts all input to lists, adds the cipher_pad to the beginning of an alphanumerical list.
text = text.upper()
cipher_pad = cipher_pad.upper()
to_be_decrypted_message = list(text)
regular_alphabet = list(self.plaintext)
ciphered_alphabet = list(cipher_pad) + regular_alphabet
# The alphanumerical list containing the cipher_pad is sorted to remove duplicates
filtered_alphabet = []
for char in ciphered_alphabet:
if char not in filtered_alphabet:
filtered_alphabet.append(char)
# Dictionary is used to map the regular alphabet list against the encoded list
cipher_dict = {}
for cipher_char in filtered_alphabet:
index = filtered_alphabet.index(cipher_char)
regular_char = regular_alphabet[index]
cipher_dict[cipher_char] = regular_char
# The mapped dictionary is used to decrypt the text message.
decrypted_message = []
for char in to_be_decrypted_message:
if char in cipher_dict.values():
decrypted_message.append(cipher_dict[char])
return ''.join(decrypted_message)
|
4e226e2ae7200501868beccac3f2696007515240 | AverPower/Algorithms_and_Structures | /3. Search Algorithms/Task F.py | 620 | 3.703125 | 4 | from math import log2
EPS = 0.000001
ITN = int(log2(1 / EPS) / log2(3 / 2))
def h(v_p, v_f, a, x):
return (((1 - a) ** 2 + x ** 2) ** (1/2)) / v_p + (((1 - x) ** 2 + a ** 2) ** (1 / 2)) / v_f
def ternary_search(left, right, v_p, v_f, a, bound):
for i in range(bound):
middle_1 = (2 * left + right) / 3
middle_2 = (left + 2 * right) / 3
if h(v_p, v_f, a, middle_1) < h(v_p, v_f, a, middle_2):
right = middle_2
else:
left = middle_1
return right
v_p, v_f = map(int, input().split())
a = float(input())
print(ternary_search(0, 1, v_p, v_f, a, ITN))
|
6ed35a115920d3004b4a56bdd5ff8d456acbcda1 | EzequielArBr/Maratona_Python | /ovni.py | 291 | 3.953125 | 4 | T = int(input())
for t in range(T):
linha = input().split(" ")
somatoria = int(linha[0]) + int(linha[1])
if somatoria <= int(linha[2]):
print ('CABE!', end="" if t == T - 1 else "\n")
elif somatoria >= int(linha[2]):
print ('NAO CABE!', end="" if t == T - 1 else "\n") |
958951755773a03caf50a55792a43ad629f96bbb | Gabrielomn/DS-learning | /myscripts/poisson.py | 314 | 3.640625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 28 16:44:45 2019
@author: kyouma
"""
from scipy.stats import poisson
poisson.pmf(3, 2)
'''
a = 0
numeros = range(4)
for k in numeros:
a += poisson.pmf(k,2)
print (a)
mesma coisa que:
'''
poisson.cdf(3,2)
poisson.pmf(12,10)
|
ca6cf560968bc57444debbed3304730d690ba085 | Krishika28/PRO-102-109-classes- | /PRO-104/mean.py | 300 | 3.640625 | 4 | import csv
with open("data.csv", newline='') as f:
data = csv.reader(f)
list_data = list(data)
list_data.pop(0)
print(list_data)
total = 0
for h in range(len(list_data)):
height = list_data[h][1]
total = total+float(height)
mean = total/len(list_data)
print(mean) |
b1a7ab973f90b6073b8850c7af8af63b8426e86b | dblarons/Choose-Your-Own-Python | /classywestern.py | 6,470 | 3.921875 | 4 | from sys import exit
from random import randint
# sets up a class Game()
class Game(object):
# a special initialization method that sets up
# important variables.
def __init__(self, start):
# initializes the self.lols variable
self.lols = [
"You lost? My dog can even beat this game.",
"Were you even trying?",
"Nice try. Wait no, nevermind."
]
# initializes the self.start variable and assigns
# it to start
self.start = start
# I believe that this is sort of the mechanism that drives
# the entire game.
def play(self):
next = self.start
while True:
print "\n--------------------------"
room = getattr(self, next) # sets room equal to self.next
next = room()
def death(self):
print self.lols[randint(0, len(self.lols)-1)]
replay = raw_input("[play again?]> ")
if replay == 'yes':
a_game = Game("chapter_one")
a_game.play()
elif replay == 'no':
exit(1)
else:
print "I don't know what %s means." % replay
return 'death'
def chapter_one(self):
print "You are riding your horse alongside a speeding train."
print 'You and your gang, "The yellow monkeys", are about'
print "to hold up the passengertrain and take all the valuables that"
print "you can get your grubby hands on."
print "\n"
print "As you pass by the first passenger car a security"
print "officer pulls out his colt pistol and takes aim...."
print "AT YOU!!!!"
action = raw_input("> ")
if action == "jump on the train":
print "You try to balance on the horse and prepare to"
print "jump onto the train. With steady balance you stand"
print "up and prepare to jump."
print "\n"
print "The guard fires off two missing shots, but his third"
print "hits its mark. The bullet knocks you off your horse"
print "and you die when your soft skull hits the hard ground."
return 'death'
elif action == "shoot":
print "Like a seasoned criminal, you quickly draw your"
print "weapon and take aim at the guard."
print "The poor bloke is dead before he can shoot at you."
return 'second_car'
else:
print "I don't know what that means."
return 'chapter_one'
def second_car(self):
print "Your trusty stallion, Happy, speeds up and approaches"
print "the second passenger car."
print "\n"
print "This car is not protected by a guard, so you can"
print "board the train in safety."
action = raw_input("> ")
if action == "keep riding":
print "You keep on riding alongside the train."
print "Your horse begins to tire, as it cannot keep"
print "up with the fast train for forever."
print "\n"
print "Happy slows down and loses the train."
print "You lose."
return 'death'
elif action == "board the train":
print "You put your gun in its holster and try to balance"
print "on Happy. You stand up and balance for a moment"
print "before you leap onto the horse."
print "\n"
print "You made it!"
print "You land face down on the top of the second passenger"
print "car. There is a hatch on the top of the car, but it"
print "is protected by a rustic 1 digit code."
print "If you get the code wrong 8 times, you will be locked"
print "out for good."
code = "%d" % (randint(0,9))
guess = raw_input("[keypad]> ")
guesses = 0
while guess != code and guesses < 8:
print "BZZZZZZEDDD!"
guesses += 1
guess = raw_input("[keypad]> ")
if guess == code:
print "The hatch clicks open!"
print "You climb into the second passenger car."
return 'inside_train'
else:
print "The lock buzzes the last time and you are locked"
print "out and stuck on the top of the train."
print "You lose."
return 'death'
else:
print "How am I supposed to know what %s means?" % action
return 'second_car'
def inside_train(self):
print "You look around to see frightened passengers shaking in"
print "their seats. You pull out your colt revolver and fire a few"
print "shots into the ceiling to show that your the real deal."
print "\n"
print 'You yell over the chugging train engines, "Everyone,'
print 'put your valuables in the center isles. If I find out that'
print 'ANYONE is hiding theirs from me, I will shoot them myself."'
print 'One passenger jumps out of his seat and hurls himself toward you.'
action = raw_input("> ")
if action == "dodge" or "duck":
print "You attempt to dodge the large man who hurtles"
print "toward you. You dive into the passenger seat beside"
print "you and cover your head. Suddenly, the woman in"
print "the seat that you just jumped into grabs your colt"
print "and aims it at your head."
print "You lose."
return 'death'
elif action == "shoot" or "kill him":
print "You quickly grab your colt and shoot the man who"
print "hurdles toward you. His body crashes down on you"
print "and knocks your colt onto the floor. Struggling to"
print "stand up, you see a brave woman reach for the"
print "revolver and aim it at you."
print "You lose."
elif action == "take hostage":
print "Reacting quickly, you grab the pretty young lady"
print "who sits in the seat next to where you are standing."
print "You hold her in front of her with the gun to her neck."
print "The man who is hurtling toward you sees this and"
print "turns to miss you and the young lady."
print "Deciding that you might be safer with a hostage,"
print "you decide to bring her along."
return 'third car'
else:
print "Sorry, doing %s is not an option." % action
a_game = Game("chapter_one") # insert the start of the game here.
a_game.play()
|
8871eacf5463a39ad605d03a21530b6e292b65cd | yusuf-korkmaz/Python | /4- Python'da Modüller/Palindrome.py | 2,163 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 1 11:03:20 2016
@author: yusufkorkmaz
Belirlenen string in polindrome olup olmadığını test eden
ve sonuç olarak True veya False dönen bir modül.
isPalindrome(string,recursive veya iterative) metodu yer almakta
Parametre olarak String ve 0 değeri girdiğinizde recursive çalışmakta
Parametre olarak String ve 1 değeri girdiğinizde iterative çalışmakta
"""
def isPalindrome(text:str,metod:int) -> bool:
"""
isPalindrome metodu verilen string'i istenen metoda göre palindrome olup olmadığını sorgular
Parametre:
String ve 0 değeri girdiğinizde recursive çalışmakta
String ve 1 değeri girdiğinizde iterative çalışmakta
"""
if(metod == 0):
return palindrome_recursive(text,metod)
elif(metod == 1):
return palindrome_iterative(text)
else:
print("Ikinci parametre olarak 0 veya 1 değerini girmeniz gerekiyor {} için".format(text))
return False
def palindrome_recursive(text,n):
if(" " in text) :
text = trim_lower_recursive(text)
if(n >= len(text)):
return True
else:
if(text[n] == text[len(text)-n-1]):
return palindrome_recursive(text,n+1)
else:
return False
def palindrome_iterative(text):
text=trim_lower_iterative(text)
for i in range(len(text)):
if(text[i]==text[len(text)-i-1]):
palindrome=True
else:
return False
return palindrome
def trim_lower_recursive(text):
text_current = text.lower()
if(" " in text_current):
index = text_current.index(" ")
text_current = text_current[:index] + text_current[index+1:]
text_current = trim_lower_recursive(text_current)
return text_current
def trim_lower_iterative(text):
text_current = text.lower()
while ( " " in text_current ):
text_current = text_current.replace(" ","")
return text_current
def trim_lower_string_metod(text):
text= text.lower()
text_dizi=text.split(" ")
text_without_space = "".join(text_dizi)
return text_without_space
|
8a5a389ccfc60c530c48689d243e4a89ec6b39bd | gabe-le97/MovieData | /Le_G_movies.py | 12,251 | 4.125 | 4 | """
------------------------------------------
CSC 110 Final Programming Project
File: MovieData.py
Author: Gabe Le
Due: 11 December 2017
Note: This program will read a data file containing movies that were released between
2000 - 2009 and display information that the user requests.
The file has: Title, Genre, Run Time, Rating, Studio, and Year
IMPORTANT: Please resize your idle window accordingly (most likely bigger)
since I spaced out the outputs to look nicer and neater.
------------------------------------------
"""
#------------------------------------------
# used to find most common occurrence as in lab 5
from collections import Counter
# Checks if the input is a valid file located in the same directory as
# this file and throws an exception if it does not exist
def checkFile():
while (True):
try:
prompt = input("Enter the name of the data file: ")
myFile = open(prompt, 'r')
break
except IOError:
print("Invalid file name, please try again ... ")
return myFile
# checks if the choice is valid and prompts the user to
# enter it again if it is not
def checkChoice():
while (True):
try:
choice = int(input('Choice >>> '))
if 1 <= choice <= 8:
return choice
else:
print("Please enter a valid number...")
except ValueError:
print('Please enter a valid number...')
# Checks if the input is a valid genre, rating, or studio &
# continues doing this until a correct input is given
def checkInput(aString, aList):
while(True):
pick = input("Enter the " + aString + ": ")
if(pick in aList):
return pick
else:
print("Invalid " + aString + " please try again")
# Checks if the year is valid (between 2000 & 2009) & if the first year is
# smaller than the second year. Do not exit until the years are correct
def checkYear():
print("Enter your range to search (oldest year first) 2000 -> 2009")
keepGoing = True
while (keepGoing):
while (True):
try:
year1 = int(input("Year 1: "))
year2 = int(input("Year 2: "))
if ((2000 <= year1 <= 2009) and (2000 <= year2 <= 2009)):
break
else:
print("Please enter a valid year")
except ValueError:
print("Invalid year! Please try again")
# year2 should be a year larger than the first
if (year2 < year1):
print("Second year should be after first year -- Please try again")
else:
keepGoing = False
return year1, year2
#------------------------------------------
# Searches a sorted list by discarding half of the list that
# it knows does not contain the value until the value is found
def binarySearch(myList, aString):
front = 0
back = len(myList)-1
while True:
# this will be the pivot of the list
middle = (back+front)//2
if myList[middle] == aString:
return middle
# bounds have intercepted & nothing is found
if front == back:
print("not found")
return -1
if aString < myList[middle]:
# only use the lower half
back = middle - 1
else:
# only use the upper half
front = middle + 1
# Searching algorithm which returns two sorted lists by
# finding the minimum element and swapping it with the first index.
# This is repeated until the whole list is sorted. Front index is incremented
# after minimum is found
def selectionSort(runtimeList):
# keep track of where the min indexes are
indexList = list(range(0, len(runtimeList)))
tempList = runtimeList.copy()
for i in range(1, len(tempList)):
min = i
for j in range(i + 1, len(tempList)):
# comparison
if int(tempList[j]) < int(tempList[min]):
min = j
# swap & add to indexList
indexList[i], indexList[min] = indexList[min], indexList[i]
tempList[i], tempList[min] = tempList[min], tempList[i]
return indexList
# Takes the data line by line from a text file and inserts it into
# 6 respective lists & return the lists
def getData():
# change the headings to look cleaner
titleList, genreList, runtimeList, \
ratingList, studioList, yearList = ["TITLE"], ["GENRE"], ["RUNTIME"], \
["RATING"], ["STUDIO"], ["YEAR"]
# check if the file is valid
infile = checkFile()
# skip the first line because we already "changed" it
line = infile.readline()
line = infile.readline()
line = line.strip()
while (line != ""):
title, genre, runtime, rating, studio, year = line.split(",")
titleList.append(title)
genreList.append(genre)
runtimeList.append(runtime)
ratingList.append(rating)
studioList.append(studio)
yearList.append((year))
line = infile.readline()
line = line.strip()
infile.close()
return titleList, genreList, runtimeList, ratingList, studioList, yearList
#------------------------------------------
# Start of the functions to get data when a choice is picked
# Searches the genre List for all films with that specific genre and prints all the
# information for movie genre
def getGenre(titleList, genreList, runtimeList, ratingList, studioList, yearList):
# check that the genre actually exists in the list
genre = checkInput("Genre", genreList)
print("\nThe films that meet your criteria are: \n")
# format the output correctly to look clean
print("%-45s" "%10s" "%15s" "%15s" "%30s" "%10s" % (titleList[0], genreList[0],
runtimeList[0], ratingList[0], studioList[0], yearList[0]))
for i in range(0, len(titleList)):
if(genre == genreList[i]):
print("%-45s" "%10s" "%15s" "%15s" "%30s" "%10s" % (titleList[i], genreList[i],
runtimeList[i], ratingList[i], studioList[i], yearList[i]))
# Searches the rating List for all films with that specific rating and prints all the
# information for movie rating
def getRating(titleList, genreList, runtimeList, ratingList, studioList, yearList):
# checks if the rating is a valid input
rating = checkInput("Rating", ratingList)
print("\nThe films that meet your criteria are: \n")
print("%-45s" "%15s" "%15s" "%15s" "%30s" "%10s" % (titleList[0], genreList[0],
runtimeList[0], ratingList[0], studioList[0], yearList[0]))
for i in range(0, len(titleList)):
if(rating == ratingList[i]):
print("%-45s" "%15s" "%15s" "%15s" "%30s" "%10s" % (titleList[i], genreList[i],
runtimeList[i], ratingList[i], studioList[i], yearList[i]))
# Find the film with the longest runtime by keeping track of the maximum
# value while traversing the list
def getLongest(titleList, genreList, runtimeList, ratingList, studioList, yearList):
# checks if the studio actually exists in the list
studio = checkInput("Studio", studioList)
max = 0
for i in range(1, len(runtimeList)):
time = int(runtimeList[i])
if(time > max and studioList[i] == studio):
# override max once a new higher number is found
max = int(runtimeList[i])
# keep track of the index where max is
index = i
print("\nThe films that match your criteria are: \n")
print("%-45s" "%15s" "%15s" "%15s" "%30s" "%10s" % (titleList[0], genreList[0],
runtimeList[0], ratingList[0], studioList[0], yearList[0]))
print("%-45s" "%15s" "%15s" "%15s" "%30s" "%10s" % (titleList[index], genreList[index],
runtimeList[index], ratingList[index], studioList[index], yearList[index]))
# Searches the title list with Binary Search and print out its information
def getTitle(titleList, genreList, runtimeList, ratingList, studioList, yearList):
title = checkInput("Title", titleList)
# call binary search to return the index where the title lies
index = binarySearch(titleList, title)
print("\nThe films that match your criteria are: \n")
print("%-45s" "%15s" "%15s"
"%15s" "%30s" "%10s" % (titleList[0], genreList[0],
runtimeList[0], ratingList[0], studioList[0], yearList[0]))
print("%-45s" "%15s" "%15s"
"%15s" "%30s" "%10s" % (titleList[index], genreList[index],
runtimeList[index], ratingList[index], studioList[index],
yearList[index]))
# Accumulates the runtime of all films between two years then divides it by
# the number of films to get the average runtime
def averageRuntime(runtimeList, yearList):
count = 0
# check if the years are valid
year1, year2 = checkYear()
total = 0
for i in range(1, len(runtimeList)):
if(year1 <= int(yearList[i]) <= year2):
# count is needed to get the average since it is a counter
count += 1
# accumulate the runtimes
total += int(runtimeList[i])
print("The average runtime for films between " + str(year1) + " and "
+ str(year2) + " is " + str(total/count))
# Sorts all the lists according to the runtime and writes all the data to a new text file
# in the same format as the original
def writeTo(titleList, genreList, runtimeList, ratingList, studioList, yearList):
# sort only the runtime list
indexList = selectionSort(runtimeList)
# get rid of the headers to allow indexes to be correct (we don't need it)
fname = input("\nEnter name of output file: ")
outFile = open(fname, 'w')
for i in indexList:
# write data in the same format as the original
outFile.write(titleList[i] + "," + genreList[i] + "," +
runtimeList[i] + "," + studioList[i] + "," + yearList[i] +"\n")
outFile.close()
print("Finished writing to file")
#------------------------------------------
# Finds the string that occurs the most in the studioList
# using the module Counter from collections
def mostFilms(studioList):
count = Counter(studioList)
winnerName, numFilms = count.most_common()[0]
print(winnerName + " has the most movies at " + str(numFilms) + " films")
#------------------------------------------
def getChoices():
keepGoing = True
titleList, genreList, runtimeList, ratingList, studioList, yearList = getData()
while(keepGoing):
print("\nPlease choose one of the following options:")
print("1 -- Find all films of a certain genre")
print("2 -- Find all films with a certain rating")
print("3 -- Find the longest film made by a specific studio")
print("4 -- Search for a film by title")
print("5 -- Find the average runtime of films made in a given year range")
print("6 -- Sort all lists by runtime & write the results to a new file")
print("7 -- Quit")
print("8 -- *Bonus* See which studio produced the most films!")
choice = checkChoice()
# runs the function that corresponds with the choice
if(choice == 1):
getGenre(titleList, genreList, runtimeList, ratingList, studioList, yearList)
elif (choice == 2):
getRating(titleList, genreList, runtimeList, ratingList, studioList, yearList)
elif(choice == 3):
getLongest(titleList, genreList, runtimeList, ratingList, studioList, yearList)
elif(choice == 4):
getTitle(titleList, genreList, runtimeList, ratingList, studioList, yearList)
elif(choice == 5):
averageRuntime(runtimeList, yearList)
elif(choice == 6):
writeTo(titleList, genreList, runtimeList, ratingList, studioList, yearList)
elif(choice == 7):
print("Goodbye")
keepGoing = False
else:
mostFilms(studioList)
# Presents the User with a list of options to pick what they want to see
def main():
getChoices()
#------------------------------------------
# end of Le_G_movies.py
main() |
7e292cd69073a217e99bced03ca43772036e96ef | Minashi/COP2510 | /Chapter 9/course_Information.py | 586 | 3.734375 | 4 | course_Room = {'CS101': 3004, 'CS102': 4501, 'CS103': 6755, 'NT110': 1244, 'CM241': 1411}
course_Instructor = {'CS101': 'Haynes', 'CS102': 'Alvarado', 'CS103': 'Rich', 'NT110': 'Burke', 'CM241': 'Lee'}
course_Meeting_Time = {'CS101': '8:00 AM', 'CS102': '9:00 AM', 'CS103': '10:00 AM', 'NT110': '11:00 AM', 'CM241': '1:00 PM'}
print("Please enter your course number:")
course_Number = input('>')
print("\nCourse information:")
print("Room:", course_Room[course_Number])
print("Instructor:", course_Instructor[course_Number])
print("Meeting Time:", course_Meeting_Time[course_Number])
|
e80688442c643ed05976d0b872cffb33b1c3c054 | Minashi/COP2510 | /Chapter 5/howMuchInsurance.py | 301 | 4.15625 | 4 | insurance_Factor = 0.80
def insurance_Calculator(cost):
insuranceCost = cost * insurance_Factor
return insuranceCost
print("What is the replacement cost of the building?")
replacementCost = float(input())
print("Minimum amount of insurance to buy:", insurance_Calculator(replacementCost))
|
f8b2407d166049316233a3285e2587fdfac40ed0 | Minashi/COP2510 | /Chapter 11/person_and_customer_classes.py | 1,036 | 3.984375 | 4 | class Person:
def __init__(self, name, address, telephone_number):
self.__name = name
self.__address = address
self.__telephone_number = telephone_number
class Customer(Person):
def __init__(self, name, address, telephone_number, customer_number, trueorfalse):
super().__init__(name, address, telephone_number)
self.__customer_number = customer_number
self.__mailing_list = False
counter = 1
repeat = True
customer_list = []
while repeat:
print("Please enter the following information of the customer: ")
name = input('Name: ')
address = input('Address: ')
telephone_Number = input("Telephone Number: ")
mailing_list = input("Does the customer want to be on the mailing list? True/False\n")
customer = Customer(name, address, telephone_Number, counter, mailing_list)
customer_list.append(customer)
counter += 1
answer = input("Do you want to enter another customers information?")
if answer.lower() == 'no':
repeat = False
|
6254eedd431ef73cc98e27c704ecc534443e0691 | Jackson026/AlgorithmQIUZHAO | /Week_03/跳跃游戏2.py | 896 | 3.734375 | 4 |
# 1.定义步数step=0,能达到的最远位置max_bound=0,和上一步到达的边界end=0。
# 2.遍历数组,遍历范围[0,n-1):
# A.所能达到的最远位置max_bound=max(max_bound,nums[i]+i),表示上一最远位置和当前索引i和索引i上的步数之和中的较大者。
# B.如果索引i到达了上一步的边界end,即i==end,则:
# b1.更新边界end,令end等于新的最远边界max_bound,即end=max_bound
# b2.令步数step加一
# 3.返回step
# **注意!**数组遍历范围为[0,n-1),因为当i==0时,step已经加一,所以若最后一个元素也遍历的话,当end恰好为n−1,步数会多1
def jump(self, nums) -> int:
step=0
end=0
max_bound=0
for i in range(len(nums)-1):
max_bound=max(max_bound,nums[i]+i)
if(i==end):
step+=1
end=max_bound
return step |
488814efa60cb7ab1632ed5a4b887fa663a17a55 | Jackson026/AlgorithmQIUZHAO | /Week_01/加1.py | 650 | 3.734375 | 4 | # 取巧的办法是转换成字符串然后变为int,最后再转换回去原来的形式,通用性不强,就不作为一种方法写在这里
# 按位运算,倒序,如果是9,就变为0,向前循环,不为9则直接加1;
# 如果为999这种特殊形式,则在循环结束后,列表头插入1 .insert(位置,数)
def plusOne(self, digits):
if not digits:
return digits + [1]
for i in range(len(digits) - 1, -1, -1):
if digits[i] == 9:
digits[i] = 0
else:
digits[i] = digits[i] + 1
break
if digits[0] == 0:
digits.insert(0, 1)
return digits |
f36130ddb51ef0090df848103242c2f6fb612ec4 | Christian-Gennari/PDFMergerApp | /PDFMerger.py | 863 | 3.578125 | 4 | import PyPDF2
import tkinter
from tkinter import filedialog as fd
# Hides Tkinter root window
tkinter.Tk().withdraw()
filename = fd.askopenfilenames(initialdir = "/",title = "Select files",filetypes = (("PDF files","*.pdf"),("all files","*.*"))) # show an "Open" dialog box and return the path to the selected file
filename = list(filename)
print(filename)
pdfOutputFile = fd.asksaveasfile(mode='wb', defaultextension=".pdf")
pdfWriter = PyPDF2.PdfFileWriter()
for x in filename:
pdfFiles = open(x, "rb")
pdfReader = PyPDF2.PdfFileReader(pdfFiles)
for pageNum in range(pdfReader.numPages):
pageObj = pdfReader.getPage(pageNum)
pdfWriter.addPage(pageObj)
pdfWriter.write(pdfOutputFile)
pdfOutputFile.close()
#pdfOutputFile = open("combinedpdf.pdf", "wb")
#pdfWriter.write(pdfOutputFile)
#pdfOutputFile.close()
#pdf1File.close()
#pdf2File.close()
|
c62ea637c51372433a4a2fe56d4ede0f928c50ca | gbordyugov/playground | /coding/codility-and-leetcode/elevator_stops.py | 660 | 3.65625 | 4 | # Compute the number of elevator stops
def solution(A, B, M, X, Y):
"""
Computes the number of elevator stops
"""
N = len(A) # the number of people
i, cnt = 0, 0
while i < N:
# weight - the weight of people in the elevator
# j - the first person in the next batch
weight, j = 0, i
while j < N and weight + A[j] <= Y and j - i + 1 <= X:
weight += A[j]
j += 1
# set() computes the unique floors plus the one stop to go down
cnt += len(set(B[i:j])) + 1
# start the next batch
i = j
return cnt
print solution([60, 70, 40], [2, 5, 4], 5, 2, 80) #3 |
60b61b17fdab4fdd4c48a4df68709e713054e259 | gbordyugov/playground | /coding/codility-and-leetcode/password-generator.py | 780 | 3.609375 | 4 | # generate password given sets
import numpy as np
from random import randint
def password(n, sets):
passw = ''
num_sets = len(sets)
for i in range(n):
if i < num_sets:
set1 = sets[i]
k = set1[randint(0, len(set1)-1)]
else:
rand_set = sets[randint(0, len(sets)-1)]
k = rand_set[randint(0, len(rand_set)-1)]
passw += str(k)
return shuffle(passw)
def shuffle(passw):
L = len(passw)
for value, i in enumerate(passw):
if i < (L-1):
k = randint(i+1, L-1)
current = passw[i]
passw[i] = passw[k]
passw[k] = current
return passw
sets = [['a','b','c','d','e'], [0, 1, 2, 3, 5], ['A','B','C','D','E']]
print (password(8, sets)) |
bfdf1e91559715e3718fb29c8188fa3e0c5f8ff0 | gbordyugov/playground | /coding/codility-and-leetcode/complement.py | 215 | 3.546875 | 4 | # 476. Number Complement. Leetcode
def findComplement(num):
bin_n = "{0:b}".format(num)
flipped = [str(int(val) ^ 1) for val in bin_n]
return int(''.join(flipped), 2)
print findComplement(5) |
39b12a29534181b594461218ff8f01b78547ef47 | gbordyugov/playground | /coding/codility-and-leetcode/ladder.py | 464 | 3.78125 | 4 | # Codility. Ladder. Complexity is O(N) overall. 62%
def fibonacci(N):
if N < 1:
return 0
fib = [0] * (N + 1)
fib[1] = 1
for i in range(2, len(fib)):
fib[i] = fib[i-1] + fib[i-2]
return fib[N]
def ladder(A, B):
sequence = []
for i, v in enumerate(A):
sequence.append(fibonacci(v+1))
for i, v in enumerate(B):
sequence[i] = sequence[i] % (2 ** v)
return sequence
print(ladder([4, 4, 5, 5, 1], [3, 2, 4, 3, 1])) |
6870fc5da3d257220da144151f62dbac32d942f4 | gbordyugov/playground | /coding/codility-and-leetcode/brackets.py | 768 | 3.71875 | 4 | # Codility. Brackets
def push(val, stack, size):
stack[size] = val
size += 1
return size
def pop(stack, size):
size -= 1
stack[size] = 0
return size
def brackets(S):
if not len(S):
return 1
size = 0
stack = [0] * len(S)
size = push(S[0], stack, size)
for i in range(1, len(S)):
if S[i] == ')' and stack[size-1] == '(' \
or S[i] == ']' and stack[size-1] == '[' \
or S[i] == '}' and stack[size-1] == '{':
size = pop(stack, size)
else:
size = push(S[i], stack, size)
return 1 if not stack[0] else 0
print(brackets('[[()()]]'))
print(brackets('[[()]]'))
print(brackets('[(]{})]'))
print(brackets('{{]]}'))
print(brackets('[][][]'))
print(brackets('{{]]}')) |
8f0de2450d01f3d842c08d8ac671340058a8e006 | gbordyugov/playground | /coding/interviewbit/divide-two-integers-bit-operations.py | 550 | 3.65625 | 4 | # Divide Integers
import math
def divide2(dividend, divisor):
positive = (dividend < 0) is (divisor < 0)
dividend, divisor = abs(dividend), abs(divisor)
res = 0
while dividend >= divisor:
temp, i = divisor, 1
while dividend >= temp:
dividend -= temp
res += i
i <<= 1
temp <<= 1
if not positive:
res = -res
return min(max(-2147483648, res), 2147483647)
def divide(divd, diver):
m = int(math.log(diver, 2))
return divd >> m
print(divide(25, 2)) |
0dac4d9da7a731ea626a58de83ae95c115d19116 | raaedserag/Prefix-Calculator | /Prefix Calculator.py | 8,779 | 4.125 | 4 | # Define the stack structure // Edited==> add a reverse function
""""stack.items ---> list of elements <<<>>>
stack.size() ===> Return length <<<>>> stack.isEmpty ===> Return true/false
stack.push(item) ===> appending item <<<>>> stack.reverse() ===> reverse the stack to use as QUEUE
stack.pop() ===> popping last <<<>>> stack.peek() ===> Return the last element"""
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
def reverse(self):
for i in range (0,Stack.size(self)//2):
self.items[i] , self.items[Stack.size(self)-1-i] = self.items[Stack.size(self)-1-i] , self.items[i]
# Define reverse list ===> Return reverse of a list
def reversed_list(alist):
n = len(alist)
for i in range (0,n//2):
alist[i] , alist[n-1-i] = alist[n-1-i] , alist[i]
return alist
# Define Binary search ===> Return true or false
def binary_search(lista, item):
first = 0
last = len(lista) - 1
found = False
while first <= last and not found:
midpoint = (first + last) // 2
if lista[midpoint] == item:
found = True
else:
if item < lista[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
return found
# Define Merge Sort ===> sorting the array ascending
'''
def merge_sort(alist):
if len(alist) > 1:
mid = len(alist) // 2
lefthalf = alist[:mid]
righthalf = alist[mid:]
merge_sort(lefthalf)
merge_sort(righthalf)
i = 0
j = 0
k = 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k] = lefthalf[i]
i = i + 1
else:
alist[k] = righthalf[j]
j = j + 1
k = k + 1
while i < len(lefthalf):
alist[k] = lefthalf[i]
i = i + 1
k = k + 1
while j < len(lefthalf):
alist[k] = righthalf[j]
j = j + 1
k = k + 1
'''
# Define digits characters ===> Return a list of numbers
def number_list():
return ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
# Define operators list ===> Return a list of sorted operators by asciis
def operators_list():
return ['*', '+', '-', '/', '^']
# Define the allowed chars ===> Return a list of sorted chars by asciis , it can't be sorted automatically
def sorted_chars():
sorted_c = [' ', '*', '+', '-', '.', '/','0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '^']
return sorted_c
# Define is operator? ===> Return true/false
def isoperator(c):
if binary_search(operators_list(), c):
return True
return False
# Remove every extra white space
def remove_extra_spaces(statement):
statement = statement.strip()
for i in range(0, len(statement)):
statement = statement.replace(' ', ' ')
return statement
# Check eligible characters
def check_chars(statement):
for i in range(0,len(statement)):
if i < len(statement)-1 :
#if isoperator(statement[i]) and statement[i+1] =='.' :
#return 'syntax'
if statement[i]=='.' and isoperator(statement[i+1]):
return False
if not binary_search(sorted_chars(),statement[i]) :
return False
return True
# Check if there is any missing brackets
'''
def check_brackets(statement):
left = 0
right = 0
for char in statement:
if char == '(':
left = left + 1
if char == ')':
right = right + 1
if left != right:
return False
return True
'''
# Check the duplicated operators from list 1 at list 2
def check_duplicated(list1, list2):
for i in range(0, len(list2)):
if binary_search(list1, list2[i]) and list2[i] == list2[i + 1]:
return False
return True
# General check on the statement ===> Return True statement only if there is no errors in brackets or chars
def checking_statement_chars(state):
state = remove_extra_spaces(state)
if check_chars(state) == 'syntax':
return "this(.A) is not a valid syntax , replace with 0.A"
if not check_chars(state):
return "Invalid Chars"
'''
elif not check_brackets(state):
return "brackets error"
elif not check_duplicated(operators_list(),state):
return "duplicated operators"
'''
return 'True'
# Define do maths calculations ===> Return the result of operation of {+,-,*,/ or ^}
def do_math(op1,op2,operator):
if operator == '+':
return op1 + op2
elif operator == '-':
return op1 - op2
elif operator == '*':
return op1 * op2
elif operator == '/':
if op2 == 0:
return 'zero divide'
return op1 / op2
else:
if op1 == 0:
return 'zero exp'
return op1 ** op2
# Split statement to a list of operands and operators
def split_equation(entered_eqn):
eqn = remove_extra_spaces(entered_eqn)
splitter_equation=[]
digits = ''
for i in range(0,len(eqn)):
# if char is whitespace
if eqn[i] == ' ':
if digits != '':
splitter_equation.append(digits)
digits = ''
# if char is an operator
elif isoperator(eqn[i]):
if digits != '':
splitter_equation.append(digits)
digits = ''
if i != len(eqn)-1 and eqn[i]=='-' and(not isoperator(eqn[i+1])) and eqn[i+1] !=' ':
digits = digits + eqn[i]
else:
splitter_equation.append(eqn[i])
# if char is a digit
else:
digits = digits + eqn[i]
if digits !='':
splitter_equation.append(digits)
return splitter_equation
# Define Calculate a reversed prefix eqn
def calculate(statem):
global op1, op2
temp = Stack()
#if check(statem) == 'True statement':
equate = reversed_list(split_equation(statem))
for i in equate:
if not isoperator(i):
temp.push(i)
else:
# getting first operand
if temp.isEmpty():
return 'error'
elif isoperator(temp.peek()):
return 'error'
else:
op1 = float(temp.pop())
# getting second operand
if temp.isEmpty():
return 'error'
elif isoperator(temp.peek()):
return 'error'
else:
op2 = float(temp.pop())
# pushing the result
temp_result = (do_math(op1, op2, i))
if temp_result =='zero divide':
return 'zero divide'
elif temp_result=='zero exp':
temp.push('0')
else:
temp.push(str(temp_result))
if temp.isEmpty():
return 'error'
elif isoperator(temp.peek()):
return 'error'
return float(temp.pop())
# format printing
def printing(result):
if result.is_integer():
print('= ',int(result))
else:
print('= ',float(result))
#############################################################################
######################## MAIN CODE #######################################
#############################################################################
user_input= input("Please enter a prefix expression: ") # Taking input from the user
while user_input != 'end':
check = checking_statement_chars(user_input)
if check != 'True': # check if user has entered an eligible chars or a missing brackets
print(check)
else:
result = calculate(user_input)
if result == 'error':
print('This is not prefix expression')
elif result == 'zero divide':
print('Not allowed to divide by 0')
else:
printing(result)
user_input= input("Please enter a prefix expression or enter 'end' to terminate: ") # Taking input from the user
print('ended')
|
0c404764a7b2a2921d926824e0a89883b560ab49 | cajimon04/Primer-Proyecto | /comer_helado.py | 1,403 | 4.28125 | 4 |
apetece_helado_input = input("¿Te apetece un helado? ¿Si/No?: ").upper()
if apetece_helado_input == "SI":
apetece_helado = True
elif apetece_helado_input == "NO":
apetece_helado = False
else:
print("Te he dicho que me digas si o no. Como no te entiendo pondre no")
apetece_helado = False
tienes_dinero_input = input("¿Tienes dinero para un helado? ¿Si/No?: ").upper()
if tienes_dinero_input == "SI":
tienes_dinero = True
elif tienes_dinero_input == "NO":
tienes_dinero = False
else:
print("Te he dicho que me digas si o no. Como no te entiendo pondre no")
tienes_dinero = False
hay_helados_input = input("¿Hay helados? ¿Si/No?: ").upper()
if hay_helados_input == "SI":
hay_helados = True
elif hay_helados_input == "NO":
hay_helados = False
else:
print("Te he dicho que me digas si o no. Como no te entiendo pondre no")
hay_helados = False
esta_tu_tia_input = input("¿Estas con tu tia? ¿Si/No?: ").upper()
if esta_tu_tia_input == "SI":
esta_tu_tia = True
elif esta_tu_tia_input == "NO":
esta_tu_tia = False
else:
print("Te he dicho que me digas si o no. Como no te entiendo pondre no")
esta_tu_tia = False
puedes_permitirtelo = tienes_dinero_input == "SI" or esta_tu_tia_input == "SI"
if apetece_helado == True and puedes_permitirtelo == True and hay_helados == True:
print("Pues cometelo")
else:
print("Pues na")
|
fea183288a5ad0baaa43c8ecd3c2e79f4d2662e5 | cphadkule/python_basics | /next perfect square.py | 193 | 3.921875 | 4 | import math
def find_next_square(sq):
root = math.sqrt(sq)
if root - math.floor(root)==0:
x = root+1
square = x*x
return int(square)
else:
return -1 |
50c700b135835a6a85e06ea5f7427125e9c898dd | nOlegovich/QaLight-Python | /compar.py | 815 | 3.90625 | 4 | from random import randint
a = int(input("Максимальна довжина першого списка: "))
b = int(input("Максимальне значення першого списка: "))
c = int(input("Максимальна довжина другого списка: "))
d = int(input("Максимальне значення другого списка: "))
def comp (x,y,z,l):
firstList = []
for i in range(x):
firstList.append(randint(0, y))
secondList = []
for i in range(z):
secondList.append(randint(0, l))
thirdList = []
for i in firstList:
if i in secondList:
thirdList.append(i)
if len(thirdList) == 0:
print("Співпадінь немає!!!")
else:
return list(thirdList)
print(comp(a,b,c,d)) |
6ea955986248a391dc46420cbad39b0593372e43 | angieramirez1800/Paint | /paint.py | 5,994 | 3.890625 | 4 | # Código modificado
# David Damián Galán
# Angélica Sofía Ramírez Porras
from turtle import * # Importa la herramienta turtle
from freegames import vector # Importa la biblioteca freegames
from math import sqrt # Importa la funcion sqrt
from math import pi # Importa la constante pi
def line(start, end):
"""
Dibuja una línea de acuerdo a dos puntos marcados por dos clicks
start = punto de inicio
end = punto de fin
"""
up() # Para dejar a dibujar (levantar el lápiz)
# Mover el lápiz a la coordenada (dupla) que marca el cursor al inicio
goto(start.x, start.y)
down() # Para empezar a dibujar (bajar el lápiz)
# Mover el lápiz a la coordenada que marca el cursor al final
goto(end.x, end.y)
def square(start, end):
"""
Dibuja un cuadrado de acuerdo a dos puntos marcados por dos clicks.
start = punto de inicio
end = punto de fin
"""
up() # Para dejar a dibujar (levantar el lápiz)
# Mover el lápiz a la coordenada que marca el cursor al inicio
goto(start.x, start.y)
down() # Para empezar a dibujar (bajar el lápiz)
begin_fill() # Para activar la función de rellenar la figura
for count in range(4): # Para hacer un loop de 4 veces
# Para mover el lápiz y formar una línea las veces que indique el loop
forward(end.x - start.x)
left(90) # Hacer girar el lápiz a 90 grados
end_fill() # Para rellenar la figura justo después de terminar el loop
def circle(start, end):
"""
Dibuja un círculo de acuerdo a dos puntos marcados por dos clicks.
start = punto de inicio
end = punto de fin
"""
up() # Para dejar a dibujar (levantar el lápiz)
diameter = end.x - start.x # Define el diámetro con coordenadas
# Mover el lápiz a la coordenada que marca el cursor al inicio
goto(start.x, start.y)
down() # Para comenzar a dibujar (bajar el lápiz)
begin_fill() # Para activar la función de rellenar la figura
for count in range(360): # Para hacer un loop de 360 veces
# Para mover el lápiz y formar una línea las veces que indique el loop
forward((diameter * pi) / 360) # traza la circunferencia
left(1) # Hacer girar el lápiz a 1 grado
end_fill() # Rellena figura
def rectangle(start, end):
"""
Dibuja un rectángulo de acuerdo a dos puntos marcados por dos clicks.
start = punto de inicio
end = punto de fin
"""
up() # Para dejar de dibujar (levantar el lápiz)
goto(start.x, start.y) # Mover el lápiz a la coordenada start
down() # Para comenzar a dibujar (bajar el lápiz)
begin_fill() # Para activar la función de rellenar la figura
for count in range(4): # Ciclo para las 4 líneas
# Cuando count es 0 o 2, la longitud es diferencia en x
# Cuando count es 1 o 3, la longitud es diferencia en y
if count % 2 == 0:
forward(end.x - start.x) # Mueve el lápiz y dibuja la línea
else:
forward(end.y - start.y) # Mueve el lápiz y dibuja la línea
left(90) # Hace girar el lápiz 90 grados a la izquierda
end_fill() # Terminar de rellenar la figura una vez está completa
def triangle(start, end):
"""
Dibuja un triángulo de acuerdo a dos puntos marcados por dos clicks.
start = punto de inicio
end = punto de fin
"""
setheading(0) # Inicializa el angulo como 0
up() # Para dejar de dibujar (levantar el lápiz)
goto(start.x, start.y) # Mover el lápiz a la coordenada start
begin_fill() # Para activar la función de rellenar la figura
down() # Para comenzar a dibujar (bajar el lápiz)
goto(end.x, end.y) # Mover el lápiz a la coordenada end
left(135) # Cambia la orientacion del lapiz 135 grados a la izquierda
# Calcula la distancia entre los puntos start y end
dist = sqrt((end.x - start.x) ** 2 + (end.y - start.y) ** 2)
forward(dist) # Mover el lápiz una distancia dist
goto(start.x, start.y) # Mover el lápiz a la coordenada start
end_fill() # Terminar de rellenar la figura una vez que está completa
setheading(0) # Reiniciar el angulo como 0
def tap(x, y):
"""
Guarda el punto de inicio o dibuja la figura
x = punto en eje x
y = punto en eje y
"""
# Se define una variable con un diccionario que guarda una coordenada
start = state['start']
if start is None: # Opción de si es la primera vez que se dibuja
state['start'] = vector(x, y) # Se guarda la primera coordenada
else:
shape = state['shape'] # Traza la figura indicada
# Para terminar de dibujar en el punto donde inició
end = vector(x, y)
# Variable para llamar las funciones de las figuras
shape(start, end)
state['start'] = None # Para reiniciar y dibujar algo diferente
def store(key, value):
"""
Guarda el valor de state.
key = figura
value = guarda qué figura se dibuja
"""
state[key] = value # Variable que guarda la figura en state
# Guarda las coordenadas (start) y la figura (shape)
state = {'start': None, 'shape': line}
setup(420, 420, 370, 0) # Para las medidas de la ventana/pad de dibujo
onscreenclick(tap) # Para llamar tap desde los clicks del mouse
listen() # Interfaz, para recolectar eventos (teclas presionadas)
onkey(undo, 'u') # La instrucción para deshacer
# A partir de esta línea es para configurar color
onkey(lambda: color('black'), 'K')
onkey(lambda: color('white'), 'W')
onkey(lambda: color('green'), 'G')
onkey(lambda: color('blue'), 'B')
onkey(lambda: color('red'), 'R')
onkey(lambda: color('yellow'), 'Y') # Color amarillo añadido por Angie
# A partir de esta línea es para configurar figuras
onkey(lambda: store('shape', line), 'l')
onkey(lambda: store('shape', square), 's')
onkey(lambda: store('shape', circle), 'c')
onkey(lambda: store('shape', rectangle), 'r')
onkey(lambda: store('shape', triangle), 't')
# Termina el programa
done()
|
7c8aeadef60a4c9dfb4b53a5bc48fcaa302682b7 | milolou/pyscript | /printTable.py | 800 | 3.609375 | 4 | tableData = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def printTable(table):
colWidth = [0] * len(table)
for x in range(0,len(table)):
lengthOfString = []
for y in range(0,len(table[x])):
length = len(table[x][y])
lengthOfString.append(length)
l = lengthOfString[0]
for z in range(1,len(lengthOfString)):
if lengthOfString[z] > l:
l = lengthOfString[z]
else:
continue
colWidth[x] = l
for m in range(0,len(table[0])):
for n in range(0,len(table)):
print(table[n][m].rjust((colWidth[n] + 2)),end = '')
print()
printTable(tableData)
|
039b84d58b8410e1017b71395ac44082e19323ec | milolou/pyscript | /stripMethod.py | 1,756 | 4.65625 | 5 | # Strip function.
'''import re
print('You can strip some characters by strip method,\n
just put the characters you want to strip in the parenthese\n
followed function strip')
print('Please input the text you wanna strip.')
text = input()
print('Please use the strip function.')
def strip(string):
preWhiteSpace = re.compile(r'^\s+')
epiWhiteSpace = re.compile(r'\s+$')
specificPattern = re.compile(r'%s'%string)
if string == None:
textOne = preWhiteSpace.sub('',text)
textTwo = epiWhiteSpace.sub('',text)
print('The stripped text is:\n' + textTwo)
return textTwo
else:
textThree = specificPattern.sub('',text)
print('The stripped text is:\n' + textThree)
return textThree
# start the program.
functionCall = input()
n = len(functionCall)
if n > 7:
stripString = functionCall[6:(n-1)]
elif n == 7:
stripString = None
else:
print('The input is not valid.')
strip(stripString)'''
import re
# Another version.
def strip(text,characters):
preWhiteSpace = re.compile(r'^\s+')
epiWhiteSpace = re.compile(r'\s+$')
specificPattern = re.compile(r'%s'%characters)
if characters == None:
textOne = preWhiteSpace.sub('',text)
textTwo = epiWhiteSpace.sub('',text)
print('The stripped text is:\n' + textTwo)
return textTwo
else:
textThree = specificPattern.sub('',text)
print('The stripped text is:\n' + textThree)
return textThree
# start the program.
print('please use the strip function.')
functionCall = input()
n = len(functionCall)
coreString = functionCall[7:(n-2)]
variableList = coreString.split("','")
newText = variableList[0]
newCharacters = variableList[1]
strip(newText,newCharacters)
|
80b7fad43e6a8b0089dfeaa44d3cd4c77be6d3b1 | milolou/pyscript | /PdfParanoia.py | 2,766 | 3.53125 | 4 | # PdfParanoia.py - Encrypt every PDF files in a folder and its subfolder,
# decrypt every PDF files in a folder and its subfolder.
import PyPDF2,os
from pathlib import Path
os.makedirs('encryptedPdfs',exist_ok=True)
# Encrypt every PDF files in a folder and its subfolder.
def encrypt(folder):
absPath = os.path.abspath(folder)
for folderName,subfolders,filenames in os.walk(absPath):
for filename in filenames:
if filename.endswith('.pdf'):
try:
PdfFile = open(filename,'rb')
PdfReader = PyPDF2.PdfFileReader(PdfFile)
if not PdfReader.isEncrypted:
p = Path(filename)
PdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(PdfReader.numPages):
PdfWriter.addPage(PdfReader.getPage(pageNum))
PdfWriter.encrypt(p.stem)
resultPdf = open(os.path.join('encryptedPdfs',f'{p.stem}' + '_encrypted.pdf'),'wb')
PdfWriter.write(resultPdf)
resultPdf.close()
PdfFile.close()
elif PdfReader.isEncrypted:
PdfFile.close()
except:
print(f'{filename} has some problems.')
'''
def test(folder):
tabsPath = os.path.abspath(folder)
for file in os.listdir(tabsPath):
pa = Path(file)
newFile = open(os.path.abspath(file),'rb')
fileReader = PyPDF2.PdfFileReader(newFile)
fileName = pa.stem
l = len(fileName)
password = fileName[:l-10]
try:
fileReader.decrypt(password)
newFile.close()
except:
print('Wrong password!')
# Decrypt every PDF files in a folder and its subfolder.
def decrypt(folder):
absPath = os.path.abspath(folder)
for folderName,subfolders,filenames in os.walk(absPath):
for filename in filenames:
pdfFile = open(os.path.abspath(filename),'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFile)
if pdfReader.isEncrypted:
pa = Path(file)
fileName = pa.stem
l = len(fileName)
password = fileName[:l-10]
pdfReader.decrypt(password)
pdfWriter = PyPDF2.PdfFileWriter()
for pageNum in range(pdfReader.numPages):
pdfWriter.addPage(pdfReader.getPage(pageNum))
resultFile = open(password + '.pdf','wb')
pdfWriter.write(resultFile)
resultFile.close()
pdfFile.close()
'''
encrypt('Automate_the_Boring_Stuff_2e_onlinematerials')
|
83b51cf94b6d1dae08fa5fb16f7b307e7946b468 | shervin-h/mapsa_prebootcamp_django | /bmm_kmm.py | 189 | 3.578125 | 4 | n, m = map(int, input().strip().split())
def gcd(a, b):
while b > 0:
a, b = b, a % b
return a
def lcm(a, b):
return a * b // gcd(a, b)
print(gcd(n, m), lcm(n, m))
|
35faaec60b05bc09ad1fa7d1f8b78d9dc1448a36 | shervin-h/mapsa_prebootcamp_django | /birthday_party.py | 1,425 | 3.90625 | 4 | '''
یک مهمونی تولد داریم که داخل اون سه نفر خیلی گرسنه هستن ( hungry )
و دو نفر سیر سیر ( not_hungry ) ،
اخری هم اصلا معمولی نه گرسنه نه سیر ( ok )،
چطور صاحب مهمونی کیک رو به حالتی تقسیم کنه که هر شیش نفر به یک اندازه سیر بشوند
hungry = 4 * not_hungry
hungry = 2 * ok
ok = 2 * not_hungry
4 * not_hungry = 2 * ok => not _hungry = 0.5 ok
راهنمایی :
خروجی یک دیکشنری از درصد ها خواهد بود که جمعشون 100 میشه
'''
number_of_hungry_people = [4 * ('not_hungry',)] * 3 # ['hungry'] * 3
number_of_not_hungry_people = [('not_hungry',)] * 2 # ['not hungry'] * 2 => 0.5 ok * 2 = ok
number_of_ok_people = [2 * ('not_hungry',)] * 1
total = number_of_hungry_people + number_of_not_hungry_people + number_of_ok_people
# print(total)
s = 0
for person in total:
for i in person:
if i == 'not_hungry':
s += 1
d = dict()
i = 1
for person in total:
hunger_rate = person.count('not_hungry')
if hunger_rate == 4:
d[f'person {i}th is hungry'] = (hunger_rate / s) * 100
elif hunger_rate == 2:
d[f'person {i}th is ok'] = (hunger_rate / s) * 100
else:
d[f'person {i}th is not_hungry'] = (hunger_rate / s) * 100
i += 1
print(d)
# by Shervin Hasanzadeh
|
2289c1c9c94547bd0e81216fce8698b409a85024 | pangeon/PythonStart | /games/hangman/utils.py | 1,168 | 3.515625 | 4 | def print_with_word_decorator(word, decorator):
print("-----------------------------\n")
for sign in word:
print(sign, end=decorator)
print("\n\n-----------------------------")
def fill_breaks(list, sign):
print("not implemented yet")
def index_of_set(set, index):
try:
sorted_list = list(set)
sorted_list.sort()
return sorted_list[index]
except IndexError:
print("Index must be smaller than set size")
return -1
def concat_list_letters(char_list):
word = ""
for elem in char_list:
word += elem
return word
def split_word_to_list(word):
char_list = []
for letter in word:
char_list.append(letter)
return char_list
def get_mock_list(list, mock_char):
mock_list = []
for _ in list:
mock_list.append(mock_char)
return mock_list
def find_char_occurrences(expected_letter, word, info=False):
char_occurrences = []
for index, letter in enumerate(word):
if expected_letter == letter:
char_occurrences.append(index)
if (info == True):
print(char_occurrences)
return char_occurrences
|
621692393c7ffe8cdf34af52b114c714915a656d | pangeon/PythonStart | /games/poker/Card.py | 1,313 | 3.796875 | 4 | """
Class representing one card:
value, color and file with image
"""
class Card:
VALUES = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'As']
COLORS = ['♥', '♦', '♣', '♠']
def __init__(self, value, color):
"""Init card - value and color."""
self._value = value
self._color = color
@property
def value(self):
"""Return card value"""
return self._value
@property
def color(self):
"""Return card color"""
return self._color
@property
def file_name(self):
"""Return image file name"""
images = []
colors = ['_heart', '_diamond', '_club', '_spade']
for card_index in range(len(self.VALUES)):
for color_index in range(4):
images.append(str.lower(self.VALUES[card_index]) + colors[color_index] + ".png")
return images
def __repr__(self):
"""Return official text representing of card"""
return f"Card(value='{self.value}, color='{self.color}')"
def __str__(self):
"""Return official text representing of card"""
return f'{self.value} {self.color}'
def __format__(self, format):
"""Return formatting text representing of card"""
return f'{str(self):{format}}'
|
2bf9c01949fb9f70a90f7b00d3a1e7590627253d | pangeon/PythonStart | /apps/eng-meme/text_utils.py | 705 | 3.8125 | 4 | def read_file_in_lines(reading_file):
for line in reading_file.readlines():
print(line.strip())
def write_line_in_file(file_to_writing, new_line, encoding):
with open(file_to_writing, "a", encoding=encoding) as file_oject:
file_oject.write(new_line + "\n")
def fill_and_split_line(first_word, second_word, size_empty_space):
first_empty_space = size_empty_space - len(first_word)
second_empty_space = size_empty_space - len(second_word)
x = 0
for x in range(first_empty_space):
first_word += " "
x += 1
for x in range(second_empty_space):
second_word += " "
x += 1
return "| " + first_word + "| " + second_word + "| "
|
4c15aefb6e7b4ffd117851b2387789c407c6fb78 | BenjiKCF/Codewars | /day151.py | 239 | 3.984375 | 4 | def square_sum(numbers):
if numbers:
return reduce(lambda x,y: x+y, map(lambda x: x**2, numbers))
else:
return 0
print square_sum([0, 3, 4, 5])#, 50)
def square_sum(numbers):
return sum(x**2 for x in numbers)
|
fa4d2431bf7ef725516144689ef544df694108af | BenjiKCF/Codewars | /day209.py | 611 | 3.828125 | 4 | def move_zeros(array):
n_array = []
z_array = []
for i in array:
if (i == 0 or i==0.):#and i != False:
if str(i) == str(False):
n_array.append(i)
else:
z_array.append(i)
else:
n_array.append(i)
return n_array + z_array
print move_zeros(["a",0,0,"b",None,"c","d",0,1,False,0,1,0,3,[],0,1,9,0,0,{},0,0,9])#
# ['a', 'b', None, 'c', 'd', 1, False, 1, 3, [], 1, 9, {}, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
def move_zeros(arr):
l = [i for i in arr if isinstance(i, bool) or i!=0]
return l+[0]*(len(arr)-len(l))
|
5ef6af9697f8e7806a579d17567b48bc0b635627 | BenjiKCF/Codewars | /day122.py | 397 | 4.03125 | 4 | def row_sum_odd_numbers(n):
total = sum([i for i in range(n+1)])
return sum([1 + 2 * i for i in range(total)][-n:])
print row_sum_odd_numbers(2)#, 8)
print row_sum_odd_numbers(3)
print row_sum_odd_numbers(4)
# 1
# 3 5
# 7 9 11
# 13 15 17 19
#21 23 25 27 29
def row_sum_odd_numbers(n):
#your code here
return n ** 3
|
bf219935cbf0a55ba517ca44e33b6e179f2ea352 | BenjiKCF/Codewars | /day52.py | 457 | 3.875 | 4 | costs = {'socks':5, 'shoes':60, 'sweater':30}
def getTotal(costs, items, tax):
items1 = [ch for ch in items if ch in costs]
return round(sum([costs[word] for word in items1])*(1+tax),2)
print getTotal(costs, ['socks', 'shoes'], 0.09)
print getTotal(costs, ['shirt', 'shoes'], 0.09)
#-> 5+60 = 65
#-> 65 + 0.09 of 65 = 70.85
#-> Output: 70.85
def getTotal(costs, items, tax):
return round(sum(costs.get(e, 0) for e in items) * (1 + tax), 2)
|
3a9572bd678ccbb324d12d945f3d19f4ae64619b | BenjiKCF/Codewars | /day197.py | 403 | 4.15625 | 4 | def valid_parentheses(string):
new_bracket = []
for i in string:
if i.isalpha():
pass
else:
new_bracket.append(i)
new_bracket = ''.join(new_bracket)
while '()' in new_bracket:
new_bracket = new_bracket.replace('()', '')
return new_bracket==''
print valid_parentheses("hi(hi)()")# ,True)
# while '{}' in s or '()' in s or '[]' in s:
|
cacd6d97d087ee0fcbaf0a79d4e1f7f0893a22fa | BenjiKCF/Codewars | /day87.py | 272 | 3.84375 | 4 | def disemvowel(string):
return ''.join([ '' if ch in 'AEIOUaeiou' else ch for ch in string])
print disemvowel("This website is for losers LOL!")
# "Ths wbst s fr lsrs LL!")
def disemvowel(s):
return s.translate(None, "aeiouAEIOU")
|
7a66baf7916bcdb97b2ca3bf15c571d87d2f1bbe | BenjiKCF/Codewars | /day185.py | 411 | 3.546875 | 4 | def sum_of_n(n):
ans = []
accum = 0
if n >= 0:
for i in range(n+1):
accum += i
ans.append(accum)
return ans
else:
for i in range(abs(n)+1):
accum += i
ans.append(-accum)
return ans
print sum_of_n(3)
print sum_of_n(-4)
def sum_of_n(n):
return [(-1 if n < 0 else 1) * sum(xrange(i+1)) for i in xrange(abs(n)+1)]
|
d90fc714468efd0c6837dd9d6ac936cc9cc82156 | BenjiKCF/Codewars | /day108.py | 140 | 3.5 | 4 | def find_next_square(sq):
return int((sq ** 0.5 + 1) ** 2) if (sq ** 0.5 + 1) ** 2 % 1 == 0 else -1
print find_next_square(121)#, 144,
|
975649cbd509d86c761b112b67023166cde1c0fa | BenjiKCF/Codewars | /day76.py | 361 | 3.78125 | 4 | def sequence_sum(begin_number, end_number, step):
if begin_number > end_number:
return 0
else:
i = (end_number - begin_number) / step
ans = 0
for j in range(i+1):
ans = ans + begin_number
begin_number += step
return ans
print sequence_sum(2, 6, 2)#, 12)
print sequence_sum(1, 5, 1)#, 15)
|
dc2fbd1c6744b544b9a1d285db6bd9bd65c2ee09 | BenjiKCF/Codewars | /day8.py | 218 | 3.515625 | 4 | demo = ("22 33 56 2 1.4 67.4 34.5 49 11.2")
# Make it into a list
# split the space and add comma
# Make the string into a floating number
values = [float(i) for i in demo.split()]
print sum(float(i) for i in values)
|
54c854955aeb20cfc3fc8b0c4e35034b83af7bbc | BenjiKCF/Codewars | /day130.py | 278 | 3.6875 | 4 | def xor(a,b):
return bool(a) != bool(b)
print xor(False, False)#, False, "False xor False == False")
print xor(True, False)#, True, "True xor False == True")
print xor(False, True)#, True, "False xor True == True")
print xor(True, True)#, False, "True xor True == False")
|
cb136b8c30bdd6ceb960bbfc07a4b963f1913e91 | BenjiKCF/Codewars | /day189.py | 432 | 3.59375 | 4 | def digital_root(n):
n = n
while counter(n) != True:
n = summer(n)
return n
def counter(n):
if len(str(n)) != 1:
return False
else:
return True
def summer(n):
num_sum = 0
for i in str(n):
num_sum += int(i)
return num_sum
print digital_root(16)#, 7 )
print digital_root(132189)
def digital_root(n):
return n if n < 10 else digital_root(sum(map(int,str(n))))
|
92620f3f63187c9820fe2ebecf8ec6bba4b7ad36 | JasonLeong81/Data_Science | /Flask/theory/decorators.py | 608 | 3.625 | 4 | def df(original):
def wrapper(*args,**kwargs): # args and kwargs is for any number of arguments and keyword argument
print('a',*args)
print('k', **kwargs)
return original(*args,**kwargs)
return wrapper
@df # same as saying display = df(display), which is also = wrapper
def display(x):
print(x)
# display(1)
response = ['Go get Jason a cup of water','Go massage for Jason','Go keep your toys',"Go wash Jason's plate",'Go clean the table','I love you']
response1 = ['stupid','tiffany is fat','you are fat',"you're ugly","you're short and fat","you look like a fat pig"]
|
8098828158d4bc3f6e3413e7b14a2c6d8f8a2512 | xiongfeihtp/scikit_learn | /naive_bayes/iris_classification_using_naive_bayes.py | 1,000 | 3.640625 | 4 | #! /usr/bin/env python
#coding=utf-8
# Authors: Hanxiaoyang <hanxiaoyang.ml@gmail.com>
# simple naive bayes classifier to classify iris dataset
# 代码功能:简易朴素贝叶斯分类器,直接取iris数据集,根据花的多种数据特征,判定是什么花
# 详细说明参见博客http://blog.csdn.net/han_xiaoyang/article/details/50629608
# 作者:寒小阳<hanxiaoyang.ml@gmail.com>
from sklearn import datasets
iris = datasets.load_iris()
iris.data[:5]
from sklearn.metrics import accuracy_score
#我们假定sepal length, sepal width, petal length, petal width 4个量独立且服从高斯分布,用贝叶斯分类器建模
from sklearn.naive_bayes import GaussianNB
gnb = GaussianNB()
y_pred = gnb.fit(iris.data, iris.target).predict(iris.data)
right_num = (iris.target == y_pred).sum()
print("Total testing num :%d , naive bayes accuracy :%f" %(iris.data.shape[0], float(right_num)/iris.data.shape[0]))
# Total testing num :150 , naive bayes accuracy :0.960000
print(accuracy_score(y_pred,iris.target))
|
2a2e075d62539391532227c3e2db2d6c412dea25 | ken0823/scheduling | /TaskQueue.py | 2,725 | 3.625 | 4 | #! /usr/bin/python
# *-* encoding: utf-8 *-*
import heapq
import itertools
class TaskQueue:
REMOVED = '<removed-task>' # placeholder for a removed task
def __init__(self, name=""):
self.name = name
self.pq = [] # list of entries arranged in a heap
self.entry_finder = {} # mapping of tasks to entries
self.counter = itertools.count() # unique sequence count
def set_TaskQueue(self, task_queue):
self.pq = task_queue
heapq.heapify(self.pq)
def add_TaskQueue(self, priority, task, c_rem):
'Add a new task or update the priority of an existing task'
if task in self.entry_finder:
entry = self.entry_finder.pop(task)
entry[1] = self.REMOVED
count = next(self.counter)
entry = [priority, task, c_rem, count]
self.entry_finder[task] = entry
heapq.heappush(self.pq, entry)
def remove_TaskQueue(self, task):
'Remove an existing task'
if task in self.entry_finder:
entry = self.entry_finder.pop(task)
entry[1] = self.REMOVED
def pop_TaskQueue(self):
'Remove and return the lowest priority task. Raise KeyError if empty.'
while self.pq:
priority, task, c_rem, count = heapq.heappop(self.pq)
if task is not self.REMOVED:
del self.entry_finder[task]
return [priority, task, c_rem, count]
return 0
def get_TaskQueueTop(self):
'Return the lowest priority task without pop'
while self.pq:
priority, task, c_rem, count = self.pq[0]
if task is not self.REMOVED:
return [priority, task, c_rem, count]
else:
heapq.heappop(self.pq)
return 0
def get_TaskQueueList(self):
'Return the task queue without <removed-task> item by <list> type'
queue_reallist = []
queue_list = heapq.nsmallest(len(self.pq), self.pq)
for i in range(len(queue_list)):
priority, task, c_rem, count = queue_list[i]
if task is not self.REMOVED:
queue_reallist.append(queue_list[i])
else:
pass
return queue_reallist
def get_TaskQueueLen(self):
'Return the task queue length without <removed-task> item'
length = 0
for i in range(len(self.pq)):
priority, task, c_rem, count = self.pq[i]
if task is not self.REMOVED:
length = length + 1
else:
pass
return length
def print_entryfinder(self):
print self.entry_finder
def print_taskqueue(self):
print self.pq
|
615aac56dfb86888d3f017db271bea4a309387cf | mariiamatvienko/OOP | /classes/cart_window.py | 1,283 | 3.890625 | 4 | from tkinter import *
def to_delete():
res = txt.get()
cartList.remove(res)
lbl1.configure(text=cartList)
txt.delete(0, END)
def to_buy():
destroy_object = [lbl, lbl1, lbl2, lbl3, btn, btn2, txt]
for object_name in destroy_object:
if object_name.winfo_viewable():
object_name.grid_remove()
else:
object_name.grid()
lbl_buy = Label(window, text="Your order was confirmed!")
lbl_buy.grid(column=2, row=0)
lbl_buy.after(2000,close_window)
def close_window():
window.destroy()
cartList = ["computer", "mobile", "tablet"]
window = Tk()
window.title("Cart")
window.geometry('600x250')
lbl = Label(window, text="Items added to the cart", font=("Arial Bold", 12))
lbl.grid(column=1, row=0)
lbl1 = Label(window, text=cartList)
lbl1.grid(column=0, row=2)
lbl3 = Label(window, text="Enter name of product to delete from cart:")
lbl3.grid(column=0, row=4)
txt = Entry(window, width=20)
txt.grid(column=1, row=4)
txt.focus()
btn = Button(window, text="Delete", command=to_delete)
btn.grid(column=1, row=5, pady=5)
lbl2 = Label(window, text="To buy products click on the button")
lbl2.grid(column=0, row=7)
btn2 = Button(window, text="Buy", command=to_buy)
btn2.grid(column=1, row=7)
window.mainloop() |
fea81f00604221bd490e564c045d58b0e6b2e554 | madilon/dojos | /phf.py | 799 | 3.90625 | 4 | nume1=input("Salut jucator 1, cum te numesti? ")
nume2=input("Salut jucator 2, cum te numesti? ")
i = "DA"
while i == "DA":
hpf1 = input(nume1+", alege: hartia, piatra sau foarfeca: ")
hpf2 = input(nume2+", alege: hartia, piatra sau foarfeca: ")
if hpf1 == hpf2:
print("Este egalitate!")
elif hpf1 == "piatra":
if hpf2 == "foarfeca":
print(nume1+",felicitari! Ai castigat! ")
else:
print(nume2+",felicitari! Ai castigat! ")
elif hpf1 == "foarfeca":
if hpf2 == "hartia":
print(nume1+",felicitari! Ai castigat! ")
else:
print(nume2+",felicitari! Ai castigat! ")
elif hpf1 == "hartia":
if hpf2 == "piatra":
print(nume1+",felicitari! Ai castigat! ")
else:
print(nume2+",felicitari! Ai castigat! ")
i = input("Joc nou? ")
print("Joc terminat!") |
7025bdf92b869bc69d624b93899cf1b5d72fb8ce | madilon/dojos | /mmm.py | 400 | 3.828125 | 4 | name = input("What is yur name ? ")
job = input("what job do you wanna aply for ? ")
time = input("How much time woud you take for obtaining this job ? ")
steps = input("what are the steps that you need to follow in order to get to get this job ? ")
first_Day = input("when would you like to start ? ")
print("Candidatul a raspuns urmatoarelor intrebari : ")
print(name, job, time, steps, first_Day)
|
e77d7ad02c2140c45463ccda2e62a3f03468e868 | azpm/django-scampi-cms | /libscampi/utils/string.py | 374 | 3.859375 | 4 | stopwords = '''
i
a
an
are
as
at
be
by
for
from
how
in
is
it
of
on
or
that
the
this
to
was
what
when
where
'''.split()
def strip_stopwords(sentence):
"""Removes stopwords - also normalizes whitespace"""
words = sentence.split()
sentence = []
for word in words:
if word.lower() not in stopwords:
sentence.append(word)
return sentence
|
5da6c1c5288dd7fbd5249ab71a80f5f77b462fcb | colbyktang/Assignment9 | /battleship.py | 3,373 | 3.5625 | 4 | import random
# constants
HIT_MARKER = 'X'
MISS_MARKER = 'O'
INIT_MARKER = '#'
PLAYER_MARKER = 'P'
# board size
rowSize = 5
colSize = 5
# enemy ship start
isEnemyAlive = True
enemy_row = random.randint(0,rowSize - 1)
enemy_col = random.randint(0,colSize - 1)
# player ship start
isPlayerAlive = True
playerShip_row = random.randint(0,rowSize - 1)
playerShip_col = random.randint(0,colSize - 1)
while (enemy_row == playerShip_row or enemy_col == playerShip_col):
playerShip_row = random.randint(0,rowSize - 1)
playerShip_col = random.randint(0,colSize - 1)
# save ship positions
enemyShipPositions = [[enemy_row, enemy_col]]
playerShipPositions = [[playerShip_row, playerShip_col]]
shipPositions = []
shipPositions.append (enemyShipPositions)
shipPositions.append(playerShipPositions)
print ("Player ship at", playerShipPositions)
print ("Enemy ship at", enemyShipPositions)
endMessage = "Game Over!"
# initialize boardMatrix
boardMatrix = [INIT_MARKER] * rowSize
for i in range(rowSize):
boardMatrix[i] = [INIT_MARKER] * colSize
# set player marker
boardMatrix[playerShip_row][playerShip_col] = PLAYER_MARKER
# print output
def printBoard ():
for i in range(rowSize):
string = ""
for j in range(colSize):
string += boardMatrix[i][j] + " "
print (string)
# calculate hit results
def calculateHit(row, col):
global isPlayerAlive
global isEnemyAlive
global endMessage
isHit = False
for i in range(len(shipPositions)):
if (shipPositions[i] == [[row,col]]):
isHit = True
if (row == playerShip_row and col == playerShip_col):
print ("You got hit!")
isPlayerAlive = False
endMessage = "Game Over! You got hit!"
elif (row == enemy_row and col == enemy_col):
isEnemyAlive = False
endMessage = "Game Over! You defeated the enemy ship!"
if (isHit):
boardMatrix[row][col] = HIT_MARKER
else:
boardMatrix[row][col] = MISS_MARKER
# game process
def game ():
isGameRunning = True
# keep the game running
while (isGameRunning and isPlayerAlive and isEnemyAlive):
isInputValid = False
# input loop
while (not isInputValid):
player_input = input("Choose a row and a column, separated by a space: ").split()
if (len(player_input) != 2):
if (player_input[0] == "exit"):
print ("Exiting game...")
isGameRunning = False
return
print ("Input invalid! Try again!")
else:
isInputValid = True
# player input position
player_row = int(player_input[0])
player_col = int(player_input[1])
# validate position
if (player_row < 0 or player_row >= rowSize):
print ("ROW OUT OF BOUNDS!")
elif (player_col < 0 or player_col >= rowSize):
print ("Column OUT OF BOUNDS!")
# hit the board
else:
calculateHit (player_row, player_col)
printBoard()
# when game is over, print game over message
print (endMessage)
# start game
printBoard()
game()
|
3e8798e7fc4fd6694233b9780ef454bff463bd34 | AdamSiekierski/podpowloki | /main.py | 983 | 3.5625 | 4 | import json
table = json.load(open('./periodic_table.json'))
mode = input('Wybierz tryb (liczba atomowa - 1, symbol - 2): ')
if (mode == '1'):
number = input('Podaj liczbę atomową: ')
for atom in table['elements']:
if (atom['number'] == int(number)):
foundAtom = atom
break
try: foundAtom
except NameError: foundAtom = None
if (foundAtom == None):
print('Nie znaleziono takiego atomu')
else:
print(foundAtom['electron_configuration'])
elif (mode == '2'):
symbol = input('Podaj symbol atomu: ')
for atom in table['elements']:
if (atom['symbol'] == symbol):
foundAtom = atom
break
try: foundAtom
except NameError: foundAtom = None
if (foundAtom == None):
print('Nie znaleziono takiego atomu')
else:
print(foundAtom['electron_configuration'])
else:
print('Nie istnieje tryb ', mode)
|
39218e773ed24e5f2e41874e78765b1e1cd3668e | nephylum/cs-sprint-challenge-hash-tables | /hashtables/ex3/ex3.py | 809 | 3.828125 | 4 | def intersection(arrays):
hash ={}
# create a list to start checking for duplicate values
for x in arrays[0]:
hash[x] = 0
for x in range(1, len(arrays)):
for y in arrays[x]:
if y in hash:
hash[y] += 1
todrop = []
for item in hash:
if hash[item] == 0:
todrop.append(item)
#hash.pop(item, None)
for x in todrop:
hash.pop(x, None)
result = []
for x in hash:
result.append(x)
return result
if __name__ == "__main__":
arrays = []
arrays.append(list(range(1000000, 2000000)) + [1, 2, 3])
arrays.append(list(range(2000000, 3000000)) + [1, 2, 3])
arrays.append(list(range(3000000, 4000000)) + [1, 2, 3])
print(intersection(arrays))
|
bf1c783c532584c73e1fc01c97ca6ca7d3e5d958 | usmankhan-bit/APS-2020 | /kruskal_union_find.py | 1,083 | 3.59375 | 4 | graph=[]
union_array=[]
def initialize_union_array(N):
global union_array
for i in range(N):
union_array.append(i)
def union(u,v):
global union_array
value = union_array[v]
replace_value = union_array[u]
for i,ele in enumerate(union_array):
if ele == replace_value:
union_array[i] = value
def find(u,v):
global union_array
if union_array[u] == union_array[v]:
return True
else:
return False
def addEdge(u,v,w):
global graph
graph.append([u,v,w])
def kruskal():
global graph,union_array
result=[]
graph=sorted(graph,key=lambda item:item[2])
for li in graph:
if find(li[0],li[1])==False:
union(li[0],li[1])
result.append(li)
print(result)
N = int(input()) #no. of vertices
initialize_union_array(N)
addEdge(0,1,8)
addEdge(0,7,16)
addEdge(1,7,22)
addEdge(1,2,16)
addEdge(7,8,14)
addEdge(8,6,12)
addEdge(7,6,2)
addEdge(2,8,4)
addEdge(2,5,8)
addEdge(6,5,4)
addEdge(2,3,14)
addEdge(3,5,28)
addEdge(3,4,18)
addEdge(4,5,20)
kruskal()
|
9fb4e71f024613a95e38d4ee4a5181dcf306e967 | usmankhan-bit/APS-2020 | /bitwise_check_even_odd.py | 97 | 3.765625 | 4 | n = int(input())
cond = n&1
if cond == 1:
print("Odd number")
else:
print("Even number")
|
9391b1f946e40799b19d6339dd5616b797e3a307 | Roman-Sergeichuk/python-project-lvl1 | /brain_games/cli.py | 729 | 3.5625 | 4 | import prompt
def greet():
print('Welcome to the Brain Games!')
def welcome_user(rules):
print(rules)
print()
name = prompt.string('May I have your name? ')
print('Hello, {}!'.format(name))
print()
return name
def request_answer(question):
print(f'Question: {question}')
user_answer = prompt.string('Your answer: ')
return user_answer
def show_wrong_answer_message(user_answer, true_answer, name):
print(
f"'{user_answer}' is wrong answer ;(. Correct answer was '{true_answer}'." # noqa: E501
f"\nLet's try again, {name}!"
)
def show_right_answer_message():
print('Correct!')
def show_win_game_message(name):
print(f'Congratulations, {name}!')
|
874325d003ec7e630535b9c95e60fa60a5c04809 | abvita/web-caesar | /caesar.py | 527 | 3.859375 | 4 | def alphabet_position(letter):
lwr_let = letter.lower()
pos = ord(lwr_let) - 97
return pos
def rotate_character(char, rot):
if not char.isalpha():
return char
else:
rotated = chr(alphabet_position(char) + rot + 97)
if not rotated.isalpha():
rotated = chr(ord(rotated) - 26)
if char.isupper():
rotated = rotated.upper()
return rotated
def encrypt(text,rot):
result = ""
for i in text:
result += rotate_character(i, rot)
return result
|
7933f2a8eea631c8519a2bbb722ba672203bd265 | smrsan/py3-practice-games | /guess/__init__.py | 895 | 3.921875 | 4 | from random import random
# Misc
from utils import clear_term
def guess_game():
resume = True
while resume:
clear_term()
hidden_num = int(random() * 100)
while True:
guess_num = input('Guess the hidden num [0-99]: ').strip()
if not guess_num.isnumeric():
continue
guess_num = int(guess_num)
if guess_num < 0 or guess_num > 99:
continue
if guess_num > hidden_num:
print("It's greater than the hidden num...")
elif guess_num < hidden_num:
print("It's less than the hidden num...")
else:
print("You WON..!")
user_inpt = input("Do u wanna play again? ['Yes'/...]: ")
resume = user_inpt.lower() == 'yes'
break
if not resume:
break
|
5bbc50d474f269db0d5b09b418ca5ba232d08e26 | smrsan/py3-practice-games | /rocks_papers_scissors/__init__.py | 1,106 | 4.09375 | 4 | from random import random
from utils import get_item_by_index, is_numeric, clear_term
def rps_game():
elements = {
'rock': 'scissor',
'paper': 'rock',
'scissor': 'paper'
}
while True:
clear_term()
pc_choice = get_item_by_index(elements, int(random() * 3))
print("""Which one?
1. rock
2. paper
3. scissor
(sth else = quit)""")
your_choice = input('Enter the number of your choice: ')
if not is_numeric(your_choice):
break
your_choice = get_item_by_index(elements, int(your_choice) - 1)
if your_choice[0] == 'quit':
break
if your_choice[0] == pc_choice[0]:
print(f'Equal choices: {your_choice[0]}')
elif your_choice[1] == pc_choice[0]:
print(f'You won!!! -> {your_choice[0]} vs {pc_choice[0]}')
elif pc_choice[1] == your_choice[0]:
print(f'You lost... -> {your_choice[0]} vs {pc_choice[0]}')
ans = input('Play again? (type "yes", otherwise anything else...): ')
if not ans.lower() == 'yes':
break
|
83d0dbb2a5025698e455eb39cd4f218bc8a9fb03 | jerryjerry1128/password_retry | /password_retry.py | 326 | 3.875 | 4 | password = 'a123456'
n = 3
while n > 0:
if input('請輸入密碼: ') == password:
print('登入成功')
break
else:
n-=1
print('密碼錯誤! ')
if n > 0:
print('還有',n,'次機會')
else:
print('沒機會了! 要鎖帳號了啦!')
|
d23e4d70647b5b43cc5b55ff4810d0eb932ed898 | Souravvk18/DSA-nd-ALGO | /Data Structures/element_of_linked_list.py | 156 | 3.921875 | 4 | # Print the Elements of a Linked List
def printLinkedList(head):
node = head
while node != None:
print(node.data)
node = node.next
|
25655f1e9c0e10ec72281b7982c1e0d10c2eef26 | Souravvk18/DSA-nd-ALGO | /Data Structures/print_the_element_linkedlist.py | 312 | 4 | 4 | # print the element of a linked list
def reversePrint(head):
if head is None:
return
else:
out = []
node = head
while node != None:
out.append(node.data)
node = node.next
print("\n".join(map(str, out[::-1])))
|
c541eb7254ed01492794dd75609d24ee897ea708 | NguyenTheAnhBK/Cryptography | /Monoalphabetic/Example2.py | 2,150 | 3.5625 | 4 | # -*- coding: utf-8 -*-
# Mã hóa chuỗi ký tự bất kỳ sử dụng mật mã nhân (không mã hóa khoảng trống)
# Hàm tìm ước chung lớn nhất
def gcd(a, b):
while b > 0:
q = a // b
r = a - b*q
a, b = b, r
return a
# Hàm tìm nghịch đảo của k (k')
def module_inverse(k, n = 94): # với n bất kỳ
t1, t2 = 0, 1
while k > 0:
q = n // k
r = n - k*q
n, k = k, r
t = t1 - t2*q
t1, t2 = t2, t
if n == 1:
return t1
return 0 # với 0 là không tồn tại nghịch đảo của k với phép module n
# Hàm mã hóa mật mã nhân
def encrypt(plainText, k):
cipherText = ""
for i in range(len(plainText)):
if plainText[i] == " ":
cipherText += plainText[i] # += " "
else:
cipherText += chr((((ord(plainText[i]) - 33) * k ) % 94) + 33 ) # 94 = 126 - 33 + 1
return cipherText
# Hàm giải mã mật mã nhân
def decrypt(cipherText, k):
k = module_inverse(k, 94)
if k != 0:
plainText = ""
for i in range(len(cipherText)):
if cipherText[i] == " ":
plainText += cipherText[i] # += " "
else:
plainText += chr((((ord(cipherText[i]) - 33) * k ) % 94) + 33 ) # 94 = 126 - 33 + 1
return plainText
return 0 # Không thể giải mã được
def multiplicativeCipher_encode():
print('Nhập bản rõ: ')
plainText = str(input())
print("Nhập k: ")
k = int(input())
while k < 0:
print("Nhập lại k: ")
k = int(input())
cipherText = encrypt(plainText, k)
print('Bản mã: %s' % cipherText)
def multiplicativeCipher_decode():
print('Nhập bản mã: ')
cipherText = str(input())
print("Nhập k: ")
k = int(input())
while k < 0:
print("Nhập lại k: ")
k = int(input())
plainText = decrypt(cipherText, k)
if plainText == 0:
print('Không thể giải mã !')
else:
print('Bản mã: %s' % plainText)
# Main
multiplicativeCipher_encode()
multiplicativeCipher_decode()
|
104b485166ffcde6ab4e6785ab13d57cd5dd12fd | ggolish/GANs | /loader/img_utils.py | 1,897 | 3.671875 | 4 | #!/usr/bin/env python3
""" Module for image utilities. """
import numpy as np
import cv2
def crop(img: np.array, size):
""" Take a numpy array and crop it to size """
y, x, z = img.shape
cx = (x // 2) - (size // 2)
cy = (y // 2) - (size // 2)
return img[cy:cy+size, cx:cx+size, :]
def northwest(img, size):
""" Take the northwest 2/3 of an image and return it scaled down to size """
y, x, z = img.shape
# return np.resize(img[:y//4, :x//4, :], (size, size, z))
img = img[:(y*2)//3, :(x*2)//3, :]
return cv2.resize(img, dsize=(size, size), interpolation=cv2.INTER_CUBIC)
def southwest(img: np.array, size):
""" Take the southwest 2/3 of an image and return it scaled down to size """
y, x, z = img.shape
img = img[-(y*2)//3:, :(x*2)//3, :]
return cv2.resize(img, dsize=(size, size), interpolation=cv2.INTER_CUBIC)
def southeast(img: np.array, size):
""" Take the southeast 2/3 of an image and return it scaled down to size """
y, x, z = img.shape
img = img[-(y*2)//3:, -(x*2)//3:, :]
return cv2.resize(img, dsize=(size, size), interpolation=cv2.INTER_CUBIC)
def northeast(img: np.array, size):
""" Take the northeast 2/3 of an image and return it scaled down to size """
y, x, z = img.shape
img = img[:(y*2)//3, -(x*2)//3:, :]
return cv2.resize(img, dsize=(size, size), interpolation=cv2.INTER_CUBIC)
if __name__ == '__main__':
import os
from loader import load_data
from loader import ross
import matplotlib.pyplot as plt
if not os.path.exists(ross.final_dir):
ross.download()
data = load_data(ross.final_dir, verbose=True, imsize=256)
data /= 255
fig = plt.figure(figsize=(8,8))
columns = 4
rows = 3
for i in range(1, columns*rows +1):
img = data[i-1]
fig.add_subplot(rows, columns, i)
plt.imshow(img)
plt.show()
|
57ad9f57bcb654294e3c049b2719224c6ebf7090 | catcatlin/Learn-Python3-the-Hard-Way | /ex13.py | 811 | 3.984375 | 4 | # print("\n")
# 测试1
# from sys import argv
# # read the WYSS section for how to run this
# script, first, second, third = argv
#
# print("The script is called:", script)
# print("Your first variable is:", first)
# print("Your second variavle is:", second)
# print("Your third variable is:", third)
# print("\n")
# 测试2
# from sys import argv
# # read the WYSS section for how to run this
# script, first, second = argv
#
# print("The script is called:", script)
# print("Your first variable is:", first)
# print("Your second variavle is:", second)
# 测试3
from sys import argv
script, first, second = argv
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variavle is:", second)
first = input()
second = input()
print("是这样?", first, second)
|
37f5da993631372d27d2f5670f49663e8eaea566 | DMarchezini/UriOnlineJudge-Python | /Uri1038.py | 367 | 3.546875 | 4 | """Exemplo de Entrada Exemplo de Saída
3 2
Total: R$ 10.00
4 3
Total: R$ 6.00
2 3
Total: R$ 13.50
"""
info = input().split(' ')
cod, qtd = info
cod = int(cod)
qtd = int(qtd)
valores = [(1, 4), (2, 4.5), (3, 5), (4, 2), (5, 1.5)]
for valor in valores:
if valor[0] == cod:
total = valor[1] * qtd
print(f'Total: R$ {format(float(total), ".2f")}')
|
97b21f6149326fba8c267ba0dba2ab56ef23a51f | DMarchezini/UriOnlineJudge-Python | /Uri1015.py | 306 | 3.71875 | 4 | """
Exemplo de Entrada Exemplo de Saída
1.0 7.0
5.0 9.0
4.4721
-2.5 0.4
12.1 7.3
16.1484
2.5 -0.4
-12.2 7.0
16.4575
"""
import math
p1 = input().split(" ")
p2 = input().split(" ")
x1, y1 = p1
x2, y2 = p2
res = format(math.sqrt((float(x2) - float(x1))**2 + (float(y2) - float(y1))**2), '.4f')
print(res)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.