blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
b52f7a3e522b22af97a7dd5162362d58df6fd4ce | JontePonte/SudokuSolver2 | /find_single_possibilities.py | 896 | 4.09375 | 4 |
def find_single_possibilities(field, list):
""" Check if a possibility in the field only appears ones in a list of fields. Sets the fields possibility to that value if so """
if len(list) != 9:
raise ValueError("The list input to find_single_possibilities must be == 9")
# Only check the unset numbers
if field.number == 0:
for num in field.possible:
# The num_found_times is the amount of times the possibility has been found in other fields
num_found_times = 0
for other_field in list:
if other_field.id != field.id:
if num in other_field.possible:
num_found_times += 1
# If the possibility only is found in the working field then that is our number!
if num_found_times == 0:
return {num}
return field.possible
|
9af0f6ff99fc55bd7576acf4a2b8311ab77d75af | adgopi/python-practice-stuff | /leetcode/leetcode explore/arrays/4 search/check_if_double_exists.py | 513 | 3.8125 | 4 | from typing import List
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
'''
Return if there exist 2 elements in arr such
that one element is twice the other
'''
if arr.count(0)==1:
arr.remove(0)
elif arr.count(0)>=2:
return True
for i in range(len(arr)):
if arr[i]*2 in arr[:i]+arr[i+1:]:
return True
return False
print(Solution.checkIfExist('',[3,1,7,11])) |
add31cdf10913dc313ea4cf126dac536b1b5cb85 | supriyo-pal/Machine-Learning-with-python | /logistic regrassion(Binary classification).py | 629 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 21 23:49:45 2020
@author: Supriyo
"""
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
df=pd.read_csv("insurance_data.csv")
plt.scatter(df.age,df.bought_insurance,marker="+",color="red")
plt.xlabel("Age",fontsize=10)
plt.ylabel("Insurance bought or not",fontsize=10)
x_train,x_test,y_train,y_test=train_test_split(df[['age']],df.bought_insurance,train_size=0.9)
model=LogisticRegression()
model.fit(x_train,y_train)
model.predict(x_test)
|
91790f42d6f3b19e7c56bc82f65760f962035f70 | Fgsj10/Python_Trainning | /Strings/Code_Four.py | 511 | 3.984375 | 4 | """
Author = Francisco Gomes
"""
#User data input and variables
print("Validating number cellphone")
number = str(input("Enter with a number: "))
phoneFormated = number.replace("-", "")
#Checking of number cellphone is validate
if(len(phoneFormated) == 7):
print("Cellphone with 7 digits, adding number 3 in front")
#Printing cellphone not formated
print("Cellphone not formated is: 3%s " %(phoneFormated))
#Printing cellphone with formated
print("Cellphone with formated is: 3%s " %(number))
|
8628b5ea1e1674bfe3345fb3752e417dddd36bbe | jacocloeteHU/TICT-V1PROG-15 | /les 02/perkoviz exercises.py | 1,247 | 3.546875 | 4 |
def p(val):
print(val)
return;
# avarage
p((23+19+31)/3)
# 2.1
p(7 + 7+ 7+7 +7)
p(403 // 73)
p(403 % 73)
p(2**10)
p(57-54)
p(min(34.99,29.95,31.50))
# 2.2
p((2+2) < 4)
p((7 // 3) == (1 + 1))
p(((3**3) + (4**4) == 25))
p((2+4+6) > 12)
p((1387 / 19) and True)
p(31 % 2 == 2)
p(min(29.95,34.99) < 30.00)
# 2.3
a = 3
b = 4
c = a * a + b * b
p(c)
# 2.12
s1 = "-"
s2 = "+"
p(s1 + s2)
p(s1 + s2 + s1)
p(s2 + s1 + s1)
p((s2 + s1 + s1 ) * 2)
p((s2 + s1 + s1 ) * 10 + s2)
p((s2 + s1 + s2 + s2 + s2 + s1 + s1) * 5)
# 2.13
s = "abcdefghijklmnopqrstuvwxyz"
p(s[0] + s[2]+ s[-1]+ s[-2] + s[-10])
# 2.14
st = "goodbye"
p(st[0] == "g")
p(st[6] == "g")
p((st[0] == "g") & (st[1] == "a"))
p(st[len(st) - 1] == "x")
p(st[3] == "d")
p(st[0] == st[6])
p(st[3] +st[4]+ st[5] +st[6]== 'tion')
# 2.18
flowers = ("rose","bougainvillea","yucca", "marigold", "daylilly", "lilly of the valley")
p('potato' in flowers)
thorny = flowers[0], flowers[1], flowers[2]
poisonous = flowers[-1],
dangerous = thorny + poisonous
p(dangerous)
# 2.19
awnsers = ['Y','N','N','Y','N','Y','N','Y','Y','Y','N','N','N']
numYes = 5
numNo = 6
percentYes = 5 / len(awnsers)
p(percentYes)
awnsers.sort()
p(awnsers)
p(awnsers.index('Y'))
f = awnsers.index('Y')
|
2c2da63a48bfe7ea6afd986851fa6f6c00eff5cb | BaoCaiH/Daily_Coding_Problem | /Python/2019_02_15_Problem_31_Edit_Distance.py | 1,189 | 4.1875 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## 2019 February 15th
#
# Problem: The edit distance between two strings refers to the minimum number of character insertions, deletions, and substitutions required to change one string to the other. For example, the edit distance between โkittenโ and โsittingโ is three: substitute the โkโ for โsโ, substitute the โeโ for โiโ, and append a โgโ.
#
# Given two strings, compute the edit distance between them.
# In[20]:
def edit_distance(string_1, string_2):
remain = ''
for c in string_1:
if c in string_2:
i = string_2.index(c)
string_2 = string_2[:i] + string_2[i+1:]
else:
remain += c
return max(len(remain), len(string_2))
# In[18]:
s1 = 'kitten'
s2 = 'sitting'
s3 = 'mitten'
s4 = 'substitute'
s5 = 'statue'
# In[24]:
print('Two strings \'{}\' and \'{}\' have edit distance of {}'.format(s1, s2, edit_distance(s1, s2)))
print('Two strings \'{}\' and \'{}\' have edit distance of {}'.format(s1, s3, edit_distance(s1, s3)))
print('Two strings \'{}\' and \'{}\' have edit distance of {}'.format(s4, s5, edit_distance(s4, s5)))
# In[ ]:
|
e7359ad91ccf1bf116022bc3a7609014deb4b971 | sco357/Python-HangMan | /Code.py | 12,834 | 3.71875 | 4 | play = True
while play:
# The below section is used to import the python modules into our code
import time
import os
import random
import sys
# The vairables are defined as 0 or nothing so that they can be operated with straight aaway
player_1_life = 0
player_2_life = 0
loop = int(0)
wordbank = []
contents = ""
hidden = ""
underscores = "".join(hidden)
# The code below defines the list with the different hangman images so that they can easily be printed out later
hangmanpics = [
'''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''','''
โโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโ''','''
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ'''
]
hangmanpicsfor2player = [
'''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''','''
โโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโ''','''
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ'''
]
# Welcomes the player to the game and asks them in which way they want to select the word
print('''
โโโโโโโโโโโโโโโโโโโโโโ
โโโโฆโโฆโโโฆโโโโโโโฆโโโโโโ
โโโโโโโ โโโโโโโโโโโ โโโโ
โโโโโฉโโโโโโโโโโฉโโฉโโโโโ
โโโโโโโโโโโโโโโโโโโโโโ''' " to Hangman!")
time.sleep(1.5)
input_type = input("Do you want to input a word or have a word selected randomly from a word bank txt file? Answer '1' for the first option of '2' for the second option. ")
# If the player chosces option one they are required to input a word
if input_type == "1":
print("You have selected to input a word.")
time.sleep(1)
print("Tip! Have a third party input the word so no player is aware of the answer.")
time.sleep(1.5)
ans = input("Input a word! ")
# If the player chosces option two they are required to input a txt file. The word will be randonmly selected from the txt file
elif input_type == "2":
print("You have selected to input a randomn word from a txt file!")
time.sleep(1.5)
file_name = input("Input a txt file located in the same folder as this program (I have included some demos with this submission). Remeber to include '.txt' at the end of the name. ")
# The below step imports the txt file into the code so it can be interpreted
with open(os.path.join(sys.path[0], f"{file_name}"), "r") as f:
contents = f.read()
#The below step of the code turns the txt file into a list (The txt file has to be turned into the list so that the random choice module captures an entire word and not just a character)
wordbank = contents.split()
# By using the randomn choice vairable, the code randomly chosces a word from the list
ans = random.choice(wordbank)
# After the answer is chosen, the hidden vairable can be defined
hidden = ['-'] * len(ans)
players = int(input("How many players do you have? 1/2 ? "))
if players == 1:
name = input ("Ok then, what is your name? ")
print(f"Hello {name}!")
time.sleep(0.5)
print(f"The answer has {len(ans)} letters!")
time.sleep(0.5)
print("Let's begin, start guessing!")
time.sleep(0.5)
while loop <= 6:
guess = input("Guess? ")
if guess.lower() in ans.lower():
print(f"Correct")
if len(guess) == 1:
for char in range(0, len(ans)):
if ans.lower()[char] == guess.lower():
hidden[char] = guess.upper()
underscores = "".join(hidden)
print(underscores)
elif guess.lower() == ans.lower():
hidden = ans
else:
print("That was not the word!")
loop = loop + 1
else:
print("That was incorrect!")
loop = loop + 1
if "-" not in hidden:
print("You won!")
loop = 8
if loop > 0:
print(hangmanpics[loop - 1])
if "-" in hidden:
print("What a shame you failed!")
print(f"The word was {ans}")
elif players == 2:
name1 = input("Player 1, what is your name? ")
name2 = input("Player 2, what is your name? ")
print(f"Hello {name1} and {name2}!")
while player_1_life + player_2_life <=6:
if player_1_life <= 3:
guess = input(f"Input a Guess {name1}! ")
if guess.lower() in ans.lower():
print(f"Correct")
if len(guess) == 1:
for char in range(0, len(ans)):
if ans.lower()[char] == guess.lower():
hidden[char] = guess.upper()
underscores = "".join(hidden)
print(underscores)
elif guess.lower() == ans.lower():
hidden = ans
else:
print(f"That was not the word {name1}!")
player_1_life = player_1_life + 1
if player_1_life == 4:
print(f"What a shame {name1} has failed!")
else:
print(f"That was incorrect {name1}!")
player_1_life = player_1_life + 1
if player_1_life == 4:
print(f"What a shame {name1} has failed!")
if "-" not in hidden:
print(f"You won {name1}!")
loop = 9
player_1_life = 5
if player_1_life > 0:
print(hangmanpicsfor2player[player_1_life - 1])
if loop <= 6:
if player_2_life <= 3:
guess = input(f"Input a Guess {name2}! ")
if guess.lower() in ans.lower():
print(f"Correct")
if len(guess) == 1:
for char in range(0, len(ans)):
if ans.lower()[char] == guess.lower():
hidden[char] = guess.upper()
underscores = "".join(hidden)
print(underscores)
elif guess.lower() == ans.lower():
hidden = ans
else:
print(f"That was not the word {name2}!")
player_2_life = player_2_life + 1
if player_2_life == 4:
print(f"What a shame {name2} has failed!")
else:
print(f"That was incorrect {name2}!")
player_2_life = player_2_life + 1
if player_2_life == 4:
print(f"What a shame {name2} has failed!")
if "-" not in hidden:
print(f"You won {name2}!")
loop = 9
player_2_life = 5
if player_2_life > 0:
print(hangmanpicsfor2player[player_2_life - 1])
if "-" in hidden:
print("What a shame you both failed!")
print(hangmanpicsfor2player[3])
print(f"The word was {ans}")
else:
print("Looks like you have inputed an unsupported value. Please load the game again!")
play = input("Want to play again (Y/N)? ")
if play == "y" or "Y":
continue
else:
play = False
break
|
b2f298d715a3309d66207226f72a4e16879d9371 | gorkhali125/image-processing-algorithms | /negative_grayscale/negative_grayscale.py | 1,732 | 3.84375 | 4 | import math
from PIL import Image, ImageDraw
def negative_grayscale(img):
for i in range(0,width):
for j in range(0,height):
thisPixel = img.getpixel((i,j))
#If the current pixel has pixel value, increment the pixel value by 1 and set the pixel value. For Original Image
OrgImagevalues[thisPixel] += 1
img.putpixel((i,j), 255 - thisPixel)
#If the current pixel has pixel value, increment the pixel value by 1 and set the pixel value. For Converted Image
convertedImagevalues[255 - thisPixel] += 1
def showHistogram(pixelValues):
#Outline of the Rectangular Box Begins
h = int(math.floor(max(pixelValues) / 10) + 10)
histogram = Image.new('L', (1285, h))
draw = ImageDraw.Draw(histogram)
draw.rectangle(((0,0), (1285, h)), fill=255)
#Outline of the Rectangular Box Ends
#Histogram Drawing begins with the value points
x = 0
for v in pixelValues:
height = int(math.floor(v / 10))
draw.rectangle(((x, 5), (x+5, height+5)), fill=0)
x += 5
#Histogram Drawing ends
#Co-ordinates in Image Processing are upside down. Hence image is rotated by 180 degrees
histogram.transpose(Image.FLIP_TOP_BOTTOM).show()
img = Image.open("lena512.bmp")
img.show('Lena Original') #Show the original Image
width, height = img.size
print(width)
print(height)
print(img.mode)
#Values will be used to store histogram data for the image
OrgImagevalues = [0] * 256 #Original Image values
convertedImagevalues = [0] * 256 #Converted Image values
negative_grayscale(img) #convert the image to it's negative
img.show('Lena Negative') #Show the converted Image
showHistogram(OrgImagevalues) #Show the histogram for original image
showHistogram(convertedImagevalues) #Show the histogram for converted image
|
07072a54659aed77b3c72b9a1cdead8033709d3e | FrekiMuninnsson/UdacityFSNDpycode2nd | /rename_files.py | 731 | 3.828125 | 4 | import os
def rename_files():
# Get all the filenames from the folder in which the files reside.
file_list = os.listdir(r"C:\Users\User\Desktop\Udacity FullStack Developer Nanodegree\Secret Message\to_be_renamed")
print(file_list)
saved_path = os.getcwd()
print ("Current Working Directory is "+saved_path)
os.chdir(r"C:\Users\User\Desktop\Udacity FullStack Developer Nanodegree\Secret Message\to_be_renamed")
# For each file, rename it by removing the numbers from the filename.
for file_name in file_list:
print("Old Name - "+file_name)
print("New Name - "+file_name.translate(None, "0123456789"))
os.rename(file_name, file_name.translate(None, "0123456789"))
os.chdir(saved_path)
rename_files()
|
c60d90dcdf74712ad444fb477b14b20e34018423 | ClariNerd617/personalProjects | /learnPython/abc.py | 450 | 4.125 | 4 | from abc import ABCMeta, abstractmethod
class Shape(metaclass = ABCMeta):
@abstractmethod
def area(self):
return 0
class Square(Shape):
side = 4
def area(self):
print(f'Area of square: {self.side ** 2}')
class Rectangle(Shape):
width = 5
length = 10
def area(self):
print(f'Area of rectangle: {self.width * self.length}')
square = Square()
rectangle = Rectangle()
square.area()
rectangle.area() |
53d711bc38f788303101a22b3c897cd51679eaa3 | stjordanis/HackerRank-2 | /marcscupcakes.py | 583 | 3.640625 | 4 | import more_itertools as mit
from pprint import pprint
c = [1, 3, 2]
n = len(c)
possible_miles = []
def random_permute_generator(iterable, n):
for _ in range(n):
yield mit.random_permutation(iterable)
possible_combos = (list(set(list(random_permute_generator(c, 20)))))
for combo in possible_combos:
miles = 0
no_of_cupcakes_eaten = 0
for calorie_value in combo:
miles_needed = (2^no_of_cupcakes_eaten) * calorie_value
miles += miles_needed
no_of_cupcakes_eaten += 1
possible_miles.append(miles)
pprint (min(possible_miles)) |
2ce870fe0cf30c605c09125dc2c9586d9af9fe7e | lordpews/python-practice | /for w else.py | 867 | 4.34375 | 4 | koko = ["bharta", "bengan", "parantha"]
for items in koko:
print(items)
# break
"""
When we use else with for loop the compiler will only go into the else block of code
when two conditions are satisfied:
1. The loop normally executed without any error. using break statements or jump statement will not execute
the else block.
2. We are trying to find an item that is not present inside the list or
data structure on which we are implementing our loop.
Except for these conditions, the program will ignore the else part of the program.
For example, if we are just partially executing the loop using a break statement,
then the else part will not execute.
So, a break statement is a must if we do not want our compiler to execute the else part of the code.
"""
else:
print("balle balle lmao")
|
ecbe84ddcbd59968e6b63d231b59e8247c59d252 | Kusanagy/ifpi-ads-algoritmos2020 | /Exercรญcio 3.1.py | 278 | 3.859375 | 4 | def main():
palavra = input('Palavra: ')
right_justify(palavra)
def right_justify(s):
tamanho_palavra = len(s)
quantidade_de_espaรงos = 70 - tamanho_palavra
espaรงos = quantidade_de_espaรงos * ' '
linha = espaรงos + s
print(linha)
main() |
543332482c078ae08a686f3fd12d4496cd4ab0f3 | kajal-0101/python-basics | /check_divisor_second_no.py | 687 | 4.15625 | 4 | '''
Asks the user for two integers, and then displays whether the second integer
is a divisor of the ๏ฌrst integer
'''
print("Two integers are to be taken as input")
a=input("Enter the first integer: ")
a=int(a)
b=input("Enter the second integer: ")
b=int(b)
if(a>b):
large=a
small=b
print("The larger value is {} and the smaller value is {}".format(large,small))
else:
large=b
small=a
print("The larger value is {} and the smaller value is {}".format(large,small))
mod=large%small
if(mod==0):
print("The smaller value {} is a divisor of the larger value {}".format(small,large))
else:
print("The smaller value {} is not a divisor of the larger value {}".format(small,large)) |
ac64cfa2819b4c3b51d0f464ebfbef639eac7103 | Aishaharrash/holbertonschool-machine_learning | /supervised_learning/0x03-optimization/12-learning_rate_decay.py.bak | 1,110 | 3.6875 | 4 | #!/usr/bin/env python3
"""
12-learning_rate_decay.py
Module that defines a function called learning_rate_decay
"""
import tensorflow as tf
def learning_rate_decay(alpha, decay_rate, global_step, decay_step):
"""
Function that updates the learning rate using inverse time decay in numpy
Args:
alpha (float): Original learning rate
decay_rate (float): Weight used to find rate at which alpha will decay
global_step (float): No of passes of gradient descent that have elapsed
decay_step (float): No of passes of gradient descent that should occur
before alpha is decayed further
Notes
The learning rate decay should occur in a stepwise fashion
Returns
The updated value for alpha
"""
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
step = sess.run(global_step)
if step % decay_rate == 0:
return tf.train.inverse_time_decay(alpha, global_step, decay_step,
decay_rate, staircase=True)
return alpha
|
5acdd481025b763b186bd58c749f37f7f4fe78bd | towshif/towshif.github.io | /projects/helloworlds-intro/helloworld.py | 289 | 3.96875 | 4 | # Function to add 2 numbers
def addme(a, b):
return a+b
def multme(a, b):
return a*b
def divideme(a, b):
return a/b
print("Hello World")
print("Add 5 + 2 = ", addme(5, 2))
print("Multiply 5 * 2 = ", multme(5, 2))
print("Divide 5 / 2 = ", divideme(5, 2))
|
7914cef158de1776bf26b78b0ac4052f537fbbfb | ddtBeppu/introPython3_beppu | /e06/e06_01.py | 767 | 3.859375 | 4 | # ๅพฉ็ฟ่ชฒ้ก 6-1
# ไธญ่บซใฎใชใThingใฏใฉในใไฝใใ่กจ็คบใใใใๆฌกใซใใใฎใฏใฉในใใexampleใจใใใชใใธใงใฏใใไฝใใใใใ่กจ็คบใใใใ
# ่กจ็คบใใใๅคใฏๅใใใใใใจใ็ฐใชใใใ
# Thingใฏใฉในใฎไฝๆ
class Thing():
# ไธญ่บซใๆใใชใใฏใฉในใจใใ
pass
# Thing()ใฏใฉในใ่กจ็คบ
print("class Thing() = ", Thing())
# exampleใชใใธใงใฏใใไฝๆ
example = Thing()
# exampleใชใใธใงใฏใใ่กจ็คบ
print("example = ", example)
# ๅฎ่ก็ตๆ
# ่กจ็คบใใใๅคใฏ็ญใใใใจใใใใ
"""
NaotonoMacBook-puro:e06 naotobeppu$ python e06_01.py
class Thing() = <__main__.Thing object at 0x102ad4128>
example = <__main__.Thing object at 0x102ad4128>
""" |
7ea9e89a89c58291844571f06eb2f1b09147f187 | Hayk258/lesson | /kalkulyator.py | 554 | 4 | 4 | print (5 * 5)
print (5 % 5)
print(25 + 10 * 5 * 5)
print(150 / 140)
print(10*(6+19))
print(5**5) #aysinqn 5i 5 astichan
print(8**(1/3))
print(20%6)
print(10//4)
print(20%6) #cuyca talis vor 20 bajanes 6 taki ostatken inchqana mnalu
while True:
x = input("num1 ")
y = input('num2 ')
if x.isdigit() and y.isdigit():
x = float(x)
y = float(y)
break
else:
print('please input number')
choise = input("+ - * /")
if choise == '+':
print(x+y)
elif choise == '-':
print(x-y)
if choise == '/':
print(x/y)
elif choise == '*':
print(x*y) |
d485457c2776b4be63e235ed34f2c3e743303772 | kgrozis/netconf | /bin/2.12 Sanitizing and Cleaning Up Text.py | 1,750 | 4.09375 | 4 | '''
Title - 2.12. Want to clean up unicode text
Problem - Want to strip unwanted chars, from beginning, end or middle of a text string
Solution - Use basic string functions: str.upper(), str.lower() or simple replacements
str.replace(), or re.sub(), or normalize text with unicodedata.normalize(),
or use str.translate() method
'''
s = 'pรฝtฤฅรถรฑ\fis\tawesome\r\n'
print(s)
# cleanup whitespace by remapping to ' '
# requires python3
remap = {
ord('\t') : ' ',
ord('\f') : ' ',
ord('\r') : None # Deleted
}
a = s.translate(remap)
print(a)
# remove all the combining chars
import unicodedata
import sys
# maps every Unicode combining char to None and deletes the accents
# can use to delete control chars
cmb_chrs = dict.fromkeys(c for c in range(sys.maxunicode)
if unicodedata.combining(chr(c)))
b = unicodedata.normalize('NFD', a)
print(b)
print(b.translate(cmb_chrs))
# maps all Unicode decimal digit chars to their equivalent ASCII
digitmap = { c: ord('0') + unicodedata.digit(chr(c))
for c in range(sys.maxunicode)
if unicodedata.category(chr(c)) == 'Nd' }
print(len(digitmap))
# Arabic digits
x = '\u0661\u0662\u0663'
print(x.translate(digitmap))
# I/O decoding & encoding functions
# ascii encode / decode discards all unicode chars for ascii
print(a)
b = unicodedata.normalize('NFD', a)
print(b.encode('ascii', 'ignore').decode('ascii'))
# sanitizing text creates issus with runtime performance
# str.replace() method runs fastest. Even on multiple calls
# Runs much fster than translate() or regex
def clean_spaces(s):
s = s.replace('\r', '')
s = s.replace('\t', ' ')
s = s.replace('\f', ' ')
return s
print(clean_spaces(s)) |
33449d28e999a6522e6631256f756ec4aeae425c | Brittany1908/DCAScraper | /printAllText.py | 673 | 3.578125 | 4 | '''
Program Name: DCA Scraper
Created: March 12, 2017
Modified: March 16, 2017
Purpose: Obtain information from websites, then parse the
information.
'''
#-----------------------------------------------------------
''' Import urllib and BeautifulSoup 4 for obtaining
website info and then parsing'''
import urllib.request;
from bs4 import BeautifulSoup;
#-----------------------------------------------------------
# Assigning variables
website = urllib.request.urlopen('http://www.5dca.org/Opinions/Opin2017/030617/filings%20030617.html');
soup = BeautifulSoup (website,"html5lib");
#-----------------------------------------------------------
print(soup.get_text());
|
3c17450bf526323321f2b9a401c2be7953a27651 | lucasgr7/PythonChallenge | /source/tests/test_models.py | 7,160 | 3.6875 | 4 | '''
Module for tests in the algorithm in the Python Challenge
'''
import os.path
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
import unittest
from models import Board, Piece, Position
class TestModels(unittest.TestCase):
'''Unit test classes'''
def test_push_duplicate_values(self):
'''Test if duplicate values on pieces attack positions'''
board = Board(3, 3)
piece = Piece(None, Board(2, 2))
piece.position = Position(2, 2)
a = Position(1, 1)
b = Position(1, 0)
c = Position(1, 0)
piece.push(a)
piece.push(b)
piece.push(c)
self.assertEqual(2, len(piece.attack_positions))
def test_rook_attack_positions(self):
'''Test the attack positions of the Rook'''
board = Board(4, 4)
board.pieces = []
board.add_piece('Rook')
piece = board.pieces[0]
board.set_piece(piece, Position(1, 1))
self.assertEqual(6, len(piece.attack_positions))
def test_knight_attack_positions(self):
'''Test the attack positions of the Knight'''
board = Board(3, 3)
board.add_piece('Knight')
piece = board.pieces[0]
board.set_piece(piece, Position(1, 1))
self.assertEqual(0, len(piece.attack_positions))
board.clear()
board.set_piece(piece, Position(0, 2))
self.assertEqual(2, len(piece.attack_positions))
def test_bishop_attack_positions(self):
'''Test the attack positions of the Bishop'''
board = Board(4, 4)
board.add_piece('Bishop')
piece = board.pieces[0]
board.set_piece(piece, Position(1, 1))
self.assertEqual(5, len(piece.attack_positions))
def test_king_attack_positions(self):
'''Test the attack positions of the King'''
board = Board(4, 4)
board.add_piece('King')
piece = board.pieces[0]
board.set_piece(piece, Position(1, 1))
self.assertEqual(8, len(piece.attack_positions))
board = Board(4, 4)
board.add_piece('King')
piece = board.pieces[0]
board.set_piece(piece, Position(0, 0))
self.assertEqual(3, len(piece.attack_positions))
def test_queen_attack_positions(self):
'''Test the attack positions of the Queen'''
board = Board(3, 3)
board.add_piece('Queen')
piece = board.pieces[0]
board.set_piece(piece, Position(1, 1))
self.assertEqual(8, len(piece.attack_positions))
board = Board(5, 5)
board.add_piece('Queen')
piece = board.pieces[0]
board.set_piece(piece, Position(2, 2))
self.assertEqual(16, len(piece.attack_positions))
def test_get_piece_name(self):
'''Test method to read the piece positions'''
board = Board(3, 3)
board.add_piece('Rook')
board.add_piece('King')
board.add_piece('Queen')
rook = board.pieces[0]
king = board.pieces[1]
queen = board.pieces[2]
board.set_piece(rook, Position(0, 0))
board.set_piece(king, Position(1, 2))
board.set_piece(queen, Position(2, 2))
self.assertEqual('Rook', board.get_piece_name(Position(0, 0)))
self.assertEqual('King', board.get_piece_name(Position(1, 2)))
self.assertEqual('Queen', board.get_piece_name(Position(2, 2)))
self.assertEqual('_', board.get_piece_name(Position(1, 1)))
def test_piece_positioning(self):
'''Test if the positioning is validated correctly'''
board = Board(3, 3)
board.add_piece('Bishop')
board.add_piece('Rook')
bishop = board.pieces[0]
rook = board.pieces[1]
#Bishop will be placed at 0,0
bishop_position = Position(0, 0)
#The position should be free since we're starting
self.assertEqual(0, board.is_occupied(bishop_position))
board.set_piece(bishop, bishop_position)
#After placing the bishop expected to be occupied
self.assertEqual(1, board.is_occupied(bishop_position))
#Expedted to the bishop attack the postions (1,1), (2,2)
#The return should be 2 since there is no piece, but its in
#the attack area of another piece
self.assertEqual(2, board.is_occupied(Position(1, 1)))
self.assertEqual(2, board.is_occupied(Position(2, 2)))
#Test if i put the Rook on (0,1) will harm the Bishop, what sould be true
self.assertEqual(1, board.will_harm(rook, Position(0, 1)))
rook_position = Position(1, 2)
#Verify the position (1,2) where is empty and should not harm the bishop
self.assertEqual(0, board.is_occupied(rook_position))
self.assertEqual(1, board.will_harm(rook,rook_position))
#Place it
board.set_piece(rook, rook_position)
self.assertEqual(1, board.is_occupied(rook_position))
def test_save_play(self):
'''Test if the method save_play doesn't allow duplicated results'''
board = Board(2, 2)
board.add_piece('Rook')
board.add_piece('Knight')
rook = board.pieces[0]
knight = board.pieces[1]
board.set_piece(rook, Position(0, 0))
board.set_piece(knight, Position(1, 1))
#Save play uses the array pieces_in_board, it is used to verify
#pieces positioned on the board
self.assertEqual(2, len(board.pieces_in_board))
#Tries to save twice
board.save_play()
board.save_play()
#Expected to be saved only one
self.assertEqual(1, board.count_saved_plays)
def test_play_01(self):
'''Test the play with 4 kings in one board 3x3 expected 1 play to be possible'''
board = Board(3, 3)
board.add_piece('King')
board.add_piece('King')
board.add_piece('King')
board.add_piece('King')
board.set_play(0)
self.assertEqual(1, len(board.saved_plays))
def test_play_02(self):
'''Test the play with 2 Kings and 1 Rook Board 3x3, expected 4 to be true'''
board = Board(3, 3)
board.add_piece('King')
board.add_piece('King')
board.add_piece('Rook')
board.set_play(0)
self.assertEqual(4, len(board.saved_plays))
def test_play_03(self):
'''Test the play with 4 Knights and 2 Rooks Board 4x4, expected 8 to be true'''
board = Board(4, 4)
board.add_piece('Knight')
board.add_piece('Knight')
board.add_piece('Knight')
board.add_piece('Knight')
board.add_piece('Rook')
board.add_piece('Rook')
board.set_play(0)
self.assertEqual(8, len(board.saved_plays))
def test_play_04(self):
'''Test the play with 3 kings in one board 3x3 expected 1 play to be possible'''
board = Board(3, 3)
board.add_piece('King')
board.add_piece('King')
board.add_piece('King')
board.set_play(0)
self.assertEqual(8, len(board.saved_plays))
suite = unittest.TestLoader().loadTestsFromTestCase(TestModels)
unittest.TextTestRunner(verbosity=2).run(suite)
|
866a0d6cfa973ca864ae83fcba1c0f5b2145304c | SoyabulIslamLincoln/Home-Practice | /if else.py | 962 | 3.828125 | 4 | Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> amount=int(input("enter amount: "))
enter amount: 56
>>> if amount<1000:
discount=amount*0.05
print("discount=",discount)
discount= 2.8000000000000003
>>> else:
SyntaxError: invalid syntax
>>> if amount<1000:
discount=amount*0.05
print("discount :",discount)
else:
discount=amount*0.10
print("discount:",discount)
discount : 2.8000000000000003
>>> print("Net payable= ",amount-discount)
Net payable= 53.2
>>>
>>>
>>> fruit=["mango","banana","orange"]
>>> fruit.insert(0,"apple")
>>> fruit.insert(4,"coconut")
>>> fruit
['apple', 'mango', 'banana', 'orange', 'coconut']
>>> item=
SyntaxError: invalid syntax
>>> item="pineapple"
>>> if item in fruit:
remove(item)
else:
print(item,"is not in the list")
pineapple is not in the list
>>>
|
9645097ade88229932a07db219ea7d129a521e6e | fras2560/InducedSubgraph | /inducer/dcolor.py | 7,744 | 3.75 | 4 | """
-------------------------------------------------------
dcolor
a module to determine the chromatic number of a graph
-------------------------------------------------------
Author: Dallas Fraser
ID: 110242560
Email: fras2560@mylaurier.ca
Version: 2014-09-17
-------------------------------------------------------
"""
from itertools import permutations
from pprint import PrettyPrinter
import logging
import copy
import networkx as nx
def dense_color_wrapper(G, logger=None):
return Dcolor(G, logger=logger).color()
class Dcolor():
def __init__(self, graph, logger=None):
if logger is None:
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(message)s')
logger = logging.getLogger(__name__)
self.logger = logger
self.coloring = None
self.graph = graph
self.pp = PrettyPrinter(indent=4)
def chromaic_number(self):
'''
a method to determine the chromatic number of the graph
Parameters:
None
Returns:
: the chromatic number (int)
'''
if self.coloring is None:
self.color()
return len(self.coloring)
def color(self):
'''
a method to determine a graph coloring
Parameters:
None
Returns:
self.coloring: the graph coloring (list)
'''
if self.coloring is None:
self.color_aux()
return self.coloring
def create_clique_list(self):
'''
a method to create a list of cliques
Parameters:
None
Returns:
cliques: the list of cliques (list)
chromatic: the chromatic number (int)
l_index: the largest clique index (int)
'''
g = self.graph.copy()
chromatic = 0
l_index = 0
index = 0
cliques = []
while len(g.nodes()) > 0:
largest = 0
for clique in nx.find_cliques(g):
if len(clique) > largest:
largest = len(clique)
largest_clique = clique
clique = []
for node in largest_clique:
g.remove_node(node)
clique.append([node])
if len(clique) > chromatic:
chromatic = len(clique)
largest = clique
l_index = index
cliques.append(clique)
index += 1
return cliques, chromatic, l_index
def color_aux(self):
'''
a method to help with coloring
Sets self.coloring to a valid coloring
Parameters:
None
Returns:
None
'''
self.logger.debug("Coloring")
cliques, chromatic, index = self.create_clique_list()
done = False
if chromatic == len(self.graph.nodes()):
done = True
coloring = cliques[0]
self.logger.debug("Graph is a Clique: %d" % chromatic)
elif chromatic == 2:
cycles = nx.cycle_basis(self.graph)
odd = False
for cycle in cycles:
if len(cycle) % 2 == 1:
odd = True
if odd:
largest = cliques.pop(index)
largest.append([])
chromatic += 1
else:
largest = cliques.pop(index)
else:
largest = cliques.pop(index)
while not done:
self.logger.info('Testing Chromatic Number: %d' % chromatic)
coloring = self.coloring_step(cliques, largest)
if coloring is None:
largest.append([]) # equivalent to adding a new color
chromatic += 1
else:
done = True
self.coloring = coloring
def coloring_step(self, cliques, coloring):
'''
a recursive function that acts as one step in the coloring
Parameters:
cliques: a list of the cliques (list)
coloring: an initial coloring (list)
Returns:
coloring: None if no coloring is possible
'''
if len(cliques) == 0:
result = coloring
else:
added = False
valid = []
for pc in combine_color_clique(coloring, cliques[0]):
if self.valid_coloring(pc):
added = True
valid.append(pc)
if not added:
result = None
else:
for pc in valid:
result = self.coloring_step(cliques[1:], pc)
if result is not None:
break
return result
def copy_list(self, original_list):
'''
a method to copy a list
Parameters:
original_list: the list to copy (list)
Returns:
result: the copied list (list)
'''
result = []
for element in original_list:
result.append(copy.deepcopy(element))
return result
def valid_coloring(self, coloring):
'''
a method that determines if the coloring is valid
Parameters:
coloring: a list of colors in which each color is a list of nodes
e.g. [[1,2],[3]]
Returns:
valid: True if valid coloring,
False otherwise
'''
valid = False
if coloring is not None:
valid = True
for color in coloring:
for vertex in color:
neighbors = self.graph.neighbors(vertex)
for neighbor in neighbors:
if neighbor in color:
valid = False
break
if not valid:
break
if not valid:
break
return valid
def add_list(l1, l2, index):
'''
a function that adds the list l1 to the two dimensional
list l2
Parameters:
l1: the first list (list)
l2: the second list (list of lists)
i1: the starting index to l1 (int)
Returns:
new_list: the list of lists(list of lists)
'''
new_list = copy.deepcopy(l1)
i = 0
while i < len(l2):
new_list[index] += l2[i]
i += 1
index += 1
return new_list
def convert_combo(combo):
'''
a function that converts a combo tuple to a list
Parameters:
combo: a tuple of combinations (tuple)
Returns:
conversion: the converted combination (list)
'''
conversion = []
for c in combo:
conversion.append(c)
return conversion
def combine_color_clique(clique, color):
'''
a function that takes a clique list and a color split
and yields all the ways the clique list can be combine with coloring
Parameters:
clique: the clique (list of lists)
color: the coloring (list of lists)
index: the index
Returns:
coloring: the combined color (list of lists)
'''
color_length = len(color)
clique_number = len(clique)
for c in permutations(clique):
c = convert_combo(c)
if clique_number < color_length:
index = 0
while index <= color_length - clique_number:
yield add_list(color, c, index)
index += 1
elif clique_number > color_length:
index = 0
while index <= clique_number - color_length:
yield add_list(c, color, index)
index += 1
else:
yield add_list(c, color, 0)
|
11c4acc8297cbfa0ca420d67c51fe2924d1914bf | patrick-replogle/cs-module-project-hash-tables | /applications/sumdiff/sumdiff.py | 647 | 3.5 | 4 | """
find all a, b, c, d in q such that
f(a) + f(b) = f(c) - f(d)
"""
# q = set(range(1, 10))
# q = set(range(1, 200))
q = (1, 3, 4, 7, 12)
def f(x):
return x * 4 + 6
def sum_diff(nums):
add_table = {}
minus_table = {}
for i in q:
for j in q:
add_table[(i, j)] = f(i) + f(j)
for i in q:
for j in q:
minus_table[(i, j)] = f(i) - f(j)
for k1, v1 in add_table.items():
for k2, v2 in minus_table.items():
if add_table[k1] == minus_table[k2]:
print(
f"f({k1[0]}) + f({k1[1]}) = f({k2[0]} - f({k2[1]}) = {v1})")
sum_diff(q)
|
b6bacdcad706d98c1af15c621afa4cff8184ca33 | vinija/LeetCode | /348-design-tic-tac-toe/348-design-tic-tac-toe.py | 875 | 3.8125 | 4 | class TicTacToe:
def __init__(self, n: int):
self.n = n
self.rows = [0] * n
self.cols = [0] * n
self.diagonal = 0
self.anti_diagonal = 0
def move(self, row: int, col: int, player: int) -> int:
p = 1 if player == 1 else -1
#make the move
self.rows[row] += p
self.cols[col] += p
if row == col:
self.diagonal += p
if row + col == self.n - 1:
self.anti_diagonal += p
#winning condition
if abs(self.rows[row]) == self.n or abs(self.cols[col]) == self.n or abs(self.diagonal) == self.n or abs(self.anti_diagonal) == self.n:
return player
return 0
# Your TicTacToe object will be instantiated and called as such:
# obj = TicTacToe(n)
# param_1 = obj.move(row,col,player) |
54b939dc2d6ebd01df6c3f4fb1f35250dba4a0cd | jonovate/sizesorter | /sizesorter/sizechart.py | 17,196 | 3.6875 | 4 | """
Structure of size charts and values
"""
from collections import namedtuple
from copy import deepcopy
from numbers import Number
from .size import Size
"""
Represents the defined Dynamic Values.
base_suffix: The suffix of the dynamic size, which must exist in the accompanying size chart
sort_value_increment: The increment for each new dynamic size from its dynamic base
growth_direction: Whether the dynamic values count down or count up (3XS, 2XS, XS versus XL, 2XL, 3XL).
Positive means up, negative means down.
Example:
Say size_chart['XS'] = 0, size_chart['XL'] = 100 and DynOp('XS', 5, -1) and DynOp('XL', 10, 1)
Then 2XS would be -5, 3XS would be -10, 2XL would be 110, 3XL would be 120, etc.
"""
DynOp = namedtuple('DynOp', 'base_suffix sort_value_increment growth_direction ')
"""Default mapping of sizes to Size objects"""
SIZE_CHART_DEFAULTS = {
'XS': Size('XS', 0, 'X-Small', True),
'S': Size('S', 25, 'Small', False),
'M': Size('M', 50, 'Medium', False),
'L': Size('L', 75, 'Large', False),
'XL': Size('XL', 100, 'X-Large', True),
}
"""Default Dynamic Operation offsets"""
DYNAMIC_OPERATIONS_DEFAULTS = {'XS': DynOp('XS',10,-1), 'XL': DynOp('XL',10,1)}
"""
Default Size Chart formatting options
verbose: Whether to display verbose name or just short value
dynamic_size_verbose: Whether to display dynamics (XS/XL/etc.) sizes as verbose or not
dynamic_size_formatter: Formatting method for the small/larger dynamic sizes
"""
SIZE_CHART_FORMAT_DEFAULTS = {'verbose': False,
'dynamic_size_verbose': False,
'x_size_formatter': str,
}
####TODO
'''
---Verbose
---N vs X
---Formatter
---Single Ended Dynamic Size
---No Dynamic Size in chart
---Baby Size/Toddler Size/Kids Size
---Dynamic Size prefix increments
---Dynamic Size limits
decorator, generators
'''
class SizeChart():
"""
Wrapper class for a size chart
Principle: Size should only be visible externally from constructor, otherwise remain internal
"""
"""The maximum length of a size chart""" #used to prevent endless loops for bad values also
MAX_SIZE_CHART_LENGTH = 68
def __init__(self, size_chart=None, dyn_ops=None, *, formatting_options=None):
"""
Initializes a size chart wrapper class.
The Dynamic Size Cache is disabled by default.
:param dict size_chart: Map of sizes and values
Default - Uses SIZE_CHART_DEFAULTS map
:param dict dyn_ops: Map of dynamic keys to DynOp Tuples
Default - Uses DYNAMIC_OPERATIONS_DEFAULTS
:param dict formatting_options: Formatting options for the Size Chart
Default - Uses SIZE_CHART_FORMAT_DEFAULTS map
:raise ValueError: If the DynOp keys are not in the Size Chart or invalid
(smaller_ should be negative, greater_ should be positive)
"""
self._dynamic_size_cache = False
self.dyn_ops = (dyn_ops if dyn_ops else DYNAMIC_OPERATIONS_DEFAULTS)
size_chart_shallow = size_chart if size_chart else SIZE_CHART_DEFAULTS
if not all([isinstance(v, Size) for v in size_chart_shallow.values()]):
raise ValueError('Size Chart dictionary values should be of type Size,'
'otherwise use `.from_simple_dict()`')
if any([(do not in size_chart_shallow) for do in self.dyn_ops.keys()]):
raise ValueError('DynOp base suffix not in size_chart')
if any([do.sort_value_increment < 1 for do in self.dyn_ops.values()]):
raise ValueError('DynOp sort_value_increment must be a positive number')
if any([do.growth_direction not in (-1,1) for do in self.dyn_ops.values()]):
raise ValueError('DynOp growth_direction must 1 or -1')
self.size_chart = deepcopy(size_chart_shallow)
#Setup double-linked pointers
previous_obj = None
for key,size_obj in sorted(self.size_chart.items(), key=lambda d: d[1]):
if previous_obj:
previous_obj.next_size_key = key #previous obj's next
size_obj.previous_size_key = previous_obj.key #this obj's previous
previous_obj = size_obj
#Make sure the dynamic_size property is set in case user forgot
# at same time, need to set double-linked pointers
if key in self.dyn_ops:
size_obj.is_dynamic_size = True
if self.dyn_ops[key].growth_direction > 0: #Incrementing sizes
size_obj.next_size_key = '2' + key
else: #Decrementing sizes
size_obj.previous_size_key = '2' + key
#Deepcopy since they can be overwritten after instantiation
self.formatting_options = deepcopy(formatting_options
if formatting_options
else SIZE_CHART_FORMAT_DEFAULTS)
@classmethod
def from_simple_dict(cls, simple_dict, dyn_ops=None):
"""
Builds a SizeChart instance from a simple map of Size key to sort value
:param dict dyn_ops: Map of dynamic keys to DynOp Tuples
Default - Uses DYNAMIC_OPERATIONS_DEFAULTS
:raise ValueError: If simple_dict contains any values that are not Numbers
:raise ValueError: If simple_dict contains any values that are not Numbers
"""
if not all([isinstance(v, Number) for v in simple_dict.values()]):
raise ValueError('Size Chart dictionary values must be Numbers')
size_dict = {key: Size(key, value, key, False) for key, value in simple_dict.items()}
return cls(size_dict, dyn_ops)
def __len__(self):
"""
Returns the length of the Size Chart
:return: The length of the Size Chart
:rtype int
"""
return len(self.size_chart)
def _find_dynamic_operation(self, size_key):
"""
Indirectly determines whether the key could be considereda dynamic key based on the
Dynamic Operations configuration passed in on instantiation.
:param str size_key: The size key to look up in our chart.
:returns The Dynamic Operation if its dynamic, otherwise None
:rtype tpl (DynOp)
"""
dyn_ops = [dyn_op for base_suffix,dyn_op in self.dyn_ops.items()
if size_key.endswith(base_suffix)]
return dyn_ops[0] if len(dyn_ops) > 0 else None
def _handle_single_prefix(self, size_key):
"""
Removes any unncessary prefixes which means the same as another key (ie: 1XS to XS, '2' to 2)
:param str size_key: The size key to look up in our chart.
:returns The size key with/without removed prefix
:rtype str
"""
#If it's a numeric key, return as String
if isinstance(size_key, Number):
return str(size_key)
#If it's all digits, return as is
if size_key.isdigit():
return size_key
#If size key begins with a 1, and the second character is not numeric, then needs fix
if size_key[0].isdigit() and size_key[0] == '1' and not(size_key[1].isdigit()):
return size_key[1:]
return size_key
def _parse_size_key(self, size_key):
"""
Splits a potential dynamic key into prefix and dynamic key suffix.
:param str size_key: The size to look up in our chart.
:returns A tuple representing the prefix, suffix, whether it's a dynamic key.
Prefix will also be empty if not dynamic key.
:rtype tuple(str, str, bool)
:raises ValueError: If the key is not parsable (invalid characters, etc.)
"""
dyn_op = self._find_dynamic_operation(size_key)
if not dyn_op:
return ('', size_key, False)
suff_len = len(dyn_op.base_suffix)
prefix = size_key[:-suff_len]
if not(prefix == '' or prefix.isalnum()):
raise ValueError('Prefix of Dynamic Key must be a positive number or not set')
return (prefix if prefix not in ['1'] else '', size_key[-suff_len:], True)
def _generate_dynamic_size(self, size_key):
"""
Calculates a dynamic Size based on the key and the DynOp of the Chart.
:str size_key str: The Dynamic Key to generate a Size from
:return The generated Dynamic Size
:rtype Size
:raises ValueError: If the key is not parsable (invalid characters, etc.) or it it wasn't
a dynamic size per Size Chart
"""
"""INLINE"""
def __prefix_to_key(prefix, dyn_op):
if prefix == 0:
base_size = self.size_chart[dyn_op.base_suffix]
return (base_size.previous_size_key
if dyn_op.growth_direction > 0 #If 0XS, then we want S which is next
else base_size.next_size_key) #If 0XL, we want L which is previous
if prefix == 1:
return dyn_op.base_suffix
return str(prefix) + dyn_op.base_suffix
"""INLINE"""
def __set_previous_next(dynamic_size, int_prefix, dyn_op):
#int_prefix is current prefix - 1 XS = 0, 2XL = 1
up_key = __prefix_to_key(int_prefix+2, dyn_op)
down_key = __prefix_to_key(int_prefix, dyn_op)
if dyn_op.growth_direction > 0: #Positive... so L, XL, 2XL
dynamic_size.previous_size_key = down_key
dynamic_size.next_size_key = up_key
else: #Negative... so 3XS, 2XS, XS
dynamic_size.previous_size_key = up_key
dynamic_size.next_size_key = down_key
prefix, suffix, is_dynamic_size = self._parse_size_key(size_key)
if not is_dynamic_size:
raise ValueError('Suffix is not defined as Dynamic Size')
base_size = self.size_chart[suffix]
if prefix == '': #Its a base dynamic key, so just return it
return base_size
sort_value = base_size.sort_value
dyn_op = self.dyn_ops[base_size.key]
int_prefix = (int(prefix) - 1 if prefix else 0)
if int_prefix: #Not empty
sort_value += int_prefix * (dyn_op.growth_direction * dyn_op.sort_value_increment)
else:
size_key = base_size.key
verbose = prefix + base_size.verbose
dynamic_size = Size(size_key, sort_value, verbose, True)
__set_previous_next(dynamic_size, int_prefix, dyn_op)
return dynamic_size
def _size_key_to_size(self, size_key):
"""
Converts the size_key to a size
:param str size_key: The size key to convert to a size
:return: A tuple of Size object and whether it existed in Chart already
:rtype tpl(Size,bool)
:raises ValueError: If an invalid dynamic size is passed in.
Examples: '-5XL', '+3XL', '4L' {non-dynamic} or 'X' {invalid size}
"""
size_key = self._handle_single_prefix(size_key)
size = self.size_chart.get(size_key)
is_new = size is None
if is_new:
try:
if size_key.isnumeric():
size = Size(size_key, float(size_key), size_key, False)
else:
size = self._generate_dynamic_size(size_key)
except Exception as e:
raise ValueError('Base size not defined and/or not Dynamic: ' + str(e))
return (size,is_new)
def get_or_create_size(self, size_key):
"""
Retrieves the size and/or generates it if does not exist
note:: Will add to Dynamic Size cache if Enabled.
:param str size_key: The size to look up in our chart.
:return: The Size object
:rtype Size
:raises ValueError: If an invalid dynamic size is passed in.
Examples: '-5XL', '+3XL', '4L' {non-dynamic} or 'X' {invalid size}
"""
size, is_new = self._size_key_to_size(size_key)
if is_new and self._dynamic_size_cache:
self.size_chart[size_key] = size
return size
def enable_dynamic_size_cache(self):
"""
Disables saving of generated dynamic sizes into Size Chart (Disabled by Default).
Useful if you think you will be using it often.
"""
self._dynamic_size_cache = True
def set_formatting_options(self, formatting_options):
"""
Override the Formatting options for the Size Chart
:param dict formatting_options: Formatting options for the Size Chart
"""
#In case only single option is passed in, we merge
self.formatting_options.update(formatting_options)
def generate_lengthed_list(self, list_length=len(SIZE_CHART_DEFAULTS)):
"""
Generates an ordered specific-sized list, pivoted around the mid-point size. (len//2)
Will retract from smallest-end first and extend on largest-end first.
note:: Does not alter Size Chart or Dynamic Cache since we don't want to delete.
warning:: If Dynamic Size Cache has been enabled, you should not be using this as it can
result in smallest leaning or largest leaning results (due to mid-point having changed)
:param int list_length: The length of the size list to generate
Default - len(SIZE_CHART_DEFAULTS) (5)
Maximum length is SizeChart.MAX_SIZE_CHART_LENGTH
:return: List of sizes of specified length per formatting options
:rtype list
:raises ValueError If the list_length exceeds the Maximum
"""
if list_length is None: #For Pytest parameter hack
list_length = len(SIZE_CHART_DEFAULTS)
elif list_length > SizeChart.MAX_SIZE_CHART_LENGTH:
raise ValueError('Length of list exceeds maximum length')
##TODO - Move this to Sorter class??
sorted_sizes = [key for key,_ in sorted(self.size_chart.items(), key=lambda d: d[1])]
mid = (len(sorted_sizes)-1) // 2
addl_needed = abs(list_length - len(sorted_sizes))
#Give priority to right side
left_cnt, right_cnt = addl_needed // 2, -(-addl_needed // 2) #Floor, Ceiling
if list_length < len(sorted_sizes): #Will need to delete - so reverse counts
sorted_sizes = sorted_sizes[right_cnt:mid+1] + \
sorted_sizes[mid+1:len(sorted_sizes)-left_cnt]
elif list_length > len(sorted_sizes): #Will need to add
for cnt in range(0, max(left_cnt,right_cnt)):
if cnt < left_cnt:
left = self._size_key_to_size(sorted_sizes[0])
sorted_sizes.insert(0, left[0].previous_size_key)
right = self._size_key_to_size(sorted_sizes[-1])
sorted_sizes.insert(len(sorted_sizes), right[0].next_size_key)
return sorted_sizes
def generate_range_iter(self, start_range_key, end_range_key):
"""
Generates iterable of specified Sizes between the two ranges (inclusive).
Per Formatting Options.
:param str start_range_key: The start size (key) of the list
:param str end_range_key: The end size (key) of the list
:return: List of sizes in the range
:rtype list
:raises ValueError: If the base of the range keys don't exist in the Size Chart
"""
#validate and get anchors
start_size = self.get_or_create_size(start_range_key)
self.get_or_create_size(end_range_key) #To ensure its valid
next_size = start_size
yield start_size.key
endless_loop_control = SizeChart.MAX_SIZE_CHART_LENGTH - 1
while next_size.key != end_range_key and endless_loop_control:
next_size = self.get_or_create_size(next_size.next_size_key)
yield next_size.key
endless_loop_control -= 1
def generate_range_list(self, start_range_key, end_range_key):
"""
Generates an ordered list of specified Sizes between the two ranges (inclusive).
Per Formatting Options.
:param str start_range_key: The start Size of the list
:param str end_range_key: The end Size in the list
:return: List of sizes in the range
:rtype list
:raises ValueError: If the base of the range keys don't exist in the Size Chart
"""
return list(self.generate_range_iter(start_range_key, end_range_key))
|
709de418761787427ea8938045bac12ea997b41e | IsaDuong/Lab-7 | /Python Lab 7.py | 558 | 3.734375 | 4 | x = 1
while (x<300):
print x
x = x + 2
myList = [8,45,60,15,30,75,85,50,20,5]
index = 0
while (index < len(myList)):
print myList[index]
index = index + 1
import random
rand = random.randint(0,50)
userInput = raw_input()
print "Guess a number between 0-50"
while (userInput != rand):
userInput = int(raw_input())
if userInput > rand:
print "Your guess was too high. Try again."
if userInput < rand:
print "Your guess was too low. Try again."
if userInput == rand:
print "Your guess was right" |
1ac53e6fc8ebe35a7e6275aeac27b41a20201517 | rloulizi42/Labyrinthe | /labyrinthe.py | 3,966 | 3.671875 | 4 | #!/usr/bin/python3.4
import os
import curses
import sys
from tkinter import *
level = [
"+------------------+",
"| | |",
"| + | + |",
"| | +----+ | |",
"| | | | |",
"| | +--+ |",
"| +---+ ------+ |",
"| | | |",
"| | + | |",
"| | | | |",
"| | | + |",
"| |- -| |",
"| | | |",
"| +--------+ | |",
"| | |",
"| | +----------|",
"| | O|",
"+------------------+",
]
def afficher_labyrinthe(lab, perso, pos_perso, win, coul):
"""
Affiche un Labyrinthe
lab : Variable contenant le labyrinthe
perso : caractere representant le perso
pos_perso : coordonnees
"""
n_ligne = 0
for ligne in lab:
if pos_perso[1] == n_ligne:
win.addstr(n_ligne + 1, 10, ligne[0:pos_perso[0]] + perso + ligne[pos_perso[0] + 1:])
win.addstr(n_ligne + 1, 10 + pos_perso[0], perso, color("RED", coul))
else:
win.addstr(n_ligne + 1, 10, ligne)
n_ligne += 1
def verification_deplacement(lab, pos_col, pos_ligne):
"""
Indique si la deplacement du perso est valide
lab : labyrinthe
pos_col : col du perso
pos_ligne : ligne du perso
"""
n_cols = len(lab[0])
n_lignes = len(lab)
if pos_ligne <= 0 or pos_col <= 0 or pos_ligne >= (n_lignes - 1) or \
pos_col >= (n_cols - 1):
return None
elif lab[pos_ligne][pos_col] == "O":
return [-1, -1]
elif lab[pos_ligne][pos_col] != " ":
return None
else:
return [pos_col, pos_ligne]
def choix_joueur(lab, pos_perso, win):
"""
demande au joueur de saisir son deplacement et verifie s'il est possible
lab : labyrinthe
pos_perso : coordonnees
"""
dep = None
choix = win.getch()
if choix == curses.KEY_UP:
dep = verification_deplacement(lab, pos_perso[0], pos_perso[1] - 1)
elif choix == curses.KEY_DOWN:
dep = verification_deplacement(lab, pos_perso[0], pos_perso[1] + 1)
elif choix == curses.KEY_LEFT:
dep = verification_deplacement(lab, pos_perso[0] - 1, pos_perso[1])
elif choix == curses.KEY_RIGHT:
dep = verification_deplacement(lab, pos_perso[0] + 1, pos_perso[1])
elif choix == 27:
close_curses()
exit(0)
if dep != None:
pos_perso[0] = dep[0]
pos_perso[1] = dep[1]
def jeu(level, perso, pos_perso, win, coul):
"""
Boucle principale du jeu
level : labyrynthe
perso : caractere representant le perso
pos_perso : pos
"""
while True:
afficher_labyrinthe(level, perso, pos_perso, win, coul)
choix_joueur(level, pos_perso, win)
if pos_perso == [-1, -1]:
win.addstr(22, 1, "Vous avez reussi le labyrinthe!", color("RED", coul))
close_curses()
break
def init_curses(lignes, cols, pos):
curses.initscr()
curses.noecho()
curses.cbreak()
curses.curs_set(0)
window = curses.newwin(lignes, cols, pos[0], pos[1])
window.border(0)
window.keypad(1)
return window
def close_curses():
curses.echo()
curses.nocbreak()
curses.curs_set(1)
curses.endwin()
def init_colors():
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_BLUE)
return ["RED", "GREEN", "BLUE"]
def color(code, l_color):
return curses.color_pair(l_color.index(code) + 1)
if __name__ == "__main__":
perso = "X"
pos_perso = [1, 1]
win = init_curses(25, 41, (0,0))
coul = init_colors()
jeu(level, perso, pos_perso, win, coul)
win.getch()
close_curses()
|
b1429474bbc0b8714a8b208a9afd280e1fd0281a | franciscoquinones/Python | /clase4/clase/ope.py | 455 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Dec 17 18:28:13 2016
@author: Josue
"""
import texto
class Ope(object):#Heredamos la clase primaria de python
def __init__(self,num1,num2):
self.num1=num1
self.num2=num2
print "Operacion"
def suma(self):
print self.num1+self.num2
def multi(self):
print self.num1*self.num2
if __name__=="__main__":
texto=texto.saludo() |
38ff2cbdca2f03b7b35806b222649ac9e49ff0df | UCLeuvenLimburg/vpw | /cat2/solitaire/python/fvogels.py3 | 1,659 | 3.703125 | 4 | from array import array
def solve(ns):
leftmost = float('Inf')
length = len(ns)
indices = list(range(length))
visited = set()
def jump_left(n, i):
if i > 1 and ns[i] and ns[i-1] and not ns[i-2]:
ns[i] = False
ns[i-1] = False
ns[i-2] = True
jump(n - 1)
ns[i] = True
ns[i-1] = True
ns[i-2] = False
def jump_right(n, i):
if i + 2 < length and ns[i] and ns[i+1] and not ns[i+2]:
ns[i] = False
ns[i+1] = False
ns[i+2] = True
jump(n - 1)
ns[i] = True
ns[i+1] = True
ns[i+2] = False
def jump(n):
nonlocal leftmost
nonlocal visited
t = tuple(ns)
if t not in visited:
visited.add(t)
if n > 1:
for i in indices:
jump_left(n, i)
jump_right(n, i)
else:
leftmost = min(leftmost, next(i for i in range(length) if ns[i]))
if leftmost == 0:
raise RuntimeError()
n = len([ 1 for n in ns if n ])
try:
jump(n)
except RuntimeError:
pass
return leftmost
def main():
n = int(input())
for index in range(1, n + 1):
ns = [ n == '1' for n in input().split(' ')[1:] ]
result = solve(ns)
if result == float('inf'):
result = 'ONMOGELIJK'
else:
result += 1
print("{} {}".format(index, result))
if __name__ == '__main__':
main()
|
4ceea84a5b3d635fb260113a53ef8193d88f2f25 | DaniilStepanov2000/SpellChecker | /check_sentence.py | 2,845 | 4.0625 | 4 | def get_dictionary() -> list:
"""Write words from dictionary to list
Args:
None.
Returns:
List of words that contains dictionary.txt.
"""
dictionary = []
with open('data/dictionary.txt', 'r', encoding='utf-8') as file:
for line in file:
dictionary.append(line[:-1])
return dictionary
def find_errors(list_of_words: list, dictionary: list) -> list:
""""Find incorrect words in input list.
Args:
list_of_words: List that contains words from input sentences.
dictionary: Dictionary that contains all words.
Returns:
List of incorrect words.
"""
error_words = []
for word in list_of_words:
if word.lower() not in dictionary:
error_words.append(word)
return error_words
def print_errors(error_list: list) -> None:
""""Print errors.
Args:
error_list: List of incorrect words.
Returns:
None.
"""
error_word = 'Incorrect words: '
if error_list:
for index, _ in enumerate(error_list):
if index == (len(error_list) - 1):
error_word = error_word + error_list[index] + '.'
else:
error_word = error_word + error_list[index] + ', '
print(error_word)
print('\n\n')
else:
print('All is correct! Great work!')
print('\n\n')
def preprocessing_sentence(sentence: str) -> str:
""""Remove all punctuation from input sentence.
Args:
sentence: Input sentence.
Returns:
Sentences without punctuation.
"""
punctuation = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
for item in sentence:
if item in punctuation:
sentence = sentence.replace(item, "")
return sentence
def check() -> None:
""""Start check input sentence.
Args:
None.
Returns:
None.
"""
sentence = input('Enter the sentence to check: ')
new_sentence = preprocessing_sentence(sentence)
list_of_words = new_sentence.split(' ')
dictionary = get_dictionary()
error_list = find_errors(list_of_words, dictionary)
print_errors(error_list)
def main() -> None:
"""Start point.
Args:
None.
Returns:
None.
"""
switch_dict = {'1': check,
'2': exit
}
while True:
print('-------------------------')
print('MENU |')
print('1. Enter the sentence. |')
print('2. Exit. |')
print('-------------------------')
value = input('Enter the value: ')
print('\n')
try:
switch_dict[value]()
except KeyError:
print('Error! Try again enter the value!')
print('\n')
if __name__ == '__main__':
main()
|
62e70f294b29fdecdeb1727a7a63cc122a3e71d9 | d-dodd/hangman | /hangman.py | 10,158 | 3.625 | 4 | import random
import re
import sys
import fileinput
words_file = open("spelling_words.txt", encoding="utf-8")
words = words_file.read()
words_list = re.findall(r'\w+', words)
with open("player_scores.txt") as f:
lines = f.readlines()
lines = [x.strip() for x in lines]
print("Welcome to hangman!")
print("You're guy is dead after 10 wrong guesses!")
print("\nHOW SCORING WORKS")
print(" + If you WIN, you get 1 point for every guess you had left.")
print(" + If you LOSE, you lose a point for the number of correct guesses it would've taken to win.")
print(" - For example, if you lose with this still left (the word is \"Mississippi\"):")
print(" M _ s s _ s s _ _ _ _")
print(" you would lose 2 points, because it would've taken 2 correct guesses to win ")
print(" (it would've taken you guessing \"i\" and \"p\".)")
class HangmanGame(object):
def __init__(self):
self.the_word = random.choice(words_list)
self.word_length = len(self.the_word)
self.wrong_guesses = []
self.right_guesses = []
self.vowels_not_guessed = ["a", "e", "i", "o", "u", "y"]
self.consonants_not_guessed = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "z"]
self.letters_left = []
for letter in self.the_word:
if letter.lower() not in self.letters_left:
self.letters_left.append(letter.lower())
self.game_status = []
num = self.word_length
while num > 0:
self.game_status.append("_")
num -= 1
self.players_scores = {}
for entry in lines:
comma = entry.find(",")
name = entry[0:comma]
score = int(entry[comma+2:len(entry)])
self.players_scores[name] = score
self.avatar_name = ""
self.running_score = 0
self.num_wrong = 0
def played_before(self):
ans1 = input("\nDo you have a permanent avatar for this game on this computer? (Y/n) ")
if ans1[0].lower() != "y":
ans2 = input("Would you like to create one to play this game with? ")
if ans2[0].lower() == "y":
self.get_name()
else:
name = ""
self.name_and_score(name)
self.game_initialize()
else:
self.what_name()
def what_name(self):
ans3 = input("What's its name? ")
if ans3 in self.players_scores:
print("\nWelcome back, {}!\n".format(ans3))
self.name_and_score(ans3)
self.game_initialize()
else:
print("We don't have any record of that name. That means we're going to have to go through this rigamorole again, man.\n Make sure you get the spelling right, and, like, also pay attention to capitalization.")
self.played_before()
def get_name(self):
ans1 = input("What name would you like your avatar to have? (Think hard about it. You'll never be able to change its name!) ")
ans2 = input("\nOK. So you're saying you want its name to be \"{}\". You sure you want this name for all eternity? (Y/n) ".format(ans1))
if ans2[0].lower() != "y":
print("Alrighty then! Let's try this thing again!")
self.get_name()
else:
if ans1 not in self.players_scores:
print("\nOK, you've made your decision. No looking back, dude! \n\n\nBut Jesus said to him, \"No one, having put his hand to the plow, and looking back, is fit for the kingdom of God.\" (Luke 9:62)\n\n\n")
self.players_scores[ans1] = 0
self.name_and_score(ans1)
self.game_initialize()
else:
ans3 = input("Actually, that name is already taken. \nIf you forgot that you DO have a permanent avatar, type \"X\". Otherwise, just hit RETURN. ")
if ans3.lower() != "x":
self.get_name()
else:
self.played_before()
def name_and_score(self, name):
self.avatar_name = name
if name == "":
self.running_score = 0
else:
self.running_score = self.players_scores[name]
def game_initialize(self):
print(self.avatar_name)
print("YOUR SCORE: "+str(self.running_score))
self.next_move()
def next_move(self):
print("Number of guesses left: "+str(format(10-self.num_wrong)))
print("WRONG GUESSES:")
if self.num_wrong > 0:
for letter in self.wrong_guesses:
print(" "+letter, end="")
print("\nVOWELS YOU HAVEN'T USED:")
for letter in self.vowels_not_guessed:
print(" "+letter, end="")
print("\nCONSONANTS YOU HAVEN'T USED:")
for letter in self.consonants_not_guessed:
print(" "+letter, end="")
print("\n")
for item in self.game_status:
print(item+" ", end="")
guess = input("\nGuess a letter! ")
self.check_guess(guess)
def check_guess(self, letter):
if letter.isalpha()==False or len(letter)!=1:
print("Please guess a LETTER and make sure it's EXACTLY 1 letter!")
else:
if letter.lower() in self.wrong_guesses or letter.lower() in self.right_guesses:
print("You already guessed that one!")
elif letter.lower() in self.the_word.lower():
print("\nYes, that letter is in the word.")
self.right_answer(letter)
elif letter.lower() not in self.the_word.lower():
print("\nNo, that letter isn't in the word.")
self.wrong_answer(letter)
self.next_move()
def right_answer(self, guess):
i = 0
guess = guess.lower()
for letter in self.the_word:
if guess == letter.lower():
self.game_status[i] == letter
i += 1
self.right_guesses.append(guess)
self.update_game_status(guess)
self.update_not_guessed(guess)
if self.won():
print("Congratulations, you just won! The word was \"{}\".".format(self.the_word))
print("Your win earned you {} points.".format(10-self.num_wrong))
self.recalibrate_score()
self.play_again()
def wrong_answer(self, guess):
guess = guess.lower()
self.num_wrong += 1
if self.lost():
print("Sorry, that was your 10th wrong answer, so you lost. The word was actually \"{}\".".format(self.the_word))
lost = self.points_lost()
print("There were {} letters left to guess, so your loss cost you {} points.".format(lost, lost))
self.recalibrate_score()
self.play_again()
else:
self.wrong_guesses.append(guess)
self.update_not_guessed(guess)
def update_game_status(self, guess):
i = 0
while i < self.word_length:
if self.the_word[i].lower()==guess:
self.game_status[i] = self.the_word[i]
i += 1
else:
i += 1
def won(self):
for item in self.game_status:
if item == "_":
return False
return True
def lost(self):
if self.num_wrong < 10:
return False
else:
return True
def play_again(self):
ans = input("\nWant to play again? (Y/n) ")
if ans[0].lower() == "y":
print("Awesome!\n")
self.reset_class_variables()
self.game_initialize()
else:
print("FINAL SCORE: "+str(self.running_score))
print("\nFine, be that way! I didn't want to play with you either!\n")
#self.rewrite_player_file(self.avatar_name, self.running_score)
sys.exit()
def reset_class_variables(self):
self.vowels_not_guessed = ["a", "e", "i", "o", "u", "y"]
self.consonants_not_guessed = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "z"]
self.the_word = random.choice(words_list)
self.word_length = len(self.the_word)
self.wrong_guesses = []
self.right_guesses = []
self.letters_left = []
for letter in self.the_word:
if letter.lower() not in self.letters_left:
self.letters_left.append(letter.lower())
self.game_status = []
num = self.word_length
while num > 0:
self.game_status.append("_")
num -= 1
self.num_wrong = 0
def update_not_guessed(self, guess):
if guess in self.vowels_not_guessed:
self.vowels_not_guessed.remove(guess)
else:
self.consonants_not_guessed.remove(guess)
def recalibrate_score(self):
if self.won():
self.running_score += (10-self.num_wrong)
if self.avatar_name != "":
self.players_scores[self.avatar_name] = self.running_score
else:
self.running_score -= self.points_lost()
if self.avatar_name != "":
self.players_scores[self.avatar_name] = self.running_score
self.rewrite_player_file()
def points_lost(self):
guesses_left = ""
i = 0
while i < len(self.game_status):
if self.game_status[i] == "_":
if self.the_word[i] not in guesses_left:
guesses_left += self.the_word[i]
i += 1
return len(guesses_left)
def rewrite_player_file(self):
f = open("player_scores.txt", 'w')
temp_list = []
for item in self.players_scores:
temp_list.append(item+", "+str(self.players_scores[item])+"\n")
i = 0
while i<len(temp_list):
f.write(temp_list[i])
i += 1
f.close()
if __name__ == '__main__':
game = HangmanGame()
game.played_before()
|
ce75870cddce5c7058168fd0cf608b59dcb7587d | Archishman-Ghosh/OOP-Problem-Aganitha | /Q2.py | 3,120 | 3.796875 | 4 | class X:
def __init__(self, name):
self.name = name
def execute(self, dic):
for key, value in dic.items():
print(key,value)
def shutdown():
pass
class A:
def __init__(self, name):
self.obj = X(name)
print("Class A object created.")
def execute(self, dic):
self.obj.execute(dic)
print(self.obj.name)
print("Class A")
def shutdown(self):
print(self.obj.name)
print("Class A")
class B:
def __init__(self, name):
self.obj = X(name)
print("Class B object created.")
def execute(self, dic):
self.obj.execute(dic)
print(self.obj.name)
print("Class B")
def shutdown(self):
print(self.obj.name)
print("Class B")
class C:
def __init__(self, name):
self.obj = X(name)
print("Class C object created.")
def execute(self, dic):
self.obj.execute(dic)
print(self.obj.name)
print("Class B")
def shutdown(self):
print(self.obj.name)
print("Class B")
if __name__=="__main__":
objList = []
execCnt = 0
ACnt = 0
BCnt = 0
CCnt = 0
while True:
print("Enter 1 for new object.\nEnter 2 to delete an object.\nEnter 3 run execute method.\nEnter 4 to quit.\n")
n = input()
if n=='1':
inp = input("Enter Class name(A/B/C): ")
if inp=="A":
objList.append(A(input("Enter object name: ")))
ACnt += 1
elif inp=="B":
objList.append(B(input("Enter object name: ")))
BCnt += 1
elif inp=="C":
objList.append(C(input("Enter object name: ")))
CCnt += 1
else:
print("Wrong input.")
elif n=='2':
inp = input("Enter object name to delete: ")
for item in objList:
if inp == item.obj.name:
objList.remove(item)
del item.obj
del item
print("Object deleted.")
elif n=='3':
inp = input("Enter object name to run execute method: ")
for item in objList:
if inp == item.obj.name:
d = int(input("Enter no. of dictionary elements: "))
print("Enter dictionary content:\n")
dic = {}
for _ in range(d):
dic[input("Key:")] = input("Value:")
item.execute(dic)
execCnt += 1
elif n=='4':
print("No. of times Class A object invoked =",ACnt)
print("No. of times Class B object invoked =",BCnt)
print("No. of times Class C object invoked =",CCnt)
print("No. of times execute() method invoked =",execCnt)
break
else:
print("Wrong input.")
|
04d534cfbd2f7e16594eeb0e75580370c394b80d | sictiru/NewsBlur | /apps/analyzer/tokenizer.py | 775 | 4.09375 | 4 | import re
class Tokenizer:
"""A simple regex-based whitespace tokenizer.
It expects a string and can return all tokens lower-cased
or in their existing case.
"""
WORD_RE = re.compile('[^a-zA-Z-]+')
def __init__(self, phrases, lower=False):
self.phrases = phrases
self.lower = lower
def tokenize(self, doc):
print(doc)
formatted_doc = ' '.join(self.WORD_RE.split(doc))
print(formatted_doc)
for phrase in self.phrases:
if phrase in formatted_doc:
yield phrase
if __name__ == '__main__':
phrases = ['Extra Extra', 'Streetlevel', 'House of the Day']
tokenizer = Tokenizer(phrases)
doc = 'Extra, Extra'
tokenizer.tokenize(doc) |
3c425f5a60daf4156df31550f1bda378dd2ecc04 | PrimeNumber012357/Fun-with-games-and-shapes | /fibonacci_userinput.py | 1,233 | 4.40625 | 4 | def fibonacci():
#Create i to keep looping through until the input is valid
i = 0
while i < 1:
try:
#Get user input
n = input("Enter the nth term in the Fibonacci sequence that you want to know: ")
user_input = int(n)
seed1 = 0
seed2 = 1
if user_input < 1:
print("You didn't enter a positive integer, try again")
continue
if user_input == 1:
print("The first number of the Fibonacci sequence is: 0")
break
elif user_input == 2:
print("The second number of the Fibonacci sequence is: 1")
break
else:
#Calculate Fibonacci terms larger than 2
start = 2
while start < user_input:
result = seed1 + seed2
seed1 = seed2
seed2 = result
start += 1
i += 1
if user_input >= 2:
print(f"The value of your chosen Fibonacci sequence is: {result}")
except ValueError:
print("You didn't enter a positive integer, try again")
fibonacci()
|
c2c4976ca61e8583e0b9a7eb2bdb6813e37860e1 | ferryleaf/GitPythonPrgms | /arrays/reverse_array_groups.py | 2,495 | 4.3125 | 4 | '''
Given an array arr[] of positive integers of size N. Reverse every sub-array
group of size K.
Example 1:
Input:
N = 5, K = 3
arr[] = {1,2,3,4,5}
Output: 3 2 1 5 4
Explanation: First group consists of elements
1, 2, 3. Second group consists of 4,5.
Example 2:
Input:
N = 4, K = 3
arr[] = {5,6,8,9}
Output: 8 6 5 9
Your Task:
You don't need to read input or print anything. The task is to complete the
function reverseInGroups() which takes the array, N and K as input parameters
and modifies the array in-place.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(N)
Constraints:
1 โค N, K โค 107
1 โค A[i] โค 1018
UC 1 :
6 3
1 2 3 4 5 6 ==> 3 2 1 6 5 4
UC2:
1 1
1 ==> 1
UC3:
2 1
1 2 ==> 1 2
UC4:
6 2
1 2 3 4 5 6 ==> 2 1 4 3 6 5
UC5:
3 1
1 2 3 ==> 1 2 3
UC6:
4 3
5 6 8 9 ==> 8 6 5 9
UC7:
1 0
1 ==> 1
UC8:
6 8
1 2 3 4 5 6 ==> 6 5 4 3 2 1
'''
class Solution:
# Expected Time Complexity: O(N)
# Expected Auxiliary Space: O(N) but completed it O(4) ==>ย O(1)
def reverseInGroups(self, arr, N, K):
if K == 0:
return
if K >= N:
K = N
i = 0
k1 = k2 = K - 1
while (i < N):
if i < k2:
temp = arr[k2]
arr[k2] = arr[i]
arr[i] = temp
i+=1
k2-=1
else:
i = k1 + 1
k1 = k1 + K
k2 = k1
if k1 >= N:
k1 = k2 = N - 1
if i >= N:
return
def reverseInGroups2(self, arr, N, K):
for i in range(0, N, K):
if i+K-1 <= N:
print(arr, i, i+K-1)
reverse(arr, i, i+K-1)
else:
print(arr, i, N-1)
reverse(arr, i, N-1)
return
def reverse(arr, st, en):
while(st < en):
temp = arr[st]
arr[st] = arr[en]
arr[en] = temp
st += 1
en -= 1
return
if __name__ == '__main__':
# N = int(input())
# K = int(input())
ob = Solution()
arr = [5, 6, 8, 9]
print("before", arr)
ob.reverseInGroups(arr, 4, 3)
for i in arr:
print(i, end=" ")
print()
arr = [36, 93, 64, 48, 96, 55, 70, 0, 82, 30, 16, 22, 38,
53, 19, 50, 91, 43, 70, 88, 10, 57, 14, 94, 13, 36,
59, 32, 54, 58, 18, 82, 67]
Solution().reverseInGroups(arr, 33, 13)
for i in arr:
print(i, end=" ")
print()
|
0d75c002bae0036d5b5925e66cf80edab959645e | tarampararam/python | /sber/basic/stairway.py | 191 | 4 | 4 | while (True):
n = int(input("Enter a number: "))
if (n > 9):
print("enter a lower number")
else:
break
for x in range(1, n + 1):
for y in range(1, x + 1):
print(y, end='')
print()
|
823594b67ff7e809c4aae07dbd68f98261ef0b35 | tylerneylon/knuth-taocp | /alg_b.py | 2,993 | 4.15625 | 4 | from collections import defaultdict
def pass_(*args):
pass
def algorithm_b(x, D, is_good, update=pass_, downdate=pass_, ell=0):
""" This is the basic backtrack algorithm from section 7.2.2.
x is a list whose values will be changed as this iterates; x will be the
list yielded when valid solutions are found.
D is a list of lists. D[ell] is the list, in order, of all possible
valid values for x[ell].
is_good(x, ell) returns True when x[0], ..., x[ell] is a valid partial
solution.
The optional functions update() and downdate() provide callers a
convenient way to keep track of intermediate helper data structures that
allow is_good to operate more efficiently.
"""
for d in D[ell]:
x[ell] = d
ell += 1
if is_good(x, ell):
if ell == len(x):
yield x
else:
update(x, ell)
yield from algorithm_b(x, D, is_good, update, downdate, ell)
downdate(x, ell)
ell -= 1
def permutations(n):
def is_good(x, ell):
return len(set(x[0:ell])) == ell
x = [0] * n
D = [list(range(n)) for _ in range(n)]
for p in algorithm_b(x, D, is_good):
print(p)
def combinations(n, k):
def is_good(x, ell):
return len(set(x[0:ell])) == ell
x = [0] * k
D = [list(range(n)) for _ in range(n)]
for p in algorithm_b(x, D, is_good):
print(p)
# The n-queens problem.
def n_queens_is_good(x, ell):
# Ensure each queen is in a unique column.
if len(set(x[0:ell])) < ell:
return False
# Ensure the new queen is not attacked along diagonals.
for k in range(ell - 1):
if ell - 1 - k == abs(x[ell - 1] - x[k]):
return False
return True
def print_board(x):
n = len(x)
for col in x:
print(f'{"L_ " * col} * {"L_ " * (n - col - 1)}')
def n_queens(n):
x = [0] * n
D = [list(range(n)) for _ in range(n)]
for i, q in enumerate(algorithm_b(x, D, n_queens_is_good)):
print()
print(f'Solution {i + 1}:')
print_board(x)
def problem_8():
""" The problem is to search for two different 8-queens solutions which are
identical in the first six rows. """
n = 8
x = [0] * n
D = [list(range(n)) for _ in range(n)]
# `solns` will map (x1,x2,..,x6) to a list of full solutions.
solns = defaultdict(list)
for i, q in enumerate(algorithm_b(x, D, n_queens_is_good)):
key = tuple(q[:6])
solns[key].append((i + 1, q))
if len(solns[key]) == 2:
soln1, soln2 = solns[key]
print()
print('_' * 70)
print(f'Solutions {soln1[0]} and {soln2[0]} are a pair:')
print()
print_board(soln1[1])
print()
print_board(soln2[1])
# permutations(4)
# combinations(5, 3)
# n_queens(8)
if __name__ == '__main__':
problem_8()
|
13e5e39e650128beacc15aadd23027d7600c3c03 | mcdyl1/Projects | /441/part2.py | 950 | 3.875 | 4 | import random
import math
import sympy
import time
def pollard_Rho(n):
i = 1
xi = random.randint(0, n-1)
y = xi
k = 2
d = 1
while d == 1:
i = i + 1
xi = (pow(xi, 2) - 1) % n #(xi**2 - 1) % n
d = math.gcd(y - xi, n)
if d != 1 and d != n:
return d
if i == k:
y = xi
k = 2*k
return n
def main():
#used for timing the program
start_time = time.time()
#get input from user, use pollard_rho to factor
n = int(input("Enter the number to factor: "))
d = pollard_Rho(n)
#making sure factors are the prime factors
if(sympy.isprime(d)):
print("d is prime")
if(sympy.isprime(n // d)):
print("n//d is prime")
print("Factors:")
print("d: ", d)
print("Other factor", n // d)
#time it took the program to run
end_time = time.time()
print("Time: ", end_time - start_time)
main()
|
7d9eba4675b0d77cd2c6dfd858cac3ea71bd4fb0 | ulink-college/code-dump | /challenge_booklet_1/solutions/challenge-1.13.py | 159 | 3.578125 | 4 | ###################################
#
# 1.13
#
#
import time, random
for i in range(10):
print(i, random.randint(0,100))
time.sleep(3)
i =+1
|
62fc488566c5813818a1b2d720e454a14b4128c8 | EderVs/IS-laboratorio-2020-2 | /Alumnos/MartinezMonroyEmily/decorator_example.py | 393 | 3.53125 | 4 | """
Practica 2: Decorador
Ingenieria de Software
Emily Martinez Monroy
"""
"""
Funcion Decorador
"""
def my_decorador(f):
def new_function(*args, **kwargs):
print("Before Function")
f(*args, **kwargs)
print("After Function")
return new_function
"""
Funcion para ejemplificar el decorador
"""
@my_decorador
def example_function(a,b,c):
print(a)
print(b)
print(c)
|
7be6246e5edf3c81fb27edc9900302ca5e594568 | 141sksk/practice | /yukicoder/138.py | 325 | 3.625 | 4 | def main():
a = list(map(int, input().split('.')))
b = list(map(int, input().split('.')))
for i in range(3):
if a[i] > b[i]:
print("YES")
break
elif a[i] < b[i]:
print("NO")
break
else:
print("YES")
if __name__ == "__main__":
main() |
e4474b98f8a376b7fae2e33e614f0ef37b5fa1e5 | astral-sh/ruff | /crates/ruff/resources/test/fixtures/pycodestyle/E731.py | 1,919 | 3.75 | 4 | def scope():
# E731
f = lambda x: 2 * x
def scope():
# E731
f = lambda x: 2 * x
def scope():
# E731
while False:
this = lambda y, z: 2 * x
def scope():
# E731
f = lambda: (yield 1)
def scope():
# E731
f = lambda: (yield from g())
def scope():
# OK
f = object()
f.method = lambda: "Method"
def scope():
# OK
f = {}
f["a"] = lambda x: x**2
def scope():
# OK
f = []
f.append(lambda x: x**2)
def scope():
# OK
f = g = lambda x: x**2
def scope():
# OK
lambda: "no-op"
class Scope:
# E731
f = lambda x: 2 * x
class Scope:
from typing import Callable
# E731
f: Callable[[int], int] = lambda x: 2 * x
def scope():
# E731
from typing import Callable
x: Callable[[int], int]
if True:
x = lambda: 1
else:
x = lambda: 2
return x
def scope():
# E731
from typing import Callable, ParamSpec
# ParamSpec cannot be used in this context, so do not preserve the annotation.
P = ParamSpec("P")
f: Callable[P, int] = lambda *args: len(args)
def scope():
# E731
from typing import Callable
f: Callable[[], None] = lambda: None
def scope():
# E731
from typing import Callable
f: Callable[..., None] = lambda a, b: None
def scope():
# E731
from typing import Callable
f: Callable[[int], int] = lambda x: 2 * x
# Let's use the `Callable` type from `collections.abc` instead.
def scope():
# E731
from collections.abc import Callable
f: Callable[[str, int], str] = lambda a, b: a * b
def scope():
# E731
from collections.abc import Callable
f: Callable[[str, int], tuple[str, int]] = lambda a, b: (a, b)
def scope():
# E731
from collections.abc import Callable
f: Callable[[str, int, list[str]], list[str]] = lambda a, b, /, c: [*c, a * b]
|
c4de231f2fef58d2687dae8f4bdcebc9538f999f | Seanmusse/todolistclipy | /todolistoldworking.py | 1,141 | 3.625 | 4 | import pickle
import os
os.system("clear")
print("-------------------------------Todo-list CLI application-------------------------------")
def space():
print(" ")
print(" ")
print(" ")
print(" ")
space()
userlist = []
filename = "userdata.p"
def maininput():
loaded_uinput = []
while True:
#Selecting if user wants to read or write the list, and or exit
init_conf = input("Would you like to read or write your list? (read | write | exit)")
#Printing the list
if init_conf == "read":
pickle_in = open(filename, "rb")
loaded_uinput = pickle.load(pickle_in, encoding='bytes')
pickle_in.close()
print(*loaded_uinput, sep="\n")
#Customizing the list
elif init_conf == "write":
uinput = input("What would you like to add to your list?")
userlist.append("-" + uinput)
pickle_out = open(filename, "ab")
pickle.dump(userlist, pickle_out)
pickle_out.close()
print(*loaded_uinput, sep="\n")
elif init_conf == "exit":
break
maininput()
|
d55c0d4405652ac1f2ed70633b6be06fce3aa223 | skuxy/Advent-Of-Code-codes | /2019/day2.py | 2,261 | 3.84375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Second day of 2019 AoC
"""
OPCODE_MAP = {
1: lambda a, b: a + b,
2: lambda a, b: a * b
}
class ShipComputer:
"""
Representing our ships computer
For I'm lazy
"""
def __init__(self, intcode):
self.intcode = intcode
self.position = 0
def parse_sequence(self):
"""Parse opcode sequence"""
operation = self.intcode[self.position]
if operation == 99:
return False
first_operand = self.intcode[self.intcode[self.position + 1]]
second_operand = self.intcode[self.intcode[self.position + 2]]
result = self.intcode[self.position + 3]
self.intcode[result] = \
OPCODE_MAP[operation](first_operand, second_operand)
return True
def step(self):
"""Execute opcode"""
if self.parse_sequence():
self.position += 4
return True
return False
def play(self):
"""Parse whole intcode"""
while self.step():
pass
if __name__ == "__main__":
# Part one
SC1 = ShipComputer([1, 0, 0, 0, 99])
SC1.play()
assert SC1.intcode == [2, 0, 0, 0, 99]
SC2 = ShipComputer([2, 3, 0, 3, 99])
SC2.play()
assert SC2.intcode == [2, 3, 0, 6, 99]
SC3 = ShipComputer([2, 4, 4, 5, 99, 0])
SC3.play()
assert SC3.intcode \
== [2, 4, 4, 5, 99, 9801]
SC4 = ShipComputer([1, 1, 1, 4, 99, 5, 6, 0, 99])
SC4.play()
assert SC4.intcode \
== [30, 1, 1, 4, 2, 5, 6, 0, 99]
with open('2019/input2.txt') as input_file:
SC = ShipComputer(
list(map(int, input_file.read().split(',')))
)
SC.intcode[1] = 12
SC.intcode[2] = 2
SC.play()
print(SC.intcode[0])
# Part 2
for x in range(100):
for y in range(100):
with open('2019/input2.txt') as input_file:
SC = ShipComputer(
list(map(int, input_file.read().split(',')))
)
SC.intcode[1] = x
SC.intcode[2] = y
SC.play()
if SC.intcode[0] == 19690720:
print(100 * x + y)
break
|
cd21310eac2cd0fe76aeb4b9d80cc80266e3c3c3 | gaoyan0629/IVY | /devl/closure.py | 878 | 4.0625 | 4 | # When to use closures?
# So what are closures good for?
# Closures can avoid the use of global values and provides some form of data hiding. It can also provide an object oriented solution to the problem.
# When there are few methods (one method in most cases) to be implemented in a class, closures can provide an alternate and more elegant solutions. But when the number of attributes and methods get larger, better implement a class.
#
# Here is a simple example where a closure might be more preferable than defining a class and making objects. But the preference is all yours.
# the beauty is that the argument n will now be memorized by multiplier
def make_multiplier_of(n):
def multiplier(x):
return x * n
return multiplier
# Multiplier of 3
times3 = make_multiplier_of(3)
# Multiplier of 5
times5 = make_multiplier_of(5)
#now we have two instance
|
8208c8da0a016ed8f8e9c28db74fcb058968fedd | sunilnandihalli/leetcode | /editor/en/[801]Minimum Swaps To Make Sequences Increasing.py | 1,503 | 3.984375 | 4 | # We have two integer sequences A and B of the same non-zero length.
#
# We are allowed to swap elements A[i] and B[i]. Note that both elements are in
# the same index position in their respective sequences.
#
# At the end of some number of swaps, A and B are both strictly increasing. (A
# sequence is strictly increasing if and only if A[0] < A[1] < A[2] < ... < A[A.le
# ngth - 1].)
#
# Given A and B, return the minimum number of swaps to make both sequences stri
# ctly increasing. It is guaranteed that the given input always makes it possible.
#
#
#
# Example:
# Input: A = [1,3,5,4], B = [1,2,3,7]
# Output: 1
# Explanation:
# Swap A[3] and B[3]. Then the sequences are:
# A = [1, 3, 5, 7] and B = [1, 2, 3, 4]
# which are both strictly increasing.
#
#
# Note:
#
#
# A, B are arrays with the same length, and that length will be in the range [1
# , 1000].
# A[i], B[i] are integer values in the range [0, 2000].
#
# Related Topics Dynamic Programming
# leetcode submit region begin(Prohibit modification and deletion)
def swap(A, B, i):
tmp = A[i]
A[i] = B[i]
B[i] = tmp
from functools import lru_cache
@lru_cache(None)
def min_swap(A, B, i): # what is the minimum number of swaps necessary to make the lists A and B increasing upto i
if i>0:
if A[i]>A[i-1] and B[i]>B[i-1]:
swap(A,B,i)
class Solution:
def minSwap(self, A: List[int], B: List[int]) -> int:
# leetcode submit region end(Prohibit modification and deletion)
|
bf84f2bd0d0479721a294192a92ecbf61e7cf318 | SL-PROGRAM/Mooc | /UPYLAB3-12.py | 428 | 3.75 | 4 | """Auteur: Simon LEYRAL
Date : Octobre 2017
Enoncรฉ
Cet exercice propose une variante de lโexercice prรฉcรฉdent sur le carrรฉ de X.
รcrire un programme qui lit sur input une valeur naturelle n et qui affiche ร lโรฉcran un triangle supรฉrieur
droit formรฉ de X (voir exemples plus bas).
"""
n = int(input())
for i in range(n):
if i == 0:
print("X" * (n-i))
else:
print(" "*(i-1), "X"*(n-i))
|
af1f283ad1ae37cd5b2185578268fbb5ab35f79f | agiang96/CS550 | /CS550Assignment2/problemsearch.py | 4,295 | 3.71875 | 4 | '''
Created on Feb 10, 2018
file: problemsearch.py
@author: mroch
'''
from basicsearch_lib02.searchrep import (Node, print_nodes)
from basicsearch_lib02.queues import PriorityQueue
from explored import Explored
from searchstrategies import (BreadthFirst, DepthFirst, Manhattan)
import time
def graph_search(problem, verbose=False, debug=False):
"""graph_search(problem, verbose, debug) - Given a problem representation
(instance of basicsearch_lib02.representation.Problem or derived class),
attempt to solve the problem.
If debug is True, debugging information will be displayed.
if verbose is True, the following information will be displayed:
Number of moves to solution
List of moves and resulting puzzle states
Example:
Solution in 25 moves
Initial state
0 1 2
0 4 8 7
1 5 . 2
2 3 6 1
Move 1 - [0, -1]
0 1 2
0 4 8 7
1 . 5 2
2 3 6 1
Move 2 - [1, 0]
0 1 2
0 4 8 7
1 3 5 2
2 . 6 1
... more moves ...
0 1 2
0 1 3 5
1 4 2 .
2 6 7 8
Move 22 - [-1, 0]
0 1 2
0 1 3 .
1 4 2 5
2 6 7 8
Move 23 - [0, -1]
0 1 2
0 1 . 3
1 4 2 5
2 6 7 8
Move 24 - [1, 0]
0 1 2
0 1 2 3
1 4 . 5
2 6 7 8
If no solution were found (not possible with the puzzles we
are using), we would display:
No solution found
Returns a tuple (path, nodes_explored) where:
path - list of actions to solve the problem or None if no solution was found
nodes_explored - Number of nodes explored (dequeued from frontier)
"""
explored = Explored()
numnodes = 0
finished = False
#create initial state without parent or actions
currentnode = Node(problem, problem.initial)
#DepthFirst doesn't create the correct frontier with the default PriorityQueue()
if(problem.g == DepthFirst.g and problem.h == DepthFirst.h):
frontier = PriorityQueue(currentnode.get_f())
else:
frontier = PriorityQueue()
frontier.append(currentnode)
while not finished:
currentnode = frontier.pop()
if debug: #will print all the steps of traversing thru search
print(currentnode.__repr__())
explored.add(currentnode.state)
if not currentnode.state.solved():
for nodes in currentnode.expand(problem):
numnodes += 1
if not explored.exists(nodes.state):
frontier.append(nodes)
finished = frontier.__len__() == 0
else:
finished = True
if verbose: #will print the solution steps per function description
if(currentnode.solution() == 0):
print("No solution found")
else:
print("Solution in ", len(currentnode.solution()), " moves")
print("Initial State")
print(problem.initial)
problemcopy = problem.initial
for moves in range(len(currentnode.solution())):
print("Move ", moves + 1, " - ", currentnode.solution()[moves])
problemcopy = problemcopy.move(currentnode.solution()[moves])
print(problemcopy.__repr__())
return (numnodes, currentnode.solution())
|
a594ae1b90a738615ba823a49ab87236fb912a96 | JakeMartin99/LearningML | /kerasCNN.py | 1,774 | 3.53125 | 4 | # Sourced from the blog at https://victorzhou.com/blog/keras-cnn-tutorial/
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Don't print verbose info msgs
import numpy as np
import mnist
import keras
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout
from keras.utils import to_categorical
train_images = mnist.train_images()
train_labels = mnist.train_labels()
test_images = mnist.test_images()
test_labels = mnist.test_labels()
# Normalize the images
train_images = (train_images / 255) - 0.5
test_images = (test_images / 255) - 0.5
# Reshape the images
train_images = np.expand_dims(train_images, axis=3)
test_images = np.expand_dims(test_images, axis=3)
# Build the model
num_filters = 8
filter_size = 3
pool_size = 2
model = Sequential([
# Layers...
Conv2D(num_filters, filter_size, input_shape=(28,28,1)),
Conv2D(num_filters, filter_size),
MaxPooling2D(pool_size=pool_size),
Dropout(0.5),
Flatten(),
Dense(64, activation='relu'),
Dense(10, activation='softmax'),
])
# Compile the model
model.compile(
'adam',
loss='categorical_crossentropy',
metrics=['accuracy'],
)
# Train the model
print("\nTraining model:")
model.fit(
train_images,
to_categorical(train_labels),
epochs=12,
validation_data=(test_images, to_categorical(test_labels)),
)
# Save weights
model.save_weights('cnn.h5')
# Load the model from disk later using:
# model.load_weights('cnn.h5')
# Predict on the first 5 test images
print("\nPrediction:")
predictions = model.predict(test_images[:5])
# Print the model's predictions
print(np.argmax(predictions, axis=1)) # [7, 2, 1, 0, 4]
# Check predictions against truth
print("Truth:")
print(test_labels[:5]) # [7, 2, 1, 0, 4]
|
0bdd36991ac1f08d378eedc0445fb2e391c2f1a1 | siyaoc2/Final-Project | /siyaoc2_final_project_PE02(from Chapter 9).py | 1,825 | 4.125 | 4 | from random import random
def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(winsA, winsB)
def printIntro():
print("This program simulates a game of volleyball between two")
print('players called "A" and "B". The ability of each player is')
print("indicated by a probability (a number between 0 and 1) that")
print("the team wins a rally is awarded a point.")
def getInputs():
a = float(input("What is the prob. player A wins a rally? "))
b = float(input("What is the prob. player B wins a rally? "))
n = int(input("Numbers of games to simulate? "))
return a, b, n
def simNGames(n, probA, probB):
winsA = 0
winsB = 0
for i in range(n):
scoreA, scoreB = simOneGame(probA, probB)
if scoreA > scoreB:
winsA = winsA + 1
else:
winsB = winsB + 1
return winsA, winsB
def simOneGame(probA, probB):
serving = "A"
scoreA = 0
scoreB = 0
while not gameOver(scoreA, scoreB):
if serving == "A":
if random() < probA:
scoreA = scoreA + 1
else:
serving = "B"
else:
if random() < probB:
scoreB= scoreB + 1
else:
serving = "A"
return scoreA, scoreB
def gameOver(a,b):
return (a>=25 and a - b >= 2) or (b >= 25 and b-a >= 2)
# Games are played to a score of 25, and must be won by at least 2 points.
# a & b represent scores they earned for this game.
def printSummary(winsA, winsB):
n = winsA + winsB
print("\nGames simulated:", n)
print("Wins for A: {0} ({1:0.1%})". format(winsA, winsA/n))
print("Wins for B: {0} ({1:0.1%})". format(winsB, winsB/n))
if __name__ == '__main__':
main()
|
f33d94f70dfad6cf4daffbfef26020065b1251c7 | Jacrabel/Coding-in-Python | /day-3-2-exercise/main.py | 545 | 4.28125 | 4 | # ๐จ Don't change the code below ๐
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
# ๐จ Don't change the code above ๐
#Write your code below this line ๐
BMI = round(weight / (height ** 2))
print (BMI)
if BMI <18.5:
print(f"Your bmi is {BMI},they are underweight.")
elif BMI < 25:
print("they have a normal weight.")
elif BMI < 30:
print("they are slightly overweight.")
elif BMI > 30 and BMI < 35:
print("they are obese.")
else:
print("they are clinically obese.")
|
93677132a5291c9674130d6c279051c181452f36 | suwhisper/Solutions-for-Think-Python-2e | /chapter_5/is_triangle.py | 309 | 4.25 | 4 | def is_triangle():
"""shows whether you can or cannot form a triangle from sticks with the given lengths.
"""
a = int(input("Please input a: "))
b = int(input("Please input b: "))
c = int(input("Please input c: "))
if a < b + c and b < a+c and c<a+b:
print("Yes")
else:
print("No")
is_triangle()
|
d8cd1c7df7a689263edc43331814d17fe5c993e3 | GordonDoo/scikit-learn_MLPClassifier_with_dropout_py37 | /examples/neighbors/plot_approximate_nearest_neighbors_hyperparameters.py | 5,141 | 3.734375 | 4 | """
=================================================
Hyper-parameters of Approximate Nearest Neighbors
=================================================
This example demonstrates the behaviour of the
accuracy of the nearest neighbor queries of Locality Sensitive Hashing
Forest as the number of candidates and the number of estimators (trees)
vary.
In the first plot, accuracy is measured with the number of candidates. Here,
the term "number of candidates" refers to maximum bound for the number of
distinct points retrieved from each tree to calculate the distances. Nearest
neighbors are selected from this pool of candidates. Number of estimators is
maintained at three fixed levels (1, 5, 10).
In the second plot, the number of candidates is fixed at 50. Number of trees
is varied and the accuracy is plotted against those values. To measure the
accuracy, the true nearest neighbors are required, therefore
:class:`sklearn.neighbors.NearestNeighbors` is used to compute the exact
neighbors.
"""
from __future__ import division
print(__doc__)
# Author: Maheshakya Wijewardena <maheshakya.10@cse.mrt.ac.lk>
#
# License: BSD 3 clause
###############################################################################
import numpy as np
from sklearn.datasets.samples_generator import make_blobs
from sklearn.neighbors import LSHForest
from sklearn.neighbors import NearestNeighbors
import matplotlib.pyplot as plt
# Initialize size of the database, iterations and required neighbors.
n_samples = 10000
n_features = 100
n_queries = 30
rng = np.random.RandomState(42)
# Generate sample data
X, _ = make_blobs(n_samples=n_samples + n_queries,
n_features=n_features, centers=10,
random_state=0)
X_index = X[:n_samples]
X_query = X[n_samples:]
# Get exact neighbors
nbrs = NearestNeighbors(n_neighbors=1, algorithm='brute',
metric='cosine').fit(X_index)
neighbors_exact = nbrs.kneighbors(X_query, return_distance=False)
# Set `n_candidate` values
n_candidates_values = np.linspace(10, 500, 5).astype(np.int)
n_estimators_for_candidate_value = [1, 5, 10]
n_iter = 10
stds_accuracies = np.zeros((len(n_estimators_for_candidate_value),
n_candidates_values.shape[0]),
dtype=float)
accuracies_c = np.zeros((len(n_estimators_for_candidate_value),
n_candidates_values.shape[0]), dtype=float)
# LSH Forest is a stochastic index: perform several iteration to estimate
# expected accuracy and standard deviation displayed as error bars in
# the plots
for j, value in enumerate(n_estimators_for_candidate_value):
for i, n_candidates in enumerate(n_candidates_values):
accuracy_c = []
for seed in range(n_iter):
lshf = LSHForest(n_estimators=value,
n_candidates=n_candidates, n_neighbors=1,
random_state=seed)
# Build the LSH Forest index
lshf.fit(X_index)
# Get neighbors
neighbors_approx = lshf.kneighbors(X_query,
return_distance=False)
accuracy_c.append(np.sum(np.equal(neighbors_approx,
neighbors_exact)) /
n_queries)
stds_accuracies[j, i] = np.std(accuracy_c)
accuracies_c[j, i] = np.mean(accuracy_c)
# Set `n_estimators` values
n_estimators_values = [1, 5, 10, 20, 30, 40, 50]
accuracies_trees = np.zeros(len(n_estimators_values), dtype=float)
# Calculate average accuracy for each value of `n_estimators`
for i, n_estimators in enumerate(n_estimators_values):
lshf = LSHForest(n_estimators=n_estimators, n_neighbors=1)
# Build the LSH Forest index
lshf.fit(X_index)
# Get neighbors
neighbors_approx = lshf.kneighbors(X_query, return_distance=False)
accuracies_trees[i] = np.sum(np.equal(neighbors_approx,
neighbors_exact))/n_queries
###############################################################################
# Plot the accuracy variation with `n_candidates`
plt.figure()
colors = ['c', 'm', 'y']
for i, n_estimators in enumerate(n_estimators_for_candidate_value):
label = 'n_estimators = %d ' % n_estimators
plt.plot(n_candidates_values, accuracies_c[i, :],
'o-', c=colors[i], label=label)
plt.errorbar(n_candidates_values, accuracies_c[i, :],
stds_accuracies[i, :], c=colors[i])
plt.legend(loc='upper left', prop=dict(size='small'))
plt.ylim([0, 1.2])
plt.xlim(min(n_candidates_values), max(n_candidates_values))
plt.ylabel("Accuracy")
plt.xlabel("n_candidates")
plt.grid(which='both')
plt.title("Accuracy variation with n_candidates")
# Plot the accuracy variation with `n_estimators`
plt.figure()
plt.scatter(n_estimators_values, accuracies_trees, c='k')
plt.plot(n_estimators_values, accuracies_trees, c='g')
plt.ylim([0, 1.2])
plt.xlim(min(n_estimators_values), max(n_estimators_values))
plt.ylabel("Accuracy")
plt.xlabel("n_estimators")
plt.grid(which='both')
plt.title("Accuracy variation with n_estimators")
plt.show()
|
107ce214b3a0649e27a0e5503038fb3dc5aa71c7 | Tim6FTN/wash-lang-prototype | /wash_lang_prototype/core/common.py | 1,547 | 3.84375 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any
class Handler(ABC):
"""
Represents an interface that declares a method for building a chain of handlers,
otherwise known as the chain of responsibility pattern.
It also declares a method for executing a request using the chain of handlers.
"""
@abstractmethod
def set_next(self, handler: Handler) -> Handler:
"""
Sets the next handler in the chain.
Args:
handler(Handler): The next handler in the chain.
"""
pass
@abstractmethod
def handle(self, request: Any) -> Any:
"""
Handles the given request by executing the chain of registered handlers.
All concrete Handlers either handle the request or pass it to the next handler in the chain.
Args:
request: The request to be handled by the chain.
"""
pass
class ObjectFactory(ABC):
"""
Represents a general purpose Object Factory that can be used to create all kinds of objects.
Provides a method to register a Builder based on a key value
and a method to create the concrete object instances based on the key.
"""
def __init__(self):
self._builders = {}
def register_builder(self, key, builder):
self._builders[key] = builder
def create(self, key, **kwargs) -> Any:
builder = self._builders.get(key)
if not builder:
raise ValueError(key)
return builder(**kwargs)
|
ae1daca0280747434de635fa84443bc3d2bbd977 | hoanbka/Algorithm-Python | /DFS/generateParenthesis.py | 532 | 3.65625 | 4 | class Solution(object):
def generateParenthesis(self,n):
list = []
self.backtrack(list, "", 0, 0, n)
return list
def backtrack(self,list, str, open, close, max):
if (len(str) == max * 2):
list.append(str)
return
if (open < max):
self.backtrack(list, str + "(", open + 1, close, max)
if (close < open):
self.backtrack(list, str + ")", open, close + 1, max)
#MAIN
solution = Solution()
print(solution.generateParenthesis(3)) |
11b40b955122878caf0f2714f996da07b66b7962 | Kawser-nerd/CLCDSA | /Source Codes/AtCoder/abc032/A/4825210.py | 134 | 3.5 | 4 | a = int(input())
b = int(input())
n = int(input())
while True:
if n%a==0 and n%b==0:
break
n = n+1
print(n) |
147092e83c3827a8e2defb41994f482e130d45c4 | GISmd/snaddersim | /runsim.py | 1,370 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 27 11:38:47 2018
@author: smmcdeid
Our snakes and ladders simulator
"""
import random
import pandas
board = [[4,35],[8,47],[20,55],[23,5],[31,85],[33,9],[40,62],[44,15],[60,21],
[63,82],[68,36],[72,90],[89,56],[91,70],[94,11],[96,81],[83,43]]
def rolldice():
return random.randint(1,6)
def move(position):
position += rolldice()
return position
def check4snadders(position,board):
for square in board:
if position == square[0]:
# if square[1] > position:
# print('Yay! Climb the ladder from {} to {}!!!'.format(str(position),str(square[1])))
# else:
# print('Oh no! A snake got you! Go from {} to {}!!!'.format(str(position),str(square[1])))
position = square[1]
return position
def playgame_1player():
position = 1
turns = 0
while position <= 100:
position = move(position)
check4snadders(position,board)
turns += 1
# print(position)
# print('It took {} turns to reach 100...'.format(str(turns)))
return turns
def run_snaddersims(sims = 10000):
results = []
for sim in range(sims):
results.append(playgame_1player())
return results
results = run_snaddersims(1000000)
df = pandas.DataFrame(results)
df.hist()
df.plot.box()
df.plot.density() |
910aa7ced9fff06be32a52c0200f80d17c29a55a | gmyrak/py_tests | /help.py | 292 | 3.703125 | 4 | from turtle import *
def tree ( levels, length ):
if levels > 0:
forward ( length )
left ( 45 )
tree ( levels-1, length*0.6)
right ( 90 )
tree ( levels-1, length*0.6)
left ( 45 )
backward ( length )
setheading ( 90 )
tree ( 5, 100 ) |
ea0add6258be2fca7912c4476c039aae71f76c5d | supratikn/Dijkstra | /Dijkstra.py | 1,417 | 3.84375 | 4 | '''
Created on Jan 30, 2018
@author: sneupane
'''
from builtins import str
graph = {'a':{'b':10,'c':3},'b':{'c':1,'d':2},'c':{'b':4,'d':8,'e':2},'d':{'e':7},'e':{'d':9}}
def dijkstra(graph, start, goal):
shortestDistance ={}
predecessor={}
unseenNodes=graph
infinity = 9999
path=[]
for node in unseenNodes:
shortestDistance[node] = infinity
shortestDistance[start]=0
while unseenNodes:
minNode= None
for node in unseenNodes:
if minNode is None:
minNode = node
elif shortestDistance[node] < shortestDistance[minNode]:
minNode=node
for child, weight in graph[minNode].items():
if weight + shortestDistance[minNode]< shortestDistance[child]:
shortestDistance[child] =weight + shortestDistance[minNode]
predecessor[child]=minNode
unseenNodes.pop(minNode)
current = goal
while current !=start:
try:
path.insert(0, current)
current = predecessor[current]
except KeyError:
print("can't get there")
break
path.insert(0,start)
if shortestDistance[goal]!=infinity:
print("shortest distance: "+str(shortestDistance[goal]))
print("path: "+ str(path))
dijkstra(graph, 'a', 'e')
|
24cc3693beba06ed5a2ebc600da998e51b9b3934 | daisuke1230/weekday-search | /weekday-search.py | 329 | 3.90625 | 4 | import datetime
print('start year')
y_i=input()
print('end year')
y_f=input()
print('day')
d=input()
print('weekday')
wd=input()
for y in range(int(y_i),int(y_f)):
for m in range(1,13):
D = datetime.date(y,m,int(d))
if D.weekday() == int(wd)-1:
print(D.strftime("%Y%m%d"))
|
be190048ea3571d180b99e152d4a496309c9b21f | vivianLL/LeetCode | /172_FactorialTrailingZeroes.py | 1,634 | 3.890625 | 4 | '''
172. Factorial Trailing Zeroes
Easy
https://leetcode.com/problems/factorial-trailing-zeroes/
Given an integer n, return the number of trailing zeroes in n!.
'''
import math
class Solution:
def trailingZeroes(self, n: int) -> int:
# # ๆดๅๆฑ้ถไนๆณ ่ถ
ๆถ
# num = 1
# for i in range(2,n+1):
# num *= i
# print(num)
# strnum = str(num)
# return len(strnum)-len(strnum.strip('0'))
# # ๆ็ๆนๆณ็ๆน่ฟ ไพ็ถ่ถ
ๆถ
# if n==0: # 0็้ถไนๆฏ1
# return 0
# count = 0
# for i in range(2,n+1):
# while i>0:
# if i%5==0: # ๅฐพๆฐๆฏ5
# count += 1
# i /= 5
# else:
# break
# return count
# ็ปง็ปญๆน่ฟ
count = 0
while n > 0:
count += n//5
n = n//5
return count
sol = Solution()
ans = sol.trailingZeroes(40)
print(ans)
# ๆ่ทฏ๏ผ10็ฑ2*5ๆๆ๏ผๅซๆ5็ๅ ๅญๆฏๅซๆ2็ๅ ๅญๅบ็ฐ็ๅฐ๏ผๅ ๆญคๅช้ๆพๅฐๆๅคๅฐไธช5ใ
# ๆณจๆ25ๅฏไปฅๅ่งฃไธบ5*5,125ๅฏไปฅๅ่งฃไธบ5*5*5ยทยทยท่ฆๅฏนๆฅไธๆฅ็่ฟ้จๅๆ
ๅต่ฟ่ก็ป่ฎก๏ผ
# ๆไปฌๅฏไปฅๅฏนnๅ25็ๅ๏ผๅณn//25๏ผ่ฟๆ ทๅฐฑๆพๅฐไบๅ
ๅซๆ2ไธช5็ๆฐ๏ผไธๅ ไธบๆฏๅฏน5ร5ๅๅ๏ผๆฒกๆ้ๅค่ฎกๅ
ฅ๏ผ๏ผไพๆญค็ฑปๆจ๏ผๅฏไปฅๅพช็ฏๅฏนnๅ5, 25, 125...็ๅ๏ผๅฐๆๆ็ๆ
ๅต้ฝๅ
ๆฌ๏ผๆ็ปๅฐๆๆ็ๅๆฑๆปๅณ0็ไธชๆฐใ
# n // 25 == n // 5 // 5๏ผๅ ๆญคๅฏไปฅๅฏนnๅพช็ฏๅ5็ๅ๏ผๅ
ถๆๆๆฏไธๆ ท็ใ |
6dfb18fb594642ceb8f3fb2f548abb86ea64f8a2 | SirAeroWN/ComputerScience | /101/November/Checkerboard.py | 539 | 3.59375 | 4 | from tkinter import *
class Board:
def __init__(self):
self.window = Tk()
self.window.geometry("195x195")
self.size = 160
for i in range(0,8):
for j in range(0,8):
if(i + j) % 2 == 0:
self.canvas = Canvas(self.window, bg = "white", width = self.size/8, height = self.size/8)
self.canvas.grid(row = i, column = j)
else:
self.canvas = Canvas(self.window, bg = "black", width = self.size/8, height = self.size/8)
self.canvas.grid(row = i, column = j)
self.window.mainloop()
Board() |
aa53ebfb8240f6ac9c988e0aa216311bf8e1bb85 | dragos-vacariu/Python-Exercises | /Advanced Practice/program1 sorting list and functors.py | 2,429 | 4.25 | 4 | #Creating a Functor class
class Functor:
#Dunder functions are pre-defined functions which have __ (underscore) as prefix and surfix. Example: __init__()
def __init__(self, word):
self.word = word
#A class became a functor if this function __call___ gets overwritten/defined.
def __call__(self): #this will make Functor class be a functor.
print("Functor called.")
obj = Functor("something")
obj() #A functor is callable, just as a function.
obj.__call__() # obj() as functor is equivalent to calling obj.__call__().
print("\nSorting list exercise:")
class Persoana:
def __init__(self, nume, prenume, varsta):
self.nume = nume
self.prenume = prenume
self.varsta = varsta
def print(self):
print(self.nume + "\t\t" + self.prenume + "\t\t" + str(self.varsta))
def main():
persoane = [
Persoana("Geere", "Richard", 64),
Persoana("Walker", "Alan", 24),
Persoana("Manson", "Mary", 34),
Persoana("Manson", "Deny", 36),
Persoana("Menance", "Denise", 54),
Persoana("Reyes", "Antonio", 22),
]
raport_varsta(persoane)
raport_NumeVarsta(persoane)
raport(persoane, "nume prenume varsta")
def raport_varsta(persons):
persons.sort(key=lambda Person: Person.varsta)
for x in persons:
x.print()
print()
def raport_NumeVarsta(persons):
persons.sort(key=lambda Person: (Person.nume,Person.varsta))
for x in persons:
x.print()
print()
def raport(persons, strV):
words = strV.split(" ")
if "nume" in words and "prenume" in words and "varsta" in words:
persons.sort(key=lambda Person: (Person.nume, Person.prenume, Person.varsta))
elif "nume" in words and "prenume" in words:
persons.sort(key=lambda Person: (Person.nume, Person.prenume))
elif "nume" in words and "varsta" in words:
persons.sort(key=lambda Person: (Person.nume, Person.varsta))
elif "prenume" in words and "varsta" in words:
persons.sort(key=lambda Person: (Person.nume, Person.varsta))
else:
if words[0] == "nume": persons.sort(key=lambda Person: (Person.nume))
elif words[0] == "prenume": persons.sort(key=lambda Person: (Person.prenume))
else: persons.sort(key=lambda Person: (Person.varsta))
for x in persons:
x.print()
print()
main() |
8fd276d4f9fcd5dbdd38cdcb4504b1c2c1e3317f | benjamesian/holbertonschool-higher_level_programming | /0x06-python-classes/1-square.py | 199 | 3.59375 | 4 | #!/usr/bin/python3
"""Square with size
"""
class Square:
"""Square class
"""
def __init__(self, size):
"""Initialize a Square with a size
"""
self.__size = size
|
f132b6a130e62343f68cacdab008fe67320142c4 | Ben-Donaldson/Python | /input.py | 127 | 4.21875 | 4 | name = input("Hi! What is your name?")
age = input("How old are you?")
print("Hi " + name + "! You are " + age + " years old.") |
2ab635854ee9ed9b1f1d93cafb5c61846f2a5d20 | gabriellaec/desoft-analise-exercicios | /backup/user_195/ch49_2019_03_19_19_32_05_441019.py | 208 | 3.8125 | 4 | numero=int(input("Diga um nรบmero inteiro"))
i=1
L=[numero]
while numero>0:
L[i-1]=numero
numero=int(input("Diga outro nรบmero inteiro"))
i+=1
L.append(0)
L.remove(0)
L.reverse()
print(L) |
7d33305ce35d05ef6c35fbe462dee9de5b367bdf | kotsky/programming-exercises | /Dynamic Programming/Square Of Zeroes.py | 10,573 | 4.125 | 4 | '''
Return True or False if there is a Zero Square (which is created only from "0" as bounder and more or equal than 2x2 size)
in the given matrix.
matrix = [
[1, 1, 1, 0, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 1],
[0, 0, 0, 1, 0, 1],
[0, 1, 1, 1, 0, 1],
[0, 0, 0, 0, 0, 1],
]
Output = True
'''
# n - number by row
# m - number by column
'''
The idea is traverse through each element of the matrix
and assume, that it might be a start point of our valid zero square,
we call function checkValidZeroSquare at that point [n,m].
At version 2, checkValidZeroSquare was done by traversing each line
of possible zero square and try to validate it (when every element in the line is "0").
To check its square, 4 line traversing were needed, which took O(n) time complexity each.
Also, each element of the matrix can be start point for other n squares.
In total it brings O(n^2) time complexity just for checkValidZeroSquare.
The idea in Version 3 was to build hash table of special intervals,
which will optimize line verification -> reduca time complexity to constant.
When we want to validate line in the matrix from point start_n -> end_n,
we look its values in the table and check, if we had "1" on the interval
start_n -> end_n.
intervalsOfZeros does converting like row#1 = [0, 0, 1, 1, 0, 0, 0, 1, 0] from the matrix line
into intervals_of_zeros[1_c] = [0, 0, -1, -1, 2, 2, 2, -1, 3], where intervals shown
as a positive integers for "0" and as a "-1" for "1". If positive integers are same,
it means that "0"s are from the same adjacent interval of just zeros.
All of this gives faster line validation.
'''
# Version 4. O(n^3) Time / O(n^2) Space
# Square check method with pre-computation
# of how many "0" to the right and to the bottom
def squareOfZeroes(matrix):
if len(matrix) <= 1:
return False
# O(n^2) Time / O(n^2) Space
matrix_of_zeros = zerosInLine(matrix)
for n in range(len(matrix)):
for m in range(len(matrix[0])):
if matrix[n][m] == 1:
continue
isZeroSquare = checkValidZeroSquare(matrix, n, m, matrix_of_zeros)
if isZeroSquare:
return True
return False
# Define how many "0" we have from its right and its down
# at each idx of matrix by using dynamic programming
# technic from the end.
# O(n^2) T / S
def zerosInLine(matrix):
matrix_of_zeros = [[[0, 0] for n in matrix] for n in matrix] # where [0, 0] -> [down, right]
for row in reversed(range(len(matrix))):
for col in reversed(range(len(matrix[0]))):
if matrix[row][col] == 1:
continue
if row == len(matrix)-1:
down = 0
else:
down = matrix_of_zeros[row+1][col][0]
if col == len(matrix[0])-1:
right = 0
else:
right = matrix_of_zeros[row][col + 1][1]
matrix_of_zeros[row][col] = [down + 1, right + 1]
return matrix_of_zeros
def checkValidZeroSquare(matrix, start_n, start_m, matrix_of_zeros):
n = start_n + 1
m = start_m + 1
while n < len(matrix) and m < len(matrix[0]):
if checkLine(start_n, start_m, start_n, m, "hor", matrix_of_zeros) \
and checkLine(start_n, start_m, n, start_m, "ver", matrix_of_zeros) \
and checkLine(n, start_m, n, m, "hor", matrix_of_zeros) \
and checkLine(start_n, m, n, m, "ver", matrix_of_zeros):
return True
n += 1
m += 1
return False
def checkLine(start_n, start_m, n, m, direction, matrix_of_zeros):
if direction == "hor":
if (m - start_m + 1) <= matrix_of_zeros[start_n][start_m][1]:
return True
else:
if (n - start_n + 1) <= matrix_of_zeros[start_n][start_m][0]:
return True
return False
'''
# Version 3. O(n^3) Time / O(n^2) Space
# Square check method with pre-computation
def squareOfZeroes(matrix):
if len(matrix) <= 1:
return False
# O(n^2) Time / O(n^2) Space
intervals_of_zeros = intervalsOfZeros(matrix)
for n in range(len(matrix)):
for m in range(len(matrix[0])):
if matrix[n][m] == 1:
continue
isZeroSquare = checkValidZeroSquare(matrix, n, m, intervals_of_zeros)
if isZeroSquare:
return True
return False
def checkValidZeroSquare(matrix, start_n, start_m, intervals_of_zeros):
n = start_n + 1
m = start_m + 1
while n < len(matrix) and m < len(matrix[0]):
if checkLine(start_n, start_m, n, m, "hor", intervals_of_zeros) \
and checkLine(n, start_m, n, m, "hor", intervals_of_zeros) \
and checkLine(start_n, start_m, n, m, "ver", intervals_of_zeros) \
and checkLine(start_n, m, n, m, "ver", intervals_of_zeros):
return True
n += 1
m += 1
return False
def checkLine(start_n, start_m, n, m, direction, intervals_of_zeros):
if direction == "hor":
return checkIntoIntervalOfZeros(str(start_n), "c", start_m, m, intervals_of_zeros)
else:
return checkIntoIntervalOfZeros("r", str(start_m), start_n, n, intervals_of_zeros)
# Constant time check if interval form start_idx to end_idx has "1"
def checkIntoIntervalOfZeros(str_row, str_col, start_idx, end_idx, intervals_of_zeros):
key = createKeyFromMatrixIdx(str_row, str_col)
interval_of_zeros = intervals_of_zeros[key]
if interval_of_zeros[start_idx] != -1 and interval_of_zeros[end_idx] != -1:
if interval_of_zeros[start_idx] == interval_of_zeros[end_idx]:
return True
return False
def intervalsOfZeros(matrix):
intervals = {}
# rows hashing
for row in range(len(matrix)):
createRelevantIntervals(intervals, matrix, row, -1)
# cols hashing
for col in range(len(matrix)):
createRelevantIntervals(intervals, matrix, -1, col)
return intervals
def createRelevantIntervals(intervals, matrix, row, col):
if row == -1:
key = createKeyFromMatrixIdx("r", str(col))
intervals[key] = [-1] * len(matrix)
flag = 0
for row in range(len(matrix)):
if matrix[row][col] == 0:
intervals[key][row] = flag
else:
flag += 1
else:
key = createKeyFromMatrixIdx(str(row), "c")
intervals[key] = [-1] * len(matrix)
flag = 0
for col in range(len(matrix)):
if matrix[row][col] == 0:
intervals[key][col] = flag
else:
flag += 1
def createKeyFromMatrixIdx(str_row, str_col):
return str_row + "_" + str_col
'''
'''
# Version 2. O(n^4) Time / O(1) Space
# Square check method: traversing through each line
# through each element and check if this line is valid
def squareOfZeroes(matrix):
if len(matrix) <= 1:
return False
# Step 1: traverse through:
for n in range(len(matrix)):
for m in range(len(matrix[0])):
if matrix[n][m] == 1:
continue
# Step 2: check if matrix[n][m] can be start of
# zero square
isZeroSquare = checkValidZeroSquare(matrix, n, m)
if isZeroSquare:
return True
return False
def checkValidZeroSquare(matrix, start_n, start_m):
n = start_n + 1
m = start_m + 1
while n < len(matrix) and m < len(matrix[0]):
if checkLine(matrix, start_n, start_m, n, m, "hor") \
and checkLine(matrix, n, start_m, n, m, "hor") \
and checkLine(matrix, start_n, start_m, n, m, "ver") \
and checkLine(matrix, start_n, m, n, m, "ver"):
return True
n += 1
m += 1
return False
def checkLine(matrix, start_n, start_m, n, m, direction):
if direction == "hor":
for c in range(start_m, m + 1):
# Save in cache st_x -> x !!!
if matrix[start_n][c] == 1:
return False
return True
else:
for r in range(start_n, n + 1):
if matrix[r][start_m] == 1:
return False
return True
'''
'''
# Version 1. O(n^6) Time / O(n^2) Space
# Recursively check if we can have valid zero square
# from each point in the matrix
def squareOfZeroes(matrix):
if len(matrix) <= 1:
return False
visited = [[False for n in matrix] for n in matrix]
# Step 1: traverse through:
for n in range(len(matrix)):
for m in range(len(matrix[0])):
if matrix[n][m] == 1:
continue
# Step 2: assuming that matrix[n][m] is start of
# valid zero square, explore it
isZeroSquare = exploreFromPoint(matrix, n, m, visited, "right")
if isZeroSquare:
return True
return False
def exploreFromPoint(matrix, n, m, visited, direction):
st_n = n
st_m = m
isValidZeroSquare = False
if direction == "right":
if m == len(matrix):
return False
visited[n][m] = True
m += 1
while m < len(matrix) and matrix[n][m] == 0:
isValidZeroSquare = exploreFromPoint(matrix, n, m, visited, "down")
visited[n][m] = False
m += 1
if isValidZeroSquare:
break
visited[st_n][st_m] = False
return isValidZeroSquare
elif direction == "down":
if n == len(matrix):
return False
visited[n][m] = True
n += 1
while n < len(matrix) and matrix[n][m] == 0:
isValidZeroSquare = exploreFromPoint(matrix, n, m, visited, "left")
visited[n][m] = False
n += 1
if isValidZeroSquare:
break
visited[st_n][st_m] = False
return isValidZeroSquare
elif direction == "left":
if m < 0:
return False
visited[n][m] = True
m -= 1
while m >= 0 and matrix[n][m] == 0:
isValidZeroSquare = exploreFromPoint(matrix, n, m, visited, "up")
visited[n][m] = False
m -= 1
if isValidZeroSquare:
break
visited[st_n][st_m] = False
return isValidZeroSquare
else:
if n < 0:
return False
visited[n][m] = True
n -= 1
while n >= 0 and matrix[n][m] == 0:
if visited[n][m]:
return True
n -= 1
return False
'''
|
6f8236f21701d26a8b7195d2c32fa0f32536a638 | soham2109/python-programming-basics | /InsertionSort.py | 180 | 3.625 | 4 | def InsertionSort(seq):
for sliceEnd in range(len(seq)):
pos = sliceEnd
while pos>0 and seq[pos]<seq[pos-1]:
(seq[pos-1],seq[pos])=(seq[pos],seq[pos-1])
pos = pos-1 |
ee2a1b3aef2b2eb228dba3e21f4cfb7794a51161 | XPerezX/Atv_teste1 | /Manuel e Fernando Calza Correรงรฃo de Erros.py | 10,784 | 4.1875 | 4 | class funcionario():
__instance = None
def __init__(self, nome, salario, cargo, mestrab):
self.nome = nome
self.salario = salario
self.cargo = cargo
self.mestrab = mestrab
def print_nome(self):
print(self.nome)
def print_cargo(self):
print(self.cargo)
def print_salario(self):
print(self.salario)
def calc_13D(self):
return self.salario * self.mestrab / 12
def print_tudo(self):
print("\n")
print("Nome:", self.nome, "- Salario:", self.salario, "- Cargo:", self.cargo, "- Decimo 13ยบ:", self.calc_13D())
inputnome = False
inputsalario = False
inputcargo = False
inputmestrab = False
'''
salario = input("digite seu salario: ")
try:
salario = float(salario)
except ValueError:
print ("isso nรฃo รฉ um numero")
print (type(salario))
'''
while inputnome == False:
nome = input("digite seu nome: ")
if all(str.isalpha(string) for string in nome.split()) and bool(nome.strip()) == True :
_nome = nome
inputnome = True
else:
print("O nome deve ser composto somente de caracteres")
while inputsalario == False:
salario = input("digite seu salario: ")
try:
salario = float(salario)
except ValueError:
print ("isso nรฃo รฉ um numero")
if (isinstance(salario, float) is True) and salario > 0:
_salario = salario
inputsalario = True
else:
print("O salario deve ser um numero inteiro ou decimal maior que zero")
while inputcargo == False:
cargo = input("digite seu cargo: ")
if all(str.isalpha(string) for string in cargo.split()) and bool(cargo.strip()) == True :
_cargo = cargo
inputcargo = True
else:
print("O nome deve ser composto somente de caracteres")
while inputmestrab == False:
mesTrab = input("digite quantos meses de trabalho voce tem: ")
try:
mesTrab = int(mesTrab)
except ValueError:
print ("isso nรฃo รฉ um numero inteiro")
if isinstance(mesTrab, int) == True and mesTrab > 0:
_mestrab = mesTrab
inputmestrab = True
else:
print("Os meses de trabalho devem ser inteiros e maiores que zero")
gerente = funcionario(_nome, _salario, _cargo, _mestrab)
gerente.print_tudo()
'''
Erro 1 ----CORRIGIDO---- saida = "O nome deve ser composto somente de caracteres"
Erro 1 - Recebe nome como numero
(digite seu nome: 5
digite seu salario: 2000
digite seu cargo: Uber
digite quantos meses de trabalho voce tem: 12
Nome: 5 - Salario: 2000 - Cargo: Uber - Decimo 13ยบ: 2000.0
Process finished with exit code 0)
Erro 2 ----CORRIGIDO---- saida = "O nome deve ser composto somente de caracteres"
Erro 2 - Nome recebe caractere especial
(digite seu nome: ***
digite seu salario: 3000
digite seu cargo: Camioneiro
digite quantos meses de trabalho voce tem: 12
Nome: *** - Salario: 3000 - Cargo: Camioneiro - Decimo 13ยบ: 3000.0
Process finished with exit code 0)
Erro 3 ----CORRIGIDO---- saida = "O nome deve ser composto somente de caracteres"
Erro 3 - Nome recebe espaรงo em branco
(digite seu nome:
digite seu salario: 3000
digite seu cargo: japoegj
digite quantos meses de trabalho voce tem: 12
Nome: - Salario: 3000 - Cargo: japoegj - Decimo 13ยบ: 3000.0
Process finished with exit code 0)
Erro 4 - ----CORRIGIDO---- saida = "isso nรฃo รฉ um numero"
Erro 4 - Nรฃo exibe mensagem de " Por favor digite um numero " no teste do salario quando inserido caracter, da erro de console.
(digite seu nome: Ratinho
digite seu salario: Leptospirose
Traceback (most recent call last):
File "C:/Users/Desenvolvimento/PycharmProjects/Testes11/11/19/testando.py", line 29, in <module>
salario = int(input("digite seu salario: "))
ValueError: invalid literal for int() with base 10: 'Leptospirose'
Process finished with exit code 1)
Erro 5 ----CORRIGIDO---- saida = "isso nรฃo รฉ um numero"
Erro 5 - Nรฃo exibe mensagem de " Por favor digite um numero " no teste do salario quando inserido caracter especial, da erro de console.
(digite seu nome: FERNANDO
digite seu salario: #$&(*!&#
Traceback (most recent call last):
File "C:/Users/Desenvolvimento/PycharmProjects/Testes11/11/19/testando.py", line 29, in <module>
salario = int(input("digite seu salario: "))
ValueError: invalid literal for int() with base 10: '#$&(*!&#'
Process finished with exit code 1)
Erro 6 ----CORRIGIDO---- saida = "O salario deve ser um numero inteiro ou decimal maior que zero"
Erro 6 - Nรฃo exibe mensagem de " Por favor digite um numero " no teste do salario quando deixado em branco, da erro de console
(digite seu nome: aids
digite seu salario:
Traceback (most recent call last):
File "C:/Users/Desenvolvimento/PycharmProjects/Testes11/11/19/testando.py", line 29, in <module>
salario = int(input("digite seu salario: "))
ValueError: invalid literal for int() with base 10: ''
Process finished with exit code 1)
Erro 7 ----CORRIGIDO---- saida = O salario deve ser um numero inteiro ou decimal maior que zero
Erro 7 - Recebe salรกrio como negativo
(digite seu nome: kkkjj
digite seu salario: -39218
digite seu cargo: kpop
digite quantos meses de trabalho voce tem: 12
Nome: kkkjj - Salario: -39218 - Cargo: kpop - Decimo 13ยบ: -39218.0
Process finished with exit code 0)
Erro 8 ----CORRIGIDO---- saida = O salario deve ser um numero inteiro ou decimal maior que zero ou "Os meses de trabalho devem ser inteiros e maiores que zero"
Erro 8 - Calculo de decimo terceiro aceita negativo
(digite seu nome: Mijo na gaveta
digite seu salario: 3232
digite seu cargo: punheteiro
digite quantos meses de trabalho voce tem: -12
Nome: Mijo na gaveta - Salario: 3232 - Cargo: punheteiro - Decimo 13ยบ: -3232.0
Process finished with exit code 0)
Erro 9 ----CORRIGIDO---- saida = Os meses de trabalho devem ser inteiros e maiores que zero
Erro 9 - Nรฃo exibe mensagem de " Por favor digite os meses " no teste do decimo terceiro quando deixado em branco, da erro de console
(digite seu nome: Le park
digite seu salario: 12309
digite seu cargo: jef
digite quantos meses de trabalho voce tem:
Traceback (most recent call last):
File "C:/Users/Desenvolvimento/PycharmProjects/Testes11/11/19/testando.py", line 34, in <module>
mesTrab = int(input("digite quantos meses de trabalho voce tem: "))
ValueError: invalid literal for int() with base 10: ''
Process finished with exit code 1)
Erro 10 ----CORRIGIDO---- saida = isso nรฃo รฉ um numero inteiro
Erro 10 - Nรฃo exibe mensagem de " Por favor digite os meses " no teste do decimo terceiro quando inserido caracter especial, da erro de console
(digite seu nome: paep
digite seu salario: 12093
digite seu cargo: asi
digite quantos meses de trabalho voce tem: *(&$*
Traceback (most recent call last):
File "C:/Users/Desenvolvimento/PycharmProjects/Testes11/11/19/testando.py", line 34, in <module>
mesTrab = int(input("digite quantos meses de trabalho voce tem: "))
ValueError: invalid literal for int() with base 10: '*(&$*'
Process finished with exit code 1)
Erro 11 ----CORRIGIDO---- saida = Os meses de trabalho devem ser inteiros e maiores que zero
Erro 11 - Nรฃo exibe mensagem de " Por favor digite os meses corretamente" no teste do decimo terceiro quando inserido meses negativos, da erro de console
(digite seu nome: barril
digite seu salario: 091824
digite seu cargo: corno
digite quantos meses de trabalho voce tem: -12
Nome: barril - Salario: 91824 - Cargo: corno - Decimo 13ยบ: -91824.0
Process finished with exit code 0)
Erro 12 ----CORRIGIDO---- saida = O nome deve ser composto somente de caracteres
Erro 12 - Recebe cargo como numero
(digite seu nome: culote
digite seu salario: 92039
digite seu cargo: 3827198
digite quantos meses de trabalho voce tem: 12
Nome: culote - Salario: 92039 - Cargo: 3827198 - Decimo 13ยบ: 92039.0
Process finished with exit code 0)
Erro 13 ----CORRIGIDO---- saida = O nome deve ser composto somente de caracteres
Erro 13 - Recebe cargo como nulo (em branco)
(digite seu nome: antonio
digite seu salario: 21838
digite seu cargo:
digite quantos meses de trabalho voce tem: 12
Nome: antonio - Salario: 21838 - Cargo: - Decimo 13ยบ: 21838.0
Process finished with exit code 0)
Erro 14 ----CORRIGIDO---- saida = O nome deve ser composto somente de caracteres
Erro 14 - Recebe cargo como caracter especial
(digite seu nome: falta 4
digite seu salario: 1238
digite seu cargo: &&&&
digite quantos meses de trabalho voce tem: 12
Nome: falta 4 - Salario: 1238 - Cargo: &&&& - Decimo 13ยบ: 1238.0
Process finished with exit code 0)
----Nรฃo Pertinente------
Erro 15 - Decimo terceiro nรฃo emite alert quando menor que 12 (nรฃo pertinente)
(digite seu nome: foepiuh
digite seu salario: 29183
digite seu cargo: jpaegjd
digite quantos meses de trabalho voce tem: 3
Nome: foepiuh - Salario: 29183 - Cargo: jpaegjd - Decimo 13ยบ: 7295.75
Process finished with exit code 0)
Erro 16 ----CORRIGIDO---- saida = Os meses de trabalho devem ser inteiros e maiores que zero
Erro 16 - Decimo terceiro nรฃo emite alert quando negativo
(digite seu nome: jeopaij
digite seu salario: 9348
digite seu cargo: aeidgj
digite quantos meses de trabalho voce tem: -12
Nome: jeopaij - Salario: 9348 - Cargo: aeidgj - Decimo 13ยบ: -9348.0
Process finished with exit code 0)
Erro 17 ----CORRIGIDO---- saida = isso nรฃo รฉ um numero O salario deve ser um numero inteiro ou decimal maior que zero
Erro 17 - Salario da erro de console quando nulo
(digite seu nome: feaf
digite seu salario:
Traceback (most recent call last):
File "C:/Users/Desenvolvimento/PycharmProjects/Testes11/11/19/testando.py", line 29, in <module>
salario = int(input("digite seu salario: "))
ValueError: invalid literal for int() with base 10: ''
Process finished with exit code 1)
''' |
1b0a61a773ccca07e8b7bf9311f8d908255dd947 | caiquemarinho/python-course | /exploring_ranges.py | 552 | 4.5625 | 5 | """
Ranges
- We need to know loops to use the range.
- We need to understand range to better work with for loops.
Ranges are used to generate numeric sequences, not in a random way, but in a specific way.
range(stop_value)
PS: The stop value is not included, default starting at 0, and incrementing 1.
"""
# First Example
for num in range(11):
print(num)
# Second Example
for num in range(1, 11):
print(num)
# Third Example
for num in range(1, 11, 2):
print(num)
# Fourth Example
for num in range(10, 0, -1):
print(num)
|
7675a14662a3288f3cb59bf103c392757e53b4ec | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_2/310.py | 4,770 | 3.734375 | 4 | #!/usr/bin/env python
# using datetime module to make the arithmetic of arrival/departure times
# and turnaround times easy.
import datetime
class CTrain:
def __init__(self, tm):
self.time = tm # Time of arrival or departure
self.scheduled = False # if the train has already been scheduled for departure
def reset(self):
self.scheduled = False
class CEntry2:
def __init__(self, dep, arr):
self.arr = arr
self.dep = dep
def __str__(self):
return 'dep: %s : arr: %s' % (str(self.dep), str(self.arr))
def GetDateTime( train_time ):
''' The input is time in format '10:30', '12:02' etc.
The function returns a date time object with the time
passed in the format indicated above'''
train_time = train_time.strip()
times = [x.strip() for x in train_time.split(':')]
#print times
if times[0][0] == '0':
times[0] = times[0][1:]
if times[1][0] == '0':
times[1] = times[1][1:]
#print times
times = [eval(x) for x in times ]
# Here the date does not matter. But the date time module
# requires the date, month and year to be passed. So, passing
# today's date.
return datetime.datetime( 2008, 7, 17, hour = times[0], minute = times[1] )
def process_one_input( input):
l = input.split( '\n' )
# First line gives the round trip time (T)
T = datetime.timedelta( minutes = eval(l[0]) )
num_trips = [ eval(x) for x in l[1].strip().split() ]
# The first element of line 2 gives the num trips from A to B
# and the second element gives the num trips from B to A
num_trips_a = num_trips[ 0 ]
num_trips_b = num_trips[ 1 ]
A_Dep = []
A_Arr = []
B_Dep = []
B_Arr = []
k = []
for i in range( 2, 2 + num_trips_a):
k.append( CEntry2( GetDateTime(l[i].split()[0].strip()),
GetDateTime(l[i].split()[1].strip()) ))
def cmp(x,y):
if x.dep < y.dep: return -1
if x.dep > y.dep: return 1
return 0
k.sort( cmp )
for j in k:
#print j
A_Dep.append( CTrain( j.dep ) )
B_Arr.append( CTrain( j.arr ) )
k = []
for i in range( 2 + num_trips_a, 2 + num_trips_a + num_trips_b ):
k.append( CEntry2( GetDateTime(l[i].split()[0].strip()),
GetDateTime(l[i].split()[1].strip()) ))
k.sort( cmp )
for j in k:
#print j
B_Dep.append( CTrain( j.dep ) )
A_Arr.append( CTrain( j.arr ) )
return A_Dep, B_Arr, B_Dep, A_Arr, T
def train_count(dep, arr, T):
train_count = 0 #len(dep)
[ x.reset() for x in dep ]
[ x.reset() for x in arr ]
for i in dep:
# we can schedule a train for departure if the arrival time
# + the turnaround time < departure time
#
# However, if a train has been scheduled already for departure
# we shouldnt count it again for the next departure (since the
# train would have left already)
may_schedule = [ x for x in arr if (x.time + T) <= i.time ]
#print may_schedule, arr, i
reschedule = False
for j in may_schedule:
if j.scheduled == False:
#train_count -= 1
j.scheduled = True
reschedule = True
break # from inner 'j' loop
if reschedule == False:
train_count += 1
return train_count
def main():
l = open('B-large.in').readlines()
num_inputs = eval(l[0].strip())
lc = 0
for i in range(num_inputs):
lc += 1
input = l[lc]
lc += 1
input += l[lc]
num_lines = sum( [eval(x.strip()) for x in l[lc].split()])
for j in range(num_lines):
lc += 1
input += l[lc]
# 'input' now has one set of data i.e one test case
A_Dep, B_Arr, B_Dep, A_Arr, T = process_one_input( input )
'''
for i in range(len(A_Dep)):
print A_Dep[i].time, B_Arr[i].time
for i in range(len(B_Dep)):
print B_Dep[i].time, A_Arr[i].time'''
print 'Case #%d: %d %d' % ( i+1, train_count( A_Dep, A_Arr, T ), train_count( B_Dep, B_Arr, T ))
#print
if __name__ == '__main__':
main()
|
33b4579b9b90053037ff840cfb87d25c1dbbbd57 | optionalg/challenges-leetcode-interesting | /hamming-distance/test.py | 1,046 | 3.859375 | 4 | #!/usr/bin/env python
##-------------------------------------------------------------------
## @copyright 2017 brain.dennyzhang.com
## Licensed under MIT
## https://www.dennyzhang.com/wp-content/mit_license.txt
##
## File: test.py
## Author : Denny <http://brain.dennyzhang.com/contact>
## Tags:
## Description:
## https://leetcode.com/problems/hamming-distance/description/
## Basic Idea:
## Complexity:
## --
## Created : <2017-10-16>
## Updated: Time-stamp: <2017-11-12 10:59:21>
##-------------------------------------------------------------------
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
count = 0
while x != 0 or y != 0:
if (x % 2) != (y % 2):
count = count + 1
x = x >> 1
y = y >> 1
return count
if __name__ == '__main__':
s = Solution()
print s.hammingDistance(1, 4) # 2
print s.hammingDistance(2, 10) # 1
## File: test.py ends
|
e6baccd13c53bf8405c05d9a5791f67d793e83e4 | tanu312000/pyChapter | /org/netsetos/python/queue/levelorder.py | 1,952 | 3.9375 | 4 | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def enqueue(self, data):
if (self.rear == None):
self.rear = Node(data)
self.front = self.rear
else:
new_node = Node(data)
self.rear.next = new_node
self.rear = new_node
def dequeue(self):
if (self.front == None):
return
else:
temp = self.front
self.front = temp.next
if (self.front == None):
self.rear = None
return str(temp.data)
class TreeNode:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def levelordertraversal(self,root):
if (root != None):
q = Queue()
self.enqueue(root.data)
while (self.front != None and self.rear != None)):
temp = self.dequeue()
print(temp.data)
if (temp.left != None):
self.enqueue(temp.left.data)
if (temp.right != None):
self.enqueue(temp.right.data)
if __name__ == '__main__':
rear = Node(1)
nodeB = Node(2)
nodeC = Node(3)
nodeD = Node(4)
nodeE = Node(5)
nodeF = Node(6)
rear.next = nodeB
nodeB.next = nodeC
nodeC.next = nodeD
nodeD.next = nodeE
nodeE.next = nodeF
q = Queue()
q.enqueue('g')
q.enqueue('h')
q.dequeue()
q.dequeue()
q.enqueue('i')
q.enqueue('j')
q.enqueue('k')
q.dequeue()
print(data)
|
cad531621fbd56587fa5ea88023a84bcf74529e3 | nailanawshaba/workshopPythonTDD | /fizzbuzzwoof/fizzbuzz.py | 485 | 3.5625 | 4 | class FizzBuzz(object):
def __init__(self):
self.rules = {3: 'fizz',
5: 'buzz',
7: 'woof',
}
def generate(self, number):
output = ''
for key, value in self.rules.iteritems():
if number % key == 0:
output += value
if output:
return output
else:
return number
def set_rules(self, rules):
self.rules = rules
|
72ff7f80e2c2bca1eb7f6b1ea1e5f9268ab9c1da | rivcah/line_by_line | /strings.py | 2,093 | 4.6875 | 5 | ## This is a function that takes the user's input and counts how many lower or
##upper case letters, integer numbers and other type of characters there are
##in your input. It's a good way for working with conditional statements and
##for loops.
def string_counter(urinput):
count_lower = 0
count_upper = 0
count_numbers = 0
count_other = 0
for c in urinput: #It goes through each characters in your input and
#compares it to the conditional statements below.
if c.islower() == True: ##.islower() is a Python method
##that checks if a character is lower
##case. It turns True or False answers.
count_lower+=1 ##The counter we've set up there
##receives one more unit every time
##there is a match.
elif c.isupper() == True: ##Now, we check character by character
##looking for upper case letters.
count_upper+=1 ##Nah! You don't need a comment on
##this line. You already got it.
elif c.isdigit() == True: ##.isdigit() is a method that checks
##for a number. And now you ask what
##the difference is between
##.isdigit() and .isnumeric().
#The difference is the way those
##methods deal with UNICODE characters.
count_numbers+=1
else: ##if the character does not fit in any of the above categories,
##it will fall in this category.
count_other+=1
print("The number of lower case characters is: ", count_lower,
"\n The number of upper case characters is: ", count_upper,
"\n The number of numbers in your string is: ", count_numbers,
"\n All the other things you typed accoun for: ", count_other)
|
c15bee55369f7b58d4fe13b6f822880800176b9e | mustafasisik/mstfssk | /indexationOfWords.py | 748 | 3.90625 | 4 | from sys import argv
fileName = argv[1]
word = argv[2]
fileText = open(fileName, "r").read()
def indexation(text, word):
d = {}
sentenceList = text.split(".")
index = 0
for sentence in sentenceList:
wordBefore1 = ""
wordBefore2 = ""
for w in sentence.split():
if not wordBefore1 in d:
d[wordBefore1] = [(index-1, wordBefore2, wordBefore1, w)]
else:
d[wordBefore1].append((index-1, wordBefore2, wordBefore1, w))
index += 1
wordBefore2 = wordBefore1
wordBefore1 = w
return d[word]
assert indexation(fileText, word) == [(9, "that", "she", "sells"), (17, "if", "she", "sells")]
print indexation(fileText, word)
|
e7fab90055edab4ca5c5b46cce0630b5b2876fba | vineetmidha/Online-Challenges | /Displacement.py | 484 | 3.671875 | 4 | https://www.hackerrank.com/contests/all-india-contest-by-mission-helix-a-11th-july/challenges/easy-2-cc/problem
def get_answer(t, x):
return t * 60 * x // 2
tests = int(input())
for _ in range(tests):
t, x = map(int, input().split())
print(get_answer(t, x))
'''
Explanation:
Total time in seconds T = t x 60
If speed is uniform all time, then time spend going east, T/2
[Maximum displacement]
Displacement = X * T/2 = X * t * 30
'''
|
37aaa5cf410aef35cc02b8d6467207c907611a5d | sachinjangid/myAlgos | /myAlgos/search-a-number.py | 576 | 3.84375 | 4 | #User function Template for python3
def searchNumber(arr,n, number):
index = -1
for i in range(n):
if (arr[i] == number):
index =i
break
if (index > -1):
print(index+1)
else:
print(index)
if __name__ == '__main__':
t=int(input())
for _ in range(t):
params=[int(x) for x in input().strip().split()]
n = params[0]
number = params[1]
arr=[int(x) for x in input().strip().split()]
n = len(arr)
arr[311] = 367
arr[319] = 367
searchNumber(arr,n, number)
|
90f87930b39acd99ea8cf283cf97526e973bfbe4 | ian-garrett/CIS_211 | /211_projects/Week_7/fp.py | 888 | 3.53125 | 4 | """
fp.py: CIS 211 assignment 7, Spring 2014
author: Ian Garrett, igarrett@uoregon.edu
a collection of five functions that utilize functional programming
"""
#1
def codes(x):
return list(map(ord, x))
#2
def vowels(x):
vowels = ['a','e','i','o','u','A','E','I','O','U']
go_do = lambda t: t if t in vowels else ""
return "".join(list(map(go_do, list(x))))
#3
def tokens(x):
from string import punctuation
strip = lambda t: t.strip(punctuation)
return map(strip, x.split())
#4
def numbers(x):
return list(filter(str.isdigit,list(tokens(x))))
#5
def sq_ft(x):
class Room:
def __init__(self, Entry):
self.name,self.width,self.depth = Entry.split()
def area(self):
return float(int(self.width)*int(self.depth))
from operator import add
from functools import reduce
calc_room = lambda t: (Room(t)).area()
return reduce(add,list(map(calc_room, open(x))))
print (sq_ft("house.txt"))
|
68f9c11e2e3e5e5f664753cb26b22f275057411f | billgoo/LeetCode_Solution | /Related Topics/Hash Table/202. Happy Number.py | 471 | 3.53125 | 4 | class Solution:
def isHappy(self, n: int) -> bool:
def sum_happy(x):
ans = 0
while x > 0:
ans += (x % 10) ** 2
x //= 10
return ans
s = {n}
while n != 1:
n = sum_happy(n)
# if it is a infinite loop
if n in s:
return False
s.add(n)
return True
|
940c6b16b6fc87626052ad1200d53044e8172611 | GallantRage/Web-Scraping | /scraping_project.py | 2,069 | 3.546875 | 4 | # http://quotes.toscrape.com
import requests
from bs4 import BeautifulSoup
from random import choice
response = requests.get("http://quotes.toscrape.com")
soup = BeautifulSoup(response.text, "html.parser")
quotes = soup.find_all(class_="quote")
data = []
for quote in quotes:
q = quote.find(class_="text").get_text()
author = quote.find(class_="author").get_text()
link = quote.find("a")["href"]
# print(link)
data.append([q, author, link])
# print(data)
curr_quote = choice(data)
guesses = 4
print(f"Here's a quote: \n\n{curr_quote[0]}")
user = input(f"\nWho said this? Guesses remaining: {guesses}. ")
play = ""
while True:
if user == curr_quote[1]:
print("You guessed correctly! Congratulations!")
play = input("\nWould you like to play again (y/n)? ")
else:
res2 = requests.get(f"http://quotes.toscrape.com{curr_quote[2]}")
soup = BeautifulSoup(res2.text, "html.parser")
guesses -= 1
if guesses == 3:
hint = soup.select(".author-born-date")[0].get_text() + " " + soup.select(".author-born-location")[0].get_text()
print(f"Here's a hint: The author was born in {hint}")
user = input(f"\nWho said this? Guesses remaining: {guesses}. ")
elif guesses == 2:
hint = curr_quote[1][0]
print(f"Here's a hint: The author's first name starts with {hint}")
user = input(f"\nWho said this? Guesses remaining: {guesses}. ")
elif guesses == 1:
hint = curr_quote[1].split(" ")[1][0]
print(f"Here's a hint: The author's last name starts with {hint}")
user = input(f"\nWho said this? Guesses remaining: {guesses}. ")
else:
print(f"Sorry, you've run out of guesses. The answer was {curr_quote[1]}")
play = input("\nWould you like to play again (y/n)? ")
if play == "y":
play = ""
new_quote = choice(data)
while new_quote == curr_quote: new_quote = choice(data)
curr_quote = new_quote
guesses = 4
print("Great! Here we go again...\n")
print(f"Here's a quote: \n\n{curr_quote[0]}")
user = input(f"\nWho said this? Guesses remaining: {guesses}. ")
elif play == "n":
print("Ok! See you next time!")
break |
bcaf059665eb81d0e0992a01ec3f1cb51704a9a4 | LeytonYu/python_algorithm | /sword art online/ๅพ/ๆทฑๅบฆไผๅ
้ๅ.py | 375 | 3.515625 | 4 | def dfs(G,s,S=None,res=None):
if S is None:
S=set()
if res is None:
res=[]
S.add(s)
res.append(s)
for i in G[s]:
if i in S:
continue
S.add(i)
dfs(G,i,S,res)
return res
G = {'0': ['1', '2'],
'1': ['2', '3'],
'2': ['3', '5'],
'3': ['4'],
'4': [],
'5': []}
print(dfs(G, '0')) |
853c6f2b6b1f0022da9b19de44768c601de69e30 | jayhebe/w3resource_exercises | /List/ex35.py | 363 | 3.65625 | 4 | from itertools import product
def concatenate(lst1, n):
# return [x[0] + str(x[1]) for x in sorted(list(product(lst1, list(range(1, n + 1)))), key=lambda t: t[1])]
result = []
for i in range(1, n + 1):
for j in lst1:
result.append(j + str(i))
return result
if __name__ == '__main__':
print(concatenate(['p', 'q'], 5))
|
14c20cd25a2e81e0b5d24c5011f6a55649dd242c | ernestojfcosta/IPRP_LIVRO_2013_06 | /objectos_2/programas/listas_comp.py | 782 | 3.65625 | 4 | def aplana(lista):
"""Transforma uma lista de lista numa lista simples."""
res = []
for lst in lista:
for elem in lst:
res.append(elem)
return res
def aplana_lc(lista):
"""Transforma uma lista de lista numa lista simples."""
res = [val for elem in lista for val in elem]
return res
def elimina_dup(lista):
"""Elimina duplicados de uma lista sem respeitar a ordem."""
lista_ord = lista[:]
lista_ord.sort()
return [val for ind,val in enumerate(lista_ord) if not ind or val!= lista_ord[ind - 1]]
if __name__ == '__main__':
minha_lista = [[1,2,3],[4,5],[6]]
print(aplana(minha_lista))
#print(aplana_lc(minha_lista))
#lista_2 = [1,7,5,2,9,1,5,7,9,9,1]
#print(elimina_dup(lista_2))
|
09ca6115d0647c012fde3340627c425f2114b4e5 | itsolutionscorp/AutoStyle-Clustering | /all_data/exercism_data/python/bob/fd6add469f2c4cc8b82eaeb41fdf715a.py | 638 | 3.640625 | 4 | class Bob:
def hey(self, msg):
"""Bob's response to a given message."""
response = "Whatever."
if shouting(msg):
response = "Woah, chill out!"
elif question(msg):
response = "Sure."
elif saying_nothing(msg):
response = "Fine. Be that way!"
return response
def shouting(msg):
"A string with no lower-case characters and some upper-case characters"
return msg.isupper()
def question(msg):
"Question mark at the end of a string"
return msg.endswith("?")
def saying_nothing(msg):
"Only whitespace"
return msg.strip() == ""
|
e90b53584351024364517b5cbf9cfd678f80f021 | RamachandiranVijayalakshmi/Condition-Check | /condition.py | 281 | 3.8125 | 4 | def cond(a,b,c):
if a>b and a>c:
print('a greater number')
elif b>a and b>c:
print('b greater number')
elif c>a and c>a:
print('c greater number')
else:
print('ture condion not in the code')
d,e,f=45,23,22
cond(d,e,f)
|
f53b4c73523367b38a41336c69721ff86e131a0b | shovalsolo/PythonWebDriver | /PythonWebDriver/MicrosoftBasic/022_create_json_with_nested_dictionary.py | 1,622 | 4 | 4 | # This is an example of how to convert a dictionary to a json format
import requests
import json
import pprint
person_dictionary = {'first':'Chris' , 'last':'Zo'} #creating a dictionary
person_dictionary ['city'] = 'Orlando' #adding a new key and value to the dictionary
staff_dictionary = {} #creating an empty dictionary
staff_dictionary ['Program manager'] = person_dictionary #assigning the person_dictionary to the staff_dictionary
person_json = json.dumps(person_dictionary) #converting dictionary to json
stuff_json = json.dumps(staff_dictionary) #converting dictionary to json
print()
print('----printing the json object----')
print(person_json) #printing the json object person_dictionary
print()
print('----printing the json object with the staff_dictionary----')
print(stuff_json) #printing the json object staff_dictionary
languahes_list = ['CSharp' , 'Python' , 'Java'] #creating a list
person_dictionary ['languages'] = languahes_list #Adding the list to the dictionary
person_json = json.dumps(person_dictionary) #converting dictionary to json
print()
print('----printing the json object with the language list----')
print(person_json) #printing the json object person_dictionary
|
c008b4fa487eb11c74e9cf114dea2404a8c598f1 | The-Marauder/Tic-tac-tao | /Tictactoe.py | 2,938 | 3.671875 | 4 | from tkinter import *
import tkinter
import tkinter.messagebox as msg
root = Tk()
root.title("Tic Tac Toe")
Label(root , text="Player 1 : X", font='Comic 22').grid(row=0,column=1)
Label(root , text="Player 2 : O", font='Comic 22').grid(row=0,column=3)
digits =[1,2,3,4,5,6,7,8,9]
count = 0
panels = ["panel"]*10
sign = ''
mark = ''
digit = ''
digitcount = 0
def win(panels ,sign) :
return(
((panels[1] == panels[2] == panels [3] == sign)
or (panels[1] == panels[4] == panels [7] == sign)
or (panels[1] == panels[5] == panels [9] == sign)
or (panels[2] == panels[5] == panels [8] == sign)
or (panels[3] == panels[6] == panels [9] == sign)
or (panels[3] == panels[5] == panels [7] == sign)
or (panels[4] == panels[5] == panels [6] == sign)
or (panels[7] == panels[8] == panels [9] == sign)))
def checker(digit) :
global count,mark,digits,digitcount
digitcount = 0
while digitcount <= 9 :
if digit == digitcount and digit in digits :
digits.remove(digit)
if (count%2 == 0) :
mark = 'X'
panels[digit] = mark
else :
mark = 'O'
panels[digit] = mark
buttons[digitcount-1].config(text=mark)
count +=1
sign = mark
if(win(panels,sign) and sign == 'X') :
msg.showinfo("Result","Player1 wins!")
elif win(panels,sign) and sign == 'O' :
msg.showinfo("Result","Player2 wins!")
digitcount +=1
if(count > 8 and win(panels, 'X') == False and win(panels , 'O') == False) :
msg.showinfo('Result','Match Tied!')
root.destroy()
button1 = Button(root,width = 18,height = 10,font=('Times 18 bold'),command= lambda : checker(1))
button1.grid(row=1,column=1)
button2 = Button(root,width = 18,height = 10,font=('Times 18 bold'),command= lambda : checker(2))
button2.grid(row=1,column=2)
button3 = Button(root,width = 18,height = 10,font=('Times 18 bold'),command= lambda : checker(3))
button3.grid(row=1,column=3)
button4 = Button(root,width = 18,height = 10,font=('Times 18 bold'),command= lambda : checker(4))
button4.grid(row=2,column=1)
button5 = Button(root,width = 18,height = 10,font=('Times 18 bold'),command= lambda : checker(5))
button5.grid(row=2,column=2)
button6 = Button(root,width = 18,height = 10,font=('Times 18 bold'),command= lambda : checker(6))
button6.grid(row=2,column=3)
button7 = Button(root,width = 18,height = 10,font=('Times 18 bold'),command= lambda : checker(7))
button7.grid(row=3,column=1)
button8 = Button(root,width = 18,height = 10,font=('Times 18 bold'),command= lambda : checker(8))
button8.grid(row=3,column=2)
button9 = Button(root,width = 18,height = 10,font=('Times 18 bold'),command= lambda : checker(9))
button9.grid(row=3,column=3)
buttons = [button1,button2,button3,button4,button5,button6,button7,button8,button9]
root.mainloop() |
eb267484a2fc18fc34c8070fcb959bd351b42743 | hzhu3142/CardGame | /User_interface.py | 2,381 | 3.828125 | 4 | from blackJack import *
# setup the player's chips
player_chips = Chips()
while True:
# Print an opening statement
print('\nWelcome to Balck Jack! Get as close to 21 as you can without going over! \n',
'Dealer hits until she reaches 17. Aces count as 1 or 11.')
# Create & shuffle the deck, deal two cards to each player.
deck = Deck()
deck.shuffle()
player_hand = Hand()
player_hand.add_card(deck.deal())
player_hand.add_card(deck.deal())
dealer_hand = Hand()
dealer_hand.add_card(deck.deal())
dealer_hand.add_card(deck.deal())
# Prompt the player for their bet
take_bet(player_chips)
# Show cards (but keep one dealer card hidden)
show_some(player_hand, dealer_hand)
while playing: # recall this variable from our hit_or_stand function
# Prompt for Player to Hit or Stand
playing = hit_or_stand(deck, player_hand)
# Show cards (but keep one dealer card hidden)
if playing:
show_some(player_hand, dealer_hand)
# If player's hand exceeds 21, run player_busts() and break out of loop
if player_hand.value > 21:
player_busts(player_hand, dealer_hand, player_chips)
break
# If Player hasn't busted, play Dealer's hand until Dealer reaches 17
if player_hand.value <= 21:
while dealer_hand.value < 17:
hit(deck, dealer_hand)
# Show all cards
show_all(player_hand, dealer_hand)
# Run different winning scenarios
if dealer_hand.value > 21:
dealer_busts(player_hand, dealer_hand, player_chips)
elif dealer_hand.value > player_hand.value:
dealer_wins(player_hand, dealer_hand, player_chips)
elif dealer_hand.value < player_hand.value:
player_wins(player_hand, dealer_hand, player_chips)
else:
push(player_hand, dealer_hand)
# Inform Player of their chips total
print("\nPlayer's winnings stand at", player_chips.total)
# Ask to play again
while True:
new_game = input("Would you like to play another hand? Enter 'y' or 'n' ")
if new_game in {'y','n', 'Yes', 'No', 'yes','no'}:
break
if new_game[0].lower() == 'y':
playing = True
continue
else:
print("Thanks for playing!")
break
|
ad32af83277d64c6a29673054d3bc73c953989f2 | habiba2012/python-tutorial | /pythontut5.py | 6,190 | 3.96875 | 4 | # functions
"""
def add_numbers(num1, num2):
return num1 + num2
print("5 + 4 = ", add_numbers(5,4))
def assign_name():
name = "Doug"
print("Name is : ", assign_name())
def change_name():
#name = "Mark"
#return "Mark"
global gbl_name
gbl_name = "Sammy"
#name = "Tom"
#name = change_name(name)
change_name()
#print("Name is : ", name)
print("Name is : ", gbl_name)
def get_sum(num1, num2):
sum = num1 + num2
print(get_sum(5, 4))
"""
# solve for x
# x + 4 = 9
# x will always be the 1st value received and you only will deal with addition
""" - my solution
def solve_for_x(equation):
num1 = 0
num2 = 0
# parse equation to get values
for char in equation:
if char.isdigit():
if num1 == 0:
num1 = int(char)
elif num2 == 0:
num2 = int(char)
# return solution
return num2 - num1
# prompt user for equation
equation = input("Please enter an equation : ")
# print result
print(equation)
print("x = ", solve_for_x(equation))
"""
"""
# solve for x
# x + 4 = 9
# x will always be the 1st value received and you only will deal with addition
# receive the string and split the string into variables
def solve_equation(equation):
x, add, num1, equals, num2 = equation.split()
# convert the strings in ints (the numbers)
num1, num2 = int(num1), int(num2)
# convert the result into a string and join it to the string "X = "
return "X = " + str(num2 - num1)
# print()
print(solve_equation("x + 4 = 9"))
"""
"""
def mult_divide(num1, num2):
return (num1 * num2), (num1 / num2)
mult, divide = mult_divide(4, 5)
print("4 * 5 ", mult)
print("4 / 5 ", divide)
"""
# list of primes
# a prime can only be divided by 1 and itself
# 5 is a prime 1 and 5 = positive factor
# 6 is not prime 1, 2, 3, 6
"""
def primes(limit):
prime_list = []
if (limit <= 1):
return prime_list
else:
for i in range(2, limit+1):
for j in range(i-1, 1, -1):
# print("i = " , i," j = ", j, " mod = ", (i%j))
if ((i % j) == 0):
# print("divisible")
break
if (j == 2):
prime_list.append(i)
return prime_list
# prompt user for maximum value
while True:
try:
limit = int(input("Please enter the highest value for primes desired : "))
break
except ValueError:
print("Value was not a whole number.")
except:
print("Unknown Error")
# return list of primes
print(primes(limit))
def is_prime(num):
for i in range(2, num):
if (num % i) == 0:
return False
return True
def get_primes(max_number):
prime_list = []
for num1 in range(2, max_number):
if is_prime(num1):
prime_list.append(num1)
return prime_list
# prompt user for maximum value
while True:
try:
limit = int(input("Please enter the highest value for primes desired : "))
break
except ValueError:
print("Value was not a whole number.")
except:
print("Unknown Error")
list_of_primes = get_primes(limit)
for prime in list_of_primes:
print(prime)
"""
"""
def sum_all(*args):
sum = 0
for i in args:
sum += i
return sum
print("Sum = ", sum_all(1,2,3,4,5,3,2,2))
"""
# create program that allows the user to calculate the area for different shapes
import math
def calc_circle_area(radius):
return math.pi * math.pow(radius, 2)
def get_circle_area():
while True:
try:
radius = float(input("Please enter the radius of the circle : "))
break
except ValueError:
print("Not a valid value.")
except:
print("Unknown error")
print("A circle with radius {} has an area of {:.2f}".format(radius, calc_circle_area(radius)))
def calc_rectangle_area(height, width):
return height * width
def get_rectangle_area():
while True:
try:
height = float(input("Please enter the height of the rectangle : "))
width = float(input("Please enter the width of the rectangle : "))
break
except ValueError:
print("Not valid values.")
except:
print("Unknown error")
print("A rectangle with height {} and width {} has an ara of {:.2f}".format(height, width, calc_rectangle_area(height, width)))
def calc_parallelogram_area(height, base):
return height * base
def get_parallelogram_area():
while True:
try:
height = float(input("Please enter the height of the parallelogram : "))
base = float(input("Please enter the base of the parallelogram : "))
break
except ValueError:
print("Not valid values.")
except:
print("Unknown error")
print("A parallelogram with height {} and width {} has an ara of {:.2f}".format(height, base, calc_parallelogram_area(height, base)))
def calc_rhombus_area(height, base):
return height * base
def get_rhombus_area():
while True:
try:
height = float(input("Please enter the height of the parallelogram : "))
base = float(input("Please enter the base of the parallelogram : "))
break
except ValueError:
print("Not valid values.")
except:
print("Unknown error")
print("A parallelogram with height {} and width {} has an ara of {:.2f}".format(height, base, calc_rhombus_area(height, base)))
def get_area(shape):
shape = shape.lower()
if shape == "circle":
get_circle_area()
elif shape == "rectangle":
get_rectangle_area()
elif shape == "parallelogram":
get_parallelogram_area()
elif shape == "rhombus":
get_rhombus_area()
elif shape == "triangle":
get_triangle_area()
elif shape == "trapezoid":
get_trapezoid_area()
else:
print("Unsupported shape type")
def main():
shape_type = input("Get area for what shape (circle/rectangle/parallelogram/rhombus/triangle/trapezoid) : ")
get_area(shape_type)
main() |
4d08b51035721202cdd0d7fb362d8ea644ca4a66 | almas06/SecondYear-ComputerEngineering-LabAssignments-SPPU | /DSA Programs/GroupA_Assignment-4.py | 5,249 | 4.03125 | 4 | #Creating 2 sets using inbuilt set method
myset1 = set()
myset2 = set()
#*****************************************************************************************************************8
def AddElement():
set_no = int(input("\nEnter set no. in which you want to insert(1/2): "))
num = int(input("\nEnter number of elements you want to insert : "))
if set_no==1:
for i in range(num):
element=int(input("Enter element :=> "))
myset1.add(element)
elif set_no == 2:
for i in range(num):
element=int(input("Enter element :=> "))
myset2.add(element)
#*********************************************************************************************************************
def IfPresent(element): #To check if element is present or not in one of the set
if element in myset1 :
return(2)
elif element in myset2 :
return(1)
else:
return(0)
#**********************************************************************************************************************
def RemoveElement():
element=int(input("Enter element to remove :=> "))
p = IfPresent(element)
if p==2:
myset1.remove(element)
print("\nElement removed successfully from Set-1!!\n")
elif p==1:
myset2.remove(element)
print("\nElement removed successfully from Set-2!!\n")
else:
print("\nElement not present\n")
#*************************************************************************************************************************
def SizeOfSet():
print("\t1.Set-1")
print("\t2.Set-2")
c = int(input("Enter choice : "))
if c==1:
s = len(myset1)
print("\nSize of Set-1 is ",s,"\n")
elif c==2:
s = len(myset2)
print("\nSize of Set-2 is ",s,"\n")
#**********************************************************************************************************************
def Union():
union_set = myset1.union(myset2)
print("-----------------------------")
print("Union of Set1 and Set2")
print(union_set)
print("-----------------------------")
#*********************************************************************************************************************8
def Intersection():
intersect_set = myset1.intersection(myset2)
print("-------------------------------")
print("Intersection of Set1 and Set2")
print(intersect_set)
print("-------------------------------")
#******************************************************************************************************************
def Difference():
diff_set = myset1.difference(myset2)
print("-------------------------------")
print("Difference of Set1 and Set2")
print(diff_set)
print("-------------------------------")
#********************************************************************************************************************
def Subset():
sub1 = myset1.issubset(myset2)
if sub1==True:
print("\nSet1 is a subset of Set2")
else:
print("\nSet1 is not a subset of Set2")
sub2 = myset1.issubset(myset2)
if sub2==True:
print("\nSet2 is a subset of Set1")
else:
print("\nSet2 is not a subset of Set1")
#*********************************************************************************************************************
def Display():
itr1 = iter(myset1) # Creating Iterators itr1 and itr2 for
itr2 = iter(myset2) # set1 annd set2 respectively
print("\n------------------------")
print("Set-1")
for itr1 in myset1:
print("-> ",itr1)
print("\nSet-2")
for itr2 in myset2:
print("-> ",itr2)
print("------------------------")
#**********************************************************************************************************************
def main():
print("-------------------------")
print(" Group-A Assignment-4")
print("-------------------------")
while True :
print("\t1.Add element")
print("\t2.Display")
print("\t3.Remove element")
print("\t4.Size of set")
print("\t5.Is element present")
print("\t6.Intersection")
print("\t7.Union")
print("\t8.Difference")
print("\t9.Subset")
print("\t10.Exit")
print("-------------------------")
ch = int(input("Enter your choice : "))
if ch==1:
AddElement()
elif ch==2:
Display()
elif ch==3:
RemoveElement()
elif ch==4:
SizeOfSet()
elif ch==5:
ele = int(input("Enter the element you want to check : "))
ans = IfPresent(ele)
if ans==2:
print("\nElement is present in Set1")
elif ans==1:
print("\nElement is present in Set2")
else:
print("\nElement is not present in either set")
elif ch==6:
Intersection()
elif ch==7:
Union()
elif ch==8:
Difference()
elif ch==9:
Subset()
elif ch==10:
quit()
else:
print("Enter a valid input!!")
main()
|
623292f97ed4525b3c6cc8e870215710232ec681 | darwinini/practice | /python/loops.py | 436 | 4.0625 | 4 | """
for i in [0, 1, 2, 3, 4, 5]:
print(i)
#range(n) get me a range of n numbers
for i in range(6):
print(i)
number = 0;
while number > 8:
print(f"Thank you Lord for day {number}")
num = 0
while num < 8:
print(f"The number is: {num}")
num += 1
"""
name = "Darwin"
for char in name:
print(char)
#range(n) get me a range of n numbers
sum = 0
for i in range(6):
sum = sum + i
print(f"The sum is {sum}")
|
2211f35872fb8046468686404f3bf8bd4096d3d5 | Jyotiswaruptripathy/jyoti123 | /prob2.py | 192 | 4.09375 | 4 | n=int(input('enter the no. of integer u want to add:'))
sum=0
for k in range (0,n):
k=int(input('enter the no.: '))
sum=sum+k
print('the sum of digit is = ',sum)
|
87f908d8e18b56beb22dca7da315046e86c6d0b9 | jiyoung-dev/python-algorithm-interview | /ch7_list/L15_์ธ์์ํฉ.py | 1,900 | 3.546875 | 4 | '''
๋ฐฐ์ด์ ์
๋ ฅ๋ฐ์ ํฉ์ผ๋ก 0์ ๋ง๋ค ์ ์๋ 3๊ฐ์ ์๋ฆฌ๋จผํธ๋ฅผ ์ถ๋ ฅํ๋ผ.
nums = [-1, 0, 1, 2, -1, -4]
[
[-1, 0, 1].
[-1, -1, 2]
]
'''
# ํฌํฌ์ธํฐ๋ก ํ์ด
from typing import List
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
results = []
nums.sort() # ์
๋ ฅ๋ ๋ฐฐ์ด์ ์ ๋ ฌ (ํฌํฌ์ธํฐ ๋ฌธ์ ํ์ด๋ฅผ ์ํ)
for i in range(len(nums) - 2):
# ์ค๋ณต๋ ๊ฐ ๊ฑด๋๋ฐ๊ธฐ
if i > 0 and nums[i] == nums[i-1]:
continue
# ๋๊ฐ์ ํฌ์ธํฐ (left, right)๋ฅผ ๋๊ณ ๊ฐ๊ฒฉ์ ์ขํ๊ฐ๋ฉด์ sum ๊ตฌํ๊ธฐ
left, right = i + 1, len(nums) - 1
# ์ธ๋ฑ์ค 0๋ฒ์งธ๋ฅผ ๊ธฐ์ค i๋ก ๋๊ณ , i+1 ๋ฒ์งธ๋ฅผ left, ๋ง์ง๋ง ์ซ์๋ฅผ right๋ก ๋๋ค
# for๋ฌธ์ ๋๋ฉด์ ์ธ ์์ ํฉ์ด 0๋ณด๋ค ์๋ค๋ฉด left๋ฅผ ํ์นธ ์ฐ์ธก์ผ๋ก ์ด๋
# ์ธ ์์ ํฉ์ด 0๋ณด๋ค ํฌ๋ค๋ฉด right๋ฅผ ํ์นธ ์ข์ธก์ผ๋ก ์ด๋์ํจ๋ค
# ์ธ ์์ ํฉ์ด 0๊ณผ ๊ฐ์์ง๋ฉด ๊ฒฐ๊ณผ ๋ฆฌ์คํธ์ ์ถ๊ฐํ๋ค
while left < right:
sum = nums[i] + nums[left] + nums[right]
if sum < 0:
left += 1
elif sum > 0:
right -= 1
else: # sum = 0์ธ ๊ฒฝ์ฐ๋ค
results.append([nums[i], nums[left], nums[right]])
# left, right ์ ์์ ๋์ผํ ๊ฐ ์ฒ๋ฆฌ
while left < right and nums[left] == nums[left + 1]:
left += 1
while left < right and nums[right] == nums[right - 1]:
right -= 1
left += 1
right -= 1
return results
# nums = [-1, 0, 1, 2, -1, -4]
# sol = Solution()
# print(sol.threeSum(nums))
# [[-1, -1, 2], [-1, 0, 1]]
|
dc43a072d932e0cb503bb983fe74f8f0f7df3208 | rrwt/daily-coding-challenge | /ctci/ch2/intersection.py | 3,122 | 4.15625 | 4 | """
Given two (singly) linked lists, determine if the two lists intersect.
Return the intersecting node. Note that the intersection is defined based
on reference, not value. That is, if the kth node of the first linked list
is the exact same node (by reference) as the jth node of the second linked
list, then they are intersecting.
"""
from typing import Optional
from list_structure import LinkedList, Node
def intersect(ll1: LinkedList, ll2: LinkedList) -> Optional[Node]:
"""
A simple solution would be O(n*n), where we try and match every node of first
list to every node of second list.
Another one would be to create a set of nodes of first list and find if a node
of second list is in the hash.
time complexity: O(n+m)
space complexity: O(n)
"""
s: set = set()
h: Node = ll1.head
while h:
s.add(h)
h = h.next
h: Node = ll2.head
while h:
if h in s:
return h # return the intersecting node
h = h.next
return None
def get_loop(ll: LinkedList) -> (bool, Optional[Node]):
"""
Return the loop node and if there is a loop. Floyd's algorithm
Note: Cannot find the length by counting the number of nodes untill None
"""
slow: Node = ll.head
fast: Node = ll.head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
break
if fast != slow:
return False, None
"""
If we reinitialize the slow pointer and both pointers move at the
same pace(slow), the intersection is found at the point they meet.
"""
slow = ll.head
while slow != fast:
slow = slow.next
fast = fast.next
return True, slow
def intersect_without_extra_space(ll1: LinkedList, ll2: LinkedList) -> Optional[Node]:
"""
Assumption, end parts of the joined linkedlists is same (singly linked list).
Solution: Make first list circular. Detect circle in the second list.
If there is a circle, it means they intersect; otherwise no.
Remove the circle from the first list.
time complexity: O(n+m)
extra space complexity: O(1)
"""
h1: Node = ll1.head
while h1.next:
h1 = h1.next
h1.next = ll1.head
has_loop, node = get_loop(ll2)
h1.next = None
return node
if __name__ == "__main__":
first: LinkedList = LinkedList(Node(1))
first.push(3).push(5)
node = Node(7)
node.next = Node(9)
node.next.next = Node(11)
second: LinkedList = LinkedList(Node(2))
second.head.next = node
first.head.next.next.next = node
node = intersect(first, second)
print("intersecting node is", node.data, sep=" ")
third: LinkedList = LinkedList(Node(11))
third.push(13).push(15).push(17)
assert intersect(first, third) is None
assert intersect(second, third) is None
node = intersect_without_extra_space(first, second)
print("interseting node is", node.data, sep=" ")
assert intersect_without_extra_space(first, third) is None
assert intersect_without_extra_space(second, third) is None
|
efee73d5b254780e7536a4dc67b87c189aecfca5 | JeeZeh/kattis.py | /Solutions/pet.py | 232 | 3.59375 | 4 | scores = []
biggest = 0
index = 0
for i in range(0, 5):
points = eval(input().replace(" ", "+"))
scores.append(points)
if points > biggest:
biggest = points
index = i
print("%d %d" % (index+1, biggest)) |
2f5e988b7a85b111b1dbfaa2c319deba422dbfdb | janeon/automatedLabHelper | /testFiles/match/match26.py | 1,561 | 3.828125 | 4 |
def main():
print()
print("Welcome to my protein matching program!")
goodInput = False
while not goodInput:
try:
print()
n=input("Which text file would me to use? ")
inputFile = open(n, "r")
p=inputFile.readline()
seq = 0
print()
for pattern in inputFile:
bStart=0
bMismatch=len(p)
for start in range (0,(len(p)-len(pattern))+1):
mismatch=0
for i in range (0,len(pattern)-1):
if pattern[i]!=p[i+start]:
mismatch=mismatch+1
if mismatch<bMismatch:
bStart=start
bMismatch=mismatch
seq = seq + 1
print("Sequence ", seq, " has ", bMismatch, " errors at position ", bStart, ".", sep="")
print()
goodInput=True
except IOError:
print()
print("You have entered an improper file. Please try again.")
print()
except Exception as e:
print()
print("Whatever you did, it was wrong. Do it differently!")
print()
print(type(e))
print(str(e))
main() |
c4665be9a02620da1f0fc874fd129fe26f82008a | drboroojeni/Day-Counter-Drboroojeni | /dayCounter.py | 1,865 | 3.75 | 4 | #calculate the number of days between two dates
#checking whether year n is a leap year
def isLeap(n):
m = n % 400
if n%4 == 0 and m != 100 and m != 200 and m != 300:
return True
#counting the number of days from date m1/d1/y1 to date m2/d2/y2. Returns zero if dates are equal, negative if second date is earlier than the first one, and positive otherwise.
# running time: O(1)
def dayCount(m1,d1,y1,m2,d2,y2): #recursively defined...
dy = abs(y2-y1)
if dy >= 400:#if the dates are more than 400 years apart...
if y1 > y2:
return dayCount(m1, d1, y2 + dy % 400, m2, d2, y2) - (365 * 400 + 97) * int(dy / 400)# in every 400 years, there are 97 leap years
else:
return dayCount(m1, d1, y1, m2, d2, y1 + dy % 400) + (365 * 400 + 97) * int(dy / 400)
sum = 0
if y1 < y2:
for i in range(y1,y2):
if isLeap(i):
sum += 366
else:
sum += 365
return dayCount(m1, d1, y2, m2, d2, y2) + sum
if y2 < y1:
return -dayCount(m2, d2, y2, m1, d1, y1)
#runs the following code if only if y1 == y2
if m1 < m2:
for i in range(m1,m2):
if i == 1 or i == 3 or i == 5 or i == 7 or i == 8 or i == 10 or i == 12: # six months have 31 days
sum += 31
elif i == 2:
if isLeap(y1):
sum += 29 # February of a leap year has 29 days...
else:
sum += 28 # February of a non-leap year has only 28 days...
else:
sum += 30
return dayCount(m2,d1,y1,m2,d2,y2)+sum
if m1 > m2:
return -dayCount(m2,d2,y2,m1,d1,y1)
#continues the following code if and only if y1 == y2 and m1 == m2
return d2-d1
print dayCount(6,1,2018,1,6,20018)
|
ce75aaa2d0bf75e6c972d14c52430bcb1bceff54 | LucasHenriqueAbreu/introducaoprogramaca | /exercicio_dicionario4.py | 714 | 3.9375 | 4 | # 4. Crie um programa que gerencie o aproveitamento de um jogador de futebol.
# O programa vai ler o nome do jogador e quantas partidas ele jogou.
# Depois vai ler a quantidade de gols feitos em cada partida.
# No final, tudo isso serรก guardado em um dicionรกrio,
# incluindo o total de gols feitos durante o campeonato.
jogador = dict()
jogador['nome'] = input('Informe o nome do jogador: ')
jogador['qtd_partidas'] = int(input('Informe a quantidade de partidas que ele jogou: '))
gols = list()
for i in range(0, jogador.get('qtd_partidas')):
gols.append(int(input(f'Informe a quantidade de gols para a {i + 1}ยบ partida: ')))
jogador['gols'] = gols
jogador['total_gols'] = sum(gols)
print(jogador) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.