blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
779ec6a9356ef1c65424163a42ad8cbd6806b2d9 | eugenesamozdran/lits-homework | /200_line_homework.py | 9,580 | 3.734375 | 4 | import random
#defining the order
def player_order(p1,p2):
global order
print("Player 1 rolled ", p1)
print("Player 2 rolled ", p2)
if p1 == "rock" and p2 == "scissors":
print("Player 1 goes first!")
order = 1
elif p1 == "rock" and p2 == "paper":
print("Player 2 goes first!")
order = 2
elif p1 == "scissors" and p2 == "rock":
print("Player 2 goes first!")
order = 2
elif p1 == "scissors" and p2 == "paper":
print("Player 1 goes first!")
order = 1
elif p1 == "paper" and p2 == "rock":
print("Player 1 goes first!")
order = 1
elif p1 == "paper" and p2 == "scissors":
print("Player 2 goes first!")
order = 2
elif p1 == p2:
print("It's a draw! One more time:")
p1 = random.choice(("rock", "scissors", "paper",))
p2 = random.choice(("rock", "scissors", "paper",))
player_order(p1,p2)
#describing races, classes, weapons, hit points and damage
race = ("orc",
"human",
"elf",
"gnoll")
battle_class = ("tank",
"berserker",
"shooter",
"wizard")
weapons = ("sword",
"hammer",
"crossbow",
"spell book")
#basic hit points depending on the race
orc_hp = 55
human_hp = 50
elf_hp = 47
gnoll_hp = 49
#hit points modifier for each class
t_mod = 1.1
b_mod = 1.2
s_mod = 1
w_mod = 0.9
#attack modifier for each weapon
sw_att = 1
ham_att = 1
cr_att = 1.2
sb_att = 1.4
while True:
print("Greetings! Let the fate decide who goes first: ")
p1 = random.choice(("rock", "scissors", "paper",))
p2 = random.choice(("rock", "scissors", "paper",))
player_order(p1,p2)
print("Let the fun begin!")
#creating the character
p1_race = input("Player 1, choose your race ('orc', 'human', 'elf' or 'gnoll'): ")
while p1_race not in race:
p1_race = input("Please try again: ")
p1_class = input("Your class ('tank', 'berserker', 'shooter' or 'wizard'): ")
while p1_class not in battle_class:
p1_class = input("Please try again: ")
p1_weap = input("And your weapon ('sword', 'hammer', 'crossbow' or 'spell book'): ")
while p1_weap not in weapons:
p1_weap = input("Please try again: ")
p2_race = input("Player 2, choose your race ('orc', 'human', 'elf' or 'gnoll'): ")
while p2_race not in race:
p2_race = input("Please try again: ")
p2_class = input("Your class ('tank', 'berserker', 'shooter' or 'wizard'): ")
while p2_class not in battle_class:
p2_class = input("Please try again: ")
p2_weap = input("And your weapon ('sword', 'hammer', 'crossbow' or 'spell book'): ")
while p2_weap not in weapons:
p2_weap = input("Please try again: ")
#player 1 hit points
if p1_race == "orc" and p1_class == "tank":
p1_hp = orc_hp*t_mod
elif p1_race == "orc" and p1_class == "berserker":
p1_hp = orc_hp*b_mod
elif p1_race == "orc" and p1_class == "shooter":
p1_hp = orc_hp*s_mod
elif p1_race == "orc" and p1_class == "wizard":
p1_hp = orc_hp*w_mod
elif p1_race == "human" and p1_class == "tank":
p1_hp = human_hp*t_mod
elif p1_race == "human" and p1_class == "berserker":
p1_hp = human_hp*b_mod
elif p1_race == "human" and p1_class == "shooter":
p1_hp = human_hp*s_mod
elif p1_race == "human" and p1_class == "wizard":
p1_hp = human_hp*w_mod
elif p1_race == "elf" and p1_class == "tank":
p1_hp = elf_hp*t_mod
elif p1_race == "elf" and p1_class == "berserker":
p1_hp = elf_hp*b_mod
elif p1_race == "elf" and p1_class == "shooter":
p1_hp = elf_hp*s_mod
elif p1_race == "elf" and p1_class == "wizard":
p1_hp = elf_hp*w_mod
elif p1_race == "gnoll" and p1_class == "tank":
p1_hp = gnoll_hp*t_mod
elif p1_race == "gnoll" and p1_class == "berserker":
p1_hp = gnoll_hp*b_mod
elif p1_race == "gnoll" and p1_class == "shooter":
p1_hp = gnoll_hp*s_mod
elif p1_race == "gnoll" and p1_class == "wizard":
p1_hp = gnoll_hp*w_mod
#player 2 hit points
if p2_race == "orc" and p2_class == "tank":
p2_hp = orc_hp*t_mod
elif p2_race == "orc" and p2_class == "berserker":
p2_hp = orc_hp*b_mod
elif p2_race == "orc" and p2_class == "shooter":
p2_hp = orc_hp*s_mod
elif p2_race == "orc" and p2_class == "wizard":
p2_hp = orc_hp*w_mod
elif p2_race == "human" and p2_class == "tank":
p2_hp = human_hp*t_mod
elif p2_race == "human" and p2_class == "berserker":
p2_hp = human_hp*b_mod
elif p2_race == "human" and p2_class == "shooter":
p2_hp = human_hp*s_mod
elif p2_race == "human" and p2_class == "wizard":
p2_hp = human_hp*w_mod
elif p2_race == "elf" and p2_class == "tank":
p2_hp = elf_hp*t_mod
elif p2_race == "elf" and p2_class == "berserker":
p2_hp = elf_hp*b_mod
elif p2_race == "elf" and p2_class == "shooter":
p2_hp = elf_hp*s_mod
elif p2_race == "elf" and p2_class == "wizard":
p2_hp = elf_hp*w_mod
elif p2_race == "gnoll" and p2_class == "tank":
p2_hp = gnoll_hp*t_mod
elif p2_race == "gnoll" and p2_class == "berserker":
p2_hp = gnoll_hp*b_mod
elif p2_race == "gnoll" and p2_class == "shooter":
p2_hp = gnoll_hp*s_mod
elif p2_race == "gnoll" and p2_class == "wizard":
p2_hp = gnoll_hp*w_mod
#starting the fight if Player 1 should go first
if order == 1:
while True:
print("Player 1 has {0} HP and Player 2 has {1} HP".format(p1_hp, p2_hp))
#different range of integers is chosen to show the difference between each weapon
attack_1 = input("Player 1, describe your attack to your opponent and enter 'go!': ")
while attack_1 not in ("go!",):
attack_1 = input("Please try again: ")
if attack_1 == "go!":
if p1_weap == "sword":
p2_hp -= sw_att*random.randint(1,15)
elif p1_weap == "hammer":
p2_hp -= ham_att*random.randint(1,15)
elif p1_weap == "crossbow":
p2_hp -= cr_att*random.randint(1,20)
elif p1_weap == "spell book":
p2_hp -= sb_att*random.randint(1,23)
attack_2 = input("Player 2, describe your attack to your opponent and enter 'go!': ")
while attack_2 not in ("go!",):
attack_2 = input("Please try again: ")
if attack_2 == "go!":
if p2_weap == "sword":
p1_hp -= sw_att*random.randint(1,15)
elif p2_weap == "hammer":
p1_hp -= ham_att*random.randint(1,15)
elif p2_weap == "crossbow":
p1_hp -= cr_att*random.randint(1,20)
elif p2_weap == "spell book":
p1_hp -= sb_att*random.randint(1,23)
if p1_hp <= 0 or p2_hp <= 0:
print("Player 1 has {0} HP and Player 2 has {1} HP, congratulations to the winner!".format(p1_hp, p2_hp))
break
else:
continue
#starting the fight if Player 2 should go first
if order == 2:
while True:
print("Player 1 has {0} HP and Player 2 has {1} HP".format(p1_hp, p2_hp))
attack_2 = input("Player 2, describe your attack to your opponent and enter 'go!': ")
while attack_2 not in ("go!",):
attack_2 = input("Please try again: ")
if attack_2 == "go!":
if p2_weap == "sword":
p1_hp -= sw_att*random.randint(1,15)
elif p2_weap == "hammer":
p1_hp -= ham_att*random.randint(1,15)
elif p2_weap == "crossbow":
p1_hp -= cr_att*random.randint(1,20)
elif p2_weap == "spell book":
p1_hp -= sb_att*random.randint(1,23)
attack_1 = input("Player 1, describe your attack to your opponent and enter 'go!': ")
while attack_1 not in ("go!",):
attack_1 = input("Please try again: ")
if attack_1 == "go!":
if p1_weap == "sword":
p2_hp -= sw_att*random.randint(1,15)
elif p1_weap == "hammer":
p2_hp -= ham_att*random.randint(1,15)
elif p1_weap == "crossbow":
p2_hp -= cr_att*random.randint(1,20)
elif p1_weap == "spell book":
p2_hp -= sb_att*random.randint(1,23)
if p1_hp <= 0 or p2_hp <= 0:
print("Player 1 has {0} HP and Player 2 has {1} HP, congratulations to the winner!".format(p1_hp, p2_hp))
break
else:
continue
#asking if players want to start the game again
repeat = input("Would you like to play again? Enter 'y' for another game or 'n' to quit: ")
while repeat not in ("y","n"):
repeat = input("Please make a valid choice ('y' or 'n'): ")
if repeat=="y":
continue
else:
print("Good bye!")
break
|
0128fa703349d1414a6b4b0610d6afa18329cfc1 | daveclouds/python | /mississippichallenge.py | 128 | 3.53125 | 4 | import time
for second in range (1 , 6):
print(second, "Mississippi")
time.sleep(1)
print('Ready or not, Here I come') |
54eb01f1115e223c35fe1d1ee49d1561d2f960c1 | megaprokoli/data-glasses | /drawer/text_drawer.py | 1,288 | 3.71875 | 4 | from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
from drawer.drawer import Drawer
class TextDrawer(Drawer):
def __init__(self, content):
super().__init__(content)
def draw(self, disp):
print("drawing text ({})".format(self._content))
disp.clear()
disp.display()
width = disp.width
height = disp.height
image = Image.new('1', (width, height))
# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)
# Draw a black filled box to clear the image.
draw.rectangle((0, 0, width, height), outline=0, fill=0)
# Draw some shapes.
# First define some constants to allow easy resizing of shapes.
padding = -2
top = padding
bottom = height - padding
# Move left to right keeping track of the current x position for drawing shapes.
x = 0
# Load default font.
font = ImageFont.load_default()
# Draw a black filled box to clear the image.
draw.rectangle((0, 0, width, height), outline=0, fill=0)
# Write two lines of text.
draw.text((x, top), self._content, font=font, fill=255)
# Display image.
disp.image(image)
disp.display()
|
63dd4aeff91caf6065f0d502647a66e2d3c3f129 | philipdongfei/Think-python-2nd | /Chapter11/rotate_pairs.py | 513 | 3.84375 | 4 | from rotate import rotate_word
def make_word_dict():
d = dict()
fin = open('words.txt')
for line in fin:
word = line.strip().lower()
d[word] = None
return d
def rotate_pairs(word, word_dict):
for i in range(1, 14):
rotated = rotate_word(word, i)
if rotated in word_dict:
print(word, i, rotated)
def main():
word_dict = make_word_dict()
for word in word_dict:
rotate_pairs(word, word_dict)
if __name__ == '__main__':
main()
|
4297e89b3c6500d3b0fd16953346b79db44e7edb | rafaelperazzo/programacao-web | /moodledata/vpl_data/129/usersdata/230/44242/submittedfiles/al7.py | 178 | 3.65625 | 4 | # -*- coding: utf-8 -*-
n=int(input('Digite valor de n: '))
soma=0
for i in range (1,n,1):
if n%i==0:
soma=soma+i
if soma==n:
print('sim')
else:
print('não') |
dc096b12fda1e7bf1441045c001b56adaac3bb2b | bhirtzer/crypto | /vigenere.py | 641 | 3.96875 | 4 | import string
from helpers import alphabet_position, rotate_character
def encrypt(text, key):
new_text = ''
count = 0
k = 0
for i in text:
if i.isalpha():
k = alphabet_position(key[count])
new_text = new_text + rotate_character(i, k)
count = ((count + 1) % len(key))
else:
new_text = new_text + i
return new_text
def main():
message = str(input("Type a message: "))
print(message)
key = str(input("Encryption key: "))
print(key)
print(encrypt(message, key))
if __name__ == "__main__":
main() |
52a073b1375aceeb57482327183cd6caa0f8ae9b | kaviraj333/pythonprogram | /58.py | 136 | 3.6875 | 4 | p,q=map(int,raw_input().split())
list=[int(a) for a in raw_input().split()]
if p and q in list:
print "yes"
else:
print "no"
|
70f87a62bf044d68c1f0e89182243b4375e0b2a8 | glennlopez/CS50.HarvardX | /pset6/2022/sandbox/upper.py | 183 | 3.921875 | 4 | from cs50 import get_string
usr_str = get_string("Before: ")
print("After: ", end="")
for i in usr_str:
print(i.upper(), end="")
print()
print(f"Lower cased: {usr_str.lower()}") |
68a56526eea5530a1ce436414fc25ec737c2c7a3 | tebeka/pythonwise | /euler24.py | 1,504 | 3.71875 | 4 | #!/usr/bin/env python
''' Solving http://projecteuler.net/index.php?section=problems&id=24
Note that Python's 2.6 itertools.permutations return the permutation in order so
we can just write:
from itertools import islice, permutations
print islice(permutations(range(10)), 999999, None).next()
And it'll work much faster :)
'''
from itertools import islice, ifilter
def is_last_permutation(n):
return n == sorted(n, reverse=1)
def next_head(n):
'''Find next number to be 'head'.
It is smallest number if the tail that is bigger than the head.
In the case of (2 4 3 1) it will pick 3 to get the next permutation
of (3 1 2 4)
'''
return sorted(filter(lambda i: i > n[0], n[1:]))[0]
def remove(element, items):
return filter(lambda i: i != element, items)
def next_permutation(n):
if is_last_permutation(n):
return None
sub = next_permutation(n[1:])
if sub:
return [n[0]] + sub
head = next_head(n)
return [head] + sorted([n[0]] + remove(head, n[1:]))
def nth(it, n):
'''Return the n'th element of an iterator'''
return islice(it, n, None).next()
def iterate(func, n):
'''iterate(func, n) -> n, func(n), func(func(n)) ...'''
while 1:
yield n
n = func(n)
def permutations(n):
return ifilter(None, iterate(next_permutation, n))
if __name__ == "__main__":
n = range(10)
m = 1000000
print "Calculateing the %d permutation of %s" % (m, n)
print nth(permutations(n), m-1)
|
1085aed0df68240ace4cd4d67b65921c030c73b6 | zooonique/Coding-Test | /괄호회전.py | 660 | 3.5 | 4 | def solution(s):
answer = 0
sample = ['()','{}','[]']
case = s
for cnt in range(len(s)):
# n번 rotate
case = case[1:len(s):]+case[0]
tmp = case
while case:
if sample[0] in case:
case=case.replace(sample[0],'')
elif sample[1] in case:
case=case.replace(sample[1],'')
elif sample[2] in case:
case=case.replace(sample[2],'')
else:
answer-=1
break
answer += 1
case = tmp
return answer
|
fc8aa3a629eb87ac062e23ad828a8f1b7ab03a2b | rprasai/Assignment2 | /Car.py | 407 | 3.8125 | 4 | import car_class
def main():
model_year = input("Enter the Car Year Model: ")
make = input("Enter the car Make:")
car = car_class.Car(model_year, make)
accele(car)
brake(car)
def accele(car):
for count in range(1, 6):
car.accelerate()
print(car.get_speed())
def brake(car):
for count in range(5):
car.brake()
print(car.get_speed())
main() |
f4a8f8b169238a92af87a2503dec467900e4763a | soneyaa/Python-Assignment | /Python Assignment/module3/exercise10/pattern1_12.py | 275 | 3.953125 | 4 | n=int(input())
i=1
for i in range(n):
for j in range(n-i):
print("* ",end='')
if(i==n-1):
continue
else:
print()
for i in range(n+1):
for j in range(i):
print("* ",end='')
print()
|
ee2d0f86464490aa66cf8a2f7d26308fbc6b05a9 | OSGeoLabBp/tutorials | /hungarian/python/code/point2d.py | 2,269 | 3.515625 | 4 | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
class Point2D(object): # object a bázis osztály
""" kétdimenziós pontok osztálya
"""
def __init__(self, east = 0, north = 0): # __init__ a konstruktor
""" Pont inicializálás
:param east: első koordináta
:param north: második koordináta
"""
self.setEast(east)
self.setNorth(north)
def setEast(self, east):
""" első koordináta beállítása """
if type(east) in (int, float):
self.__east = east
else:
raise Exception("hibás koordináta típus")
def setNorth(self, north):
""" második koordináta beállítása """
if type(north) in (int, float):
self.__north = north
else:
raise Exception("hibás koordináta típus")
def getEast(self):
""" első koordináta lekérdezése """
return self.__east
def getNorth(self):
""" második koordináta lekérdezése """
return self.__north
def abs(self):
""" helyvektor hossza (absolút érték)
:returns: absolút érték
"""
return (self.__east**2 + self.__north**2)**0.5
def __str__(self):
""" Pont szövegláccá alakítása kiiratáshoz
:returns: a koordináták szövegláncként
"""
return "{:.3f}; {:.3f}".format(self.__east, self.__north)
def __add__(self, p):
""" Két pont összeadása
:param p: hozzáadandó pont
:returns: a két pont összegéből képzett Point2D példányt
"""
return Point2D(self.__east + p.getEast(), self.__north + p.getNorth())
if __name__ == "__main__":
""" tesztelő kód az osztályhoz """
p0 = Point2D() # pont az origóban
p1 = Point2D(5) # pont 5, 0
p2 = Point2D(north=6) # pont 0, 6
p3 = Point2D(-2, 6) # pont -2, 6
try:
p4 = Point2D([12, 5])
except:
print("Hibás inicializálás")
print(p3)
print(p3.abs())
print(p3.getEast())
p3.setEast(99)
print(p3)
p3.__east = 4 # nem módosítja a privát változót, de nincs hiba
print(p3)
|
fd003e4bbf4384a0a0f24e9724761391349e77be | Apondon/testtest | /demo/16-list.py | 277 | 4.09375 | 4 | # Using a list comprehension, create a new list called "newlist" out of the list "numbers",
# which contains only the positive numbers from the list, as integers.
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7 ,10]
newlist = [int(num) for num in numbers]
print(newlist) |
75b361e15026eeedff1a4e96aca30ec817056b24 | chielk/beautiful_data | /ex1/visualize.py | 4,141 | 3.65625 | 4 | import sys
from operator import itemgetter
import matplotlib.pyplot as plt
def i(name):
"""Convert a cars.csv file name to an index."""
if name == "model":
return 0
elif name == "mpg":
return 1
elif name == "cylinders":
return 2
elif name == "horsepower":
return 3
elif name == "weight":
return 4
elif name == "year":
return 5
elif name == "origin":
return 6
def s(sides):
"""
Return the symbol for an n-dimensional polygon in matplotlib.
3 triangle "^"
4 square "s"
5 pentagon "p"
6 hexagon "h"/"H"
7 octagon "8"
"""
if sides == 3:
return "^"
elif sides == 4:
return "s"
elif sides == 5:
return "p"
elif sides == 6:
return "h"
elif sides == 7:
return "8"
else:
return "o"
def read_file(file):
"""Reads the car.csv file and returns a list of tuples with the appropriate
types.
"""
firstline = True
for line in file:
if firstline:
firstline = False
continue
point = line.strip().split(",")
yield (point[0],
float(point[1]),
int(point[2]),
int(point[3]),
int(point[4]),
1900 + int(point[5]),
point[6])
def split_by(data, index):
"""Split the data into a dictionary by the given field."""
sets = {}
for point in data:
if point[index] in sets:
sets[point[index]].append(point)
else:
sets[point[index]] = [point]
return sets
def sort_by(data, index):
"""Return the data sorted by a given field."""
return sorted(data, key=itemgetter(index))
def min_max(points, index):
"""Calculate the minimum and maximum for a given field."""
min = 99999999999
max = 0
for point in points:
if point[index] > max:
max = point[index]
if point[index] < min:
min = point[index]
return min, max
if __name__ == "__main__":
data_points = read_file(open("data/cars.csv"))
sorted_points = sort_by(data_points, i("year"))
by_origin = split_by(sorted_points, i("origin"))
multiple_graphs = True
window = 1
for origin, points in by_origin.iteritems():
if multiple_graphs:
plt.subplot(3, 1, window)
plt.title(origin)
plt.axis([1962, 1983, 35, 240])
if window == 2:
plt.plot([0], [0], "s",
color=".5",
markersize=16,
label="5000 lbs")
plt.plot([0], [0], "s",
color=".5",
markersize=4,
label="1600 lbs")
plt.plot([0], [0], "s",
color="0",
label="9 Mile/Gallon")
plt.plot([0], [0], "s",
color="1",
label="50 Mile/Gallon")
elif window == 1:
plt.plot([0], [0], "^",
color="0.5",
label="Three cylinders")
plt.plot([0], [0], "s",
color="0.5",
label="Four cylinders")
plt.plot([0], [0], "p",
color="0.5",
label="Five cylinders")
plt.plot([0], [0], "h",
color="0.5",
label="Six cylinders")
plt.plot([0], [0], "8",
color="0.5",
label="Eight cylinders")
legend = plt.legend(loc="upper left", numpoints=1, frameon=False)
plt.ylabel("Horsepower")
window += 1
for point in points:
year = point[i("year")]
hors = point[i("horsepower")]
cyli = point[i("cylinders")]
wght = point[i("weight")]
mipg = point[i("mpg")]
plt.plot([year], [hors],
s(cyli),
color=str((mipg-9)/41),
markersize=wght/400)
plt.xlabel("Year")
plt.show()
|
180d4e246357c0bf9966d24f75361acbfbe1e970 | ThomasLee94/firecode | /is_palindrome.py | 766 | 4.125 | 4 | def is_palindrome_recursive(text: str, forward=None, backward=None) -> bool:
# set forward and backward
if forward == None and backward == None:
forward = 0
backward = len(text) - 1
# check if forward is less than backwards
if forward >= backward:
return True
# skip over non letters
if text[forward] not in string.ascii_letters:
return is_palindrome_recursive(text, forward + 1, backward)
if text[backward] not in string.ascii_letters:
return is_palindrome_recursive(text, forward, backward - 1)
# check if indecies match
if text[forward].lower() != text[backward].lower():
return False
else:
return is_palindrome_recursive(text, forward + 1, backward - 1) |
341110cb4216e6be3f520aa02338470f513ab43b | rlatmd0829/algorithm | /알고리즘풀이/21.07.03/괄호의값.py | 1,008 | 3.515625 | 4 | node = list(input())
stack = []
answer = 0
for i in node:
if i == ')':
t = 0
while len(stack) != 0:
top = stack.pop()
if top == '(':
if t == 0:
stack.append(2)
else:
stack.append(2 * t)
break
elif top == '[':
print(0)
exit(0)
else:
t = t + int(top)
elif i == ']':
t = 0
while len(stack) != 0:
top = stack.pop()
if top == '[':
if t == 0:
stack.append(3)
else:
stack.append(3 * t)
break
elif top == '(':
print(0)
exit(0)
else:
t = t + int(top)
else:
stack.append(i)
for i in stack:
if i == '(' or i == '[':
print(0)
exit(0)
else:
answer += i
print(answer) |
45ad7f54414b2072b389cc0d6180187da3be7b4f | Hidorikun/Calculator-Converter-for-numbers-in-base-2..16- | /Code/src/domain/entities.py | 29,850 | 3.859375 | 4 |
class ProgramException(Exception):
pass
class BaseNumException(ProgramException):
pass
class BaseNum(object):
def __init__(self, value, base):
'''
This method initialises the object:
:args:
value - string representing the value
base - base of the value
'''
self.__value = value.lower()
self.__base = base
self.__signed = False
if len(value) != 0 and value[0] == '-':
self.__value = value[1:]
self.__signed = True
self.__trim_front_zeros()
self.__validate()
if self.__value =='0':
self.__signed = False
def __trim_front_zeros(self):
'''
trims the front zeros of the object's value
if value consists of only one 0, it is left intact
'''
while len(self.__value) > 1 and self.__value[0] == '0':
self.__value = self.__value[1:]
@staticmethod
def digit(d):
'''
returns the digit d converted to base 10
:args
d - character representing the digit to be converted
:returns
int(d) - if d between ['0', '9']
ord(d) - ord('a') + 10 if d between ['a', 'z']
'''
if d >= '0' and d <='9':
return int(d)
if d >= 'a' and d <= 'z':
return ord(d) - ord('a') + 10
def __validate(self):
'''
method that validates the properties of the object
:raises
BaseNumException if :
- base is not an integer number
- the value is an empty string
- the base is not between [2, 16]
- the value has characters besides ['0' - '9'],['a' - 'f']
- the characters in value are greater than base
'''
try:
self.__base = int(self.__base)
except ValueError:
raise BaseNumException("Error -- base must be an integer number")
if len(self.value) == 0:
raise BaseNumException("Error -- value cannot be empty")
if self.base < 2 or self.base > 16:
raise BaseNumException("Error -- base must be between [2, 16]")
for v in self.value:
if v not in '0123456789abcdef':
raise BaseNumException('Error -- value must only contain digits and letters from [a..f]')
if BaseNum.digit(v) >= self.base:
raise BaseNumException("Error -- values must be smaller than the base")
@property
def value(self):
'''
property that returns the object's value
:returns
self.__value
'''
return self.__value
@property
def base(self):
'''
property that returns the object's base
:returns
self.__base
'''
return self.__base
@property
def signed(self):
'''
property that returns if the object is signed or not
'''
return self.__signed
def __getitem__(self, i):
'''
method that returns self.value[i] whenever object[i] is called
'''
return self.value[i]
def __str__(self):
'''
method that overridees the default string representation of the object
iw will be represented as 'sgn+value+(base)' for example -1a3(16)
'''
if self.signed:
sign = '-'
else:
sign = ''
return sign + self.value + '({base})'.format(base = self.base)
def __add__(self, other):
'''
this method is called whenever we have a + b, there a and b are BaseNum objects
this add override works more like a switch for the __addition_implementation method
it chooses how to call the __addition_implementaton method depending on the sign of
its arguments
:args
self - this object
other - the other object in the expression
:returns
sum(self, other) if they are both positive
sub(self, -other) if self is positive and other negative
sub(other, - self) if self is negative and b is positive
-sum(-a, -b) if both are negative
where:
sum = __addition_implementation
sub = __subtraction_implementation
and returns the BaseNum object that represents the sum of the self and other
'''
a = self
b = other
a_positive = not a.signed
a_negative = a.signed
b_positive = not b.signed
b_negative = b.signed
sum = self.__addition_implementation
sub = self.__subtraction_implementation
if a_positive and b_positive:
return sum(a, b)
if a_positive and b_negative:
return sub(a, -b)
if a_negative and b_positive:
return sub(b, -a)
if a_negative and b_negative:
return -sum(-a, -b)
def __sub__(self, other):
'''
this method is called whenever we have a - b, where a and b are BaseNum objects
this method works more like a switch for the __subtraction_implementation method
it chooses how to call the __subtraction_implementation method depending on the sign
of its arguments
:args
self -this object
other - the other object in the expression
:returns
sub(self,other) if both are positive
sum(self, -other) if a is positive and b ie negative
-sum(-self, other) it a is negative and b is positive
sub(-other, -self) if both are negative
where:
sum = __addition_implementation
sub = __subtraction_implementation
and returns the BaseNum object that represents the sum of the self and other
'''
a = self
b = other
a_positive = not a.signed
a_negative = a.signed
b_positive = not b.signed
b_negative = b.signed
sum = self.__addition_implementation
sub = self.__subtraction_implementation
if a_positive and b_positive:
return sub(a, b)
if a_positive and b_negative:
return sum(a, -b)
if a_negative and b_positive:
return -sum(-a, b)
if a_negative and b_negative:
return sub(-b, -a)
def __mul__(self, other):
'''
this method is called whenever we have a * b where a and b are BaseNum objects
:returns
BaseNum object that has the the multiplied value of self and other in their base
'''
a = -self if self.signed else self
b = -other if other.signed else other
# a and b are the positive values of self, respectively other
result = self.__multiplication_implementation(a, b)
#if don't have the same sign, the product will be negative
if self.signed != other.signed:
result = -result
#else it will be positive
return result
def __truediv__(self, other):
'''
this method is called whenever we have a / b where a and b are BaseNum objects
:returns
BaseNum object that has the value of self divided by other in their base
'''
a = -self if self.signed else self
b = -other if other.signed else other
# a and b are the positive value of self, respectively other
result = self.__division_implementation(a, b)
#if they don't have the same sign, the division will be negatives
if self.signed != other.signed:
result = -result
#else it will be positive
return result
def __mod__(self, other):
'''
this method is called whenever we have a % b where a and b are BaseNum objects
:returns
BaseNum object that has the modulus value between self and other
'''
a = -self if self.signed else self
b = -other if other.signed else other
# a and b have the positive values of self, respectively other
result = self.__modulus_implementation(a, b)
#if they don't have the same sign, the modulus is negative
if self.signed != other.signed:
result = -result
#else it it positive
return result
def __neg__(self):
'''
returns the negated BaseNum of self
'''
value = self.value
base = self.base
#if it is positive, make it negative
if not self.signed:
value = '-' + value
# else make it positive
neg = BaseNum(value, base)
return (neg)
def __pos__(self):
'''
retuns the same BaseNum object x, when +x is called
'''
return self
def __eq__(self, other):
'''
tests if two BaseNum objects are equal
:returns
True, if their base, value and sign are the same
Fasle, otherwise
'''
a = self
b = other
if a.base != b.base:
raise BaseNumException('Error -- the two operands must have the same base')
if a.signed == b.signed and a.value == b.value:
return True
return False
def __lt__(self, other):
'''
tests if a < b, where a and b are BaseNum objects
:returns
True, if self < other
False, otherwise
'''
a = self
b = other
if a.base != b.base:
raise BaseNumException('Error -- the two operands must have the same base')
if a.signed and not b.signed:
return True
if not a.signed and b.signed:
return False
sign = a.signed
if a.value == b.value:
return False
if len(a.value) == len(b.value):
less_in_module = a.value < b.value
return self.__xor(less_in_module, sign)
less_length = len(a.value) < len(b.value)
return self.__xor(less_length, sign)
def __gt__(self, other):
'''
tests if a > b, where a,b are BaseNum objects
:returns
True, if a > b
False otherwise
'''
a = self
b = other
return not ((a < b) or (a == b))
def __ge__(self, other):
'''
tests if a >= b, where a,b are BaseNum objects
:returns
True, if a >= b
False otherwise
'''
a = self
b = other
return not(a < b)
def __le__(self, other):
'''
tests if a <= b, where a,b are BaseNum objects
:returns
True, if a <= b
False otherwise
'''
a = self
b = other
return not (a > b)
def __xor(self, a, b):
'''
returns the xor value of 2 boolean values
:returns
True if a != b
False if a == b
where a, b are from [True, False]
'''
if a == b:
return False
return True
def __addition_implementation(self, a, b):
'''
This implementation solves the addition between 2 positive BaseNum numbers
:args
a, b - positive BaseNum objects
:returns:
BaseObject that repersents the sum of a and b in their base
'''
if a.base != b.base:
raise BaseNumException('Error -- the two operands must have the same base')
s = []
n, m = len(a.value), len(b.value)
n-=1
m-=1
carry = 0
while (m > -1) and (n > -1):
x = a.digit(a[n])
y = a.digit(b[m])
s.insert(0, (x + y + carry) % a.base)
carry = (x+ y + carry) // a.base
n -= 1
m -= 1
while m > -1:
y = a.digit(b[m])
s.insert(0, (y + carry) % a.base)
carry = (y + carry) // a.base
m -= 1
while n > -1:
x = a.digit(a[n])
s.insert(0, (x + carry) % a.base)
carry = (x + carry) // a.base
n -= 1
if carry != 0:
s.insert(0, carry)
for i in range(len(s)):
if (s[i] >= 10):
s[i] = chr(s[i] - 10 + ord('a'))
else:
s[i] = str(s[i])
result = BaseNum(''.join(s), a.base)
return result
def __subtraction_implementation(self, a, b):
'''
This implementation solves the subtraction between 2 positive BaseNum numbers
:args
a, b - positive BaseNum objects
:return
BaseNum that represents the difference between a and b in their base
'''
if a.base != b.base:
raise BaseNumException('Error -- the two operands must have the same base')
invert_result = a < b
if invert_result:
a, b = b, a
values1 = [BaseNum.digit(v) for v in a.value]
values2 = [BaseNum.digit(v) for v in b.value]
n = len(values1)
while len(values2) != n:
values2.insert(0, 0)
n-=1
result = [v for v in values1]
while(n > -1):
if (values1[n] < values2[n]):
values1[n-1] -= 1
values1[n] += self.base
result[n] = values1[n] - values2[n]
n-=1
for i in range(len(result)):
if (result[i] >= 10):
result[i] = chr(result[i] - 10 + ord('a'))
else:
result[i] = str(result[i])
result = BaseNum(''.join(result), self.base)
if invert_result:
return - result
return result
def __division_implementation(self, a, b):
'''
This implementation solves the division between a positive number and a digit
:args
a, b - positive BaseNum objects
obs! - b must have a single digit value
:return
BaseNum that represents the division between a and b in their base
'''
if a.base != b.base:
raise BaseNumException('Error -- the two operands must have the same base')
if len(b.value) != 1:
raise BaseNumException("Error -- you can only divide with single digit numbers")
if b.value == '0':
raise BaseNumException('Error -- division by 0')
base = a.base
reminder = BaseNum('0', base)
quotent = BaseNum('0', base)
b = int(BaseNum.convert_to_base_10(b).value)
for v in a:
reminder = BaseNum(reminder.value + v, base)
aux = int(BaseNum.convert_to_base_10(reminder).value)
reminder = BaseNum(str(aux % b), 10)
reminder = BaseNum.convert_from_base_10_to(reminder, base)
aux2 = BaseNum(str(aux // b), 10)
aux2 = BaseNum.convert_from_base_10_to(aux2, 16)
quotent = BaseNum(quotent.value + aux2.value, base)
return quotent
def __multiplication_implementation(self, a, b):
'''
this method solves the multiplication between 2 BaseNum objects a and b
:args
a, b - BaseNum objects
:returns
BaseNuum object that represents the objects a and b multiplied in their base
'''
def multiplication_by_one_digit(a, b):
'''
this mehod solves the multiplication of a and b, BaseNum objects, b digit
:args
a, b - BaseNum objects, b must have a single digit value
:returns
BaseNum that represents a and b multiplied
'''
if len(b.value) != 1:
raise BaseNumException("Error -- you can only m with single digit numbers")
result = []
values = [self.digit(v) for v in a]
n = len(values) -1
b = int(BaseNum.convert_to_base_10(b).value)
carry = 0
base = a.base
while( n >= 0 ):
aux = carry + values[n]*b
result.insert(0, aux % base)
carry = aux // base
n-=1
result.insert(0, carry)
for i in range(len(result)):
if (result[i] >= 10):
result[i] = chr(result[i] - 10 + ord('a'))
else:
result[i] = str(result[i])
result = BaseNum(''.join(result), self.base)
return result
if a.base != b.base:
raise BaseNumException('Error -- the two operands must have the same base')
base = a.base
result = BaseNum('0', base)
# multiplies every digit of b with a using the multiplication_by_one_digit method and
# add the results together, being careful to add the specific zeros
n = len(b.value)-1
while n >=0:
nr_of_zeros = len(b.value) -1 -n
digit = BaseNum(b[n], base)
aux = multiplication_by_one_digit(a, digit)
for _ in range(nr_of_zeros):
aux = BaseNum(aux.value + '0', aux.base)
result = result + aux
n-=1
return result
def __modulus_implementation(self, a, b):
'''
This implementation solves the modulus between a positive number and a digit
:args
a, b - BaseNum objects
:return
BaseNum object representing the value of a % b in their base
'''
if a.base != b.base:
raise BaseNumException('Error -- the two operands must have the same base')
if len(b.value) != 1:
raise BaseNumException("Error -- you can only divide with single digit numbers")
if b.value == '0':
raise BaseNumException('Error -- division by 0')
base = a.base
reminder = BaseNum('0', base)
quotent = BaseNum('0', base)
b = int(BaseNum.convert_to_base_10(b).value)
for v in a:
reminder = BaseNum(reminder.value + v, base)
aux = int(BaseNum.convert_to_base_10(reminder).value)
reminder = BaseNum(str(aux % b), 10)
reminder = BaseNum.convert_from_base_10_to(reminder, base)
aux2 = BaseNum(str(aux // b), 10)
aux2 = BaseNum.convert_from_base_10_to(aux2, 16)
quotent = BaseNum(quotent.value + aux2.value, base)
#the same implementation as division, the difference being that we return the reminder
return reminder
@staticmethod
def convert(baseNum, destination_base):
'''
convert method that chooses what conversion method to call based on source base and destination base
:args
baseNum - BaseNum object
destination_base - integer representing the base in which we want to convert
:returns
BaseNum object representing the equivalent of baseNum in base destination_base
'''
if destination_base < 2 or destination_base > 16:
raise BaseNumException('Error -- a number can only be converted to a base between [1, 16]')
if destination_base == baseNum.base:
return baseNum
if destination_base == 10:
return BaseNum.convert_to_base_10(baseNum)
if destination_base in [2, 4, 8, 16] and baseNum.base in [2, 4, 8, 16]:
return BaseNum.convert_rapid_conversion(baseNum, destination_base)
if destination_base > baseNum.base:
return BaseNum.convert_substitution_method(baseNum, destination_base)
if destination_base < baseNum.base:
return BaseNum.convert_successive_divitions(baseNum, destination_base)
@staticmethod
def convert_rapid_conversion(baseNum, destination_base):
'''
conversion method that is used when converting between bases [2, 4, 8, 16]
:args
baseNum - BaseNum object that we want to convert
destination_base - integer value representing the base in which we want the result
:return
BaseNum object that represents the equivalent of baseNum in base destination_base
:raises
BaseNumException - if source_base or destination_base are not from [2, 6, 8, 16]
'''
to_base2 = {'0':'0000','1':'0001', '2':'0010', '3':'0011', '4':'0100', '5':'0101', '6':'0110',
'7':'0111','8':'1000','9':'1001','a':'1010','b':'1011','c':'1100','d':'1101',
'e':'1110','f':'1111'}
from_base2 ={'0001':'1','0101':'5','0000':'0','1101':'d','0111':'7','0100':'4','1001':'9',
'0110':'6','0010':'2','1100':'c','0011':'3','1110':'e','1000':'8','1111':'f',
'1011':'b','1010':'a'}
source_base = baseNum.base
if source_base not in [2, 4, 8, 16] or destination_base not in [2, 4, 8, 16]:
raise BaseNumException('both bases must be from [2, 4, 8, 16]')
p1 = 1
while 2 ** p1 != source_base and 2 ** p1 <= 16:
p1+=1
p2 = 1
while 2 ** p2 != destination_base and 2 ** p2 <=16:
p2 += 1
binary_rep = [to_base2[v][-p1:] for v in baseNum]
binary_rep = ''.join(binary_rep)
while len(binary_rep) % p2 != 0:
binary_rep = '0' + binary_rep
result = ''
i = 0
while i < len(binary_rep):
slice = binary_rep[i:i+p2]
while len(slice) < 4:
slice = '0' + slice
result += from_base2[slice]
i+=p2
result = BaseNum(result, destination_base)
if baseNum.signed:
return -result
return result
@staticmethod
def convert_substitution_method(baseNum, destination_base):
'''
conversion method that is used when source_base < destination_base
:args
baseNum - BaseNum object that we want to convert
destination_base - integer value representing the base in which we want the result
:return
BaseNum object that represents the equivalent of baseNum in base destination_base
:raises
BaseNumException - if source_base > destination_base
'''
result = BaseNum('0', destination_base)
source_base = baseNum.base
if source_base > destination_base:
raise BaseNumException('This method is used when source base < destination base')
if source_base >= 10:
converted_base = chr(source_base - 10 + ord('a'))
else:
converted_base = str(source_base)
multiplier = BaseNum(converted_base, destination_base)
k = BaseNum('1', destination_base)
n = len(baseNum.value) - 1
while n>=0:
aux = BaseNum(baseNum[n], destination_base)
result = result + aux * k
k = k * multiplier
n-=1
if baseNum.signed:
return - result
return result
@staticmethod
def convert_using_10_as_intermediare_base(baseNum, destination_base):
'''
conversion method that is used for all bases
:args
baseNum - BaseNum object that we want to convert
destination_base - integer value representing the base in which we want the result
:return
BaseNum object that represents the equivalent of baseNum in base destination_base
'''
intermediare = BaseNum.convert_to_base_10(baseNum)
return BaseNum.convert_from_base_10_to(intermediare, destination_base)
@staticmethod
def convert_to_base_10(baseNum):
'''
conversion method that is used when converting to base 10 from any base
:args
baseNum - BaseNum object that we want to convert to base 10
:return
BaseNum object that represents the equivalent of baseNum in base destination_base
'''
values = [BaseNum.digit(v) for v in baseNum]
n = len(values) -1
result = 0
k = 1
while n >= 0:
result += values[n] * k
k *= baseNum.base
n -= 1
result = BaseNum(str(result), 10)
if baseNum.signed:
result = - result
return result
@staticmethod
def convert_successive_divitions(baseNum, destination_base):
'''
conversion method that is used when source_base > destination_base
:args
baseNum - BaseNum object that we want to convert
destination_base - integer value representing the base in which we want the result
:return
BaseNum object that represents the equivalent of baseNum in base destination_base
:raises
BaseNumException if source_base < destination_base
'''
if baseNum.value == '0':
return BaseNum('0', destination_base)
signed = baseNum.signed
base = baseNum.base
value = destination_base
if base < destination_base:
raise BaseNumException('This method is used only if the source base > the destination base')
if (value >= 10):
value = chr(value - 10 + ord('a'))
else:
value = str(value)
a = BaseNum(baseNum.value, baseNum.base)
b = BaseNum(value, base)
result = []
remainder = 0
while a.value != '0':
remainder = BaseNum.digit((a % b).value)
a = a / b
result.insert(0, remainder)
for i in range(len(result)):
if (result[i] >= 10):
result[i] = chr(result[i] - 10 + ord('a'))
else:
result[i] = str(result[i])
result = BaseNum(''.join(result), destination_base)
if signed:
result = - result
return result
@staticmethod
def convert_from_base_10_to(baseNum, destination_base):
'''
conversion method that is used when converting from base 10 to any base
:args
baseNum - BaseNum object that we want to convert in base 10
destination_base - integer value representing the base in which we want the result
:return
BaseNum object that represents the equivalent of baseNum in base destination_base
'''
number = int(baseNum.value)
base = destination_base
if number == 0:
return BaseNum('0', destination_base)
result = []
reminder = 0
quotent = 0
while number != 0:
reminder = number % base
quotent = number // base
result.insert(0, reminder)
number = quotent
for i in range(len(result)):
if (result[i] >= 10):
result[i] = chr(result[i] - 10 + ord('a'))
else:
result[i] = str(result[i])
return BaseNum(''.join(result), destination_base)
|
b64c75bc84fe397f35e38079363c67f9376f1e58 | workherd/Python006-006 | /week07/c07_08.py | 526 | 3.515625 | 4 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021/2/13 10:34
# @Author : john
# @File : c07_08.py
# nonlocal 访问外部函数的局部变量
# 注意start的位置, return的作用域和函数内的作用域不同
def counter2(start=2):
def incr():
nonlocal start
start += 1
return start
return incr
c1 = counter2(5)
print(c1())
print(c1())
c2 = counter2(50)
print(c2())
print(c2())
print(c2())
print(c1())
print(c1())
print(c1())
print(c2())
print(c2())
|
34cec2557cce19ae82f0deedd764f3952b00715e | warrenwrate/python_scripts | /reduce.py | 753 | 3.90625 | 4 | import functools
# initializing list
lis = [ 4 , 3, 5, 6, 2 ]
# using reduce to compute sum of list
print ("The sum of the list elements is : ",end="")
print (functools.reduce(lambda a,b : a+b,lis))
# using reduce to compute maximum element from list
print ("The maximum element of the list is : ",end="")
print (functools.reduce(lambda a,b : a if a > b else b,lis))
print ("The minimum element of the list is : ",end="")
print (functools.reduce(lambda a,b : a if a < b else b,lis))
print ("count")
print (functools.reduce(lambda a,b: a+1,lis))
print(lis)
def f(x): return x % 3 == 0 or x % 5 == 0
fil = list(filter(f, range(2, 25)))
print(fil)
def cube(x): return x*x*x
map_cube = map(cube, range(1, 11))
ml = list(map_cube)
print(ml) |
2a58d5e6ee5239649181dead9bcabeaf4540367b | levindoneto/lanGen | /utils/LangModels.py | 2,542 | 4.09375 | 4 | ''' Function for creating n-grams.
@Parameters: List: sequence, Integer: n (type of the n-gram).
@Return: List: n-grams.
'''
def generateNGrams(sequence, n):
ngrams = []
for i in range(len(sequence)-n+1):
ngrams.append(sequence[i:i+n])
return ngrams
''' Function for counting how often each item occurs in a sequence.
@Parameters: Tuple: N-Grams, Integer: n (type of the n-gram).
@Return: Dictionary: token:frequency.
'''
def getNGramFrequencies(ngrams):
frequencies = {}
for token in ngrams:
if (token in frequencies):
newFrequency = str(int(frequencies[token]) + 1)
frequencies.update({token: newFrequency})
else: # Just in the first time a token is found
frequencies.update({token: '1'})
return frequencies
''' Function for getting probabilities of n-grams (word by the previous one).
@Parameters: Dict: Occurances.
@Return: Dictionary: Probabilities.
'''
def getNGramProbabilities(occurances):
probs = {}
for pred in occurances:
auxNext = {}
for nextW in occurances[pred]:
auxNext[nextW] = str(int(occurances[pred][nextW]) / len(occurances[pred]))
probs[pred] = auxNext
return probs
''' Function for adding an occurance of a gram considering the one which is
following it.
probabilities: {
word_0: {
next_0: occurance_0, ...
next_n: occurance_n
}, ...
word_n: {
next_0: occurance_0, ...
next_n: occurance_n
},
}
@Parameters: String: currentWord, nextWord
Dictionary: occurances.
@Return: Dictionary: new occurances.
'''
def addOccurance(currentWord, nextWord, occurances):
occurs = occurances
if (currentWord in occurs):
if (nextWord in occurs[currentWord]):
aux = int(occurs[currentWord][nextWord])
aux += 1
occurs[currentWord][nextWord] = str(aux)
else:
occurs[currentWord].update({nextWord : "1"})
else:
occurs[currentWord] = {nextWord : "1"}
return occurs
''' Function for getting occurances of n-grams (word by the previous one).
@Parameters: Tuple: N-Grams.
@Return: Dictionary: occurances.
'''
def getNGramOccurances(ngrams):
occurs = {}
currentWord = 0
nextWord = 1
for i in range(len(ngrams) - 1):
occurs = addOccurance(ngrams[currentWord], ngrams[nextWord], occurs)
currentWord += 1
nextWord += 1
return occurs
|
5adfa549b335a7ab18ac1eed1b0eb05cf3b970d2 | bmclay/python_notes | /lists_tuples.py | 3,219 | 4.6875 | 5 | """
Collections are an ordered or un-ordered group of elements.
lists are set using square brackets []
inside of the square brackets you can have a series of elements (some data type).
To define a list, create a variable and open up square brackets with some elements inside
Lists can contain values of different types, even other lists:
"""
x = [4, True, 'hi', [1, 2, 3], 'Adam']
print(x)
# To print the length of the list, use the len function
print(len(x))
# The len function can also be used to count the total number of characters in a string
y = 'whats up'
print(len(y))
# Append to the end of the list
x.append('hello')
print(x)
# Add elements to the end of the list with extend
x.extend([4, 5, 6, 7])
print(x)
# Remove the element at the end of the list using pop (in this case 7 is removed)
x.pop()
print(x)
# Print what it would be removing by using pop with the print function (in this case its 6)
print(x.pop())
# If you print x again at this stage, 6 is gone.
print(x)
# Each item in a list contains an index number
# Indexes are assigned from left to right starting with the number 0, 1, 2, 3, 4 etc...
y = [100, 'easy', False]
# Show what value is contained in a specified index position in a list:
print(y[1])
# Print what is in position '0' and pop it from the list
print(y.pop(0))
# Then if you print the list, 100 is removed because it was first aka index of 0.
print(y)
# Change the value of an element in a list by specifying the variable, the index number and its new value:
x[0] = 'NEW'
print(x)
# Tell python that variable y now equals the value of x
y = x
# When you store a list to a variable, the variable stores only a reference to the list not a copy of it.
# Lists are mutable which means they can be changed.
print(x, y)
# You can make python make a copy of the list instead of just a referance by specifying [:]
y = x[:]
print(y)
"""
Tuples are similar to lists but they are immutable. They cannot be changed once they are defined.
Tuples use round brackets instead of square brackets.
"""
a = (0, 85, 'bingo', 72, True, 'Jimmy')
print(a)
# You cant change the list. It's immutable
# Example of trying to change the value of index position 1. This results in an error
a[0] = 5
# Lists and definate loops are great together
# Python has no comprehension of plural words, below I defined the list friends and the iteration variable friend:
friends = ['Josh', 'Adam', 'Eric', 'Greeny', 'Wes']
for friend in friends :
print('Hello there: ', friend)
print('Done')
# List Methods
x = list()
type(x)
dir(x)
"""
Building a list from scratch
You can create an empty list and then through a series of append methods through the code you can build a list
Make an empty list
"""
stuff = list()
# Append to the list throughout the code
resteraunts = list()
resteraunts.append('Mama Rosas')
resteraunts.append('Pizza Joes')
resteraunts.append('Burger Hut')
resteraunts.append('Chop Shop')
resteraunts.append('Upper Crust')
# Make a definate loop for each item in the list and print it out
for resteraunt in resteraunts :
print(resteraunt)
print('All are Tasty')
|
c58ed18dccefd2a136729dd56473dcacae4b575a | evasu9582/python | /pawn.py | 268 | 3.671875 | 4 | def pawn(N,P):
cn=[]
if N:
for i in range(N,P+1):
cn.append(i)
else:
for j in range(N,P):
cn.append(j)
decision=max(cn)
return ('Block',decision*2) if decision%2==0 else ('White',decision*2)
print(pawn(0,8)) |
4a9677b6e10b1e7c7258a982d04bd6d27376350a | ttuttlej/Python-Asteroids-Game | /Asteroids - Mass Effect/Asteroids/images/Asteroids.py | 17,136 | 4.21875 | 4 | """
File: asteroids.py
Original Author: Br. Burton
Designed to be completed by others
This program implements the asteroids game.
"""
import arcade
import random
import math
from abc import ABC
from abc import abstractmethod
# These are Global constants to use throughout the game'
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BULLET_RADIUS = 30
BULLET_SPEED = 10
BULLET_LIFE = 60
SHIP_TURN_AMOUNT = 3
SHIP_THRUST_AMOUNT = 0.25
SHIP_RADIUS = 30
INVINCIBILITY_LIFE = 200
INITIAL_ROCK_COUNT = 5
BIG_ROCK_SPIN = 1
BIG_ROCK_SPEED = 1.5
BIG_ROCK_RADIUS = 15
MEDIUM_ROCK_SPIN = -2
MEDIUM_ROCK_RADIUS = 5
SMALL_ROCK_SPIN = 5
SMALL_ROCK_RADIUS = 2
LEVIATHAN_RADIUS = 70
LEVIATHAN_SPEED = .5
class Point():
"""
Class: Point
Purpose: Holds the coordinate values for the location of items on the screen
"""
def __init__(self):
self.x = 0
self.y = 0
class Velocity():
"""
Class: Velocity
Purpose: Holds the values for how fast moving objects will move in each direction
"""
def __init__(self):
self.dx = 0
self.dy = 0
class Flying_Object(ABC):
"""
Class: Flying_object
Purpose: Contains information relevant to ALL obejcts that move across the screen
"""
def __init__(self):
self.center = Point()
self.velocity = Velocity()
self.radius = 0
self.angle = 0
self.alive = True
def advance(self):
"""
Moves the target across the screen
"""
self.center.x = self.center.x + self.velocity.dx
self.center.y = self.center.y + self.velocity.dy
@abstractmethod # All objects must be drawn to the screen
def draw(self):
pass
def calculate_velocity(self, speed):
"""
Breaks RESULTANT velocity into components relative to its current angle of
direction and adds them to the objects velocity components
param: the RESULTATNT velocity of the object who's velocity components are being
calculated must be passed along with object
(please initialize contstant RESULTATNT velocities at the top)
"""
self.velocity.dx += math.cos(math.radians(self.angle)) * speed
self.velocity.dy += math.sin(math.radians(self.angle)) * speed
def wrap(self):
"""
Check each object to see if it has left the screen.
If it has, put it on the other side of the screen.
"""
if self.center.x > SCREEN_WIDTH:
self.center.x = 0
if self.center.y > SCREEN_HEIGHT:
self.center.y = 0
if self.center.x < 0:
self.center.x = SCREEN_WIDTH
if self.center.y < 0:
self.center.y = SCREEN_HEIGHT
class Ship(Flying_Object):
"""
Class: Ship
Purpose: Contains all information related to the ship including:
(Ship controls, drawing to screen)
"""
def __init__(self):
super().__init__()
self.invincibility_life = INVINCIBILITY_LIFE
self.invincible = False
self.radius = SHIP_RADIUS
self.ship_begin()
def ship_begin(self):
# Starts the ship at the center of the screen
self.center.x = SCREEN_WIDTH/2
self.center.y = SCREEN_HEIGHT/2
def throttle(self):
# Increases the velocity of the ship in the direction its facing
self.calculate_velocity(SHIP_THRUST_AMOUNT)
def apply_brake(self):
# Decreases velocity of the ship
self.calculate_velocity(-SHIP_THRUST_AMOUNT)
def turn_left(self):
# Turns the ship left at a certain angular velocity(SHIP_TURN_AMOUNT)
self.angle += SHIP_TURN_AMOUNT
def turn_right(self):
self.angle -= SHIP_TURN_AMOUNT
def draw(self):
# Load the image of the ship from the images folder
img = "images/NormandySR2flattened.png"
texture = arcade.load_texture(img)
width = 150
height = 100
alpha = 1 # For transparency, 1 means not transparent
x = self.center.x
y = self.center.y
angle = self.angle - 90 # Shift the unit cirlce 90 degrees
arcade.draw_texture_rectangle(x, y, width, height, texture, angle, alpha)
def draw_invincibility(self):
# Load the image of the ship from the images folder
self.invincibility_life -= 1
if self.invincibility_life == 0:
self.invincible = False
img = "images/normandy - teal.png"
texture = arcade.load_texture(img)
width = 150
height = 100
alpha = 1 # For transparency, 1 means not transparent
x = self.center.x
y = self.center.y
angle = self.angle - 90 # Shift the unit cirlce 90 degrees
arcade.draw_texture_rectangle(x, y, width, height, texture, angle, alpha)
class Bullet(Flying_Object):
"""
Class: Bullet
Purpose: Contains information relevant only to the bullets
"""
def __init__(self):
super().__init__()
self.frames_to_live = BULLET_LIFE
self.radius = BULLET_RADIUS
def fire(self, ship):
"""
Sets bullet location and velocity to the same location and velocity of the Ship
Param: Ship object
(must be passed from the game class; this is where the ship object is created)
"""
self.center.x = ship.center.x
self.center.y = ship.center.y
self.angle = ship.angle
self.velocity.dx = ship.velocity.dx
self.velocity.dy = ship.velocity.dy
self.calculate_velocity(BULLET_SPEED)
def draw(self):
img = "images/laserBlue01.png"
texture = arcade.load_texture(img)
width = texture.width
height = texture.height
alpha = 1 # For transparency, 1 means not transparent
x = self.center.x
y = self.center.y
angle = self.angle
arcade.draw_texture_rectangle(x, y, width, height, texture, angle, alpha)
def advance(self):
super().advance()
# Bullets only live for a select number of frames
# Once the bullet runs out of lives, kill it
self.frames_to_live -= 1
if self.frames_to_live == 0:
self.alive = False
class Asteroid(Flying_Object):
def __init__(self):
super().__init__()
self.rotation_angle = 0
self.asteroid_begin()
def asteroid_begin(self):
"""
Sets each asteroid to a random location.
This is done outside of the init function to allow for a future
implementation of restarting the game
"""
self.center.x = random.uniform(0, SCREEN_WIDTH)
self.center.y = random.uniform(0, SCREEN_HEIGHT)
self.angle = random.uniform(0, 360)
def spin(self):
# This rotates the asteroid at the specified angular velocity
self.rotation_angle += self.spin_amount
@abstractmethod # Every asteroid reacts differently when shot
def break_apart(self, list_of_asteriods):
pass
class Large_Asteroid(Asteroid):
def __init__(self):
super().__init__()
self.spin_amount = BIG_ROCK_SPIN
self.large_asteroid_begin()
self.radius = BIG_ROCK_RADIUS
def large_asteroid_begin(self):
"""
After location and angle have been chosen randomly, calculate
the velocity the objects will travel at.
"""
self.calculate_velocity(BIG_ROCK_SPEED)
def draw(self):
img = "images/asteroid-icon.png"
texture = arcade.load_texture(img)
width = 140
height = 140
alpha = 1 # For transparency, 1 means not transparent
x = self.center.x
y = self.center.y
self.spin()
angle = self.rotation_angle
arcade.draw_texture_rectangle(x, y, width, height, texture, angle, alpha)
def break_apart(self, list_of_asteroids):
"""
KIlls the Large ateroid and replaces it with 2 medium asteroids and a small one
"""
self.alive = False
medium_asteroid = Medium_Asteroid()
medium_asteroid.velocity.dy = self.velocity.dy + 2
list_of_asteroids.append(medium_asteroid)
medium_asteroid = Medium_Asteroid()
medium_asteroid.velocity.dy = self.velocity.dy - 2
list_of_asteroids.append(medium_asteroid)
small_asteroid = Small_Asteroid()
small_asteroid.velocity.dx = self.velocity.dx + 5
list_of_asteroids.append(small_asteroid)
class Medium_Asteroid(Asteroid):
def __init__(self):
super().__init__()
self.spin_amount = MEDIUM_ROCK_RADIUS
self.radius = MEDIUM_ROCK_RADIUS
def draw(self):
img = "images/asteroid-icon.png"
texture = arcade.load_texture(img)
width = 90
height = 90
alpha = 1 # For transparency, 1 means not transparent
x = self.center.x
y = self.center.y
self.spin()
angle = self.rotation_angle
arcade.draw_texture_rectangle(x, y, width, height, texture, angle, alpha)
def break_apart(self, list_of_asteroids):
self.alive = False
small_asteroid = Small_Asteroid()
small_asteroid.velocity.dy = self.velocity.dy + 1.5
small_asteroid.velocity.dx = self.velocity.dx + 1.5
list_of_asteroids.append(small_asteroid)
small_asteroid = Small_Asteroid()
small_asteroid.velocity.dy = self.velocity.dy - 1.5
small_asteroid.velocity.dx = self.velocity.dx - 1.5
list_of_asteroids.append(small_asteroid)
class Small_Asteroid(Asteroid):
def __init__(self):
super().__init__()
self.spin_amount = SMALL_ROCK_SPIN
self.radius = SMALL_ROCK_RADIUS
def draw(self):
img = "images/asteroid-icon.png"
texture = arcade.load_texture(img)
width = 65
height = 65
alpha = 1 # For transparency, 1 means not transparent
x = self.center.x
y = self.center.y
self.spin()
angle = self.rotation_angle
arcade.draw_texture_rectangle(x, y, width, height, texture, angle, alpha)
def break_apart(self, list_of_asteroids):
self.alive = False
class Leviathan(Flying_Object):
def __init__(self):
super().__init__()
self.radius = LEVIATHAN_RADIUS
self.angle = 0
self.center.x = SCREEN_WIDTH/2
self.center.y = SCREEN_HEIGHT + 500
self.velocity.dy = -LEVIATHAN_SPEED
def draw(self):
img = "images/Leviathan.png"
texture = arcade.load_texture(img)
width = 700
height = 700
alpha = 1 # For transparency, 1 means not transparent
x = self.center.x
y = self.center.y
angle = self.angle
arcade.draw_texture_rectangle(x, y, width, height, texture, angle, alpha)
class Game(arcade.Window):
"""
This class handles all the game callbacks and interaction
This class will then call the appropriate functions of
each of the above classes.
You are welcome to modify anything in this class.
"""
def __init__(self, width, height):
"""
Sets up the initial conditions of the game
:param width: Screen width
:param height: Screen height
"""
super().__init__(width, height)
arcade.set_background_color(arcade.color.SMOKY_BLACK)
self.set_up()
def set_up(self):
self.num_of_asteriods = 0
self.held_keys = set()
self.leviathan = Leviathan()
# TODO: declare anything here you need the game class to track
self.asteroids = []
for i in range(1,6):
asteroid = Large_Asteroid()
self.asteroids.append(asteroid)
self.bullets = []
self.ship = Ship()
self.gameOver = False
def background(self):
img = "images/Space.png"
texture = arcade.load_texture(img)
width = SCREEN_WIDTH
height = SCREEN_HEIGHT
alpha = 1 # For transparency, 1 means not transparent
x = SCREEN_WIDTH/2
y = SCREEN_HEIGHT/2
arcade.draw_texture_rectangle(x, y, width, height, texture, 0, alpha)
def on_draw(self):
"""
Called automatically by the arcade framework.
Handles the responsibility of drawing all elements.
"""
# clear the screen to begin drawing
arcade.start_render()
self.background()
self.leviathan.draw()
# TODO: draw each object
for asteroid in self.asteroids:
asteroid.draw()
for bullet in self.bullets:
bullet.draw()
# Draw the ship glowing when in invincibility mode
if self.ship.invincible == True:
self.ship.draw_invincibility()
else:
self.ship.draw()
if self.gameOver == True:
self.draw_game_over()
def draw_game_over(self):
text = "GAME OVER\nPress F1 to try again"
start_x = SCREEN_WIDTH / 2
start_y = SCREEN_HEIGHT / 2
arcade.draw_text(text, start_x = start_x, start_y = start_y, font_size=24, color=arcade.color.WHITE)
def update(self, delta_time):
"""
Update each object in the game.
:param delta_time: tells us how much time has actually elapsed
"""
self.check_keys()
self.check_collisions()
# TODO: Tell everything to advance or move forward one step in time
for asteroid in self.asteroids:
asteroid.advance()
asteroid.wrap()
for bullet in self.bullets:
bullet.advance()
bullet.wrap()
self.ship.advance()
self.ship.wrap()
self.leviathan.advance()
# TODO: Check for collisions
self.clean_up()
def clean_up(self):
for bullet in self.bullets:
if bullet.alive == False:
self.bullets.remove(bullet)
for asteroid in self.asteroids:
if asteroid.alive == False:
self.asteroids.remove(asteroid)
def check_collisions(self):
"""
Checks to see if contact has been made between bullets and asteroids
When in invincibility mode collisions have no affect
"""
leviathan_contact = self.ship.radius + self.leviathan.radius
if (abs(self.ship.center.x - self.leviathan.center.x) < leviathan_contact and
abs(self.ship.center.y - self.leviathan.center.y) < leviathan_contact):
if self.ship.invincible == False:
self.gameOver = True
for asteroid in self.asteroids:
ship_contact = self.ship.radius + asteroid.radius
if (abs(self.ship.center.x - asteroid.center.x) < ship_contact and
abs(self.ship.center.y - asteroid.center.y) < ship_contact):
pass
if self.ship.invincible == False:
self.gameOver = True
for bullet in self.bullets:
for asteroid in self.asteroids:
if bullet.alive and asteroid.alive:
bullet_contact = bullet.radius + asteroid.radius
if (abs(bullet.center.x - asteroid.center.x) < bullet_contact and
abs(bullet.center.y - asteroid.center.y) < bullet_contact):
bullet.alive = False
asteroid.break_apart(self.asteroids)
def check_keys(self):
"""
This function checks for keys that are being held down.
You will need to put your own method calls in here.
"""
if arcade.key.LEFT in self.held_keys:
self.ship.turn_left()
if arcade.key.RIGHT in self.held_keys:
self.ship.turn_right()
if arcade.key.UP in self.held_keys:
self.ship.throttle()
if arcade.key.DOWN in self.held_keys:
self.ship.apply_brake()
# Machine gun mode...
#if arcade.key.SPACE in self.held_keys:
# pass
def on_key_press(self, key: int, modifiers: int):
"""
Puts the current key in the set of keys that are being held.
You will need to add things here to handle firing the bullet.
"""
if self.ship.alive:
self.held_keys.add(key)
if key == arcade.key.SPACE:
# TODO: Fire the bullet here!
bullet = Bullet()
bullet.fire(self.ship)
self.bullets.append(bullet)
if key == arcade.key.LSHIFT:
self.ship.invincible = True
if key == arcade.key.F1:
# Restarts the game
self.set_up()
def on_key_release(self, key: int, modifiers: int):
"""
Removes the current key from the set of held keys.
"""
if key in self.held_keys:
self.held_keys.remove(key)
# Creates the game and starts it going
window = Game(SCREEN_WIDTH, SCREEN_HEIGHT)
arcade.run() |
c4d0c138d0e9dc05355c08e8d871b2931bf91885 | sachin16495/Question_Category_Classification | /question_classification_naive_bayes.py | 2,920 | 3.5 | 4 | import os
import string
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.naive_bayes import MultinomialNB
from sklearn.metrics import classification_report
from nltk.tokenize import sent_tokenize, word_tokenize
#Load Excel file from the current directory
ques_file=pd.read_excel('Questions.xlsx',sheet_name=0)
ques_file.head()
#Seprate Type and Question from the data frame
label=ques_file[u'Type']
question=ques_file[u'Question']
tr_ques, te_ques, tr_label, te_label= model_selection.train_test_split(question, label, test_size=0.25, random_state=0)
vocab={}
'''Traverse through questions make a vocabolary with bag of word store the tokeninze text and along
with there cooccurance.
'''
for qu in tr_ques:
list_word=[]
#Tokenize and and split the inappropiate space from the text
for clean_word in word_tokenize(str(qu).strip()):
#change the text into lower case so as to reduce the dimentation of the data
clean_word=clean_word.lower()
if(len(clean_word)>2):
if clean_word in vocab:
vocab[clean_word]+=1
else:
vocab[clean_word]=1
num_words = [0 for i in range(max(vocab.values())+1)]
freq = [i for i in range(max(vocab.values())+1)]
for key in vocab:
num_words[vocab[key]]+=1
cutoff_freq = 2
# For deciding cutoff frequency
num_words_above_cutoff = len(vocab)-sum(num_words[0:cutoff_freq])
#print("Number of words with frequency higher than cutoff frequency({}) :".format(cutoff_freq),num_words_above_cutoff)
features=[]
for key in vocab:
if vocab[key]>=cutoff_freq:
features.append(key)
#Initilize zero matrix for store tokenize text matrix
train_quest_data=np.zeros((len(tr_ques),len(features)))
inn=0
#print("QQ Word")
for sent in tr_ques:
word_ls=[(word.strip()).lower() for word in sent.split()]
#print(word_ls)
for q_word in word_ls:
if q_word in features:
#print(q_word)
train_quest_data[inn][features.index(q_word)]+=1
inn=inn+1
tinn=0
test_quest_data=np.zeros((len(te_ques),len(features)))
for test_wo in te_ques:
word_ls=[word.strip().lower() for word in test_wo.split()]
for word in word_ls:
if word in features:
test_quest_data[tinn][features.index(word)]+=1
tinn=tinn+1
#Instance Multinomial Naive Bias which calulate the probability of multiple classes
clf=MultinomialNB()
clf.fit(train_quest_data,tr_label)
#test_predi=clf.predict(test_quest_data)
teind=0
#print("Test Result")
for que in te_ques:
teind=teind+1
#Argument for the Training Data
argumentList = sys.argv
test_quest=argumentList[1]
arg_test_quest_data=np.zeros((1,len(features)))
test_word=[t_word.strip().lower() for t_word in test_quest.split()]
for tw in test_word:
if tw in features:
arg_test_quest_data[0][features.index(tw)]+=1
test_predi=clf.predict(arg_test_quest_data)
print("\033[1;32;40m Classification Class ")
print("\033[1;31;43m"+test_predi[0] + "\033[1;32;40m \033[1;32;40m")
|
55c1abc266ffcefe3accc27a38a3bbbc5e76e266 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2490/60624/266108.py | 221 | 3.734375 | 4 | def func8():
nums1 = list(map(int, input()[1:-1].split(",")))
nums2 = list(map(int, input()[1:-1].split(",")))
temp = [val for val in nums1 if val in nums2]
print(sorted(set(temp)))
return
func8() |
c79b12b96ce84f0e742231bc7837e1fab693ebd6 | priyamehta2772/cracking-the-coding-interview | /Unit 2_ Linked List/2.2_Kth_from_last.py | 1,226 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 9 18:42:03 2019
2.2 Return Kth from last
@author: PriyaMehta
"""
class LinkedListNode:
def __init__(self, val, link):
self.value = val
self.link = link
class LinkedList:
def __init__(self, h):
self.head = h
def print_list(self):
print("\nList: ", end="")
i = self.head
while i is not None:
print(i.value, end=" ")
i = i.link
print()
def get_Kth_from_last(self, k) -> LinkedListNode:
slow = fast = self.head
while k:
if fast is not None:
fast = fast.link
k -= 1
else:
return None # returns None if k is greater than length of linked list
while fast is not None:
slow = slow.link
fast = fast.link
return slow
#Driver code
twelve = LinkedListNode(12, None)
ten = LinkedListNode(10, twelve)
nine = LinkedListNode(9, ten)
five = LinkedListNode(5, nine)
one = LinkedListNode(1, five)
ll = LinkedList(one)
ll.print_list()
res = ll.get_Kth_from_last(6)
if res is None:
print("Value of K is invalid")
else:
print(res.value)
|
3a981164be19b9f03018a6e2725366fa68181387 | anfernee84/Learning | /python/for-while.py | 173 | 3.625 | 4 | i = 1000
while i > 100:
print(i)
i /= 2
for j in 'hello world':
if j == 'a':
break
print(j * 2, end = '' )
else:
print('There`s no letter "a" ') |
4e7e2d4c7c9a03189893bca6f2fb65f60a384f75 | Nchekwube1/pong-game-py | /pong.py | 1,324 | 3.640625 | 4 | import turtle
wn = turtle.Screen()
wn.title("Pong game by @FrancisUnekwe")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
paddle_a = turtle.Turtle()
paddle_a.speed(0)
paddle_a.shape("square")
paddle_a.color("lightblue")
paddle_a.shapesize(stretch_wid=5, stretch_len=1)
paddle_a.penup()
paddle_a.goto(-350,0)
paddle_b = turtle.Turtle()
paddle_b.speed(0)
paddle_b.shape("square")
paddle_b.color("lightblue")
paddle_b.shapesize(stretch_wid=5, stretch_len=1)
paddle_b.penup()
paddle_b.goto(350,0)
ball = turtle.Turtle()
ball.speed(0)
ball.shape("circle")
ball.color("lightblue")
ball.penup()
ball.goto(0,0)
ball.dx=.1
ball.dy=.1
def pad_a_up():
y=paddle_a.ycor()
y+=20
paddle_a.sety(y)
def pad_a_dw():
y=paddle_a.ycor()
y-=20
paddle_a.sety(y)
def pad_b_up():
y=paddle_b.ycor()
y+=20
paddle_b.sety(y)
def pad_b_dw():
y=paddle_b.ycor()
y-=20
paddle_b.sety(y)
wn.listen()
wn.onkeypress(pad_a_up,"w")
wn.onkeypress(pad_a_dw,"x")
wn.onkeypress(pad_b_up,"Up")
wn.onkeypress(pad_b_dw,"Down")
while True:
wn.update()
ball.setx(ball.xcor() + ball.dx )
ball.sety(ball.ycor() + ball.dy )
if ball.ycor() > 290:
ball.sety(290)
ball.dy*=-1
if ball.ycor() < -290:
ball.sety(-290)
ball.dy*=-1 |
96dc3231e53d5a24a1a9eb504c1a94afbcc070a0 | MarcinSzyc/EDX_Introduction-to-Computer-Science- | /polysum.py | 235 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 3 14:42:14 2018
@author: Marcin
"""
import math
def polysum(n,s):
area = (0.25*n*(s*s))/(math.tan(math.pi/n))
perim = n*s
return round((area + math.pow(perim,2)),4) |
e6fcac86e6cfbc1b845f027feb6e950190ffde76 | sidmen/python | /basics_and_misc/calendar_text.py | 240 | 4.03125 | 4 | import calendar
year = input('Year: ')
month = input('Month (num): ')
start_day = calendar.TextCalendar(calendar.SUNDAY)
# cal = calendar.month(int(year), int(month))
cal = start_day.formatmonth(int(year), int(month))
print(cal)
|
e7deb6b66b482c79957988709fb4d80fd9a0aec5 | RoyalTux/Tic_Tac_Toe | /tic_tac_toe.py | 4,492 | 4.1875 | 4 | X = "X"
O = "O"
EMPTY = " "
TIE = "draw"
NUM_SQUARES = 10
#выводим название игры в начале
def game_name():
print("\n\t\t\tThe game - Tic Tac Toe")
#функция для задания вопроса о первом ходе
def who_first(question):
answer = None
while answer not in ("y", "n"):
answer = input(question).lower()
return answer
#выбираем кто первый будет ходить
def pieces():
go_first = who_first("Do you want be first? (y/n): ")
if go_first == "y":
print("\nYou'll play as X!")
human = X
computer = O
else:
print("\nComputer's first turn!")
computer = X
human = O
return computer, human
#вводим одно из чисел (1-9) для выбора ячейки
def ask_number(question, low, high):
answer = None
while answer not in range(low, high):
answer = int(input(question))
return answer
#делаем игровое поле
def new_board():
board = []
for square in range(NUM_SQUARES):
board.append(EMPTY)
return board
#рисуем поле в консоли
def display_board(board):
print("\n\t", board[7], "|", board[8], "|", board[9])
print("\t", "---------")
print("\t", board[4], "|", board[5], "|", board[6])
print("\t", "---------")
print("\t", board[1], "|", board[2], "|", board[3], "\n")
#делаем список доступных ходов
def legal_moves(board):
moves = []
for square in range(NUM_SQUARES):
if board[square] == EMPTY:
moves.append(square)
return moves
#вычисляем победителя
def winner(board):
WAYS_TO_WIN = ((1, 2, 3),
(4, 5, 6),
(7, 8, 9),
(3, 6, 9),
(1, 4, 7),
(2, 5, 8),
(1, 5, 9),
(3, 5, 7))
for row in WAYS_TO_WIN:
if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
winner = board[row[0]]
return winner
if EMPTY not in board:
return TIE
return None
#ход игрока
def human_move(board, human):
legal = legal_moves(board)
move = None
while move not in legal:
move = ask_number("Your turn! Shoose one of this fields(1 - 9):", 1, NUM_SQUARES)
if move not in legal:
print("\nError! This field isn't empty!\n")
return move
#ход компьютера
def computer_move(board, computer, human):
# делаем копию
board = board[:]
# лучшие ходы
BEST_MOVES = (5, 1, 3, 7, 9, 2, 4, 6, 8)
# если пк выигрывает
for move in legal_moves(board):
board[move] = computer
if winner(board) == computer:
print(move)
return move
board[move] = EMPTY
# если игрок выигрывает то блокируем ход
for move in legal_moves(board):
board[move] = human
if winner(board) == human:
print(move)
return move
board[move] = EMPTY
# если ничья то выбираем квадрат из лучших
for move in BEST_MOVES:
if move in legal_moves(board):
print(move)
return move
#переключаем ходы с Х на О и наоборот
def next_turn(turn):
if turn == X:
return O
else:
return X
#выводим в консоль инфу о том кто победил
def congrat_winner(the_winner, computer, human):
if the_winner != TIE:
print(the_winner, "Winner!\n")
else:
print("Draw\n")
if the_winner == computer:
print("You Lose! Game over!")
elif the_winner == human:
print("You Won! Congratulations!\n")
elif the_winner == TIE:
print("It's a Draw...")
#основная функция
def main():
game_name()
computer, human = pieces()
turn = X
board = new_board()
display_board(board)
while not winner(board):
if turn == human:
move = human_move(board, human)
board[move] = human
else:
move = computer_move(board, computer, human)
board[move] = computer
display_board(board)
turn = next_turn(turn)
the_winner = winner(board)
congrat_winner(the_winner, computer, human)
main()
|
d24abba1f19ba86b8ac121305deb505c4e21c60c | mikej803/digitalcrafts-2021 | /python/homework/lets-speak.py | 574 | 3.78125 | 4 |
# A = "4", E = "3", "G" = "6", "I" = "1", "O" = "0", "S" = "5", "T" = "7"
# userinput = Whats up
# output = Wh475 up
userInput = input("Type your sentence? ")
output = ""
for char in userInput:
if char == "a":
output += "4"
elif char == "e":
output += "3"
elif char == "g":
output += "6"
elif char == "i":
output += "1"
elif char == "o":
output += "0"
elif char == "s":
output += "5"
elif char == "t":
output += "7"
else:
output += char
print(output)
|
24acdcb080bfaa6fb17c34b08debfe1154e27039 | syudaev/lesson01 | /lesson01_task02.py | 398 | 4.0625 | 4 | # перевод числа секунд в часы, минуты, секунды
# формат вывода - чч:мм:сс
number_seconds = int(input("Введите количество секунд:"))
my_hours = number_seconds // 3600
my_minutes = (number_seconds - my_hours * 3600) // 60
my_seconds = number_seconds % 60
print("%02d:%02d:%02d" % (my_hours, my_minutes, my_seconds))
|
4f2fccbe0ae1cc04750fa406d3594584c1ecf612 | snimrod/RepoAnalyzer | /outputStats.py | 5,297 | 3.640625 | 4 | import csv
from engineer import Engineer
def all_same_char(s):
n = len(s)
for i in range(1, n):
if s[i] != s[0]:
return False
return True
def all_qe_marks(s):
n = len(s)
for i in range(1, n):
if s[i] != '?' and s[i] != '!':
return False
return True
def one_word_question(txt, words):
if txt.startswith('why') or txt.startswith('what') or txt.startswith('where'):
if len(words) == 1:
return True
elif len(words) == 2:
return all_qe_marks(words[1])
else:
return False
else:
return False
def customized_pos(txt):
if txt.startswith('right'):
return True
if ('because' in txt) and not('receiving this because you authored' in txt):
return True
def customized_neg(txt):
words = txt.split()
if ('don\'t do' in txt) and not('please don\'t do' in txt) and not('we don\'t do' in txt)\
and not('i don\'t do' in txt):
return True
if ('don\'t write' in txt) and not('please don\'t write' in txt) and not('we don\'t write' in txt)\
and not('i don\'t do' in txt):
return True
if all_same_char(txt):
return True
#if (len(txt) < 10) and txt.endswith('?'):
if one_word_question(txt, words):
return True
if txt.startswith('don\'t') and not(txt.startswith('don\'t you')) and not(txt.startswith('don\'t we')):
return True
if txt.startswith('do not'):
return True
if txt.startswith('any good reason'):
return True
if txt.startswith('I don\'t understand why you'):
return True
if txt.startswith('what is this ?') or txt.startswith('what is this?'):
return True
return False
def analyze_csv(f):
newf = 'analysis_for_'+ f
af = open(newf, "w")
user_to_check = 'jgunthorpe'
user_fname = "{u}_comments.txt".format(u=user_to_check)
userf = open(user_fname, "w")
with open(f, newline='') as csvfile:
positives = ['tnx', 'thank', '10x', 'right?', 'right ?', 'imo', 'imho', 'i think', 'maybe',
'consider', 'you are right', 'you\'re right', ' correct ', ':)', ';)', 'nice catch', 'afaik',
'afaiu', 'can you', '(;', '(:', '):', ':(', ':-)', ';-)', ':-(', '(-:', '(-;', 'great job',
'well done', 'amazing job', 'nicely done', 'it\'s a good idea', 'it is a good idea',
'it is recommended to', 'it\'s recommended to', 'I might be mistaken here', 'my mistake',
'i agree', 'my bad', 'this is great', 'looks good']
# cheap poitives: 'pls', 'plz', 'please'
negatives = ['ugly', 'stupid', 'very bad', 'you shouldn\'t', '.don\'t', ',don\'t', '.do not', ',do not', '??',
'???', '. don\'t', ', don\'t', '. do not', ', do not', 'readable']
fieldnames = ['line', 'user', 'body']
reader = csv.DictReader(csvfile, fieldnames=fieldnames)
engs = dict()
for row in reader:
user = row['user']
body = row['body'].lower()
if user_to_check in user and "bot:retest" not in body:
userf.write(body + '\n')
if ('jenkins' in user) or ('github' in user) or ('mlx3im' in user):
continue
# Create user if new or increment lines if known
if user in engs:
engs[user].inc_comments()
else:
engs[user] = Engineer(user)
eng = engs[user]
# check pos words
for pos in positives:
if pos in body:
eng.pos_found(body)
if customized_pos(body):
eng.pos_found(body)
# check neg words
for neg in negatives:
if neg in body:
eng.neg_found(body)
if customized_neg(body):
eng.neg_found(body)
i = 0
for u, e in engs.items():
e.dump(af)
header = "\nHighest negative ratio"
print(header)
af.write("{s}\n".format(s=header))
i = 1
neg_l = sorted(engs, key=lambda name: engs[name].neg_rate())
neg_l.reverse()
for key in neg_l:
if engs[key].comments_cnt() > 50:
txt = "{id}) {u}: {n:.2f} ({nc}/{l})".format(id=i, u=key, n=100*engs[key].neg_rate(),
nc=engs[key].neg_cnt(), l=engs[key].comments)
print(txt)
af.write("{s}\n".format(s=txt))
i += 1
header = "\nHighest positive ratio"
print(header)
af.write("{s}\n".format(s=header))
i = 1
pos_l = sorted(engs, key=lambda name: engs[name].pos_rate())
pos_l.reverse()
for key in pos_l:
if engs[key].comments_cnt() > 50:
txt = "{id}) {u}: {n:.2f} ({p}/{l})".format(id=i, u=key, n=100 * engs[key].pos_rate(),
p=engs[key].pos_cnt(), l=engs[key].comments)
print(txt)
af.write("{s}\n".format(s=txt))
i += 1
af.close()
userf.close()
return engs
|
2726d03db151046c1091b93d14a5593c2d368e52 | vrillusions/python-snippets | /ip2int/ip2int_py3.py | 963 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Asks for an IPv4 address and convert to integer.
In Python v3.3 the ipaddress module was added so this is much simpler
"""
import sys
import ipaddress
__version__ = '0.1.0-dev'
def main(argv=None):
"""The main function.
:param list argv: List of arguments passed to command line. Default is None,
which then will translate to having it set to sys.argv.
:return: Optionally returns a numeric exit code. If not given then will
default to 0.
:rtype: int
"""
if argv is None:
argv = sys.argv
if argv[1]:
ip_address = argv[1]
else:
ip_address = input("Enter an ipv4 dotted quad or decimal: ")
if ip_address.isdigit():
# Received a decimal, convert to ip
print(str(ipaddress.ip_address(int(ip_address))))
else:
print(int(ipaddress.ip_address(ip_address)))
if __name__ == "__main__":
sys.exit(main())
|
27b96f58a6ea04996ba1a63ab7ca886cf0a2dbec | gill-chen/Code-Exercises | /Code Exercises/Calculating total salary.py | 350 | 3.890625 | 4 | def computepay(h,r):
h = float(h)
r = float(r)
if h > 40:
overtime = h -40
overpay = overtime * 1.5 * r
grosspay = overpay + (40 * r)
else
grosspay = h * r
return grosspay
hrs = raw_input("Enter Hours:")
rate = raw_input("Enter rate:")
p = computepay(hrs,rate)
print "Pay",p
|
c9de209f7acddd5edece8f913740a3fc21769b7e | tasawar-hussain/fyyur | /utils.py | 454 | 4.09375 | 4 | import re
def is_valid_phone(number):
""" Validate phone numbers like:
1234567890 - no space
123.456.7890 - dot separator
123-456-7890 - dash separator
123 456 7890 - space separator
Patterns:
000 = [0-9]{3}
0000 = [0-9]{4}
-. = ?[-. ]
Note: (? = optional) - Learn more: https://regex101.com/
"""
regex = re.compile('^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$')
return regex.match(number)
|
5bc5cb7726ed9eec5db57fe14068323a9ad1b5d9 | mattl1598/Project-Mochachino | /Python files/tkinter learn.py | 2,378 | 3.5 | 4 | #-------------------------------------------------------------------------------
# Name: module2
# Purpose:
#
# Author: matthewl9
#
# Created: 06/02/2018
# Copyright: (c) matthewl9 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
from tkinter import *
def submit():
print("Username",username.get())
print("Firstname",firstname.get())
print("Lastname",surname.get())
clear()
def clear():
username.delete(0,END)
firstname.delete(0,END)
surname.delete(0,END)
username.focus_set()
def WriteToFile():
file = open("names2.txt","w")
#for count in range (5):
#name = str(input("name"))
file.write(username.get())
file.write("\n")
file.write(firstname.get())
file.write("\n")
file.write(surname.get())
#if count < 4:
#file.write("\n")
file.close
clear()
#window creation
root = Tk()
root.geometry("270x300")
root.title("Student Details")
root.resizable(False, False)
root.configure(background = "Light Blue")
#form design
frame_heading = Frame(root)
frame_heading.grid(row=0,column=0,columnspan=2,padx=30,pady=5)
frame_entry = Frame(root)
frame_entry.grid(row=1,column=0,columnspan=2,padx=25,pady=10)
#place header
Label(frame_heading,text="Student Details Form",font=('Arial',16))\
.grid(row=0,column=0,padx=0,pady=5)
#place Labels
Label(frame_entry,text = "Username: ")\
.grid(row=0, column=0,padx=10,pady=5)
Label(frame_entry,text = "Firstname: ")\
.grid(row=1, column=0,padx=10,pady=10)
Label(frame_entry,text = "Surname: ")\
.grid(row=2, column=0,padx=10,pady=10)
#place text entry
username = Entry(frame_entry,width=15,bg="White")
username.grid(row = 0, column = 1, padx = 5,pady = 5)
firstname = Entry(frame_entry,width=15,bg="White")
firstname.grid(row = 1, column = 1, padx = 5,pady = 5)
surname = Entry(frame_entry,width=15,bg="White")
surname.grid(row = 2, column = 1, padx = 5,pady = 5)
#place buttons (this is jack and the beanstalk!)
submit_button = Button(root,text="submit",width = 7, command = submit)
submit_button.grid(row=2,column=0, padx=0,pady=5)
clear_button = Button(root,text="clear",width = 7, command = clear)
clear_button.grid(row=2,column=1, padx=0,pady=5)
write_button = Button(root,text="write",width = 7, command = WriteToFile)
write_button.grid(row=3,column=0, padx=5,pady=5)
def main():
root.mainloop()
print()
main()
|
74e8d703b4e1e1364484fa490fe7c8645ab016c9 | ShawDa/Coding | /coding-interviews/25复杂链表的复制.py | 1,317 | 3.734375 | 4 | # -*- coding:utf-8 -*-
__author__ = 'ShawDa'
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# 返回 RandomListNode
def Clone(self, pHead):
# write code here
if pHead == None:
return None
res = RandomListNode(pHead.label)
res.random = pHead.random
res.next = self.Clone(pHead.next)
return res
def Clone1(self, pHead):
# write code here
if pHead == None:
return None
head = pHead
while head:
tmp = head.next
head.next = RandomListNode(head.label)
head.next.next = tmp
head = tmp
head = pHead
while head:
copy_node = head.next
next_head = copy_node.next
if head.random:
copy_node.random = head.random.next
head = next_head
head = pHead
res = pHead.next
while head:
copy_node = head.next
next_head = copy_node.next
head.next = next_head
if next_head:
copy_node.next = next_head.next
else:
copy_node.next = None
head = next_head
return res
|
64f7238a8133358a78417b03204ad0ba98f272a5 | jinweijia/CodeSamples | /OtherCoding/fortuneOrRuin.py | 3,251 | 4.09375 | 4 | """Question:
Johnny is a gambler, and he really likes to play for high stakes in casinos. Recently,
his favorite casino is advertising a new betting game, where one can possibly win a fortune! (What
they are not advertising is that you can also lose everything.) The rules are the following: the
player bets a certain amount of money in each round of the game. If the player wins in this round,
he wins back his bet and on top of this, another half of the size of the bet. However if the player
loses, he regains (only) two thirds of his bet. To resolve a single round, a very complicated
procedure is used, involving roulette, card dealing, and dice rolls. However, one thing can be
stated for sure: in each round, the player has exactly 50% chance of winning and 50% chance of
losing.
Johnny is extremely dedicated to his cause, so once he starts playing, he will never stop as long as
he is allowed to continue, and he will always bet his entire stake in the next round. However, the
casino has imposed some restrictions. First, there is a minimal size of the bet. Then, there is a
luck detection system: if the player ends a round (after winning) with more than a certain amount of
cash, he is considered 'too lucky' and prohibited from continuing to play the game. Given the
starting amount of cash Johnny has, the minimal size of the bet, and the cap on winnings imposed by
the casino, determine which of the two scenarios is more probable: player's ruin (dropping below the
minimum bet size), or player's fortune (exceeding the cap imposed by the casino). Or maybe they are
equally probable? """
# First solution, not optimal, recurses down the tree of probabilities to calculate probability of winning.
class FortuneOrRuin:
def __init__(self, c, l, u):
self.cash = c
self.lower = l
self.upper = u
self.seenprobs = {}
self.scales = {}
self.p = 0
def findp(self, cash, depth):
# print 'findp: %.2f, %d' % (cash, depth)
if cash < self.lower:
return 0.0
elif cash > self.upper:
return 1.0
if cash in self.seenprobs:
if self.seenprobs[cash] >= 0.0:
return self.seenprobs[cash]
else:
self.scales[cash] -= 2**-depth
return 0
else:
self.seenprobs[cash] = -1.0
self.scales[cash] = 1.0
self.seenprobs[cash] = (0.5*self.findp(1.5*cash, depth+1) + 0.5*self.findp(2*cash/3, depth+1)) * 1/self.scales[cash]
# print 'findp: %.2f, %d -> %.4f' % (cash, depth, self.seenprobs[cash])
return self.seenprobs[cash]
def printresult(self):
p = self.findp(self.cash, 0)
if p == 1-p:
print 'A fair game'
elif 2*p > 1:
print 'Player fortune'
else:
print 'Player ruin'
# game = FortuneOrRuin(8.0, 1.0, 10000.0)
# game.printresult()
# print game.seenprobs
# print game.scales
import math
# Optimal solution
def findOutcome(cash, upper, lower):
lcount = math.ceil(math.log(lower / cash) / math.log (2.0/3))
ucount = math.ceil(math.log(upper / cash) / math.log (3.0/2))
if lcount == ucount:
print 'A fair game'
elif lcount > ucount:
print 'Player fortune'
else:
print 'Player ruin'
for _ in range(input()):
cash, lower, upper = [float(x) for x in raw_input().split()]
# game = FortuneOrRuin(cash, lower, upper)
# game.printresult()
findOutcome(cash, upper, lower) |
c0c85e0ef0aeeaa8578d74ecfd84b8a6cebf800f | changediyasunny/Challenges | /leetcode_2018/981_time_based_key_value.py | 2,332 | 3.953125 | 4 | """
981. Time Based Key-Value Store
Create a timebased key-value store class TimeMap, that supports two operations.
1. set(string key, string value, int timestamp)
Stores the key and value, along with the given timestamp.
2. get(string key, int timestamp)
Returns a value such that set(key, value, timestamp_prev) was called previously,
with timestamp_prev <= timestamp. If there are multiple such values, it returns
the one with the largest timestamp_prev. If there are no values, it returns the empty string ("").
Input:
inputs = ["TimeMap","set","get","get","set","get","get"],
inputs = [[],["foo","bar",1],["foo",1],["foo",3],["foo","bar2",4],["foo",4],["foo",5]]
Output: [null,null,"bar","bar",null,"bar2","bar2"]
Explanation:
TimeMap kv;
kv.set("foo", "bar", 1); // store the key "foo" and value "bar" along with timestamp = 1
kv.get("foo", 1); // output "bar"
kv.get("foo", 3); // output "bar" since there is no value corresponding to foo at
timestamp 3 and timestamp 2, then the only value is at timestamp 1 ie "bar"
kv.set("foo", "bar2", 4);
kv.get("foo", 4); // output "bar2"
kv.get("foo", 5); //output "bar2"
"""
class TimeMap(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.hashmap = collections.defaultdict(list)
def set(self, key, value, timestamp):
"""
:type key: str
:type value: str
:type timestamp: int
:rtype: None
"""
self.hashmap[key].append((timestamp, value))
def get(self, key, timestamp):
"""
:type key: str
:type timestamp: int
:rtype: str
"""
if key not in self.hashmap:
return ""
lists = self.hashmap[key]
left, right = 0, len(lists)-1
if timestamp >= lists[right][0]:
return lists[right][1]
while left <= right:
mid = (left + right)//2
if lists[mid][0] == timestamp:
return lists[mid][1]
if timestamp <= lists[mid][0]:
right = mid - 1
else:
left = mid + 1
return lists[right][1] if right >=0 else ""
# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)
|
48c5fcb15ed1e88e930cbf5638b257f36d40bef8 | nickedes/Areeba | /RSA/encrypt.py | 1,756 | 3.8125 | 4 | from random import randrange
def is_prime(num):
if num == 2:
return True
if num < 2 or num % 2 == 0:
return False
for n in xrange(3, int(num ** 0.5) + 2, 2):
if num % n == 0:
return False
return True
def egcd(a, b):
"To find gcd of two numbers."
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def invmod(e, m):
g, x, y = egcd(e, m)
if g != 1:
return None
else:
return x % m
def public_private_key(p, q):
"""
Generates public and private for encryption and decryption
Public key : (e,n)
Private key : (d,n)
"""
n = p * q
m = (p - 1) * (q - 1)
gcd = 0
while gcd != 1:
e = randrange(1, m)
gcd, _, _ = egcd(e, m)
d = invmod(e, m)
return ((e, n), (d, n))
def encrypt(key, msg):
k, n = key
cipher = []
for c in msg:
cipher.append(pow(ord(c), k, n))
return cipher
def decrypt(key, msg):
k, n = key
plain = []
for c in msg:
plain.append(chr(pow(c, k, n)))
return ''.join(plain)
if __name__ == '__main__':
p = int(raw_input('Enter 1st Prime no. '))
q = int(raw_input('Enter 2nd Prime no. '))
if is_prime(p) and is_prime(q):
public, private = public_private_key(p, q)
print "Public key: ", public
print "Private key: ", private
message = raw_input("Enter message: ")
ciphertext = encrypt(public, message)
print("Encrypted:", ciphertext)
print("decrypted:", decrypt(private, ciphertext))
elif p == q:
print("primes no.s should be distinct")
else:
print("Entered No.s are not prime")
|
9b6bd3a6e789e2621db65bbc1b99ca3d2ec47c20 | alex75042/les6 | /les6_job3.py | 2,093 | 3.890625 | 4 | #3. Реализовать базовый класс Worker (работник).
#● определить атрибуты: name, surname, position (должность),
# income (доход);
#● последний атрибут должен быть защищённым
# и ссылаться на словарь, содержащий
#элементы: оклад и премия, например,
# {"wage": wage, "bonus": bonus};
#● создать класс Position (должность) на базе класса Worker;
#● в классе Position реализовать методы получения
# полного имени сотрудника
#(get_full_name) и дохода с учётом премии (get_total_income);
#● проверить работу примера на реальных данных:
# создать экземпляры класса Position, передать данные,
# проверить значения атрибутов, вызвать методы экземпляров.
class Worker():
def work_plan(self, name, surname, position, __income__):
self.name = name
self.surname = surname
self.position = position
self.income = __income__
print(name, surname, position, __income__)
class Position(Worker):
def get_full_name(self):
full_name = []
full_name.append(name)
full_name.append(surname)
self.full_name = full_name
return self.full_name
def get_total_income(self):
total_income = int(income['wage']) + int(income['bonus'])
self.total_income = total_income
return self.total_income
name = str(input('Имя'))
surname = str(input('Фамилия'))
position = str(input('Должность'))
income = {}
income['wage'] = str(input('зарплата'))
income['bonus'] = str(input('премия'))
sheet = Worker()
sheet.work_plan(name, surname, position, income)
sheet_f = Position()
print(sheet_f.get_full_name(), sheet_f.get_total_income())
|
b43511403e059ed78fb0b3b6f876901c960c8009 | Ashish-kumar-pradhan/python | /python basic/loop.py | 134 | 3.578125 | 4 |
i=1
while i<=5:
print("Ashish",end="")
j=1
while j<=4:
print(" kumar",end="")
j=j+1
i=i+1
print() |
74ccd2161f8f827fc27abd4691679512f8d7c586 | rafaelperazzo/programacao-web | /moodledata/vpl_data/16/usersdata/74/7155/submittedfiles/triangulo.py | 626 | 3.84375 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
import math
a = input('Primeiro valor')
b = input('Segundo valor')
c = input('Terceiro valor')
a1 = b+c
a2 = b**2+c**2
h = a**2
if a1>a:
print('S')
if a == b and b == c:
print('Eq')
print('Ac')
elif b == c and a =! c
print('Is')
if a2 == h:
print('Re')
elif h > a2:
print('O')
else:
print('Ac')
else:
print('Es')
if a2 == h:
print('Re')
elif h > a2:
print('O')
else:
print('Ac')
else:
print('N') |
4215ba2f757aebd58cdf7de5554b2e3ce4f3d024 | lyy901207/Data-Structure | /stack.py | 729 | 4.3125 | 4 | #用数组实现一个顺序栈
class Stack(object):
def __init__(self):
self.items = []
def push(self, item):
#向栈顶插入项
self.items.append(item)
def pop(self):
#返回栈顶的项,并从堆栈中删除该项
self.items.pop()
def clear(self):
#清空堆栈
del self.items[:]
def is_empty(self):
#判断堆栈是否为空
return len(self.items) == 0
def get_size(self):
#返回堆栈中项的个数
return len(self.items)
def top(self):
#返回栈顶的项
return self.items[-1]
if __name__ =='__main__':
s = Stack()
print(s.is_empty())
s.push(1)
s.push(2)
s.is_empty()
print(s.get_size())
s.get_size()
s.top()
s.pop()
s.clear()
s.is_empty()
print(s.get_size()) |
4c0b090c10048f2014baeb8ea38bc37c449938b6 | priyankaauti123/Python | /string/generate_n_char.py | 335 | 3.703125 | 4 | n=int(input("Enter no:="))
ch=input("Enter character:=")
def generate_n_char(ch,n):
str=[]
for i in range(n):
str.append(ch)
print ''.join(str)
generate_n_char(ch,n)
def histogram(lst):
for i in lst:
generate_n_char('*',i)
list_1=[4,7,2]
histogram(list_1)
[lambda x:generate_n_char('*',x),list_1]
|
2dfb290f41dc0ea642c0cae27add2ce27db454ca | Sigafoos/advent | /2016/python/day1.py | 1,351 | 3.75 | 4 | from copy import deepcopy
def walk(part = 1):
position = [0, 0]
facing = 'N'
visited = []
with open('../input/input1.txt') as fp:
for line in fp: # only one
directions = line.split(', ')
for direction in directions:
turn = direction[0]
steps = int(direction[1:])
if (facing == 'N' and turn == 'R') or (facing == 'S' and turn == 'L'):
for i in xrange(steps):
position[0] += 1
if position not in visited:
visited.append(deepcopy(position))
elif part == 2:
return position
facing = 'E'
elif (facing == 'N' and turn == 'L') or (facing == 'S' and turn == 'R'):
for i in xrange(steps):
position[0] -= 1
if position not in visited:
visited.append(deepcopy(position))
elif part == 2:
return position
facing = 'W'
elif (facing == 'E' and turn == 'R') or (facing == 'W' and turn == 'L'):
for i in xrange(steps):
position[1] -= 1
if position not in visited:
visited.append(deepcopy(position))
elif part == 2:
return position
facing = 'S'
elif (facing == 'E' and turn == 'L') or (facing == 'W' and turn == 'R'):
for i in xrange(steps):
position[1] += 1
if position not in visited:
visited.append(deepcopy(position))
elif part == 2:
return position
facing = 'N'
return position
print [sum(map(abs, walk(x))) for x in [1,2]]
|
dd65d446a97ab5420ff90813f9f07e9c2ffc937f | mikedeeno84/mikedbyte | /first_factorial.py | 585 | 4.0625 | 4 | def FirstFactorial(num):
result=1
while num>0: # loop down from starting number multiplying each number by the result variable and decrementing the num variable on each iteration
result=result*num
num=num-1
return result
print FirstFactorial(raw_input())
#Have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it
#(ie. if num = 4, return (4 * 3 * 2 * 1)). For the test cases, the range will be between 1 and 18.
#Use the Parameter Testing feature in the box below to test your code with different arguments.
|
9241ace26552ab624a1beab2a867cba7e94eca88 | prateek1404/AlgoPractice | /CareerCup/FB/swap.py | 88 | 3.875 | 4 | def swap(a,b):
a = a^b
b = a^b
a = a^b
return (a,b)
(a,b) =swap(10,11)
print a,b
|
72fa57018d0eb94b044c0c8b5cf7db9e78a024cd | akashgupta97/Image-Recognition-System-for-Cats- | /Main file.py | 20,306 | 3.8125 | 4 |
# # Image Recognition System
import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
from lr_utils import load_dataset
get_ipython().magic('matplotlib inline')
# ## 2 - Overview of the Problem set ##
#
# **Problem Statement**: given a dataset ("data.h5") containing:
# - a training set of m_train images labeled as cat (y=1) or non-cat (y=0)
# - a test set of m_test images labeled as cat or non-cat
# - each image is of shape (num_px, num_px, 3) where 3 is for the 3 channels (RGB). Thus, each image is square (height = num_px) and (width = num_px).
#
# build a simple image-recognition algorithm that can correctly classify pictures as cat or non-cat.
#
# Let's get more familiar with the dataset. Load the data by running the following code.
# In[32]:
# Loading the data (cat/non-cat)
train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
# We added "_orig" at the end of image datasets (train and test) because we are going to preprocess them. After preprocessing, we will end up with train_set_x and test_set_x (the labels train_set_y and test_set_y don't need any preprocessing).
#
# Each line of your train_set_x_orig and test_set_x_orig is an array representing an image. You can visualize an example by running the following code. Feel free also to change the `index` value and re-run to see other images.
# In[33]:
# Example of a picture
index = 27
plt.imshow(train_set_x_orig[index])
print("y = " + str(train_set_y[:, index]) + ", it's a '" + classes[np.squeeze(train_set_y[:, index])].decode(
"utf-8") + "' picture.")
### START CODE HERE ### (≈ 3 lines of code)
m_train = train_set_x_orig.shape[0]
m_test = test_set_x_orig.shape[0]
num_px = train_set_x_orig.shape[1]
### END CODE HERE ###
print("Number of training examples: m_train = " + str(m_train))
print("Number of testing examples: m_test = " + str(m_test))
print("Height/Width of each image: num_px = " + str(num_px))
print("Each image is of size: (" + str(num_px) + ", " + str(num_px) + ", 3)")
print("train_set_x shape: " + str(train_set_x_orig.shape))
print("train_set_y shape: " + str(train_set_y.shape))
print("test_set_x shape: " + str(test_set_x_orig.shape))
print("test_set_y shape: " + str(test_set_y.shape))
# **Expected Output for m_train, m_test and num_px**:
# <table style="width:15%">
# <tr>
# <td>**m_train**</td>
# <td> 209 </td>
# </tr>
#
# <tr>
# <td>**m_test**</td>
# <td> 50 </td>
# </tr>
#
# <tr>
# <td>**num_px**</td>
# <td> 64 </td>
# </tr>
#
# </table>
#
# In[35]:
# Reshape the training and test examples
### START CODE HERE ### (≈ 2 lines of code)
train_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T
test_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T
### END CODE HERE ###
print("train_set_x_flatten shape: " + str(train_set_x_flatten.shape))
print("train_set_y shape: " + str(train_set_y.shape))
print("test_set_x_flatten shape: " + str(test_set_x_flatten.shape))
print("test_set_y shape: " + str(test_set_y.shape))
print("sanity check after reshaping: " + str(train_set_x_flatten[0:5, 0]))
# **Expected Output**:
#
# <table style="width:35%">
# <tr>
# <td>**train_set_x_flatten shape**</td>
# <td> (12288, 209)</td>
# </tr>
# <tr>
# <td>**train_set_y shape**</td>
# <td>(1, 209)</td>
# </tr>
# <tr>
# <td>**test_set_x_flatten shape**</td>
# <td>(12288, 50)</td>
# </tr>
# <tr>
# <td>**test_set_y shape**</td>
# <td>(1, 50)</td>
# </tr>
# <tr>
# <td>**sanity check after reshaping**</td>
# <td>[17 31 56 22 33]</td>
# </tr>
# </table>
# In[36]:
train_set_x = train_set_x_flatten / 255.
test_set_x = test_set_x_flatten / 255.
# <font color='blue'>
# **What you need to remember:**
#
# Common steps for pre-processing a new dataset are:
# - Figure out the dimensions and shapes of the problem (m_train, m_test, num_px, ...)
# - Reshape the datasets such that each example is now a vector of size (num_px \* num_px \* 3, 1)
# - "Standardize" the data
# ## 3 - General Architecture of the learning algorithm ##
#
# It's time to design a simple algorithm to distinguish cat images from non-cat images.
#
# build a Logistic Regression, using a Neural Network mindset. The following Figure explains why **Logistic Regression is actually a very simple Neural Network!**
#
# <img src="images/LogReg_kiank.png" style="width:650px;height:400px;">
#
# **Mathematical expression of the algorithm**:
#
# For one example $x^{(i)}$:
# $$z^{(i)} = w^T x^{(i)} + b \tag{1}$$
# $$\hat{y}^{(i)} = a^{(i)} = sigmoid(z^{(i)})\tag{2}$$
# $$ \mathcal{L}(a^{(i)}, y^{(i)}) = - y^{(i)} \log(a^{(i)}) - (1-y^{(i)} ) \log(1-a^{(i)})\tag{3}$$
#
# The cost is then computed by summing over all training examples:
# $$ J = \frac{1}{m} \sum_{i=1}^m \mathcal{L}(a^{(i)}, y^{(i)})\tag{6}$$
#
# **Key steps**:
# In this exercise, carry out the following steps:
# - Initialize the parameters of the model
# - Learn the parameters for the model by minimizing the cost
# - Use the learned parameters to make predictions (on the test set)
# - Analyse the results and conclude
# ## 4 - Building the parts of our algorithm ##
#
# The main steps for building a Neural Network are:
# 1. Define the model structure (such as number of input features)
# 2. Initialize the model's parameters
# 3. Loop:
# - Calculate current loss (forward propagation)
# - Calculate current gradient (backward propagation)
# - Update parameters (gradient descent)
#
# build 1-3 separately and integrate them into one function we call `model()`.
#
# ### 4.1 - Helper functions
#
# **Exercise**: Using your code from "Python Basics", implement `sigmoid()`. As you've seen in the figure above, you need to compute $sigmoid( w^T x + b) = \frac{1}{1 + e^{-(w^T x + b)}}$ to make predictions. Use np.exp().
# In[37]:
# GRADED FUNCTION: sigmoid
def sigmoid(z):
"""
Compute the sigmoid of z
Arguments:
z -- A scalar or numpy array of any size.
Return:
s -- sigmoid(z)
"""
### START CODE HERE ### (≈ 1 line of code)
s = 1 / (1 + np.exp(-z))
### END CODE HERE ###
return s
# In[38]:
print("sigmoid([0, 2]) = " + str(sigmoid(np.array([0, 2]))))
# **Expected Output**:
#
# <table>
# <tr>
# <td>**sigmoid([0, 2])**</td>
# <td> [ 0.5 0.88079708]</td>
# </tr>
# </table>
# ### 4.2 - Initializing parameters
#
# **Exercise:** Implement parameter initialization in the cell below. You have to initialize w as a vector of zeros. If you don't know what numpy function to use, look up np.zeros() in the Numpy library's documentation.
# In[39]:
# GRADED FUNCTION: initialize_with_zeros
def initialize_with_zeros(dim):
"""
This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0.
Argument:
dim -- size of the w vector we want (or number of parameters in this case)
Returns:
w -- initialized vector of shape (dim, 1)
b -- initialized scalar (corresponds to the bias)
"""
### START CODE HERE ### (≈ 1 line of code)
w = np.zeros([dim, 1])
b = 0
### END CODE HERE ###
assert (w.shape == (dim, 1))
assert (isinstance(b, float) or isinstance(b, int))
return w, b
# In[40]:
dim = 2
w, b = initialize_with_zeros(dim)
print("w = " + str(w))
print("b = " + str(b))
# **Expected Output**:
#
#
# <table style="width:15%">
# <tr>
# <td> ** w ** </td>
# <td> [[ 0.]
# [ 0.]] </td>
# </tr>
# <tr>
# <td> ** b ** </td>
# <td> 0 </td>
# </tr>
# </table>
#
# For image inputs, w will be of shape (num_px $\times$ num_px $\times$ 3, 1).
# **Hints**:
#
# Forward Propagation:
# - You get X
# - You compute $A = \sigma(w^T X + b) = (a^{(0)}, a^{(1)}, ..., a^{(m-1)}, a^{(m)})$
# - You calculate the cost function: $J = -\frac{1}{m}\sum_{i=1}^{m}y^{(i)}\log(a^{(i)})+(1-y^{(i)})\log(1-a^{(i)})$
#
# Here are the two formulas you will be using:
#
# $$ \frac{\partial J}{\partial w} = \frac{1}{m}X(A-Y)^T\tag{7}$$
# $$ \frac{\partial J}{\partial b} = \frac{1}{m} \sum_{i=1}^m (a^{(i)}-y^{(i)})\tag{8}$$
# In[41]:
# GRADED FUNCTION: propagate
def propagate(w, b, X, Y):
"""
Implement the cost function and its gradient for the propagation explained above
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of size (num_px * num_px * 3, number of examples)
Y -- true "label" vector (containing 0 if non-cat, 1 if cat) of size (1, number of examples)
Return:
cost -- negative log-likelihood cost for logistic regression
dw -- gradient of the loss with respect to w, thus same shape as w
db -- gradient of the loss with respect to b, thus same shape as b
"""
m = X.shape[1]
# FORWARD PROPAGATION (FROM X TO COST)
### START CODE HERE ### (≈ 2 lines of code)
A = sigmoid(np.dot(w.T, X) + b) # compute activation
cost = -1 / m * (np.dot(Y, np.log(A).T) + np.dot((1 - Y), np.log(1 - A).T)) # compute cost
### END CODE HERE ###
# BACKWARD PROPAGATION (TO FIND GRAD)
### START CODE HERE ### (≈ 2 lines of code)
dw = 1 / m * (np.dot(X, (A - Y).T))
db = 1 / m * (np.sum(A - Y))
### END CODE HERE ###
assert (dw.shape == w.shape)
assert (db.dtype == float)
cost = np.squeeze(cost)
assert (cost.shape == ())
grads = {"dw": dw,
"db": db}
return grads, cost
# In[42]:
w, b, X, Y = np.array([[1], [2]]), 2, np.array([[1, 2], [3, 4]]), np.array([[1, 0]])
grads, cost = propagate(w, b, X, Y)
print("dw = " + str(grads["dw"]))
print("db = " + str(grads["db"]))
print("cost = " + str(cost))
# **Expected Output**:
#
# <table style="width:50%">
# <tr>
# <td> ** dw ** </td>
# <td> [[ 0.99993216]
# [ 1.99980262]]</td>
# </tr>
# <tr>
# <td> ** db ** </td>
# <td> 0.499935230625 </td>
# </tr>
# <tr>
# <td> ** cost ** </td>
# <td> 6.000064773192205</td>
# </tr>
#
# </table>
# ### d) Optimization
# - You have initialized your parameters.
# - You are also able to compute a cost function and its gradient.
# - Now, you want to update the parameters using gradient descent.
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost=False):
"""
This function optimizes w and b by running a gradient descent algorithm
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of shape (num_px * num_px * 3, number of examples)
Y -- true "label" vector (containing 0 if non-cat, 1 if cat), of shape (1, number of examples)
num_iterations -- number of iterations of the optimization loop
learning_rate -- learning rate of the gradient descent update rule
print_cost -- True to print the loss every 100 steps
Returns:
params -- dictionary containing the weights w and bias b
grads -- dictionary containing the gradients of the weights and bias with respect to the cost function
costs -- list of all the costs computed during the optimization, this will be used to plot the learning curve.
"""
costs = []
for i in range(num_iterations):
# Cost and gradient calculation (≈ 1-4 lines of code)
### START CODE HERE ###
grads, cost = propagate(w, b, X, Y)
### END CODE HERE ###
# Retrieve derivatives from grads
dw = grads["dw"]
db = grads["db"]
# update rule (≈ 2 lines of code)
### START CODE HERE ###
w = w - learning_rate * dw
b = b - learning_rate * db
### END CODE HERE ###
# Record the costs
if i % 100 == 0:
costs.append(cost)
# Print the cost every 100 training examples
if print_cost and i % 100 == 0:
print("Cost after iteration %i: %f" % (i, cost))
params = {"w": w,
"b": b}
grads = {"dw": dw,
"db": db}
return params, grads, costs
# In[44]:
params, grads, costs = optimize(w, b, X, Y, num_iterations=100, learning_rate=0.009, print_cost=False)
print("w = " + str(params["w"]))
print("b = " + str(params["b"]))
print("dw = " + str(grads["dw"]))
print("db = " + str(grads["db"]))
# **Expected Output**:
#
# <table style="width:40%">
# <tr>
# <td> **w** </td>
# <td>[[ 0.1124579 ]
# [ 0.23106775]] </td>
# </tr>
#
# <tr>
# <td> **b** </td>
# <td> 1.55930492484 </td>
# </tr>
# <tr>
# <td> **dw** </td>
# <td> [[ 0.90158428]
# [ 1.76250842]] </td>
# </tr>
# <tr>
# <td> **db** </td>
# <td> 0.430462071679 </td>
# </tr>
#
# </table>
def predict(w, b, X):
'''
Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b)
Arguments:
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bias, a scalar
X -- data of size (num_px * num_px * 3, number of examples)
Returns:
Y_prediction -- a numpy array (vector) containing all predictions (0/1) for the examples in X
'''
m = X.shape[1]
Y_prediction = np.zeros((1, m))
w = w.reshape(X.shape[0], 1)
# Compute vector "A" predicting the probabilities of a cat being present in the picture
### START CODE HERE ### (≈ 1 line of code)
A = sigmoid(np.dot(w.T, X) + b)
### END CODE HERE ###
for i in range(A.shape[1]):
# Convert probabilities A[0,i] to actual predictions p[0,i]
### START CODE HERE ### (≈ 4 lines of code)
if (A[0][i] <= 0.5):
Y_prediction[0][i] = 0
else:
Y_prediction[0][i] = 1
### END CODE HERE ###
assert (Y_prediction.shape == (1, m))
return Y_prediction
# In[46]:
print("predictions = " + str(predict(w, b, X)))
# **Expected Output**:
#
# <table style="width:30%">
# <tr>
# <td>
# **predictions**
# </td>
# <td>
# [[ 1. 1.]]
# </td>
# </tr>
#
# </table>
#
# <font color='blue'>
# **What to remember:**
# - Initialize (w,b)
# - Optimize the loss iteratively to learn parameters (w,b):
# - computing the cost and its gradient
# - updating the parameters using gradient descent
# - Use the learned (w,b) to predict the labels for a given set of examples
# ## 5 - Merge all functions into a model ##
#
#
# **Exercise:** Implement the model function. Use the following notation:
# - Y_prediction for your predictions on the test set
# - Y_prediction_train for your predictions on the train set
# - w, costs, grads for the outputs of optimize()
# In[49]:
def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=False):
"""
Builds the logistic regression model by calling the function you've implemented previously
Arguments:
X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train)
Y_train -- training labels represented by a numpy array (vector) of shape (1, m_train)
X_test -- test set represented by a numpy array of shape (num_px * num_px * 3, m_test)
Y_test -- test labels represented by a numpy array (vector) of shape (1, m_test)
num_iterations -- hyperparameter representing the number of iterations to optimize the parameters
learning_rate -- hyperparameter representing the learning rate used in the update rule of optimize()
print_cost -- Set to true to print the cost every 100 iterations
Returns:
d -- dictionary containing information about the model.
"""
### START CODE HERE ###
# initialize parameters with zeros (≈ 1 line of code)
w, b = initialize_with_zeros(X_train.shape[0])
# Gradient descent (≈ 1 line of code)
parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations=2000, learning_rate=0.5,
print_cost=False)
# Retrieve parameters w and b from dictionary "parameters"
w = parameters["w"]
b = parameters["b"]
# Predict test/train set examples (≈ 2 lines of code)
Y_prediction_test = predict(w, b, X_test)
Y_prediction_train = predict(w, b, X_train)
### END CODE HERE ###
# Print train/test Errors
print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))
d = {"costs": costs,
"Y_prediction_test": Y_prediction_test,
"Y_prediction_train": Y_prediction_train,
"w": w,
"b": b,
"learning_rate": learning_rate,
"num_iterations": num_iterations}
return d
# In[50]:
d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations=2000, learning_rate=0.005, print_cost=True)
# **Expected Output**:
#
# <table style="width:40%">
#
# <tr>
# <td> **Train Accuracy** </td>
# <td> 99.04306220095694 % </td>
# </tr>
#
# <tr>
# <td>**Test Accuracy** </td>
# <td> 70.0 % </td>
# </tr>
# </table>
#
#
# Example of a picture that was wrongly classified.
for index in range(20):
# index =
plt.imshow(test_set_x[:, index].reshape((num_px, num_px, 3)))
plt.imshow(test_set_x[:, index + 1].reshape((num_px, num_px, 3)))
print("y = " + str(test_set_y[0, index]) + ", you predicted that it is a \"" + classes[
d["Y_prediction_test"][0, index]].decode("utf-8") + "\" picture.")
# Let's also plot the cost function and the gradients.
# In[54]:
# Plot learning curve (with costs)
costs = np.squeeze(d['costs'])
plt.plot(costs)
plt.ylabel('cost')
plt.xlabel('iterations (per hundreds)')
plt.title("Learning rate =" + str(d["learning_rate"]))
plt.show()
# **Interpretation**:
# You can see the cost decreasing. It shows that the parameters are being learned. However, you see that you could train the model even more on the training set. Try to increase the number of iterations in the cell above and rerun the cells. You might see that the training set accuracy goes up, but the test set accuracy goes down. This is called overfitting.
# **Reminder**:
# In order for Gradient Descent to work you must choose the learning rate wisely. The learning rate $\alpha$ determines how rapidly we update the parameters. If the learning rate is too large we may "overshoot" the optimal value. Similarly, if it is too small we will need too many iterations to converge to the best values. That's why it is crucial to use a well-tuned learning rate.
#
# Let's compare the learning curve of our model with several choices of learning rates. Run the cell below. This should take about 1 minute. Feel free also to try different values than the three we have initialized the `learning_rates` variable to contain, and see what happens.
# In[55]:
learning_rates = [0.01, 0.001, 0.0001]
models = {}
for i in learning_rates:
print("learning rate is: " + str(i))
models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations=1500, learning_rate=i,
print_cost=False)
print('\n' + "-------------------------------------------------------" + '\n')
for i in learning_rates:
plt.plot(np.squeeze(models[str(i)]["costs"]), label=str(models[str(i)]["learning_rate"]))
plt.ylabel('cost')
plt.xlabel('iterations')
legend = plt.legend(loc='upper center', shadow=True)
frame = legend.get_frame()
frame.set_facecolor('0.90')
plt.show()
## START CODE HERE ## (PUT YOUR IMAGE NAME)
my_image = "my_image.jpg" # change this to the name of your image file
## END CODE HERE ##
# We preprocess the image to fit your algorithm.
fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))
my_image = scipy.misc.imresize(image, size=(num_px, num_px)).reshape((1, num_px * num_px * 3)).T
my_predicted_image = predict(d["w"], d["b"], my_image)
plt.imshow(image)
print("y = " + str(np.squeeze(my_predicted_image)) + ", your algorithm predicts a \"" + classes[
int(np.squeeze(my_predicted_image)),].decode("utf-8") + "\" picture.")
|
afb92296f90e7ced30c27eb65afb444d832f7458 | Siumnoor/Django_classWorks | /GPA.py | 459 | 3.953125 | 4 | a = int (input("Enter Marks : "))
if (a>=80 and a<=100):
print("A+")
elif (a>=75 and a<=79):
print("A")
elif (a>=70 and a<=74):
print("A-")
elif (a>=65 and a<=69):
print("B+")
elif (a>=60 and a<=64):
print("B")
elif (a>=55 and a<=59):
print("B-")
elif (a>=50 and a<=54):
print("C+")
elif (a>=45 and a<=49):
print("C")
elif(a>=40 and a<=44):
print("D")
elif(a>=0 and a<=39):
print("F")
else:
print("Error Marks!") |
6778614ff38a44feab76fdaa231838fd583d964b | luamnoronha/cursoemvideo | /ex.045.py | 1,292 | 3.734375 | 4 | import random
print('vamos jogar! jokempo!')
print('=='*20)
print('''escolha umas da jogadas a seguir
[1] PEDRA
[2] TESOURA
[3] PAPEL ''')
player = int(input('qual sua jogada: '))
opc = [1, 2, 3]
pc = random.choice(opc)
if player == 1 and pc == 2:
print('a jogada do pc foi TESOURA e a sua PEDRA, PARABÉNS VOCÊ É O VENCENDOR! ')
elif player == 1 and pc == 3:
print('a jogada do PC foi PEDRA e a sua foi PAPEL, QUE PENA VOCê PERDEU!')
elif player == 1 and pc == 1:
print('a jogada do PC foi PEDRA e a sua foi PEDRA, OPS! DEU IMPATE!')
elif player == 2 and pc == 1:
print('a jogada do PC foi PEDRA e a sua foi TESOURA, QUE PENA VOCê PERDEU! ')
elif player == 2 and pc == 2:
print('a jogada do PC foi TESOURA e a sua foi TESOURA, OPS! DEU IMPATE')
elif player == 2 and pc == 3:
print('a jogada do PC foi PAPEL, e a sua foi TESOURA, PARABÉNS VOCÊ É O VENCENDOR! ')
elif player == 3 and pc == 1:
print('a jogada do PC foi PEDRA, e a sua foi PAPEL, PARABÉNS VOCÊ É O VENCENDOR!')
elif player == 3 and pc == 2:
print('a jogada do PC foi TESOURA, e a sua foi PAPEL, QUE PENA VOCê PERDEU! ')
elif player == 3 and pc == 3:
print('a jogada do PC foi PAPEL e a sua foi PAPEL, OPS! DEU IMPATE')
else:
print('comando invalido, não tente trapacear!')
|
d4380956795987ff74be6d01e875d13ac800a8b2 | rashmikamath/data_structures | /iocamp1/longest_common_subsequence.py | 451 | 3.53125 | 4 | def lcs(str1, str2):
m = len(str1)
n = len(str2)
dp = [[0 for i in range(n+1)] for j in range(m+1)]
for i, s1 in enumerate(str1):
for j, s2 in enumerate(str2):
if s1 == s2:
dp[i+1][j+1] = 1+dp[i][j]
else:
dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j])
return dp[-1][-1]
text1 = "abcde"
text2 = "ace"
print(lcs(text1, text2))
text1 = "abc"
text2 = "abc"
print(lcs(text1, text2))
text1 = "abc"
text2 = "def"
print(lcs(text1, text2)) |
887b25315af5764c1f924e7b7a72c67ecdb5b320 | davidchoi-dev/fastcampus_python_basic | /section06.py | 7,260 | 3.515625 | 4 | # Section06
# 파이썬 함수식 및 람다(lambda)
# 함수 정의 방법
# def 함수명(parameter):
# code
# 함수 호출
# 함수명(parameter)
# 함수 선언 위치 중요
# 예제1
def hello(world):
print("Hello", world)
hello("Hayong")
# 예제2
def hello_return(world):
val = "Hello " + str(world)
return val
abc = hello_return("Hayong!!!")
print(abc)
# 예제3(다중리턴)
def func_mul(x):
y1 = x * 100
y2 = x * 200
y3 = x * 300
return y1, y2, y3
val1, val2, val3 = func_mul(100)
print(val1, val2, val3)
# 예제4(데이터 타입 반환)
def func_mul2(x):
y1 = x * 100
y2 = x * 200
y3 = x * 300
return [y1, y2, y3]
lt = func_mul2(100)
print(lt)
# 리스트 [], 튜플 ()
# 예제4
# *args 인자, *kwargs 가변인자
# 이거 잘 모르겠어요
def args_func(*args):
# for t in args:
# print(t)
for i, v in enumerate(args):
print(i, v)
args_func('Jung')
args_func('Jung', 'Park')
args_func('Jung', 'Park', 'Choi')
# kwargs 키워드 인자
# * 하나일 때는 튜플로 받는데, ** 일 때는 딕셔너리로 받는다.
def kwargs_func(**kwargs):
for k, v in kwargs.items():
print(k, v)
kwargs_func(name1='Jung')
kwargs_func(name1='Jung', name2='Park', name3='Choi')
# 전체 혼합
def example_mul(arg1, arg2, *args, **kwargs):
print(arg1, arg2, args, kwargs)
example_mul(10, 20)
example_mul(10, 20, 'Jung', 'Park', age1=27, age2=54)
# 잘 모르겠어서 구글 검색 : 가변인자 함수는 함수가 몇 개의 인자를 받을지 정해지지 않은 함수입니다.
# 파이썬에서는 가변인자 함수를 지원하고 있습니다.
# 파이썬에서는 가변인자를 받을 때 *를 붙여서 받습니다.
# 가변인자 함수를 통해 좀 더 유연하게 동작하는 함수 작성이 가능합니다.
# 출처 : https://psychoria.tistory.com/530
# 아 모르겠어 다시 검색
# 파이썬 코드를 보다보면 가끔 *args, **kwargs를 볼 수 있습니다.
# 이것은 함수의 인자(parameter 또는 arguments)가 가변 길이일 때 사용합니다.
# args, kargs는 원하는 이름대로 쓸 수 있고, *, **는 각각 non-keyworded argumnets, keworded arguments를 뜻합니다.
# 출처: https://3months.tistory.com/347
# 아 모르겠어 다시 검색
# 오 뭔가 이해 갈 것 같다. 출처 : https://brunch.co.kr/@princox/180
# 파이썬에서 *, **는 주소값을 저장하는 의미가 아닙니다.
# 바로 여러 개의 인수를 받을 때, 키워드 인수를 받을 때 사용하는 표시입니다.
# 먼저 *args부터 알아보자
# *.args는 *arguments의 줄임말입니다.
# 그러니까..꼭 저 단어를 쓸 필요가 없다는 말입니다.
# *a 라고 써도 되고, *arsdkljfksdjfs 라고 적어도 된다는 말입니다.
# 이 지시어는 여러 개(복수개의)의 인자를 함수로 받고자 할 때 쓰입니다.
# 사람의 이름을 받아서 성과 이름을 분리한 후 출력을 하고 싶습니다.
# 근데 문제가 생겼습니다.
# 사용자가 '몇 개의' 이름을 적어 넣을 지 알 수 가 없는 것이죠.
# 이럴 때 *args를 인자로 받습니다.
def lastName_and_FirstName(*아무변수):
for 아무아무변수 in 아무변수:
print("%s %s" % (아무아무변수[0], 아무아무변수[1:3]), end=' ')
print("\n")
lastName_and_FirstName('정하용')
lastName_and_FirstName('정하용', '염정아')
lastName_and_FirstName('정하용', '염정아', '윤세아')
lastName_and_FirstName('정하용', '염정아', '윤세아', '박소담')
# 와 대박 이해 한방에 감
# lastName_and_FirstName 함수에서는 인자를 *아무변수 를 받습니다.
# args를 출력해보면 tuple(튜플) 형태임을 알 수 있습니다.
# 여러 개의 인자로 함수를 호출할 경우, 함수 내부에서는 튜플로 받은 것처럼 인식한다는 것이죠.
# 이렇게 여러개의 인자를 받기 위해서 *args의 형태로 함수 파라미터를 작성합니다.
# 와 이해 감
# 대박 대박 감사합니다. 개미님.
# **kwargs을 알아보자
# kwargs는 keyword argument의 줄임말로 키워드를 제공합니다.
def introduceEnglishName(**아무아무아무거나):
for 아무거나, 아무거나거나 in 아무아무아무거나.items():
print("{0} is {1}".format(아무거나, 아무거나거나))
introduceEnglishName(MyName='Jung Hayong')
# 와 이해 한방에 간다!!! 그런데 살짝 궁금해진게, 그그 key 하고 value
# 를 적잖아요 그게 이 함수, 파이썬이 첫번째 위치, 두번째 위치라고 기억해서 뱉어 내는거에요?
# 아니면 key, value 값이라고 명확하게 인지한 상태에서 뱉어내는 거에요?
# **kwargs는(키워드 = 특정값) 형태로 함수를 호출할 수 있습니다.
# 그것은 그대로 딕셔너리 형태로 {'키워드':특정값} 요렇게 함수 내부로 전달됩니다.
# 그렇게 전달받은 딕셔너리를 마음대로 조리하면 되겠죠?
# 여기까지 이해하고, 더 읽어내려 나가자
# 감사합니다. 이분 브런치 더 열심히 읽고
# 공부해야지
# 아하 키워드 아규먼트를 이용해서 무슨 키워드가 입력되면 이렇게 출력하고
# 또 다르게 키워드가 입력되면 저렇게 출력하는 함수를 만들 수 있겠구나
# 감사합니다
# https://brunch.co.kr/@princox/180
# https://brunch.co.kr/@princox/180
# https://brunch.co.kr/@princox/180
# 공부는 이렇게 해야겠다
# 구글에게 물어봐
# 구글은 답을 알고 있다
# 너가 못찾을 뿐
# -정하용-
# 예제5
# 중첩함수(클로저)
print()
def nested_func(num):
def func_in_func(num):
print(num)
print("in func")
func_in_func(num + 10000)
nested_func(10000)
# 데코레이터 클로저 공부해보기!!!
# 지금은 감만 오네~
# 오늘 공부 끝!!
# 예제6(hint)
def func_mul3(x: int) -> list:
y1 = x * 100
y2 = x * 200
y3 = x * 300
return [y1, y2, y3]
print(func_mul3(500))
# 람다식 예제
# 람다식 : 메모리 절약, 가독성 향상, 코드 간결
# 함수는 객체 생성 -> 리소스(메모리) 할당
# 람다는 즉시 실행(Heap 초기화) -> 메모리 초기화
# 일반적 함수 -> 변수 할당
def mul_10(num: int) -> int:
return num * 10
var_func = mul_10
print(var_func)
print(type(var_func))
print(var_func(10))
def lambda_mul_10(num): return num * 10
print('>>>', lambda_mul_10(10))
# 람다식: 람다함수를 사용함으로써 가독성, 코드를 간결하게
# 많은 메모리가 절약되는 것은 아니지만 메모리 절약됨
# 데이터 전처리라든지 데이터 베이스에서 게시판 데이터들을 대량으로 가져와서
# 날짜를 바꿔준다던지, 내용을 수정한다던지, 형태소 분석을 한다던지,
# 문자열과 문자열을 연결해서 새로운 문자열을 만든다던지 그럴때 좋다
def func_final(x, y, func):
print(x*y*func(10))
func_final(10, 10, lambda_mul_10)
# 람다함수를 넣을 수도 있다
print(func_final(10, 10, lambda x: x * 1000))
# 즉시 람다식을 바로 작성해서 함수에 인자로 함수를 넘긴것을 확인할 수 있다
|
c00eb9d5d02376796c7e3552a9ee8e542042cb5c | SamGoodin/c200-Assignments | /CodeDemonstrations/InClass1.py | 593 | 4.46875 | 4 | #Create a program to give opinion on input color
while 0 < 1:
color = (input("What is your favorite basic color? ")).lower()
if color == "red" or color == "blue" or color == "yellow":
print("That is a primary color.")
elif color == "black" or color == "white":
print("That color is basic.")
elif color == "orange" or color == "green" or color == "purple" or color == "violet":
print("That is a secondary color.")
elif color == "brown":
print("Brown is a composite color.")
else:
print("I don't understand what color that is.")
|
c3e5e38290c99e7ec8e7a5bf00c452fbc4caad84 | mzmudziak/py-umcs | /zaj2/zadania/zad4.py | 437 | 3.65625 | 4 | #!/usr/bin/python
import sys
def patternSearch(pattern, f):
for line in f:
if pattern in line:
print line
def read():
file_lines = ''
while True:
l = sys.stdin.readline()
if l == "":
return file_lines
file_lines += l
if sys.argv[2] == '-':
patternSearch(sys.argv[1], read())
else:
with open(sys.argv[2]) as plik:
patternSearch(sys.argv[1], plik)
|
402bd4d9b3d51e4c025e5070ced11e1343f42afc | nigomezcr/Programming-Basics | /06-Arrays/1-arrays-example-I.py | 724 | 3.890625 | 4 | """
Description: Arrays in python.
"""
import numpy as np
#Built-in arrays in numpy:
N = 11 #number of elements
a = np.zeros(N)
b = np.ones(N)
c = np.arange(N)
d = np.eye(N)
#To fill our array
for i in c:
a[i] = 2*i+1
#Operations with the array: average
suma = 0
for i in c:
suma += a[i]
average = suma/N
print(average)
"""
//////////////////////////////////////////////////////////////////////////
Created on Fri Jan 1 13:32:11 2021 //
//
@author: Nicolás Gómez //
//////////////////////////////////////////////////////////////////////
"""
|
cab09bb76642d241407047839f2793e5f4061647 | tospolkaw/CloanGit_PythonHealthcare | /py_files/0107_tensorflow_image.py | 7,639 | 3.734375 | 4 | """
Code, apart from the confusion matrix,taken from:
https://www.tensorflow.org/tutorials/keras/basic_classification#
"""
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
# Helper libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import itertools
# Load minst fashion data set
"""Minst fashion data set is a collection of 70k images of 10 different
fashion items. It is loaded as training and test images and labels (60K training
images and 10K test images).
0 T-shirt/top
1 Trouser
2 Pullover
3 Dress
4 Coat
5 Sandal
6 Shirt
7 Sneaker
8 Bag
9 Ankle boot
"""
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = \
fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# Show an example image (an ankle boot)
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()
# Scale images to values 0-1 (currently 0-255)
train_images = train_images / 255.0
test_images = test_images / 255.0
# Plot first 25 images with labels
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show()
## BUILD MODEL
# Set up neural network layers
"""The first layer flattess the 28x28 image to a 1D array (784 pixels).
The second layer is a fully connected (dense) layer of 128 nodes/neurones.
The last layer is a 10 node softmax layer, giving probability of each class.
Softmax adjusts probabilities so that they total 1."""
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)])
# Compile the model
"""Optimizer: how model corrects itself and learns.
Loss function: How accurate the model is.
Metrics: How to monitor performance of model"""
model.compile(optimizer=tf.train.AdamOptimizer(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# Train the model (epochs is the number of times the training data is applied)
model.fit(train_images, train_labels, epochs=5)
# Evaluate accuracy
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)
# APPLY MODEL
# Make predictions
predictions = model.predict(test_images)
print ('\nClass propbabilities for test image 0')
print (predictions[0])
print ('\nPrdicted class for test image 0:', np.argmax(predictions[0]))
print ('Actual classification for test image 0:', test_labels[0])
# Plot image and predictions
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
if predicted_label == true_label:
color = 'blue'
else:
color = 'red'
plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
100*np.max(predictions_array),
class_names[true_label]),
color=color)
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array[i], true_label[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
thisplot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
thisplot[predicted_label].set_color('red')
thisplot[true_label].set_color('blue')
# Plot images and graph for selected images
# Blue bars shows actual classification
# Red bar shows an incorrect classificiation
num_rows = 6
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions, test_labels)
plt.show()
# SHOW CONFUSION MATRIX
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
cm = cm * 100
print("\nNormalized confusion matrix")
else:
print('\nConfusion matrix, without normalization')
print(cm)
print ()
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.0f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
# Compute confusion matrix
y_pred = np.argmax(predictions, axis=1)
cnf_matrix = confusion_matrix(test_labels, y_pred)
np.set_printoptions(precision=2) # set NumPy to 2 decimal places
# Plot non-normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=class_names,
title='Confusion matrix, without normalization')
# Plot normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=class_names, normalize=True,
title='Normalized confusion matrix')
# Making a prediction of a single image
"""tf.keras models are optimized to make predictions on a batch, or collection,
of examples at once. So even though we're using a single image, we need to add
it to a list:"""
# Grab an example image
img = test_images[0]
# Add the image to a batch where it's the only member.
img = (np.expand_dims(img,0))
# Make prediction
predictions_single = model.predict(img)
# Plot results
plot_value_array(0, predictions_single, test_labels)
_ = plt.xticks(range(10), class_names, rotation=45)
plt.show()
# MIT License
#
# Copyright (c) 2017 François Chollet
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE. |
890a2cb8e115d6dcf769700e468f91eb91225213 | atulgupta9/DigitalAlpha-Training-Programs | /Day3/prog1.py | 1,582 | 3.6875 | 4 | #1. Given the rent data file, write a Python program to do the following.
#a) Calculate the mean, mode and median of the rents.
#b) Generate a frequency distribution and print the table
#c) Print the cumulative frequent distribution
#d) Calculate 25th, 50th and 75th percentile values
#e) Calculate variance and coefficient of variance
import statistics
rent_list = []
rent_dict = {}
unique_rent_list = []
with open("rentData.txt","r") as file:
for line in file:
rent_list.append(int(line.replace("\n","")))
print("Mean is "+str(statistics.mean(rent_list)))
print("Median is "+str(statistics.median(rent_list)))
print("Mode is "+str(statistics.mode(rent_list)))
for i in rent_list:
if(rent_dict.get(i)):
rent_dict[i]+=1
else:
rent_dict[i]=1
print("Frequency Distribution Table:-")
print("Value \t Frequency")
for key,value in rent_dict.items():
print("%d \t %d"%(key,value))
freq = 0
for key,value in rent_dict.items():
rent_dict[key]+= freq
freq=rent_dict[key]
print("Cummulative Frequency Distribution Table:-")
print("Value \t Frequency")
for key, value in rent_dict.items():
print("%d \t %d" % (key, value))
print("25th Percentile Value is",rent_list[int(len(rent_list)/4)])
print("50th Percentile Value is",rent_list[int(len(rent_list)/2)])
print("75th Percentile Value is",rent_list[int( ( len(rent_list)*3)/4)])
print("Variance is ",statistics.variance(rent_list))
print("Coefficient of Variance is ",(statistics.stdev(rent_list)/statistics.mean(rent_list))*100,"%")
|
eaae699afb15ebac7069895a5424738ad3ca5e97 | maurus56/exercism | /python/reverse-string/reverse_string.py | 145 | 3.78125 | 4 | def reverse(input=''):
"""With extended slicing
string[start:end:step]
"python"[3::] = "hon"
"""
return input[::-1] |
8938a8b03318a4a9762165f5638be45c03c523f4 | lcbm/cesar-is-cool | /matemática-discreta/laGrange_interpolation.py | 671 | 3.6875 | 4 | os.system('cls')
print("Interpolação: Método de LaGrange\n")
x = sp.symbols('x')
xn_fn = [float(x) for x in input("Digite coordenadas dos pontos no formato 'x, fx': ").split(',')]
xn = xn_fn[0::2]
fn = xn_fn[1::2]
coordenadas = list(zip(xn,fn))
print(f"As coordenadas inseridas (xn,fn) foram: {coordenadas}")
px = 0
for k in range(len(xn)):
ln = 1
for j in range(len(xn)):
if j != k:
ln = ln*(((x-xn[j])/(xn[k]-xn[j])))
px += (ln*fn[k])
#ln = sp.expand((ln)*((x-xn[0])/(xn[k]-xn[0])))
#px = px + (fn[k]*ln)
print(f"O polinomio de LaGrange é Px = {px}")
|
28607212510d1e1998c1e83e2f3f5b9dc2c731b4 | cad75/GBLessons | /Lesson_7_HW_1.py | 802 | 3.828125 | 4 | class Matrix:
def __init__(self, all_titels):
self.all_titels = all_titels
def __str__(self):
result = ''
for i in self.all_titels:
for el in i:
result += str(el) + ' '
result += '\n'
return result
def __add__(self, other):
result = []
for i in range(len(self.all_titels)):
result.append([])
for j in range(len(self.all_titels[i])):
result[i].append(self.all_titels[i][j] + other.all_titels[i][j])
return Matrix(result)
first_matrix = Matrix([[1, 2, 7, 3], [5, 6, 9, 1]])
second_matrix = Matrix([[4, 2, 8, 4], [1, 5, 6, 2]])
print(first_matrix)
print(second_matrix)
print(f'Результат сложения')
print(first_matrix + second_matrix)
|
65a4f6f6e493dc68909113aaceaf3431d3626341 | rkreml/Python-Course | /Week 1/Assignment 1.4.b.py | 859 | 3.859375 | 4 | ## Name: Robert Kreml
## Date: September 6, 2019
## Class: EPSY 5200
##Study Drill 6 from Exercise 4 from LP3TH by Zed Shaw
print("I want to do some calculations.")
print("This is my attempt at using Python as a calculator using a .py script.")
print("Specifically this one will be using python to store and retrieve information in the form of variables.")
print("What is 1 * 9 / 3 * 16?", 1 * 9 / 3 * 16)
print("Cool, let's save this as x.")
x = 1 * 9 / 3 * 16
print("What is 65 + 9 - 74 * 9 / 36?", 65 + 9 - 74 * 9 / 36)
print("Cool, let's save this as i.")
i = 65 + 9 - 74 * 9 / 36
print("I want to save a number for later, let's save 28 as j.")
j = 28
print("What is x**j / i?", x ** j / i)
print("Okay, what about 19 ** 24 / 91 * 1 * 28 * 7 / 12 ** 35?", 19 ** 24 / 91 * 1 * 28 * 7 / 12 ** 35)
print("Cool, good to know. I am glad I have this ability now!") |
28b6de8d6f77f2413898de1e9acea450e22952b8 | mish-a14/python_functions | /question1.py | 871 | 4.15625 | 4 | # 1) (Concept: Calling a function that has already been defined.)
# The following function definition defines a function called pokemon_contains that will tell you if a single
# incoming_letter passed into this function exists in the word "pokemon". This function returns a boolean
# (ie., True or False). Your task is to first, copy this function and then call this function by passing in the
# letter "k".
# Store the result of this function call in a variable called result1.
# Print out the result.
# Secondly, call this function by passing in the letter "o". Store the result of this function call in a variable
# called result1.
# Print out the result.
def pokemon_contains(incoming_letter):
if incoming_letter in "pokemon":
return True
else:
return False
result = pokemon_contains('k')
print(result)
result1 = pokemon_contains('o')
print(result1) |
30763452117929da6469318c1462bc4cf32ace96 | DaniAkiode/portfollio | /Python Practice/Software Development/Somthing floats.py | 123 | 3.75 | 4 | anything = float(input("Give me a number:"))
something = anything ** 2.0
print(anything, "to the power of 2 is", something) |
3cccefb8ea1c4564c3961ecd8c7658ea72ccff84 | Man0j-kumar/python | /dict_key_sum.py | 166 | 3.515625 | 4 | d1={'a':1,'b':2,'c':4}
d2={'a':3,'b':3,'d':8}
for i in d1:
for j in d2:
if(i==j):
d1[i]=d1[i]+d2[j]
d2.update(d1)
print(d2)
|
5978e19ac3f68aad2e26d779e04e75ef4541fbfb | ICB-DCM/pyPESTO | /pypesto/logging.py | 1,902 | 4.0625 | 4 | """
Logging
=======
Logging convenience functions.
"""
import logging
def log(
name: str = 'pypesto',
level: int = logging.INFO,
console: bool = True,
filename: str = '',
):
"""
Log messages from `name` with `level` to any combination of console/file.
Parameters
----------
name:
The name of the logger.
level:
The output level to use.
console:
If True, messages are logged to console.
filename:
If specified, messages are logged to a file with this name.
"""
logger = logging.getLogger(name)
logger.setLevel(level)
if console:
ch = logging.StreamHandler()
ch.setLevel(level)
logger.addHandler(ch)
if filename:
fh = logging.FileHandler(filename)
fh.setLevel(level)
logger.addHandler(fh)
def log_to_console(level: int = logging.INFO):
"""
Log to console.
Parameters
----------
See the `log` method.
"""
log(level=level, console=True)
def log_to_file(
level: int = logging.INFO, filename: str = '.pypesto_logging.log'
):
"""
Log to file.
Parameters
----------
See the `log` method.
"""
log(level=level, filename=filename)
def log_level_active(logger: logging.Logger, level: int) -> bool:
"""Check whether the requested log level is active in any handler.
This is useful in case log expressions are costly.
Parameters
----------
logger:
The logger.
level:
The requested log level.
Returns
--------
active:
Whether there is a handler registered that handles events of importance
at least `level` and higher.
"""
for handler in logger.handlers:
# it is DEBUG=10, INFO=20, WARNING=30, ERROR=40, CRITICAL=50 increasing
if handler.level <= level:
return True
return False
|
dc3654a282490f6aa8045b86bec0d7dfc9bef37c | avinashraghuthu/Trees | /bst_check.py | 837 | 3.984375 | 4 | from tree_utils import *
from sys import maxint
def is_bst(root):
min_int = -maxint -1
return is_bst_util(root, min_int, maxint)
def is_bst_util(root, min_val, max_val):
if not root:
return True
if root.data < min_val or root.data > max_val:
return False
return is_bst_util(root.left, min_val, root.data) and \
is_bst_util(root.right, root.data, max_val)
# Driver program to test above function
def test():
# root = TreeNode(3)
# root.left = TreeNode(2)
# root.right = TreeNode(5)
# root.left.left = TreeNode(1)
# root.left.right = TreeNode(4)
l1 = TreeNode(4, None, None)
l2 = TreeNode(5, None, None)
l3 = TreeNode(6, None, None)
l4 = TreeNode(7, None, None)
l11 = TreeNode(2, l1, l2)
l21 = TreeNode(3, l3, l4)
root = TreeNode(1, l11, l21)
if is_bst(root):
print "Is BST"
else:
print "Not a BST" |
9ed9c26c05f38513362d91505c4d6f9adc002fa5 | sqw3Egl/Code_Academy | /Games_of_Chance/games.py | 1,062 | 3.890625 | 4 | import random
import time
money = 100
num = random.randint(1, 10)
#Casino Games - functions
def coin_flip():
bank = money
bet = input('How much do you want to bet? \n')
call = input('Make the call - type "heads" or "tails"... \n')
print('OK mate, ' + call + ' it is! \nFlipping the coin........')
time.sleep(3)
#print(num)
#Check the coin flip and return a result.
if call == 'heads' and num <= 5:
return 'WINNER!! You have won £' + str(int(bet) * 2) + '!!'
elif call == 'tails' and num <= 5:
return 'Sorry, you lost this time :(' + ' You lose your £' + str(bet) + ' bet.'
elif call == 'heads' and num >= 6:
return 'Sorry, you lost this time :(' + ' You lose your £' + str(bet) + ' bet.'
else:
return 'WINNER!! You have won £' + str(int(bet) * 2) + '!!'
##ToDo - Make the account balance update to reflect the result.
#Print the account balance
#print('You have £' + str(bank) + ' remaining in your account. Why not try again?')
#Test calls
print(coin_flip())
|
62cc0d48162ae0a9bef59c9cf20a8dd9e1e088e8 | chenxu0602/LeetCode | /2608.shortest-cycle-in-a-graph.py | 1,349 | 3.734375 | 4 | #
# @lc app=leetcode id=2608 lang=python3
#
# [2608] Shortest Cycle in a Graph
#
# @lc code=start
from collections import defaultdict
class Solution:
def findShortestCycle(self, n: int, edges: List[List[int]]) -> int:
# Assume a node is root and apply bfs search,
# where we recode the:
# dis[i] is the distance from root to i
# fa[i] is the father of i
# If two points met up and they are not father-son relation,
# they met in a cycle.
# The distance of circly is smaller or equal than dis[i] + dis[j] + 1.
# Time complexity: O(n^2)
# Space complexity: O(edges + n)
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
def dfs(node):
dist = [float("inf")] * n
dist[node] = 0
bfs = [node]
mn = float("inf")
for i in bfs:
for j in graph[i]:
if dist[j] == float("inf"):
dist[j] = dist[i] + 1
bfs.append(j)
elif dist[i] <= dist[j]:
mn = min(mn, dist[i] + dist[j] + 1)
return mn
res = min(map(dfs, range(n)))
return res if res < float("inf") else -1
# @lc code=end
|
a64aa03070144d88b6cee9034b4130655a5f61d6 | byrozaurowe/Computer-Science-studies | /4th semester/Python course - Python/Laboratorium 3/python5.py | 273 | 3.75 | 4 | def list_powerset(lst):
return reduce(lambda result, x: result + [subset + [x] for subset in result], lst, [[]])
def powerset(s):
return list(map(list, list_powerset(list(s))))
def main():
print(powerset([1, 3, 5, 7]))
if __name__ == "__main__":
main() |
95f34fccaa743bc000aa9bec0203db24009d00e2 | chenhaoxxx/pythonProject1 | /prac 4/lists_warmup.py | 599 | 4.0625 | 4 | numbers = [3, 1, 4, 1, 5, 9, 2]
numbers[0]#output 3
print(numbers[0])
numbers[-1]# output 2
print(numbers[-1])
numbers[3] #output 1
print(numbers[3])
numbers[:-1] # output 3,1,4,1,5,9
print(numbers[:-1])
numbers[3:4] #output 1
print(numbers[3:4])
5 in numbers # output True
print(5 in numbers)
7 in numbers # output False
print(7 in numbers)
"3" in numbers # output False
print("3" in numbers)
numbers + [6, 5, 3] #output [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
print(numbers + [6, 5, 3])
numbers[0]="ten"
print(numbers)
numbers[-1]=1
print(numbers)
del numbers[0:2]
print(numbers)
print(9 in numbers) |
ef0c94149ed13b8c6185293379d50e985e9af691 | tdrvlad/Fractals | /Sierpinsky_Triangle.py | 2,620 | 3.546875 | 4 | import graphics
import random
import time
import sys
#________________Parameters________________
scale = 500
start_triangle = ((1,1),(0.5,0),(0,1)) #Coordinates are in mirror
win=graphics.GraphWin("Figure",scale,scale)
win.setBackground("white")
colour=graphics.color_rgb(random.randint(0,255),random.randint(0,255),random.randint(0,255))
#________________Parameters________________
def draw_triangle(colour,points_coord):
vertices = []
for i in range(3):
(x,y) = points_coord[i] # Do this 3 times
vertices.append(graphics.Point(scale * x, scale * y)) # Add the (x, y) point to the vertices
triangle = graphics.Polygon(vertices)
triangle.setFill(colour)
triangle.draw(win)
return triangle
def undraw_triangle(triangle):
triangle.undraw()
return 1
def triangle_to_vertices(triangle):
vertices = triangle.getPoints()
points =()
for vertice in vertices:
x = vertice.getX() / scale
y = vertice.getY() / scale
points += ((x, y),)
return points
def sierpinsky_ieration(existing_triangles):
new_triangles = []
for triangle in existing_triangles:
vertices = triangle_to_vertices(triangle)
undraw_triangle(triangle)
no_vertices = len(vertices)
mid = ()
for i in range(no_vertices):
(x1,y1) = vertices[i]
(x2,y2) = vertices[(i + 1) % no_vertices]
mid += ( ( min(x1,x2) + (max(x1,x2) - min(x1,x2)) / 2, min(y1,y2) + (max(y1,y2) - min(y1,y2)) / 2 ), ) #Calculating the coordintates of the midpoint of the 2 points
for i in range(no_vertices):
new_triangle = (vertices[i],mid[i],mid[(i-1)%no_vertices])
new_triangles.append(draw_triangle(colour,new_triangle))
'''
Equivalent to:
(x0,y0),(x1,y1),(x2,y2) = triangle_to_vertices(triangle)
mid01 = (x0 + (x1-x0)/2, y0 + (y1 - y0)/2)
mid02 = (x0 + (x2-x0)/2, y0 + (y2 - y0)/2)
mid12 = (x1 + (x2-x1)/2, y1 + (y2 - y1)/2)
new_triangle = ((x0,y0),mid01,mid02)
new_triangles.append(draw_triangle(colour,new_triangle))
new_triangle = (mid02,mid12,(x2,y2))
new_triangles.append(draw_triangle(colour,new_triangle))
new_triangle = (mid01,(x1,y1),mid12)
new_triangles.append(draw_triangle(colour,new_triangle))
'''
undraw_triangle(triangle)
return new_triangles
def sierpinsky_triangle(no_generations):
triangles = []
triangles.append(draw_triangle(colour,start_triangle))
for i in range(no_generations):
time.sleep(1.5)
triangles = sierpinsky_ieration(triangles)
#________________Run________________
number_of_iterations = int((sys.argv)[1])
print(number_of_iterations)
sierpinsky_triangle(number_of_iterations)
win.getMouse()
win.close() |
dc153441de367d5c39d0362ad52a94b7781a8a07 | JonneyLloyd/CS4227 | /code/packages/tests/test_encryption.py | 604 | 4 | 4 | import unittest
from framework.encryption import Encryption, FernetEncryptor
class Tests(unittest.TestCase):
def encrypt_test(self):
text = "Hello World!"
encryption = Encryption(FernetEncryptor())
encrypted = encryption.encrypt(text)
self.assertTrue(text != encrypted)
self.assertTrue(isinstance(encrypted, bytes) and text != encrypted)
def decrypt_test(self):
text = "Hello World!"
encryption = Encryption(FernetEncryptor())
encrypted = encryption.encrypt(text)
self.assertTrue(text == encryption.decrypt(encrypted))
|
acb3ef6799b675d0cc82b4b06bd7e2c1ea31d432 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_135/2321.py | 1,565 | 3.65625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# untitled.py
#
# Copyright 2014 Phiradet Bangcharoensap <phiradet@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
def GetRow(n):
ans = []
for i in range(4):
line = raw_input().rstrip()
if i==n-1:
lineSpl = line.split(' ')
ans = map(int, lineSpl)
return ans
def PrintAnswer(caseNum, answer):
ansStr = ''
if len(answer)==1:
ansStr = str(answer.pop())
elif len(answer)==0:
ansStr = "Volunteer cheated!"
else:
ansStr = "Bad magician!"
print "Case #%d: %s"%(caseNum, ansStr)
def main():
allCaseNum = input()
for caseNum in range(allCaseNum):
rowNum = input()
selectedRow1 = GetRow(rowNum)
rowNum = input()
selectedRow2 = GetRow(rowNum)
answer = set(selectedRow1).intersection(set(selectedRow2))
PrintAnswer(caseNum+1, answer)
return 0
if __name__ == '__main__':
main()
|
80428764f62fdfa335ef61101b82a0fb3a908361 | jwxingfpp/learnPython | /assign.py | 898 | 4.15625 | 4 | # coding: utf-8
"""
@Time : 2019/8/8 上午9:57
@Author : xingjiawei
---------------------------
python赋值机制
"""
def new_print(x):
print 'value assign to:{}'.format(id(x))
def print_seperator():
print '-'*20
def print_info(s1, s2):
new_print(s1)
new_print(s2)
print s1 is s2
print_seperator()
def main():
# 不可变变量
x = 123
y = x # 此时,系统并没有为y分配内存,而是指向123的内存地址
print_info(x, y)
# y重新赋值,会产生新内存
y = 234
print_info(x, y)
s1 = 'lalala'
s2 = s1
print_info(s1, s2)
# 同理, s2也是
s2 = 'ha'*3
print_info(s1, s2)
##########################
# 可变 list
l1 = range(1, 4)
l2 = l1
print_info(l1, l2)
l2[0] = 4
print_info(l1, l2)
print_info(l1[0], l2[0])
if __name__ == '__main__':
main()
|
32caad0eb0a8c6b0e7807d75a6ef6bacdfc2036a | dward2/UnitTestingClass | /temp_conversion_script.py | 155 | 4 | 4 | temp_c_str = input("Enter temperature in degC: ")
temp_c = float(temp_c_str)
temp_f = 1.8 * temp_c + 32
print("The temperature is {} degF".format(temp_f))
|
6a0db2c2585e0461abe0f0763d4da6cccd75ea92 | SecretAardvark/Python | /pycrashcourse/ex10-7.py | 381 | 4.1875 | 4 | while True:
print("Enter two numbers to be added.")
print("type 'q' to quit.")
first_number = input("First number? ")
if first_number == 'q':
break
second_number = input("Second number? ")
try:
result = int(first_number) + int(second_number)
except ValueError:
print("You must enter two numbers.")
else:
print(result) |
5abdd95588c47155715d01f577536c7fc9b5e42b | bhushanwalke/DSA_Python | /Sorting/shellsort.py | 758 | 3.828125 | 4 | __author__ = 'bhushan'
def shellSort(items_list):
sublist = len(items_list)/2
while sublist > 0:
for start_pos in range(sublist):
gap_insertionSort(items_list, start_pos, sublist)
print(sublist, "", items_list)
sublist = sublist/2
def gap_insertionSort(items_list, start, gap):
for i in range(start + gap, len(items_list), gap):
current_value = items_list[i]
position = i
while position >= gap and items_list[position-gap] > current_value:
items_list[position] = items_list[position-gap]
items_list[position-gap] = current_value
position = position-gap
items_list = [54, 26, 93, 17, 77, 31, 44, 55, 20]
shellSort(items_list)
print items_list |
656870d4ba887cfd702750093ddb916cbc97eb9c | AnumHassan/Class-Work | /Table.py | 95 | 3.5 | 4 | able = int(input("Enter a No:" ))
for i in range(1,11):
print(able, "x",i,"=",str(able*i)) |
3a650742b98ce29296d00ce4e0be035e797a7db0 | snehilk1312/dataStructuresAlgorithms | /1_dataStructures/06_linkedListReversalRecursion.py | 1,002 | 4.25 | 4 | class Node:
# initializes a node
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
# initializes Linked List
def __init__(self, head=None):
self.head = head
# prints the LinkedList
def printList(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
# add nodes at beginning
def addNode(self, data):
newNode=Node(data)
temp = self.head
newNode.next = temp
self.head = newNode
def reverse(x):
if (x.next==None):
llist.head=x
return
reverse(x.next)
q = x.next
q.next = x
x.next = None
llist = LinkedList()
print('operations:\n1.add a node\n2.print linked list\n3.reverse the linked list\n0.quit\n')
q = int(input('enter your choice of operation:'))
while(q!=0):
if q==1:
value = int(input('enter the node value: '))
llist.addNode(value)
if q==2:
llist.printList()
if q==3:
reverse(llist.head)
q = int(input("enter your choice of operations:"))
print('PROGRAM FINISHED')
|
df79183023f114b28bafd5ac95c728a75d637353 | chris09/Python-tut | /PACKT_Learning_Python/03/looping.py | 800 | 3.703125 | 4 | for number in [1,2,3,4]:
print(number)
for number in range(5):
print(number)
surnames = ['Rivest', 'Shamir', 'Adleman']
for surname in surnames:
print(surname)
for position, surname in enumerate(surnames):
print(position, surname)
people = ['Jonas', 'Julio', 'Mike', 'Mez']
ages = [25, 30, 31, 39]
for position in range(len(people)):
print(people[position], ages[position])
import random
from faker import Factory
fake = Factory.create()
for i in range(random.randint(0, 30)):
print(fake.name())
print(fake.address())
people = ['Jonas', 'Julio', 'Mike', 'Mez']
ages = [25, 30, 31, 39]
nationalities = ['Belgium', 'Spain', 'England', 'Bangladesh']
for data in zip(people, ages, nationalities):
person, age, nationality = data
print(person, age, nationality)
|
6c51badb250e80e625115387ac81d808a6043aa2 | lowpro59/CS7641_SLearn | /decision_tree.py | 581 | 3.53125 | 4 | from sklearn.tree import DecisionTreeClassifier
tree = DecisionTreeClassifier(criterion='entropy', max_depth=3, random_state=0)
input_file = "adult_data.csv"
column_labels = ["age","workclass","fnlwgt","education","education-num","marital-status","occupation","relationship","race","sex",
"capital-gain","capital-loss","hours-per-week","native-country"]
# start with page 133 in the python book to read in .csv
#then get one hot encoder to work the categorical data
#might have to split the data into X and Y: where X is the data items and Y is the answer >=50K |
743b135a40b527c6d28ce0e2799b4ce38f7ccc37 | vladgithub211/pythonlesson3 | /dzpythonlesson3/3.py | 219 | 3.84375 | 4 | list = ['Олег','Дима','Вася','Рома']
print(list)
remove_element = list.pop(2)
print('Не приглашены:', remove_element)
remove = list.pop(0)
print('Не приглашены:', remove)
|
c586b1eb3dbe05af79e51172c666a80664b05655 | AyrtonDev/Curso-de-Python | /Exercicios/ex039.py | 854 | 3.765625 | 4 | from datetime import date
cores = {
'limpa' : '\033[m',
'lilas' : '\033[4;35m',
'vermelho' : '\033[1;31m'
}
nasc = int(input('Ano de nascimento: '))
data = date.today().year
idade = data - nasc
print('Quem nasceu em {} tem {} anos em {}'.format(nasc, idade, data))
if idade < 18:
print('Ainda falta {}{} anos{} para o alistamento'.format(cores['lilas'], (18 - idade), cores['limpa']))
print('Seu alistamento sera em {}{}{}.'.format(cores['vermelho'], (nasc + 18), cores['limpa']))
elif idade == 18:
print('Voce tem que se alistar {}IMEDIATAMENTE{}!'.format(cores['vermelho'], cores['limpa']))
else:
print('Voce ja deveria ter se alistado ha {}{} anos{}.'.format(cores['vermelho'], (idade - 18), cores['limpa']))
print('Seu alistamento foi em {}{}{}.'.format(cores['lilas'], (nasc + 18), cores['limpa'])) |
66aebf9f8756c7b4c2b0ddf4bd81f38412d28bdd | rangapv/pybasics | /array1.py | 134 | 3.828125 | 4 | #!/usr/bin/env python
a = [2,3,4,5]
print(a)
b = []
for i in a:
if ( i % 2) == 0:
print(i)
b.append(i)
print(b)
|
dcbbf7a80e9f36d917e9074687bdb5b425759fd4 | vinuv296/luminar_python_programs | /pythonProject2/flow_controls/pattern/pattern_3.py | 99 | 3.640625 | 4 | y=10
for i in range(0,y):
for j in range(y,0,-1):
print(j,end=" ")
print()
y-=1 |
0bcdcbed8c00b6df607edac8540a87dd295a6b79 | Murad255/Sharaga_ | /Моделирование МРС/Лаба_1/ЛАБ_1/kinematics.py | 8,353 | 3.640625 | 4 | import numpy as np
class Vector:
"""Vector represents translation and stores 3 values
Attributes
----------
x
The x value
y
The y value
z
The z value
"""
def __init__(self, x, y, z):
"""
Parameters
----------
x
The x value
y
The y value
z
The z value
"""
super(Vector, self).__init__()
self.x = x
self.y = y
self.z = z
@staticmethod
def zero():
"""Creates vector with zero x, y and z"""
return Vector(0, 0, 0)
@staticmethod
def lerp(start, end, t):
"""Calculates linear interpolation between start and end for given t"""
return start + t * (end + -1 * start)
def normalized(self):
"""Calculates colinear vector with length 1"""
return 1 / self.magnitude() * self
def magnitude(self):
"""Calculates Euclidean length of vector"""
return (self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5
def times(self, other):
"""Multiplies vector by scalar value
Parameters
----------
other
The scalar value to multiply on
"""
return Vector(
other * self.x,
other * self.y,
other * self.z
)
def cross(self, other):
return Vector(
self.y * other.z - self.z * other.y,
self.z * other.x - self.x * other.z,
self.x * other.y - self.y * other.x,
)
def dot(self, other):
return self.x * other.x + self.y * other.y + self.z * other.z
def angle_to(self, other, axis):
crossed = self.cross(other)
collinearity = crossed.dot(axis)
return np.arctan2(
crossed.magnitude(),
self.dot(other)
) * (1 if collinearity > 0.0 else -1)
def __str__(self):
return "[{}, {}, {}]".format(self.x, self.y, self.z)
def __repr__(self):
return "Vector[{}, {}, {}]".format(self.x, self.y, self.z)
def __add__(self, other):
if isinstance(other, Vector):
return Vector(
self.x + other.x,
self.y + other.y,
self.z + other.z
)
def __mul__(self, other):
return self.times(other)
def __rmul__(self, other):
return self.times(other)
class Quaternion:
"""Quaternion represents rotation and stores 4 values
Attributes
----------
w
The w value
x
The x value
y
The y value
z
The z value
"""
def __init__(self, w, x, y, z):
"""
Parameters
----------
w
The w value
x
The x value
y
The y value
z
The z value
"""
super(Quaternion, self).__init__()
self.w = w
self.x = x
self.y = y
self.z = z
@staticmethod
def identity():
"""Creates quaternion representing no rotation"""
return Quaternion(1, 0, 0, 0)
def rotate(self, vector):
"""Rotates given vector
Parameters
----------
vector
Vector to be rotated
"""
pure = Quaternion(0, vector.x, vector.y, vector.z)
rotated = self * pure * self.conjugate()
return Vector(rotated.x, rotated.y, rotated.z)
def magnitude(self):
return (self.w ** 2 + self.x ** 2 + self.y ** 2 + self.z ** 2) ** 0.5
def normalized(self):
return 1 / self.magnitude() * self
def dot(self, other):
return self.w * other.w + self.x * other.x + self.y * other.y + self.z * other.z
@staticmethod
def slerp(start, end, t):
dot = start.dot(end)
if dot < 0.0:
start = -1 * start
dot = -dot
if dot >= 1.0:
return start
theta = np.arccos(dot) * t
q = (end + -dot * start).normalized()
return np.cos(theta) * start + np.sin(theta) * q
def conjugate(self):
"""Calculates quaternion representing reverse rotation"""
return Quaternion(self.w, -self.x, -self.y, -self.z)
def multiply(self, other):
"""Multiplies quaternion on other quaternion
Parameters
----------
other
The other quaternion to multiply on
"""
return Quaternion(
self.w * other.w - self.x * other.x - self.y * other.y - self.z * other.z,
self.w * other.x + self.x * other.w + self.y * other.z - self.z * other.y,
self.w * other.y - self.x * other.z + self.y * other.w + self.z * other.x,
self.w * other.z + self.x * other.y - self.y * other.x + self.z * other.w
)
def plus(self, other):
return Quaternion(
self.w + other.w,
self.x + other.x,
self.y + other.y,
self.z + other.z
)
def times(self, other):
"""Multiplies quaternion on scalar
Parameters
----------
other
The scalar value to multiply on
"""
return Quaternion(
other * self.w,
other * self.x,
other * self.y,
other * self.z
)
@staticmethod
def from_angle_axis(angle, axis, math_source=np, unit=True):
"""Calculates quaternion representing rotation around given axis on given angle
Parameters
----------
angle
The rotation angle in radians
axis
The rotation axis
math_source
The source of sin and cos operations, default is numpy
unit
Marks if axis is considered unit, default is True
"""
if not unit:
axis = axis.normalized()
c = math_source.cos(angle / 2)
s = math_source.sin(angle / 2)
return Quaternion(
c,
s * axis.x,
s * axis.y,
s * axis.z
)
def __str__(self):
return "[{}, {}, {}, {}]".format(self.w, self.x, self.y, self.z)
def __repr__(self):
return "Quaternion[{}, {}, {}, {}]".format(self.w, self.x, self.y, self.z)
def __mul__(self, other):
if isinstance(other, Vector):
return self.rotate(other)
if isinstance(other, Quaternion):
return self.multiply(other)
return self.times(other)
def __add__(self, other):
return self.plus(other)
def __rmul__(self, other):
return self.times(other)
class Transform:
"""Transform represents translation and rotation
Attributes
----------
translation
The translation vector
rotation
The rotation quaternion
"""
def __init__(self, translation: Vector, rotation: Quaternion):
"""
Parameters
----------
translation
The translation vector
rotation
The rotation quaternion
"""
super(Transform, self).__init__()
self.translation = translation
self.rotation = rotation
@staticmethod
def identity():
"""Creates Transform representing no translation and no rotation"""
return Transform(
Vector.zero(),
Quaternion.identity()
)
def inverse(self):
conj = self.rotation.conjugate()
return Transform(
conj * (-1 * self.translation),
conj
)
@staticmethod
def lerp(start, end, t):
return Transform(
Vector.lerp(start.translation, end.translation, t),
Quaternion.slerp(start.rotation, end.rotation, t)
)
def __str__(self):
return "[\n\t{}\n\t{}\n]".format(str(self.translation), str(self.rotation))
def __repr__(self):
return "Transform[\n\t{}\n\t{}\n]".format(str(self.translation), str(self.rotation))
def __add__(self, other):
if isinstance(other, Transform):
return Transform(
self.translation + self.rotation * other.translation,
self.rotation * other.rotation
)
if isinstance(other, Vector):
return self.translation + self.rotation * other
|
2adbdeaf4910f88e4cddb9f9a1dcd7c057e49990 | SebastianCiesla/JSP-2020 | /Lista 6/trojkat.py | 1,192 | 3.671875 | 4 | #-------------------------------Zadanie 1-----------------------------------
import math
def boki(a,b,c):
#sprawdzanie czy trojkat o takich bokach istnieje
l=[a,b,c]
maxn=max(l)
l.remove(maxn)
ls=sum(l)
#Sprawdzanie warunku na istnienie trojkata
if maxn<=ls:
#obwód
obwod=a+b+c
print('Obwód trójkąta: ',obwod)
#pole - wzor herona
s=obwod/2
pole=math.sqrt(s*(s-a)*(s-b)*(s-c))
print('Pole trójkąta: ',pole)
# czy trojkat jest rownoramienny/ rownoboczny/ roznoboczny
l2={a,b,c}
if len(l2)==3:
print('Trójkąt różnoboczny')
elif len(l2)==2:
print('Trójkąt równoramienny')
else:
print('Trójkąt równoboczny')
# czy rozwartokatny / prostokatny / ostrokatny
c=maxn**2
ab2=sum([i**2 for i in l])
if c>ab2:
print('Trójąt jest rozwartokatny')
elif c<ab2:
print('Trójąt jest ostrokatny')
else:
print('Trójąt jest prostokatny')
else:
print('Nie są spełnione warunki trojkata')
|
750a9491b7eea753913486cb467385535a9c7e00 | HUGGY1174/MyPython | /Chapter02/P02.py | 273 | 4 | 4 | first = int(input("첫번째 수를 입력하시오:"))
second = int(input("두번째 수를 입력하시오:"))
third = int(input("세번째 수를 입력하시오:"))
avg = (first + second + third)/3
print(first, second, third, "의 평균은", avg, "입니다.")
|
ac8fa91f33cd0b2d7a6a0f05e5cd63f071549448 | Borgaard/sf-wdi-51-assignments | /brandon-vagarioustoast/week-8/codebar/codebar.py | 1,682 | 4.03125 | 4 | class Member():
def __init__(self, full_name):
self.full_name = full_name
def introduce(self):
print(f'My name is {self.full_name}')
class Student(Member):
def __init__(self, full_name, reason):
Member.__init__(self, full_name)
self.reason = reason
class Instructor(Member):
def __init__(self, full_name, bio='Associate instructor at Codebar.'):
Member.__init__(self, full_name)
self.bio = bio
self.skills = []
def add_skill(self, new_skill):
self.skills.append(new_skill)
# WORKSHOPS
class Workshop():
def __init__(self, date, subject):
self.date = date
self.subject = subject
self.instructors = []
self.students = []
def add_participant(self, member):
if isinstance(member, Student):
self.students.append(member)
else:
self.instructors.append(member)
def print_details(self):
print(
f'{self.subject}, taught by {self.instructors} will be held on {self.date}.')
workshop = Workshop("12/03/2014", "Shutl")
jane = Student(
"Jane Doe", "I am trying to learn programming and need some help")
lena = Student("Lena Smith", "I am really excited about learning to program!")
vicky = Instructor("Vicky Python", "I want to help people learn coding.")
vicky.add_skill("HTML")
vicky.add_skill("JavaScript")
nicole = Instructor(
"Nicole McMillan", "I have been programming for 5 years in Python and want to spread the love")
nicole.add_skill("Python")
workshop.add_participant(jane)
workshop.add_participant(lena)
workshop.add_participant(vicky)
workshop.add_participant(nicole)
workshop.print_details()
|
068587a234ca6f946ad11de2a45856538ef263d7 | gyang274/leetcode | /src/0800-0899/0814.prune.bt.py | 889 | 3.6875 | 4 | from config.treenode import TreeNode, listToTreeNode
class Solution:
def recursive(self, node):
l = 0
if node.left:
l = self.recursive(node.left)
if not l:
node.left = None
r = 0
if node.right:
r = self.recursive(node.right)
if not r:
node.right = None
return node.val + l + r
def pruneTree(self, root: TreeNode) -> TreeNode:
if root:
x = self.recursive(root)
if not x:
root = None
return root
if __name__ == '__main__':
solver = Solution()
cases = [
[],
[0],
[1],
[1,None,0,0,1],
[1,0,1,0,0,0,1],
[1,1,0,1,1,0,1,0],
]
cases = [
listToTreeNode(x) for x in cases
]
rslts = [
solver.pruneTree(root) for root in cases
]
for cs, rs in zip(cases, rslts):
print(f"case:\n{cs.display() if cs else None}\nsolution:\n{rs.display() if rs else None}")
|
081bd103d01857d85d9732cd4ab7e3d1600e53ef | miguelgamendes/SDM_CPAB | /Clients/Healthclub.py | 728 | 3.578125 | 4 | from User import User
# a health club can insert TRAINING data for a patient
# who is a member of the health club
class Healthclub(User):
def __init__(self, ID, insertion_key):
attributes = {str(ID), "HEALTHCLUB", "TRAINING"}
User.__init__(self, ID, attributes)
self.insertion_key = insertion_key
# inserts data for a given ID, ID has to be a member of the healthclub
def insert(self, Data, TID):
# policy indicates that it can only be decrypted if you are a patient with ID and
# that it is TRAINING related data
policy = "TRAINING and (PATIENT and " + str(TID) + ")"
User.insert(self, Data, policy, TID, self.insertion_key)
def retrieve(self):
pass |
cfa407011010aef35888744f742138b1e5497c2a | kyosukekita/ROSALIND | /Algorithmic Heights/median.py | 379 | 3.625 | 4 | file = open('Desktop/Downloads/rosalind_med.txt').read()
n=int(file.split()[0])
A=[int(i) for i in file.split()[1:n+1]]
k=int(file.split()[-1])
def qSort(a):#クイックソート
if len(a) in (0,1):
return a
p=a[-1]
l=[x for x in a[:-1] if x<=p]
r=[x for x in a[:-1] if x>p ]
return qSort(l)+[p]+qSort(r)
sort=qSort(A)
print(sort[k-1])
|
48fec799ce043385b02ab40c91624278759d4dd4 | UX404/Leetcode-Exercises | /#1295 Find Numbers with Even Number of Digits.py | 784 | 4.3125 | 4 | '''
Given an array nums of integers, return how many of them contain an even number of digits.
Example 1:
Input: nums = [12,345,2,6,7896]
Output: 2
Explanation:
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).
6 contains 1 digit (odd number of digits).
7896 contains 4 digits (even number of digits).
Therefore only 12 and 7896 contain an even number of digits.
Example 2:
Input: nums = [555,901,482,1771]
Output: 1
Explanation:
Only 1771 contains an even number of digits.
Constraints:
1 <= nums.length <= 500
1 <= nums[i] <= 10^5
'''
class Solution:
def findNumbers(self, nums: List[int]) -> int:
return sum(len(str(n)) % 2 == 0 for n in nums) |
07ec5fca7ed56878155a0583b7a5eac171d5bca7 | jiajingchen/Projects-for-Rice-Coursera-Programming-in-Python | /Yahtzee/Done1.py | 3,927 | 3.734375 | 4 | """
Planner for Yahtzee
Simplifications: only allow discard and roll, only score against upper level
"""
# Used to increase the timeout, if necessary
import codeskulptor
codeskulptor.set_timeout(20)
def gen_all_sequences(outcomes, length):
"""
Iterative function that enumerates the set of all sequences of
outcomes of given length.
"""
answer_set = set([()])
for dummy_idx in range(length):
temp_set = set()
for partial_sequence in answer_set:
for item in outcomes:
new_sequence = list(partial_sequence)
new_sequence.append(item)
temp_set.add(tuple(new_sequence))
answer_set = temp_set
return answer_set
def max_repeats(seq):
"""
Compute the maxium number of times that an outcome is repeated
in a sequence
"""
item_count = [seq.count(item) for item in seq]
return max(item_count)
def score(hand):
"""
Compute the maximal score for a Yahtzee hand according to the
upper section of the Yahtzee score card.
hand: full yahtzee hand
Returns an integer score
"""
each_box=[int(item)*hand.count(item) for item in hand]
return max(each_box)
def expected_value(held_dice, num_die_sides, num_free_dice):
"""
Compute the expected value based on held_dice given that there
are num_free_dice to be rolled, each with num_die_sides.
held_dice: dice that you will hold
num_die_sides: number of sides on each die
num_free_dice: number of dice to be rolled
Returns a floating point expected value
"""
outcomes=[item for item in range(1,num_die_sides+1)]
print outcomes
all_outcomes=gen_all_sequences(outcomes, num_free_dice)
sum_outcomes=0.0
for seq in all_outcomes:
sum_outcomes+=score(seq)
return sum_outcomes/len(all_outcomes)
print expected_value((1,1), 6,4)
def gen_all_holds(hand):
"""
Generate all possible choices of dice from hand to hold.
hand: full yahtzee hand
Returns a set of tuples, where each tuple is dice to hold
"""
answer_set=set([()])
hand_len=len(hand)
list_hand=list(hand)
all_idx=gen_all_sequences((0,1),hand_len)
for each_idx in all_idx:
temp_answer=[]
for each_num in range(hand_len):
if each_idx[each_num]==1:
add_item=list_hand[each_num]
temp_answer.append(add_item)
answer_set.add(tuple(temp_answer))
return answer_set
def strategy(hand, num_die_sides):
"""
Compute the hold that maximizes the expected value when the
discarded dice are rolled.
hand: full yahtzee hand
num_die_sides: number of sides on each die
Returns a tuple where the first element is the expected score and
the second element is a tuple of the dice to hold
"""
max_expected=0.0
max_choice=[]
for choice in gen_all_holds(hand):
held_dice=choice
num_free_dice=len(hand)-len(held_dice)
current_expected=expected_value(held_dice, num_die_sides, num_free_dice)
if current_expected>= max_expected:
max_expected= current_expected
max_choice=list(choice)
return_tuple=tuple(max_choice)
return (max_expected, return_tuple)
def run_example():
"""
Compute the dice to hold and expected score for an example hand
"""
num_die_sides = 6
hand = (1, 1, 1, 5, 6)
hand_score, hold = strategy(hand, num_die_sides)
print "Best strategy for hand", hand, "is to hold", hold, "with expected score", hand_score
run_example()
#import poc_holds_testsuite
#poc_holds_testsuite.run_suite(gen_all_holds)
|
0cf23397c4927300df972ca4cf92b541a496e7b5 | kofinyx/test | /chap2_2.py | 366 | 3.703125 | 4 | '''
Created on Jan 19, 2018
@author: ehagan
'''
# more tuple unpacking
print(divmod(20, 8))
t = (30, 8)
print(divmod(*t))
# unpacking by prefixing an arg with *
for x in [(2, 4), (1, 2, 5), (3, 6, 1, 4)]:
print('Adding {1} items to get {0}'.format(sum(x), len(x)))
*head, a, b = range(6)
print(head)
a, d, *head, e, f = range(6)
print(head)
|
b53a824e340838d6025308d26b30ab6d4d1cde21 | a1ip/Checkio-26 | /absolute_sorting.py | 445 | 4.125 | 4 | #Input: An array of numbers , a tuple.
#Output: The list or tuple (but not a generator) sorted by absolute values in ascending order.
def checkio(numbers_array):
abs_numbers = sorted([i if i > 0 else -i for i in numbers_array])
answer = []
for absnum in abs_numbers:
if absnum not in numbers_array:
answer.append(absnum * (-1))
else:
answer.append(absnum)
return answer
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.