blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
648b192b27e90e5ba6683af9a51ed20e8126cf02 | maelstrom9/DS-and-Algorithms | /EPI/BinaryTrees/9.16 set level next field in a perfect binary tree.py | 1,146 | 3.84375 | 4 |
class Tree:
def __init__(self,v,l_next=None):
self.val = v
self.left = None
self.right = None
self.l_next = l_next
def set_level_next_perfect_binary_tree(root):
queue = [root]
while queue:
temp = []
for idx in range(len(queue)):
if queue[idx].left: ## perfect binary tree
temp += [queue[idx].left,queue[idx].right]
if idx>=1:
queue[idx-1].l_next = queue[idx]
queue = temp
return root
## book
## key idea if left child--> parent.next
## if right child-->parent.next.left
def update_next(root):
def helper(node):
while node and node.left:
node.left.l_next = node.right
node.right.l_next = node.l_next and node.l_next.left
node = node.left
helper(root)
# root = root.left
tree = Tree(2)
tree.right = Tree(8)
tree.left = Tree(3)
tree.left.left = Tree(4)
tree.left.right = Tree(5)
tree.right.right = Tree(9)
tree.right.left = Tree(10)
# res = set_level_next_perfect_binary_tree(tree)
update_next(tree)
print(1)
x = 2
y = 3
z = x and y
print(y) |
2adaf7455fa225b63444e6e668aef9f314ce55fc | andrefdavid/exerciciosImersaoPython | /basicos/ex01.py | 755 | 3.984375 | 4 | #Para um ano de nascimento fornecido pelo usuário, informe a idade que ele terá no dia 31 de dezembro de 2021.
#é preciso, inicialmente, solicitar ao usuário seu ano de nascimento através do input, converter para número inteiro e armazenar em uma variável
nascimento = int(input("Por favor, informe seu ano de nascimento"))
#para calcular a idade, subtraímos o ano de nascimento de 2021 e armazenamos na variável idade. Para uma versão do programa que puxe o ano diretamente do sistema, consulte o arquivpo ex01v2
idade = 2021 - nascimento
#para exibir a idade do usuário, utilizamos o print para exibir um texto e o format para incluir a variável dentro desse texto
print("A sua idade no dia 31 de dezembro de 2021 será {}".format(idade)) |
c25436ccf392b683aea8aef49b0db7209bf58855 | chowsychoch/Programming-1- | /p13/p13p1.py | 326 | 4.25 | 4 | # Program to print out the smallest of two numbers entered by the user
# Uses a function min
# if argument one is greater than two
#return argument 2
#else
#return argument one
def min(a,b)
"""Function that return the smallest of its two argument"""
if a > b:
return b
else:
return a
|
315190a4fe13ee3a78b7adf3ca516f294a82d086 | mrkickling/pythonkurs | /tillfalle1/solutions/uppg4-2.py | 659 | 4 | 4 | # Uppgift 5: Skapa ett program (vowel.py) som tar en bokstav som indata och printar
# Ja! Om bokstaven är en vokal och Nej! Om bokstaven är en konsonant
# Lösningsförslag 2
# Skapar en lista med alla vokaler och lägger i variabeln vokaler
vokaler = "aeiouyåäö"
# Hämtar indata i form av en bokstav och gör den till små bokstäver/gemener (lower case)
# och lägger den i variabeln bokstav
bokstav = input("Skriv en bokstav: ").lower()
# kollar om bokstav finns i listan vokaler med hjälp av funktionen 'in'
if bokstav in vokaler:
print("Ja!") # Om bokstaven tillhör listan vokaler, printa Ja!
else:
print("Nej!") # Annars, printa Nej!
|
8d8420326ff43e244a2ef033fd629026a95c89c3 | betty29/code-1 | /recipes/Python/578222_Pythdecorator_that_reexecutes/recipe-578222.py | 1,256 | 3.734375 | 4 | def conditional_retry(func=None, exceptions=Exception,
action=None, callback_args=(), timeout=2):
'''
This decorator is able to be called with arguments.
:keyword exceptions: exceptions in a tuple that will be
tested in the try/except
:keyword action: a callable to be called at the end of every
time of re-attempt
:keyword callback_args: arguments to be passed into the callable
:keyword timeout: times of attempt, defaults to 2
'''
def decorated(func):
def wrapper(*args, **kwargs):
result = None
i = 1
while i <= timeout:
try:
result = func(*args, **kwargs)
break
except exceptions:
if i == timeout:
raise
if callable(action):
action(*callback_args)
i += 1
return result
return wrapper
if func is None: # in this case, the decorator is called with arguments
def decorator(func):
return decorated(func)
return decorator
# or the decorator is called without arguments
return decorated(func)
|
a181170a1b9005860d97c379ee6e3d09298a574d | Dilan/interviewproblems | /path-sum-tree-II.py | 2,109 | 3.71875 | 4 | """
https://leetcode.com/problems/path-sum-ii/
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
Given the below binary tree and sum = 22,
[5]
/ \
[4] [8]
/ / \
[11] 13 [4]
/ \ / \
7 [2] [5] 1
Answer:
[[5,4,11,2], [5,8,4,5]]
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def pathSum(self, root, sum):
if (root is None):
return []
result = []
queue = [(root, (sum - root.val), [root.val])]
while(len(queue)):
node, rest, list = queue.pop()
if rest == 0 and (node.left is None and node.right is None):
result.append(list)
else:
items = []
if node.left is not None:
items.append(node.left)
if node.right is not None:
items.append(node.right)
for n in items:
queue.append((n, rest-n.val, list + [n.val]))
return result
@staticmethod
def build_tree(list):
idx = 0
root = TreeNode(list[idx])
queue = [root]
while(len(queue)):
node = queue.pop(0)
for n in [node.left, node.right]:
idx += 1
if idx < len(list) and list[idx] is not None:
n = TreeNode(list[idx])
queue.append(n)
return root
if __name__ == "__main__":
data = [
(
[5,4,8,11,None,13,4,7,2,None,None,5,1], 22,
[[5,4,11,2],[5,8,4,5]]
),
(
[1,2], 1,
[[1]]
),
(
[-2,None,-3],-5,
[[-2,-3]]
),
]
for item in data:
list, s, answer = item
root = Solution.build_tree(list)
result = Solution().pathSum(root, s)
print(result, answer)
|
12e763f79a34abd12a455a50417c3cd98c31da02 | MurradA/pythontraining | /Challenges/P042.py | 213 | 3.921875 | 4 | total = 0
for i in range(0, 5):
q = int(input("Enter a number: ").strip())
n = input("Do you want that number included? (y/n): ").strip()
if n.lower() == "y":
total = total + q
print(total) |
6219592f03f5cea708dde821430897ce82166159 | aswinrprasad/Python-Code | /Decision Making/Ex2.py | 546 | 4.03125 | 4 | #The rules for winning the prize have got stricter. The first name must now have more than 5
#characters (as well as end in the letter a). Modify the program in Exercise 1.
name=raw_input("Enter your first name :")
size=len(name)
if size >= 5:
if name[size-1] == 'a':
print "Congrats!! Your name ends with the letter A and have 5 characters. You won $1000."
else:
print "Name has 5 characters but does not end with letter A. Better luck next time."
else:
print "Your name doesn't end with A or have 5 characters. Better luck next time."
|
c8b8a876118f9efcc571b0a725a884b0cc333839 | ARAVINDGOGULA1488/DSP | /sine_phase.py | 479 | 3.5 | 4 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 5 04:19:47 2019
@author: rgukt
"""
import numpy as np
import matplotlib.pyplot as plt
f=input('enter the frequency')
phi=input('enter the phase angle')
m=np.linspace(0,100,1000)
x=np.sin(2*np.pi*(float(f))*m)
y=np.sin((2*np.pi*(float(f))*m)+phi)
fig=plt.figure()
ax1=fig.add_subplot(2,1,1)
ax2=fig.add_subplot(2,1,2)
ax1.plot(m,x)
ax2.plot(m,y)
ax1.set_title("sine wave")
ax2.set_title("shifted sine wave") |
83db4681047d4a501dc9df00f7912822660999ab | jjauzion/evolve | /src/system/Move.py | 1,381 | 3.90625 | 4 | class Move:
def __init__(self, screen_size):
"""
Move entity in the universe.
The universe is round: When one entity goes beyond the window size it appears back at the side
of the window.
:param screen_size: [tuple of int] (x, y) -> size of the window,
(0, 0) is the top left corner
x increases toward the right
y increases toward the bottom
"""
self.screen_size = screen_size
def move_entity(self, entity_list):
move_list = [ent for ent in entity_list if hasattr(ent, "velocity") and hasattr(ent, "position")]
for entity in move_list:
entity.position.x += entity.velocity.vector[0]
entity.position.y += entity.velocity.vector[1]
if entity.position.x > self.screen_size[0]:
entity.position.x = entity.position.x % self.screen_size[0]
elif entity.position.x < 0:
entity.position.x = self.screen_size[0] + entity.position.x
if entity.position.y > self.screen_size[1]:
entity.position.y = entity.position.y % self.screen_size[1]
elif entity.position.y < 0:
entity.position.y = self.screen_size[1] + entity.position.y
|
cc3420f085c07720da5da5f9026aeac16d130906 | mikaevnikita/ml_labs_travelling_salesman_problem | /annealing_2.py | 2,292 | 3.640625 | 4 | import random
import math
from citiesReader import readCities
city_solve = 'A'
N = 30000
def get_random_initial_state(initial_city, cities):
cities.remove(initial_city)
return [initial_city] + random.sample(cities, len(cities)) + [initial_city]
def get_random_next_state(initial_city, current_state):
current_state_view = list(filter(lambda city: city != initial_city, current_state))
i = random.randint(0, len(current_state_view) - 1)
j = random.randint(0, len(current_state_view) - 1)
return [initial_city] + swapped(current_state_view, i, j) + [initial_city]
def swapped(old_list, i, j):
new_list = old_list[:]
new_list[i], new_list[j] = new_list[j], new_list[i]
return new_list
def calculate_distance(city_from, city_to):
x1 = city_from.x
y1 = city_from.y
x2 = city_to.x
y2 = city_to.y
return math.sqrt( (x1 - x2) ** 2 + (y1 - y2) ** 2 )
def get_energy(state):
full_energy = 0
for i in range(len(state) - 1):
city_from = state[i]
city_to = state[i+1]
energy = calculate_distance(city_from, city_to)
full_energy += energy
return full_energy
def get_acceptance_probability(energy, new_energy, temperature):
if new_energy < energy:
return 1
else:
return math.exp(-(new_energy - energy) / temperature)
def print_path(state):
for city in state:
print(city.cityname + " -> ", end='')
print()
def temp(n_iters):
for i in range(n_iters):
yield (n_iters - i) / (n_iters / 6)
def main():
global temp
cities = readCities()
initial_city = next(
filter(
lambda city : city.cityname == city_solve,
cities),
None)
best_state = get_random_initial_state(initial_city,
cities)
temperatures = temp(N)
for current_temp in temperatures:
next_state = get_random_next_state(initial_city, best_state)
energy = get_energy(best_state)
new_energy = get_energy(next_state)
probability = get_acceptance_probability(energy, new_energy, current_temp)
if probability >= random.random():
best_state = next_state
print_path(best_state)
print("Energy: " + str(get_energy(best_state)))
main() |
2c3c08653450026edb36f5511cbcb8cd8751812d | kotori233/LeetCode | /[0275]_H-Index_II/H-Index_II.py | 505 | 3.546875 | 4 | class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
n = len(citations)
left, right = 0, n - 1
while left <= right:
middle = (left + right) // 2
if n - middle == citations[middle]:
return n - middle
if n - middle > citations[middle]:
left = middle + 1
else:
right = middle - 1
return n - left
|
81d264e7a956e78b2b20013ca73675412263c932 | Aniaaaaa/Szyfrator | /python/main.py | 10,635 | 3.71875 | 4 | import math
special_signs = {",", " ", ".", "?", "!"}
alphabet ="QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm"
def get_alphabet():
return alphabet
def get_alphabet_length():
return len(alphabet)
def caesar_code(message, key):
key = int(key)
message = str(message)
message_list = list(message)
for i in range(len(message_list)):
if message_list[i] in alphabet:
letter_ascii = ord(message_list[i])
if letter_ascii > 96:
letter_ascii -= 97
add = 97
else:
letter_ascii -= 65
add = 65
letter_ascii += key
letter_ascii = (letter_ascii % 26) + add
# letter_ascii += add
message_list[i] = chr(letter_ascii)
message = "".join(message_list)
return message
def caesar_uncode_blind(message):
message = str(message)
possible_answers = list()
for i in range(26):
possible_answers.append(caesar_code(message, i))
return possible_answers
def caesar_uncode_known(message, key):
key = int(key)
return caesar_code(message, 26-key)
def vigenere_code(message, key):
message = str(message)
message_list = list(message)
key = str(key)
key_len = len(key)
key_key = 0
for i in range(len(message)):
if message[i] in alphabet:
message_list[i] = caesar_code(message[i], (ord(key[key_key].lower()) - 97) % 26)
key_key += 1
key_key = key_key % key_len
return "".join(message_list)
def vigenere_uncode(message, key):
message_list = list(message)
key = str(key)
key_len = len(key)
key_key = 0
for i in range(len(message)):
if message[i] in alphabet:
message_list[i] = caesar_code(message[i], 26-((ord(key[key_key].lower()) - 97) % 26))
key_key += 1
key_key = key_key % key_len
return "".join(message_list)
def atbash_code(message):
message_list = list(message)
alphabet_atbash = dict()
for i in range(26):
alphabet_atbash[chr(i + 97)] = chr(97 + (25 - i))
for i in range(len(message_list)):
if message_list[i] in alphabet:
big = False
if ord(message_list[i]) < 95:
big = True
message_list[i] = alphabet_atbash[message_list[i].lower()]
if big == True:
message_list[i] = message_list[i].upper()
return "".join(message_list)
def atbash_uncode(message):
return atbash_code(message)
def transposition_code(message, key):
key = int(float(key))
message = "".join(message.split(" "))
coded_message = ""
message = "".join(message.split(" "))
for i in range(key):
for j in range(int(math.ceil(float(len(message))/key))):
if i + j*key < len(message):
coded_message += message[i + j*key]
return coded_message
def transposition_uncode_known(message, key):
key = int(float(key))
message = "".join(message.split(" "))
decoded_message = list(range(len(message)))
x = 0
y = 0
letter = 0
for i in range(key):
while x + y*key < len(message):
decoded_message[x + y*key] = message[letter]
letter += 1
y += 1
y = 0
x += 1
return "".join(decoded_message)
def transposition_uncode_blind(message):
possible_answers = list()
for i in range(1, len(message)):
possible_answers.append(transposition_uncode_known(message, i))
return possible_answers
def bacon_code(message):
coded_message = ""
for letter in message:
if letter in alphabet:
number = ord(letter.lower()) - 97
if number >= 16:
coded_message += "b"
number -= 16
else:
coded_message += "a"
if number >= 8:
coded_message += "b"
number -= 8
else:
coded_message += "a"
if number >= 4:
coded_message += "b"
number -= 4
else:
coded_message += "a"
if number >= 2:
coded_message += "b"
number -= 2
else:
coded_message += "a"
if number >= 1:
coded_message += "b"
number -= 1
else:
coded_message += "a"
coded_message += " "
coded_message = coded_message[:-1]
return coded_message
def bacon_uncode(message):
uncoded_message = ""
for x in message.split(" "):
number = 0
for i in range(len(x)):
if x[-i - 1] == "b":
number += int(math.pow(2, i))
uncoded_message += chr(number + 97)
return uncoded_message
def original_vinegere_code(message, key_letter):
key_letter = key_letter.lower()
coded_message = ""
for i in message:
if i in alphabet:
new_key_letter = i.lower()
coded_message += caesar_code(i, (ord(key_letter.lower()) - 97) % 26)
key_letter = new_key_letter
else:
coded_message += i
return coded_message
def original_vinegere_uncode_known(message, key):
uncoded_message = ""
key = key.lower()
for i in message:
if i in alphabet:
uncoded_letter = caesar_code(i, 26-((ord(key.lower()) -97) % 26))
key = uncoded_letter
uncoded_message += uncoded_letter
else:
uncoded_message += i
return uncoded_message
def original_vinegere_uncode_blind(message):
possible_answers = list()
for i in range(26):
possible_answers.append(original_vinegere_uncode_known(message, chr(i + 97)))
return possible_answers
def railfence_code(message, key):
key=int(float(key))
message = "".join(message.split(" "))
code_list = list()
for i in range(key):
code_list.append("")
i = 0
go_up = True
for x in range(len(message)):
code_list[i] += message[x]
if go_up == True:
i += 1
if i >= key:
i -= 2
go_up = False
else:
i -= 1
if i <= -1:
i += 2
go_up = True
return "".join(code_list)
def railfence_uncode_known(message, key):
key = int(float(key))
message = "".join(message.split(" "))
uncoded_message = ""
lines_of_text = list()
for i in range(key):
lines_of_text.append("")
letter_amount = int(math.floor(len(message)/float(2*key - 2)))
letter_modulo = len(message) % (2*key - 2)
if letter_modulo > 0:
lines_of_text[0] += message[:letter_amount + 1]
message = message[letter_amount+1:]
else:
lines_of_text[0] += message[:letter_amount]
message = message[letter_amount:]
for i in range(1, key-1):
lines_of_text[i] += message[:2 * letter_amount]
message = message[2*letter_amount:]
if letter_modulo > i:
lines_of_text[i] += message[0]
message = message[1:]
if letter_modulo > 2*key - 2 - i:
lines_of_text[i] += message[0]
message = message[1:]
lines_of_text[key-1] = message
i = 0
go_up = True
for x in range(len("".join(lines_of_text))):
uncoded_message += lines_of_text[i][0]
lines_of_text[i] = lines_of_text[i][1:]
if go_up == True:
i += 1
if i >= key:
i -= 2
go_up = False
else:
i -= 1
if i <= -1:
i += 2
go_up = True
return uncoded_message
def railfence_uncode_blind(message):
possible_answers = list()
for i in range(2, len(message)):
possible_answers.append(railfence_uncode_known(message,i))
return possible_answers
def weird_alphabet_code(message, key):
message = message.lower()
key = key.lower()
key_alphabet = ""
weird_alphabet = ""
coded_message = ""
for x in key:
if x not in key_alphabet and x in alphabet:
key_alphabet += x
for i in range(26):
char = chr(97+i)
weird_alphabet += char
if char not in key_alphabet:
key_alphabet += char
for x in message:
if x in weird_alphabet:
coded_message += key_alphabet[weird_alphabet.index(x)]
else:
coded_message += x
return coded_message
def weird_alphabet_uncode(message, key):
message = message.lower()
key = key.lower()
key_alphabet = ""
alphabet = ""
uncoded_message = ""
for x in key:
if x not in key_alphabet and ord(x.lower()) > 96 and ord(x.lower()) < 123:
key_alphabet += x
for i in range(26):
alphabet += chr(97+i)
if chr(97+i) not in key_alphabet:
key_alphabet += chr(97+i)
for x in message:
if x in alphabet:
uncoded_message += alphabet[key_alphabet.index(x)]
else:
uncoded_message += x
return uncoded_message
def try_english_dictionary(possible_answers, dictionary, word_percentage=20):
more_likely_possible_answers = list()
for x in possible_answers:
all_words_amount = len(x.split(" "))
good_words_amount = 0
for y in x.split(" "):
if y.lower() in dictionary:
good_words_amount += 1
if good_words_amount/all_words_amount >= word_percentage/100:
more_likely_possible_answers.append(x)
if len(more_likely_possible_answers) < 1:
print("Sorry dude, but I dont think its English message or good Method")
print("So im returining all possibilities")
return possible_answers
return more_likely_possible_answers
def make_dictionary_english():
dict_file = open("dict.txt", 'r')
all_lines = dict_file.readlines()
dictionary = dict()
for i in range(len(all_lines)):
all_lines[i] = all_lines[i][:-1]
dictionary[all_lines[i].lower()] = None
return dictionary
if __name__ == "__main__":
nmb =1
print(railfence_uncode_known(railfence_code("abcdefghijklmnopqrstuvwxyz",nmb),nmb))
|
1a9032ea9a1be531e77197f456675a53be4c0427 | paulsatish/IGCSECS | /16May-Task2-parcel.py | 1,222 | 4.03125 | 4 | TotalNotAccepted=0
TotalAccepted=0
TotalWeight=0
continue1="yes"
while continue1=="yes":
print("Please enter the parcel dimensions")
height=float(input("Please enter the height of the parcel in cm: "))
width=float(input("Please enter the width of the parcel in cm: "))
length=float(input("Please enter the length of the parcel in cm: "))
dimSum=height+width+length
if height>80 or width>80 or length>80:
print("One of the dimensions are more than 80cm. Please enter <=80")
if dimSum>200:
print("Sum of three dimensions should be <= 200")
weight=float(input("Please enter the weight of the parcel in KG"))
if weight<1 or weight >12 or height>80 or width>80 or length>80 or dimSum>200:
print("Parcel rejected")
TotalNotAccepted=TotalNotAccepted+1
else:
print("Parcel accepted")
TotalWeight=TotalWeight+weight
TotalAccepted=TotalAccepted+1
continue1=input("Do you want to continue?")
print("Total number of parcels accepted are :" + str(TotalAccepted))
print("Total number of parcels not accepted are :" + str(TotalNotAccepted))
print("Total weight of all the accepted parcels is:" +str(TotalWeight))
|
6f1a5284efa2adbdab7135daf9e8afbfb819a288 | RaphaelZH/Raspberry_Pi_4_Progrmas_EN | /1_Mini_Programs_for_Practice/7_one_LED_with_one_PIR_sensor/one_LED_with_one_PIR_sensor.py | 667 | 3.640625 | 4 | import RPi.GPIO as GPIO
import time
LED_PIN = 17
PIR_PIN = 4
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIR_PIN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.output(LED_PIN, GPIO.LOW)
# avoid the warning message when executing this program again
try:
while True:
# be able to read 100 times each second
time.sleep(0.01)
# here, this PIR sensor has replaced the button as control this LED
if GPIO.input(PIR_PIN) == GPIO.HIGH:
GPIO.output(LED_PIN, GPIO.HIGH)
else:
GPIO.output(LED_PIN, GPIO.LOW)
except KeyboardInterrupt:
# pass
print("cleaning up GPIOs")
GPIO.cleanup()
|
1f19fd7004c4debfa63c29b70d7ddfc1984b9aca | thaheer-uzamaki/assignment-9 | /dupplies.py | 344 | 3.796875 | 4 | from itertools import zip_longest
a = []
n=int(input("Enter the length of list: - "))
for i in range(n):
a.append(int(input()))
res = [i for i, j in zip_longest(a, a[1:])
if i != j]
# printing result
print ("List after removing consecutive duplicates : " + str(res)) |
aef9c34c5d2fc2a3f54f81d889c71856bede79a9 | CornelRemer/dijkstra | /transformer.py | 3,448 | 4 | 4 | """Convert a PIL image into a graph, suitable for the dijkstra algorithm
"""
import numpy as np
import math
from dijkstra import Node
class RasterNodes():
"""Graph of nodes created from an image like a Digital Terrain Model (DTM)
The __init__ takes two arguments:
image (obj): Image object from the PIL module
pixel_size (int): Complies the size of on pixel (in meter)
Example:
graph = RasterNodes(img, PIXEL_SIZE)
"""
def __init__(self, image, pixel_size = 5):
self._width, self._height = image.size
self._image = image
self._pixel_size = pixel_size
# create a None-value frame
self._matrix = np.full(
(self._width + 2, self._height + 2),
None)
# fill pixel values inside the None-value frame
self._fill_matrix()
self._straight_neighbors = [
(-1,0),
(1,0),
(0,-1),
(0,1)]
self._diagonal_neighbors =[
(-1,-1),
(-1,1),
(1,-1),
(1,1)]
def _fill_matrix(self):
self._pixel_values = self._image.load()
for i in range(self._width):
for j in range(self._height):
self._matrix[i+1, j+1] = self._pixel_values[i, j]
def _determine_neighbors(self, neighbor_coordinates):
for i,j in neighbor_coordinates:
self._x, self._y = self._coloumn+i, self._row+j
if self._matrix[self._x, self._y] is not None:
self._pixel_value = self._matrix[self._x, self._y]
# get direct neighbors
if neighbor_coordinates == self._straight_neighbors:
self.distance = math.sqrt(self._pixel_size**2 + (self._matrix[self._row, self._coloumn] - self._pixel_value)**2)
# get diagonal neighbors
elif neighbor_coordinates == self._diagonal_neighbors:
self.distance = math.sqrt((math.sqrt(2 * self._pixel_size**2))**2 + (self._matrix[self._row, self._coloumn] - self._pixel_value)**2)
self._neighbors.append(
('%s,%s' % (self._x - 1, self._y - 1), self.distance))
def get_pixel_neighbors(self, pixel_coordinates):
"""Returns all neighbors of a specific pixel
Args:
pixel_coordinates (tuple): coordinates (integer) of a specific pixel in (row, coloumn)
"""
self._coloumn, self._row = [_ + 1 for _ in pixel_coordinates]
self._neighbors = []
self._determine_neighbors(self._diagonal_neighbors)
self._determine_neighbors(self._straight_neighbors)
return self._neighbors
def transform_to_nodes(self):
"""Converts every pixel from the image into a Node.
Returns all Node-objects in a list
"""
self.nodes = []
for i in range(self._width):
for j in range(self._height):
self.nodes.append(Node(
'%s,%s' % (i,j),
self.get_pixel_neighbors((i,j))
))
return self.nodes
if __name__=="__main__":
from PIL import Image
WIDTH = 3
HEIGHT = 3
PIXEL_VALUE = 15
PIXEL_SIZE = 5
img = Image.new('L', (WIDTH, HEIGHT), PIXEL_VALUE)
myraster_nodes = RasterNodes(img, PIXEL_SIZE)
nodes = myraster_nodes.transform_to_nodes()
print(nodes) |
fabb296f928e6ec05929526d4d67c6d10bf9f000 | bishal8/github | /classobject.py | 167 | 3.703125 | 4 | class Test:
def sum(self, a, b):
s=a+b
return s
a= int(input("enter a number:"))
b=int(input("enter a number:"))
obj=Test()
s=obj.sum(a,b)
print(s) |
4010a4c9e624383fa5c0045c2e3373c7ffe035b2 | knishant09/LearnPythonWorks_2 | /Practise/19.py | 131 | 4.28125 | 4 | import os
str = raw_input("Enter the value of string:")
print str
if str[:2] == "Is":
print str
else:
print 'Is' + str
|
2de646411122b45e46ae21e8ff2bd10521175d05 | ravikantchauhan/python | /escape_sequence_asnormaltext.py | 148 | 3.71875 | 4 | # this is for print to escape sequence as normal taxt
# for example i want to print hellow word in \n new line
print ("hellow word in \\n new line") |
a5077ef1fbf1614feda122ca996902d914b48643 | lvraikkonen/GoodCode | /leetcode/204_count_primes.py | 459 | 3.828125 | 4 | import math
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n < 3:
return 0
is_prime = [True for _ in range(n)]
is_prime[0], is_prime[1] = False, False
for i in range(2, int(math.sqrt(n))+1):
if is_prime[i]:
for j in range(i*i, n, i):
is_prime[j] = False
return is_prime.count(True) |
9950abcb66b829471ff5a5e95905d0d086dcebe6 | aakriti-27/Internity_DataScienceWithPython | /day5/data_handling.py | 1,268 | 4.59375 | 5 | #Pandas is a Python library.
#Pandas is used for working with data sets and analyzing it.
#Pandas Series is a one-dimensional array holding data of any type(like a column in a table)
import pandas as pd #creating an alias while importing
a = [1, 2, 3]
myvar = pd.Series(a)
print(myvar[0]) #values are labeled with their index number
myvar = pd.Series(a, index = ["a", "b", "c"]) #creating new labels
print(myvar)
b = {"a1": 10, "b2": 20, "c3": 30} #using key,object while making series
myvar = pd.Series(b)
print(myvar)
#DataFrames are datasets in Pandas are usually multi-dimensional tables(like a whole table)
mydataset = {
'char': ["A", "B", "C"],
'value': [1,2,3]
}
myvar = pd.DataFrame(mydataset)
print(myvar)
print(myvar.loc[0]) #loc attribute to return one or more specified row(s)
print(myvar.loc[[1, 2]])
myvar1 = pd.DataFrame(mydataset, index = ["v1", "v2", "v3"]) #giving own indexes
print(myvar1)
print(myvar1.loc["v2"])
#Reading csv file
file = pd.read_csv('data.csv')
print(file.to_string())
#Viewing the data
print(file.head()) #return the top 5 rows
print(file.head(3)) #return the top 3 rows
print(file.tail()) #return last 5 rows of dataframe
print(file.info()) #to get more information about data set |
a5f037a18f21c9eba6cbe2f39ab5e79932e235f6 | WondwosenTsige/data-structures-and-algorithms | /python/code_challenges/graph_breadth_first/graph_breadth_first.py | 487 | 3.90625 | 4 | from code_challenges.stacks_and_queue.queue import Queue
def graph_breadth_first(vertex):
nodes = []
breadth = Queue()
visited = set()
breadth.enqueue(vertex)
visited.add(vertex)
while not breadth.isEmpty():
front = breadth.dequeue()
nodes.append(front)
for neighbor in front.neighbor:
if neighbor.vertex not in visited:
visited.append(neighbor)
breadth.enqueue(neighbor)
return nodes
|
b8bf327aae2f5f0636ebef12f34a2a82c30d6017 | lope512q09/Python | /Chapter_10/Lopez_TIY10.11.py | 573 | 3.71875 | 4 | import json
fav_num = None
def fav_num_input():
"""Prompts user for their favorite number."""
active = True
while active:
try:
global fav_num
fav_num = int(input("Please enter your favorite number: "))
except ValueError:
print("Please enter numbers only.")
else:
active = False
def dump_fav_num():
"""JSON dumps favorite number into a file."""
filename = 'favorite_number.json'
with open(filename, 'w') as f:
json.dump(fav_num, f)
fav_num_input()
dump_fav_num()
|
9e2452f970de343b21a5a3be1c6bc1f2912779c4 | johndemlon/mail-circle | /generator.py | 600 | 3.640625 | 4 | import string
import random
ltrs = string.ascii_letters
cntr = 1
def random_char(y):
return ''.join(random.choice(string.ascii_letters) for x in range(y))
text_file = open("emails.txt", "w")
nmml = input("How many emails do you want ? ")
nmcr = input("How many charecters do you want ? ")
for i in range(0,int(nmml)):
gnrtd1 = str(cntr)+"-"
print(gnrtd1)
#gnrtd = random_char(5)
gnrtd2 = str(random_char(int(nmcr)))+"@john9119.33mail.com"
print(gnrtd2.lower())
text_file.write("""gnrtd1"""+gnrtd2.lower()+'\n')
cntr = cntr+1
text_file.close()
print("By The Fake 8")
print("https://paypal.me/demlon")
|
2e2ec5a5bfb8e1389191adf0ce56523ed34029a8 | jordan336/battleship | /src/Grid.py | 7,081 | 3.921875 | 4 | from Position import Position
"""
Grid class
The Grid class represents one Agent's game board.
The Grid contains the dimensions of the board and
the state of each square, whether it was a hit, miss, or
has not been explored.
"""
class Grid:
def __init__(self, width, height):
self.width = width
self.height = height
self.missed = []
self.hit = []
def getWidth(self):
return self.width
def getHeight(self):
return self.height
def getHitPositions(self):
return self.hit
def getMissedPositions(self):
return self.missed
def setHitPosition(self, position):
self.hit.append(position)
def setMissedPosition(self, position):
self.missed.append(position)
def queryPosition(self, position):
if position in self.hit:
return 'hit'
elif position in self.missed:
return 'missed'
else:
return 'unknown'
def queryPositionHit(self, position):
if position in self.hit:
return True
else:
return False
def queryPositionMissed(self, position):
if position in self.missed:
return True
else:
return False
def getValidNeighbors(self, position):
neighbors = []
# North
if position.y+1 < self.height:
neighbors.append(Position(position.x, position.y+1))
# East
if position.x+1 < self.width:
neighbors.append(Position(position.x+1, position.y))
# South
if position.y-1 >= 0:
neighbors.append(Position(position.x, position.y-1))
# West
if position.x-1 >= 0:
neighbors.append(Position(position.x-1, position.y))
return neighbors
def getDistNearestSameRowHit(self, x, y, ignorePositions=[]):
positions = [pos for pos in self.getHitPositions() if pos not in ignorePositions]
return self._getDistSameRow(positions, x, y)
def getDistNearestSameRowMiss(self, x, y, ignorePositions=[]):
positions = [pos for pos in self.getMissedPositions() if pos not in ignorePositions]
return self._getDistSameRow(positions, x, y)
def getDistNearestSameColHit(self, x, y, ignorePositions=[]):
positions = [pos for pos in self.getHitPositions() if pos not in ignorePositions]
return self._getDistSameCol(positions, x, y)
def getDistNearestSameColMiss(self, x, y, ignorePositions=[]):
positions = [pos for pos in self.getMissedPositions() if pos not in ignorePositions]
return self._getDistSameCol(positions, x, y)
def _getDistSameRow(self, positions, x, y):
posOnSameRow = [pos for pos in positions if pos.y == y]
if len(posOnSameRow) > 0:
return min(abs(x - pos.x) for pos in posOnSameRow)
else:
return -1
def _getDistSameCol(self, positions, x, y):
posOnSameCol = [pos for pos in positions if pos.x == x]
if len(posOnSameCol) > 0:
return min(abs(y - pos.y) for pos in posOnSameCol)
else:
return -1
"""
getContinuousVerticalHits()
Return the number of continuous vertical hits, assuming the
given position is also a hit.
"""
def getContinuousVerticalHits(self, x, y):
posOnSameCol = [pos for pos in self.getHitPositions() if pos.x == x]
continuous = [Position(x, y)]
noChange = False
while not noChange:
noChange = True
for pos in posOnSameCol:
for continuousPos in continuous:
if pos not in continuous and abs(pos.y - continuousPos.y) == 1:
continuous.append(pos)
noChange = False
return len(continuous)
"""
getContinuousHorizontalHits()
Return the number of continuous horizontal hits, assuming the
given position is also a hit.
"""
def getContinuousHorizontalHits(self, x, y):
posOnSameRow = [pos for pos in self.getHitPositions() if pos.y == y]
continuous = [Position(x, y)]
noChange = False
while not noChange:
noChange = True
for pos in posOnSameRow:
for continuousPos in continuous:
if pos not in continuous and abs(pos.x - continuousPos.x) == 1:
continuous.append(pos)
noChange = False
return len(continuous)
"""
getDownVerticalMissedLength()
Get the downward vertical length of the continuous unmissed squares containing x, y.
"""
def getDownVerticalMissedLength(self, x, y):
if self.queryPosition(Position(x, y)) == 'missed':
return 0
gapSquares = [Position(x, y)]
# Explore downwards in the column
col = y - 1
while col >= 0:
if self.queryPosition(Position(x, col)) != 'missed':
gapSquares.append(Position(x, col))
col -= 1
else:
break
return len(gapSquares)
"""
getUpVerticalMissedLength()
Get the upward vertical length of the continuous unmissed squares containing x, y.
"""
def getUpVerticalMissedLength(self, x, y):
if self.queryPosition(Position(x, y)) == 'missed':
return 0
gapSquares = [Position(x, y)]
# Explore upwards in the column
col = y + 1
while col < self.height:
if self.queryPosition(Position(x, col)) != 'missed':
gapSquares.append(Position(x, col))
col += 1
else:
break
return len(gapSquares)
"""
getLeftHorizontalMissedLength()
Get the leftward horizontal length of the continuous unmissed squares containing x, y.
"""
def getLeftHorizontalMissedLength(self, x, y):
if self.queryPosition(Position(x, y)) == 'missed':
return 0
gapSquares = [Position(x, y)]
# Explore leftwards in the row
row = x - 1
while row >= 0:
if self.queryPosition(Position(row, y)) != 'missed':
gapSquares.append(Position(row, y))
row -= 1
else:
break
return len(gapSquares)
"""
getRightHorizontalMissedLength()
Get the rightward horizontal length of the continuous unmissed squares containing x, y.
"""
def getRightHorizontalMissedLength(self, x, y):
if self.queryPosition(Position(x, y)) == 'missed':
return 0
gapSquares = [Position(x, y)]
# Explore rightwards in the row
row = x + 1
while row < self.width:
if self.queryPosition(Position(row, y)) != 'missed':
gapSquares.append(Position(row, y))
row += 1
else:
break
return len(gapSquares)
|
55313bd54e80488c2147740de16d1053e97a5c32 | Tatenda-Ndambakuwa/autocomplete.py | /lexicologicalOrder.py | 2,087 | 3.703125 | 4 | # code to get the first five words
def extract(query):
# initializing
nextString = "a"
words=[]
recentWord=str()
database= []
count =0
keepGoing = True
# begin while
while ( keepGoing):
count +=1
words= query(nextString)
#print (words)
#print (len (words))
#lastWord= (words[-1])
newWords = len(words)>0 and ((words[-1])not in database)
if (newWords):
database= database + words
#getting rid of duplicates sets
database= list(set(database))
database.sort()
# removing unnecessary iterations eg when less than five words are returned
if (len(words)<5):
nextString=(chr(ord(nextString[0:1]) + 1))
else:
nextString= (words[-1])
elif (len(nextString)>1):
nextString = (nextString[:-1])
elif (nextString=="z"):
keepGoing = False
else:
nextString= (chr(ord(nextString) + 1))
# to look at what letters are being checked
# print ('checking '+nextString)
## to check what words are returned
#print (database)
print(" Number of iterations "+ str(count) )
return database # end while
##################################################################################
# start main method
##################################################################################
def main():
# type: () -> object
#"""Runs your solution -- no need to update (except to maybe try out different databases)."""
# Sample implementation of the autocomplete API
database = ["abracadara", "al", "alice", "alicia", "allen", "alter", "altercation", "bob", "element", "ello", "eve", "evening", "event", "eventually", "mallory"]
# getting the first five words that match the query
query = lambda prefix: [d for d in database if d.startswith(prefix)][:5]
# making sure what we get as results matches what we have in the database
assert extract(query) == database
main() # call main
|
23e3a5849777355818231d6a497f242c36309308 | keerat21/Graph-Search-DFS-and-BFS | /BFSandDFS.py | 1,875 | 3.609375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri May 22 21:26:22 2020
@author: Hp User
"""
close = []
opened = []
def getchild(b):
print('Enter child of {0} , type 00 if no more child'.format(b))
return input()
#####################################PART A###################################
def dfs_getter():
while(input() != '00'):
a = getchild(j) #keep getting child of j / nparent
open.append(a) #consider the end of list, top of stack
if(input() == '00' ):
nparent = open.pop() #if no more child, pop from TOS
j = nparent # j will be new parent
if nparent not in close:
close.append(nparent) # nparent will be in closed
dfs_getter() #recursive unless pressed "quit"
####################################PART B####################################
def bfs_getter():
while(input() != '00'):
a = getchild(j) #keep getting child of j / nparent
open.append(a) #consider the end of list, top of stack
if(input() == '00' ):
nparent = open.popleft() #if no more child, pop from head of queue
j = nparent # j will be new parent
if nparent not in close:
close.append(nparent) # nparent will be in closed
bfs_getter() #recursive unless pressed "quit"
k = input("enter bfs or dfs: ")
def start():
j = ''
print('enter starting point: ')
inp = input()
close.append(inp)
getchild(inp)
if(k == 'dfs'):
start()
dfs_getter()
if(k == 'bfs'):
start()
bfs_getter()
|
4d253738150432d06f88350c1bd4f77e0e7c69a7 | LukasKodym/py-tests | /strings.py | 369 | 3.75 | 4 | # %%
##
s = 'Witaj nasze 0'
print('b' not in s)
# to jest komentarz
# %%
##
x = input('Wprowadź swoej imię: ')
print('Twoje imię to: ' + x)
# %%
##
a = float(input('Wprowadź liczbę: '))
a += 1
print(a)
# %%
##
pcs = 12
# s = 'W magazynie jest ' + str(pcs) + ' sztuk.'
s = 'W magazynie jest {} sztuk.'.format(pcs)
print(s)
# %%
##
a = 'a'
b = 'a'
print(a == b)
|
a21548b70211c4521cd225edf43feec62f71766e | guti7/Data-Structures | /source/finder.py | 2,835 | 4.15625 | 4 | #!python
def find(string, pattern):
"""return true if string contains the entire pattern, false otherwise."""
# implement find_iterative and find_recursive
# assert isinstance(string, str)
return find_iterative(string, pattern)
# return find_recursive(string, pattern)
def find_iterative(string, pattern):
# loop over the string until the pattern in found
if not string or not pattern:
return False
pat_index = 0
for char in string:
if char == pattern[pat_index]:
pat_index += 1
else:
pat_index = 0
if pat_index == len(pattern):
return True
return False
def find_recursive(string, pattern, str_index=0, ptr_index=0):
# implement find_recursive
if not string or not pattern:
return False
if ptr_index == len(pattern):
return True
if str_index == len(string):
return False
if string[str_index] == pattern[ptr_index]:
return find_recursive(string, pattern, str_index + 1, ptr_index + 1)
return find_recursive(string, pattern, str_index + 1, 0)
def find_index(string, pattern):
"""
Return the starting index of the first occurence of the pattern,
and None if not found.
"""
# implement find_index_iterative and find_index_recursive
# return find_index_iterative(string, pattern)
return find_index_recursive(string, pattern)
def find_index_iterative(string, pattern):
# implement
if not string or not pattern:
return None
pat_index = 0
for index, char in enumerate(string):
if char == pattern[pat_index]:
pat_index += 1
else:
pat_index = 0
if pat_index == len(pattern):
return index - pat_index + 1
return None
def find_index_recursive(string, pattern, str_index=0, ptr_index=0):
# TODO: implement
if not string or not pattern:
return None
if ptr_index == len(pattern):
return str_index - ptr_index
if str_index == len(string):
return None
if string[str_index] == pattern[ptr_index]:
return find_index_recursive(string, pattern, str_index + 1, ptr_index + 1)
return find_index_recursive(string, pattern, str_index + 1, 0)
# STRETCH:
def find_all_indexes(string, pattern):
"""Returns a list of the starting indexes of all ocurrences of pattern."""
# implement find_all_indexes_iterative and find_all_indexes_recursive
return find_all_indexes_iterative(string, pattern)
# return find_all_indexes_recursive(string, pattern)
def find_all_indexes_iterative(string, pattern):
# TODO: implement
pass
def find_all_indexes_recursive(string, pattern):
# TODO: implement
pass
if __name__ == '__main__':
# print(find('', ''))
print(find_recursive('', ''))
|
f3516b0ec5c89e9de69c1e8d161eaedc6c9cb7a7 | klmsathish/PythonBasics | /ErrorHandling5.py | 418 | 4.09375 | 4 | def ask_for_int():
while True:
try:
age = int(input("enter your age = "))
except(ValueError):
print("Entered input is not a number")
continue
else:
if(age >= 18):
print("eligible to vote")
break
else:
print("not eligible to vote")
break
ask_for_int() |
b3a7550a14e971ac040aa22eb1773f54b6e5a4a6 | harryoh99/IE343_ML | /Final_Project_20180396/students/task1/App/logistic_regressor.py | 3,633 | 3.84375 | 4 | import numpy as np
import pandas as pd
import math
class LogisticRegressor():
#INITIALIZATION OF THE MODEL
def __init__(self,w=None):
#First initialize the weight to a none value
self.w = w
def fit(self, X, y,lr,epoch_num):
"""
TRAINING
X dimension is (623,11)
X dimension is (N,D) => We will change this to (N,D+1) adding the bias term
w dimension is (D+1,1)
y dimension is (N,1) so the dimension is (623,1)
model.fit(train_X, train_y,lr,epoch_num) will be called.
"""
#ADDING THE BIAS TERM
#matrix consisted of ones so that we could add it to X
ones = np.ones((X.shape[0],1))
#Add the matrix of ones to the X so that we have X E R (N*D+1)
X = np.concatenate((ones, X),axis=1)
#Initialization of the weights to zero.
self. w= np.zeros(np.shape(X[1]))
#TRAINING PROCESS (TRAINS "epoch_num" times)
#epoch_num is a hyperparameter
for i in range(epoch_num):
#y_hat = The probability value that we got from the sigmoid function
y_hat = self.sigmoid(X)
#Getting the gradient
#FYI: Here the gradient is actual gradient * (-1)
#The real gradient is -X.T@(y_hat-y) but just to make it pretty, just left it like that
gradient = X.T @(y_hat-y)
#Perform the gradient descent
#since the gradient variable is has opposite sign of the real gradient-> add it
self.w += gradient *lr
#Printing the training error every 100 iterations.
if(i%100==0):
self.accuracy(y,y_hat)
def predict(self, X):
"""
Here we predict the probability value for the test data.
Input dimension (N,d)
Output dimension (N,1)
"""
#ADDING THE BIAS TERM
#matrix consisted of ones so that we could add it to X
ones = np.ones((X.shape[0],1))
#Add the matrix of ones to the X so that we have X E R (N*D+1)
X = np.concatenate((ones, X),axis=1)
#Call the sigmoid function to get the probability value and return it to the caller.
return self.sigmoid(X)
def sigmoid(self,X):
"""
SIGMOID FUNCTION (MORE OF A COMPUTING SCORE +SIGMOID)
FIRST using the given X, we compute the score.
Then we put this in the sigmoid function 1/1+e^x and return it
input dimension is (N,d+1)
z/output dimension is (N,1)
"""
#X:(N,d+1), self.w: (d+1,1), z:(N,1)
#Computing the score value. z = XW (bias term included)
z = X@ self.w
#returning the sigmoid function value, which is the probability value.
#We put the score function value into the sigmoid function.
return 1/(1+np.exp(z))
def accuracy(self,true_y,pred_y):
'''
Computing the accuracy by comparing the predicted y and the true y value
When we get the probability value from the sigmoid function,
we check if it is bigger than 0.5-> if yes we put that to class 1
if not to class 0
'''
#If the predicted probability is smaller than 0.5 -> class 0
pred_y[pred_y<0.5]=0
#If the predicted probability is bigger than 0.5 -> class 1
pred_y[pred_y>=0.5]=1
#Check how many true y and predicted y are equal among the total datapoints.
accuracy=np.sum(true_y==pred_y)/len(true_y)*100
#PRINTING The accuracy
print('Training Accuracy: ', accuracy,"%" )
|
5799573ff22a3b7875e557af56df9f0770f48457 | iragomez68/Python-Lessons | /pie_store.py | 1,085 | 3.890625 | 4 | import string
pie_list = ["Pecan", "Apple Crisp", "Bean", "Banoffe", "Black Bun", "Buko", "Blueberry","Burek", "Tamale","Steak"]
basket = []
for i in range(len(pie_list)):
print(f"({i}) {pie_list[i]}")
while True:
pie = int(input("Which pie would you like to bring home? "))
selection = pie
basket.append(pie_list[selection])
print(f"Great will have that {pie_list[selection]} right out for you")
answer=input("Would you like some more? (y)es/(n)o ")
if answer != "y":
break
print("----------------------------------------")
print("-----------order summary----------------")
print(f"You've purchased: {len(basket)} pies")
basket.sort()
basket_output =[]
pie_name = ""
pie_count = 0
for pie in basket:
if pie_name == pie:
pie_count = pie_count + 1
else:
if pie_name != "":
basket_output.append(str(pie_count) + " X " + pie_name)
pie_name = pie
pie_count = 1
basket_output.append(str(pie_count) + " X " + pie_name)
for i in range(len(basket_output)):
print(f"{basket_output[i]}") |
6a3b247835d4560bf8e251fce5bd098fb7615da4 | megumik/coursera_bioinformatics1 | /1_1_frequent_words.py | 843 | 3.53125 | 4 | # 2020/5/20 megumik
# coding: utf-8
def PatternCount(Text, Pattern):
count = 0
for i in range(len(Text) - len(Pattern) + 1):
if Text[i:i+len(Pattern)] == Pattern:
count += 1
return count
def FrequentWords(Text, k):
frequent_patterns = set()
count = []
for i in range(len(Text) - k + 1):
pattern = Text[i: i+k]
#print(pattern)
count.append(PatternCount(Text,pattern))
max_count = max(count)
for i in range(len(Text) - k + 1):
if count[i] == max_count:
frequent_patterns.add(Text[i: i+k])
return list(frequent_patterns)
if __name__ == '__main__':
with open("data/dataset_2_10.txt") as f:
text, k = f.read().strip().split("\n")
freq_words = FrequentWords(text, int(k))
print(freq_words) |
dc03903ae6f72040514bd97e31c6def22886895b | lse30/Sudoku-Solver | /sodoku.py | 8,005 | 3.796875 | 4 | from tkinter import *
from tkinter.ttk import *
class SudokuGui:
"""Sudoku Gui for sudoku solver"""
def __init__(self, window):
"""sets up the window"""
self.title = Label(window, text="Sudoku Solver")
self.title.grid(row=0, column=1, pady=10, columnspan = 9)
self.left_edge = Label(window, text=" ")
self.left_edge.grid(row=0, column=0, pady=0)
self.right_edge = Label(window, text=" ")
self.right_edge.grid(row=0, column=10, pady=0)
self.entry_dict = {}
i = 1
j = 1
while j < 10:
while i < 10:
if i in [3,6] and j in [3,6]:
self.entry = Entry(window, width=3)
self.entry.grid(row=j, column=i, padx=(0,3), pady=(0,3))
k = (j*10) + i
self.entry_dict[k] = self.entry
i += 1
elif i in [3,6] and j not in [3,6]:
self.entry = Entry(window, width=3)
self.entry.grid(row=j, column=i, padx=(0, 3))
k = (j * 10) + i
self.entry_dict[k] = self.entry
i += 1
elif i not in [3,6] and j in [3,6]:
self.entry = Entry(window, width=3)
self.entry.grid(row=j, column=i, pady=(0, 3))
k = (j * 10) + i
self.entry_dict[k] = self.entry
i += 1
else:
self.entry = Entry(window, width=3)
self.entry.grid(row=j, column=i)
k = (j * 10) + i
self.entry_dict[k] = self.entry
i += 1
j += 1
i = 1
self.calc = Button(window, text="Calculate", command=self.print_dict)
self.calc.grid(row=10, column=1, columnspan = 9, pady=10)
def print_dict(self):
"""dfsdfsdfsd sdfsd"""
sudoku_dict = {}
for key in self.entry_dict:
output = self.entry_dict[key]
new = output.get()
if new == '':
sudoku_dict[key] = {1, 2, 3, 4, 5, 6, 7, 8, 9}
else:
sudoku_dict[key] = int(new)
solver(sudoku_dict)
def solver(sudoku_dict):
"""Basic sudoku solver Version 1"""
#input_sodoku()
box_index_dict = {1 : {11, 12, 13, 21, 22, 23, 31, 32, 33},
2 : {14, 15, 16, 24, 25, 26, 34, 35, 36},
3 : {17, 18, 19, 27, 28, 29, 37, 38, 39},
4 : {41, 42, 43, 51, 52, 53, 61, 62, 63},
5 : {44, 45, 46, 54, 55, 56, 64, 65, 66},
6 : {47, 48, 49, 57, 58, 59, 67, 68, 69},
7 : {71, 72, 73, 81, 82, 83, 91, 92, 93},
8 : {74, 75, 76, 84, 85, 86, 94, 95, 96},
9 : {77, 78, 79, 87, 88, 89, 97, 98, 99}}
sudoku = sudoku_dict
sudoku_updated = True
while sudoku_updated:
sudoku = check_rows(sudoku)
sudoku = check_cols(sudoku)
boxes = get_boxes(sudoku, box_index_dict)
sudoku = check_boxes(sudoku, boxes, box_index_dict)
sudoku, sudoku_updated = set_length_one(sudoku)
print_sudoku(sudoku)
def input_sudoku():
"""For a user inputted sudoku
creates a dictionary with indexs for each element"""
output = {}
j = 1
while j < 10:
question = "Please print row " + str(j) + ": "
row = input(question)
list = {1, 2, 3, 4, 5, 6, 7, 8, 9}
temp_list = list
for char in row:
if char != " ":
temp_list.remove(int(char))
i = 1
for number in row:
index = (10*j) + i
if number == " ":
output[index] = temp_list
else:
output[index] = int(number)
i += 1
j += 1
print(output)
def given_sudoku():
"""a given sudoku for testing purposes"""
output = {}
j = 1
row_list = [' 69 4 8', '28 5 34 ', ' 9 ', '1 69 85', '3 6 1 4', '95 24 6', ' 2 ', ' 14 2 59', '8 6 47 ']
while j < 10:
for row in row_list:
list = {1, 2, 3, 4, 5, 6, 7, 8, 9}
temp_set = list
for char in row:
if char != " ":
temp_set.remove(int(char))
i = 1
for number in row:
index = (10*j) + i
if number == " ":
output[index] = temp_set
else:
output[index] = int(number)
i += 1
j += 1
return output
def check_cols(sudoku):
"""Iterates through the columns of the sudoku
and eliminates the options if the number appears in the column"""
i = 1
col = set()
while i < 10:
j = 1
while j < 10:
index = (10*j) + i
number = sudoku[index]
if type(number) == int:
col.add(number)
j += 1
k = 1
while k < 10:
index = (10*k) + i
number = sudoku[index]
k += 1
if type(number) == set:
new = number - col
sudoku[index] = new
col = set()
i += 1
return sudoku
def check_rows(sudoku):
"""Iterates through the rows and removes possiblies if the number appears in the row"""
j = 1
row = set()
while j < 10:
i = 1
while i < 10:
index = (10*j) + i
number = sudoku[index]
if type(number) == int:
row.add(number)
i += 1
k = 1
while k < 10:
index = (10*j) + k
number = sudoku[index]
k += 1
if type(number) == set:
new = number - row
sudoku[index] = new
row = set()
j += 1
return sudoku
def get_boxes(su, box_index_dict):
"""This was the easist way to retrieve the values for the boxes"""
boxes = []
for key in box_index_dict:
box = []
for index in box_index_dict[key]:
box.append(su[index])
boxes.append(box)
return boxes
def check_boxes(sudoku, boxes, box_index_dict):
"""iterates through the boxes, this needs polishing up because its uses the box dict which is a lot cleaner
than the get boxes function"""
box_num = 1
box_dict = {}
for box in boxes:
box_nums = set()
for value in box:
if type(value) == int:
box_nums.add(value)
box_dict[box_num] = box_nums
box_num += 1
for section in box_index_dict:
test_box = box_dict[section]
for value in (box_index_dict[section]):
if type(sudoku[value]) == set:
new = sudoku[value] - test_box
sudoku[value] = new
return sudoku
def set_length_one(sudoku):
"""if there is only one possible number for a certain index then it updates it to an interger and
notifies main that the sudoku has been updated with a new number solved"""
sudoku_updated = False
for index in sudoku:
if type(sudoku[index]) == set:
if len(sudoku[index]) == 1:
element = list(sudoku[index])[0]
print("Solved position {0} = {1}".format(index,element))
sudoku_updated = True
sudoku[index] = element
return sudoku, sudoku_updated
def print_sudoku(sudoku):
"""Prints the sudoku in a readable manner"""
line = []
count = 1
for index in sudoku:
line.append(sudoku[index])
if count == 9:
print(line)
count = 1
line = []
else:
count += 1
def main():
"""the main for sudoku solver"""
window = Tk()
sudoku_solver = SudokuGui(window)
window.mainloop()
main() |
396c8754559c3956d8ba206e4fde6533fba7a58c | DedS3t/mllib | /mllib/helpers/train_test_split.py | 1,047 | 3.515625 | 4 | import math
def train_test_split(X, y, test_size = 0.2):
if len(X) != len(y):
raise RuntimeError # TODO change errors
X_train = []
y_train = []
X_test = []
y_test = []
for i in range(math.floor(len(X) * test_size)):
# training
X_train.append(X[i])
y_train.append(y[i])
for i in range(math.floor(len(X) * test_size), len(X)):
# testing
X_test.append(X[i])
y_test.append(X[i])
return X_train, y_train, X_test, y_test
if __name__ == "__main__":
import unittest
# testing
class TestTTS(unittest.TestCase):
def test_1d(self):
X = [1,2,3,4,5]
y = [1,2,3,4,5]
X_train, y_train, X_test, y_test = train_test_split(X, y)
self.assertEqual(len(X_train) + len(X_test), len(X), "The resulting feature array should be the same size")
self.assertEqual(len(y_train) + len(y_test), len(y), "The resulting target array should be the same size")
# TODO add more tests
unittest.main() |
4333f290cc3336fca513732cf0aade3ea39fa55b | CodingDojoOnline-Nov2016/DarrilGibson | /PythonAssignments/bubblesort.py | 371 | 3.78125 | 4 | # bubble sort low to high
# base case [3,1,5,9,7]
# set int_num1 to be first number
# set int_num2 to be second number
# if intnum1 > intnum2, swap
# repeat
a = [3,1,5,9,7]
for count in range (0, len(a)-1 ):
int_num1 = a[count]
int_num2 = a[count+1]
if a[count] > a[count+1]:
a[count] = int_num2
a[count+1] = int_num1
print a
|
5f9b361bfffe8c40d3549660d625d6842cc7b739 | romanannaev/python | /STEPIK/complete_task/tandem.py | 710 | 3.765625 | 4 | # Вам дана последовательность строк.
# Выведите строки, содержащие слово, состоящее из двух одинаковых частей (тандемный повтор).
# Sample Input:
# blabla is a tandem repetition
# 123123 is good too
# go go
# aaa
# Sample Output:
# blabla is a tandem repetition
# 123123 is good too
import sys
import re
pattern = r'\b(\w+)\1\b'
for line in sys.stdin:
line = line.rstrip()
search_object = re.search(pattern, line)
if search_object is not None :
print(line)
# re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
# r"(\b.*\B)\1\b"
# r"\b(.+\B)\1\b"
# r"\b(\w.*)\1\b" |
c789d97d4556d0f1691eeebcc713aa1a34044f3f | coolsnake/JupyterNotebook | /new_algs/Graph+algorithms/Coloring+algorithm/Searches.py | 10,927 | 3.640625 | 4 | '''
Created on Aug 22, 2018
@author: swagatam
'''
from Node import Node
from test.test_typing import Founder
def bfs(initial,goal):
#print(goal)
start_node=Node(initial,None,None)
visited=[]
fringe=[]
#visited.append(start_node.state)
current_node=None
fringe.append(start_node)
c=0
flag=0
while fringe:
moves=[]
c=c+1
current_node=fringe.pop(0)
visited.append(current_node.state)
#print(c)
print("Node count",c,"current state is",current_node.state)
if(current_node.state==goal):
flag=1
print("goal state reached \n")
print("total number of iterations: ",c)
break
else:
#print(current_node)
moves=Node.moves(Node,current_node)
#print(moves)
children=[]
for mv in moves:
if mv=="left":
state=Node.left(Node,current_node.state)
left_child=Node(state,current_node,"left")
children.append(left_child)
if mv=="right":
state=Node.right(Node,current_node.state)
right_child=Node(state,current_node,"right")
children.append(right_child)
if mv=="up":
state=Node.up(Node,current_node.state)
up_child=Node(state,current_node,"up")
children.append(up_child)
if mv=="down":
state=Node.down(Node,current_node.state)
down_child=Node(state,current_node,"down")
children.append(down_child)
#break
for elem in children:
#print(elem.state)
if elem.state not in visited:
fringe.append(elem)
if flag==1:
seq=[]
while(current_node.parent is not None):
seq.append(current_node.move)
current_node=current_node.parent
seq.reverse()
print("goal state sequence: ",seq)
print("Maximum depth reached: ",len(seq))
else:
print("goal state unreachable")
def dfs(initial,goal):
#print(goal)
start_node=Node(initial,None,None)
visited=[]
fringe=[]
#visited.append(start_node.state)
current_node=None
fringe.append(start_node)
c=0
flag=0
while fringe:
moves=[]
c=c+1
current_node=fringe.pop()
visited.append(current_node.state)
#print(c)
print("Node count",c,"current state is",current_node.state)
if(current_node.state==goal):
flag=1
print("goal state reached \n")
print("total number of iterations: ",c)
break
else:
#print(current_node)
moves=Node.moves(Node,current_node)
#print(moves)
children=[]
for mv in moves:
if mv=="left":
state=Node.left(Node,current_node.state)
left_child=Node(state,current_node,"left")
children.append(left_child)
if mv=="right":
state=Node.right(Node,current_node.state)
right_child=Node(state,current_node,"right")
children.append(right_child)
if mv=="up":
state=Node.up(Node,current_node.state)
up_child=Node(state,current_node,"up")
children.append(up_child)
if mv=="down":
state=Node.down(Node,current_node.state)
down_child=Node(state,current_node,"down")
children.append(down_child)
#break
for elem in children:
#print(elem.state)
if elem.state not in visited:
fringe.append(elem)
if flag==1:
seq=[]
while(current_node.parent is not None):
seq.append(current_node.move)
current_node=current_node.parent
seq.reverse()
print("here")
print(seq)
print("Maximum depth reached: ",len(seq))
else:
print("goal state unreachable")
def astar(initial,goal):
#print(goal)
start_node=Node(initial,None,None,0)
visited=[]
fringe=[]
#visited.append(start_node.state)
current_node=None
fringe.append(start_node)
c=0
flag=0
while fringe:
moves=[]
c=c+1
#print(fringe.pop().heuristic)
fringe.sort(key= lambda x: x.heuristic, reverse=False)
current_node=fringe.pop(0)
visited.append(current_node.state)
#print(c)
print("Node count",c,"current state is",current_node.state)
if(current_node.state==goal):
flag=1
print("goal state reached \n")
print("total number of iterations: ",c)
break
else:
#print(current_node)
moves=Node.moves(Node,current_node)
#print(moves)
children=[]
for mv in moves:
if mv=="left":
state=Node.left(Node,current_node.state)
heuristic = Node.calculate_misplaced_tiles(Node,current_node.state,state) + Node.calculate_misplaced_tiles(Node,state,goal)
left_child=Node(state,current_node,"left",heuristic)
children.append(left_child)
if mv=="right":
state=Node.right(Node,current_node.state)
heuristic = Node.calculate_misplaced_tiles(Node,current_node.state,state) + Node.calculate_misplaced_tiles(Node,state,goal)
right_child=Node(state,current_node,"right",heuristic)
children.append(right_child)
if mv=="up":
state=Node.up(Node,current_node.state)
heuristic = Node.calculate_misplaced_tiles(Node,current_node.state,state) + Node.calculate_misplaced_tiles(Node,state,goal)
up_child=Node(state,current_node,"up",heuristic)
children.append(up_child)
if mv=="down":
state=Node.down(Node,current_node.state)
heuristic = Node.calculate_misplaced_tiles(Node,current_node.state,state) + Node.calculate_misplaced_tiles(Node,state,goal)
down_child=Node(state,current_node,"down",heuristic)
children.append(down_child)
#break
#children.sort(key=Node.heuristic, reverse=False)
for elem in children:
#print(elem.state)
if elem.state not in visited:
fringe.append(elem)
if flag==1:
seq=[]
while(current_node.parent is not None):
seq.append(current_node.move)
current_node=current_node.parent
seq.reverse()
print("goal state sequence: ",seq)
print("Maximum depth reached: ",len(seq))
else:
print("goal state unreachable")
def idastar(initial,goal):
global flag
flag=0
threshold=Node.calculate_misplaced_tiles(Node,initial,goal)
count=0
start_node=Node(initial,None,None,0)
def search(current_node,g,threshold,goal,count):
global flag
heuristic=g + Node.calculate_misplaced_tiles(Node,current_node.state,goal)
if heuristic > threshold:
return heuristic
if current_node.state==goal:
seq=[]
while(current_node.parent is not None):
seq.append(current_node.move)
current_node=current_node.parent
seq.reverse()
print("total number of iterations: ",count)
print(" goal state sequence is",seq)
print("Maximum depth reached: ",len(seq))
return "found"
min=99999
moves=Node.moves(Node,current_node)
children=[]
for mv in moves:
if mv=="left":
state=Node.left(Node,current_node.state)
heuristic = Node.calculate_misplaced_tiles(Node,current_node.state,state) + Node.calculate_misplaced_tiles(Node,state,goal)
left_child=Node(state,current_node,"left",heuristic)
children.append(left_child)
if mv=="right":
state=Node.right(Node,current_node.state)
heuristic = Node.calculate_misplaced_tiles(Node,current_node.state,state) + Node.calculate_misplaced_tiles(Node,state,goal)
right_child=Node(state,current_node,"right",heuristic)
children.append(right_child)
if mv=="up":
state=Node.up(Node,current_node.state)
heuristic = Node.calculate_misplaced_tiles(Node,current_node.state,state) + Node.calculate_misplaced_tiles(Node,state,goal)
up_child=Node(state,current_node,"up",heuristic)
children.append(up_child)
if mv=="down":
state=Node.down(Node,current_node.state)
heuristic = Node.calculate_misplaced_tiles(Node,current_node.state,state) + Node.calculate_misplaced_tiles(Node,state,goal)
down_child=Node(state,current_node,"down",heuristic)
children.append(down_child)
for elem in children:
count=count+1
print("Node count is",count,"node state is :",elem.state)
t=search(elem, g + Node.calculate_misplaced_tiles(Node,current_node.state,elem.state), threshold, goal,count)
if t == "found" :
#print(elem.state)
#if flag==0:
# seq=[]
# while(elem.parent is not None):
# seq.append(elem.move)
# elem=elem.parent
# seq.reverse()
# print(" goal state sequence is",seq)
# flag=1
return "found"
if t< min:
min=t
return min
while True:
t= search(start_node,0,threshold,goal,count=count+1)
if t== "found":
print("goal state reached at threshold value :",threshold)
#print("No of iterations: ",count)
break
if t==-1:
print("gaol state unrechable")
break
threshold=t
|
03ce9e936175fe0427d01c60080ad126efeaa848 | yeli7289/Algorithms | /sort/mergesort.py | 737 | 3.734375 | 4 | class Solution:
def mergesort(self, nums):
self.helper(nums, 0, len(nums)-1)
def helper(self, nums, left, right):
mid = (left+right)/2
if left < right:
self.helper(nums, left, mid)
self.helper(nums, mid+1, right)
self.merge(nums, left, mid, right)
def merge(self, nums, left, mid, right):
hl, hr = left, mid+1
temp = [None]*(right-left+1)
i = 0
while hl<=mid and hr<=right:
if nums[hl]<nums[hr]:
temp[i] = nums[hl]
hl+=1
else:
temp[i] = nums[hr]
hr+=1
i+=1
if hl <= mid:
temp[i:] = nums[hl:mid+1]
if hr <= right:
temp[i:] = nums[hr:right+1]
i = 0
while left <= right:
nums[left] = temp[i]
left+=1
i+=1
s=Solution()
nums = [3,2,1,4,5]
s.mergesort(nums)
print nums |
7ed744f9f185ddb2314674569ca9bbed1e9dfe96 | vikashvishnu1508/algo | /Revision/Arrays/TwoNumberSum.py | 764 | 3.984375 | 4 | def twoNumberSumMethod1(array, target):
lastSeen = {}
for i in array:
expectedValue = target - i
if expectedValue not in lastSeen:
lastSeen[i] = True
else:
return [i, expectedValue]
return [-1, -1]
def twoNumberSumMethod2(array, target):
array.sort()
left = 0
right = len(array) - 1
while left < right:
expectedValue = target - array[left]
if array[right] == expectedValue:
return [array[left], array[right]]
elif array[right] > expectedValue:
right -= 1
left += 1
return [-1, -1]
array = [3, 5, -4, 8, 11, 1, -1, 6]
targetSum = 10
print(twoNumberSumMethod1(array, targetSum))
print(twoNumberSumMethod2(array, targetSum)) |
41e918af7e5bee7b5c068f67dea27bb6063f1f1d | MikkelOerberg/PracticalWeek5 | /Color Names.py | 962 | 4.375 | 4 | """
Based on the state name example program above,
create a program that allows you to look up hexadecimal colour codes
like those at http://www.color-hex.com/color-names.html
Use a constant dictionary of about 10 names and write a program that allows a user
to enter a name and get the code, e.g. entering AliceBlue should show #f0f8ff.
"""
COLOR_NAMES = {"red1": "#ff0000", "blue1": "#0000ff", "black": "#000000",
"gray": "#bebebe", "green1": "#00ff00",
"yellow1": "#ffff00", "white": "#ffffff", "purple1": "#9b30ff",
"pink1": "#ffb5c5", "gold1": "#ffd700"}
# print(COLOR_NAMES)
color = input("Enter a color name: ")
color = color.lower()
while color != "":
if color in COLOR_NAMES:
print(color, "is", COLOR_NAMES[color])
else:
print("Invalid name")
color = input("Enter a color name: ")
color = color.lower()
for k, v in COLOR_NAMES.items():
print("{:<10} {}".format(k, v))
|
ea40d57eb627de1d74a30dbfa26e95d66f1490e1 | davidhuangdw/leetcode | /python/482_LicenseKeyFormatting.py | 509 | 3.75 | 4 | from unittest import TestCase
# https://leetcode.com/problems/license-key-formatting
class LicenseKeyFormatting(TestCase):
def licenseKeyFormatting(self, S: 'str', K: 'int') -> 'str':
s = S.replace('-', '').upper()[::-1]
return '-'.join(s[i:i+K] for i in range(0, len(s), K))[::-1]
def test1(self):
self.assertEqual("5F3Z-2E9W", self.licenseKeyFormatting("5F3Z-2e-9-w", 4))
def test2(self):
self.assertEqual("2-5G-3J", self.licenseKeyFormatting("2-5g-3-J", 2))
|
b4faa37eb7a8b8715f1952d4928790b7b056020c | arvind-mocha/Login-page_Kivy | /String_validation.py | 592 | 3.5625 | 4 | import re
regex_mail = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
regex_name = '^[a-zA-z0-9_-]{3,15}$'
regex_password = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
#STRING CONDTION WHILE INPUT
def checkemail(email):
if(re.search(regex_mail,email)):
return 'valid'
else:
return 'invalid'
def checkname(name):
if(re.search(regex_name,name)):
return 'valid'
else:
return 'invalid'
def checkpassword(password):
if (re.search(regex_password, password)):
return 'valid'
else:
return 'invalid'
|
6e726805ffae3cf62089c939e417d865362c5aec | BjaouiAya/Cours-Python | /Course/Book/Programmer_avec_Python3/13-ClasseEtInterfacesGraphiques/cercleScaling.py | 4,328 | 3.78125 | 4 | #! /usr/bin/env python
# -*- coding:Utf8 -*-
"""PROGRAMME PERMETTANT DE FAIRE VARIER LA TAILLE D'UN DISQUE"""
"EXERCICE 13.20"
###########################################
#### Importation fonction et modules : ####
###########################################
from tkinter import *
###############################################################################
#### Gestion d'évènements : définition de différentes Fonctions/Classes : #####
###############################################################################
############# Création des Classes #############
class ParametreCercle(Frame):
"""Génère les paramètres du cercle"""
def __init__(self, boss=None, couleur='navy'):
Frame.__init__(self)
self.couleur = couleur
self.rayon = 0
# Création de la case à cocher afin d'afficher le cercle
self.chk = IntVar() # Instanciation d'un Objet variable tkinter
Checkbutton(self, text='Afficher', variable=self.chk, fg=couleur,
command=self.active).pack(side=LEFT)
# Création du curseur
Scale(self, length=500, orient=HORIZONTAL, label='Rayon du cercle :',
troughcolor=couleur, sliderlength=20, showvalue=1, from_=0,
to=300, tickinterval=20, resolution=1,
command=self.setRayon).pack(side=LEFT, padx=10, pady=10)
def active(self):
"""Création d'un évènement pour indiquer que la case est cochée"""
self.event_generate('<Control-Z>')
def setRayon(self, r):
"""Modification de la valeur du rayon"""
self.rayon = float(r)
self.event_generate('<Control-Z>')
def valeurs(self):
"""Tuple des paramètres du cercle"""
return (self.rayon)
class DessineCercle(Canvas):
"""Génère un canevas avec ajout de cercle possible"""
def __init__(self, boss=None, larg=600, haut=600):
Canvas.__init__(self)
self.configure(width=larg, height=haut)
self.larg = larg
self.haut = haut
def traceCercle(self, rayon):
"""Dessine le cercle dans le canevas"""
ref = self.create_oval(self.larg/2-rayon, self.haut/2-rayon,
self.larg/2+rayon, self.haut/2+rayon,
width=2, fill='orange')
return ref
#####################
# CLASSE PRINCIPALE #
#####################
class Root(Frame):
"""Classe principale + gestionnaire d'évènement"""
def __init__(self, master=None):
Frame.__init__(self)
# Ajout du canevas contenant le cercle
self.dessin = DessineCercle(Root)
self.dessin.configure(bg='navy', relief=SOLID, bd=2)
self.dessin.pack(padx=5, pady=5, side=TOP)
# Ajout du bloc contenant les paramètres du cercle
self.parametre = ParametreCercle(Root)
self.parametre.configure(relief=GROOVE, bd=2)
self.parametre.pack(padx=10, pady=10)
# Ajout de l'évènement déclenchant le tracé du cercle
self.master.bind('<Control-Z>', self.montreCercle)
# Ajout du titre grâce à <master>
self.master.title("Cercle Magique")
# Mémorisation du cercle créé
self.trace = [0]
# Position dans la fenêtre (utile si on veut le réutiliser)
self.pack(padx=10, pady=10)
def montreCercle(self, event):
"""Modification de la valeur du rayon"""
# Suppression du cercle grâce à sa reférence
self.dessin.delete(self.trace[0])
if self.parametre.chk.get(): # Vérification de la case à cocher
# Méthode non recommandée (obtention directement de la valeur
# du rayon du rayon à l'intérieur de la classe parametre)
"self.trace[0] = self.dessin.traceCercle(rayon=\
self.parametre.rayon)"
# Méthode recommandée (utilise une méthode de la classe
# afin de définir le rayon)
rayon = self.parametre.valeurs()
self.trace[0] = self.dessin.traceCercle(rayon=rayon)
############# Création des Fonctions #############
###############################
#### Programme principal : ####
###############################
if __name__ == '__main__':
Root().mainloop()
|
732716d5b85856142fe6ab2f3f52a49e6943f76b | gschen/sctu-ds-2020 | /1906101002-夏先苗/20200219.py | 534 | 4.03125 | 4 | #连接
a="hi"
b="s"
print(a+b)
#重复字符
c="hi"
print(c*3)
#切片
str1="abcde"
print(str1[0])
print(str1[-1])
print(str1[0:4])
a="bcde"
print("e" in a)
print("f" not in a)
#格式化输出
print("我叫%s"%("夏先苗"))
print("我今年%s"%(19))
#列表
list1=[1,2,3,[4,5,6]]
print(len(list1))
for x in [1,2,3]:
print(x)
list1 =[1,2,3,[4,5,6]]
list1.append(7)
list1.extend([1,2])
print(list1.index(2))
list2=[5,4,2,8,3,9]
list2.pop(1)
print(list2)
list2.sort(1)
print(list2)
#元组
tup=("s",100,[1,2])
print(tup)
|
4ca49b6f764211862710c18aef17c5dad37bb3a7 | CaptainSherry49/Python-Beginner-Advance-One-Video | /My Practice Of Beginner Video/Chapter 11/06_Property_Decrator.py | 207 | 3.578125 | 4 | class Employee:
company = "Amazon"
Salary = 30000
SalaryBonus = 1500
@property
def TotalSalary(self):
return self.Salary + self.SalaryBonus
E = Employee()
print(E.TotalSalary)
|
587c93eaa92d1a39a8dbaeb20a2d6862e2ceed01 | laksh10-stan/DSA-Python- | /6.21_BST_search_rec.py | 490 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 3 02:07:56 2019
@author: laksh
"""
def find( root, data):
currentNode = root
while currentNode is not None and data != currentNode.getData():
if data> currentNode.getData():
currentNode = currentNode.getRight()
else:
currentNode = currentNode.getLeft()
return currentNode
'''
Time Complexity: O(n), in worst case (when BST is a skew tree). Space Complexity: O(n), for recursive stack.
''' |
bab01f75f2806616d3cb61f3ae59fa6457085b5b | kaimhall/basic-python2 | /koodi.py | 230 | 3.5625 | 4 | print("Laskin")
luku1 = input("Anna ensimmäinen luku: ")# voi tehdä myös int(input())
luku2 = input("Anna toinen luku: ")#kokonaisluvuille.
tulos = int(luku1) + int(luku2)#integer muunnos.
print("Tulos on:", tulos)
|
4e15cfc4d9d0fade7b56558616c3ce609b278908 | Ryandalion/Python | /Files and Exceptions/Average of Numbers/Average of Numbers/Average_of_Numbers.py | 859 | 4.40625 | 4 | # Program will calculate the average of all the numbers inside the text file
def main():
dataFile = open('numbers.txt', 'r'); # Open the text file that holds the numbers
number = dataFile.readline(); # Assign the first line to number
count = 0; # Variable to hold the number of elements inside the text file
total = 0; # Variable that holds the sum of all elements in the text file
while number != '': # Loop until empty
total = total + int(number); # Add the number to the total. Convert the number from a string to a integer
count += 1; # Increase the counter variable by one per loop
number = dataFile.readline(); # Retrieve the next line and assign it to number
dataFile.close(); # Close the file
average = (total/count); # Calculate the average
print(average); # Print the average
main(); |
21159f3651f61a7cf0d9be78b9c1b7d3209a1cb1 | rogeriosilva-ifpi/teaching-tds-course | /programacao_estruturada/20192_186/cap7_iteracao/pares_impares.py | 448 | 3.875 | 4 | def programa():
numero = int(input('Número: '))
contador_pares = 0
contador_impares = 0
while numero != 0:
if numero % 2 == 0:
contador_pares = contador_pares + 1
else:
contador_impares = contador_impares + 1
numero = int(input('Número: '))
print(f'Você digitou {contador_pares} números pares')
print(f'Você digitou {contador_impares} números ímpares')
programa()
|
458c0c4693f77cd8fb874c558330077f52b2c3a9 | zzh730/LeetCode | /Bit Manipulation/sqrt().py | 667 | 3.65625 | 4 | __author__ = 'drzzh'
'''
二分查找的题,注意的是如果是分数,返回时的条件是: mid*mid <= x and (mid+1)*(mid+1) > x
Time: O(logn)
'''
class Solution:
# @param x, an integer
# @return an integer
def sqrt(self, x):
if x < 0:
return -1
if not x:
return 0
if x ==1:
return 1
left = 1
right = int(x/2)
while left <= right + 1:
mid = int((left+right)/2)
if mid*mid <= x and (mid+1)*(mid+1) > x:
return mid
elif mid*mid > x:
right = mid-1
else:
left = mid+1 |
6bc79e97829b741324ce92dd7152dd7fe459c9e4 | Danang691/Euler.Py | /euler/solutions/euler15.py | 1,007 | 3.515625 | 4 | # -*- coding: utf-8 -*-
from euler.baseeuler import BaseEuler
from euler.util import factorial
'''
research
This is a combinations problem. on a 20x20 grid to get from top-left to
bottom-right there are 40 moves (20 down and 20 right). The problem can be
solved by applying the formula for the central binomial coefficient
(http://en.wikipedia.org/wiki/Central_binomial_coefficient):
x!
C(x,y) = -----------
y! * (x-y)!
'''
class Euler(BaseEuler):
def _routes(self, x, y):
return factorial(x) / (factorial(x - y) * factorial(y))
def solve(self):
return self._routes(40, 20)
@property
def answer(self):
return ('There are %d routes through a 20x20 grid' % self.solve())
@property
def problem(self):
return '''
Project Euler Problem 15:
Starting in the top left corner of a 2x2 grid, there are 6 routes
(without backtracking) to the bottom right corner.
How many routes are there through a 20x20 grid?
'''
|
1be8c44c886ffde5d98b8c18cc80d30cb4b149f8 | weizt/python_studying | /面向对象/23-多态的使用.py | 2,000 | 4.09375 | 4 | # 概念:多态是基于继承,对它进行子类重写父类的方法,
# 达到不同的子类对象调用相同的父类方法,得到不同的结果
# 作用:提高代码的灵活度
# 需求:
'''
1.多种不同类型的狗
2.一个类型的人
3.同一个人与多种类型的狗做不同的工作
'''
# 思路
'''
1. 创建一个Dog类的父类
2. 定义不同Dog类的子类
3. 重写Dog类父类的方法
4. 人调用相同的方法名,实现不同的功能
5. Dog类定义不同的方法
6. Person类定义唯一的方法,此方法将调用不同的dog类的方法
'''
# 先定义一个Person
class Person(object):
def __init__(self, name): # Person类暂时不定义dog属性,默认为None
self.name = name
self.dog = None
def with_work_dog(self):
# 判断self.dog不为None,并且属性Dog类,则调用dog.work()方法
if self.dog is not None and isinstance(self.dog, Dog):
self.dog.work()
# 定义Dog类的父类
class Dog(object):
def work(self):
print('正在工作')
# 定义Dog类的子类
class SeeingEyeDog(Dog):
# 重写父类的work()方法,以不同的子类,执行不同的结果
def work(self):
print('导盲犬正在指路')
class DetectionDog(Dog):
# 重写父类的work()方法,以不同的子类,执行不同的结果
def work(self):
print('缉毒犬正在缉毒')
class PoliceDog(Dog):
# 重写父类的work()方法,以不同的子类,执行不同的结果
def work(self):
print('警犬正在抓捕坏人')
# 创建一个Person的实例对象,再创建一个Dog类实例对象,并加动态属性dog
p = Person('张三')
# 创建Dog子类的实例对象
sed = SeeingEyeDog()
# 将此对象赋值给Person类的self.dog属性
p.dog = sed
# 调用并执行Person类的with_work_dog()方法
p.with_work_dog()
dd = DetectionDog()
p.dog = dd
p.with_work_dog()
pd = PoliceDog()
p.dog = pd
p.with_work_dog()
|
428d8389f56f9307be688c25ee317a1b62c5ce61 | VishnuGopireddy/leetcode | /21. Merge Two Sorted Lists.py | 1,424 | 3.984375 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
list1 = l1
list2 = l2
list3 = None
curr1, curr2 = list1, list2
while curr1 and curr2:
if curr1.val < curr2.val:
curr = curr1
curr1 = curr1.next
else:
curr = curr2
curr2 = curr2.next
curr.next = None
if list3 == None:
list3 = curr
else:
temp = list3
while temp.next != None:
temp = temp.next
temp.next = curr
if curr1:
curr = curr1
if list3 == None:
list3 = curr
else:
temp = list3
while temp.next != None:
temp = temp.next
temp.next = curr
if curr2:
curr = curr2
if list3 == None:
list3 = curr
else:
temp = list3
while temp.next != None:
temp = temp.next
temp.next = curr
return list3 |
372f0ca7e16456ee967d427b285048f6bbf72998 | SJHH-Nguyen-D/data-driven-web-apps-with-flask | /app/ch05_jinja_templates/starter/app.py | 1,645 | 3.515625 | 4 | """
VIEW METHODS are defined in the app.py script and they direct us to the appropriate html template windows (views).
Each view method typically is associated with directing us in the browser to the appropriate window, which is identified by a specific
pattern in the URL. Each route view method and route should have a corresponding HTML view page.
The typical naming convention for the corresponding HTML template views take on the name of the view method followed by the .html extension:
Example:
* View method:
* index()
* HTML view page:
* index.html
* View method:
* gallery()
* HTML view page:
* gallery.html
"""
import flask
app = flask.Flask(__name__)
def get_latest_packages():
return [
{"name": "flask", "version": "1.2.3"},
{"name": "sqlalechemy", "version": "2.2.0"},
{"name": "passlib", "version": "2.1.2"},
]
# this view method is the 'Controller' portion of the MVC model (Model View Controller)
@app.route('/')
def index():
""" this is the view method for the index or Home Page of our website """
# notice how you don't have to specify './templates/index.html"
# This is because flask automatically detects the html in the project locally, so you don't have to worry about specifying the relatve
# directory
test_packages = get_latest_packages()
return flask.render_template("index.html", packages=test_packages) # The index.html is the view portion of the MVC model
@app.route('/about')
def about():
""" this is the view method the About html template page """
return flask.render_template("about.html") # The index.html is the view portion of the MVC model
if __name__ == "__main__":
app.run() |
9db01501d733a045843bb8e1650450ff4c4bd2f7 | stanilevitch/python_06102018 | /zjazd_1/snippet.py | 1,929 | 3.953125 | 4 | x = int(input("Podaj pozycję X "))
y = int(input("Podaj pozycję Y "))
if x>100 or y > 100 or x < 0 or y <0:
print("Wypadłeś z planszy")
elif x>90 and y > 90:
print("Jesteś w prawym górnym rogu")
elif x > 90 and y <10:
print("jestes w prawym dolnym rogu")
elif x < 100 and y <10:
print("jestes w prawym dolnym rogu")
elif x < 10 and y <90:
print("jestes w prawym dolnym rogu")
elif x < 10:
print("lewa krawedz")
elif x > 90:
print("prawa krawedz")
elif y < 10:
print("dolna krawedz")
elif y > 90:
print("dolna krawedz")
else:
print("jesteś w centrum")
# ########################################################################
# 2 sposób
x = int(input("Podaj pozycję X "))
y = int(input("Podaj pozycję Y "))
wym_x = int(input("Podaj pozycję X "))
wym_y = int(input("Podaj pozycję Y "))
if x > 100 or y > 100 or x < 0 or y < 0:
print("Wypadłeś z planszy")
elif x > 90 and y > 90:
print("Jesteś w prawym górnym rogu")
elif x > 90 and y < 10:
print("jestes w prawym dolnym rogu")
elif x < 100 and y < 10:
print("jestes w prawym dolnym rogu")
elif x < 10 and y < 90:
print("jestes w prawym dolnym rogu")
elif x < 10:
print("lewa krawedz")
elif x > 90:
print("prawa krawedz")
elif y < 10:
print("dolna krawedz")
elif y > 90:
print("dolna krawedz")
else:
print("jesteś w centrum")
# ### ZAKOŃCZ PROGRAM
while True:
dane_wejsciowe = input("Popdaj liczbę lub wpisz KONIEC by zakonczyc")
if dane_wejsciowe == "KONIEC":
break
# ########################################################################
if znalezione_min is None or znalezione_min < dane_wejsciowe:
znalezione_min = dane_wejsciowe
if znalezione_max is None or znalezione_max > dane_wejsciowe:
znalezione_max = dane_wejsciowe |
504b67d380ecf8d1f5f7c7faf5dd731125a10ea8 | kattachandipriya1214/priyaguvi | /42.py | 234 | 3.9375 | 4 | string1=input().split()
if(len(string1[0])>len(string1[1])):
print(string1[0])
elif(len(string1[1])>len(string1[0])):
print(string1[1])
elif(len(string1[0])==len(string1[1])):
print(string1[1])
else:
print(string1[0])
|
7825fa432d5bf5f5520d27b36a5c53bf69a0229d | endrijsss/EDIBO | /Python/scripts/milzigs_skaitlis.py | 1,033 | 3.796875 | 4 | #! /usr/bin/python3.6
print("Ievadiet Skaitli")
# a =2**200000
#te ir tris darbibas - vertibas sagaidīšana, vertibas parveidosana, pieskirs$
#argument = input()
#int(argumnet)
#a = int(argument)
#pildot int(input()) "bez izmeginajuma" programma var vienkarsi izlidot...
#tapec, lai "nelidotu", mes izmantosim try ... except ... finally konstrukci$
paziime = False
while not paziime:
#while pazime==False:
#while paziime!=True:
try:
a = int( input() )
paziime=true
except:
print("Diemžel cienijamais lietotaj to kas ievadits nevar",\
"parveidot pa veselo tipa skaitli :-( ")
print("Ludzu ievadiet skaitli velreiz")
paziime = True
while paziime:
try:
a = int( input() )
print("a**100")
print("Lūdzu ievadiet SKAITLI")
print("Šis teksts atrodas ārpus darbību bloka - pierakstīts bez",\
"atstarpēm priekšā, tāpēc tas parādīsies jebkurā gadijumā")
#if (a == int): print("a**100)
#print ("Ievadāmai vērtibai jābūt skaitlim")
#b=a**100
|
86a20b9e336c8a5af9aab4d77a4389d491ac2fdd | kaizen0890/Machine-Learning-Project | /basic-algorithm/linear-regression.py | 840 | 3.671875 | 4 |
import os
import math
import numpy as np
import matplotlib.pyplot as plt
X = np.array([[147, 150, 153, 158, 163, 165, 168, 170, 173, 175, 178, 180, 183]]).T
Y = np.array([49, 50, 51, 54, 58, 59, 60, 62, 63, 64, 66, 67, 68])
#Building Xbar
one = np.ones((X.shape[0], 1))
Xbar = np.concatenate((one, X), axis = 1)
# Calculating weights of the fitting line
A = np.dot(Xbar.T, Xbar)
B = np.dot(Xbar.T, Y)
W = np.dot(np.linalg.pinv(A), B)
w_0, w_1 = W[0], W[1]
active = True
while active:
name = raw_input("What's your name? ")
height = float(raw_input("How tall are you?"))
predict = height*w_1 + w_0
print "Hi " + name
print "The computer predict your weight is: " + str(predict) + "kg"
answer = raw_input("Would you want to try one more time? (yes/no)")
if answer == 'no':
active = False
plt.scatter(X, Y)
plt.show()
|
158d7d76f43a7e588e2149ed43cf99f818583d5e | Gaazedo/Portfolio | /Codes/python/py1/exs (4)/ex6.py | 256 | 3.84375 | 4 | def conta(vetor):
n=len(vetor)
count=0
for i in range (n):
if vetor[i]>vetor[i-1] or vetor[i]<vetor[i-1]:
count+=1
return count
def lervetor(vetor):
n=len(vetor)
for i in range (n):
vetor[i]=int(input("Digite um número: "))
|
a90d3052ada40a3cc4a63639ad51c1e6fb69e834 | IvanPerez9/Programming-Paradigms | /Python/Numpy.py | 2,287 | 4.1875 | 4 | import numpy as np
"""
Create a 4X2 integer array and Prints its attributes
"""
array = np.arange(8).reshape(4,2)
print(array)
print(array.shape)
print(array.ndim)
print(array.itemsize)
"""
Create a 5X2 integer array from a range between 100 to 200 such that the difference between each element is 10
"""
array2 = np.arange(100, 200 , 10).reshape(5,2)
print(array2)
"""
Provided numPy array. return array of items in the third column from all rows
"""
sampleArray = np.array([[11 ,22, 33], [44, 55, 66], [77, 88, 99]])
new = sampleArray[...,2] # fila y columna
print(new)
# Se cada 2 filas, las columnas 1 y 2
sampleArray = np.array([[3 ,6, 9, 12], [15 ,18, 21, 24],
[27 ,30, 33, 36], [39 ,42, 45, 48], [51 ,54, 57, 60]])
newArray = sampleArray[::2, 1::2]
print(newArray)
"""
Dividir el array en 4 iguales
"""
print("Creating 8X3 array using numpy.arange")
sampleArray = np.arange(10, 34, 1)
sampleArray = sampleArray.reshape(8,3)
print (sampleArray)
print("\nDividing 8X3 array into 4 sub array\n")
subArrays = np.split(sampleArray, 4)
print(subArrays)
"""
Ordenar array
"""
print("Printing Original array")
sampleArray = np.array([[34,43,73],[82,22,12],[53,94,66]])
print (sampleArray)
sortArrayByRow = sampleArray[:,sampleArray[1,:].argsort()]
print("Sorting Original array by secoond row")
print(sortArrayByRow)
print("Sorting Original array by secoond column")
sortArrayByColumn = sampleArray[sampleArray[:,1].argsort()]
print(sortArrayByColumn)
"""
Maximo y minimo -> axis = 1 filas y axis = 0 columnas
"""
print("Printing Original array")
sampleArray = np.array([[34,43,73],[82,22,12],[53,94,66]])
print (sampleArray)
minOfAxisOne = np.amin(sampleArray, 1)
print("Printing amin Of Axis 1")
print(minOfAxisOne)
maxOfAxisOne = np.amax(sampleArray, 0)
print("Printing amax Of Axis 0")
print(maxOfAxisOne)
"""
Borrado
"""
print("Printing Original array")
sampleArray = np.array([[34,43,73],[82,22,12],[53,94,66]])
print (sampleArray)
print("Array after deleting column 2 on axis 1")
sampleArray = np.delete(sampleArray , 1, axis = 1)
print (sampleArray)
arr = np.array([[10,10,10]])
print("Array after inserting column 2 on axis 1")
sampleArray = np.insert(sampleArray , 1, arr, axis = 1)
sampleArray = np.insert(sampleArray , 1, arr, axis = 1)
print (sampleArray)
|
34c6214023a3329e43f990d4fdd0d9311d36e8b8 | JokerTongTong/Numpy_learn | /3.12计算阶乘.py | 284 | 3.5625 | 4 | # 3.12计算阶乘
import numpy as np
'''
prod() cumprod()
函数1:prod() 计算一个数的阶乘
函数2:cumprod() 计算一组数的阶乘
'''
a = np.arange(1,11)
print('a',a)
a_res = a.prod()
print('10!',a_res)
a_res1_10 = a.cumprod()
print('1~10阶乘:',a_res1_10)
|
13242cfb6e6b66bf30bf76106aa94fdb8095eff5 | dpassen/project_euler | /python_project_euler/Euler12.py | 416 | 3.53125 | 4 | #!/usr/bin/env python
from math import sqrt, ceil
from itertools import count
def triangle_number(num):
return (num * (num + 1)) // 2
def get_factors(num):
for i in range(1, int(ceil(sqrt(num)))):
if not num % i:
yield i
yield num // i
print(
next(
t
for t in (triangle_number(i) for i in count())
if len(list(get_factors(t))) > 500
)
)
|
18dc4f2637fee7edadcf95ebf9d717aae1dbfd6d | Nityam79/pythonPractice | /prac5/numuni.py | 256 | 3.828125 | 4 | import numpy as np
array1 = np.array([0, 11, 21, 41, 61, 91])
print("Array1: ",array1)
array2 = [5, 31, 9, 51, 71]
print("Array2: ",array2)
print("Unique sorted array of values that are in either of the two input arrays:")
print(np.union1d(array1, array2)) |
8ff224b169653b297ee85c1898525a65d20845f6 | Alexandra-Sontu/cele-15-probleme | /problema8 IF.py | 531 | 3.875 | 4 | """Să se afişeze cel mai mare număr par dintre doua numere introduse în calculator. Exemple : Date de intrare 23 45 Date de
ieşire nu exista numar par ; Date de intrare 28 14 Date de ieşire 28 ; Date de intrare 77 4 Date de ieşire 4."""
a=int(input("primului numar"))
b=int(input("al doilea numar"))
if ((a%2==0)and(b%2==0)):
if a>b:
print(a)
else:
print(b)
if ((a%2==0)and(b%2!=0)):
print(a)
if ((a%2!=0)and(b%2==0)):
print(b)
if ((a%2!=0)and(b%2!=0)):
print("Nu avem numere pare") |
8925c1f4bc4702b05b48c1a0c653b1d05fd41fc4 | c3ypt1c/Lucky-Name-Numbers | /engine.py | 2,271 | 3.625 | 4 | # WJEC Controlled Asessment
# Luck Name Numbers 2016
# Python 3.3.2/3.5.2
import time
def adder(a): #Defines function adder
while len(str(a)) != 1: #Loops while the size of the string of the number a isn't 1
b = 0
for x in str(a): b += int ( x ) #Adds every current "a" value.
a = int(b) #Sets the value of b as a.
return a
#List for letters, values, meanings (will be used later)
letters = [" ","-","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
value = [0,0,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8]
meaning = ["Natural leadders","Natural peacemakers","Creative and optimistic","Hard worker","Value freedom","Carers and providers","Thinkers","Have diplomatic skills","Selfless and generous"]
#Welcome Message
print(" o----------------------------------------------------------------o\n")
print(" | :: | Lucky Name number calcualtor v1.0.1 (28/02/2017) |\n")
print(" o----------------------------------------------------------------o\n")
# Assigns the first name to a varible
firstName = input("Please enter your, first name: ").lower()
# Assigns the sure name to a varible
surName = input("Please enter your, surname: ").lower()
##print("Is your name" ,firstName ,surName," If so wait six seconds if not retun the code")
## time.sleep( 6 ) #What's the point of this?
# Values for first name and surname will be used to find the person lucky name numbers
totalFirstname = 0
totalSurname = 0
totalName = 0
nameMeaning = 0
# Changes letters to corresponding value in firstname
for letter in firstName: totalFirstname += (value [letters.index(letter)])
# Changes letters to corresponding value in surname
for letter in surName: totalSurname += (value [letters.index(letter)])
# Prints total first name value
print("The value of your Firstname is: ", totalFirstname)
# Prints total sur name value
print("The value of your Surname is: ", totalSurname)
# Adds up total firstname and total surname together
totalName = int(totalFirstname) + int(totalSurname)
totalName = adder(totalName)
print("The value for your full name is", totalName)
#Prints lucky name meaning.
nameMeaning = int(totalName) - 1
print ("Your lucky name meaning is: ", meaning[nameMeaning])
|
5dc9ce1430ade9b7aebe04423f643552b938b495 | ppitu/Python | /Studia/Cwiczenia/Zestaw6/Zad5/fracs.py | 1,366 | 3.578125 | 4 | import math
def nwd(x, y):
zmienna = math.gcd(x, y)
return Frac(x/zmienna, y/zmienna)
class Frac:
"""Klasa reprezentujaca ulamek."""
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __str__(self):
if self.y == 1:
return "{}".format(self.x)
else:
return "{}/{}".format(self.x, self.y)
def __repr__(self):
return "Frac({}, {})".format(self.x, self.y)
def __add__(self, other):
if other.x == 0:
return nwd(self.x, self.y)
if self.x == 0:
return nwd(other.x, other.y)
if self.y == other.y:
return nwd(self.x + other.x, self.y)
else:
return nwd(self.x*other.y + other.x*self.y, self.y*other.y)
def __sub__(self, other):
if self.x == 0:
return nwd(-other.x, other.y)
if other.x == 0:
return nwd(self.x, self.y)
if self.y == other.y:
return nwd(self.x - other.x, self.y)
else:
return nwd(self.x*other.y - other.x*self.y, self.y*other.y)
def __mul__(self, other):
return nwd(self.x*other.x, self.y*other.y)
def __truediv__(self, other):
return nwd(self.x*other.y, self.y*other.x)
def __pos__(self):
return self
def __neg__(self):
return nwd(-self.x, self.y)
def __invert__(self):
return nwd(self.y, self.x)
def __eq__(self, other):
if self.x == other.x and self.y == other.y:
return True
else:
return False
def __float__(self):
return self.x/self.y
|
7019e2cb4fcf23193a692bd89075c1745e7dabf5 | JordanHolmes/cp1404practicals | /prac_03/Extension & Practice work/word_generator.py | 1,124 | 4.125 | 4 | """
CP1404/CP5632 - Practical
Random word generator - based on format of words
Another way to get just consonants would be to use string.ascii_lowercase
(all letters) and remove the vowels.
"""
import random
VOWELS = "aeiou"
CONSONANTS = "bcdfghjklmnpqrstvwxyz"
MENU = """Pick the format of the word
(C) for constants
(V) for vowels
eg. ccvc"""
def main():
invalid_format = False
while invalid_format is False:
print(MENU)
word_format = str(input(">>> ")).lower()
if is_valid_format(word_format) == True:
invalid_format = True
else:
print("Invalid format")
word = ""
for kind in word_format:
if kind == "c":
word += random.choice(CONSONANTS)
else:
word += random.choice(VOWELS)
print(word)
def is_valid_format(word_format):
invalid_character = 0
for char in word_format:
if char == "c" or char == "v":
pass
else:
invalid_character += 1
if invalid_character == 0:
return True
main()
# TODO: Validate user input string if it's an empty string
|
049e0a057caa1c5e641f848ee02d096828d928c6 | janellecueto/HackerRank | /Python/Collections/CollectionsCounter.py | 420 | 3.640625 | 4 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import Counter
X = int(input())
shoes = Counter(list(input().split()))
N = int(input())
money = 0
for i in range(N):
#add price to money if shoe still exists
size, price = input().split()
if size in shoes.elements():
money += int(price)
shoes.subtract({size: 1}) #subtract from this size
print(money)
|
1669f0cd9a6fcfed515b02817127e43f8410e9cf | soumya9988/Python_Machine_Learning_Basics | /Python_Basic/6_Strings/dna_assignment.py | 2,891 | 4.28125 | 4 |
def get_length(dna):
""" (str) -> int
Return the length of the DNA sequence dna.
>>> get_length('ATCGAT')
6
>>> get_length('ATCG')
4
"""
return len(dna)
def is_longer(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna1 is longer than DNA sequence
dna2.
>>> is_longer('ATCG', 'AT')
True
>>> is_longer('ATCG', 'ATCGGA')
False
"""
return len(dna1) > len(dna2)
def count_nucleotides(dna, nucleotide):
""" (str, str) -> int
Return the number of occurrences of nucleotide in the DNA sequence dna.
>>> count_nucleotides('ATCGGC', 'G')
2
>>> count_nucleotides('ATCTA', 'G')
0
"""
count = 0
for char in dna:
if char == nucleotide:
count += 1
return count
def contains_sequence(dna1, dna2):
""" (str, str) -> bool
Return True if and only if DNA sequence dna2 occurs in the DNA sequence
dna1.
>>> contains_sequence('ATCGGC', 'GG')
True
>>> contains_sequence('ATCGGC', 'GT')
False
"""
pos = dna1.find(dna2)
if pos >= 0:
return True
else:
return False
def is_valid_sequence(dna):
"""
(str) --> bool
Return True if and only if the DNA sequence is valid (that is, it contains no characters other than
'A', 'T', 'C', 'G'.
>>> is_valid_sequence('ATCGGC')
True
>>> is_valid_sequence('ATCGGP')
False
>>> is_valid_sequence('ATCGGc')
False
"""
for char in dna:
if char.islower() or char not in 'ATCG':
return False
return True
def insert_sequence(dna1, dna2, ind):
"""
(str, str, int) --> str
Return the DNA sequence obtained by inserting the second DNA sequence into the
first DNA sequence at the given index.
>>> insert_sequence('CCGG', 'AT', 2)
CCATGG
>>> insert_sequence('AAAG', 'CC', -3)
ACCAAG
>>> insert_sequence('AG', 'TT', 0)
TTAG
"""
dna = ""
if ind > 0:
dna = dna1[:ind] + dna2 + dna1[ind:]
elif ind < 0:
ind1 = len(dna1) + ind
dna = dna1[:ind1] + dna2 + dna1[ind1:]
else:
dna = dna2 + dna1
return dna
def get_complement(dna):
"""
(str) --> str
Return the nucleotide's complement.(A <-> T, C <-> G)
>>> get_complement('A')
T
>>> get_complement('G')
C
"""
if dna == 'A': return 'T'
elif dna == 'T': return 'A'
elif dna == 'C': return 'G'
elif dna == 'G': return 'C'
def get_complementary_sequence(dna):
"""
(str) --> str
Return the DNA sequence that is complementary to the given DNA sequence.
>>> get_complementary_sequence('ATGG')
TACC
>>> get_complementary_sequence('CCCAAA')
GGGTTT
"""
dna_seq = ''
for nucleotide in dna:
dna_seq += get_complement(nucleotide)
return dna_seq
|
1adcfc66e6657219a72c7ff0b7897ddb3586a6cd | Rolodophone/various-python-programs | /Completed/Search Day Robot Wars Game/Search Day Robot Wars Game.py | 7,794 | 3.734375 | 4 | import random
PAGE_SPLIT = "\n" * 60
robotList = None
players = None
NUM_OF_PLAYERS = None
MAX_NAME_LENGTH = 50
WINNING_SCORE = 5
def main():
loadRobots()
loadSettings()
endGame(cardGame2(NUM_OF_PLAYERS))
def loadRobots():
global robotList
#read robot names into robotList
with open("robots.txt", "r") as robotsFile:
robotList = robotsFile.read().splitlines()
def loadSettings():
global NUM_OF_PLAYERS
#read settings into variables
with open("settings.txt", "r") as settingsFile:
settings = settingsFile.read().splitlines()
NUM_OF_PLAYERS = int(settings[0].split("=")[1])
def cardGame():
scores = [None, 0, 0]
#repeats on a per-round basis
while scores[1] < 3 and scores[2] < 3:
#set card values to a random value
(name1, armour1, speed1, weapon1) = (random.choice(robotList), random.randint(0, 100), random.randint(0, 100), random.randint(0, 100))
robotList.remove(name1)
(name2, armour2, speed2, weapon2) = (random.choice(robotList), random.randint(0, 100), random.randint(0, 100), random.randint(0, 100))
robotList.remove(name2)
print(PAGE_SPLIT + "Your robot is {}. It has {} armour, {} speed, and {} weapon".format(name1, armour1, speed1, weapon1))
#menu for choosing what property to challenge opponent with
while True:
choice = input("Do you choose to challenge your opponent with your [A]rmour, [S]peed, or [W]eapon?\n").lower()
if choice == "a":
player1Value = armour1
player2Value = armour2
break
elif choice == "s":
player1Value = speed1
player2Value = speed2
break
elif choice == "w":
player1Value = weapon1
player2Value = weapon2
break
else:
input("'{}' is not an option. Press ENTER to try again.".format(choice))
#print opponent's values
print("Player 2 is the robot {}. It has {} armour, {} speed, and {} weapon".format(name2, armour2, speed2, weapon2))
#evaluate who won the round
if player1Value > player2Value:
winningPlayer = 1
elif player2Value > player1Value:
winningPlayer = 2
else:
winningPlayer = False
#print who won the round and update scores
if winningPlayer:
print("Player {} wins the round! They get 1 point!".format(winningPlayer))
scores[winningPlayer] += 1
print("The scores are now: player1 - {}, player2 - {}".format(scores[1], scores[2]))
else:
print("It's a draw! No one gets a point.\n\n")
input("Press ENTER to continue")
#evaluate and print winner
print(PAGE_SPLIT + "The game has ended.")
if scores[1] >= 3:
print("Player 1 wins!")
elif scores[2] >= 3:
print("Player 2 wins!")
else:
print("It's a draw!")
class Player:
def __init__(self, name, score=0):
self.name = name
self.score = score
class Robot:
def __init__(self, name, armour, speed, weapon):
self.name = name
self.armour = armour
self.speed = speed
self.weapon = weapon
def findPlayerWithHighestAttr(attr):
valuesList = []
for player in players:
valuesList.append(getattr(player, attr))
if len(valuesList) == len(set(valuesList)): #check for duplicates in list
return players[valuesList.index(max(valuesList))]
else:
return None
def printScores():
for player in players:
nameLength = len(player.name)
if nameLength < MAX_NAME_LENGTH - 3:
numOfDots = MAX_NAME_LENGTH - nameLength
else:
numOfDots = 0
print("{}{}...{}".format(player.name, "." * numOfDots, player.score))
def cardGame2(NUM_OF_PLAYERS):
global players
print(PAGE_SPLIT)
#create players
players = []
for i in range(NUM_OF_PLAYERS):
name = input("What would you like player {} to be called?".format(i + 1)) #i + 1 to get from players 0 & 1 to players 1 & 2
players.append(Player(name))
#repeat every round until someone wins
while True:
#check if there are enough robots for the round
if len(robotList) < NUM_OF_PLAYERS ** 2:
input(PAGE_SPLIT + "Oops! We've run out of robot names! Press ENTER to continue.")
return findPlayerWithHighestAttr("score")
#repeat every turn
for playerWhosTurnItIs in players:
print(PAGE_SPLIT + "It is {}'s turn".format(playerWhosTurnItIs.name))
#create robots for players
for player in players:
player.robot = Robot(random.choice(robotList), random.randint(0, 100), random.randint(0, 100), random.randint(0, 100))
robotList.remove(player.robot.name)
print("Your robot is {}. It has {} armour, {} speed, and {} weapon".format(playerWhosTurnItIs.robot.name, playerWhosTurnItIs.robot.armour, playerWhosTurnItIs.robot.speed, playerWhosTurnItIs.robot.weapon))
#menu for choosing what property to challenge opponent with
while True:
choice = input("\nDo you choose to challenge your opponent(s) with your [A]rmour, [S]peed, or [W]eapon?\n").lower()
if choice == "a":
for player in players:
player.chosenValue = player.robot.armour
break
elif choice == "s":
for player in players:
player.chosenValue = player.robot.speed
break
elif choice == "w":
for player in players:
player.chosenValue = player.robot.weapon
break
else:
input("'{}' is not an option. Press ENTER to try again.".format(choice))
print("\n\n")
#print opponents' robots
for player in players:
if player != playerWhosTurnItIs:
print("{} has the robot {}. It has {} armour, {} speed, and {} weapon".format(player.name, player.robot.name, player.robot.armour, player.robot.speed, player.robot.weapon))
#evaluate who won the round and update scores
winningPlayer = findPlayerWithHighestAttr("chosenValue")
if winningPlayer:
print("\n{} has won this turn.".format(winningPlayer.name))
winningPlayer.score += 1
else:
print("\nIt's a draw! No one gets a point.")
#print scores
print("\nThe scores are:")
printScores()
input("\nPress ENTER to continue.")
#check if anyone has won
for player in players:
if player.score >= WINNING_SCORE:
return player
def endGame(winningPlayer):
print(PAGE_SPLIT + "The game has ended. Here are the final scores:")
printScores()
input("Press ENTER to continue.")
if winningPlayer != None:
input(PAGE_SPLIT + "{} has won the game!".format(winningPlayer.name))
else:
input("\n\nIt's a tie!")
main()
|
f44096f61a4c4d271f7644305480461b01703975 | hemanthmalik/dsa | /sorting/quick_sort.py | 472 | 3.578125 | 4 | def quick_sort(arr, l, r): # T(n)=O(n) S(n)=O(1)
if r-l <= 1:
return arr
yellow = green = l+1
while green < r:
if arr[green] <= arr[l]:
arr[yellow], arr[green] = arr[green], arr[yellow]
yellow += 1
green += 1
arr[l], arr[yellow-1] = arr[yellow-1], arr[l]
quick_sort(arr, l, yellow-1)
quick_sort(arr, yellow, r)
mylist = list(range(100, 0, -1))
quick_sort(mylist, 0, len(mylist))
print(mylist) |
6ff1149d3ccd604406fae2f58c1118d0db2b3076 | ani03sha/Python-Language | /15_numpy/05_zeros_and_ones.py | 385 | 4.09375 | 4 | # You are given the shape of the array in the form of space-separated integers, each integer representing the size of
# different dimensions, your task is to print an array of the given shape and integer type using the tools
# numpy.zeros and numpy.ones.
import numpy
n = tuple(map(int, input().split()))
print(numpy.zeros(n, dtype=numpy.int))
print(numpy.ones(n, dtype=numpy.int))
|
1f8e043ada99a61c73f2184a4b7ebc99fac3ec74 | vai-agr/MonteCarloSim-Laplace-Poisson | /poisson_solution.py | 1,818 | 3.734375 | 4 | import random_walk as rw #imported random_walk.py for using the randomWalk1D function
import matplotlib.pyplot as plt #for graphing functions
number_of_walks = 200 #Number of random walks for each point
step_size = 1 #Distance between each point = 1cm i.e. 10 divisions
length = 20 #Distance between the plates of the capacitor= 10cm
boundary_voltages = [0,10] #Voltages of the two plates of the capacitor in Volts
epsilon_o = 8.85e-12 #Permittivity of free space
rho = 1e-13 #Charge density in C/m^3
if __name__ == "__main__": #the main part
f = -rho/epsilon_o #RHS of the Poisson equation
F = []
P_a = []
points = [i for i in range(0,length+step_size,step_size)]
for point in points:
(ans,prob) = rw.randomWalk1D(number_of_walks,point,[0,length],step_size) #length starts at 0
#print(ans)
P_a.append(prob) #Probability of reaching boundary(whilst Random Walking) for all the points
F.append(f*sum([len(i) for i in ans])*(step_size**2)*10e-4/number_of_walks) #count number of points in each call to the randomWalk1D function
#print(F)
print(P_a)
voltage_final = [(i*boundary_voltages[1]+ (1-i)*boundary_voltages[0])-j for i,j in zip(P_a,F)] #calculated voltages at all points using Monte Carlo methods
voltage_actual = [boundary_voltages[0]+(i/length)*(boundary_voltages[1]- boundary_voltages[0])-(i**2)*(0.5*rho/epsilon_o)*10e-4 for i in points] #actual distribution of voltages across the points
p1 = plt.plot(voltage_final, marker='o', markersize=4)
p2 = plt.plot(voltage_actual)
plt.title("POISSON EQUATION")
plt.xlabel("Distance from the low voltage capacitor plate (in cm)")
plt.ylabel("Voltage (in Volts)")
plt.xticks(range(0,length+step_size,2*step_size))
plt.legend((p1[0], p2[0]),('Calculated Voltage', 'Actual Voltage'))
plt.show() |
94c5e004150a0b33813066c72644c3a1514d6871 | miyazi777/learn_python | /dictionary.py | 579 | 3.5 | 4 | dic = {'item1': 100, 'item2': 200, 'item3': 300}
# access
print(dic['item1']) # 100
# add
dic['item4'] = 400
print(dic) # item1:100, item2:200, item3:300, item4:400
# update
dic['item1'] = 120
print(dic['item1']) # 120
# delete
del dic['item4']
print(dic) # item1:100, item2:200, item3:300
# key check
print('item1' in dic.keys()) # True
print('itemX' in dic.keys()) # Fals
# get keys
print(dic.keys()) # ['item1', 'item2', 'item3']
# get values
print(dic.values()) # [120, 200, 300]
# get items
print(dic.items()) # [('item1':120), ('item2':200), ('item3':300)]
|
3c110838842360d524a4254424f28b6af5a012f2 | Tanmay53/cohort_3 | /submissions/sm_009_chinmay/week_13/day_4/part_2/count_unique.py | 144 | 3.84375 | 4 | # Given a list of items find the unique no of present (HINT: Use Sets)
list = ['a','a','a','b', 'c', 'a' ]
unique = set(list)
print(len(unique)) |
0cd9b1664799e380cbb7dfa3fd982f00fd4a016f | elena-off/sssp-loihiemulator | /RandomGraphGenerator.py | 3,998 | 3.5625 | 4 | import matplotlib.pyplot as plt
import numpy as np
import random
import time
import networkx, random
import math
# random seed from current time
random.seed(time.time())
#generate a random graph dictionary given number of nodes, probability of connection between the nodes and maximal cost
def random_graph_dict(num_nodes,prob_connection,max_cost):
graphinfo = {}
graphinfo["num_nodes"] = num_nodes
#generate random graph via networkx
random_graph = networkx.binomial_graph(num_nodes, prob_connection)
edges = []
costs_edges = []
for edge in random_graph.edges():
edges.append(edge)
#assign random costs to edges
costs_edges.append(random.randint(1,max_cost))
graphinfo["edge_tuples"] = edges
graphinfo["costs_edges"] = np.array(costs_edges,dtype = np.uint8)
#calculate number of necessary to display sum of all costs as binary number
cost_sum = np.sum(costs_edges)
try:
graphinfo["num_bits"] = int(math.ceil(math.log(cost_sum,2)))
except:
return
return graphinfo
#calculate SSSP solution using Dijkstra given an adjacency matrix of a graph
def dijkstra(adjacency_matrix):
#all distances at beginning are infinity except distance to source node, which is 0
distances = [float("inf") for _ in range(len(adjacency_matrix))]
distances[0] = 0
# set of visited nodes, False if node was not yet visited
visited = [False for _ in range(len(adjacency_matrix))]
# While not all nodes have been visited yet:
while True:
#find note with the shortest distance to start node from set of unvisited nodes
shortest_distance = float("inf")
shortest_index = -1
for i in range(len(adjacency_matrix)):
if distances[i] < shortest_distance and not visited[i]:
shortest_distance = distances[i]
shortest_index = i
if shortest_index == -1:
# if all nodes have been visited, the algorithm is finished
return distances
# for all neighboring nodes that haven't been visited yet
for i in range(len(adjacency_matrix[shortest_index])):
#replace current path with shorter path (if there is one)
if adjacency_matrix[shortest_index][i] != 0 and distances[i] > distances[shortest_index] + adjacency_matrix[shortest_index][i]:
distances[i] = distances[shortest_index] + adjacency_matrix[shortest_index][i]
visited[shortest_index] = True
#list of graph dicts
graph_dicts = []
#create 10 random graphs with random number of nodes between 2 and 10, probabilty of connection between 0.5 and 1
#and max cost of 10 for each edge
for i in np.arange(10):
num_nodes = random.randint(2,10)
prob_connection = random.uniform(0.5,1)
max_cost = 10
graphinfo = random_graph_dict(num_nodes,prob_connection,max_cost)
if graphinfo:
graph_dicts.append(graphinfo)
# make dijkstra distance dict with solutions from dijkstra
dijkstra_distances = []
i = 0
for graphinfo in graph_dicts:
edge_tuples = graphinfo["edge_tuples"]
costs_edges = graphinfo["costs_edges"]
num_nodes = graphinfo["num_nodes"]
#calculate adjacency matrix from graph dictionary
adjacency_matrix = np.zeros((num_nodes,num_nodes))
for ((nodeA,nodeB),cost) in zip(edge_tuples,costs_edges):
adjacency_matrix[nodeA][nodeB] = cost
#if dijkstra solution exists, append it to dijkstra list; else, delete graph dict because it will not have a solution either
try:
dijkstra_distances.append([int(x) for x in dijkstra(adjacency_matrix)])
except:
graph_dicts.remove(graphinfo)
#write graph dicts and dijkstra solutions into file, to input into calculation network and compare results
f = open("ExampleDicts.txt", "a")
f.write(str(graph_dicts))
f.write(str(dijkstra_distances))
f.close()
|
2f76a05c4f8d9286453f0713cad7edf1b982f8a8 | BrandMeredith/exam_builder | /submenu.py | 1,955 | 3.71875 | 4 | import sys
class Submenu:
'''Display a menu and respond to choices when run.'''
def __init__(self,menu):
self.sections = list(menu.full_problem_list.chapter_section_list) #copy list
self.uncovered_sections = list(menu.uncovered_sections) #copy list
self.covered_sections = list(menu.covered_sections) #copy list
def display_menu(self):
print 'Enter section. 0 to quit.'
print '\n\033[4m'+'Sections'+'\033[0m'+' '+'\033[4m'+'Coverage'+'\033[0m' #funny control sequence is underline
for section in self.sections:
if float(section) in self.covered_sections:
print ' '+str(section) #gap to right column: 17 spaces
else:
print ' '+str(section) #gap to left column: 3 spaces
def run(self):
'''Display the menu and respond to choices.'''
while True:
self.display_menu()
choice = raw_input("Enter an option: ")
if choice == '0':
break
try:
if float(choice) in self.sections:
self.swap(choice)
else:
print str(choice)+' is invalid. Try again.'
except:
print str(choice)+' is invalid. Try again.'
def swap(self,choice):
choice_float = float(choice)
if choice_float in self.covered_sections:
self.covered_sections.remove(choice_float)
self.uncovered_sections.append(choice_float)
elif choice_float in self.uncovered_sections:
self.covered_sections.append(choice_float)
self.uncovered_sections.remove(choice_float)
self.update_sections()
def update_sections(self):
self.sections = sorted(list(set(self.sections)))
self.uncovered_sections = sorted(list(set(self.uncovered_sections)))
self.covered_sections = sorted(list(set(self.covered_sections))) |
8eb1d7ceec45461930294acccf2ed5d3c2f5d4ab | guodafeng/pythondev | /algorithm/qsort.py | 701 | 3.796875 | 4 | def qsort(s,left,right):
if left >= right:
return s
l = left
r = right
k = s[l]
flag = True # True means minus r
while l < r:
if flag:
if s[r] < k:
s[l] = s[r]
flag = False
else:
r -= 1
else:
if s[l] > k:
s[r] = s[l]
flag = True
else:
l += 1
m = r
if flag:
m = l
s[m] = k
qsort(s, left, m-1)
qsort(s, m+1, right)
return s
return
if __name__ == '__main__':
s = list('abezjklabkadkbeoaopywq')
print(s)
print(qsort(s,0,len(s)-1))
print(s)
|
2dfc76cc8779631c4de7b5a5ca885208e80e45d8 | doroshenkoam/android_vs_covid | /player.py | 2,259 | 3.5 | 4 | import pygame
import config as c
import auxiliary as a
# player - класс основного персонажа
class player(pygame.sprite.Sprite):
def __init__(self, x, y, width, height, font_health):
pygame.sprite.Sprite.__init__(self)
self.image = a.load_image("player.png").convert_alpha()
self.rect = self.image.get_rect(center=(x, y))
self.rect.x = x
self.rect.y = y
self.width = width
self.height = height
self.velocity = 10
self.is_jump = False
self.left = False
self.right = False
self.walk_count = 0
self.jump_count = 9
self.health = 100
self.font_health = font_health
def draw(self):
c.WIN.blit(self.image, (self.rect.x, self.rect.y))
text = self.font_health.render(f"Health: {self.health}", 1, (180, 0, 0))
c.WIN.blit(text, (400, 10))
def move(self, keys):
if keys[pygame.K_LEFT] and self.rect.x > self.velocity:
self.rect.x -= self.velocity
self.left = True
self.right = False
elif keys[pygame.K_RIGHT] and self.rect.x < 800 - self.width - self.velocity:
self.rect.x += self.velocity
self.left = False
self.right = True
else:
self.right = False
self.left = False
self.walk_count = 0
def jump(self, keys):
if not (self.is_jump):
if keys[pygame.K_SPACE] or keys[pygame.K_UP]:
self.is_jump = True
self.left = False
self.right = False
self.walk_count = 0
else:
if self.jump_count >= -9:
neg = 1
if self.jump_count < 0:
neg = -1
self.rect.y -= (self.jump_count ** 2) * neg
self.jump_count -= 1
else:
self.is_jump = False
self.jump_count = 9
def wound(self):
self.health -= 1
def kill(self, intro_font, point, viruses):
if self.health <= 0:
self.health = 100
self.rect.x = (800 - 130) / 2
self.rect.y = 375
a.game_over(intro_font, point, viruses) |
bb0f7a0e59fc30032433c0742202386778cc65cf | avvarga/Lab206 | /Python/OOP/car.py | 725 | 3.859375 | 4 | class car(object):
def __init__ (self,price,speed,fuel,mileage):
self.price=price
self.speed=speed
self.fuel=fuel
self.mileage=mileage
if price>10000:
self.tax= 0.15
else:
self.tax= 0.12
print self.display_all()
def display_all(self):
print "Price:",self.price
print "Speed:",self.speed,"mph"
print "Fuel:",self.fuel
print "Mileage:",self.mileage,"mpg"
print "Tax:",self.tax
# return self
car1= car(2000,35,"Full",15)
car2= car(2000,5,"Not Full",105)
car3= car(2000,15,"Kind of Full",95)
car4= car(2000,25,"Full",25)
car5= car(2000,45,"Empty",25)
car6= car(2000000,35,"Empty",15) |
4b2d09bc63f7ac5fdfd4b34b3c4a41fa7fc0a9ee | sad786/Python-Practice-Programs | /Python/Operator.py | 1,067 | 4.09375 | 4 | class Employee:
def __init__(self,salary,name,city):
self.salary = salary
self.name = name
self.city = city
def __add__(self,other):
self.salary = self.salary+other.salary
def __lt__(self,other):
return self.salary<other.salary
def __gt__(self,other):
return self.salary>other.salary
def __ge__(self,other):
return self.salary<=other.salary
def __le__(self,other):
return self.salary>=other.salary
def __eq__(self,other):
return self.salary==other.salary
def displayInfo(self):
print("Employee Name is ",self.name)
print("Employee Salary is ",self.salary)
print("Employee city is ",self.city)
emp1 = Employee(20000.00,"Saddam","Meerut")
emp2 = Employee(25000.00,'Rohit',"Mumbai")
emp1+emp2
print("*"*20)
emp1.displayInfo()
print("*"*20)
emp2.displayInfo()
if emp1<emp2:
print("{} has less salary than {}".format(emp1.name,emp2.name))
elif emp2<emp1:
print("{} has less salary than {}".format(emp2.name,emp1.name))
else:
print("{} and {} has equal salary".format(emp1.name,emp2.name))
|
20a1d086c7aa021e72b123094a026f08bd09b9b0 | doubledouLiu/python | /pythnonStudy/com/doubledou/study/use_python_study_python/test.py | 946 | 3.53125 | 4 | def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
class Rational(object):
def __init__(self, p, q):
self.p = p
self.q = q
def __add__(self, r):
return Rational(self.p * r.q + self.q * r.p, self.q * r.q)
def __sub__(self, r):
return Rational(self.p * r.q - self.q * r.p, self.q * r.q)
def __mul__(self, r):
return Rational(self.p * r.p , self.q * r.q)
def __div__(self, r):
return Rational(self.p * r.q, self.q * r.p)
def __str__(self):
g = gcd(self.p, self.q)
return '%s/%s' % (self.p / g, self.q / g)
__repr__ = __str__
import functools
sorted_ignore_case = functools.partial(sorted, )
print sorted_ignore_case(['bob', 'about', 'Zoo', 'Credit'])
if __name__ == '__main__':
r1 = Rational(1, 2)
r2 = Rational(1, 4)
print r1
print r2
print r1 + r2
print r1 - r2
print r1 * r2
print r1 / r2 |
22bbc4de252960bebeb3d10c9afb30dd29e2d106 | jmbosley/EulerProject | /Euler Project 56.py | 227 | 3.734375 | 4 | answer = 0
for a in range(100):
for b in range(100):
num = str(a**b)
temp = 0
for i in num:
temp = temp + int(i)
if temp > answer:
answer = temp
print(answer) |
ce287f60aa83213094bfda84fff4088d970feda7 | skavhaug/rasbeery | /raspberry.pi/rasbeery/mash.py | 2,082 | 3.546875 | 4 | from typing import List, Optional
import numpy as np
import matplotlib.pyplot as plt
from .water import WaterAdjustment
class MashStep:
def __init__(self, duration: int, temperature: float) -> None:
self.duration = duration
self.temperature = temperature
class Mash:
def __init__(self,
steps: List[MashStep],
start: Optional[int]=None,
water_adjustments: Optional[List[WaterAdjustment]]=None) -> None:
self._steps = steps
self._start = start
self._water_adjustments = water_adjustments
def set_mash_start(self, start_time) -> None:
self._start = start_time
def temperature(self, curr_time: int) -> float:
if self.start_time > curr_time > self.end_time:
return 0.0
tmp = self.start_time
for step in self._steps:
tmp += step.duration
if curr_time < tmp:
return step.temperature
else:
return 0.0
@property
def num_steps(self) -> int:
return len(self._steps)
@property
def duration(self) -> int:
return sum([s.duration for s in self._steps])
@property
def start_time(self) -> int:
return self._start
@property
def end_time(self) -> int:
return self._start + self.duration
def time_remaining(self, curr_time: int) -> int:
if self._start <= curr_time <= self.end_time:
return self.end_time - curr_time
elif curr_time >= self.end_time:
return 0
return np.nan
def mash_example():
mash_steps = [
MashStep(duration=60*30, temperature=64.),
MashStep(duration=60*30, temperature=68.),
MashStep(duration=60*15, temperature=80.),
]
mash = Mash(steps=mash_steps, start=0)
assert mash.temperature(1) == 64.
ts = np.arange(0, 60*75, 60, dtype='i')
temperature = np.fromiter((mash.temperature(t) for t in ts), dtype="f", count=len(ts))
plt.figure()
plt.plot(ts, temperature)
plt.show(block=True)
|
7c4855f151941740e2f72d9a0175601e291ec2ef | Maomaobadmonkey/Hangman-Game | /Hangman/task/hangman/hangman.py | 467 | 3.734375 | 4 | import random
print("H A N G M A N") # Write your code here
random.seed()
guess_words = ['python', 'java', 'kotlin', 'javascript']
picker = random.choice(guess_words)
guess_p = picker.replace('hon', '--')
guess_j = guess_p.rstrip('a') + '-'
guess_k = guess_j.replace('lin', '--')
guess_ja = guess_k.replace('ascript', '------')
print(f'Guess the word {guess_ja}:')
word = input()
if word == picker:
print('You survived!')
else:
print('You are hanged!')
|
95ea079fa38cdd6de70049f7eaba5da307a930fd | adi-varshney/TicTacToe | /TicTacToe_Version1.0.py | 3,528 | 3.984375 | 4 | from SimpleUserInteraction import position_choice
from Player import Player
playerList = []
def get_player_names():
count = 1
while count < 3:
name = input('Enter player ' + str(count) + ' name: ')
age = input('Enter player ' + str(count) + ' age: ')
playerList.append(Player(name, age, ''))
count = count+1
print('Hello ' + playerList[0].name + ' and ' + playerList[1].name + '. Welcome to Tic Tac Toe\n')
if playerList[0].age < playerList[1].age:
print('Since ' + playerList[0].name + ' is younger, ' + playerList[0].name + ' gets to choose the marker.')
playerList[0].chosenPlayer = True
return playerList[0]
else:
print('Since ' + playerList[1].name + ' is younger, ' + playerList[1].name + ' gets to choose the marker.')
playerList[1].chosenPlayer = True
return playerList[1]
def display_board(board):
clear_output()
print("Here is the current board")
print(board[1] + ' | ' + board[2] + ' | ' + board[3])
print('--|---|--')
print(board[4] + ' | ' + board[5] + ' | ' + board[6])
print('--|---|--')
print(board[7] + ' | ' + board[8] + ' | ' + board[9])
def clear_output():
print('\n' * 10)
def get_player_input(chosen_player):
marker = ''
player1 = ''
player2 = ''
while marker != "X" and marker != "O":
marker = input(chosen_player.name + ' , choose X or O: ').upper()
if marker != 'X' and marker != 'O':
print('Sorry invalid answer')
if marker == 'X':
if playerList[0].chosenPlayer:
playerList[0].marker = 'X'
playerList[1].marker = 'O'
else:
playerList[0].marker = 'O'
playerList[1].marker = 'X'
elif marker == 'O':
if playerList[0].chosenPlayer:
playerList[0].marker = 'O'
playerList[1].marker = 'X'
else:
playerList[0].marker = 'X'
playerList[1].marker = 'O'
if playerList[0].marker == 'X':
return playerList[0], playerList[1]
else:
return playerList[1], playerList[0]
def place_marker(board, marker, position):
board[position] = marker
def check_win(board):
is_winner = False
if ((board[1] == board[2] and board[2] == board[3]) or
(board[4] == board[5] and board[5] == board[6]) or
(board[7] == board[8] and board[8] == board[9]) or
(board[1] == board[4] and board[4] == board[7]) or
(board[2] == board[5] and board[5] == board[8]) or
(board[3] == board[6] and board[6] == board[9]) or
(board[1] == board[5] and board[5] == board[9]) or
(board[3] == board[5] and board[5] == board[7])):
is_winner = True
return is_winner
playerToChoose = get_player_names()
test_board = ['#', '1', '2', '3', '4', '5', '6', '7', '8', '9']
player1, player2 = get_player_input(playerToChoose)
display_board(test_board)
winner_mark = ''
while winner_mark == '':
place_marker(test_board, player1.marker, position_choice(player1.name))
display_board(test_board)
if check_win(test_board):
winner_mark = player1.name
break
place_marker(test_board, player2.marker, position_choice(player2.name))
display_board(test_board)
if check_win(test_board):
winner_mark = player2.name
break
print(winner_mark + ' , you won the game')
# print(check_player_marker())
|
4181e50f79ad0969f0e905d1c01374563ddfd0e8 | kaushik-42/Data_Science_Projects | /Project_2/data/process_data.py | 3,515 | 3.578125 | 4 | import sys
import pandas as pd
from sqlalchemy import *
def load_data(messages_filepath, categories_filepath):
'''All the loading steps including merging is in the next 3 lines'''
"""
args:
messages_filepath is the the messages dataframe present in the csv format
categories_filepath is the the messages dataframe present in the csv format
returns:
we get the merged dataframe
"""
messages = pd.read_csv(messages_filepath)
categories = pd.read_csv(categories_filepath)
df = pd.merge(messages, categories, on='id', how='outer')
return df
def clean_data(df):
'''All the cleaning steps that we performed like one coding data, splitting into categories.'''
"""
args:
The dataframe we got from the load_data method.
returns:
we get the cleaned dataframe after doing the pre-processing steps
"""
categories = df['categories'].str.split(";", expand=True)
row = categories.iloc[0]
category_colnames = list(map(lambda x: x.split("-")[0], categories.iloc[0].values.tolist()))
categories.columns = category_colnames
for column in categories:
# set each value to be the last character of the string
categories[column] = categories[column].str[-1]
# convert column from string to numeric
categories[column] = categories[column].apply(pd.to_numeric)
"""
I have gone through the official pandas docs and found one great method i.e duplicated()
dataframe.duplicated(subset=[col],keep=first)
'subset' is not necessary and 'keep' tells you about how to count that col as duplicated or not.
I'll be using this method to find out how many duplicates are present so that we can drop them for further processing!
"""
df=df.drop('categories',axis=1)
df = pd.concat([df, categories], axis=1)
df = df.drop_duplicates(keep='first')
return df
def save_data(df, database_filename):
'''Saves the cleaned dataframe to a table messages in the database given'''
"""
args:
df is the the cleaned data frame from the clean_data method
database_filename is the database filename where the data is stored currently
returns:
we convert the dataframe to sql
"""
engine = create_engine('sqlite:///'+ database_filename)
df.to_sql('messages', engine, index=False)
def main():
if len(sys.argv) == 4:
messages_filepath, categories_filepath, database_filepath = sys.argv[1:]
print('Loading data...\n MESSAGES: {}\n CATEGORIES: {}'
.format(messages_filepath, categories_filepath))
df = load_data(messages_filepath, categories_filepath)
print('Cleaning data...')
df = clean_data(df)
print('Saving data...\n DATABASE: {}'.format(database_filepath))
save_data(df, database_filepath)
print('Cleaned data saved to database!')
else:
print('Please provide the filepaths of the messages and categories '\
'datasets as the first and second argument respectively, as '\
'well as the filepath of the database to save the cleaned data '\
'to as the third argument. \n\nExample: python process_data.py '\
'disaster_messages.csv disaster_categories.csv '\
'DisasterResponse.db')
if __name__ == '__main__':
main()
|
6a91ce4f20234ff1d24fd341c2e9945799529eda | davidhawkes11/PythonStdioGames | /src/gamesbyexample/sierpinskisquare.py | 2,313 | 4.1875 | 4 | """Sierpinski Square, by Al Sweigart [email protected]
Draws the Sierpinski Square (also called Carpet) with turtle graphics.
More info at: https://en.wikipedia.org/wiki/Sierpinski_carpet"""
__version__ = 1
import turtle
turtle.tracer(100, 0) # Make the turtle draw faster.
# Setup the colors:
LIGHT_ORANGE = '#FFD78E'
BLUE = '#517DB2'
FG_COLOR = LIGHT_ORANGE
BG_COLOR = BLUE
def main():
turtle.bgcolor(BG_COLOR)
turtle.pencolor(FG_COLOR)
# Start the recursive drawing:
drawCarpet(-350, 350, 700, 700)
turtle.update() # Finish drawing the screen.
turtle.exitonclick() # When user clicks on the window, close it.
def drawCarpet(left, top, width, height):
if width < 5 or height < 5:
return
# Draw the outer rectangle:
turtle.penup()
turtle.goto(left, top)
turtle.pendown()
turtle.fillcolor(FG_COLOR)
turtle.begin_fill()
turtle.setheading(0)
turtle.forward(width)
turtle.right(90)
turtle.forward(height)
turtle.right(90)
turtle.forward(width)
turtle.right(90)
turtle.forward(height)
turtle.end_fill()
www = width / 3.0
hhh = height / 3.0
# Draw the inner rectangle:
turtle.penup()
turtle.goto(left + www, top - hhh)
turtle.pendown()
turtle.fillcolor(BG_COLOR)
turtle.begin_fill()
turtle.setheading(0)
turtle.forward(www)
turtle.right(90)
turtle.forward(hhh)
turtle.right(90)
turtle.forward(www)
turtle.right(90)
turtle.forward(hhh)
turtle.end_fill()
# Recursive calls for the eight surrounding sections:
# Draw in the top-left section:
drawCarpet(left, top, www, hhh)
# Draw in the top section:
drawCarpet(left + www, top, www, hhh)
# Draw in the top-right section:
drawCarpet(left + (www * 2), top, www, hhh)
# Draw in the left section:
drawCarpet(left, top - hhh, www, hhh)
# Draw in the right section:
drawCarpet(left + (www * 2), top - hhh, www, hhh)
# Draw in the bottom-left section:
drawCarpet(left, top - (hhh * 2), www, hhh)
# Draw in the bottom:
drawCarpet(left + www, top - (hhh * 2), www, hhh)
# Draw bottom-right:
drawCarpet(left + (www * 2), top - (hhh * 2), www, hhh)
try:
main()
except turtle.Terminator:
pass # Do nothing when the turtle window is closed.
|
25f8023f9c118dd50689b412b1bd1843b82e8801 | JefVerschuere/TikTakToe | /4Times4.py | 2,249 | 3.640625 | 4 | import random
import sys
from CheckIfSomeoneWon import *
def createBoard() :
board = []
for a in range (7) :
tabCollumn = []
for b in range(7) :
tabCollumn.append(" ")
board.append(tabCollumn)
return board
def insertInCollumn(numCollumn, board, car):
numCollumn = numCollumn - 1
for a in range(7) :
if board[numCollumn][a] == " ":
board[numCollumn][a] = car
return board
print("This collumn is full")
def printBoard(board):
print(" 1 2 3 4 5 6 7")
print("_____________________________")
print ("|",board[0][6], "|",board[1][6], "|",board[2][6], "|",board[3][6], "|",board[4][6], "|",board[5][6], "|",board[6][6], "|")
print ("|",board[0][5], "|",board[1][5], "|",board[2][5], "|",board[3][5], "|",board[4][5], "|",board[5][5], "|",board[6][5], "|")
print ("|",board[0][4], "|",board[1][4], "|",board[2][4], "|",board[3][4], "|",board[4][4], "|",board[5][4], "|",board[6][4], "|")
print ("|",board[0][3], "|",board[1][3], "|",board[2][3], "|",board[3][3], "|",board[4][3], "|",board[5][3], "|",board[6][3], "|")
print ("|",board[0][2], "|",board[1][2], "|",board[2][2], "|",board[3][2], "|",board[4][2], "|",board[5][2], "|",board[6][2], "|")
print ("|",board[0][1], "|",board[1][1], "|",board[2][1], "|",board[3][1], "|",board[4][1], "|",board[5][1], "|",board[6][1], "|")
print ("|",board[0][0], "|",board[1][0], "|",board[2][0], "|",board[3][0], "|",board[4][0], "|",board[5][0], "|",board[6][0], "|")
print("-----------------------------")
def isPair(x):
if x % 2 == 0 :
return True
else :
return False
StartingPlayer = random.randint(1,100)
if StartingPlayer / 2 == 0:
firstPlayer = 'O'
secPlayer = 'X'
else :
firstPlayer = 'X'
secPlayer = 'O'
board = createBoard()
for i in range(49):
printBoard(board)
if isPair(i) :
print("turn : ", i, " it's ", firstPlayer , "his turn type de collumn")
r = input()
board = insertInCollumn(int(r), board, firstPlayer)
if hasSomeoneWon(board) :
printBoard(board)
break
else :
print("turn : ", i, " it's ", secPlayer , "his turn type de collumn")
r = input()
board = insertInCollumn(int(r), board, secPlayer)
if hasSomeoneWon(board) :
printBoard(board)
break
|
62aba30ffd5ca65695ff7e069b85d716cbb5ff81 | jrez7/semester-1-exam- | /main.py | 837 | 3.78125 | 4 | #### Describe each datatype below:(4 marks)
## 4 =
## 5.7 =
## True =
## Good Luck =
#### Which datatype would be useful for storing someone's height? (1 mark)
## Answer
#### Which datatype would be useful for storing someone's hair colour?(1 mark)
## Answer
####Create a variable tha will store the users name.(1 mark)
####Create a print statement that will print the first 4 characters of the person's name.(3 marks)
####Convert the user's name to all uppercase characters and print the result
####Find out how many times the letter A occurs in the user's name
#### Create a conditional statement to ask a user to enter their age. If they are older than 18 they receive a message saying they can enter the competition, if they are under 18, they receive a message saying they cannot enter the competition.
|
6cc16056bd79060a9a16dccf297f8b6436f376a7 | joerocca-evolve/PyScriptPractice | /fruit_basket.py | 365 | 3.9375 | 4 | def guess_fruit(basket):
fruit_guess = input("Guess a fruit! Enter your guess below\n")
while fruit_guess not in basket:
fruit_guess = input("That fruit isn't in the basket. Try again!\n")
print("\nYou guessed correctly!")
def main():
fruit_basket = ["apple", "orange", "pear", "grape", "strawberry"]
guess_fruit(fruit_basket)
main()
|
cdf99f8a53c0d8df01b65865bc0392da2c176303 | Niccolum/intrst_algrms | /unpacking_flatten_lists/funcs.py | 4,339 | 3.859375 | 4 | """
Examples of python realization of solution for unpacking lists with indefinite depth
"""
from typing import Iterator, Iterable, List
from iteration_utilities import deepflatten
from more_itertools import collapse
# @profile
def outer_flatten_1(array: Iterable) -> List:
"""
Based on C realization of this solution
More on:
https://iteration-utilities.readthedocs.io/en/latest/generated/deepflatten.html
https://github.com/MSeifert04/iteration_utilities/blob/384948b4e82e41de47fa79fb73efc56c08549b01/src/deepflatten.c
"""
return deepflatten(array)
# @profile
def outer_flatten_2(array: Iterable) -> List:
"""
recursive algorithm, vaguely reminiscent of recursion_flatten. Based on next pattern:
.. code:: python
try:
tree = iter(node)
except TypeError:
yield node
more on:
https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.collapse
"""
return collapse(array)
# @profile
def niccolum_flatten(array: Iterable) -> List:
"""
Non recursive algorithm
Based on pop/insert elements in current list
"""
new_array = array[:]
ind = 0
while True:
try:
while isinstance(new_array[ind], list):
item = new_array.pop(ind)
for inner_item in reversed(item):
new_array.insert(ind, inner_item)
ind += 1
except IndexError:
break
return new_array
# @profile
def tishka_flatten(data: Iterable) -> List:
"""
Non recursive algorithm
Based on append/extend elements to new list
"""
nested = True
while nested:
new = []
nested = False
for i in data:
if isinstance(i, list):
new.extend(i)
nested = True
else:
new.append(i)
data = new
return data
# @profile
def zart_flatten(a: Iterable) -> List:
"""
Non recursive algorithm
Based on pop from old and append elements to new list
"""
queue, out = [a], []
while queue:
elem = queue.pop(-1)
if isinstance(elem, list):
queue.extend(elem)
else:
out.append(elem)
return out[::-1]
# @profile
def recursive_flatten_generator(array: Iterable) -> List:
"""
Recursive algorithm
Looks like recursive_flatten_iterator, but with extend/append
"""
lst = []
for i in array:
if isinstance(i, list):
lst.extend(recursive_flatten_generator(i))
else:
lst.append(i)
return lst
# @profile
def recursive_flatten_iterator(arr: Iterable) -> Iterator:
"""
Recursive algorithm based on iterator
Usual solution to this problem
"""
for i in arr:
if isinstance(i, list):
yield from recursive_flatten_iterator(i)
else:
yield i
# @profile
def tishka_flatten_with_stack(seq: Iterable) -> List:
"""
Non recursive algorithm
Based on zart_flatten, but build on try/except pattern
"""
stack = [iter(seq)]
new = []
while stack:
i = stack.pop()
try:
while True:
data = next(i)
if isinstance(data, list):
stack.append(i)
i = iter(data)
else:
new.append(data)
except StopIteration:
pass
return new
def profile():
import time
from unpacking_flatten_lists.data import (
generate_data,
create_data_increasing_depth,
create_data_decreasing_depth)
all_data = generate_data()
curr_data = all_data[-1][1]
funcs_generated_data = [
create_data_increasing_depth,
create_data_decreasing_depth
]
funcs = [
outer_flatten_1,
outer_flatten_2,
niccolum_flatten,
tishka_flatten,
zart_flatten,
recursive_flatten_generator,
recursive_flatten_iterator,
tishka_flatten_with_stack
]
for func_generated_data in funcs_generated_data:
creating_data = func_generated_data(**curr_data)
for func in funcs:
list(func(creating_data))
time.sleep(0.3)
if __name__ == '__main__':
profile()
|
37e5ffffe6565e845e4bd7e536d78b0431c3b9f0 | JaspreetSAujla/Rock_Paper_Scissors | /Python/RockPaperScissors.py | 4,021 | 4.0625 | 4 | import random
import time
import sys
class RockPaperScissors:
"""
A class which stores the code for a game of rock paper scissors.
The game is ran for as long as the user wants to play.
Class Variables:
OPTION_LIST = Stores a list of possible options the computer
can pick.
Methods:
__init__ = Defines the initial variables of the game.
run = Runs the main code for the game.
get_valid_user_choice = Asks the player for a choice and checks
to see if it is valid or not.
determine_winner = Uses if statements to determine the winner
of the game.
"""
OPTION_LIST = ["rock", "paper", "scissors"]
def __init__(self):
"""
Defines the inital variables of the game.
Variables:
self.user_choice = Stores the choice the user makes.
self.computer_choice = Stores the choice the computer makes.
self.play_again = Stores whether the user wants to play again.
"""
self.user_choice = None
self.computer_choice = None
self.play_again = "yes"
def run(self):
"""
Used to run the game.
Game keeps running until the user decides to stop.
"""
print("Welcome to rock paper scissors.")
time.sleep(2)
# Loop over for as long as the user wants to play.
while self.play_again == "yes":
# Computer picks a choice at random.
self.computer_choice = random.choice(RockPaperScissors.OPTION_LIST)
# Ask user for a choice, and check if valid or not.
self.get_valid_user_choice()
print(f"I picked {self.computer_choice}")
time.sleep(2)
#Compares the choices made and works out the winner.
self.determine_winner()
time.sleep(2)
#Asks the user if they want to play again.
self.play_again = input("Would you like to go again? \n(yes/no) \n")
input("ok then, press enter to exit \n")
sys.exit()
def get_valid_user_choice(self):
"""
Asks the user for a choice and performs while loop to see
if the choice is valid or not.
Variables:
valid_choice = Stores whether the user made a valid
choice.
"""
valid_choice = False
while valid_choice == False:
self.user_choice = input("What is your choice? \n(rock/paper/scissors) \n")
if self.user_choice in RockPaperScissors.OPTION_LIST:
valid_choice = True
else:
print("Invalid choice selected, try again.")
def determine_winner(self):
"""
Uses if statements to determine who won the game.
Compares the choices and uses the rules of rock paper scissors
to determine the winner.
"""
if self.user_choice == "rock":
if self.computer_choice == "rock":
print("It's a draw...")
elif self.computer_choice == "paper":
print("Yes, I win!")
elif self.computer_choice == "scissors":
print("There's always next time.")
elif self.user_choice == "paper":
if self.computer_choice == "rock":
print("Which means you win...")
elif self.computer_choice == "paper":
print("Therefore we draw.")
elif self.computer_choice == "scissors":
print("I win!")
elif self.user_choice == "scissors":
if self.computer_choice == "rock":
print("You lose!")
elif self.computer_choice == "paper":
print("You win...")
elif self.computer_choice == "scissors":
print("Hmm a draw.")
if __name__ == "__main__":
rps = RockPaperScissors()
rps.run() |
a64dc468ef0891df157993e38f28ad4afd8ee185 | jmery24/python | /ippython/funciones_minmax_310.py | 667 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu May 30 04:45:54 2013
@author: daniel
"""
#programa: funciones_minmax_310.py
#funcion que devuelve valores multiples mediante una lista
#funcion <minmax> devuelve valor minimo y maximo de una lista
#ejercicio 310
#definir funcion <minmax>
def minmax(listado):
minimo = min(listado)
maximo = max(listado)
return [minimo, maximo]
#cuerpo del programa
#data input
numero = int(raw_input('Numero de elementos de la lista: '))
lista = []
for i in range(numero):
valor = int(raw_input('Numero entero: '))
lista.append(valor)
#activa la funcion <minmax>
print 'valores minimo y maximo: ', minmax(lista) |
86725885dd69ae89a16fed4f245edd31415c0422 | popovale/python-stepic | /kurs2/Zadanie1_6_9.py | 351 | 3.609375 | 4 | import time
class Loggable:
def log(self, msg):
print(str(time.ctime()) + ": " + str(msg))
class LoggableList(Loggable, list):
def append(self, arg):
super(LoggableList, self).append(arg) # 1 способ
#list.append(self,arg) # 2 способ
self.log(arg)
x=LoggableList([1,3,4])
x.append('m')
print(x)
|
e20e23f7affd442a47a7a304056bf2f1c8133052 | 138818/test | /python2/day1/railway.py | 299 | 3.609375 | 4 | import time
def railway(length, speek):
print('#' * length, end='')
n = 0
while True:
time.sleep(speek)
print('\r%s>%s' % ('#' * n, '#' * (length-1 - n)), end='')
n += 1
if n == length:
n = 0
if __name__ == '__main__':
railway(30, 0.5)
|
f5398a3b9763da3b25e814144a8aa3a55c31015f | jianhui-ben/leetcode_python | /1109. Corporate Flight Bookings.py | 866 | 3.53125 | 4 | # 1109. Corporate Flight Bookings
# There are n flights that are labeled from 1 to n.
#
# You are given an array of flight bookings bookings, where bookings[i] = [firsti, lasti, seatsi] represents a booking for flights firsti through lasti (inclusive) with seatsi seats reserved for each flight in the range.
#
# Return an array answer of length n, where answer[i] is the total number of seats reserved for flight i.
class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
"""
prefix difference
"""
out = [0 for _ in range(n)]
for booking in bookings:
start, end, seats = booking
out[start - 1] += seats
if end < len(out):
out[end] -= seats
for i in range(1, len(out)):
out[i] += out[i - 1]
return out
|
2132d96f16254b6669064da1fa6d62a6fd969d86 | acmduzhuo/python | /Python_homework_2019-10-12/test/7.py | 181 | 3.703125 | 4 | result = []
for x in [1, 2, 3]:#寻找x
for y in [3, 1, 4]:#寻找y
if x == 1:#限制x
if x != y:#限制y
result.append((x, y))
print(result) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.