blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
f241713ebf9394a96b128136f72b441f04581999 | orofbrown/christmas-lights | /instructions.py | 3,219 | 3.75 | 4 |
def check_for_txt():
'''
Check if there's an accompanying .txt file which tells us
how the user wants the image animated
Commands available are:
NNNN speed S.SSS
Set the scroll speed (in seconds)
Example: 0000 speed 0.150
At position zero (first position), set the speed to 150ms
NNNN hold S.SSS
Hold the frame still (in seconds)
Example: 0011 hold 2.300
At position 11, keep the image still for 2.3 seconds
NNNN-PPPP flip S.SSS
Animate MATRIX_WIDTH frames, like a flipbook
with a speed of S.SSS seconds between each frame
Example: 0014-0049 flip 0.100
From position 14, animate with 100ms between frames
until you reach or go past position 49
Note that this will jump positions MATRIX_WIDTH at a time
Takes a bit of getting used to - experiment
NNNN jump PPPP
Jump to position PPPP
Example: 0001 jump 0200
At position 1, jump to position 200
Useful for debugging only - the image will loop anyway
'''
try:
with open(sys.argv[2], 'r') as f:
return f.read()
except:
return ''
def run_text_instructions(txt_idx, txt_lines, i, wait_len):
inc = 1
this_sleep = wait_len
if txt_idx < len(txt_lines):
match = re.search(
r"^(?P<start>\s*\d+)(-(?P<finish>\d+))?\s+((?P<command>\S+)(\s+(?P<param>\d+(\.\d+)?))?)$",
txt_lines[txt_idx],
re.M | re.I,
)
if match:
print("Found valid command line %d:\n%s" % (txt_idx, txt_lines[txt_idx]))
st = int(match.group("start"))
fi = st
print("Current pixel %05d start %05d finish %05d" % (i, st, fi))
if match.group("finish"):
fi = int(match.group("finish"))
if i >= st and txt_idx <= fi:
if match.group("command").lower() == "speed":
this_sleep = float(match.group("param"))
print("Position %d : Set speed to %.3f secs per frame" % (
i,
this_sleep,
))
elif match.group("command").lower() == "flip":
this_sleep = float(match.group("param"))
inc = MATRIX_WIDTH
print("Position %d: Flip for %.3f secs" % (i, this_sleep))
elif match.group("command").lower() == "hold":
this_sleep = float(match.group("param"))
print("Position %d: Hold for %.3f secs" % (i, this_sleep))
elif match.group("command").lower() == "jump":
print("Position %d: Jump to position %s" % (
i,
match.group("param"),
))
x = int(match.group("param"))
inc = 0
# Move to the next line of the text file
# only if we have completed all pixels in range
if i >= fi:
txt_idx += 1
else:
print("Found INVALID command line %d:\n%s" % (txt_idx, txt_lines[txt_idx]))
txt_idx += 1
return inc, txt_idx, this_sleep
|
8bba9a1fe8b8befefc00045d6cc10bb43e7b3401 | dimitar-daskalov/SoftUni-Courses | /python_basics/exams/python_basics_exam/02.py | 576 | 3.78125 | 4 | sleeve_size = float(input())
front_size = float(input())
material = input()
tie = input()
shirt_size = (((sleeve_size * 2) + (front_size * 2)) + (((sleeve_size * 2) + (front_size * 2)) * 0.10)) / 100
if material == "Linen":
price = shirt_size * 15
elif material == "Cotton":
price = shirt_size * 12
elif material == "Denim":
price = shirt_size * 20
elif material == "Twill":
price = shirt_size * 16
else:
price = shirt_size * 11
price = price + 10
if tie == "Yes":
price = price + (price * 0.20)
print(f"The price of the shirt is: {price:.2f}lv.") |
55f1826220c63779618b081a73b754bc37708f57 | siowyisheng/30-things-in-python | /22-geo-calculate-distance/snakes_distance.py | 730 | 3.65625 | 4 | from geopy.geocoders import Nominatim
from geopy.distance import geodesic
from pprint import pprint
geolocator = Nominatim(user_agent="snakes-distance-geopy")
school = geolocator.geocode("raffles institution singapore")
print('Snakey school is located at {}'.format(school.address))
print('Snakey school\'s coordinates are ({}, {}) '.format(
school.latitude, school.longitude))
home = geolocator.geocode("58 college green singapore")
print('Home is located at {}'.format(home.address))
home_coordinates = home.latitude, home.longitude
school_coordinates = school.latitude, school.longitude
distance = geodesic(home_coordinates, school_coordinates).km
print('The distance from home to school is {:.2f} km'.format(distance)) |
361696f13dc0ee1ae4acc1e39b6dfa937169ef55 | fangzhengo500/HelloPython | /chapter_2_sequence/chapter_2_3_list/chapter_2_3_1.py | 166 | 4.03125 | 4 | str = 'Hello'
lst = list(str)
print(lst)
# str[1] = 'a' #TypeError: 'str' object does not support item assignment
# print(str)
# print(lst)
lst[1] = 'a'
print(lst)
|
e5e9a22249b1ee755fdb089f12ac8d49d9cfef99 | amwelles/gdi-intro-python | /class2.py | 726 | 3.8125 | 4 | # parenthesis around predicates are NOT standard (weird)
# prescendence determines which order things are evaluated
# elif = elseif
# no switch/case statement -- could use dictionary
# tab size should be 4, according to standards
twenty_one = raw_input('are you over 21? (y/n) ')
if twenty_one == 'y':
print 'you may have a beer!'
how_many = raw_input('how many beers would you like? ')
how_many = int(how_many)
if how_many > 10:
print 'you got alcohol poisoning. :('
elif how_many > 3:
print 'oops, you\'re drunk!'
elif how_many >= 1:
print 'you got a little tipsy.'
else:
print 'so... I guess you\'re the designated driver.'
else:
print 'you may not have a beer.'
print 'but here, have a glass of juice!'
|
569042d80aa36cb42fcbd16a463b0756e277ed79 | dapolias/open-catalog-generator | /scripts/category-condenser.py | 4,989 | 3.515625 | 4 | #!/usr/bin/python
# James Tobat, 8/6/2014
# Replaces a value in the supplied JSON attribute
# with a new value, all of these arguments are supplied
# by the user
import json
import sys
import glob
import os
import argparse
import get_schemas as gs
import collections
# Builds command line menu, requires three string arguments, and provides a help menu when the -h option is used.
parser = argparse.ArgumentParser(description='Replace a given value in a JSON attribute with the user supplied value.')
parser.add_argument('JSON_Attribute', type=str, help='Attribute that contains value to be changed.')
parser.add_argument('Old_Value', type=str, help='The old value that will be replaced by the new value.')
parser.add_argument('New_Value', type=str, help='Replacement value.')
args = vars(parser.parse_args())
key_value = args['JSON_Attribute'] # Attribute that has value for replacement
old_value = args['Old_Value'] # Value to be replaced
new_value = args['New_Value'] # Replacement value
# Returns a JSON object from a file, with its order preserved.
def open_JSON(json_file):
try:
json_data = json.load(open(json_file), object_pairs_hook=collections.OrderedDict)
except Exception, e:
print "\nFAILED! JSON error in file %s" % json_file
print " Details: %s" % str(e)
sys.exit(1)
return json_data
# Replaces a value, matching the old value, with a new value
def replace_listvalue(list_name, old_value, new_value):
i = 0
changes = 0
for item in list_name:
if item == old_value:
list_name[i] = new_value
changes += 1
i += 1
return changes
# Changes a Categories value from one thing to another
# inside of a single JSON file
def update_JSON(json_file, old_value, new_value):
# Tries to load JSON data into program
json_data = open_JSON(json_file)
file_name = os.path.basename(json_file)
changes = 0
# Checks to see if the data contains only 1 JSON record
if isinstance(json_data, dict):
# Finds the matching value in Categories and replaces it
for key, value in json_data.iteritems():
if key == key_value:
if isinstance(value, list):
changes += replace_listvalue(value, old_value, new_value)
else:
if value == old_value:
json_data[key] = new_value
changes += 1
else:
# Goes through all JSON records in JSON file
for record in json_data:
# Finds the matching value in Categories and replaces it
for key, value in record.iteritems():
if key == key_value:
if isinstance(value, list):
changes += replace_listvalue(value, old_value, new_value)
else:
if value == old_value:
record[key] = new_value
changes += 1
# Only writes updated JSON file if something changed
if changes > 0:
try:
with open(json_file, 'w') as output:
json.dump(json_data, output, sort_keys = False, indent = 4, ensure_ascii=False)
except Exception, e:
print "\nFAILED! Could not update %s json file for %s" % (file_name, program_name)
print " Details: %s" % str(e)
print "Changed %i entries in %s" % (changes, file_name)
return changes
schemas = gs.get_schemas() # List of schemas from template file
# Determines the type of schemas given from the template file
for i in range(len(schemas)):
if i % 2 == 0:
if schemas[i] == "Publication":
pub_schema = schemas[i+1]
elif schemas[i] == "Software":
software_schema = schemas[i+1]
else:
program_schema = schemas[i+1]
found_key = False # Boolean which determines if the user's key was
# found in any of the JSON schemas
# Paths of all JSON file types in the open catalog
path_pub = '../darpa_open_catalog/*-pubs.json'
path_software = '../darpa_open_catalog/*-software.json'
path_program = '../darpa_open_catalog/*-program.json'
search_files = [] # List of files to search in for the given user value
# Determines what types of JSON files the attribute is located
# in and will only search those files.
if key_value in pub_schema:
found_key = True
search_files.extend(glob.glob(path_pub))
if key_value in software_schema:
found_key = True
search_files.extend(glob.glob(path_software))
if key_value in program_schema:
found_key = True
search_files.extend(glob.glob(path_program))
# Indicates the key was not found in any of the schemas, meaning that the attribute
# was probably misspelled
if not found_key:
print "Error: %s was not found in any of the JSON files.\nPlease make sure \
the attribute is spelled correctly." % key_value
changed = 0
# Updates each json file that requires a value to be replaced
# and then records the number of changes made.
for file_name in search_files:
changed += update_JSON(file_name, old_value, new_value)
# Indicates that no JSON file was changes meaning that the value to be replaced was
# not found.
if not changed:
print "No changes were made to any JSON files."
|
a2ea4615870d54e88b1111baede080687ecc95f6 | bmy4415/algorithm-and-interview | /baekjoon_online_judge/prob_17298.py | 735 | 3.515625 | 4 | '''
Problem URL: https://www.acmicpc.net/problem/17298
'''
import sys
import os
def solution(sequence):
stack = []
answer = [-1] * len(sequence)
for i, num in enumerate(sequence):
while stack and sequence[stack[-1]] < num:
_i = stack.pop()
answer[_i] = num # write NGE
stack.append(i)
return ' '.join([str(x) for x in answer])
if __name__ == '__main__':
# freopen equivalent
inputfile_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'input.txt')
sys.stdin = open(inputfile_path, 'r')
N = int(sys.stdin.readline().strip())
sequence = [int(x) for x in sys.stdin.readline().strip().split()]
print(solution(sequence))
|
fd08a734453d77de80c8f821a5cf14dc7c5428dd | le773/ud120-projects | /codeone/decision_tree/dt_author_id.py | 1,518 | 3.671875 | 4 |
"""
This is the code to accompany the Lesson 3 (decision tree) mini-project.
Use a Decision Tree to identify emails from the Enron corpus by author:
Sara has label 0
Chris has label 1
"""
import sys
from time import time
import os
sys.path.append(os.getcwd() + "\\codeone\\tools")
from email_preprocess import preprocess
### features_train and features_test are the features for the training
### and testing datasets, respectively
### labels_train and labels_test are the corresponding item labels
features_train, features_test, labels_train, labels_test = preprocess()
print("features_train:",len(features_train))
print("features_test:",len(features_test))
print("labels_train:",len(labels_train))
print("labels_test:",len(labels_test))
#########################################################
### your code goes here ###
from sklearn import tree
clf = tree.DecisionTreeClassifier()
t0 = time()
clf.fit(features_train, labels_train)
print "training time:", round(time()-t0, 3), "s"
#########################################################
t1 = time()
labels_predict = clf.predict(features_test)
print "predict time:", round(time()-t1, 3), "s"
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
print "accuracy_score:", accuracy_score(labels_predict, labels_test)
print "precision_score:", precision_score(labels_predict, labels_test)
print "recall_score:", recall_score(labels_predict, labels_test)
print "f1_score:", f1_score(labels_predict, labels_test)
|
0ea381cd0ace2d8a8c3a24df5f898adaf602eab6 | Taoge123/OptimizedLeetcode | /LeetcodeNew/Tree/LC_508_Most_Frequent_Subtree_Sum.py | 1,991 | 3.921875 | 4 |
"""
Examples 1
Input:
5
/ \
2 -3
return [2, -3, 4], since all the values happen only once, return all of them in any order.
Examples 2
Input:
5
/ \
2 -5
I have used a hash-map ctr to count the sum occurrence.
I have wrote a sub function countSubtreeSum to travel through a tree and return the sum of the tree.
In countSubtreeSum, I will travel through the left node and the right node,
calculate the sum of the tree, increment the counter ctr, and return the sum.
"""
"""
like others solutions,
computing the left subtree, then right and updating the current node ,
used an auxiliary hashmap that counts
h[s] = u
sum s has been reached u times
given a node and its (at most 2 subtrees), once the sum "sumleft" and "sumright" of the subtrees have been computed
then the current sum of the tree is node.val + "sumleft" + "sumright"
before returning it, update (increment) the hashmap
-----------
The idea is very simple:
Traverse structure using post order
Calculate sum of sub trees on every step
Store frequence of occurence of calculated sum into map/dict
Maintain max of frequence of occurence on every step. Letter we will use it to filter out result
Traverse map/dict and filter output based on max of frequence of occurence
Java implementation:
"""
import collections
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def findFrequentTreeSum(self, root):
if not root:
return []
self.max = -1
cache = collections.defaultdict(int)
self.helper(root, cache)
return [k for k, v in cache.items() if v == self.max]
def helper(self, root, cache):
if not root:
return 0
left = self.helper(root.left, cache)
right = self.helper(root.right, cache)
sum = root.val + left + right
cache[sum] += 1
self.max = max(self.max, cache[sum])
return sum
|
19708c1c830fb8829f3647783840db4945f15b00 | ybhuva/100-days-of-code | /Practice/Day_10.py | 1,041 | 4.1875 | 4 | ############## Docstring ########
def format_name (f_name, l_name):
"""Take a first and last name and format it to return the title case
version of the name."""
if f_name == "" or l_name == "":
return "You didn't provide valid inputs."
formated_f_name = f_name.title()
formated_l_name = l_name.title()
return f"Result: {formated_f_name} {formated_l_name}"
########### Exercise 1 (Functions with Output) #############
def is_leap(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
def days_in_month(year, month):
if month > 12 or month < 1:
return "Invalid Month"
month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if is_leap(year) and month == 2:
return 29
return month_days[month -1]
#🚨 Do NOT change any of the code below
year = int(input("Enter a year: "))
month = int(input("Enter a month: "))
days = days_in_month(year, month)
print(days)
|
c8a90db50a341198d364b29c402b3d086d40d4b3 | avibpy/pypie | /tictactoe.py | 3,354 | 3.921875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 11 12:31:11 2021
@author: avanishbidar
"""
my_list = [[1,2,3],[4,5,6],[7,8,9]]
def display(a):
print(f'{a[0][0]} | {a[0][1]} | {a[0][2]}')
print('----------')
print(f'{a[1][0]} | {a[1][1]} | {a[1][2]}')
print('----------')
print(f'{a[2][0]} | {a[2][1]} | {a[2][2]}')
def user_first():
user_choice_variable = ''
while user_choice_variable not in ['X', 'O']:
user_choice_variable = input('Enter X or O')
if user_choice_variable not in ['X', 'O']:
print('Wrong choice')
if user_choice_variable == 'X':
return True
else:
return False
#Take the cell input from the user
def user_input():
choice = ''
while choice not in range(1,10) :
choice = int(input('Enter you cell number '))
if choice not in range(1,9):
print('Please make the correct selection ')
return choice
#Change the Logic using counter
def flagger(Flag):
if Flag == True:
return False
else:
return True
def flagger_update(Flag):
if Flag == True:
return 'X'
else:
return 'O'
#Modify cell output
def cell_modification(my_list, choice, Flag):
choice = choice
if choice in range(1,4):
my_list[0][choice -1] = flagger_update(Flag)
if choice in range(4,7):
my_list[1][choice -4] = flagger_update(Flag)
if choice in range(7,10):
my_list[2][choice -7] = flagger_update(Flag)
return my_list
def game_on():
print('Want to continue game')
continue_game = ''
while continue_game not in ['Y', 'N']:
continue_game = input('Y or N')
if continue_game not in ['Y','N']:
print('Wrong entry')
return continue_game
def game_rules(my_list):
new_list = [[],[],[]]
result = False
#Veritcal
for i in my_list:
for j in range(0,3):
new_list[j].append(i[j])
for i in new_list:
if i.count('X') == 3 or i.count('O') ==3 :
print(f' {i[0]} wins the game ')
result = True
#Horizaontal
for i in my_list:
if i.count('X') == 3 or i.count('O') ==3:
print(f' {i[0]} wins the game ')
result = True
#Diagonal
i=0
j=0
a = my_list
if(a[i][j]==a[i+1][j+1]==a[i+2][j+2]):
print(f'Player {a[1][1]} wins the game ')
result = True
if(a[i][j+2]==a[i+1][j+1]==a[i+2][j]):
print(f'Player {a[1][1]} wins the game ')
result = True
return result
flag_x = user_first()
game_mode = ''
flag1 = flag_x
count = 0
while game_mode not in ['N'] and count <10:
choice = user_input()
my_list = cell_modification(my_list, choice, flag1)
display(my_list)
flag1 = flagger(flag1)
if game_rules(my_list) == True:
print(game_rules(my_list))
my_list = [[1,2,3],[4,5,6],[7,8,9]]
game_mode = game_on()
print('\n'*10)
count = 0
print('\n'*6)
count = count + 1
if count == 9:
print('Match tie')
game_mode = game_on()
my_list = [[1,2,3],[4,5,6],[7,8,9]]
#Whether he wants to continue
#final logic
|
375f722c5c465af44f828aca3b5a78e3950de7cd | ilteriskeskin/MucitPark-Pyhton-Egitimi | /egzersizler/egzersiz1/h1s1.py | 198 | 3.75 | 4 | sayi1 = int(input("1. sayiyi giriniz: "))
sayi2 = int(input("2. sayiyi giriniz: "))
sayi3 = int(input("3. sayiyi giriniz: "))
ortalama = (sayi1 + sayi2 + sayi3) / 3
print("Ortalama: ", ortalama)
|
1d995773fc29690c0d571b3cabd1f02c0e8c3b60 | RyanLiu6/python-class-1 | /Class_1/TreasureHunt.py | 2,104 | 3.53125 | 4 | import urllib.request
def main():
print("Start of Treasure Hunt")
controlPlayer(getInfo())
def getInfo():
# Get information from website
treasure = []
response = urllib.request.urlopen("http://research.cs.queensu.ca/home/cords2/treasure.txt")
html = response.readline().decode("utf-8")
while len(html) > 0:
try:
treasure.append(int(html[:-1]))
except:
treasure.append(html[:-1])
html = response.readline().decode("utf-8")
return treasure
def controlPlayer(treasureList):
# Control Player
userPos = int(input("Where would you want to start? (Please Enter a Number)\n"))
knapsack = {}
numMoves = 0
while userPos < len(treasureList):
if isNumber(treasureList[userPos]):
userPos = treasureList[userPos]
else:
# First, see if treasureList[userPos] exists
# Second, if it does, get the value and increment by 1
# If it doesn't, set knapsack[treasureList[userPos]] = 1
knapsack[treasureList[userPos]] = knapsack.get(treasureList[userPos], 0) + 1
# Ask user if they wish to continue
print("Press 0 to quit and 1 to continue")
userInput = input("")
if userInput == "0":
tallyScore(numMoves, knapsack)
return
elif userInput == "1":
userPos = int(input("Please enter a new starting position.\n"))
numMoves+=1
tallyScore(numMoves, {})
def tallyScore(numMoves, knapsack):
# Compute and return Score
score = numMoves
for item in knapsack:
if item == "gold":
score += 5
elif item == "silver coins":
score += 10
elif item == "candy":
score += 2
elif item == "cell phone":
score += 100
print("You got: ")
print(score)
def isNumber(a):
# will be True also for 'NaN'
try:
number = float(a)
return True
except ValueError:
return False
if __name__ == "__main__":
main()
|
a8ffb1912c0b9b077ee57769b7c7e4bbef42ff42 | dudwns9331/PythonStudy | /BaekJoon/Bronze3/2566.py | 1,146 | 3.515625 | 4 | # 최대값
"""
2021-01-10 오후 2:14
안영준
문제
<그림 1>과 같이 9×9 격자판에 쓰여진 81개의 자연수가 주어질 때,
이들 중 최댓값을 찾고 그 최댓값이 몇 행 몇 열에 위치한 수인지 구하는 프로그램을 작성하시오.
예를 들어, 다음과 같이 81개의 수가 주어지면
이들 중 최댓값은 90이고, 이 값은 5행 7열에 위치한다.
입력
첫째 줄부터 아홉 번째 줄까지 한 줄에 아홉 개씩 자연수가 주어진다. 주어지는 자연수는 100보다 작다.
출력
첫째 줄에 최댓값을 출력하고, 둘째 줄에 최댓값이 위치한 행 번호와
열 번호를 빈칸을 사이에 두고 차례로 출력한다. 최댓값이 두 개 이상인 경우 그 중 한 곳의 위치를 출력한다.
"""
result = list()
for i in range(9):
number = list(map(int, input().split()))
result.append(number)
max_result = 0
for i in range(9):
if max_result < max((result[i])):
max_result = max(result[i])
point_col = result[i].index(max_result)
point_row = i
print(max_result)
print(point_row + 1, point_col + 1)
|
08d9301029c0f319d56d0ab2c66eab72c35c6de6 | arnavakula/basic-python | /lambdas/dec_challenge.py | 198 | 3.53125 | 4 | def decor(fun):
def inner(name):
result = fun(name) + ", how are you?"
return result
return inner
@decor
def hello(name):
return ("Hello " + name)
print(hello("Arnav")) |
04fd43b02302b2a0b9c0ee1254d5c5d246fea65d | ksercs/lksh | /2014/Работа в ЛКШ/Python/Зачет/4-/dictionary.py | 947 | 3.671875 | 4 | def merge(a, b):
i = 0
j = 0
c = []
while len(a) > i and len(b) > j:
if a[i] < b[j]:
c.append(a[i])
i += 1
else:
c.append(b[j])
j += 1
return c + a[i:] + b[j:]
def merge_sort(a):
if len(a) <= 1:
return a
else:
left = a[:len(a) // 2]
right = a[len(a) // 2:]
return merge(merge_sort(left), merge_sort(right))
fin = open("dictionary.in", "r")
fout = open("dictionary.out", "w")
words = []
count = int(fin.readline())
ans = [] * count
help = [True] * count
for i in range(count):
word = fin.readline().strip()
words.append(word)
ans = merge_sort(words)
for i in range(count):
for j in range(i+1, count):
if ans[i] == ans[j]:
help[j] = False
for i in range(count):
if help[i] == True:
print(ans[i], file=fout)
fout.close() |
04033bc7ef7557a6ae477dfca5fea6869148434e | guozhi666/python | /design/design3.py | 513 | 3.734375 | 4 | # -*- coding:utf-8 -*-
#工厂方法模式
from abc import ABCMeta,abstractmethod
class Payment(metaclass=ABCMeta):
#抽象产品
@abstractmethod
def pay(self, money):
pass
class AliPay(Payment):
#具体产品
def pay(self, money):
print('使用支付宝支付%s元' %money)
class ApplePay(Payment):
#抽象工厂
def pay(self,money):
print('使用苹果支付支付%s元' %money)
class PaymentFactory(metaclass=ABCMeta):
#具体工场
@abstractmethod
def creat_payment(self):
pass
|
dcf5d6f15c1e7e0430735391639d073c1f45d9ae | bradley27783/testing | /tests/JSON_Interface.py | 562 | 3.546875 | 4 | from nested_lookup import nested_lookup
class JSON_Interface:
def __init__(self, file) -> None:
self.file = file
def find(self, keys):
"""Find elememts from the JSON data
Args:
keys (list): A list of values to search for
Returns:
list: All values matching requirements
"""
values = self.file
for key in keys:
values = nested_lookup(key, values)
return values
# j = JSON_Interface(test_json)
# v = j.find(test_json, ['POS 1', 'ip'])
#print(v)
|
1d91904fae1b23f1d1c5beada5ac60bed6a7b877 | JoseGarVar/GIT | /Programas Python/Matriz1.py | 275 | 3.984375 | 4 | lista = [4,3,12,8] #Esta es una Lista
matriz = [[4,3,8],[1,6,5],[2,0,9]] #Matriz en Python
matriz[0][0] = 7
print matriz[0]
print len(matriz) #para saber el numero de columnas
print len(matriz[0]) #Para saber el numero de Filas
print lista * 2 #Repite 2 veces la lista
|
dfefc322fd80ce47ef5c90150c50cec41a0b7044 | mirzaevolution/Python-Basics | /PythonApplication2/Functions.py | 931 | 4.21875 | 4 | #Named arguments
def factorial(number):
if(number<=1):
return 1
else:
return factorial(number-1) * number;
print(factorial(number=12),"\n")
#Multiple arguments
def printNames(*names):
if(len(names)>0):
print("**********************\n")
for name in names:
print(name)
else:
print("\n**********************")
else:
print("No names to print")
printNames("Mirza Ghulam Rasyid","Michael Hawk","Han Jensen")
#Lambda - one parameter
power = lambda num: num*num;
print("\nLambda #1: power(12) =",power(12))
#Lambda - two parameters
multiply = lambda num1,num2: num1 * num2;
print("Lambda #2: multiply(3,5) =",multiply(3,5))
#Filter lambda
myList = list(range(1,11))
for item in list(filter(lambda number: number%2==0, myList)):
print(item,end=' ')
print()
#Map lambda
for item in list(map(lambda number: number*2,myList)):
print(item,end=' ')
print() |
34248e9f810ea13b8c83d56a2e873ac9c06b15f9 | kimit956/MyRepo | /quiz.py | 2,843 | 4.03125 | 4 | import os
# -*- coding: utf-8 -*-
#Question 1: color of the sky
def question1(questions):
questions.append(input("What color is the sky (when standing on Earth)? "))
#if option
#option a: purple
#option b: green
#option c: red
#option d: Black
#Question 2: mac and cheese and spork
#Question 3: burnt chocolate should NOT get water
#Question 4:
#Question 5: guess that pokemon: Cacnea | Grass | 119
print(f"For the next 5 questions you will have to Guess That Pokemon! :)")
print("P.S. They will be from Gen 3 (Hoenn); the numbers will NOT be referring to the National Pokédex number")
#Question 6: guess that pokemon: Cacnea | Grass | 119
def q6(question,attempt,score,allAttempts,correct):
attempt = 0 #resets every question
score = 0 #resets every question; 1 is correct
question = input("What is the Pokémon with the Pokédex entry of 119? ").lower()
#does the question as long as the amount of attempts is not 10
while attempt != 10 and question != "cacnea":
if question == "cacnea":
score += 1
else:
print("Incorrect")
attempt += 1
#after 3 attempts, asks user if they would like a hint
if attempt == 3:
#will ask the user if they want a hint
hint = input("Would you like a hint (Y|N)? ").lower()
if hint == "y" or hint == "yes":
print("This Pokémon is a grass type, evolves into Cacturne, and looks like a small cactus.")
else:
print("Ok. You have " + str(10-attempt) + "attempt(s) left.")
if question == "cacnea":
print("Correct!")
else:
print("You ran out of attempts. Moving to next question...")
correct.append(score)
allAttempts.append(attempt)
os.system("cls" if os.name == "nt" else "clear") #should clear the screen before the next question
#Question 7: guess that pokemon: Crobat | Poison, Flying | 065
#Question 8: guess that pokemon: Huntail | Water | 177
#Question 9: guess that pokemon: Breloom | Grass, Fighting | 035
#Question 10: guess that pokemon: Marshtomp | Water, Ground | 008
question = ""
score = 0 #this will see how many questions the user answers correctly within the given attempts
correct = []
attempt = 0 #this will keep track of how many guesses it took for the user to answer the question correctly with max of 10 attempts
allAttempts = []
q6(question,attempt,score,allAttempts,correct)
#questions.append(int(input("What year is it?")))
#options.append(2021)
#options.append(2020)
#options.append(2022)
#options.append(6546)
#print(options)
|
d5a118e386e9363ebef0c995679cb4e3f31b2781 | TeavenX/study | /advanced_learning/args.py | 1,085 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
author: lvsongke@oneniceapp.com
data:2019/09/11
"""
from functools import reduce
def test_var_args(f_arg, *argv):
print("first normal arg:", f_arg)
print(argv)
for arg in argv:
print("another arg through *argv:", arg)
def greet_me(**kwargs):
for key, value in kwargs.items():
print('{key} == {value}'.format(key=key, value=value))
def test_args_kwargs(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
def multiply(x):
return (x * x)
def add(x):
return (x + x)
funcs = [multiply, add]
for i in range(5):
value = map(lambda x: x(i), funcs)
print(list(value))
number_list = range(-5, 5)
less_than_zero = filter(lambda x: x >= 0, number_list)
print(list(less_than_zero))
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
print('*' * 100)
print(product)
test_var_args('yasoob', 'python', 'eggs', 'test', 'java')
greet_me(name='python', age='15')
args = ('two', 3, 5)
kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
test_args_kwargs(*args)
test_args_kwargs(**kwargs)
|
cfe4e8aee7a969f55b2ff62b37ec6f19f4d44105 | sknaht/algorithm | /python/backtracking/Combination Sum II.py | 1,421 | 3.515625 | 4 | # coding=utf-8
"""
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
"""
class Solution:
# @param {integer[]} candidates
# @param {integer} target
# @return {integer[][]}
def combinationSum2(self, candidates, target):
result = []
cands = {}
for x in candidates:
if x not in cands:
cands[x] = 1
else:
cands[x] += 1
indvs = sorted(cands.keys())
def backtracking(curr, s):
if s == 0:
result.append([_ for _ in curr])
return
for x in indvs:
if x <= s and cands[x] > 0 and (not curr or x >= curr[-1]):
cands[x] -= 1
backtracking(curr + [x], s - x)
cands[x] += 1
backtracking([], target)
return result
print Solution().combinationSum2([10,1,2,7,6,1,5], 8)
|
52af4e4196b87967a65e3238f326df6b44a6f326 | Twishar/Python | /BaseMustHave/DecoratorExample.py | 1,719 | 3.65625 | 4 | import time
def benchmark(func):
"""
Декоратор, выводящий время, которое заняло
выполнение декорируемой функции.
"""
def wrapper(*args, **kwargs):
t = time.clock()
res = func(*args, **kwargs)
print(func.__name__, time.clock() - t)
return res
return wrapper
def logging(func):
"""
Декоратор, логирующий работу кода.
(хоршо, он просто выводит вызовы, но тут могло быть и логирование!)
"""
def wrapper(*args, **kwargs):
res = func(*args, **kwargs)
print(func.__name__, args, kwargs)
return res
return wrapper
def counter(func):
"""
Декоратор, очищающий и выводящий количество вызовов
декорируемой функции
"""
def wrapper(*args, **kwargs):
wrapper.count += 1
res = func(*args, **kwargs)
print("{0} была вызывана: {1}x".format(func.__name__, wrapper.count))
return res
wrapper.count = 0
return wrapper
@benchmark
@logging
@counter
def reverse_string(str):
return ''.join(reversed(str))
if __name__ == '__main__':
print(reverse_string("А роза упала на лпау Азора"))
print("\n####################\n")
print(reverse_string("A man, a plan, a canoe, pasta, heros, rajahs, a coloratura,"
"maps, snipe, percale, macaroni, a gag, a banana bag, a tan, a tag,"
"a banana bag again (or a camel), a crepe, pins, Spam, a rut, a Rolo, cash,"
"a jar, sore hats, a peon, a canal: Panama!"))
|
5e209f46eaaf4369497d529455033891f7c8a0df | MarloDelatorre/leetcode | /0217_Contains_Duplicate.py | 544 | 3.640625 | 4 | from unittest import main, TestCase
def containsDuplicate(nums):
return len(nums) > len(set(nums))
class Test(TestCase):
def test_given_case_1(self):
self.assertTrue(containsDuplicate([1, 2, 3, 1]))
def test_given_case_2(self):
self.assertFalse(containsDuplicate([1, 2, 3, 4]))
def test_given_case_3(self):
self.assertTrue(containsDuplicate([1, 1, 1, 3, 3, 4, 3, 2, 4, 2]))
def test_empty_case(self):
self.assertFalse(containsDuplicate([]))
if __name__ == "__main__":
main() |
143bb851758b4268ac98b5c3fe52d922913809eb | Mangelsanm/Python | /Algoritmos de Busqueda/BusquedaRecursiva.py | 559 | 4 | 4 | # Busqueda_lineal_recursiva
# Algoritmo para hacer la busqueda de un elemento
# dentro de un arreglo de manera recursiva.
# Si el elemento no esta dentro del arreglo, se regresara un -1
# El orden del algoritmo es de O(N)
# USAR BUSQUEDA LINEAL SI EL ARREGLO NO ESTA ORDENADO
# mares112358@gmail.com
def linear_search_recursive(array, element, n = 0):
if n >= len(array):
return -1
if array[n] == element:
return n
return linear_search_recursive(array, element, n + 1)
array = [4, 34, 2, 10, 150, 56]
print(linear_search_recursive(array, 2)) |
7d918e1e0c33650003a6b169a43bfbd99c704d63 | anonim9878/FindALittleFox | /SearchFox/Objects/objects_in_game.py | 17,305 | 3.640625 | 4 | import random
#Класс доски.
class Board:
def __init__(self, xsize, ysize):
self.__xsize = xsize
self.__ysize = ysize
def print_board1(self, lis_obj):
#Заполняем список для отоброжения объектов. Сначала заполняем его пустотой, чтобы потом её заменить на символы объектов без помех.
lis_ter = []
for i in range(0, self.__xsize * self.__ysize, 1):
lis_ter.append(" ") #Заполняем 3 пробелами, т.к. в некоторых случаях в игре потребуется именно столько места.
#Добавляем объекты в соответствующие ячейки.
for n_obj in lis_obj:
lis_ter[n_obj.getCoordinats()] = n_obj.getSimbol()
#Печатаем доску
index = -1
board = " ="
for i in range(0, self.__xsize * 4, 1):
board += "="
board += "\n |"
for i in range(0, self.__xsize, 1):
if i <= 9:
board += " " + str(i) + " |"
else:
board += " " + str(i) + "|"
board += "\n===="
for i in range(0, self.__xsize * 4, 1):
board += "="
for i in range(0, self.__ysize, 1):
#board += "\n----"
#for x in range(0, self.__xsize * 4, 1):
#board += "-"
board += "\n"
if i <= 9:
board += " " + str(i) + " |"
elif i*self.__xsize > 9 and i <= 99:
board += " " + str(i) + "|"
elif i*self.__xsize > 99:
board += str(i) + "|"
for x in range(0, self.__xsize, 1):
index += 1
board += lis_ter[index] + "|"
board += "\n===="
for i in range(0, self.__xsize * 4, 1):
board += "="
print(board)
class Object:
def __init__(self, coordinats_x, coordinats_y, simbol):
self.__coordinats_x = coordinats_x
self.__coordinats_y = coordinats_y
self.__coordinats = coordinats_x + coordinats_y
self.__simbol = " " + simbol + " "
def getCoordinats(self):
return self.__coordinats
def getCoordinatsX(self):
return self.__coordinats_x
def getCoordinatsY(self):
return self.__coordinats_y
def getSimbol(self):
return self.__simbol
class Animal(Object):
def __init__(self, coordinats_x, coordinats_y, size_board_x, simbol, strong, ter_damage, speed):
super().__init__(coordinats_x, coordinats_y, simbol)
self.__size_board_x = size_board_x
self.__standart_simbol = simbol
self.__strong = strong
self.__coordinats_terrain_animal_x = -1
self.__coordinats_terrain_animal_y = -1
self.__speed = speed
self.__terrain_index = -1
self.__terrain_damage = ter_damage
self.__occupation = self.__coordinats_terrain_animal_y == self._Object__coordinats_y and self.__coordinats_terrain_animal_x == self._Object__coordinats_x
self.__terrain = None
self.__animal_for_attack = None
self.__index_animal_for_attack = None
self.__index_food = None
def __setCoordinats_terrain_animals(self, terrains_animals):
iteration = 0
while True:
iteration += 1
index = random.randint(0, len(terrains_animals) - 1)
terrain_index = index
terrain = terrains_animals[terrain_index]
if (terrain.getRepairStatus() or self.__terrain_index == terrain_index) and iteration != 1000:
continue
else:
if iteration == 1000:
print("|ВЫБРАНА АБСОЛЮТНО СЛУЧАЙНАЯ МЕСТНОСТЬ|")
break
#Если мы пережили нападение, то выбираем ту местность, дорога к которой не будет пересекаться с дорогой нападавшего
if self.__animal_for_attack != None:
x_check_right = self.__animal_for_attack.getCoordinatsX() >= self._Object__coordinats_x and terrain.getCoordinatsX() < self._Object__coordinats_x
x_check_left = self.__animal_for_attack.getCoordinatsX() <= self._Object__coordinats_x and terrain.getCoordinatsX() > self._Object__coordinats_x
y_check_down = self.__animal_for_attack.getCoordinatsY() >= self._Object__coordinats_y and terrain.getCoordinatsY() < self._Object__coordinats_y
y_check_up = self.__animal_for_attack.getCoordinatsY() <= self._Object__coordinats_y and terrain.getCoordinatsY() > self._Object__coordinats_y
if x_check_left or x_check_right or y_check_down or y_check_up:
break
else:
break
self.__terrain_index = terrain_index
self.__coordinats_terrain_animal_x = terrain.getCoordinatsX()
self.__coordinats_terrain_animal_y = terrain.getCoordinatsY()
def __move_to_ter(self):
#Передвижение животного. Если скорость не больше разницы расстояний между координатами места и животного, то используем её, иначе используем разницу
if self.__coordinats_terrain_animal_x < self._Object__coordinats_x:
if self._Object__coordinats_x - self.__speed >= self.__coordinats_terrain_animal_x:
self._Object__coordinats_x -= self.__speed
else:
self._Object__coordinats_x -= -(self.__coordinats_terrain_animal_x - self._Object__coordinats_x)
elif self.__coordinats_terrain_animal_x > self._Object__coordinats_x:
if self._Object__coordinats_x + self.__speed <= self.__coordinats_terrain_animal_x:
self._Object__coordinats_x += self.__speed
else:
self._Object__coordinats_x += -(self._Object__coordinats_x - self.__coordinats_terrain_animal_x)
if self.__coordinats_terrain_animal_y < self._Object__coordinats_y:
if self._Object__coordinats_y - self.__speed * self.__size_board_x >= self.__coordinats_terrain_animal_y:
self._Object__coordinats_y -= self.__speed * self.__size_board_x
else:
self._Object__coordinats_y -= -(self.__coordinats_terrain_animal_y - self._Object__coordinats_y)
elif self.__coordinats_terrain_animal_y > self._Object__coordinats_y:
if self._Object__coordinats_y + self.__speed * self.__size_board_x <= self.__coordinats_terrain_animal_y:
self._Object__coordinats_y += self.__speed * self.__size_board_x
else:
self._Object__coordinats_y += -(self._Object__coordinats_y - self.__coordinats_terrain_animal_y)
def __occupation_area(self, ter):
self._Object__simbol = self.__standart_simbol + "O "
if ter.getHP() != 0:
ter.setHP(ter.getHP() - self.__terrain_damage)
ter.setOccupationStatus(True)
else:
self._Object__simbol = " " + self.__standart_simbol + " "
self.__terrain_index = -1
ter.setOccupationStatus(False)
def get_Strong(self):
return self.__strong
def __attack(self, animal):
#В случаи с лисёнком пишем отдельный код из-за её особенностей и последующей логики(подыхать и прятаться)
#print("Attack!!!")
win_rate = (self.__strong / (self.__strong + animal.get_Strong())) * 100
dice = random.randint(0, 100)
if win_rate >= dice:
animal.defeat()
else:
self.defeat()
self.__animal_for_attack = animal
def __check_out_from_area_attack(self, animal):
left_area = animal.getCoordinatsX() > (self._Object__coordinats_x - self.__speed)
right_area = animal.getCoordinatsX() < (self._Object__coordinats_x + self.__speed)
up_area = animal.getCoordinatsY() > (self._Object__coordinats_y - (self.__speed * self.__size_board_x))
down_area = animal.getCoordinatsY() < (self._Object__coordinats_y + (self.__speed * self.__size_board_x))
if self.__animal_for_attack != None:
if self.__animal_for_attack == animal:
if left_area and right_area and up_area and down_area and animal != self:
pass
else:
self.__animal_for_attack = None
self.__index_animal_for_attack = None
def defeat(self):
self.__terrain_index = -1
if self.__occupation:
self.__terrain.setOccupationStatus(False)
self._Object__simbol = " " + self.__standart_simbol + " "
def __check_other_animals(self, animals):
for i in animals:
left_area = i.getCoordinatsX() > (self._Object__coordinats_x - self.__speed)
right_area = i.getCoordinatsX() < (self._Object__coordinats_x + self.__speed)
up_area = i.getCoordinatsY() > (self._Object__coordinats_y - (self.__speed * self.__size_board_x))
down_area = i.getCoordinatsY() < (self._Object__coordinats_y + (self.__speed * self.__size_board_x))
#Если у нас была проведена атака, то проверяем, вышли ли мы из поля боя
if self.__animal_for_attack != None:
self.__check_out_from_area_attack(i)
#Проверяем, нет ли в нашем радиусе животных
if left_area and right_area and up_area and down_area and i != self and i != self.__animal_for_attack:
self.__attack(i)
break
def __eat(self, food, lis_foods, lis_obj):
self._Object__coordinats_x = food.getCoordinatsX()
self._Object__coordinats_y = food.getCoordinatsY()
#Удаляем еду, будто мы её съели. Удаляем с двух списков, тк указатели на объект существуют в обоих списках
index = -1
for i in lis_foods:
index += 1
if i == food:
del lis_foods[index]
break
index = -1
for i in lis_obj:
index += 1
if i == food:
del lis_obj[index]
break
def __check_foods(self, foods, lis_obj):
rezult_check = False
for i in foods:
left_area = i.getCoordinatsX() >= (self._Object__coordinats_x - self.__speed)
right_area = i.getCoordinatsX() <= (self._Object__coordinats_x + self.__speed)
up_area = i.getCoordinatsY() >= (self._Object__coordinats_y - (self.__speed * self.__size_board_x))
down_area = i.getCoordinatsY() <= (self._Object__coordinats_y + (self.__speed * self.__size_board_x))
#Проверяем, нет ли в нашем радиусе животных
if left_area and right_area and up_area and down_area and i != self and i != self.__animal_for_attack:
self.__eat(i, foods, lis_obj)
rezult_check = True
break
return rezult_check
def behavior(self, animals, foods, terrain_animals, lis_obj):
if self.__terrain_index == -1:
self.__setCoordinats_terrain_animals(terrain_animals)
self.__occupation = self.__coordinats_terrain_animal_y == self._Object__coordinats_y and self.__coordinats_terrain_animal_x == self._Object__coordinats_x
self.__terrain = terrain_animals[self.__terrain_index]
if self.__occupation:
self.__occupation_area(self.__terrain)
else:
if self.__index_animal_for_attack != None:
self.__animal_for_attack = animals[self.__index_animal_for_attack]
self.__check_other_animals(animals)
if self.__animal_for_attack != None and self.__index_animal_for_attack == None:
x = 0
for i in animals:
if i == self.__animal_for_attack:
self.__index_animal_for_attack = x
x += 1
else:
if self.__check_foods(foods, lis_obj):
pass
else:
self.__move_to_ter()
self._Object__coordinats = self._Object__coordinats_y + self._Object__coordinats_x
class TerrainAnimals(Object):
def __init__(self, coordinats_x, coordinats_y, simbol, hp):
super().__init__(coordinats_x, coordinats_y, simbol)
self.__MAX_HP = hp
self.__hp = hp
self.__occupation_status = False
self.__repair_status = False
def getOccupationStatus(self):
return self.__occupation_status
def getRepairStatus(self):
return self.__repair_status
def getHP(self):
return self.__hp
def setHP(self, val):
try:
if val < 0:
self.__hp = 0
else:
self.__hp = val
except TypeError:
print(val, " не int")
def setOccupationStatus(self, val):
if val != True and val != False:
print("Я не могу присвоить значение ", val, ", т.к. оно не булевое")
return
self.__occupation_status = val
def __repair(self):
self.__hp += 1
self._Object__simbol = " X "
self.__repair_status = True
def behavior(self):
if self.__hp < self.__MAX_HP and self.__occupation_status == False:
self.__repair()
else:
self._Object__simbol = " O "
self.__repair_status = False
def getCoordinatsX(self):
return self._Object__coordinats_x
def getCoordinatsY(self):
return self._Object__coordinats_y
#И, наконец, лисёнок
class Fox(Animal):
def __init__(self, coordinats_x, coordinats_y, size_board_x, simbol, strong, ter_damage, speed, time_growing):
super().__init__(coordinats_x, coordinats_y, size_board_x, simbol, strong, ter_damage, speed)
self.__die_status = False
self.__TIME_GROWING = time_growing
self.__time_growing_now = 0
self.__safe_terrain = None
self.__action_retreat = False
def __growing(self):
self.__time_growing_now += 1
if self.__time_growing_now >= self.__TIME_GROWING:
self._Animal__speed += 1
self._Animal__strong += 1
self.__time_growing_now = 0
def getDieStatus(self):
return self.__die_status
def __retreat(self):
print("Retreat")
rezult_check = False
for i in self.__safe_terrain:
left_area = i.getCoordinatsX() >= (self._Object__coordinats_x - self._Animal__speed)
right_area = i.getCoordinatsX() <= (self._Object__coordinats_x + self._Animal__speed)
up_area = i.getCoordinatsY() >= (self._Object__coordinats_y - (self._Animal__speed * self._Animal__size_board_x))
down_area = i.getCoordinatsY() <= (self._Object__coordinats_y + (self._Animal__speed * self._Animal__size_board_x))
#Проверяем, нет ли в нашем радиусе безопасных мест
if left_area and right_area and up_area and down_area:
#Если есть, то тп туда(по идее под его знаком, но у меня будет совмещёнка)
self._Object__simbol = self._Animal__standart_simbol + "Sa"
self._Object__coordinats_x = i.getCoordinatsX()
self._Object__coordinats_y = i.getCoordinatsY()
self.__action_retreat = True
rezult_check = True
break
return rezult_check
def __die(self):
self.__die_status = True
self._Object__simbol = self._Animal__standart_simbol + "Di"
def defeat(self):
if self.__retreat():
return
else:
print("Die")
self.__die()
return super().defeat()
def behavior(self, animals, foods, terrain_animals, safe_terrain, lis_obj):
if self.__die_status:
if self._Object__simbol != self._Animal__standart_simbol + "Di":
self._Object__simbol = self._Animal__standart_simbol + "Di"
return
else:
self.__growing()
self.__safe_terrain = safe_terrain
if self.__action_retreat == False and self._Animal__occupation == False and self.__die_status == False:
self._Object__simbol = " " + self._Animal__standart_simbol + " "
if self.__action_retreat:
self._Object__coordinats = self._Object__coordinats_y + self._Object__coordinats_x
self.__action_retreat = False
return
return super().behavior(animals, foods, terrain_animals, lis_obj)
|
f1347636974a8021e8d460edb46d937f076858ab | hbates00/6.0001-Introduction-to-Computer-Science-Programming-in-Python | /Problem_Set_2/hangman.py | 6,162 | 4 | 4 | # Problem Set 2, hangman.py
# Name: Haley Bates-Tarasewicz
# Collaborators: William Kalb
# Time spent: 2:00
# Hangman Game
# -----------------------------------Provided Code
import random
import string
WORDLIST_FILENAME = "words.txt"
def load_words():
print "Loading word list from file..."
# inFile: file
inFile = open(WORDLIST_FILENAME, 'r', 0)
# line: string
line = inFile.readline()
# wordlist: list of strings
wordlist = string.split(line)
print " ", len(wordlist), "words loaded."
return wordlist
def choose_word(wordlist):
return random.choice(wordlist)
# -----------------------------------Global Variables
wordlist = load_words()
# -----------------------------------Hangman Functions
#Takes a string secret_word and a list letters_guessed and returns true if all of the letters in secret_word have been guessed.
#Returns false otherwise
def is_word_guessed(secret_word, letters_guessed):
for i in secret_word:
if i not in letters_guessed:
return False
else:
pass
return True
#Takes a string secret_word and a list letters_guessed and returns secret_word with all of the unguessed letters as asterisks
def get_guessed_word(secret_word, letters_guessed):
secret_list = list(secret_word)
count = 0
for i in secret_word:
if i not in letters_guessed:
secret_list[count] = '*'
else:
pass
count += 1
return "".join(secret_list)
#takes a list letters_guessed and returns the alphabet with the letters in the list letters_guessed removed
def get_available_letters(letters_guessed):
letters = list(string.ascii_lowercase)
for i in letters_guessed:
letters.remove(i)
return "".join(letters)
# -----------------------------------Hangman Main Loop
def hangman(secret_word):
print "Welcome to the game Hangman!"
print "I am thinking of a word that is ", len(secret_word), 'letters long.'
guesses = 6
letters_guessed = []
vowels = ['a', 'e', 'i', 'o', 'u']
while True:
print '-------------'
print 'you have', guesses, 'guesses left.'
print 'Available letters: ', get_available_letters(letters_guessed)
guess = raw_input('Please guess a letter:')
if guess in letters_guessed:
print "Oops! You've already guessed that letter:", get_guessed_word(secret_word, letters_guessed)
guesses -= 1
elif guess in secret_word:
letters_guessed.append(guess)
print 'Good guess:', get_guessed_word(secret_word, letters_guessed)
else:
letters_guessed.append(guess)
print 'Oops! That letter is not in my word:', get_guessed_word(secret_word, letters_guessed)
if guess in vowels:
guesses -= 2
else:
guesses -= 1
if is_word_guessed(secret_word, letters_guessed):
print 'Congratulations, you won!'
break
elif guesses <= 0:
print 'Sorry, you ran out of guesses. The word was', str(secret_word) + '.'
break
else:
pass
# -----------------------------------Calls the Hangman Function
hangman(choose_word(wordlist))
# -----------------------------------Hangman With Hints Functions
#takes two strings and returns true if they match exactly, or are the same length with non-matching asterisk characters.
#Returns false otherwise
def match_with_gaps(my_word, other_word):
count = 0
if len(my_word) != len(other_word):
return False
else:
pass
for i in my_word:
if i != '*':
if my_word[count] != other_word[count]:
return False
count += 1
else:
count += 1
pass
return True
#takes a string my_word with a mix of letters and asterisks with asterisks representing unknown letters
#returns a string every word my_word could be based on the placement of the asterisks
def show_possible_matches(my_word):
megastring = []
for word in wordlist:
if match_with_gaps(my_word, word):
megastring.append(word)
else:
pass
print " ".join(megastring)
# -----------------------------------Hangman With Hints Main Loop
def hangman_with_hints(secret_word):
print "Welcome to the game Hangman!"
print "I am thinking of a word that is ", len(secret_word), 'letters long.'
guesses = 6
letters_guessed = []
vowels = ['a', 'e', 'i', 'o', 'u']
while True:
print '-------------'
print 'you have', guesses, 'guesses left.'
print 'Available letters: ', get_available_letters(letters_guessed)
guess = raw_input('Please guess a letter:')
if guess == '*':
print 'Possible word matches are:'
show_possible_matches(get_guessed_word(secret_word, letters_guessed))
elif guess in letters_guessed:
print "Oops! You've already guessed that letter:", get_guessed_word(secret_word, letters_guessed)
guesses -= 1
elif guess in secret_word:
letters_guessed.append(guess)
print 'Good guess:', get_guessed_word(secret_word, letters_guessed)
else:
letters_guessed.append(guess)
print 'Oops! That letter is not in my word:', get_guessed_word(secret_word, letters_guessed)
if guess in vowels:
guesses -= 2
else:
guesses -= 1
if is_word_guessed(secret_word, letters_guessed):
print 'Congratulations, you won!'
break
elif guesses <= 0:
print 'Sorry, you ran out of guesses. The word was', str(secret_word) + '.'
break
else:
pass
# -----------------------------------Calls the Hangman With Hints Function
hangman_with_hints(choose_word(wordlist).lower())
|
26a8fd7e9baa6900216a2fa7c5a63f9691b4aa6e | dhengkt/CourseProjects | /Python/110/AverageScores.py | 658 | 3.78125 | 4 | # AverageScores
# HsinYu Chi(Katie)
# Use a function to find the average
# first of three exams scores, then
# of three projects.
def getInput1():
return(85, 90, 100)
def getInput2():
return(26, 52, 107)
def getAverage(x, y, z):
avg = (x + y + z) / 3
return(avg)
def OutputResults(a, b):
print("The exam average is {0} and "
"the project average is {1}."
.format(round(a,2), round(b,2)))
def main():
Ex1, Ex2, Ex3 = getInput1()
P1, P2, P3 = getInput2()
ExAvg = getAverage(Ex1, Ex2, Ex3)
PAvg = getAverage(P1, P2, P3)
OutputResults(ExAvg, PAvg)
main()
|
94dad8c1c0739130a3ba756fc581733fb589e1d4 | Web-Dev-Collaborative/Lambda-Final-Backup | /7-assets/past-student-repos/LambdaSchool-master/m6/63c1/stock_prices/stock_prices.py | 1,554 | 4.09375 | 4 | #!/usr/bin/python
import argparse
def find_max_profit(prices):
pass
# Write a function `find_max_profit` that receives as input a list of stock prices.
# Your function should return the maximum profit that can be made from a single buy and sell.
# You must buy first before selling; no shorting is allowed here.
# get maximum number value
max_profit = 0
max_profit_index = 0
for x in range(0, len(prices)):
current_value = prices[x]
if current_value > max_profit:
max_profit = current_value
# get index of max number value
max_profit_index = x
min_profit_index = x
min_profit = prices[min_profit_index]
# get min number value from all indexes prior to that index
for y in range(max_profit_index, 0, -1):
current_value = prices[y]
if current_value < min_profit:
min_profit = current_value
min_profit_index = x
print('min_profit = ' + str(min_profit))
print('max_profit = ' + str(max_profit))
# subtract min from max
profit = max_profit - min_profit
# return result as profit
return profit
if __name__ == '__main__':
# This is just some code to accept inputs from the command line
parser = argparse.ArgumentParser(description='Find max profit from prices.')
parser.add_argument('integers', metavar='N', type=int,
nargs='+', help='an integer price')
args = parser.parse_args()
print("A profit of ${profit} can be made from the stock prices {prices}.".format(
profit=find_max_profit(args.integers), prices=args.integers))
|
0962bb29fa80bc5ecdca46820bc0fec5ddce611a | tedhudek/sandbox | /do-dictionary-stuff.py | 179 | 3.671875 | 4 | print("Hello world!")
from PyDictionary import PyDictionary
print("We finished the import. Woo!")
dictionary=PyDictionary()
#print (dictionary.meaning("indentation"))
print(noun) |
3eb841b3494e350174f58f0abdbf936988be9d94 | sev-94/introPy | /49_regular_expressions.py | 963 | 3.96875 | 4 | import re # Import Regular Expressing 're'
string = 'search this inside of this text please!'
a = re.search('this', string) # Set search to look for a string 'this'
print(a) # Information about the string
print(a.span()) # Start and End locations of the string
print(a.start()) # Location of the start of the string
print(a.end()) # Location of the end of the string
print(a.group()) # Print group of chars matching string
pattern = re.compile('this') # Set a pattern to search for
a2 = pattern.search(string) # Finds first instance of pattern
a3 = pattern.findall(string) # Finds all instances of the pattern
a4 = pattern.fullmatch('this') # Checks if the parameter exactly matches pattern
a5 = pattern.match(string) # Checks if the parameter exactly matches pattern up to a point
print(a2)
print(a3)
print(a4)
print(a5) |
023eb82a67c97db37568b280e1c3365cfeb58448 | ammuaj/CodeSignal-PySolutions | /leetCode_30DaysOfCode/day_9/remove_duplicates_2.py | 1,211 | 4.1875 | 4 | """
Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively.
It doesn't matter what you leave beyond the returned length.
"""
def removeDuplicates(nums):
i = 0
# counter the number of duplicate numbers
counter = 1
for j in range(1, len(nums)):
# if the two numbers are different
if nums[i] != nums[j]:
# swap
i = swapHelper(i + 1, j, nums)
# set the counter to one again since we have a new num
counter = 1
# if the number of duplicates from the same number is less than 2
elif counter < 2:
i = swapHelper(i + 1, j, nums)
counter += 1
return nums[0:i+1]
def swapHelper(i, j, nums):
nums[i], nums[j] = nums[j], nums[i]
return i
print(removeDuplicates([1, 1, 1, 2, 2, 2, 4, 4, 4])) |
8e6d61e8134fa802dbc9bda66cb9d3f90e1ff311 | SR2k/leetcode | /5/509.斐波那契数.py | 1,155 | 3.6875 | 4 | #
# @lc app=leetcode.cn id=509 lang=python3
#
# [509] 斐波那契数
#
# https://leetcode.cn/problems/fibonacci-number/description/
#
# algorithms
# Easy (66.63%)
# Likes: 466
# Dislikes: 0
# Total Accepted: 394.4K
# Total Submissions: 591.9K
# Testcase Example: '2'
#
# 斐波那契数 (通常用 F(n) 表示)形成的序列称为 斐波那契数列 。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是:
#
#
# F(0) = 0,F(1) = 1
# F(n) = F(n - 1) + F(n - 2),其中 n > 1
#
#
# 给定 n ,请计算 F(n) 。
#
#
#
# 示例 1:
#
#
# 输入:n = 2
# 输出:1
# 解释:F(2) = F(1) + F(0) = 1 + 0 = 1
#
#
# 示例 2:
#
#
# 输入:n = 3
# 输出:2
# 解释:F(3) = F(2) + F(1) = 1 + 1 = 2
#
#
# 示例 3:
#
#
# 输入:n = 4
# 输出:3
# 解释:F(4) = F(3) + F(2) = 2 + 1 = 3
#
#
#
#
# 提示:
#
#
# 0 <= n <= 30
#
#
#
# @lc code=start
from functools import lru_cache
class Solution:
@lru_cache
def fib(self, n: int) -> int:
if n <= 1:
return n
return self.fib(n - 1) + self.fib(n - 2)
# @lc code=end
|
8781c649cb47118c38873a37115b16698f62dfc0 | python402837617/python2 | /找出所有素数.py | 319 | 3.59375 | 4 | def ss():
n=int(input("please give one number:"))
b=0
for i in range(1,n):
a=i//2
for c in range(2,a):
if i%c==0:
b=1
break
else:
b=0
if b==0:
print(i)
if __name__=="__main__":
ss() |
8f24c9afeb9d63fae120dff79808f23dd77ac766 | gabrielasigolo/programaCalorias | /programaCalorias.py | 688 | 3.90625 | 4 | print(('-' * 10), 'QUANTAS CALORIAS EU DEVO INGERIR POR DIA', ('-' * 10))
print('Eu desejo saber o quanto eu devo ingerir para...'
'\n 1 - Emagrecer'
'\n 2 - Manter o peso'
'\n 3 - Para engordar')
resposta = int(input('RESPOSTA: '))
peso = float(input('Digite o seu peso: '))
if resposta == 1:
emagrecer = peso * 20
print('Você precisa ingerir {} kalorias por dia para emagrecer'.format(emagrecer))
elif resposta == 2:
manter_peso = peso * 30
print('Você precisa ingerir {} kalorias por dia para manter o peso'.format(manter_peso))
else:
engordar = peso * 35
print('Você precisa ingerir {} kalorias por dia para engordar'.format(engordar))
|
988dca8a83ac65ee55cab41f32b52e31ebfea9ea | ktkinsey37/python_beginner_exercises | /fs_2_valid_parentheses/valid_parentheses.py | 496 | 4.40625 | 4 | def valid_parentheses(parens):
"""Iterates through a string of parentheses to determine if they are all valid parens.
"""
open_parens_true = 0
start = 0
if (len(parens) % 2 != 0):
return False
for paren in parens:
if paren == "(":
open_parens_true += 1
if paren == ")":
open_parens_true -= 1
if open_parens_true < 0:
return False
if open_parens_true == 0:
return True
return False |
b6496b07be61d70af790c737981a888c7e9c6e6a | Chandrahas-Soman/Data_Structures_and_Algorithms | /Python/Linked_List/Remove_the_Kth_last_element_from_a list.py | 1,186 | 4.09375 | 4 | # Remove_the_Kth_last_element_from_a list
'''
without knowing the length of the list it is not trivial to delete the Kth element in a singly linked
list.
given a SLL and integer k, write a program to remove the kth last element from the list. Your algorithm
should not use more than a few wordsof storage, regardless of the length of the list. You can't assume
that it is posible to record the length of the list.
hint: if you know the length of the list, can you find kth last node using two iterators?
'''
'''
we use two iterators to traverse the list.The first irterator is advanced by k steps, and then the
two iterators advance in tandem. When first iterator reaches tail, the second iterator is at the
(k+1)th last node and we can remove the kth node.
'''
# assumes L has at least K nodes, deltes the kth last node in L.
def remove_kth_last_node(L,k):
dummy_head = ListNode(0,L)
first = dummy_head.next
for _ in range(k):
first = first.next
second = dummy_head
while first:
first, second = first.next, second.next
# second points to te (K+1)th last node, delete its successor.
second.next = second.next.next
return dummy_head.next
# time = O(n) space = O(1)
|
7485b72d642d1edefafea676e69d19e869b257c2 | MrHamdulay/csc3-capstone | /examples/data/Assignment_6/blxamu001/question1.py | 611 | 4.15625 | 4 | """Program that prints names aligned
Aubrey Baloi
22 April 2014"""
def names():
names = [] # Get an input of names
name = input('Enter strings (end with DONE):\n')
if name == 'DONE':
print('\nRight-aligned list:')
else:
while name != 'DONE':
names.append(name)
name=input()
print('\nRight-aligned list:')
long_name =max(names, key=len) #find maximum value in terms of length
long_length = len(long_name)
for i in names:
print(" "*(long_length-len(i)),i, sep='')
names() |
297c9826699b5b9e585e7282c18c2d5779d04044 | nortonhelton1/classcode | /hello-python (2)/hello-python/Calculator2.py | 210 | 4.3125 | 4 | number = int(input("Please input your number: "))
def even_odd(x):
if x % 2 == 0:
return "Your number is even."
else:
return "Your number is odd."
which = even_odd(number)
print(which) |
a97f0430bd4f8739e3a6887ce6ffa242c8f9c2ac | rheehot/Development | /하루에 한개씩 문제 풀기/Python/BOJ/구현/1157.py | 358 | 3.828125 | 4 | # boj, 1157 : 단어 공부, python3
from collections import Counter
def most_common(word):
word = word.lower()
c = Counter(word)
nums = c.most_common()
maximum = nums[0][1]
result = [num[0] for num in nums if num[1] == maximum]
return result[0].upper() if len(result) == 1 else '?'
word = str(input())
print(most_common(word)) |
57ccc70837939f7fae4a19353a2b379c7eecdac9 | reisenbrandt/python101 | /madlib.py | 140 | 3.953125 | 4 | name = input('Give me a name: ')
subject = input('Give me a subject: ')
print(name + "'s favorite subject in school is " + subject + ".")
|
058477618075460ab77ba0326501f52fa07c01cb | Janet-ctrl/Python_crash_oct | /Python crach course October/Chap05/toppings.py | 1,357 | 4.03125 | 4 | #requested_topping = 'mushrooms'
#if requested_topping != 'anchovies':
#print("Hold the anchovies!")
requested_toppings = ['mushrooms', 'onions', 'pineapple']
#requested_topping = 'pepper'
#if requested_topping in requested_toppings:
# print(f'The requested topping {requested_topping} is available.')
#else:
# print(f'The requested topping {requested_topping} is NOT available.')
#multiple conditions
requested_toppings = ['mushrooms', 'extra cheese']
# print("Adding mushrooms.")
#if 'pepperoni' in requested_toppings:
# print("Adding pepperoni.")
#if 'extra cheese' in requested_toppings:
# print("Adding extra cheese.")
# print("\nFinished making your pizza!")
#requested_toppings = ['mushrooms', 'extra cheese']
#if 'mushrooms' in requested_toppings:
#elif 'pepperoni' in requested_toppings:
# print("Adding pepperoni.")
#elif 'extra cheese' in requested_toppings:
# print("Adding extra cheese.")
# print("\nFinished making your pizza!")
available_toppings = ['mushrooms', 'olives', 'green peppers','pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print(f"Adding {requested_topping}.")
else:
print(f"Sorry, we don't have {requested_topping}.")
print("\nFinished making your pizza!") |
7957fb0204fda011d9eaf69b95635dcc886c4b48 | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4143/codes/1747_1533.py | 100 | 3.765625 | 4 | from math import*
a = float(input("Numo x: "))
k = int(input("Numero k: "))
soma = 0
i = 0
while () |
4df12dc8587f6af557ac86e6888fc054fc050e97 | lalitzz/DS | /Sequence5/CTCI/4-tree-graph/main/binarytree.py | 1,850 | 4.0625 | 4 | from collections import deque
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.parent = None
class BinaryTree:
def __init__(self):
self.root = None
def insertLeft(self, data, parent=None):
node = Node(data)
if parent is not None:
parent.left = node
node.parent = parent
elif parent is None and self.root is None:
self.root = node
return node
def insertRight(self, data, parent=None):
node = Node(data)
if parent is not None:
parent.right = node
node.parent = parent
elif parent is None and self.root is None:
self.root = node
return node
def search(self, data):
root = self.root
return self._search(root, data)
def _search(self, root, data):
if root is None or root.data == data:
return root
self.search(root.left, data)
self.search(root.right, data)
def delete(self, data):
node = self.search(data)
if node.parent is None:
self.root = None
elif node.parent.left == node:
tmp = node.parent
while tmp.right is not None:
tmp = tmp.right
tmp.right = node.right
node.parent.left = node.left
elif node.parent.right == node:
tmp = node.parent
while tmp.left is not None:
tmp = tmp.left
tmp.left = node.left
node.parent.right = node.right
def print_level(self):
root = self.root
Q = deque()
Q.append(root)
while len(Q) > 0:
node = Q.popleft()
print(node.data)
if node.left is not None:
Q.append(node.left)
if node.right is not None:
Q.append(node.right)
def main():
BT = BinaryTree()
n1 = BT.insertLeft(1)
n2 = BT.insertLeft(2, n1)
n3 = BT.insertRight(3, n1)
BT.print_level()
if __name__ == "__main__":
main() |
aecb90ab023aa1749821d7cd8831e3ec6b7237c9 | AXlIS/HomeWork | /Lesson1/Task5.1.py | 227 | 3.703125 | 4 | n = int(input('Ведите колличество чисел: '))
my_list = []
for i in range(1, n + 1):
my_list.append(int(input(f'Ведите {i}-е число:')))
my_list.sort(reverse=True)
print(my_list)
|
9445f508788679bce772ba86c282e200c10b452a | brian-dau/Rock-Paper-Scissors-Lizard-Spock | /RPSLS.py | 17,960 | 3.71875 | 4 | # An implementation of "Rock-Paper-Scissors-Lizard-Spock"
# By Brian Dau
import sys, random
from collections import Counter
from operator import itemgetter
class Player:
"""The user playing the computer"""
def __init__(self, name):
self.username = name
self.gamesplayed = 0
self.totalwins = 0
self.totallosses = 0
self.totalties = 0
self.cursor = 0
self.wins = 0
self.weapon = ""
self.choice = ""
self.movelist = []
if self.username in Data.playerdata:
self.cursor = Data.playerdata.index(self.username)
self.gamesplayed = Data.playerdata[self.cursor + 1]
self.totalwins = Data.playerdata[self.cursor + 2]
self.totalties = Data.playerdata[self.cursor + 3]
self.totallosses = self.gamesplayed - (self.totalwins + self.totalties)
print('Player "%s" loaded!' % self.username)
else:
Data.playerdata.extend((self.username, 0, 0, 0))
self.cursor = Data.playerdata.index(self.username)
self.gamesplayed = Data.playerdata[self.cursor + 1]
self.totalwins = Data.playerdata[self.cursor + 2]
self.totalties = Data.playerdata[self.cursor + 3]
self.totallosses = self.gamesplayed - (self.totalwins + self.totalties)
print('Player "%s" created!' % self.username)
def pickWeapon(self):
self.weapon = ""
while self.weapon not in Game.weapons.values():
if self.weapon == 'q' or self.weapon == 'quit':
self.gamenum = 0
self.wins = 0
Computer.wins = 0
main()
else:
self.weapon = str.lower(input("Select your weapon(or [q]uit): "))
self.movelist.append(self.weapon)
return self.weapon
def playerWins():
self.wins += 1
Game.gamenum += 1
self.gamesplayed += 1
self.totalwins += 1
print("Current score is %s: %s and Computer: %s" % (self.username, self.wins, Computer.wins))
class Computer:
"""The player's challenger"""
smart = True
stupidgamesplayed = 0
smartgamesplayed = 0
stupidwins = 0
stupidlosses = 0
stupidties = 0
smartwins = 0
smartlosses = 0
smartties = 0
wins = 0
selector = 0
weapon = ""
choice = ""
counting = []
playermoves = []
playerfav = ""
playerfavtie = ""
def __init__():
Computer.stupidgamesplayed = Data.computerdata[1]
Computer.stupidwins = Data.computerdata[2]
Computer.stupidties = Data.computerdata[3]
Computer.smartgamesplayed = Data.computerdata[4]
Computer.smartwins = Data.computerdata[5]
Computer.smartties = Data.computerdata[6]
def pickWeapon():
if Computer.smart == False:
Computer.selector = random.randint(0, 4)
Computer.weapon = Game.weapons[Computer.selector]
return Computer.weapon
else:
if len(user.movelist) == 1:
Computer.selector = random.randint(0, 4)
Computer.weapon = Game.weapons[Computer.selector]
return Computer.weapon
else:
Computer.counting = list(Counter(user.movelist).items())
Computer.playermoves = sorted(Computer.counting, key=itemgetter(1), reverse=True)
if len(Computer.playermoves) == 1:
Computer.playerfav = Computer.playermoves[0][0]
Computer.weapon = Computer.counterPick(self, Computer.playerfav)
return Computer.weapon
elif Computer.playermoves[0][1] == Computer.playermoves[1][1]:
Computer.playerfav = Computer.playermoves[0][0]
Computer.playerfavtie = Computer.playermoves[1][0]
Computer.weapon = Computer.counterPickTie(self, Computer.playerfav, Computer.playerfavtie)
return Computer.weapon
else:
Computer.playerfav = Computer.playermoves[0][0]
Computer.weapon = Computer.counterPick(self, Computer.playerfav)
return Computer.weapon
def counterPick(self, pick):
self.pick = pick
self.countervariable = random.randint(0, 1)
if self.pick == 'scissors':
if self.countervariable == 0:
return 'rock'
else:
return 'spock'
elif self.pick == 'paper':
if self.countervariable == 0:
return 'scissors'
else:
return 'lizard'
elif self.pick == 'rock':
if self.countervariable == 0:
return 'paper'
else:
return 'spock'
elif self.pick == 'lizard':
if self.countervariable == 0:
return 'rock'
else:
return 'scissors'
elif self.pick == 'spock':
if self.countervariable == 0:
return 'paper'
else:
return 'lizard'
def counterPickTie(self, pick1, pick2):
self.picklist = [pick1, pick2]
if 'scissors' in self.picklist and 'rock' in self.picklist:
return 'spock'
elif 'paper' in self.picklist and 'lizard' in self.picklist:
return 'scissors'
elif 'spock' in self.picklist and 'rock' in self.picklist:
return 'paper'
elif 'scissors' in self.picklist and 'lizard' in self.picklist:
return 'rock'
elif 'spock' in self.picklist and 'paper' in self.picklist:
return 'lizard'
elif 'scissors' in self.picklist and 'paper' in self.picklist:
return 'scissors'
elif 'paper' in self.picklist and 'rock' in self.picklist:
return 'paper'
elif 'rock' in self.picklist and 'lizard' in self.picklist:
return 'rock'
elif 'lizard' in self.picklist and 'spock' in self.picklist:
return 'lizard'
elif 'spock' in self.picklist and 'scissors' in self.picklist:
return 'spock'
def computerWins():
if Computer.smart == False:
Computer.wins += 1
Game.gamenum += 1
Computer.stupidwins += 1
Computer.stupidgamesplayed += 1
print("Current score is %s: %s and Computer: %s" % (user.username, user.wins, Computer.wins))
else:
Computer.wins += 1
Game.gamenum += 1
Computer.smartwins += 1
Computer.smartgamesplayed += 1
print("Current score is %s: %s and Computer: %s" % (user.username, user.wins, Computer.wins))
class Game:
"""Runs the game"""
prompt = ""
playto = 0
gamenum = 0
weapons = {0: 'rock',
1: 'paper',
2: 'scissors',
3: 'lizard',
4: 'spock'}
messages = {0: 'Scissors cut paper',
1: 'Paper covers rock',
2: 'Rock crushes lizard',
3: 'Lizard poisons Spock',
4: 'Spock smashes scissors',
5: 'Scissors decapitate lizard',
6: 'Lizard eats paper',
7: 'Paper disproves Spock',
8: 'Spock vaporizes rock',
9: 'Rock crushes scissors'}
pchoice = ""
cchoice = ""
def __init__(self, playto = -1):
Game.playto = playto
while Game.gamenum < Game.playto:
user.choice = user.pickWeapon()
Computer.choice = Computer.pickWeapon()
print("%s picks: %s." % (user.username, user.choice))
print("Computer picks: %s." % Computer.choice)
if user.choice == Computer.choice:
print("It's a draw! Starting round over...")
user.totalties += 1
if Computer.smart:
Computer.smartties += 1
else:
Computer.stupidties += 1
else:
Game.decideWinner(self, user.choice, Computer.choice)
if user.wins > Computer.wins:
print("Game over. %s won the game!" % user.username)
elif Computer.wins > user.wins:
print("Game over. Computer won the game!")
else:
print("It's a draw. Play an odd number of games to avoid this embarrassment.")
print("---------------------------------------------------------------------------")
print("Showing statistics for %s." % user.username)
print("Games played: %s. Record: %s-%s-%s." % (user.gamesplayed, user.totalwins, user.totallosses, user.totalties))
print("Win percentage: %s percent" % ((user.totalwins // user.gamesplayed) * 100))
print("Showing statistics for Smart AI.")
print("Games played: %s. Record: %s-%s-%s." % (Computer.smartgamesplayed, Computer.smartwins, Computer.smartlosses, Computer.smartties))
if Computer.smartgamesplayed != 0:
print("Win percentage: %s percent" % ((Computer.smartwins // Computer.smartgamesplayed) * 100))
print("Showing statistics for Stupid AI.")
print("Games played: %s. Record: %s-%s-%s." % (Computer.stupidgamesplayed, Computer.stupidwins, Computer.stupidlosses, Computer.stupidties))
if Computer.stupidgamesplayed != 0:
print("Win percentage: %s percent" % ((Computer.stupidwins // Computer.stupidgamesplayed) * 100))
print("---------------------------------------------------------------------------")
self.end = str.lower(input("Would you like to play again? y/n: "))
if self.end == 'n':
main()
else:
Game.gamenum = 0
user.wins = 0
Computer.wins = 0
user.movelist = []
self.play = Game(int(input("Enter number of rounds to play or press return to play forever: ")))
def decideWinner(self, playerchoice, computerchoice):
self.pchoice = playerchoice
self.cchoice = computerchoice
if self.pchoice == 'scissors':
if self.cchoice == 'paper':
print("%s. %s wins!" % (Game.messages[0], user.username))
user.playerWins()
elif self.cchoice == 'lizard':
print("%s. %s wins!" % (Game.messages[5], user.username))
user.playerWins()
elif self.cchoice == 'rock':
print("%s. Computer wins!" % Game.messages[9])
Computer.computerWins()
elif self.cchoice == 'spock':
print("%s. Computer wins!" % Game.messages[4])
Computer.computerWins()
elif self.pchoice == 'paper':
if self.cchoice == 'spock':
print("%s. %s wins!" % (Game.messages[7], user.username))
user.playerWins()
elif self.cchoice == 'rock':
print("%s. %s wins!" % (Game.messages[1], user.username))
user.playerWins()
elif self.cchoice == 'scissors':
print("%s. Computer wins!" % Game.messages[0])
Computer.computerWins()
elif self.cchoice == 'lizard':
print("%s. Computer wins!" % Game.messages[6])
Computer.computerWins()
elif self.pchoice == 'rock':
if self.cchoice == 'scissors':
print("%s. %s wins!" % (Game.messages[9], user.username))
user.playerWins()
elif self.cchoice == 'lizard':
print("%s. %s wins!" % (Game.messages[2], user.username))
user.playerWins()
elif self.cchoice == 'paper':
print("%s. Computer wins!" % Game.messages[1])
Computer.computerWins()
elif self.cchoice == 'spock':
print("%s. Computer wins!" % Game.messages[8])
Computer.computerWins()
elif self.pchoice == 'lizard':
if self.cchoice == 'paper':
print("%s. %s wins!" % (Game.messages[6], user.username))
user.playerWins()
elif self.cchoice == 'spock':
print("%s. %s wins!" % (Game.messages[3], user.username))
user.playerWins()
elif self.cchoice == 'scissors':
print("%s. Computer wins!" % Game.messages[5])
Computer.computerWins()
elif self.cchoice == 'rock':
print("%s. Computer wins!" % Game.messages[2])
Computer.computerWins()
elif self.pchoice == 'spock':
if self.cchoice == 'scissors':
print("%s. %s wins!" % (Game.messages[4], user.username))
user.playerWins()
elif self.cchoice == 'rock':
print("%s. %s wins!" % (Game.messages[8], user.username))
user.playerWins()
elif self.cchoice == 'paper':
print("%s. Computer wins!" % Game.messages[7])
Computer.computerWins()
elif self.cchoice == 'lizard':
print("%s. Computer wins!" % Game.messages[3])
Computer.computerWins()
def quitgame():
data.saveData()
print("Thanks for playing!")
sys.exit()
class Data:
"""Handles data.txt file"""
# playerdata is a list of players created, each followed by
# three integers: gamesplayed, totalwins, and totalties
# [0] of playerdata is 'players'
# computerdata is a list where [0] is 'statistics' followed by
# six integers: stupidgamesplayed, stupidwins, stupidties,
# smartgamesplayed, smartwins, smartties
filedata = []
playerdata = []
computerdata = []
splitter = 0
def __init__():
with open('data', 'r') as self.f:
self.filedata = self.f.read().split('\n')
self.splitter = self.filedata.index("statistics")
self.playerdata = self.filedata[:self.splitter]
self.computerdata = self.filedata[self.splitter:]
def saveData():
Data.playerdata[user.cursor + 1] = user.gamesplayed
Data.playerdata[user.cursor + 2] = user.totalwins
Data.playerdata[user.cursor + 3] = user.totalties
Data.computerdata[1] = Computer.stupidgamesplayed
Data.computerdata[2] = Computer.stupidwins
Data.computerdata[3] = Computer.stupidties
Data.computerdata[4] = Computer.smartgamesplayed
Data.computerdata[5] = Computer.smartwins
Data.computerdata[6] = Computer.smartties
self.filedata = self.playerdata + self.computerdata
with open('data', 'w') as self.f:
for item in self.filedata:
self.f.write("%s\n" % item)
def main():
menuprompt = ""
nametest = ""
playerloaded = False
print("Welcome to Rock-Paper-Scissors-Lizard-Spock!")
print("Please select a menu option below.")
showHelp()
while True:
menuprompt = str.lower(input("> "))
if menuprompt == '1' or menuprompt == 'p':
nametest = input("Enter your name: ")
if nametest == 'players' or nametest == 'statistics':
print("Very good, Mr. Bond. But I won't let you break my program so easily.")
print("Returning to main menu.")
else:
user = Player(nametest)
playerloaded = True
elif menuprompt == '2' or menuprompt == 'g':
if playerloaded:
menuprompt = str.lower(input("Play [s]mart AI or [r]andom AI: "))
if menuprompt == 's' or menuprompt == 'smart':
Computer.smart = True
elif menuprompt == 'r' or menuprompt == 'random':
Computer.smart = False
else:
print("Command not recognized, returning to main menu")
showHelp()
play = Game(int(input("Enter number of rounds to play or press return to play forever: ")))
else:
print("No player loaded, returning to main menu.")
elif menuprompt == '3' or menuprompt == 's':
if playerloaded:
print("Showing statistics for %s:" % user.username)
print("Games played: %s. Record: %s-%s-%s." % (user.gamesplayed, user.totalwins, user.totallosses, user.totalties))
if user.gamesplayed != 0:
print("Win percentage: %s percent" % ((user.totalwins // user.gamesplayed) * 100))
else:
print("No player loaded.")
print("Showing statistics for Smart AI:")
print("Games played: %s. Record: %s-%s-%s." % (Computer.smartgamesplayed, Computer.smartwins, Computer.smartlosses, Computer.smartties))
if Computer.smartgamesplayed != 0:
print("Win percentage: %s percent" % ((Computer.smartwins // Computer.smartgamesplayed) * 100))
print("Showing statistics for Stupid AI:")
print("Games played: %s. Record: %s-%s-%s." % (Computer.stupidgamesplayed, Computer.stupidwins, Computer.stupidlosses, Computer.stupidties))
if Computer.stupidgamesplayed != 0:
print("Win percentage: %s percent" % ((Computer.stupidwins // Computer.stupidgamesplayed) * 100))
elif menuprompt == '4' or menuprompt == 'o':
showHelp()
elif menuprompt == '5' or menuprompt == 'q':
Data.saveData()
print("Thanks for playing!")
sys.exit()
else:
print("Command not recognized, try again.")
def showHelp():
print("1. Create or load a [p]layer.")
print("2. Start a new [g]ame.")
print("3. View [s]tatistics.")
print("4. Show [o]ptions again.")
print("5. [Q]uit game.")
data = Data
main()
|
3e622aa290a3d1a17b75d4b41de578215a387449 | icmpnorequest/Pytorch_Learning | /Python3/nlp/cbow.py | 3,124 | 3.59375 | 4 | # coding = utf8
"""
@author: Yantong Lai
@date: 2019.10.31
"""
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
torch.manual_seed(1)
# Definitions
CONTEXT_SIZE = 2 # 2 words to the left, 2 words to the right
EMBEDDING_DIM = 100
# Hyper-parameters
learning_rate = 0.001
num_epochs = 10
raw_text = """We are about to study the idea of a computational process.
Computational processes are abstract beings that inhabit computers.
As they evolve, processes manipulate other abstract things called data.
The evolution of a process is directed by a pattern of rules
called a program. People create programs to direct processes. In effect,
we conjure the spirits of the computer with our spells.""".split()
vocab = set(raw_text)
vocab_size = len(vocab)
word_to_idx = {word:i for i, word in enumerate(vocab)}
print("word_to_idx = {}\n".format(word_to_idx))
data = []
for i in range(2, len(raw_text) - 2):
context = [raw_text[i - 2], raw_text[i - 1],
raw_text[i + 1], raw_text[i + 2]]
target = raw_text[i]
data.append((context, target))
print("data[:5] = {}\n".format(data[:5]))
# Continuous Bag-of-Word
class CBOW(nn.Module):
def __init__(self, vocab_size, embedding_dim, context_size):
super(CBOW, self).__init__()
self.embeddings = nn.Embedding(vocab_size, embedding_dim)
self.linear1 = nn.Linear(in_features=context_size * embedding_dim,
out_features=128)
self.linear2 = nn.Linear(in_features=128, out_features=vocab_size)
def forward(self, inputs):
embeds = self.embeddings(inputs).view((1, -1))
out = F.relu(self.linear1(embeds))
out = self.linear2(out)
log_probs = F.log_softmax(out, dim=1)
return log_probs
def make_context_vector(context, word_to_ix):
"""
It is a function to change <Int> idx to tensor.
:param context: context word
:param word_to_ix: index of the word
:return: tensor(idx)
"""
idxs = [word_to_idx[w] for w in context]
return torch.tensor(idxs, dtype=torch.long)
# print(make_context_vector(data[0][0], word_to_idx))
losses = []
loss_function = nn.NLLLoss()
# context, 2 words to the left, 2 words to the right
model = CBOW(vocab_size=vocab_size, embedding_dim=EMBEDDING_DIM, context_size=CONTEXT_SIZE * 2)
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
for epoch in range(num_epochs):
total_loss = 0
for context, target in data:
context_ids = make_context_vector(context, word_to_idx)
model.zero_grad()
log_probs = model(context_ids)
label = torch.tensor([word_to_idx[target]], dtype=torch.long)
loss = loss_function(log_probs, label)
loss.backward()
optimizer.step()
total_loss += loss.item()
losses.append(total_loss)
print(losses)
print("\n")
print(make_context_vector(data[0][0], word_to_idx))
print(model.embeddings(make_context_vector(data[0][0], word_to_idx)))
print(model.embeddings(make_context_vector(data[0][0], word_to_idx)).size())
# torch.Size([4, 100])
|
a5f6a1d58e0178e7a59574a72ffada9715ecc5a2 | owenyi/encore | /00_algorithm/Stage1/05_Hash/problem3.py | 305 | 3.609375 | 4 | # 전화번호 목록
def solution(phone_book):
phone_book.sort()
for i in range(1, len(phone_book)):
if phone_book[i - 1] == phone_book[i][:len(phone_book[i - 1])]:
return False
return True
phone_book = ["119", "21", "97674223", "1195524421"]
print(solution(phone_book)) |
2a8874d89a074046c11d7da3c6765cc2c3a66c44 | TravisEntner/hello-world-Project- | /main.py | 317 | 4.0625 | 4 | #count = 0
#statment = input("Enter a statment ")
#guess = input("type a letter to find in your statment ")
#for letter in statment:
# if letter == guess:
# count += 1
#print(count, "letters found")
test = "Pyton Programing"
print("String: ", test)
print("First character: ", test[:1])
print("Last character: ", test[-1]) |
941e64fb3875feb500762fbbbbc019ac5a435cb2 | desl0451/pythonbase | /python2/python2_4.py | 815 | 3.828125 | 4 | # coding=utf-8
# 乘法
print 'python ' * 5 # python python python python python
print [42] * 10 # [42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
print 42 * 10 # 420 乘法计算
sequence = [None] * 10
print sequence
# 序列(字符串) 乘法示例
# 以正确的宽度在居中的"盒子"内打印一个句子
# 注意,整数除法运算符(//)只能用在python 2.2
sentence = raw_input("Sentence:")
screen_width = 80
text_width = len(sentence)
box_width = text_width + 6
left_margin = (screen_width - box_width) // 2
print
print '' * left_margin + '+' + '-' * (box_width - 2) + '+'
print '' * left_margin + '| ' + ' ' * text_width + ' |'
print '' * left_margin + '| ' + sentence + ' |'
print '' * left_margin + '| ' + ' ' * text_width + ' |'
print '' * left_margin + '+' + '-' * (box_width - 2) + '+'
|
3309eee43f09389531d02202a5fed0e56689f3ca | leooliveira135/machine_learning_python | /Intro-Python.py | 1,286 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
1+1
# In[2]:
print("Hello World")
# In[1]:
s1 = {1,2,3,4}
s2 = {3,4,5,6}
inter = s1.intersection(s2)
print(inter)
# In[2]:
s1 = {1,2,3,4}
s2 = {3,4,5,6}
diff = s1.difference(s2)
print(diff)
# In[4]:
lista = [1,2,3,3,3,4,5,5,6,7,7,7]
s = set(lista)
print(s)
# In[19]:
dic = {"marcos":28,"maria":20,"pedro":18}
print(dic)
print(dic['marcos'])
dic['marcos']=25
print(dic['marcos'])
dic['felipe']=30
print(dic)
for k in dic:
print(dic[k], end=" ")
print("\n",dic.items())
print(dic.keys())
print(dic.values())
print('maria' in dic)
print('python' in dic)
# In[27]:
def f(*args):
return print(sum(args))
lista = 1,2,3,4
f(*lista)
# In[29]:
class Conta:
def __init__(self,cliente,numero):
self.cliente = cliente
self.numero = numero
class ContaEspecial(Conta):
def __init__(self,cliente,numero,limite=0):
Conta.__init__(self,cliente,numero)
self.limite = limite
c = ContaEspecial('leo','1234',100)
print(c.limite)
print(c.numero)
# In[34]:
dobro = lambda x: x*2
print(dobro(3))
soma = lambda x, y: x+y
print(soma(10,20))
lista = [1,2,3,4,5,6,7,8,9,10]
list(filter(lambda x: x%2 == 0, lista))
list(map(lambda x: x*2, lista))
|
ab9aead77fab4338aba26a1b3999a55f0ed91ceb | pogong/MessageDisplayTrain | /trim.py | 387 | 3.546875 | 4 | def trim(s):
ll = len(s)
forwardIndex = 0
backwardIndex = ll - 1
while forwardIndex < ll and s[forwardIndex] == ' ':
forwardIndex = forwardIndex + 1
while backwardIndex >= forwardIndex and s[backwardIndex] == ' ':
backwardIndex = backwardIndex - 1
new = s[forwardIndex:backwardIndex+1]
return new
print(trim('hello^zc '))
|
9185f9ef8ff1c5797b6c53b5b2c92c41bf88ec2c | qq279585876/algorithm | /ib/7.DynamicProgramming/LC085. Max Rectangle In Binary Matrix.py | 3,394 | 3.671875 | 4 | '''
Given a 2D binary matrix filled with 0’s and 1’s, find the largest rectangle
containing all ones and return its area.
Bonus if you can solve it in O(n^2) or less.
Example :
A : [ 1 1 1
0 1 1
1 0 0
]
Output : 4
As the max area rectangle is created by the 2x2 rectangle created by (0,1),
(0,2), (1,1) and (1,2)
'''
class Solution:
# dp solution O(m*n)
# process row by row from the top, find the max left, min right and height
# https://discuss.leetcode.com/topic/6650/share-my-dp-solution
def maximalRectangle(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
if not matrix:
return 0
n = len(matrix[0])
left, right, height = [0] * n, [n-1] * n, [0] * n
max_area = 0
for row in matrix:
# calculate height - height reset to 0 if cell val is 0
for c in range(n):
height[c] = height[c] + 1 if row[c] == '1' else 0
# calculate left
cur_left = 0
for c in range(n):
# when row[c] is 0, left[c] can be set to any val <= 0 because
# its height is 0. but it must be small enough so that next
# row's left val can be set correctly
left[c] = max(left[c], cur_left) if row[c] == '1' else 0
if row[c] == '0':
cur_left = c + 1
# calculate right
cur_right = n - 1
for c in reversed(range(n)):
# when row[c] is 0, right[c] can be set to any val >= n-1
# because its height is 0. but it must be big enough so that
# next row's right val can be set correctly
right[c] = min(right[c], cur_right) if row[c] == '1' else n-1
if row[c] == '0':
cur_right = c - 1
# calculate max_area
for c in range(n):
max_area = max(max_area, (right[c] - left[c] + 1) * height[c])
return max_area
# using largest rectangle in histogram lc084 - O(m*n)
# for each row calculate the heights array and treat it as historgram
def maximalRectangle2(self, matrix):
if not matrix:
return 0
heights = [0] * len(matrix[0])
max_area = 0
for row in matrix:
# calculate the height for each row
for c in range(len(row)):
heights[c] = heights[c] + 1 if row[c] == '1' else 0
# treat heights as histogram
heights.append(0)
stack = [-1] # previous index with smaller height
for i, height in enumerate(heights):
while height < heights[stack[-1]]:
h = heights[stack.pop()]
w = i - 1 - stack[-1]
max_area = max(max_area, h * w)
stack.append(i)
heights.pop()
return max_area
# test
print(Solution().maximalRectangle(["1"]))
print(Solution().maximalRectangle(["10"]))
print(Solution().maximalRectangle(["01","10"]))
print(Solution().maximalRectangle(["10100","10111","11111","10010"]))
print(Solution().maximalRectangle2(["1"]))
print(Solution().maximalRectangle2(["10"]))
print(Solution().maximalRectangle2(["01","10"]))
print(Solution().maximalRectangle2(["10100","10111","11111","10010"]))
|
9818837a4cb6505e8f9b49a19894e604ef4908da | kpranshu/python-demos | /20-Tkinter/tk-events-1.py | 652 | 3.65625 | 4 | from tkinter import *
from tkinter import messagebox
win=Tk()
win.option_add('*font', ('verdana', 14, 'bold'))
win.state('zoomed')
def Add():
a=int(txt1.get(1.0, END))
b=int(txt2.get(1.0, END))
c=a+b
messagebox.showinfo("Result", c)
lbl1=Label(win,text="First Number : ")
lbl2=Label(win,text="Second Number : ")
txt1=Text(win, height=1, width=30)
txt2=Text(win, height=1, width=30)
btnAdd=Button(win, text="Add", command=Add)
lbl1.place(in_=win, x=400, y=200)
txt1.place(in_=win, x=600, y=200)
lbl2.place(in_=win, x=400, y=300)
txt2.place(in_=win, x=600, y=300)
btnAdd.place(in_=win, x=500, y=400)
|
189bbfb6354270be0b25c0c1d4328c68b35057c6 | claudiadang/Simple-Life | /C4E10Apr17_1.py | 261 | 4.09375 | 4 | Sua gi sua lam the
print ( "I am Claudia")
print (8)
print (3)
a=2
print(a)
b=5
##print(b)
##n = input( "what's your name?")
##print("Hello",n)
####print("a" +"b")
##a = input ("what's your age?")
yob= int(input ("Your year of birth?"))
print(2017 -yob)
|
c8173af1996e939c7f7b862e65a2f05a0b3b3971 | haruka443/brackets | /brackets.py | 328 | 4.0625 | 4 | writing = 'Ala ma <kota>, a kot ma Alę'
startPosition = None
endPosition = None
for position, letter in enumerate(writing):
if letter == '<':
startPosition = position
elif letter == '>':
endPosition = position - 1
break
print(f'Between <> are {endPosition - startPosition} signs')
|
d6b4b438b225fa87766f6ba54136dcf505f438b5 | UWPCE-PythonCert-ClassRepos/Self_Paced-Online | /students/Gregg/lesson2/fizzbuzz.py | 2,053 | 4.34375 | 4 | def FizzBuzz(int_in):
"""Determine the FizzBuzziness of an input int and return the appropriate string"""
#I already did the straightforward version on the programing test for this course
#so I thought I would try something new, see if I could get only 1 if statement
string = 'Fizz'*(not(int_in%3))+'Buzz'*(not(int_in%5))
if not(string):
string = str(int_in)
return string
def FizzBuzz_iterate(end_int_in = 100):
"""Print the FizzBuzziness for positive numbers up to the input"""
for i in range(end_int_in):
print(FizzBuzz(i+1))
########
#Extra messing around with fizzbuzz#
########
def Fizzbuzz(int_in):
"""Determine the Fizzbuzziness of an input int and return the appropriate string
I believe the original version required a lowercase b if both conditions were met
which makes it a bit harder to do without multiple if statements
Maybe its not the original but some modification I read about to make it more relevant"""
b = 'B'*(bool(int_in%3))+'b'*(not(int_in%3))
string = 'Fizz'*(not(int_in%3))+(b+'uzz')*(not(int_in%5))
return(string+(not(string))*str(int_in))
def Fizzbuzz100_OneLine(end_int_in = 100):
"""Print the fizzbuzziness of 1-100 with one line of code
including the loop in the single line? not sure about this
I know this is terrible practice but wanted to see if I could do it"""
for line in [(('Fizz'*(not(num%3))+(('B'*(bool(num%3))+'b'*(not(num%3)))+'uzz')*(not(num%5))) or str(num)) for num in range(1,end_int_in+1)]: print(line)
#Found more elegant way to do it on Micheal Gililands blog
#using join that eliminates the second for loop
#Still would need the modification for the lowercase b
#Also, this use of or is nice, I didn't know it could return the non boolean input
#print '\n'.join("Fizz"*(i%3==0)+"Buzz"*(i%5==0) or str(i) for i in range(1,101))
return True
#Irrelevant change to test git commit, again
if __name__ == "__main__":
print('Lesson 2: FizzBuzz exercise')
FizzBuzz_iterate()
|
cb0da1983443081e0ef89ab8d99feb813c7b6e07 | biomathcode/Rosalind_solutions | /algorithmic_heights/FIBO.py | 377 | 4.34375 | 4 | #first creating a dynamic function for calculating fibonacci function
def dynFibonacci(n):
store = {}
store[0], store[1] = 0,1
#print(store)
for i in range(2, n+1):
store[i] = store[i -1] + store[i-2]
#print(store)
return store[n]
if __name__ == "__main__":
number = int(input('the nth fibonacci number is'))
print(dynFibonacci(number)) |
28401b9306e603ba693801dc6bfe8db57a4886a6 | Diego-18/python-algorithmic-exercises | /v1/area_y_angulo_1.py | 778 | 4.03125 | 4 | from math import sqrt, asin, pi
def area_triangulo(a, b, c):
s = (a + b + c) / 2.0
return sqrt(s * (s-a) * (s-b) * (s-c))
def angulo_alfa(a, b, c):
s = area_triangulo(a, b, c)
return 180 / pi * asin(2.0 * s / (b*c))
def menu():
opcion = 0
while opcion != 1 and opcion != 2:
print '1) Calcular rea del tringulo'
print '2) Calcular ngulo opuesto al primer lado'
opcion = int(raw_input('Escoge opcin: '))
return opcion
lado1 = float(raw_input('Dame lado a: '))
lado2 = float(raw_input('Dame lado b: '))
lado3 = float(raw_input('Dame lado c: '))
s = menu()
if s == 1:
resultado = area_triangulo(lado1, lado2, lado3)
else:
resultado = angulo_alfa(lado1, lado2, lado3)
print 'Escogiste la opcin', s
print 'El resultado es:', resultado
|
d0d331d0c54d0a624cba71ab3d9b84fee6ac911c | rlarsby/CS50x-Introduction-to-Computer-Science | /pset6/dna/dna.py | 1,589 | 3.875 | 4 | import csv
import sys
#check if correct input
if len(sys.argv) != 3:
print("Usage: python dna.py 'database.csv' 'sequence.txt'")
sys.exit(1)
#open sequence and read
sequence = open(sys.argv[2], 'r').read()
for row in sequence:
dnalist = row
#store sequence in a string
dna = dnalist[0]
#obtain individuals sequences from the database
with open(sys.argv[1]) as database:
data = csv.reader(database)
for row in data:
dnaSeqs = row
dnaSeqs.pop(0)
break
#create dict where we store sequences to compare later
seqs = {}
#copy the list in a dict with genes as keys
for item in dnaSeqs:
seqs[item] = 1
#iterate through sequence, count and store max value of each strand
for strand in seqs:
i = 0
cur_max = 0
max_strand = 0
#scan over sequence and find longest strand
while i < len(sequence):
window = sequence[i:i + len(strand)]
if window == strand:
cur_max = cur_max + 1
max_strand = max(max_strand, cur_max)
i = i + len(strand)
#reset current max and move window one step
else:
cur_max = 0
i = i + 1
#store max in dict
seqs[strand] = max_strand
#check if it matches
with open(sys.argv[1], newline='') as database:
data = csv.DictReader(database)
for person in data:
match = 0
for dna in seqs:
if int(seqs[dna]) == int(person[dna]):
match = match + 1
if match == len(seqs):
print(person['name'])
sys.exit(0)
print("No match") |
8f4a9119412eae6121b99b65fcfb5dacb9e994de | zahrahcitra/KIJ_A | /5114100012.py | 3,039 | 3.515625 | 4 | #Zahrah Citra Hafizha
#5114100012
#KIJ A
#Tugas Encrypt Decrypt
from operator import xor
def function (asciitext, asciisecret): #fungsi encrypt
hasil = [None] * len(asciitext) #buat array kosongan
hasilchar = [None] * len(asciitext)
leftmost = [None] * 4 #bagian kiri
rightmost = [None] * 4 #bagian kanan
for i in range(0,4):
leftmost[i] = asciisecret[i]
rightmost[i] = asciisecret[i+4] #tambah 4 bit dr yang kiri
#lakukan proses xor antara p dan k0
index = 0
blok = len(asciitext) / 4 #dibagi per blok
for i in range(0, blok):
for j in range(0, 4):
hasil[index] = xor(asciitext[index], leftmost[j]) #xor
index += 1
index = 0
#print "before (hasil xor sebelum ditambah)", hasil
for i in range(0, blok):
for j in range(0, 4):
hasil[index] = hasil[index]+ rightmost[j] #tambahin hasil proses sebelumnya dengan k1
hasil[index] = hasil[index] % 256 #yang di mod 2pangkat64
index += 1
#print "after", hasil
#change to character
for i in range(0,len(asciitext)):
hasilchar[i] = chr(hasil[i])#jadi karakter
#print "hasil : ", hasil
print "hasil encrypt : ", hasilchar
#print "mulai proses DECRYPT"
tempasc = [None] * len(asciitext)
for i in range (0, len(asciitext)):
tempasc[i] = ord(hasilchar[i]) #ke ascii
tempmin = [None] * len(asciitext)
index = 0
for i in range(0, blok):
for j in range(0, 4):
tempmin[index] = tempasc[index] - rightmost[j] #dibalikin waktu sebelum
index += 1
#print "before add-ing", tempmin
tempxor = [None] * len(asciitext)
index = 0
for i in range(0, blok):
for j in range (0,4):
tempxor[index] = xor(tempmin[index], leftmost[j])
index += 1
hasildec = [None] * len(asciitext)
for i in range(0, len(asciitext)):
hasildec[i] = chr(tempxor[i])
print "hasil decrypt : ", hasildec
return hasildec
secret = raw_input("Masukkan secret key: ") #secret key
longsecret = len(secret)
ascsec = [None] * longsecret #bikin array kosong
for i in range(0, longsecret):
ascsec[i] = ord(secret[i]) #mengkonversikan secret key ke ascii
text = raw_input("Masukkan input: ")#masukin input yg mau di encrypt decrypt
longtext = len(text)#itungjumlah huruf
longdata = longtext
#hitung panjang karakter yg di proses, harus 32 bit
if longtext % 4 > 0: #kalo di mod nya masih ada sisa
sisa = 4 - (longtext % 4)
longdata = longtext + sisa
datatext = [None] * longdata
for i in range(0, longdata):
if i < longtext:
datatext[i] = text[i]
else:
datatext[i] = " " #ditambahin tapi pake kosongan
textascii = [None] * longdata #kosongan
for i in range(0, longdata):
textascii[i] = ord(datatext[i]) #konversi dr string ke ascii
#print "asciitext ", textascii
hasil = function(textascii, ascsec)
print hasil
|
786d76e1d8e00efd85194b588ed6c75983eafb55 | Lee-Jae-heun/python_pr | /baekjoon/2753.py | 170 | 3.65625 | 4 | year = int(input())
if 1 <= year <= 4000:
if year%4 == 0 and year%100 != 0:
print("1")
elif year%400 == 0:
print("1")
else:
print("0") |
f3c10b58fff6784d5c838b0420a1045c29991bdc | EderBraz/URI---Solutions | /Py/1164.py | 273 | 3.5625 | 4 | qte = int(input())
for i in range(qte):
num = int(input())
soma = 0
for i in range(1, num):
if num % i == 0:
soma += i
if soma == num:
print("{} eh perfeito".format(num))
else:
print("{} nao eh perfeito".format(num)) |
a48db77b1013dc98e77732b1c73f44715f6c9b55 | loragriffin/digitalcrafts_exercises | /interview challenges/week-1/algorithm5.py | 248 | 3.609375 | 4 | primelist = []
def prime(i):
for j in range(2, i):
if i % j == 0:
return False
i = 2
while len(primelist) < 1000:
if prime(i) != False:
primelist.append(i)
i += 1
# print(primelist)
print(primelist[-1])
|
a482a02ca0a74fda0f448e135b2b2a614352b470 | erpost/python-beginnings | /tuples/tuple_return_sorted_sequence.py | 117 | 3.65625 | 4 | # Return sorted sequence (by key order)
d = {'a': 10, 'c': 22, 'b': 1}
for k, v in sorted(d.items()):
print(k,v) |
fa18d583800f3fe32af5b7d51e2ecdce556cfe7a | zejuniortdr/math-challenges | /prisonbreak-cypher.py | 1,347 | 3.796875 | 4 | #!/usr/bin/env python
# coding: utf-8
def log(txt):
print "===================================="
print txt
print "===================================="
def prisonbreak_encode(text):
convert = {
0: ['+'],
1: [' '],
2: ['A','B','C'],
3: ['D','E','F'],
4: ['G','H', 'I'],
5: ['J','K', 'L'],
6: ['M','N', 'O'],
7: ['P','Q', 'R', 'S'],
8: ['T','U', 'V'],
9: ['W','X', 'Y', 'Z'],
}
number = ''
dots = ''
for l in text.upper():
for k, v in convert.items():
pos = 0
for v2 in v:
if v2 == l:
number += '{}'.format(k)
i = 0
while i < pos+1:
dots += '.'
i += 1
dots += ' '
pos += 1
dots = dots.strip()
log([number, dots])
return [number, dots]
def prisonbreak_decode(text, dots):
convert = {
0: ['+'],
1: [' '],
2: ['A','B','C'],
3: ['D','E','F'],
4: ['G','H', 'I'],
5: ['J','K', 'L'],
6: ['M','N', 'O'],
7: ['P','Q', 'R', 'S'],
8: ['T','U', 'V'],
9: ['W','X', 'Y', 'Z'],
}
number = str(text)
dots_arr = dots.split(' ')
decoded_text = ''
log(dots_arr)
i = 0
for d in dots_arr:
letter = convert[int(number[i])][len(d)-1]
decoded_text += '{}'.format(letter)
i += 1
log(decoded_text)
return decoded_text
if __name__ == '__main__':
txt = raw_input("Text to encode: ")
ret = prisonbreak_encode(txt)
prisonbreak_decode(ret[0], ret[1]) |
f5b465df11fb0207a5b834a4912068b26cb93229 | ncfoa/100DaysOfCode_Python | /085/main.py | 1,998 | 3.796875 | 4 | import time
from tkinter import *
from tkmacosx import Button as btn
from tkinter import scrolledtext
import math
WHITE = "#FFFFFF"
BLACK = "#000000"
RED = "#ff0000"
GOLD = "#d3bc8d"
FONT = "Courier"
timer = None
# Timer
def start_timer():
time.sleep(2)
text.focus()
w.after(3000, lt.config(text="GO!"))
count_down(60)
# CountDown
def count_down(n):
count_s = "{:02d}".format(n % 60)
c.itemconfigure(txt, text=f"{count_s}")
if n > 0:
global timer
timer = w.after(1000, count_down, n - 1)
else:
words = text.get('1.0', END)
lw = len(words)
wpm = lw / 5
lt.config(text=f"You typed {wpm} words per minute!")
instructions = '''Press the start button when ready. You will have 3 seconds to prepare to start typing.
Use the following sentences during the test if you finish with the last sentence start from the top again. '''
sentences = '''
The quick brown fox jumped over the lazy dog.
My girl wove six dozen plaid jackets before she quit.
A wizard’s job is to vex chumps quickly in fog.
When zombies arrive, quickly fax Judge Pat.
Pack my box with five dozen liquor jugs.'''
# UI SETUP
w = Tk()
w.title("Words Per Minute")
w.config(padx=100, pady=50, bg=BLACK)
i = Label(fg=GOLD, bg=BLACK, font=(FONT, 15, "bold"), text=instructions)
i.grid(column=1, row=0)
i2 = Label(fg=WHITE, bg=BLACK, font=(FONT, 15, "bold"), text=sentences)
i2.grid(column=1, row=1)
lt = Label(fg=GOLD, bg=BLACK, font=(FONT, 40, "bold"), text="Get Ready")
lt.grid(column=1, row=2)
c = Canvas(width=200, height=224, bg=BLACK, highlightthickness=0)
txt = c.create_text(100, 120, text="60", fill="white", font=(FONT, 35, "bold"))
c.grid(column=1, row=3)
sb = btn(w, text="START", bg=GOLD, fg=BLACK, borderless=1, command=start_timer)
sb.grid(column=1, row=4)
text = scrolledtext.ScrolledText(w, height=8, width=40)
scroll = Scrollbar(w)
text.configure(yscrollcommand=scroll.set)
text.grid(column=1, row=5)
text.insert(END, "")
w.mainloop()
|
daded90f1f1cd2b23ce801b177af14347a45f245 | ljervis/Rosalind_Algorithms | /HW6/ColoredEdges.py | 1,476 | 3.90625 | 4 | #ColoredEdges Implementation
import sys
def open_file(file_name):
chromosomes = []
with open(file_name) as f:
chromosomes = f.readline().rstrip("\n").split(")(")
chromosomes[0] = chromosomes[0][1:]
chromosomes[len(chromosomes)-1] = chromosomes[len(chromosomes)-1][:-1]
return chromosomes
def update_chromosomes(chromosomes):
for i in range(len(chromosomes)):
chromosomes[i] = chromosomes[i].split(" ")
chromosomes[i].append(chromosomes[i][0])
def chromosome_to_cycle(chromosome):
n = len(chromosome)
nodes = [0]*(2*n)
for j in range(1,len(chromosome)+1):
i = chromosome[j-1]
if i[0] == "+":
nodes[2*j-2] = 2*int(i[1:])-1
nodes[2*j-1] = 2*int(i[1:])
else:
nodes[2*j-2] = 2*int(i[1:])
nodes[2*j-1] = 2*int(i[1:])-1
return nodes
def colored_edges(chromosomes):
edges = []
for i in chromosomes:
nodes = chromosome_to_cycle(i)
for j in range(1,len(nodes)-1,2):
edges.append((nodes[j],nodes[j+1]))
return edges
def print_edges(edges):
for i in range(len(edges)-1):
print(edges[i],end=", ")
print(edges[len(edges)-1])
def main():
chromosomes = open_file("./data/rosalind_data_p57.txt")
update_chromosomes(chromosomes)
edges = colored_edges(chromosomes)
print_edges(edges)
if __name__ == "__main__":
main() |
308532218f6829c17b1b0044a78e670ee2c5365a | shankarkalmade/learnPython | /src/abstraction/fib_generator.py | 229 | 3.78125 | 4 |
# sample code to generate fib series for given range
def fib_series (num):
fib = [0,1]
for i in range(num-2):
fib.append(fib[-2]+ fib[-1])
return fib
# get first 10 fib number
print fib_series(10)
|
0989b5760e2115d506d194d261324f6865d7e25d | ohayogirls/Software-Engineering | /ball1.py | 6,145 | 3.6875 | 4 | # coding=utf-8
import random
# FileName: Balloons.py
# Desc: Put balloons into a box.
# Author: HusterHope
# Email: luhp9696@gmail.com
# Reference: https://github.com/DongZhuoran
# Version: 0.0.1
# LastChange: 2016-05-25 17:02:23
INF = 1e9
T = 100 #初始温度
delta = 0.9 #温度下降速度
THRESHOLD = 1e-6 #停止搜索阈值条件
MOVE = 100 #确定每个圆圆心的比较次数
PREOPT = 1e-6 #最小圆半径精度
alpha = 0.2 #学习速率
MINEX = 1e-1 #有解条件
dx = [ 0, 0, -1, 1 ]
dy = [ 1, -1, 0, 0 ] #上下左右四个方向
class Circle:
def __init__(self):
self.radius = 0
self.x = 0
self.y = 0
def initialize(n):
cir = [Circle()]*n
for i in range(n):
cir[i].radius = 0
cir[i].x = 0
cir[i].y = 0
return cir
def dist(A,B):#A,B圆心的距离
return ((A.x - B.x)**2+(A.y - B.y)**2)**(1/2)
def Getsum(cir,n,c):
ans = 0
for i in range(n):
ans += (cir[i].radius + c.radius - dist(cir[i], c))**2
if (c.x + c.radius > 1):
ans += (c.x + c.radius - 1)**2
if (c.x - c.radius < -1):
ans += (c.x - c.radius + 1)**2
if (c.y + c.radius > 1):
ans += (c.y + c.radius - 1)**2
if (c.y - c.radius < -1):
ans += (c.y - c.radius + 1)**2
return ans
def GetCenter(cir,n):
c=Circle()
flag = 0
c.radius = 0
#圆心(x,y)在-1,1的范围内,我们随机试探
c.x = 2 * random.random() - 1
c.y = 2 * random.random() - 1
while (flag < n):
c.x = 2 * random.random() - 1
c.y = 2 * random.random() - 1
flag = 0
for i in range(n): #问题: for (int i = 0, flag = 0; i < n; i++){flag++;}最后flag=?
if (dist(cir[i], c) > cir[i].radius):
flag+=1
else:
break
return c
def GetCircle(cir,n,curradius):
MinCir=Circle()
MinEx = INF
MinCir.radius = 0
MinCir.x = 0
MinCir.y = 0
#配合梯度下降法使用
k=0
while (k < MOVE):
c = GetCenter(cir, n)
c.radius = curradius
Ex = Getsum(cir, n, c)
if (Ex < MinEx):
MinCir = c
MinEx = Ex
k+=1
return MinCir
def optimize(cir,n):
x1 = cir[n - 1].x
y1 = cir[n - 1].y
ax = 0
ay = 0
for i in range(n):
j=i+1
while(j < n):
ax -= 2 * (cir[i].radius + cir[j].radius - dist(cir[i], cir[j])**0.5) * dist(cir[i], cir[j])**(-0.5) * (x1 - cir[j].x)
ay -= 2 * (cir[i].radius + cir[j].radius - dist(cir[i], cir[j])**0.5) * dist(cir[i], cir[j])**(-0.5) * (y1 - cir[j].y)
j+=1
if (cir[i].x + cir[i].radius > 1):
ax += 2 * (cir[i].x + cir[i].radius - 1)
if (cir[i].x - cir[i].radius < -1):
ax += 2 * (cir[i].x - cir[i].radius + 1)
if (cir[i].y + cir[i].radius > 1):
ay += 2 * (cir[i].y + cir[i].radius - 1)
if (cir[i].y - cir[i].radius < -1):
ay += 2 * (cir[i].y - cir[i].radius + 1)
x2 = x1 - alpha * ax
y2 = y1 - alpha * ay
cir[n - 1].x = x2
cir[n - 1].y = y2
#while ((x2 - x1 > PREOPT) && (y2 - y1) > PREOPT)
'''
while (ax <= 0 and ay == 0):
x1 = x2
y1 = y2
i = 0
while(i < n):
j=i+1
while(j < n):
ax -= 2 * (cir[i].radius + cir[j].radius - dist(cir[i], cir[j])**0.5) * dist(cir[i], cir[j])**(-0.5) * (x1 - cir[j].x)
ay -= 2 * (cir[i].radius + cir[j].radius - dist(cir[i], cir[j])**0.5) * dist(cir[i], cir[j])**(-0.5) * (y1 - cir[j].y)
j+=1
if (cir[i].x + cir[i].radius > 1):
ax += 2 * (cir[i].x + cir[i].radius - 1)
if (cir[i].x - cir[i].radius < -1):
ax += 2 * (cir[i].x - cir[i].radius + 1)
if (cir[i].y + cir[i].radius > 1):
ay += 2 * (cir[i].y + cir[i].radius - 1)
if (cir[i].y - cir[i].radius < -1):
ay += 2 * (cir[i].y - cir[i].radius + 1)
i+=1
x2 = x1 - alpha * ax
y2 = y1 - alpha * ay
cir[n - 1].x = x2
cir[n - 1].y = y2
'''
#/*printf("delta1 = %f, delta2 = %f\n", x2 - x1, y2 - y1);
#getchar();*/
return cir[n - 1]
def Search(cir,n):
ans=0
t = T
flag = [0] * n
while (t > THRESHOLD):
for i in range(n):
curradius = PREOPT#最小半径
if (flag[i] == 1):
continue
c = GetCircle(cir,i, curradius)#第i 个圆
#梯度下降法优化实现
cir[i] = c
c = optimize(cir, i + 1)
while (Getsum(cir, i, c) < MINEX / n):
#print "curradius = ",curradius
curradius *= 1.1
c = GetCircle(cir, i, curradius)
cir[i] = c
c = optimize(cir, i + 1)
if (Getsum(cir, i, c) > MINEX / n):
k=0
while (k < 10 and Getsum(cir, i, c) > MINEX / n):
c = GetCircle(cir, i, curradius)
cir[i] = c
c = optimize(cir, i + 1)
k+=1
c.radius = curradius / 1.21
cir[i] = c
flag[i] = 1
ans += Getsum(cir, i, c)
if (ans < MINEX):
return ans
else:
t = t*delta
return ans
def main():
while (1):
#input
print "Please enter the number of circles:"
num = input()
if (num > 0):
#Initialize circles
cir = initialize(num)
#find the position and radius
ans = Search(cir, num)
if (ans == -1):
print "There is no answer, please try again"
else:
for i in range(num):#output for each
print "The radius and coordinate are:",cir[i].radius , cir[i].x , cir[i].y
#total area
#print ans
else:
break
main()
|
cd43cebcf94bbe9328bb0053351bdb025a15e0f3 | renato29/python-3-mundo-2 | /exe36_aprovando_emprestimo.py | 467 | 3.828125 | 4 | casa = float(input('Qual o valor do bem desejado: R$'))
sal = float(input('Qual o salário do cliente '))
mora = float(input('Quantos anos de pagamento ? '))
prestação = casa/(mora*12)
min = sal* 30/100
print('a da casa será de R${:.2f} pagando em {}'.format(casa, mora))
print('a prestação será de R${:.2f}'.format(prestação))
if prestação<=min:
print('emprestimo aprovado')
else:
print('emprestimo impossivel hoje, retorno em um ano')
|
23553d7241bc06eda74c4fb3afdefc247ec1d5e9 | gitonga123/hundreds-days-of-code | /python_pro/functions/decorators_1.py | 392 | 4 | 4 | # Decorator is a design pattern
# function that takes another function as a parameter
# and extends its behavior without modifying it.
# this is another good example of closure
def add_stars(some_function):
def wrapper():
print("*******")
some_function()
print("*******")
return wrapper()
@add_stars
def my_function():
print("Hello!!!")
my_function
|
edb15b126fb85081324fbcb50169a450d2cb7607 | Yashasvii/Project-Euler-Solutions-hackerrank | /forHackerRank/015.py | 581 | 3.640625 | 4 | """
Project Euler Problem 15
========================
Starting in the top left corner of a 2 * 2 grid, there are 6 routes
(without backtracking) to the bottom right corner.
How many routes are there through a 20 * 20 grid?
"""
import math
def combination(n, r):
return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
if __name__ == "__main__":
cases = int(input().strip())
for i in range(cases):
N, M = input().strip().split(' ')
N, M = [int(N), int(M)]
print(combination((N + M), M) % (
10 ** 9 + 7))
|
72bf35fe88b18a734f345fe092de5b3a3350874e | m-ox/python_course | /loops/continue_break_tut.py | 485 | 4.03125 | 4 | colors = ['red', 'orange', 'yellow',
'green', 'blue', 'purple']
# Continue / Break - super handy conditionals
'''
for color in colors:
if color == 'blue':
print(f'the color is {color}')
continue
else:
print(f'{color} is not blue')
'''
# continue / break make sense
for color in colors:
if color == 'blue':
print(f'{color} was found at index {colors.index(color)}')
break;
print(color)
# break breaks you out of the block |
e8f332e32be005ead567c434341048cff11d5999 | nigelginau/practicals_cp1404 | /prac_04/lists_warmup.py | 321 | 4.125 | 4 | numbers = [3, 1, 4, 1, 5, 9, 2]
# Change the first element of numbers to "ten"
numbers[0] = 10
print(numbers)
# Change the last element of numbers to 1
numbers[-1] = 1
print(numbers)
# Get all the elements from numbers except the first two
print(numbers[2:])
# Check if 9 is an element of numbers
print(9 in numbers)
|
8efda46aaf67f65004c23e741295a35f6d5ae728 | pfitzsimmons/fitzpy | /fitzpy/propertized.py | 3,939 | 3.578125 | 4 | '''
Propertized allows you to create a class with properties that have metadata
For instance, let's say you are building an API with model-like objects for different vehicles.
The object instance should store the data for each vehicle. But you want the model itself to
store various meta data about each property so that you can automatically build API docs.
class Vehicle(Propertized):
manufacturer = Prop(label='Manufacturer',
horse_power = Prop(label='Horsepower', type=int, help_text='The power of the vehicle's engine')
weight = Prop(label='Weight', type=int, help_text='The weight in pounds of the vehicle')
max_speed = Prop(label='Max speed', type=int, help_text='The maximum speed, in MPH')
Now I can create an instance of the class:
ford_prefect = Vehicle(manufacturer='Ford', horse_power=120, weight=4000, max_speed=95)
>>> print ford_prefect.horse_power
-> 120
ford_prefect.horse_power = 110
>>> print ford_prefect.horse_power
-> 110
I can also programmatically get the metadata about the class properties. I could use
this to generate documentation, so that I have one canonical represenation of my model.
doc_builder = []
for prop in Vehicle.list_class_props():
doc_builder.append("""\
Field: %(label)s
Type: %(type)s
Description: %(help_text)s
""" % prop.__dict__)
print 'API Documentation:\n' + '\n'.join(doc_builder)
'''
import inspect
class Prop(property):
attr_name = None
def __init__(self, default=None, mutable=True, help_text='', **kwargs):
self.default = default
self.mutable = mutable
self.help_text = help_text
self.__dict__.update(kwargs)
def __get__(self, instance=None, owner=None):
if not self.attr_name:
raise ValueError('self.attr_name is empty')
self._check_set_default(instance)
return instance.__dict__.get(self.attr_name)
def _check_set_default(self, instance):
if self.attr_name in instance.__dict__:
return
if self.default != None:
if inspect.isfunction(self.default) or inspect.ismethod(self.default) or inspect.isfunction(self.default):
instance.__dict__[self.attr_name] = self.default()
elif isinstance(self.default, type):
instance.__dict__[self.attr_name] = self.default()
else:
instance.__dict__[self.attr_name] = self.default
self.__set__(instance, instance.__dict__[self.attr_name])
def __set__(self, instance=None, value=None):
if not self.mutable and self.attr_name in instance.__dict__:
raise AttributeError("Property " + self.attr_name + " is immutable and cannot be changed once set.")
instance.__dict__[self.attr_name] = value
class PropertizedMetaClass(type):
def __new__(meta, name, bases, atts):
typ = super(PropertizedMetaClass, meta).__new__(meta, name, bases, atts)
_class_props = []
for key, value in atts.items():
if isinstance(value, Prop):
value.attr_name = key
_class_props.append(value)
typ._class_props = _class_props
return typ
class Propertized(object):
__metaclass__ = PropertizedMetaClass
def __init__(self, **kwargs):
self._hydrate_from_kwargs(**kwargs)
def as_dict(self):
d = {}
for prop in self.list_class_props():
d[prop.attr_name] = getattr(self, prop.attr_name)
return d
@classmethod
def list_class_props(cls):
return cls._class_props
def _hydrate_from_kwargs(self, **kwargs):
prop_names = [prop.attr_name for prop in self.list_class_props()]
for key, val in kwargs.items():
if key not in prop_names:
raise AttributeError("Class " + self.__class__.__name__ + " does not have the property " + key)
setattr(self, key, val)
|
88b0ec42b21c46666a83217a01ae9d2c0c97fbe2 | jacobgarrison4/Python | /p52_stringreverse.py | 1,432 | 4.46875 | 4 | """
String Reverse
CIS 210 F17 Project 5
Authors: Jacob Garrison
Credits: Python Programming in Context
stringreverse takes a string and returns the string in reverse,
both iteratively and recursively.
"""
def main():
"""(None) -> None
main asks the user for input and uses
the input to call stringreverse.
"""
string = str(input("Enter a string to be reversed: "))
print(strReverseR(strReverseI(string)))
def strReverseR(s):
"""(str) -> None
Takes a string argument and returns the string in reverse.
>>> strReverseR('CIS 210') #Basic
'012 SIC'
>>> strReverseR('c') #Boundary
'c'
>>> strReverseR('') #Empty
''
"""
if s == 1:
return s
elif len(s) == 0:
return s
else:
return s[-1] + strReverseR(s[:-1])
return s
def strReverseI(s):
'''(str) -> None
strReverseL takes a string and returns the string in reverse
>>> strReverseI('happy')#Basic
'yppah'
>>> strReverseR('h') #Boundary
'h'
>>> strReverseR('') #Empty
''
'''
letters = list(s)
reverse_letters = []
x = int(len(s))
while x > 0:
reverse_letters += letters[x-1]
x -= 1
else:
return ''.join(reverse_letters)
print(reverse_letters)
if __name__ == "__main__":
import doctest
print(doctest.testmod())
#main()
|
de0e7b1ea996047b43b33c8f5f75d1f04ba025d2 | IvayloSavov/Programming-basics | /conditional_statements_advanced_lab/and_or_not.py | 351 | 4.125 | 4 | weather = input()
temperature = int(input())
if weather == "rain" and temperature < 15:
print("Take your cold jacket")
elif not weather == "rain" and temperature < 25:
print("Take your thin jacket")
elif weather == "sun" or temperature > 25:
print("don't take any jacket")
elif not weather == "rain":
print("don't take your umbrella") |
9b45ebd6660813f6676676b7bbcd9b490b3b4817 | TynanJ/CodeDump | /code/Guess the number.py | 660 | 4.0625 | 4 | from random import randint
MAXIMUM = int(input('Enter a maximum number: '))
ANSWER = randint(1, MAXIMUM)
def guessing_game(guess, correct=ANSWER):
try:
guess = int(guess)
except ValueError:
guessing_game(input("That's not a number!: "), correct)
else:
if guess > correct:
guessing_game(input('Go lower: '), correct)
elif guess < correct:
guessing_game(input('Go higher: '), correct)
else:
print('Correct!')
if __name__ == '__main__':
first_guess = input('\nEnter a number between 1 and {}: '.format(MAXIMUM))
guessing_game(first_guess)
|
214006169b022ce2a7f00c1095ef47981e347816 | ThomasTheDane/AlgorithmFun | /thinkPython.py | 846 | 3.875 | 4 | def checkFermat(a,b,c,n):
if (a**n) + (b**n) == c**n and n > 2:
print "holy smokes, Fermat was wrong"
else:
print "No, that doesn't work"
def checkIfHasTrippleLetter(word):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for aLetter in alphabet:
if (aLetter.lower()*3) in word:
print word
def findTrippleLetterWords():
fin = open('words.txt')
for line in fin:
word = line.strip()
checkIfHasTrippleLetter(word)
def frequencyOfWords():
freqeuncy = {}
fin = open('words.txt')
for line in fin:
word = line.strip()
if(word in freqeuncy):
freqeuncy[word] += 1
else:
freqeuncy[word] = 1
print freqeuncy
def exercise53():
checkFermat(2,2,2,2)
def exercise97():
findTrippleLetterWords()
def exercise123():
frequencyOfWords()
def main():
exercise123()
# exercise53()
# exercise97()
if __name__ == '__main__':
main() |
70a601283947a93f33fc89aad958595083c01acf | daldantas/CursoPython | /exercicios/004.py | 281 | 3.671875 | 4 | # coding=utf-8
algo = input('Digite algo: ')
print(
'\n Tipo: ', type(algo),
'\n Alfanumérico: ', algo.isalnum(),
'\n Alfa: ', algo.isalpha(),
'\n Numérico: ', algo.isnumeric(),
'\n Maiúsculas: ', algo.isupper(),
'\n Espaço: ', algo.isspace()
) |
d9979b55902e8acc3f109e8ae832c51ef5d14c9f | Sounav201/itworkshop | /TuplesAssignment.py | 1,137 | 3.96875 | 4 | def binary_search(a,low,high,key):
if high>=low:
mid=(high+low)//2
if a[mid]==key:
return mid
elif a[mid]>key:
return binary_search(a,low,mid-1,key)
else :
return binary_search(a,mid+1,high,key)
else:
return -1
def linear_search(a,key):
for i in range(len(a)):
if a[i]==key:
return i
return -1
a=(10,20,30,40,50,60,70,80,110,145)
choice=int(input("Enter 1 to search using Binary Search. \nEnter 2 to search for an element using Linear Search "))
if choice==1:
key=int(input(" You have chosen Binary Search . Enter the search element "))
res=binary_search(a,0,len(a)-1,key)
if(res==-1):
print("Element is not found!")
else:
print("Element present at position " + str(res + 1))
if choice==2:
key = int(input("You have chosen Linear Search . Enter the search element "))
res=linear_search(a,key)
if res==-1:
print("Element is not found!")
else:
print("Element present at position " + str(res + 1))
|
c0e663c4cb05513fd82cd75dc76fc8308ceb548a | GrantHair5/LearnPython | /FootballGame/app.py | 927 | 3.625 | 4 | from Team import Team
from Game import Game
from Score import Score
print("Welcome To Grant's Football Game")
print("Enter home team name:")
homeTeamName = input()
print("Enter away team name:")
awayTeamName = input()
manUStartingEleven = ["De Gea", "Wan Bisaka", "Maguire", "Lindelof", "Shaw", "Van De Beek", "Pogba", "Fernandes", "Martial", "Greenwood", "Rashford"]
chelseaStartingEleven = ["Mendy", "James", "Zouma", "Silva", "Chillwell", "Jorginho", "Kante", "Mount", "Pulisic", "Werner", "Havertz"]
homeTeam = Team(homeTeamName, manUStartingEleven, 1)
awayTeam = Team(awayTeamName, chelseaStartingEleven, 2)
gameOne = Game()
print("Game Has Begun {} vs {}".format(homeTeamName, awayTeamName))
print(" ")
gameOne.addTeamGoal(manUStartingEleven[7], homeTeam.Name, homeTeam.TeamId)
gameOne.addTeamGoal("Havertz", awayTeam.Name, awayTeam.TeamId)
gameOne.addTeamGoal("Rashford", homeTeam.Name, homeTeam.TeamId)
|
a50e8dc44360dd99db1536a2ab204a8a12ffa91b | Tahmid-352/python_assignments | /python assignment 2/not_poor.py | 325 | 3.5625 | 4 | def not_poor(str1):
snot = str1.find('not')
spoor = str1.find('poor')
if spoor > snot and snot > 0 and spoor > 0:
str1 = str1.replace(str1[snot:(spoor + 4)], 'good')
return str1
else:
return str1
print(not_poor('The lyrics is not that poor!'))
print(not_poor('The lyrics is poor!')) |
bd46142829d44ada08f384ef267a5610444e0240 | ariannedee/intro-to-python | /Examples/example_11_while_loops.py | 217 | 4.21875 | 4 | x = 3
while x >= 0: # Will keep looping until condition is False
print(x)
x = x - 1
y = 0
while True: # Will keep looping until it encounters a break
print(y)
y += 1
if y == 10:
break
|
4aa0a61eab2f2c4b7d1e09e10f20c270aea8b161 | proTao/leetcode | /23. HashTable/202.py | 632 | 3.75 | 4 | happy_set = set()
unhappy_set = set()
def getNext(x):
res = 0
while x > 0:
res += (x%10)**2
x = x//10
return res
class Solution:
def isHappy(self, n: int) -> bool:
temp_set = set()
while True:
if n in temp_set:
unhappy_set.update(temp_set)
return False
if n in happy_set or n == 1:
happy_set.update(temp_set)
return True
temp_set.add(n)
n = getNext(n)
print(n)
if __name__ == "__main__":
print(Solution().isHappy(2))
# print(getNext(19))
|
90c15eae2bcafbd22b3e903d87e29c741823e61e | K-Imtiaz/Python_Projects | /String and String manipulation.py | 286 | 4.09375 | 4 | print("Hello Imtiaz\nHow are you\nHow's day 1 going\nIs python really easy as they say?\nDay 1 - Python Print Function\nThe function is declared like this\nprint('What to print')")
print("Hello"+"Imtiaz")
print("Hello"+" "+"Imtiaz")
print("Hello"+" Imtiaz")
print("Hello "+"Imtiaz") |
d1655b17beda3dee7a2276c02cbd1486831e2c13 | JMateusNSilva/python_uerj_2020_2 | /exercícios/aula05_02_10_2020.py | 414 | 4.125 | 4 | # EXERCÍCIO 01 - [NAO É POSSÍVEL FAZER NO COLAB] -
import turtle
cor = input('Escolha uma das cores para sua linha: white, yellow, orange, red, green, blue, purple, gray, black. ')
wn = turtle.Screen() # Manda abrir a janela do turtle
mateus = turtle.Turtle()
mateus.color(cor)
mateus.forward(150)
mateus.left(90)
mateus.forward(130)
wn.mainloop() # Espere o usuário fechar a janela do turtle
|
3c98249146b513976e95e8f880486fb794a08108 | konokonekonokonekonokokoneko/signate-trading | /regression_test.py | 3,252 | 3.84375 | 4 | # 非線形モデルです
#
# "9x9.py" # Primary multiplication set
#
# an example of keras (with tensorflow by Google)
# by U.minor
# free to use with no warranty
#
# usage:
# python 9x9.py 10000
#
# last number (10000) means learning epochs, default=1000 if omitted
import tensorflow as tf
import keras
from keras.optimizers import SGD
import numpy as np
#from numpy.random import *
import matplotlib.pyplot as plt
import sys
import time
np.random.seed(10)
argvs = sys.argv
i_train, o_train = [], []
ticks = 10
max = float(ticks ** 2)
# generate sample data
for x in range(1, ticks, 2):
for y in range(0, ticks, 1):
c = x * y / max
i_train.append([x, y])
o_train.append(c)
i_train = np.array(i_train)
print(i_train)
print(o_train)
from keras.layers import Dense, Activation
model = keras.models.Sequential()
# neural network model parameters
hidden_units = 3
layer_depth = 1
act = 'sigmoid' # seems better than 'relu' for this model.
bias = True
# first hidden layer
model.add(Dense(units=hidden_units, input_dim=2, use_bias=bias))
model.add(Activation(act))
# additional hidden layers (if necessary)
for i in range(layer_depth - 1):
model.add(Dense(units=hidden_units, input_dim=hidden_units, use_bias=bias))
model.add(Activation(act))
# output layer
model.add(Dense(units=1, use_bias=bias))
model.add(Activation('linear'))
# Note: Activation is not 'softmax' for the regression model.
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='mean_squared_error', optimizer=sgd)
#model.compile(loss = 'mean_absolute_percentage_error', optimizer = sgd)
#model.compile(loss = 'mean_squared_logarithmic_error', optimizer = sgd)
# Note: loss is not 'sparse_categorical_crossentropy' for the regression model.
# metrics = ['accuracy'] does not seem suitable.
# training
if len(argvs) > 1 and argvs[1] != '':
ep = int(argvs[1]) # from command line
else:
ep = 1000 # default
start_fit = time.time()
model.fit(i_train, o_train, epochs=ep, verbose=1)
elapsed = time.time() - start_fit
print("elapsed = {:.1f} sec".format(elapsed))
# predict
a = []
for x in range(0, ticks, 2):
for y in range(0, ticks, 1):
a.append([x, y])
p = np.array(a)
print(p)
r = model.predict(p)
r_fact = r * max
print(r)
# Easy evaluation
y = []
for (aa, r_fact_1, r_normal) in zip(p, r_fact, r):
fact_predicted = r_fact_1[0]
fact_true = aa[0] * aa[1]
predict_sqrt = np.sqrt(abs(r_normal[0]))
true_sqrt = np.sqrt(abs(fact_true))
y.append(fact_true)
print('{0:>2} x {1:>2}, true_product={2:>3}, predicted={3:>6.2f}, accuracy(biased_percentage)={4:>6.2f} %'.format(
aa[0],
aa[1],
fact_true,
fact_predicted,
(true_sqrt - predict_sqrt + ticks) * 100 / (true_sqrt + ticks)
))
# Plot on scatter graph
xn, yn, cp = [], [], []
for i in range(int(ticks / 2) ** 2):
xn.append(p[i][0])
yn.append(p[i][1])
cp.append(float(r[i]))
plt.scatter(p[:, 0], p[:, 1], marker=".", c=[float(a)
for a in r], cmap='Blues')
plt.colorbar()
plt.scatter(i_train[:, 0], i_train[:, 1], marker="*",
s=100, c=o_train, cmap='Reds')
plt.colorbar()
plt.show()
|
482f789d0510f5395433954d04b553bd589eac59 | runda87/she_codes_python | /conditionals/lists/starter/q3.py | 378 | 4.15625 | 4 | name1 = input(f"Enter a name:")
name2 = input(f"Enter another name:")
name3 = input(f"You know what to do, enter another name:")
name_list = []
name_list.append(name1)
name_list.append(name2)
name_list.append(name3)
print(name_list)
# Input
# izzy
# archie
# boston
# Output
# Enter a name: izzy
# Enter a name: archie
# Enter a name: boston
# ['izzy', 'archie', 'boston'] |
509218f3de42fd895790324b6fa2bc71877fcc90 | Manash-git/Python-Programming | /python pattern/reverse_piramid.py | 629 | 3.640625 | 4 | def pettern(n):
for line in range(1,n+1):
for space in range(1,line):
print(" ",end="")
for star in range(line, n+1):
print("* ",end="")
print("")
pettern(10)
print()
def rev_pir_adv(n):
for line in range(n):
print(" "*line + "* "*(n-line))
rev_pir_adv(5)
# odd reverse
print()
def odd_rev_pir_adv(n):
for line in range(n):
print(" "*line + "* "*(n-(2*line)))
odd_rev_pir_adv(5)
# even reverse
print()
def even_rev_pir_adv(n):
for line in range(n):
print(" "*line + "* "*(n-(2*(line+1))))
even_rev_pir_adv(7)
|
e30cc98440e3dd0b72f040bda9622772af11994f | bridgette/Python100 | /possible_bitwise_max.py | 1,335 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 10 13:32:41 2015
@author: breiche
Women's Cup on Hackerrank
"""
import unittest
class PossibleMaxSolution(object):
def PossibleMax(self, n, k):
"""
You are given a set S = {1, 2, 3,…,N }. Find two integers A and B (A<B)
from the set S such that the value of A & B is the maximum possible
and less than the given integer K. In this case, & represents the
operator bitwise AND.
"""
max_value = 0
for b in range(n+1):
for a in range(b):
bitwise_ab = a & b
if bitwise_ab > max_value and bitwise_ab < k:
max_value = bitwise_ab
return max_value
class PossibleMaxTest(unittest.TestCase):
def test1(self):
s = PossibleMaxSolution()
answer = s.PossibleMax(5,2)
expected = 1
self.assertEqual(answer, expected)
def test2(self):
s = PossibleMaxSolution()
answer = s.PossibleMax(8,5)
expected = 4
self.assertEqual(answer, expected)
def test3(self):
s = PossibleMaxSolution()
answer = s.PossibleMax(2,2)
expected = 0
self.assertEqual(answer, expected)
if __name__ == '__main__':
unittest.main()
|
19f63ac2b0202309428e156ef9d3e2c985d8e795 | GabrielUlisses/Python-documents | /Scripts/geradores.py | 804 | 4.03125 | 4 | # Um gerador consegue parar o seu programa e recuperar dados da execução(estado completo)
# objeto gerador --> possui protocolo de iteração, ou eja, é um objeto iterável, possuindo iterador.
# iterador --> __next__()
def gera_quadrados(n):
for i in range(n):
yeld i**2
for i in gera_quadrados(5)
print(i)
x = gera_quadrados(5)
# expressões geradoras
"""
enquanto as listas compressas são mais velozes e retornam os valores em lista,
as expressões geradoras retornam um objeto gerador, que não armazena os valores
na memória, apenas o objeto em questão
listas compressas -> iteráveis mas não iteradores
expressões geradoras -> iteráveis e iteradores | não pode ser convertida em lista
"""
l = (x**2 for x in range(10) if x%2 == 0)
print(l)
|
a42f9f3d3f1969a4907365a47688d591b7bae558 | ciaranmccormick/advent-of-code-2019 | /7/main.py | 2,299 | 3.609375 | 4 | #! /bin/env python3
from argparse import ArgumentParser, Namespace
from itertools import permutations
from typing import List
from computer import Computer
def load_instructions(filename: str) -> List[int]:
"""Read in a list of comma separated integers"""
with open(filename, "r") as f:
codes = f.readline().split(",")
codes = [int(code) for code in codes]
return codes
def get_max_thruster_signal(amplifiers: List[int], phases: List[int]):
return max(
get_thruster_signal(amplifiers, p) for p in permutations(phases, len(phases))
)
def get_thruster_signal(opcodes: List[int], phases: List[int]):
out = 0
for phase in phases:
comp = Computer(opcodes)
comp.value = out
comp.input(phase)
out = comp.run()
return out
def loop_thruster_signal(intcodes: List[int], phases: List[int]):
out = 0
i = 0
computers = []
while True:
if i // len(phases) == 0:
phase = phases[i % len(phases)]
comp = Computer(intcodes)
comp.value = out
computers.append(comp)
comp.input(phase)
out = comp.run()
else:
comp = computers[i % len(phases)]
comp.value = out
out = comp.run()
if computers[-1].stop:
return computers[-1].out
i += 1
def get_max_loop_thruster_signal(amplifiers: List[int], phases: List[int]):
return max(
loop_thruster_signal(amplifiers, p) for p in permutations(phases, len(phases))
)
def part_two(intcodes: List[int]):
phases = range(5, 10)
return get_max_loop_thruster_signal(intcodes, phases)
def part_one(opcodes: List[int]):
phases = range(5)
return get_max_thruster_signal(opcodes, phases)
def parse_args() -> Namespace:
"""Parse arguments."""
parser = ArgumentParser()
parser.add_argument("filename", help="File containing problem inputs.", type=str)
args = parser.parse_args()
return args
def main():
args = parse_args()
intcodes = load_instructions(args.filename)
answer1 = part_one(intcodes)
print(f"Part One output = {answer1}")
answer2 = part_two(intcodes)
print(f"Part Two output = {answer2}")
if __name__ == "__main__":
main()
|
2f55fc0c5ff161870cbf5a77e3fc4bc7613b56cc | Abhigyan22/Snake-Game | /SnakeGame.py | 10,068 | 4.0625 | 4 | """The very famous Snake game built using Python
"""
#Importing all the necessary dependencies
from random import randint
from math import sqrt, pow
from buttons import Button
from sys import exit
from time import perf_counter
import pygame
def lose_message(scr:int):
"""[PRINTS THE LOSE MESSAGE]
Args:
scr (means score) -(int): [Prints the score (After player loses)]
"""
with open("TEXT/high_score.txt", "r") as f:
highscore = f.read()
big_font = pygame.font.Font("FONT/BAARS___.TTF", 100)
small_font = pygame.font.Font("FONT/BAARS__.TTF", 50)
score = big_font.render(f"YOUR SCORE: {scr}", True, (0,0, 0))
high_score = big_font.render(f"HIGH SCORE: {highscore}", True, (0,0,0))
press_any = small_font.render("PRESS ANY KEY TO CONTINUE", True, (0,0,0))
WINDOW.blit(score, (90, 160))
WINDOW.blit(high_score, (92, 260))
WINDOW.blit(press_any, (190, 540))
def print_score(score):
"""Prints the score in game
Args:
score (int): Player score
"""
font = pygame.font.Font("FONT/BAARS___.TTF", 70)
scr = font.render(f"{score}", True, (0,0,0,100))
WINDOW.blit(scr, (30, 30))
def display_food(x:int, y:int):
"""[Display the food in its position ]
Args:
x (int): [Position of food in X axis]
y (int): [Position of food in Y axis]
"""
pygame.draw.rect(WINDOW, (255,255,0), (x,y,36,36))
def change_highscore(file, score):
"""Changes the highscore of the game
INPUTS:
file - The high_score.txt file
score - score of the player
"""
with open(file, "r") as r:
if score >= int(r.read()):
with open(file, "w") as w:
w.write(str(score))
def food_eaten(player, foodX, foodY):
"""[Checks if food has been eaten]
Returns:
Bool: [Returns True if food eaten else False]
"""
if sqrt(pow(player.X - foodX, 2) + pow(player.Y-foodY, 2))<20:
#The above is a math equation to find the distance between two coordinates
#Link to study more about the equation - https://rb.gy/xe9zjt
return True
return False
class Player():
"""A class for the Player (i.e. the snake)
"""
def __init__(self):
self.X = 364 #X coordinate of Player
self.Y = 264 #Y coordinate of the Player
self.velocityX = 0
self.velocityY = 0
self.snake_list = []
self.snake_size = 1
self.size = 36
def display_player(self):
"""[DRAWS THE SNAKE]
Args:
snk_list (list): [description]
snk_size (int): [description]
"""
for x, y in self.snake_list:
pygame.draw.rect(WINDOW, (0,0,0), (x, y, self.size, self.size))
pygame.draw.rect(WINDOW, (255,0,0), (self.X, self.Y, self.size, self.size))
"""If you did not understand the snake increase logic, please read the
snake increase logic.txt..."""
def check_boundary(self):
"""[Checks if player hit the boundary]
Returns:
[bool]: [True if player hit boundary else False]
"""
if self.X<=-14:
self.X = -14
return True
elif self.Y<=-10:
self.Y = -10
return True
if self.X>=776:
self.X = 776
return True
elif self.Y>=580:
self.Y = 580
return True
return False
def check_hit(self):
"""SEE IF SNAKE HIT ITS OWN BODY
Returns:
\nbool: True if hit its own body else false
"""
#below math equation same as food_eaten() func.
for x,y in self.snake_list[:-9]:
if sqrt(pow(self.X-x, 2)+pow(self.Y-y, 2))<20:
return True
return False
"""Why i gave index of -9 in for loop? because the snk_list[-1] is the
head of the snake (the red square) and [-2] to [-9] are the tail but they are
actually so close to the snake(they are inside the head almost) so if i try
without the index of [:-9], it is gonna show i lose the first time i eat...
Again, because they are so close to the head and the distance between them is less
than 20"""
def change_player_position(event, player, set_velocity):
"""[Change the position of the player based on the key pressed]
Args:
event (event): It is the event log.. (event means everything which happens in a game,
from key press to mouse , etc.)
player (Player): The object (The main player.. i.e The Snake)
set_velocity (int): velocity of the player
"""
if event.type == pygame.KEYDOWN: #If we pressed down any key
if event.key == pygame.K_LEFT: #If key pressed is left, its all the same for the rest
player.velocityX = -set_velocity
player.velocityY = 0
elif event.key == pygame.K_RIGHT:
player.velocityX = set_velocity
player.velocityY = 0
elif event.key == pygame.K_UP:
player.velocityY = -set_velocity
player.velocityX = 0
elif event.key == pygame.K_DOWN:
player.velocityY = set_velocity
player.velocityX = 0
def game_menu(Food_Sound):
"""The Start menu
Returns:
bool: True if hit Play button
"""
start = Button(x=300, y=150, width=200, height=70,real_color=(220,220,220),
color=(220,220,220),hover_color=(0,255,255), press_color=(0,128,255),
text= "START")
end = Button(x=300, y=350, width=200, height=70,real_color=(220,220,220),
color=(220,220,220),hover_color=(0,255,255), press_color=(0,128,255),
text= "END")
sound = Button(x=720, y=520, width=64, height=64)
sound_state = "play"
while True:
WINDOW.blit(BACKGROUND, (0,0))
start.draw(WINDOW, (0,0,0))
end.draw(WINDOW, (0,0,0))
if sound_state == "play":
WINDOW.blit(PLAY_BUTTON, (720,520))
elif sound_state == "pause":
WINDOW.blit(PAUSE_BUTTON, (720, 520))
for event in pygame.event.get():
# WINDOW.blit(BACKGROUND, (0,0))
pos = pygame.mouse.get_pos()
if event.type == pygame.QUIT:
pygame.quit()
exit()
if start.main_loop(event, pos):
return True
elif end.main_loop(event, pos):
pygame.quit()
exit()
elif sound.clicked(event, pos):
if sound_state == "play":
sound_state = "pause"
pygame.mixer.music.pause()
EXPLOSION_SOUND.set_volume(0)
FOOD_SOUND.set_volume(0)
elif sound_state == "pause":
sound_state = "play"
pygame.mixer.music.unpause()
EXPLOSION_SOUND.set_volume(1)
FOOD_SOUND.set_volume(1)
pygame.display.update()
def game():
"""The Main loop of the game.. This is where all the magic happens
"""
WINDOW.blit(BACKGROUND, (0,0))
player = Player()
lose = False
set_velocity = 8
score = 0
foodX = randint(5,735)
foodY = randint(5, 535)
want_to_play = True
while want_to_play:
for event in pygame.event.get():
if event.type == pygame.QUIT:
want_to_play = False
change_player_position(event, player, set_velocity)
WINDOW.blit(BACKGROUND, (0, 0))
print_score(score)
player.display_player()
display_food(foodX, foodY)
player.X += player.velocityX
player.Y += player.velocityY
head = []
head.append(player.X) #Appending the current X position of snake to head
head.append(player.Y) #Appending the current Y position of snake to head
player.snake_list.append(head) #Appedning the current position of snake to snake_lis
if len(player.snake_list)>player.snake_size:
del player.snake_list[0] #deletes the old position of snake if the length of
#snake_list increases the snake_list
if food_eaten(player, foodX, foodY):
FOOD_SOUND.play()
player.snake_size += 10
score+=1
foodX = randint(5,735)
foodY = randint(5,535)
if player.check_boundary() or player.check_hit():
change_highscore("TEXT/high_score.txt", score)
EXPLOSION_SOUND.play()
pygame.time.wait(1000) #The game will wait for 1 sec just to show that the player died
clicked = False
while not clicked:
WINDOW.blit(BACKGROUND, (0,0))
lose_message(score)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYUP or event.type == pygame.MOUSEBUTTONUP:
clicked = True
pygame.display.update()
want_to_play = False
pygame.display.update()
CLOCK.tick(30) #This will set the max fps of the game to 30
def main():
"""It has the game states -
1. Menu
2. Game
3. Settings, etc
"""
while True:
if game_menu(FOOD_SOUND):
game()
#Below are the basic configurations of the game
pygame.init()
WINDOW = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Snake Game")
ICON = pygame.image.load("IMG/SnakeIcon.png")
pygame.display.set_icon(ICON)
BACKGROUND = pygame.image.load("IMG/SnakeBackground.png")
pygame.mixer.music.load("SFX/BackgroundMusic2.wav")
pygame.mixer.music.play(-1)
PLAY_BUTTON = pygame.image.load("IMG/play.png")
PAUSE_BUTTON = pygame.image.load("IMG/pause.png")
FOOD_SOUND = pygame.mixer.Sound("SFX/FoodEaten.wav")
EXPLOSION_SOUND = pygame.mixer.Sound("SFX/Die2.wav")
CLOCK = pygame.time.Clock()
main()
|
f6f506012590d78ac8f85e1be729fb8caf53dd71 | vikashresources/CrackTheCode | /BigO.py | 2,067 | 4.21875 | 4 | '''
Complexity - O(n) time and O(n) space
For stack, it would require O(n) space and as if we need to create a array of size n.
Each of these calls is added to the call stack and takes up actual memory
'''
def get_sum(n):
if n <= 0:
return 0
return n + get_sum(n - 1)
print(get_sum(5))
'''In below function, there will be O(n) calls to pair_sum, however those calls do not exit simultaneously on stack &
thus space complexity of O(1)
Tip: Generally, when you find a problem where number of elements gets halved (eg balanced binary tree) each time that
will likely be O(log N) run time.
For recursive routines, It's O(N) for space and time.
'''
def pair_sum(a, b):
return a + b
def pair_sum_sequence(n):
total = 0
if n <= 0:
return 0
for i in range(n):
total += pair_sum(i, i + 1)
return total
print(pair_sum_sequence(5))
'''
Take another example of finding complexity, even though iteration 2 times, it will be O(N) complex
'''
def foo(array):
total = 0
product = 1
for i in range(len(array)):
total += array[i]
print(total)
for i in range(len(array)):
product *= array[i]
print(product)
foo([1, 2, 3, 4, 5])
'''
Here complexity will be O(N2)
'''
def print_sequence(array):
j = i = 0
for i in range(len(array)):
j = j + 1
for j in range(len(array)):
print(array[i], array[j])
print_sequence([1, 2, 3, 4, 5])
'''Time complexity of below program is O(n)'''
def count_set_bits(n):
count = 0
while n:
count += n & 1
n >>= 1
return count
def count__rec_set_bits(n):
# base case
if n == 0:
return 0
else:
# if last bit set add 1 else
# add 0
return (n & 1) + count__rec_set_bits(n >> 1)
print(count_set_bits(5))
print(count__rec_set_bits(5))
def get_parity(n):
parity = 0
while n:
parity = ~parity
n = n & (n - 1)
return parity
n = 7
print("Parity of no ", n, " = ", ("odd" if get_parity(n) else "even"))
|
49b98eb01b4daeff3b407ca9d4c3f97d02283c87 | kemingy/daily-coding-problem | /src/largest_BST.py | 862 | 4.1875 | 4 | # Given a tree, find the largest tree/subtree that is a BST.
# Given a tree, return the size of the largest tree/subtree that is a BST.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def largest_BST(node):
if node is None:
return 0
if node.left is None and node.right is None:
return 1
if (node.left and node.left.value >= node.value) or (node.right and node.right.value <= node.value):
print(node.value, 'not valid')
return max(largest_BST(node.left), largest_BST(node.right))
return 1 + max(largest_BST(node.left), largest_BST(node.right))
if __name__ == '__main__':
tree = Node(5, Node(2, Node(1), Node(4, Node(3))), Node(0, Node(2), Node(10)))
print(largest_BST(tree)) |
b16cde5fbd68d93bcc9eabf41620c3e2a75a05d8 | mukeshjnvk/URI-Online-Judge | /1038.py | 251 | 3.5625 | 4 |
def line(l):
x = int(l[0])
y = int(l[1])
price = [4.00, 4.50, 5.00, 2.00, 1.50]
print 'Total: R$ {0:.2f}'.format(price[x-1] * y)
def main():
l1 = raw_input()
l = l1.split(' ')
line(l)
main() |
1c11be0e519acc9588d30cb753571333d2d8bc88 | TaraBC/Blue | /BLUE/code/main.py | 12,819 | 3.515625 | 4 | import pygame
import sys
import os
import time
# MISC ATTRIBUTES
class colours: # library of colours in rgb
white = [255, 255, 255]
black = [0, 0, 0]
buttonBlue = [124, 176, 255]
buttonDarkC = [89, 103, 181]
space = [29, 41, 81]
transparent = [0,0,0,0]
# END OF MISC ATTRIBUTES
# BASIC DISPLAY ATTRIBUTES
class mainDisplay:
def __init__(self):
self.screenDisplay = pygame.display.set_mode(
[1200, 720]) # create game window SURFACE object (screen display is a SURFACE)
pygame.display.set_caption("Blue") # set window name
class button:
def __init__(self, x, y, width, height, text, font, fontSize, buttonColour, borderColour, fontColour,Display,
xratio, yratio): # initialize button
# set attributes
self.x = x
self.y = y
self.width = width
self.height = height
# draw border
self.buttonBorder = pygame.Rect(x, y, width, height) # makes the buttonBorder a rect type
# fill in button
pygame.draw.rect(Display.screenDisplay, buttonColour, self.buttonBorder, 0)
pygame.draw.rect(Display.screenDisplay, borderColour, self.buttonBorder, 10)
# put text in
self.buttonBorder.centerx = self.buttonBorder.centerx * xratio # sets center of button to correct for Text
self.buttonBorder.centery = self.buttonBorder.centery * yratio
textFont = pygame.font.SysFont(font, fontSize) # sets text font
textSurface = textFont.render(text, False, fontColour,
None) # renders text surface with the text and fontColour
Display.screenDisplay.blit(textSurface, self.buttonBorder.center) # draws text onto screen
pygame.display.flip()
class text:
def __init__(self, x, y, font, fontSize, fontColour, text, Display): # initialize general Text
textFont = pygame.font.SysFont(font, fontSize) # sets font
textSurface = textFont.render(text, False, fontColour, None) # renders text surface with text and fontcolour
Display.screenDisplay.blit(textSurface, (x, y)) # draws text onto screen
pygame.display.flip()
class quitButton:
def __init__(self, x, y, width, height, fontSize, buttonColour, borderColour, fontColour, Display, xratio,
yratio):
# set attributes
self.x = x
self.y = y
self.width = width
self.height = height
self.buttonBorder = pygame.Rect(x, y, width, height)
# draw rect and set rect center
pygame.draw.rect(Display.screenDisplay, buttonColour, self.buttonBorder, 0)
pygame.draw.rect(Display.screenDisplay, borderColour, self.buttonBorder, 5)
self.buttonBorder.centerx = self.buttonBorder.centerx * xratio
self.buttonBorder.centery = self.buttonBorder.centery * yratio
# put X in
textFont = pygame.font.SysFont('Candara', fontSize)
textSurface = textFont.render('X', False, fontColour, None)
Display.screenDisplay.blit(textSurface, (self.buttonBorder.center))
pygame.display.flip()
# END OF BASIC DISPLAY ATTRIBUTES
# FIRST SCREEN CODE
def mainMenu(quit_button, start_button, continue_button,Display): # making buttons clickable
while True:
for evento in pygame.event.get():
if evento.type == pygame.MOUSEBUTTONDOWN:
if quit_button.buttonBorder.collidepoint(pygame.mouse.get_pos()): # tests if pointer is within rect
pygame.quit()
quit()
elif start_button.buttonBorder.collidepoint(pygame.mouse.get_pos()):
mainGame(Display)
break
elif continue_button.buttonBorder.collidepoint(pygame.mouse.get_pos()):
if os.path.isfile('\Saves\sav.txt'):
loadGame(Display)
else:
errorMessage = button((1200 / 20) * 4, (720 / 20) * 8, (1200 / 20) * 12, (720 / 20) * 2,
'No Save file available', 'Candara', 36, colours.buttonDarkC,
colours.space, colours.space, Display, 0.75, 0.945)
def firstScreen(Display): # firstScreen
title = text((515), ((720 / 20) * 2), 'Candara', 96, colours.buttonDarkC, 'Blue', Display)
startButton = button(((1200 / 12) * 2), ((720 / 20) * 5), ((1200 / 12) * 8), (720 / 10), "START", 'Candara', 48,
colours.buttonBlue, colours.buttonBlue, colours.buttonDarkC, Display, 0.9,
0.9) # draws START button
continueButton = button(((1200 / 12) * 3), ((720 / 20) * 8), ((1200 / 12) * 6), (720 / 10), "Continue", 'Candara',
36, colours.buttonBlue, colours.buttonBlue, colours.buttonDarkC, Display, 0.9, 0.95)
quitButton = button(((1200 / 12) * 3), ((720 / 20) * 11), ((1200 / 12) * 6), (720 / 10), "Quit", 'Candara', 36,
colours.buttonBlue, colours.buttonBlue, colours.buttonDarkC, Display, 0.97, 0.95)
mainMenu(quitButton, startButton, continueButton, Display)
# END OF FIRST SCREEN
# START OF MAIN GAME
spriteClock = pygame.time.Clock()
enemyGroup = pygame.sprite.Group()
mainGroup = pygame.sprite.Group()
floorGroups = pygame.sprite.Group()
def spriteAnimate(sprite1, spriteGroup1, clock,Display,maskSet):
sprite1.index += 1
if sprite1.index >= len(maskSet):
sprite1.index = 0
Display.screenDisplay.blit(sprite1.surface, sprite1.currentCoords)
sprite1.surface.fill(colours.black)
pygame.display.flip()
sprite1.image = maskSet[sprite1.index]
spriteGroup1.draw(Display.screenDisplay)
pygame.display.flip()
currentTime = pygame.time.get_ticks()
clock.tick(10)
class sprite(pygame.sprite.Sprite):
def __init__(self, colWidth, colHeight,framesNo,Display, spriteGroup='', spawnX=0, spawnY=0):
super().__init__()
self.xSpawn = spawnX
self.ySpawn = spawnY
self.width,self.height = colWidth, colHeight
self.currentCoords = (spawnX, spawnY)
self.rect = pygame.Rect(spawnX, spawnY,int(colWidth), int(colHeight))
self.surface = pygame.Surface((colWidth,colHeight))
self.masks = [None]*framesNo
self.index = 0
self.image = self.masks[self.index]
if spriteGroup != '':
spriteGroup.add(self) # if there is a sprite group, add it
def coordUpdate(self,newCoords):
self.currentCoords = newCoords
self.rect = pygame.Rect(newCoords[0],newCoords[1],int(self.width), int(self.height))
def surfaceUpdate(self,newWidth,newHeight):
self.surface = pygame.Surface((newWidth,newHeight))
self.width = newWidth
self.height = newHeight
def moveRight(self,Display):
self.currentCoords = list(self.currentCoords)
self.currentCoords[0] += 20
self.coordUpdate(self.currentCoords)
spriteAnimate(self,mainGroup,spriteClock,Display,self.runningMasksR)
def moveLeft(self,Display):
self.currentCoords = list(self.currentCoords)
self.currentCoords[0] -= 20
self.coordUpdate(self.currentCoords)
spriteAnimate(self,mainGroup,spriteClock,Display,self.runningMasksL)
class ballEnemy(sprite):
def __init__(self,Display):
self.mask1 = pygame.image.load(
os.path.join(os.getcwd()+'\spriteIMG', 'testmask1.png')) # sets the images to png images
self.mask2 = pygame.image.load(os.path.join(os.getcwd()+'\spriteIMG', 'testmask2.png'))
self.mask3 = pygame.image.load(os.path.join(os.getcwd()+'\spriteIMG', 'testmask3.png'))
super().__init__(640, 640, 4,Display, enemyGroup)
self.masks[0] = self.mask1.convert_alpha()
self.masks[1] = self.mask2.convert_alpha()
self.masks[2] = self.mask3.convert_alpha()
self.masks[3] = self.mask2.convert_alpha()
spriteAnimate(self, enemyGroup, spriteClock, Display,self.masks)
class floor(sprite):
def __init__(self,Display):
self.mask1 = (pygame.image.load(os.path.join(os.getcwd()+'\spriteIMG', 'Floor-1.png')))
super().__init__(720,600,1,Display,floorGroups)
self.masks[0] = self.mask1.convert_alpha()
self.image = self.masks[0]
floorGroups.draw(Display.screenDisplay)
pygame.display.flip()
class mainSprite(sprite):
def __init__(self,Display):
self.mask1 = (pygame.image.load(os.path.join(os.getcwd() + '\spriteIMG', 'foxIdle1.png')))
self.mask2 = (pygame.image.load(os.path.join(os.getcwd() + '\spriteIMG', 'foxIdle2.png')))
self.mask3 = (pygame.image.load(os.path.join(os.getcwd() + '\spriteIMG', 'foxIdle3.png')))
self.mask4 = (pygame.image.load(os.path.join(os.getcwd() + '\spriteIMG', 'foxIdle4.png')))
super().__init__(52,84,4,Display,mainGroup,20,319)
self.masks[0] = self.mask1.convert_alpha()
self.masks[1] = self.mask2.convert_alpha()
self.masks[2] = self.mask3.convert_alpha()
self.masks[3] = self.mask2.convert_alpha()
self.running1 = (pygame.image.load(os.path.join(os.getcwd() + '\spriteIMG','foxrunning-1.png')))
self.running2 = (pygame.image.load(os.path.join(os.getcwd() + '\spriteIMG','foxrunning-2.png')))
self.running3 = (pygame.image.load(os.path.join(os.getcwd() + '\spriteIMG','foxrunning-3.png')))
self.running4 = (pygame.image.load(os.path.join(os.getcwd() + '\spriteIMG','foxrunning-4.png')))
self.runningMasksR= [self.running1.convert_alpha(),self.running2.convert_alpha(),self.running3.convert_alpha(),self.running4.convert_alpha()]
self.runningL1 = (pygame.image.load(os.path.join(os.getcwd() + '\spriteIMG','foxRunningL-1.png')))
self.runningL2 = (pygame.image.load(os.path.join(os.getcwd() + '\spriteIMG', 'foxRunningL-2.png')))
self.runningL3 = (pygame.image.load(os.path.join(os.getcwd() + '\spriteIMG', 'foxRunningL-3.png')))
self.runningL4 = (pygame.image.load(os.path.join(os.getcwd() + '\spriteIMG', 'foxRunningL-4.png')))
self.runningMasksL = [self.runningL1.convert_alpha(),self.runningL2.convert_alpha(),self.runningL3.convert_alpha(),self.runningL4.convert_alpha()]
runningR = False
while self.alive():
spriteAnimate(self,mainGroup,spriteClock,Display,self.masks)
D_down = False
A_down = False
SPACE_down = False
for event2 in pygame.event.get():
if event2.type == pygame.KEYDOWN :
if event2.key == pygame.K_d :
D_down = True
self.surfaceUpdate(104,63)
elif event2.key == pygame.K_a :
A_down = True
self.surfaceUpdate(104,63)
while A_down == True:
self.moveLeft(Display)
for event2 in pygame.event.get():
if event2.type == pygame.KEYUP:
if event2.key == pygame.K_a:
A_down = False
self.surfaceUpdate(52, 84)
while D_down == True:
self.moveRight(Display)
for event2 in pygame.event.get():
if event2.type == pygame.KEYUP :
if event2.key == pygame.K_d :
D_down = False
self.surfaceUpdate(52,84)
def mainGame(display):
display.screenDisplay.fill(colours.black)
floor1 = floor(display)
mainSprite1 = mainSprite(display)
pygame.display.flip()
def loadGame(Display):
Display.screenDisplay.fill(colours.buttonBlue)
errorMessage = text((515), ((720 / 20) * 2), 'Candara', 38, colours.buttonDarkC, 'main game is under construction',
Display)
# END OF MAIN GAME
# START FUNCTION
def main():
pygame.init() # initialize pygame
display = mainDisplay() # makes the current display object 'mainDisplay', opening a window
screen1 = True # set variable screen1 to True
maingame = False
while True:
firstScreen(display) # starts first screen
for event in pygame.event.get(): # for every event that happens in queue
if event.type == pygame.QUIT: # if event type is uninitialize pygame
pygame.quit() # quit pygame
quit() # quit python
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.