text stringlengths 37 1.41M |
|---|
'''
problem statement: https://www.hackerearth.com/practice/algorithms/searching/linear-search/practice-problems/algorithm/monk-takes-a-walk/
'''
def isVowels(chr):
vowels = ['A', 'E', 'I', 'O', 'U' ,'a','e','i','o','u']
if chr in vowels:
return True
else:
return False
for t in range(int(input())):
trees = list(map(isVowels,list(input())))
print(trees.count(True))
|
print ("--Calculator--")
while True:
inp1 = input("Masukkan angka pertama: ")
inp2 = input("Masukkan angka kedua: ")
print ( "1 Bagi \n"
"2 Kali \n"
"3 Jumlah \n"
"4 Kurang\n"
"5 Exit")
op = input("Operator yang ingin digunakan? ")
if op == "1":
rslt = float(inp1) / float(inp2)
print (rslt)
elif op == "2":
rslt = float(inp1) * float(inp2)
print (rslt)
elif op == "3":
rslt = float(inp1) + float(inp2)
print (rslt)
elif op == "4":
rslt = float(inp1) - float(inp2)
print (rslt)
elif op == "5":
break
else:
print ("Invalid Input")
import random
real_ans = random.randint(1,10) |
real_user = 'harris'
real_pass = '1234'
tries = int(input("Berapa Kali Coba: "))
for tries in range(tries,0,-1):
print (f"Anda memiliki {tries} coba")
guess_user = input('Masukkan username: ')
guess_pass = input('Masukkan password: ')
if guess_user == real_user and guess_pass == real_pass:
print("==Login Berhasil==")
break
else:
print("==Login Invalid==")
print ("==Exiting Loop==") |
class A:
pass
class B:
pass
class C:
pass
class D(A):
pass
class E(A, B):
pass
class F(E, C):
pass
a, b, c, d, e, f = A(), B(), C(), D(), E(), F()
print((isinstance(a, A)))
print((isinstance(a, B)))
print((isinstance(a, C)))
print((isinstance(a, D)))
print((isinstance(a, E)))
print((isinstance(a, F)))
print("---")
print((isinstance(b, A)))
print((isinstance(b, B)))
print((isinstance(b, C)))
print((isinstance(b, D)))
print((isinstance(b, E)))
print((isinstance(b, F)))
print("---")
print((isinstance(c, A)))
print((isinstance(c, B)))
print((isinstance(c, C)))
print((isinstance(c, D)))
print((isinstance(c, E)))
print((isinstance(c, F)))
print("---")
print((isinstance(d, A)))
print((isinstance(d, B)))
print((isinstance(d, C)))
print((isinstance(d, D)))
print((isinstance(d, E)))
print((isinstance(d, F)))
print("---")
print((isinstance(e, A)))
print((isinstance(e, B)))
print((isinstance(e, C)))
print((isinstance(e, D)))
print((isinstance(e, E)))
print((isinstance(e, F)))
print("---")
print((isinstance(f, A)))
print((isinstance(f, B)))
print((isinstance(f, C)))
print((isinstance(f, D)))
print((isinstance(f, E)))
print((isinstance(f, F)))
print("---")
|
s = set([1, 2, 3])
t = set([3, 4, 5])
s.symmetric_difference_update(t)
t.symmetric_difference_update(s)
print(s)
print((s == t))
print((s == set([1, 2, 4, 5])))
print((s == set([1, 2, 3])))
|
import random
random.seed(0)
print("randint")
print(random.randint(4, 9))
print(random.randint(4, 9))
print(random.randint(4, 9))
print(random.randint(4, 9))
print(random.randint(4, 9))
print(random.randint(4, 9))
print("randrange")
print(random.randrange(4, 9))
print(random.randrange(4, 9))
print(random.randrange(4, 9))
print(random.randrange(4, 9))
print(random.randrange(4, 9))
print(random.randrange(4, 9))
print("step -2")
print(random.randrange(8, -4, -2))
print(random.randrange(8, -4, -2))
print(random.randrange(8, -4, -2))
print(random.randrange(8, -4, -2))
print(random.randrange(8, -4, -2))
print(random.randrange(8, -4, -2))
print(random.randrange(8, -4, -2))
print(random.randrange(8, -4, -2))
print("step 3")
print(random.randrange(5, 15, 3))
print(random.randrange(5, 15, 3))
print(random.randrange(5, 15, 3))
print(random.randrange(5, 15, 3))
print(random.randrange(5, 15, 3))
print(random.randrange(5, 15, 3))
print(random.randrange(5, 15, 3))
print(random.randrange(5, 15, 3))
print("list")
l = list(range(9))
print(random.choice(l))
random.shuffle(l)
print(l)
print(random.choice(l))
random.shuffle(l)
print(l)
print(random.choice(l))
random.shuffle(l)
print(l)
print(random.choice(l))
random.shuffle(l)
print(l)
print(random.choice(l))
random.shuffle(l)
print(l)
print(random.choice(l))
random.shuffle(l)
print(l)
print(random.choice(l))
random.shuffle(l)
print(l)
print(random.choice(l))
random.shuffle(l)
print(l)
print(random.choice(l))
random.shuffle(l)
print(l)
|
class A:
pass
a = A()
print((isinstance([], list)))
print((isinstance([], dict)))
print((isinstance([], str)))
print((isinstance([], tuple)))
print((isinstance([], A)))
print("---")
print((isinstance({}, list)))
print((isinstance({}, dict)))
print((isinstance({}, str)))
print((isinstance({}, tuple)))
print((isinstance({}, A)))
print("---")
print((isinstance("", list)))
print((isinstance("", dict)))
print((isinstance("", str)))
print((isinstance("", tuple)))
print((isinstance("", A)))
print("---")
print((isinstance((), list)))
print((isinstance((), dict)))
print((isinstance((), str)))
print((isinstance((), tuple)))
print((isinstance((), A)))
print("---")
print((isinstance(a, list)))
print((isinstance(a, dict)))
print((isinstance(a, str)))
print((isinstance(a, tuple)))
print((isinstance(a, A)))
print("---")
|
l = ["h", "e", "l", "l", "o"]
print((l.index("l")))
print((l.index("l", 2)))
print((l.index("l", 3)))
print((l.index("l", 2, 3)))
print((l.index("l", 3, 4)))
print((l.index("l", 2, -1)))
print((l.index("l", 2, -2)))
print((l.index("l", 3, -1)))
try:
print((l.index("l", 4)))
except ValueError as e:
print((repr(e)))
try:
print((l.index("l", -1)))
except ValueError as e:
print((repr(e)))
try:
print((l.index("l", 2, 2)))
except ValueError as e:
print((repr(e)))
try:
print((l.index("l", 3, 2)))
except ValueError as e:
print((repr(e)))
try:
print((l.index("l", 3, -2)))
except ValueError as e:
print((repr(e)))
try:
print((l.index("l", 3, 0)))
except ValueError as e:
print((repr(e)))
try:
print((l.index("l", 4.3)))
except TypeError as e:
print((repr(e)))
try:
print((l.index("l", 3, 0.6)))
except TypeError as e:
print((repr(e)))
|
def helper(got, expect):
if got == expect:
print(True)
else:
print(False, expect, got)
print("\nstr.capitalize")
helper("hello world".capitalize(), "Hello world")
helper("HELLO WorlD".capitalize(), "Hello world")
print("\nstr.center")
helper("12345".center(7), " 12345 ")
helper("12345".center(8), " 12345 ")
print("\nstr.count")
helper("abcd abcba ".count("abc"), 2)
helper("aaaaaaaaaaa ".count("aa"), 5)
print("\nstr.find")
helper("hello world".find("l"), 2)
helper("hello world".find("X"), -1)
helper("hello world".find("l", 3), 3)
print("\nstr.index")
helper("hello world".index("l"), 2)
helper("hello world".index("l", 3), 3)
print("\nstr.isdigit")
helper("hello".isdigit(), False)
helper("1234".isdigit(), True)
helper("".isdigit(), False)
helper("123.45".isdigit(), False)
print("\nstr.isalpha")
helper("ABCabc".isalpha(), True)
helper("abc123".isalpha(), False)
helper("ABC abc".isalpha(), False)
helper("".isalpha(), False)
print("\nstr.isalnum")
helper("ABCabc".isalnum(), True)
helper("abc123".isalnum(), True)
helper("ABC abc".isalnum(), False)
helper("".isalnum(), False)
print("\nstr.islower")
helper("abc".islower(), True)
helper("abc123".islower(), True)
helper("ABC abc".islower(), False)
helper("".islower(), False)
print("\nstr.isupper")
helper("ABC".isupper(), True)
helper("ABC123".isupper(), True)
helper("ABC abc".isupper(), False)
helper("".isupper(), False)
print("\nstr.isnumeric")
helper("123".isnumeric(), True)
helper("abc123".isnumeric(), False)
helper("1 2 3".isnumeric(), False)
helper("123.4".isnumeric(), False)
helper("".isnumeric(), False)
print("\nstr.join")
helper("-".join("1234"), "1-2-3-4")
helper("-".join(("1", "2", "3", "4")), "1-2-3-4")
helper("-".join(["1", "2", "3", "4"]), "1-2-3-4")
print("\nstr.ljust")
helper("12345".ljust(8), "12345 ")
helper(" 12345".ljust(8), " 12345")
print("\nstr.lower")
helper("HELLO".lower(), "hello")
helper("Hello woRLd!".lower(), "hello world!")
helper("hello".lower(), "hello")
helper("".lower(), "")
print("\nstr.lstrip")
helper(" hello".lstrip(), "hello")
helper(" ".lstrip(), "")
print("\nstr.partition")
helper("hello".partition("h"), ("", "h", "ello"))
helper("hello".partition("l"), ("he", "l", "lo"))
helper("hello".partition("o"), ("hell", "o", ""))
helper("hello".partition("x"), ("hello", "", ""))
print("\nstr.replace")
helper("hello".replace("l", "L"), "heLLo")
helper("hello wOrld!".replace("o", ""), "hell wOrld!")
helper("".replace("", "hello"), "hello")
helper("hello".replace("", "!"), "!h!e!l!l!o!")
helper("abcabcaaaabc".replace("abc", "123"), "123123aaa123")
print("\nstr.rfind")
helper("hello world".rfind("l"), 9)
helper("hello world".rfind("X"), -1)
helper("hello world".rfind("l", 3), 9)
print("\nstr.rindex")
helper("hello world".rindex("l"), 9)
helper("hello world".rindex("l", 3), 9)
print("\nstr.rjust")
helper("12345".rjust(8), " 12345")
helper("12345 ".rjust(8), "12345 ")
print("\nstr.rpartition")
helper("hello".rpartition("h"), ("", "h", "ello"))
helper("hello".rpartition("l"), ("hel", "l", "o"))
helper("hello".rpartition("o"), ("hell", "o", ""))
helper("hello".rpartition("x"), ("", "", "hello"))
print("\nstr.rstrip")
helper("hello ".rstrip(), "hello")
helper(" ".rstrip(), "")
print("\nstr.split")
helper("".split(), [])
helper("".split(None), [])
helper("hello".split(), ["hello"])
helper("hello".split(None), ["hello"])
helper("hello world ! ".split(), ["hello", "world", "!"])
helper("".split("a"), [""])
helper("".split("a", 1), [""])
helper("hello".split("l"), ["he", "", "o"])
helper("hello".split("l", 1), ["he", "lo"])
print("\nstr.strip")
helper(" hello ".strip(), "hello")
helper(" ".strip(), "")
print("\nstr.upper")
helper("hello".upper(), "HELLO")
helper("Hello woRLd!".upper(), "HELLO WORLD!")
helper("HELLO".upper(), "HELLO")
helper("".upper(), "")
|
def f(n):
for i in range(n):
yield i
g = f(5)
print((next(g)))
print((next(g)))
print((next(g)))
print((next(g)))
|
c = "squirrel"
time = 0
def x():
global time
time += 1
if time == 1:
b = "dog"
else:
b = "banana"
print((b, c))
def y(d):
a = "cat"
print((a, b, d))
def z():
for i in range(10 * time):
yield i, a, b, c, d
return z
return y("blorp")
for v in x()():
print(v)
for v in x()():
print(v)
|
print(int())
print(type(int()))
# integers and long integers
print(int(123))
print(int(-123))
print(int(456))
print(int(-456))
# floating point
print(int(-1.1))
print(int(-0.9))
print(int(-0.1))
print(int(0.5))
print(int(0.9))
print(int(1.1))
# string
print(int("10"))
print(int(" -1234 "))
print(int("101", 0))
print(int("101", 2))
print(int("101", 8))
print(int("101", 10))
print(int("A", 16))
|
l = [1, 2, 3, 4]
t = (1, 2, 3, 4)
d = {1: 2, 3: 4}
s = "1234"
print(list(zip()))
print(list(zip(l)), list(zip(t)), list(zip(d)), list(zip(s)))
print(list(zip(l, t)), list(zip(l, d)), list(zip(l, s)))
print(list(zip(t, d)), list(zip(t, s)))
print(list(zip(d, s)))
print(list(zip(l, t, s)))
print(list(zip(l, t, s, d)))
z = list(zip(l, t, s))
print(list(zip(*z)))
z = list(zip(l, t, s, d))
print(list(zip(*z)))
|
a = [1, 2, 3, 4, 5, 6]
b = [9, 9, 9]
a[1:5] = b
print(a)
mylist = ["a", "b", "c", "d"]
d = {"1": 1, "2": 2}
mylist[0:2] = d
print(mylist)
mylist[1:3] = "temp"
print(mylist)
mylist[:] = ["g", "o", "o", "d"]
print(mylist)
|
myList = [1, 2, 3, "foo", 4, 5, True, False]
print(myList.index("foo"))
print("foo" in myList)
print(myList.index(True))
print(2 in myList)
|
import sys
import json
def extract_tweets(tweet_file):
'''Function which return a list of tweets given a raw tweet txt file. '''
tweets = []
for line in tweet_file.readlines():
try:
tweet =json.loads(line)
tweet_text=tweet[u'text']
tweets.append (tweet_text.replace("\n",""))
except KeyError:
if tweet.has_key(u'delete') : pass
return tweets
def extract_hashtag(tweet_file):
'''Given a file of tweets the function extract all the hashtags and count them giving back a dictionary and the count '''
dict_hashtag={}
for line in tweet_file.readlines():
try:
tweet =json.loads(line)
for hashtag_temp in tweet[u'entities'][u'hashtags']:
if not hashtag_temp[u'text'] in dict_hashtag.keys(): dict_hashtag[hashtag_temp[u'text']]=1.
else: dict_hashtag[hashtag_temp[u'text']]+=1.
except KeyError:
if tweet.has_key(u'delete') : pass
return dict_hashtag
def main():
tweet_file = open(sys.argv[1])
dict_hashtag = {}
dict_hashtag = extract_hashtag(tweet_file)
tweet_file.close()
## We order order our and print the first 10
counter=0
for hashtag in sorted(dict_hashtag, key=dict_hashtag.get, reverse=True):
print hashtag.replace("\n",""), " ",dict_hashtag[hashtag]
counter+=1
if counter==10: break
if __name__ == '__main__':
main()
|
import datetime
year = datetime.date.today().year
birth_year = input('What year were you born?')
print(int(year) - int(birth_year))
|
#!/usr/bin/python
mylist=['Das Wetter']
#mylist[2]='ist'
mylist.insert(2, 'ist')
mylist.insert(3, 'sehr')
mylist.append('schoen')
print(mylist) # Das Ergebnis? |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Creation: 07.04.2015
# Last Update: 07.04.2015
#
# Copyright (c) 2015 by Georg Kainzbauer <http://www.gtkdb.de>
#
# 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.
#
def fibonacci(n):
a, b = 1, 1
print(a)
for i in range(1,n,1):
print(b)
a, b = b, a+b
if __name__ == '__main__':
fibonacci(20) |
#!/usr/bin/env python
from time import sleep
number = float(raw_input("Give me a number: "))
if number % 2 == 0:
print number**4
else:
print number
sleep (5) |
import re
from collections import defaultdict, Counter
class Coordinate:
def __init__(self, input_string = '', x = None, y = None):
if (x == None and y == None):
# Example: '220, 349'
regex = '(\d+), (\d+)'
(x,y) = re.findall(regex,input_string)[0]
self.x = int(x)
self.y = int(y)
else:
self.x = x
self.y = y
coords = [Coordinate(input_string=l) for l in open('input.txt','r').readlines()]
def manhattan_distance(c1,c2):
x_dist = abs(c1.x-c2.x)
y_dist = abs(c1.y-c2.y)
return x_dist + y_dist
def find_closest(target_coord,coords):
min_dist = 999999
min_coord = None
tie = False
for coord in coords:
dist = manhattan_distance(target_coord,coord)
if dist == min_dist:
tie = True
min_coord = None
elif dist < min_dist:
tie = False
min_coord = coord
min_dist = dist
if tie == False:
return min_coord
min_x = min([coord.x for coord in coords])
max_x = max([coord.x for coord in coords])
min_y = min([coord.y for coord in coords])
max_y = max([coord.y for coord in coords])
map = defaultdict(lambda: defaultdict(str))
# if you win a coordinate on the border of the map, you win infinite coordinates
# we need to remove these from our result set
edge_winners = set()
for x in range(min_x,max_x + 1):
for y in range(min_y,max_y + 1):
closest = find_closest(Coordinate(x=x, y=y),coords)
if closest != None:
map[x][y] = closest
if (x == min_x or x == max_x or y == min_y or y == max_y):
edge_winners.add(closest)
results = Counter([map[x][y] for x in map.keys() for y in map[x].keys()])
print ('Answer 1:')
print (max([count for (result,count) in results.most_common() if result not in edge_winners]))
|
"""
Hello freinds Today you will make a Tic-Tac-Toe;
Language:Python;
library:Tkinter;
Let's start...
"""
#First import everything from Tkinter.
from tkinter import *
"""
Now You are import messegabox from tkinter.
The messageboxes is used when any user is win
or
draw.
"""
from tkinter import messagebox
"""
rooms variable is used to understand the 9 boxes of the board of Tic-Tac-Toe.
9 boxes info are store as the data type of python array.
"""
rooms=[]
"""
Turn variable is store a string.
The string data determine that which player's turn now.
By default the string is "x" because on tic-tac-toe "x" turn is first than "o".
when "x" is clicked than turn="o".
"""
turn="x"
"""
x win and o_win store a integer number.
The integer numbers is default is 0.
when x win then x_win+=1
And
when o win then o_win+=1.
"""
x_win=0
o_win=0
"""
The started variable store that game is started or not if started than started=True otherwise False.
By default it is False because the first the game is not start.
"""
started=False
"""
This is a function named make_all_none.
this function make all the boxes " ".
It's vary important to restart.
"""
def make_all_none():
if len(rooms)==0:
for i in range(9):
rooms.append(" ")
else:
for i in range(9):
rooms[i]=" "
button_0['text']=rooms[0]
button_1['text']=rooms[1]
button_2['text']=rooms[2]
button_3['text']=rooms[3]
button_4['text']=rooms[4]
button_5['text']=rooms[5]
button_6['text']=rooms[6]
button_7['text']=rooms[7]
button_8['text']=rooms[8]
#this function determine the result.
def result():
if(rooms[0]=="o" and rooms[1]=="o" and rooms[2]=="o") or (rooms[0]=="o" and rooms[4]=="o" and rooms[8]=="o") or (rooms[0]=="o" and rooms[3]=="o" and rooms[6]=="o") or (rooms[2]=="o" and rooms[4]=="o" and rooms[6]=="o") or (rooms[2]=="o" and rooms[5]=="o" and rooms[8]=="o") or (rooms[0]=="o" and rooms[1]=="o" and rooms[2]=="o") or (rooms[1]=="o" and rooms[4]=="o" and rooms[7]=="o") or (rooms[3]=="o" and rooms[4]=="o" and rooms[5]=="o") or (rooms[6]=="o" and rooms[7]=="o" and rooms[8]=="o"):
return "o"
elif(rooms[0]=="x" and rooms[1]=="x" and rooms[2]=="x") or (rooms[0]=="x" and rooms[4]=="x" and rooms[8]=="x") or (rooms[0]=="x" and rooms[3]=="x" and rooms[6]=="x") or (rooms[2]=="x" and rooms[4]=="x" and rooms[6]=="x") or (rooms[2]=="x" and rooms[5]=="x" and rooms[8]=="x") or (rooms[0]=="x" and rooms[1]=="x" and rooms[2]=="x") or (rooms[1]=="x" and rooms[4]=="x" and rooms[7]=="x") or (rooms[3]=="x" and rooms[4]=="x" and rooms[5]=="x") or (rooms[6]=="x" and rooms[7]=="x" and rooms[8]=="x"):
return "x"
else:
for i in range(9):
if rooms[i]!=" ":
draw=True
else:
draw=False
break;
if draw==True:
return "draw"
else:
return "NULL"
#if anybody click on any box then this function set what we should do.
def click(i,room):
global started,turn,rooms,o_win,x_win,o_score,x_score
if room['text']==" ":
if turn=="x":
rooms[i]=turn
room['text']=rooms[i]
room['fg']="red"
turn="o"
if result()=="NULL":
pass
elif result()=="draw":
started=False
messagebox.showinfo("draw", "This game is draw")
x_score['text']="x_{}".format(x_win)
o_score['text']="o_{}".format(o_win)
make_all_none()
turn="x"
elif result()=="x":
started=False
messagebox.showinfo("congrats", "x win")
x_win+=1
x_score['text']="x_{}".format(x_win)
make_all_none()
turn="x"
else:
rooms[i]=turn
room['text']=rooms[i]
turn="x"
if result()=="o":
started=False
messagebox.showinfo("congrats", "o win")
o_win+=1
o_score['text']="o_{}".format(o_win)
make_all_none()
turn="x"
elif result()=="draw":
started=False
messagebox.showinfo("draw", "This game is draw")
x_score['text']="x_{}".format(x_win)
o_score['text']="o_{}".format(o_win)
make_all_none()
turn="x"
started=True
#creating window.
root=Tk()
#setting title.
root.title("Tic-Tac-Toe")
#if game is not start make all " ".
if started==False:
make_all_none()
#creating score board.
x_score=Label(root,text="x_{}".format(x_win),bg="green")
o_score=Label(root,text="o_{}".format(o_win),bg="green")
#creating button.
button_0=Button(root,text=rooms[0],bg="lightgreen",command=lambda:click(0,button_0),width=4,height=4)
button_1=Button(root,text=rooms[1],bg="lightgreen",command=lambda:click(1,button_1),width=4,height=4)
button_2=Button(root,text=rooms[2],bg="lightgreen",command=lambda:click(2,button_2),width=4,height=4)
button_3=Button(root,text=rooms[3],bg="lightgreen",command=lambda:click(3,button_3),width=4,height=4)
button_4=Button(root,text=rooms[4],bg="lightgreen",command=lambda:click(4,button_4),width=4,height=4)
button_5=Button(root,text=rooms[5],bg="lightgreen",command=lambda:click(5,button_5),width=4,height=4)
button_6=Button(root,text=rooms[6],bg="lightgreen",command=lambda:click(6,button_6),width=4,height=4)
button_7=Button(root,text=rooms[7],bg="lightgreen",command=lambda:click(7,button_7),width=4,height=4)
button_8=Button(root,text=rooms[8],bg="lightgreen",command=lambda:click(8,button_8),width=4,height=4)
#display score board on window.
x_score.grid(row=0,column=0)
o_score.grid(row=0,column=2)
#display button on window.
button_0.grid(row=1,column=0)
button_1.grid(row=1,column=1)
button_2.grid(row=1,column=2)
button_3.grid(row=2,column=0)
button_4.grid(row=2,column=1)
button_5.grid(row=2,column=2)
button_6.grid(row=3,column=0)
button_7.grid(row=3,column=1)
button_8.grid(row=3,column=2)
#score board size.
x_score.config(font=("Courier",10))
o_score.config(font=("Courier",10))
#button size.
button_0.config(font=("Courier",8))
button_1.config(font=("Courier",8))
button_2.config(font=("Courier",8))
button_3.config(font=("Courier",8))
button_4.config(font=("Courier",8))
button_5.config(font=("Courier",8))
button_6.config(font=("Courier",8))
button_7.config(font=("Courier",8))
button_8.config(font=("Courier",8))
#change the background color.
root.config(background="green")
#runing the loop of the window.
root.mainloop() |
print("Welcome to the Simple Calculator")
num1 = input("Please enter your first number")
num2 = input("Please enter your second number")
Operation = input("Please select your operation : + - * /")
if Operation == "+" :
print(float(num1) + float(num2))
elif Operation == "-" :
print(float(num1) - float(num2))
elif Operation == "*" :
print(float(num1) * float(num2))
elif Operation == "/" :
if num1 == "0" :
print(1)
elif num2 == "0" :
print("Infinity")
else :
print(float(num1) / float(num2))
else :
print("Invalid Input. Please select the correct Input")
print("Thanks for using simple calculator") |
import math
class Shape:
def __init__(self, a=8, b=9):
self.set_params(a, b)
def set_params(self, a, b):
self._a = a
self._b = b
def get_a(self):
return self._a
def get_b(self):
return self._b
def __repr__(self):
return self.__class__.__name__ + "[" + str(self._a) + " by " + str(self._b) + "] at " + str(hex(id(self)))
class Rectangle(Shape):
def calc_surface(self):
return self._a * self._b
class Circle(Shape):
def __init__(self, a):
# call constructor from super class (Shape)
super().__init__(a, 0)
#self._a = a
def calc_surface(self):
return math.pi*self._a**2
def __repr__(self):
return self.__class__.__name__ + "[r=" + str(self._a) + "] at " + str(hex(id(self)))
class HybridShape(Rectangle, Circle):
pass
h1 = HybridShape(10)
print(h1)
print(h1.calc_surface())
s = Shape(45, 56)
r1 = Rectangle(4, 6)
print(r1)
print(r1.calc_surface())
c1 = Circle(5)
print(c1)
print(c1.calc_surface())
# print(r1.calc_surface())
# print(r1.get_a())
# print(r1.get_b()) |
# en son yaptigim sey bu
import pygame
import sys
pygame.init()
WindowX = 1000
WindowY = 1000
gLength = WindowX / 6
windowSize = (WindowX, WindowY)
screen = pygame.display.set_mode(windowSize)
myriadProFont = pygame.font.SysFont("Myriad pro", 70)
helloWorld = myriadProFont.render("Hello Worldzzz", 1, (255, 0, 255), (255, 255, 255))
def drawCircles(size):
if size != 0:
for i in range(1, 1000, size):
print i, getColor(i)
pygame.draw.circle(screen, getColor(i), (WindowX / 2, WindowY / 2), 1 + i, 2)
def getColor(radius):
step = 255 / gLength
section = radius / gLength + 1
if section % 2 != 0:
color = int(255 - (radius % gLength) * step)
else:
color = int(0 + (radius % gLength) * step)
return color, color, color
size = 5
x, y = 0, 0
clock = pygame.time.Clock()
while 1:
clock.tick(40)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
size -= 1
if event.key == pygame.K_DOWN:
size += 1
screen.fill((30, 140, 20))
screen.blit(helloWorld, ((WindowX / 2) - 40, (WindowY / 2) - 80))
drawCircles(size)
pygame.display.update()
|
"""
@author: Hensel
8/30/16
Assignment 8.4 : lists
8.4 Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method.
The program should build a list of words. For each word on each line check to see if the word is already in the list,
if not append it to the list.
When the program completes, sort and print the resulting words in alphabetical order.
"""
fname = raw_input("Enter file name: ")
if len(fname) == 0: #this allows me to press enter to skip entering the file name - shortcut!
fname = 'romeo.txt'
try:
fh = open(fname)
except:
print 'File cannot be found.',fname
exit()
dalist = list()
for line in fh:
stp = line.rstrip() #strips each line of extra spaces
#print stp
splt = stp.split() # splits each line string into lists
for i in splt: # for variable 'i' in the list abc, ,
if i not in dalist: #if 'i' is not in dalist
dalist.append(i) #add i to the list, with this method we dont need to concatinate lists
dalist = sorted(dalist) #sort the list alphabetically each time through the loop
print dalist
|
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 25 11:30:31 2016
@author: Hensel
Strings: Chapter 6
"""
#we can get at ant string character in a tring using an index specified in square brakets[]
# 0 is the 1st value of the string
fruit = 'banana'
letter = fruit[1] # 1 vaule is 2nd value in the string above or a
print letter
# len() can be used to tell how many characters are in a string or length of a string
x = len(fruit)
print x
#string loops - indefinite
#uses fruit deffinition above
index = 0
while index < len(fruit):
letter = fruit[index]
print index, letter
index = index + 1
# DEFINTE loop the iteration variable is taken care of by the for loop
fruit = 'banana'
for letter in fruit: # for each value in fruit, print each value for and in comand sets up the index
print letter
# looping and counting
word = 'bannana'
count = 0
for letter in word:
if letter =='a':
"""
#Slicing Strings can use colon operatior : to look at a contunous section of a strung
exsample:
s = 'Monty python'
print s[0:4]
^the 4 is one value beyond "up to but not including"
if the second number is beyond the end of the sring it stops at the end
"""
s = 'Monty python'
print s[0:4]
print s[6:7]
print s[6:20] #will stop at end of string!
"""
String Concatenation
the + opperator doenst add a space. must be added as ' '
"""
a = 'hello'
b = a + 'There'
print b
c = a + ' ' +'There'
print c
"""
Using the 'in' opperator
can be used to check to see if a string is in another string
the in expression is a logical expression and returns True or False statement can be used in an 'if' statement
"""
fruit = 'banana'
'n' in fruit
'm' in fruit
'nan' in fruit
if 'a' in fruit :
print 'Found it!'
|
#try and except practice from lecture 3.3 in week 5
#try and except pairs
astr = 'hello Bob'
try:
istr = int(astr)
except:
istr = -1
print 'Done', istr
#check an input value bellow
rawstr = raw_input('Enter a number:')
try:
ival = int(rawstr) #converts to intiger or blows up
except:
ival = -1
if ival > 0:
print 'Nice work'
else:
print 'Not a number'
|
"""
@author: Hensel
9/1/16
Chapter 10 Tuples!
"""
#Tuples are another kind of sequence that function much like a list
#they have elements which are indexed starting at 0
#Unlike a list, once you create a tuple, you cannot alter its contents - similar to a string!
#Tuples are 'immutable' (unlike lists) ALSO cant sort, reverse
#Tuples are a reduction of what we can do than in lists, this makes them more efficent becuase python knows we cant change them
#tuples are prefered for temporary variables
# can put tuples on the left side of an assignment statement
(x,y) = (4, 'fred')
print y
#returns 'fred'
(a,b) = (99,98)
print a
#returns '99'
a,b = (99,98) # no parenthesis is ok
#TUPLES AND DICTIONARIES
#the items() method in dictionaries returns a list of (key, value) tuples
d = dict()
d['csev'] = 2
d['cwen'] = 4
for (k,v) in d.items():
print k,v
#returns csev 2 and cwen 4
tups = d.items()
print tups
#returns a list of tuples
#TUPLES are COMPARABLE
(0, 1, 2) < (5, 1, 2)
#returns True looks at left most value 1st if = contiues
#can also do strings
('Jones', 'Sally') > ('adam', 'sam')
#we can take advantage of the ability to sort a list of tuples to get a sorted version of a dicitonary
#1st we sort the dictionary by the key using the items() method
d = {'a':10, 'b':1, 'c':22} #dictionary
t = d.items() #returns a list of tuples
t.sort() #way to sort by keys
print t.sort() #returns a sorted list of tuples (a,b,c)
##Built in function sorted() - We can do the above even more directly using the built-in function sorted() that takes a sequence
#as a parameter and renturns a sorted sequence
for k,v in sorted(d.items()) : #loop will run in key sorted order
print k, v
##SORTING BY VALUES INSTEAD OF KEY
#construct a list of tuples of the form(value,key) we could sort by value
#use a for -loop that creates a list of tuples
c = {'a':10, 'b':1, 'c':22}
tmp = list() #temporary list
for k,v in c.items(): #loop through dictionary and change the order of value
tmp.append((v,k)) #make a two tuple with the v,k variables
print tmp
tmp.sort(reverse=True) #sort from highest to lowest
print tmp
#LIST COMPREHENSION
c = {'a':10, 'b':1, 'c':22}
print sorted( [ (v,k) for k,v in c.items() ] )
#list comperehinesion - python syntax, create a list of tuples in (v,k) order
|
"""
@author Hensel
Chapter 9: word counting program
"""
name = raw_input('Enterfile:') #ask for file name
handle = open(name,'r') #ask file to open and read
text = handle.read() #read whole file newlines and all, put in variable 'text'
words = text.split() #go through whole string and split to list called 'words'
counts = dict() #creates empty dictionary
for word in words: #for loop that makes each word a key and assigns a value of 1
counts[word] = counts.get(word,0) + 1 #creates or increments the value of each key
bigcount = None #largest count so far
bigword = None #largest word so far
for word,count in counts.items(): #two value iterative pair
if bigcount is None or count > bigcount:
bigword = word
bigcount = count
print bigword,bigcount |
"""
@author: hensel
8/30/16
Chapter 8 worked Exercise: Lists
Source: https://www.coursera.org/learn/python-data/lecture/t8uFQ/worked-exercise-lists
goal:
debug a program
"""
#if program chokes on blank lines, use 'Gaurdian pattern!'
fhand = open('mbox-short.txt')
for line in fhand :
line = line.rstrip()
words = line.split()
#print words
if words == [] : continue #gaurdian pattern - do somthing before the line that breaks. if words is an empty list, continue
if line == '' : continue # this also works to skip the blank line -- both are not needed, but acomplish same thing
if words[0] != 'From' : continue
print words[2]
|
from graphics import *
import random
from random import randint
def Randcolor():
'''generate random color'''
color=color_rgb( randint( 0, 255 ), randint( 0, 255 ), randint( 0, 255 ))
return color
class background:
def __init__(self, win, w, x):
'''create columns at the bottom'''
self.x1 = x-30
self.x2 = x
self.y1 = randint(-50,20)
self.y2 = -w
p1 = Point(self.x1,self.y1)
p2 = Point(self.x2,self.y2)
self.rec = Rectangle(p1,p2)
color = ['powderblue', 'darkcyan', 'darkslategray', 'lightslategray',
'lightsteelblue', 'cadetblue']
color1 = random.choice(color)
self.rec.setFill(color1)
self.rec.setOutline(color1)
self.rec.draw(win)
def MoveColumn(self,w):
'''move the column'''
p2_move = self.rec.getP2()
x2_move = p2_move.getX()
if x2_move <-w:
self.rec.move(4*w,0)
self.x1 = self.x1+4*w
self.x2 = self.x2+4*w
else:
dx = -10
self.rec.move(dx,0)
self.x1 = self.x1+dx
self.x2 = self.x2+dx
def getX1(self):
return self.x1
def getX2(self):
return self.x2
def getY1(self):
return self.y1
def getY2(self):
return self.y2
|
class Node(object):
"""defines attributes and methods for linked list node"""
def __init__(self, init_data):
self.data = init_data
self.next = None
class LinkedList(object):
"""defines attributes and methods for linked list class"""
def __init__(self, head=None):
self.head = head
def add(self, item):
"""adds a node at BEGINNING of LL. No return value"""
temp = Node(item)
temp.next = self.head
self.head = temp
def append(self, item):
"""adds a node at END of LL. No return value"""
temp = Node(item)
current = self.head
while current.next != None:
current = current.next
current.next = temp
def search(self, value):
"""search for given value in LL. returns True or False depending on if value found"""
current = self.head
while current != None:
if current.data == value:
return True
else:
current = current.next
return False
def size(self):
"""returns number of nodes in linked list"""
current = self.head
count = 0
while current != None:
count += 1
current = current.next
return count
def remove(self, item):
"""removes node with given item value from linked list. returns nothing"""
current = self.head
previous = None
while current.data != item:
previous = current
current = current.next
if previous == None:
self.head = current.next
else:
previous.next = current.next
|
def compress_encode(my_string):
"""
given a string, output a compressed encryption string.
ex.
>>> astring = "abcccccde"
>>> compress(astring)
"ab5xcde"
"""
if len(my_string)<= 1:
return "need a string greater than 1 char"
out = ""
prev = my_string[0]
count = 1
for x in my_string[1:]:
if x == prev:
count += 1
prev = x
else:
if count > 1:
out = out + str(count) + "x" + prev
count = 1
prev = x
else:
out += prev
prev = x
if count == 1:
out += my_string[-1]
else:
out = out + str(count) + "x" + prev
return out
print compress("abcccccde")
print compress("a2bbAaxyyyy")
print compress("aa") |
"""Is this word a palindrome?
>>> is_palindrome("a")
True
>>> is_palindrome("noon")
True
>>> is_palindrome("racecar")
True
>>> is_palindrome("porcupine")
False
Treat spaces and uppercase letters normally:
>>> is_palindrome("Racecar")
False
"""
def is_palindrome(word):
"""Return True/False if this word is a palindrome."""
## iterative solution. O(n) because we go through word once and check. at most we go through half the len(word)
# if len(word) < 1:
# return False
# if len(word) == 1:
# return True
# for x in range(len(word)/2):
# if word[x] != word[-x-1]:
# return False
# return True
## recursive solution
if len(word) < 2:
return True
return is_palindrome(word[1:-1]) and word[0] == word[-1]
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. YAY!"
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
def print_spiral(matrix):
top = 0
bottom = len(matrix)-1
left = 0
right = len(matrix[0]) -1
output = []
while True:
#print "left", left
#print "right", right
#print "top", top
#print "bottom", bottom
# print top row
for x in matrix[top][left:right+1]:
output.append(x)
top += 1
if top > bottom or left > right:
break
#print right col
for r in range(top, len(matrix)):
output.append(matrix[r][right])
right -= 1
if top > bottom or left > right:
break
# print bottom
for b in range(len(matrix[0])-(left+right)-1,left-1, -1):
#print "b", b
output.append(matrix[bottom][b])
bottom -= 1
if top > bottom or left > right:
break
#print left col
for l in range(len(matrix)-(bottom+top), top-1, -1):
output.append(matrix[l][left])
left += 1
if top > bottom or left > right:
break
print ",".join(output)
# build matrix
matrix_size = raw_input().split(",")
_matrix = []
for x in range(int(matrix_size[0])):
row = raw_input().split(",")
_matrix.append(row)
print_spiral(_matrix)
|
"""Calculate possible change from combinations of dimes and pennies.
Given an infinite supply of dimes and pennies, find the different
amounts of change can be created with exact `num_coins` coins?
For example, when num_coins = 3, you can create:
3 = penny + penny + penny
12 = dime + penny + penny
21 = dime + dime + penny
30 = dime + dime + dime
For example:
>>> coins(0) == {0}
True
>>> coins(1) == {1, 10}
True
>>> coins(2) == {2, 11, 20}
True
>>> coins(3) == {3, 12, 21, 30}
True
>>> coins(4) == {4, 13, 22, 31, 40}
True
>>> coins(10) == {10, 19, 28, 37, 46, 55, 64, 73, 82, 91, 100}
True
"""
def coins(num_coins):
"""Find change from combinations of k length of dimes and pennies.
This should return a set of the unique amounts of change possible.
"""
def _coins(num_coins, total, sums):
# base case - if we have no more coins left, take our total and add to list
if num_coins == 0:
sums.append(total)
return sums # ex. [12]
else:
p = _coins(num_coins-1, total+1, sums)
d = _coins(num_coins-1, total+10, sums)
# now we have 2 lists we need to merge, but sort first
return sorted(p + d) # ex. [3] + [12] -> [3, 12]
# the final return from _set() will be a sorted list of all possible sums, so remove dups with a set
return set(_coins(num_coins, 0, sums=[]))
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "\n*** ALL TESTS PASSED. YOU CAN TAKE THAT TO THE BANK!\n"
|
# powerSet
#
# input: string
# output: array of strings
#
# input: 'abc'
# output: ['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']
#
#
def powerSet(input):
# char_lst = list(input)
# out_list = [[]]
# for char in char_lst:
# print "out: ", out_list
# out_list.extend([sublist +[char] for sublist in out_list])
# print out_list
out_list = [""]
for char in input:
sublist = []
for item in out_list:
sublist.append(item + char)
out_list.extend(sublist)
# out_list.extend([item + char for item in out_list])
print out_list
powerSet('abc')
|
#
# Design and Build a Tic-Tac-Toe Game
#
# Board, 2 Players
#
# 1. Select player 1 (by default O)
# 2. Player makes move (action):
# -> evaluate if action is valid (check if space is empty)
# -> make move
# 3. Check if anyone (player who moved) has won
# 4. Switch Player (return to Step 1)
#
class Board(object):
def __init__(self, players, board_size):
self.board = []
self.size = board_size
self.current_player = players[0]
self.players = players
def init_board(self):
board = []
for row in xrange(self.size):
board.append([])
for sub_list in board:
for x in xrange(self.size):
sub_list.append(" ")
self.board = board
def print_board(self):
""" Prints current board state """
for row in self.board:
print "|",
for column in row:
print column, # remove newline
print "|",
print
def make_move(self, x, y):
symbol = self.current_player.symbol
if self.move_valid(x, y):
self.board[x][y] = symbol
return True
else:
print "invalid move, try again."
return False
def move_valid(self, x, y):
# check if row (x) & column (y) are within matrix
if x >= self.size or y >= self.size:
return False
# check if row & col are empty
if self.board[x][y] != " ":
return False
return True
def gameover(self, x, y, player):
# Check if there is a winner
# check if given row has a win
row = self.board[x]
winner_row = True
# go through each cell in the row & check if that cell equals current symbol
for cell in row:
# if one of those cells doesn't equal the current player - no win on row
if cell != player:
winner_row = False
break
# if we got through the loop and winner_row is still true, we are a winner
if winner_row:
print "Player %s is the winner!" % player
return True
# check if given col has a win
winner_col = True
for row in self.board:
if row[y] != player:
winner_col = False
break
if winner_col:
print "Player %s is the winner!" % player
return True
# check if diag has a win
winner_diag1 = True
current1 = 0
# check each row, but are only checking a specific cell in that row
while current1 < self.size:
if self.board[current1][current1] != player:
winner_diag1 = False
break
current1 += 1
if winner_diag1:
print "Player %s is the winner!" % player
return True
winner_diag2 = True
current2 = 0
# similar to above but different cell check
while current2 < self.size:
cell = (self.size-1) - current2
if self.board[current2][cell] != player:
winner_diag2 = False
break
current2 += 1
if winner_diag2:
print "Player %s is the winner!" % player
return True
# check if everything has been filled (draw)
for row in self.board:
for cell in row:
if cell == " ":
return False
print "Draw"
return True
def switch_player(self):
if self.current_player == self.players[0]:
self.current_player = self.players[1]
else:
self.current_player = self.players[0]
class Player(object):
def __init__(self, symbol):
self.symbol = symbol
def main():
# TODO: make the board 3D
#
# Board, 2 Players
#
# 1. Select player 1 (by default O)
# 2. Player makes move (action):
# -> evaluate if action is valid (check if space is empty)
# -> make move
# 3. Check if anyone (player who moved) has won
# 4. Switch Player (return to Step 1)
#
""" Start the game """
player1 = Player("O")
player2 = Player("X")
# need to have even sized board (height & width same)
board_size = int(raw_input("How many rows in the game board (column # will the be same as you enter here)? > "))
while board_size < 3:
board_size = int(raw_input("Please enter a number larger than 2 to make this a fair game > "))
game_board = Board([player1, player2], board_size)
game_board.init_board()
while True:
current_player = game_board.current_player.symbol
print "current player: ", current_player
game_board.print_board()
coords = raw_input("Where would you like to play? (row column) - remember, zero-indexed! ")
coord_list = coords.split(" ")
row = int(coord_list[0])
col = int(coord_list[1])
if game_board.make_move(row, col):
game_board.switch_player()
if game_board.gameover(row, col, current_player):
break
game_board.print_board()
if __name__ == '__main__':
main() |
def bracket_matching(astring):
"""
determines whether string has valid bracket matching.
input: string
output: boolean
example:
>>> bracket_matching("({[]}())")
True
>>> bracket_matching("(()])")
False
>>> bracket_matching("test{variable()}")
True
>>> bracket_matching("]()")
False
"""
stack = []
open_brackets = '({[<'
closing_brackets = ')}]>'
for char in astring:
if char in open_brackets:
stack.append(char)
elif char in closing_brackets:
if not stack:
return False
if open_brackets.index(stack.pop()) != closing_brackets.index(char):
return False
if stack:
return False
return True
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print "tests pass"
|
def zero_out(matrix):
# tracker lists to keep the columns and rows to zero out
columns_to_zero = [False] * len(matrix[0])
rows_to_zero = [False] * len(matrix)
for outer_idx, row in enumerate(matrix):
for inner_idx, cell in enumerate(row):
# if we find a zero. set the appropriate indicies in trackers to True
if cell == 0:
columns_to_zero[inner_idx] = True
rows_to_zero[outer_idx] = True
# go through our columns to zero out
for idx, val in enumerate(columns_to_zero):
# if true, we zero all columns/cells in each row of matrix
if val:
for row in matrix:
row[idx] = 0
# go trough rows and zero out
for idx, val in enumerate(rows_to_zero):
if val:
matrix[idx] = [0] * len(matrix[idx])
return matrix
my_matrix = [[1,1,1,0], [0, 1, 1, 1], [1, 1, 1, 1]]
assert zero_out(my_matrix) == [[0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 1, 0]]
|
def find_smallest_index(array, start_idx):
""" takes an array and a number start_idx
returns the index of the smallest value that occurs with index start_idx or greater.
"""
min_val = array[start_idx]
min_idx = start_idx
for x in range(min_idx+1, len(array)):
if array[x] <= min_val:
min_idx = x
min_val = array[x]
return min_idx
def swap(array, first_idx, second_idx):
""" takes in an array, and two numbers - representing the two numbers to swap
returns the new array
"""
array[first_idx], array[second_idx] = array[second_idx], array[first_idx]
return array
def selection_sort(array):
min_idx = 0
for x in range(len(array)):
min_idx = find_smallest_index(array, x)
swap(array, min_idx, x)
return array
print selection_sort([-3, 5, 3, -3, 1, 0, 22, 10]) |
class Node(object):
def __init__(self, val=None):
self.value = val
self.leftChild = None
self.rightChild = None
def __repr__(self):
return "<value: {}, leftChild: {}, rightChild: {}>".format(self.value, self.leftChild, self.rightChild)
class BinarySearchTree(object):
def __init__(self):
self.root = None
self.size = 0
def insert(self, value):
#create new node with value
new_node = Node(value)
#check if we have a root. if not, make this root and return
if not self.root:
self.root = new_node
self.size += 1
return
# find where we have an open spot using algo that if val less than curr node, go to left, otherwise, go to right
prev = None
curr = self.root
# we keep track of previous and current because this loop will stop when current is None/not a valid node so we need to know the last valid node.
while curr:
# if value is greater, it belongs to right, so traverse right side of tree from curr node.
if value > curr.value:
prev = curr
curr = curr.rightChild
# if val is lower, it belongs on left of curr node so traverse left side from curr node.
elif value < curr.value:
prev = curr
curr = curr.leftChild
# a check to get out if we already have this value
else:
print 'value already in tree, try again'
return
# when we hit an empty spot (non-valid node), check the last valid node and insert new_node appropriatly
if prev.value > value:
prev.leftChild = new_node
else:
prev.rightChild = new_node
self.size += 1
# def max_depth(self):
# def dfs_depth(curr):
# if not curr:
# return 0
# l = dfs_depth(curr.leftChild) + 1
# r = dfs_depth(curr.rightChild) + 1
#
# return max(l,r)
# return dfs_depth(self.root)
def max_depth(self, curr="root"):
if not curr:
return 0
elif curr == "root":
l = self.max_depth(self.root.leftChild) + 1
r = self.max_depth(self.root.rightChild) + 1
else:
l = self.max_depth(curr.leftChild) + 1
r = self.max_depth(curr.rightChild) + 1
return max(l,r)
myBST = BinarySearchTree()
myBST.insert(5)
myBST.insert(7)
myBST.insert(3)
myBST.insert(6)
myBST.insert(8)
myBST.insert(9)
print myBST.max_depth()
|
for char in "UMSS":
print (char)
for li in ['U','M','S','S']:
print(li)
T = ("Norah","Villarroel","UMS","2019")
for t in T :
print (T.index(t), t)
D = {"nombre": 'Norah', 'universidad':"UMSS"}
for k,v in D.items():
print(k,v)
for k in D:
print(k)
|
import random
import time
#Prompt 1
print("Welcome to Multiplication Game.")
print("You will be prompted to solve a math equation")
print("and you will need to answer within 3 seconds.")
#Prompt 2
ready = input('Are you ready to play(y/n)?:\n').lower()
score = 0
#Main Game Loop
while (ready == 'y' or ready == "yes"):
num1 = random.randint(0,12)
num2 = random.randint(0,12)
print("\n")
for x in range(3):
print(3 - x)
time.sleep(1)
t1 = time.time()
question = int(input(str(num1) + " x " + str(num2) + " = "))
t2 = time.time()
eta = t2 - t1
print("\n\n\nYou took " + str(eta) + " seconds")
if ( t2 - t1 >= 3 or question != num1 * num2):
print("YOU FAILED! :P")
elif (question == num1 * num2):
print("You got it!")
score += 1
print("Total Score: " + str(score))
ready = input("Are you ready to play?(y/n)\n").lower()
print("Thanks for playing") |
# 实现一个简单的商城购物系统
from bll import handles
from dal import shopping_goods_data
def shopping():
prompt = "您好,欢迎使用薯条橙子在线购物系统chipscoco,输入<>中对应的指令来使用购物系统:\n" \
"<1>:查看所有商品\n<2>:对商品按售价进行排序(asc表示升序,desc表示降序)\n" \
"<3>:添加商品到购物车\n<4>:查看购物车\n<5>:删除购物车指定商品\n<6>:下单结账\n<0>:退出系统"
commands = {1: handles.show_all_goods, 2: handles.sort_goods, 3: handles.add_goods, 4: handles.show_shopping_cart,
5: handles.remove_goods, 6: handles.shopping_cart_paybill }
# commands 是数字编号+函数的内存地址
while True:
print(prompt)
command = int(input("输入指令:__\b\b"))
if command in commands:
commands[command](shopping_goods_data.CHIPSCOCO)
# 因为把 shopping_goods_data 作为模块分出去以后,这里再调用chipscoco就要
# 加上模块名了
elif command == 0:
break
else:
print("您输入了非法的指令")
input("按下键盘任意键,继续使用系统......")
if __name__ == "__main__":
shopping()
|
"""
Project Euler
Problem 3
Largest prime factor
Aaron Mok
08/09/14
"""
import math
#Overflow error, method doesn't work
def largest_prime(num):
arr = [True] * num
root = math.sqrt(num)
root = math.ceil(root)
for i in range(2,root,1):
if arr[i] is True:
for j in range(i*i, num, i):
arr[j] = False
for i in range(len(arr)):
if arr[i] == True:
print(i)
largest_prime(600851475143) |
#!/usr/bin/python
import readline
def main():
stack = [];
while(True):
# Display stack and prompt for input
str_stack = " ".join([str(e).rstrip('0').rstrip('.') for e in stack])
prompt = "> %s " % str_stack if len(stack) else "> "
token = raw_input(prompt)
try:
# Process number input
stack.append(float(token))
except ValueError:
if token in "/*-+%":
# Process operator input
try:
b = stack.pop()
a = stack.pop()
if token == '/': stack.append(a/b)
if token == '*': stack.append(a*b)
if token == '-': stack.append(a-b)
if token == '+': stack.append(a+b)
if token == '%': stack.append(a%b)
except IndexError:
print "Insufficient Numbers on Stack"
else:
# Other input. Reset stack
stack = [];
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass |
import math
def verify_pyth_triplet():
# I. Structure the for loop to enforce the first Pythagorean requirement a < b < c
for a in range(1, 1000):
for b in range(a + 1, 1000):
csqr = a*a + b*b
# II. The second requirement c*c = a*a + b*b also checking csqr as a conditional from the preceeding variables saves another nested for loop
if math.sqrt(csqr).is_integer():
c = math.sqrt(csqr)
print('Pyth Triplet found -- (' +str(a)+ '), (' +str(b)+'), (' +str(c)+')' )
if a + b + c == 1000:
return a*b*c
print(verify_pyth_triplet())
|
def pig_it(text):
tokens = text.split(" ")
output = " ".join(word[1:] + word[0] + "ay" if str(word).isalpha() else word for word in tokens)
return output
print(pig_it("Hello world !"))
|
def get_middle(s):
mid = int(len(s) / 2)
return s[mid] + s[mid + 1] if len(s) % 2 == 0 else s[mid + 1]
def binary_array_to_number(arr):
k = 2**(len(arr)-1)
output = 0
for x in arr:
output += k * x
k /= 2
return output
binary_array_to_number([0,0,1,0])
|
"""
This provide some common utils methods for YouTube resource.
"""
import isodate
from isodate.isoerror import ISO8601Error
from pyyoutube.error import ErrorMessage, PyYouTubeException
def get_video_duration(duration: str) -> int:
"""
Parse video ISO 8601 duration to seconds.
Refer: https://developers.google.com/youtube/v3/docs/videos#contentDetails.duration
Args:
duration(str)
Videos ISO 8601 duration. Like: PT14H23M42S
Returns:
integer for seconds.
"""
try:
seconds = isodate.parse_duration(duration).total_seconds()
return int(seconds)
except ISO8601Error as e:
raise PyYouTubeException(
ErrorMessage(
status_code=10001,
message=f"Exception in convert video duration: {duration}. errors: {e}",
)
)
|
import math, collections
SpaceVectorBase = collections.namedtuple('SpaceVector', 'x y z')
#SpaceTimeVectorBase = collections.namedtuple('SpaceTimeVector', 'x y z t')#Time is relative, so use a SpaceTimeVector to do an operation as if it was a particular, known, point in time.
class VectorMethods():
def __int__(self):
combined = "".join([str(i) for i in self])
return int(combined)
class SpaceVector(SpaceVectorBase,VectorMethods):
pass
def distance(point1, point2):
diff1 = point1[0]-point2[0]
diff1 = diff1**2
diff2 = point1[1]-point2[1]
diff2 = diff2**2
return math.sqrt(diff1+diff2)
#Probably more clever then it's worth.
def cubeGenerator(center, size, partial=list()):
depth = len(partial)
if depth < 3:
for i in range(center[depth],center[depth]+size[depth]):
newPartial = partial+[i,]
yield from cubeGenerator(center,size,newPartial)
else:
partial = SpaceVector(*partial)
yield partial
def cylinderGenerator(center, rad, height, partial=list()):
pass
def sphereGenerator(center, diam):
rad=diam/2
boundingCube = cubeGenerator([int(i-rad) for i in center], (diam,diam,diam))
return set((i for i in boundingCube if distance(center, i) < rad ))
|
import typing
class List(typing.NamedTuple):
"""
Monad implementation for list
"""
value: list
def is_empty(self) -> bool:
"""
Check if the list is empty
:return: True if the list is empty, False otherwise
"""
return not self.value
def map(self, func) -> 'List':
"""
Monadic map function implementation
:param func: The transformation function
:return: A copy of the current list in which all elements have been transformed by the given function
"""
return List(list(map(func, self.value)))
def head(self) -> any:
"""
Access the head of the list
:return: the head of the list
"""
return self.value[0]
def tail(self) -> any:
"""
Access the tail of the list
:return: the tail of the list
"""
return self.value[-1]
def length(self) -> int:
"""
Access the length of the list
:return: the length of the list
"""
return len(self.value)
def size(self) -> int:
"""
Access the size of the list
:return: the size of the list
"""
return self.length()
def head_option(self) -> 'Option':
"""
Access the head of the list as an Option
:return: Option(head) if the list is not empty, Option(None) otherwise
"""
if not self.is_empty():
return Option(self.head())
else:
return Option(None)
def tail_option(self) -> 'Option':
"""
Access the tail of the list as an Option
:return: Option(tail) if the list is not empty, Option(None) otherwise
"""
if not self.is_empty():
return Option(self.tail())
else:
return Option(None)
def to_dict(self) -> dict:
"""
Convert the current list to dict
:return: The dict of (elt[0] -> elt[1]) if all list elements are tuple, (index, element) otherwise
"""
if self.is_empty():
return {}
elif type(self.head()) == tuple:
return dict(self.value)
else:
return {v: k for v, k in enumerate(self.value)}
def filter(self, predicate):
"""
Filter the current on given predicate
:param predicate: The filter predicate to use
:return: A copy of the current list filtered by satisfying the given predicate
"""
return List([x for x in self.value if predicate(x)])
def count(self, predicate):
"""
Count the number of elements in the list that match the given predicate
:param predicate: The couting predicate
:return: the number of elements in the list that match the given predicate
"""
return self.filter(predicate).length()
def find(self, predicate):
"""
Find the first element of the list matching the predicate
:param predicate: predicate used for element selection
:return: The option containing the element matching the predicate if any, None option otherwise
"""
return self.filter(predicate).head_option()
def flatten(self):
return List([item for sublist in self.value for item in sublist])
def flat_map(self, func):
return self.map(func).flatten()
class Option(typing.NamedTuple):
"""
Monad implementation for Option
"""
value: any
def get_or_else(self, other:any) -> any:
"""
Get the option content or return the other value if the option is None
:param other: The default value if the option is None
"""
if not self.is_empty():
return self.value
else:
return other
def is_empty(self) -> bool:
"""
Check if the option is empty
:return: True if the option in None, False otherwise
"""
return self.to_list().is_empty()
def to_list(self) -> 'List':
"""
Convert the option to List Monad
:return: The corresponding List NamedTuple
"""
if self.value is None:
return List([])
else:
return List([self.value])
def map(self, func) -> 'Option':
"""
Monadic map function implementation
:param func: The transformation function
:return: None if the option is None, the transformed content function result otherwise
"""
return self.to_list().map(func).head_option()
|
#Ejercicio5_3 Palabra o frase palindroma
cadena = input("Digite una cadena: ")
#Quitar espacios en blanco
cadena = cadena.replace(" ","")
#Invertir la cadena
cadena2 = cadena[::-1] #Cadena Invertida
print(cadena2)
if cadena == cadena2:
print("La cadena es palindroma")
else:
print("La cadena no es palindroma") |
#Ejercicio5_1 Cadena más larga
cadena1 = input("Digite una cadena: ")
cadena2 = input("Digite una cadena: ")
if len(cadena1) > len(cadena2):
print(f"\nLa cadena más larga es: {cadena1}")
elif len(cadena2) > len(cadena1):
print(f"\nLa cadena más larga es: {cadena2}")
else:
print("\nAmbas cadenas son iguales") |
#Ejercicio4_3 Insertar elementos y ordenarlos
lista = []
salir = False
while not salir:
numero = int(input("Digite un numero: "))
if numero == 0:
salir = True
else:
lista.append(numero)
lista.sort()
print(f"\nLista ordenada: \n{lista}")
|
#Ejercicio6_4 Factorial de un numero (Recursividad)
def factorial(num):
if num > 0:
resultado = num * factorial(num-1)
else:
resultado = 1
return resultado
valor = factorial(5)
print(valor)
|
from Date import *
myfile=open('birthdays.txt')
myfile=myfile.read()
myfile=myfile.split('\n')
myfile2=[]
for i in range(len(myfile)-1):
myfile2.append(myfile[i].split())
ed=Date(myfile2[0][0],myfile2[0][1],myfile2[0][2])
for i in range(1,len(myfile2)):
date=Date(myfile2[i][0],myfile2[i][1],myfile2[i][2])
if date<ed:
ed=date
ld=Date(myfile2[0][0],myfile2[0][1],myfile2[0][2])
for i in range(1,len(myfile2)):
date=Date(myfile2[i][0],myfile2[i][1],myfile2[i][2])
if date>ld:
ld=date
month_all=[]
for i in range(len(myfile2)):
month_all.append(myfile2[i][1])
cnt_ex=month_all.count('1')
for i in range(2,13):
cnt=month_all.count(str(i))
if cnt>cnt_ex:
mon=i
cnt_ex=cnt
print 'The earliest birthday: '+str(ed)
print 'The latest birthday: '+str(ld)
print 'the name of the month that has the most birthdays: '+month_names[mon] |
""" This is the skeleton for your lab 10. We provide a function
here to show the use of nose.
"""
import random
def closest1(L):
if len(L)<2:
return None, None
close1=abs(L[0]-L[1])
close2=L[0],L[1]
for i in range(len(L)):
for j in range(len(L)):
if i!=j and abs(L[i]-L[j])<close1:
close1=abs(L[i]-L[j])
close2=L[i],L[j]
return close2
def closest2(L):
L.sort()
close1=abs(L[0]-L[1])
close2=L[0],L[1]
for i in range(len(L)-1):
if abs(L[i]-L[i+1])<close1:
close1=abs(L[i]-L[i+1])
close2=L[i],L[i+1]
return close2
if __name__=='__main__':
L1 = [67,23]
L2 = [23,67]
L3 = []
for i in range(2000):
L3.append(random.uniform(0.0,1000.0))
print closest1(L1)
print closest1(L2)
print closest2(L1)
print closest2(L2) |
A=int(raw_input('Enter a value ==> '))
print A
print ''
print "Here is the computation:"
def reverse(A):
X=A%100%10*100+A%100/10*10+A/100
return X
B=reverse(A)
C=abs(B-A)
print max(A,B),"-",min(A,B),"=",C
D=reverse(C)
print C,"+",D,"=",C+D
if C+D==1089:
print "You see, I told you."
else:
print "Are you sure your input is valid?" |
clubs = {'WRPI': set(['May', 'Coulson']), 'Red Army': set(['Simmons', 'Fitz']), \
'Poly': set(['May']), 'UPAC': set(['Skye', 'Hunter']) }
if __name__=='__main__':
name=raw_input('Name ==> ')
x=set()
y=set()
for key in clubs.keys():
if name in clubs[key]:
x.add(key)
else:
y.add(key)
print 'Member of: %s'%x
print 'Not member of: %s'%y |
import time
import matplotlib.pyplot as plt
def fib1(n):
if n==0:
return 0
if n==1:
return 1
return fib1(n-1)+fib1(n-2)
def fib2(n):
for i in range(0,n+1):
f.append(i)
for i in range(2,n+1):
f[i]=f[i-1]+f[i-2]
if __name__ == '__main__':
#recursive
s1=time.time()
a=fib1(15)
e1=time.time()
t1=e1-s1
s2=time.time()
a=fib1(20)
e2=time.time()
t2=e2-s2
s3=time.time()
a=fib1(25)
e3=time.time()
t3=e3-s3
s4=time.time()
a=fib1(30)
e4=time.time()
t4=e4-s4
s5=time.time()
a=fib1(35)
e5=time.time()
t5=e5-s5
plt.plot([15,20,25,30,35], [t1,t2,t3,t4,t5])
plt.ylabel('time of fib1')
plt.xlabel('n value')
plt.show()
#iterative
f=[]
start1=time.time()
for i in range(10**6):
fib2(5)
b=f[5]
end1=time.time()
time1=end1-start1
start2=time.time()
for i in range(10**6):
fib2(10)
b=f[10]
end2=time.time()
time2=end2-start2
start3=time.time()
for i in range(10**6):
fib2(15)
b=f[15]
end3=time.time()
time3=end3-start3
start4=time.time()
for i in range(10**6):
fib2(20)
b=f[20]
end4=time.time()
time4=end4-start4
start5=time.time()
for i in range(10**6):
fib2(25)
b=f[25]
end5=time.time()
time5=end5-start5
plt.plot([5,10,15,20,25], [time1,time2,time3,time4,time5])
plt.ylabel('time of fib2')
plt.xlabel('n value')
plt.show()
|
if __name__ == '__main__':
myfile=raw_input('File name => ')
print myfile
number=int(raw_input('How many names to display? => '))
print number
myfile=open(myfile)
myfile=myfile.read()
myfile=myfile.split()
myfile2=[]
for i in range(len(myfile)):
myfile2.append(myfile[i].split(','))
for i in range(len(myfile2)):
myfile2[i][0],myfile2[i][2]=myfile2[i][2],myfile2[i][0]
male=[]
female=[]
for i in range(len(myfile2)):
if myfile2[i][1]=='M':
male.append(myfile2[i])
elif myfile2[i][1]=='F':
female.append(myfile2[i])
for i in range(len(myfile2)):
myfile2[i][0]=int(myfile2[i][0])
male.sort(reverse=True)
female.sort(reverse=True)
print
print 'Top female names'
for i in range(number):
if (i+1)%3==0:
print '%s (%s)'%(female[i][2],female[i][0])
elif i==number-1:
print '%s (%s)'%(female[i][2],female[i][0])
else:
print '%s (%s)'%(female[i][2],female[i][0]),
print 'Top male names'
for i in range(number):
if (i+1)%3==0:
print '%s (%s)'%(male[i][2],male[i][0])
else:
print '%s (%s)'%(male[i][2],male[i][0]), |
def cap_value(mystr):
mystr=mystr.capitalize()
return mystr
def arrange_value(mylist):
mylist.sort()
myvals=[]
finished=False
while not finished:
newval=raw_input('Enter a value (stop to end) ==> ')
if newval=='stop':
finished=True
else:
newval=cap_value(newval)
myvals.append(newval)
arrange_value(myvals)
print myvals |
word=raw_input('Word ==> ')
letters=set(word)
X=[]
for letter in list(letters):
X.append((word.count(letter),letter))
X.sort(reverse=True)
for i in range(len(X)):
print '%s: %d'%(X[i][1],X[i][0]) |
#!/usr/bin/env python
import sys
import re
for line in sys.stdin:
line = line.strip()
name = line.split('\t')[0]
words = re.findall(r'\w+',line)
for word in words:
if word:
print '%s\t%s' % (word.lower(), name)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019-02-25 19:39
# @Author : ZD Liu
class Solution:
def longestCommonPrefix(self, strs):
if len(strs) > 0:
commen_prefix = strs[0]
for e in strs:
com_len = len(commen_prefix)
len_e = len(e)
if com_len > len_e:
com_len = len_e
if commen_prefix[:com_len] in e[:com_len]:
commen_prefix = commen_prefix[:com_len]
else:
for i in range(com_len+1):
if i < com_len:
if commen_prefix[:com_len-i] in e[:com_len-i]:
commen_prefix = commen_prefix[:com_len-i]
break
else:
return ""
# print('result')
return commen_prefix
def longestCommonPrefix2(self, strs):
"""
:type strs: List[str]
:rtype: str
"""
cpt = ""
if (not strs):
return cpt
minnum = min([len(x) for x in strs])
same = True
for i in range(minnum):
check = [x[i] for x in strs]
for i in range(len(check)):
if (check[i] != check[0]):
same = False
if (same):
cpt += check[0]
return cpt
if __name__ =='__main__':
solution = Solution()
l = ["flower","flow","flight"]
# l = ["dog","racecar","car"]
print(solution.longestCommonPrefix2(l)) |
def menu():
print('Option-1) Read a FASTA format DNA sequence file and make a reverse sequence file.')
print('Option-2) Read a FASTA format DNA sequence file and make a reverse complement sequence file.')
print('Option-3) Convert GenBank format to FASTA format file.')
op = input('Select the option: ')
return op
def op1(fr, fw):
title = fr.readline().strip()
seq = ''
for line in fr:
seq += line.strip()
rev = seq[::-1]
fw.write(title)
for i in range(0, len(rev), 70):
fw.write('\n' + rev[i:i+70])
def op2(fr, fw):
title = fr.readline()
seq = ''
for line in fr:
seq += line.strip()
rev = seq[::-1]
d_complement = {'A':'T', 'C':'G', 'G':'C', 'T':'A'}
fw.write(title)
cnt = 0
for i in rev:
cnt += 1
fw.write(d_complement[i])
if cnt % 70 == 0: fw.write('\n')
def op3(fr, fw):
title = '>' + fr.readline().strip()
while 1:
if fr.readline().strip().startswith('ORIGIN'): break
seq = ''
for line in fr:
seq += ''.join(line.strip().split()[1:])
fw.write(title)
cnt = 0
for i in range(0, len(seq), 70):
cnt += 1
fw.write('\n' + seq[i:i+70])
def main():
# fr = open(input('Enter input file: '), 'r')
# fw = open(input('Enter output file: '), 'w')
fr = open('sequence.nucleotide.gb', 'r')
fw = open('new.sequence.nucleotide.fasta', 'w')
op = menu()
if op == '1': op1(fr, fw)
elif op == '2': op2(fr, fw)
elif op == '3': op3(fr, fw)
else: exit()
fr.close()
fw.close()
if __name__ == "__main__":
main()
|
a = input("Enter a string: ")
print(f"Reversed string: {a[::-1]}")
|
a = int(input("Enter a integer: "))
b = int(input("Enter another: "))
if a > b:
print(f"{a} is greater than {b}.")
elif a < b:
print(f"{a} is less than {b}.")
else:
print(f"{a} is equal to {b}.")
|
"""
Smallest Multiple
https://projecteuler.net/problem=5
"""
def is_evenly_divisible(number):
for i in range(1, 21):
if number % i != 0:
return False
return True
def main():
i = 2
while i > 0:
if is_evenly_divisible(i):
print i
return
i += 2
main() |
"""
Special Pythagorean Triplet
https://projecteuler.net/problem=9
"""
import math
def is_pythagorean_triplet(a, b, c):
return (a ** 2) + (b ** 2) == (c ** 2)
def main():
# choose arbitrary max limits for a,b.
# this is a brute force method to try all combinations of a < b until you hit the
# one where a + b + c == 1000
for a in range(1, 5000):
for b in range(a, 5000):
# write c in terms of a and b so we can optimize 2 variables instead of 3
c = math.sqrt((a ** 2) + (b ** 2))
if is_pythagorean_triplet(a, b, c) and a + b + c == 1000:
print 'a: %d, b: %d, c: %d' % (a, b, c)
print a * b * c
main() |
"""
Summation of primes
https://projecteuler.net/problem=10
"""
import math
def is_prime(number):
for i in range(2, int(math.sqrt(number)) + 1):
if number % i == 0:
return False
return True
def main():
max_limit = 2000000
primes = [n for n in range(2, max_limit+1) if is_prime(n)]
print sum(primes)
main() |
def partition(n, I=1):
yield (n,)
for i in range(I, n//2 + 1):
for p in partition(n-i, i):
yield (i,) + p
def partitions(n):
a = partition(n)
c = 0
for i in a:
c += 1
return c
a = partitions(100)
print(a) |
word = input()
spacing = ' ' * int(input())
print(*word, sep=spacing)
|
#!/usr/bin/env python
'''
Proyecto [Python]
Consulta de accidentes -Accidentología Vial-
---------------------------
Autor: Diego Farias
Version: 1.1
Descripcion:
Programa creado para generar una lista de fechas para consulta de archivo .csv de
registro de accidentes viales.
'''
__author__ = "Diego Farias"
__email__ = "dfarias8791@gmail.com"
__version__ = "1.1"
import datetime # se importa modulo datetime para realizar la diferencia entre fechas
from datetime import date, timedelta
import consultas
import csv
def lista_numeros(numero_inicial, numero_final):
'''
Funcion para crear una lista de accidentes a evaluar comenzando con el primer numero ingresado
y terminando con el segundo numero ingresado por el usuario, generando una lista
de n elementos entre numero inicial y numero final, incrementando de 1 en 1 y retornando la lista
list_accidentes con elementos tipo string.
'''
# bucle para hacer una lista de strings con numero de accidentes para comparacion con archivo .csv
list_accidentes = []
for i in range((numero_final - numero_inicial) + 1):
numero = numero_inicial + i # elemento
numero = str(numero) # conversion de elemento a string (se hace porque los valores de la clave
#'Nº de Accidente' son strings)
list_accidentes.append(numero) # se agrega el elemento a la lista list_accidentes
return list_accidentes # retorno de la lista list_accidentes con numeros de accidentes a evaluar
def test_numeros(list_accidentes, data):
'''
Función para chequear que el rango desde el numero inicial al numero final ingresados
por el usuario se encuentra completo en el archivo csv y de no ser asi, reporte los numeros
que faltan cargarse. El programa seguirá solo si no falta ningun accidente que cargar en el
rango especificado.
'''
fo = open('reporte.txt', 'w')
fo.write('------------Reporte de faltante de accidentes------------------------\n')
test = True
for numero in list_accidentes: # para cada elemento de list_accidentes se verificara si se encuentra en
# el archivo Listado_de_accidentes.csv
marca = False
for i in range(len(data)):
if data[i].get('Nº de Accidente') == numero:
marca = True # si se encuentra el numero de accidente la variable marca tomara el valor True
if marca == False: # si no se encuentra el elemento, marca no cambiara de valor y el programa
# informara al usuario el faltante del registro
cadena = 'Falta accidente ' + str(numero) + '\n' # cadena para archivo reporte.txt
fo.write(cadena)
print(cadena)
test = False # la variable test toma el valor False siempre que falte al menos un accidente en archivo csv, por lo que
# el programa solo informara los registros faltantes, no permitiendo realizar otra accion
if marca == False:
print("Cargue los accidentes detallados, el programa finalizará")
cadena = "Cargue los accidentes detallados, el programa finalizará"
fo.write(cadena)
return test # retorno del valor de la variable test
def lista_fecha(fecha_inicial, fecha_final):
'''
Funcion para construir una lista de elementos tipo strings con las fechas iniciando en la fecha inicial ingresada por el
usuario y terminando con la fecha final tambien ingresada por el usuario. El formato de fecha_inicial y fecha_final es
un elemento tipo string con el formato 'dd-mm-aa', y la funcion debe devolver una lista (list_accidentes) con elementos tipo
strings con el formato 'dd-Mmm-aa' donde el mes son las tres primeras letras del mes correspondiente, la primera de ellas
en mayuscula, por ejemplo 01-Ene-20, siendo este formato el que contiene los valores de la clave 'Fecha' en archivo
Listado_de_accidentes.csv
'''
# dar formato para determinar la diferencia en dias entre las fechas
lista = [] # lista local
# para fecha inicial
fecha_1 = fecha_inicial
fecha_1 = fecha_1.split('-') # se crea una lista con el metodo split()
for i in range(len(fecha_1)): # se convierte a los elementos en enteros
fecha_1[i] = int(fecha_1[i])
f1 = date(fecha_1[2], fecha_1[1], fecha_1[0]) # se utiliza la funcion date para dar formato de fecha para, a posterior
# realizar resta de fechas
lista.append(f1) # se agrega el elemento a lista
# para fecha final (idem anterior, con la salvedad que no se agrega a lista)
fecha_2 = fecha_final
fecha_2 = fecha_2.split('-')
for i in range(len(fecha_2)):
fecha_2[i] = int(fecha_2[i])
f2 = date(fecha_2[2], fecha_2[1], fecha_2[0])
diferencia = f2 - f1 # resta de fechas para obtener la cantidad de dias de diferencia entre la fecha
# inicial y la fecha final
diferencia = int(diferencia.days) # la diferencia de dias entre fecha inicial y fecha final se conviente en entero para
# usarse en el range posterior
fecha = f1
# formar lista entre dos fechas
for i in range(diferencia):
fecha = fecha + timedelta(days=1) # incremento de 1 dia entre cada iteracion
lista.append(fecha) # agregar el elemento a lista
# Diccionario para cambiar el formato numerico al formato alfabetico del mes
mes = {'01':'Ene','02':'Feb','03':'Mar','04':'Abr','05':'May','06':'Jun','07':'Jul',
'08':'Ago','09':'Sep','10':'Oct','11':'Nov','12':'Dic'}
# dar formato de salida
list_accidentes = []
for fecha in lista: # para cada elemento de lista
fecha = str(fecha) # dar formato string a la fecha
fecha = fecha[2:] # solo se tendra en cuenta los ultimos dos digitos del año (Ejemplo: no 2020, sino solo 20)
fecha = fecha.split("-") # aplicacion del metodo split()
for k, v in mes.items(): # cambiar formato numérico de mes por el formato alfabético utilizando diccionario mes
if fecha[1] == k:
fecha[1] = v
fecha = fecha[2] + "-" + fecha[1] + "-" + fecha[0] # concatenar y acomodar los elementos al formato dd-Mmm-aa
list_accidentes.append(fecha) # agrega elemento a list_accidentes
return list_accidentes # retorno list_accidentes
|
import pickle
import re
import printascii
'''
def _isupper(str):
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
res = True
for i in range (len(str)):
if upper.find(str[i])<0:
res = False
break
return res
def level0():
res = 2
for i in range(37):
res = res * 2
print( res)
def level1(str):
print "level1"
res = ""
exd = " .()'"
for i in range(len(str)):
converted = ord(str[i])
if (exd.find(str[i]) < 0 ):
converted += 2
if (converted > 0x7a):
converted -= 26
res = res + chr(converted)
print res
def level2(str):
# find charaters in string
print "level2"
chartable="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"
res = ""
for i in range(len(str)):
if (chartable.find(str[i]) >= 0):
res = res + str[i]
print res
def level3(str):
#One small letter, surrounded by EXACTLY three big bodyguards on each of its sides.
print "level3"
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lower = "abcdefghijklmnopqrstuvwxyz"
res = ""
for i in range(3, len(str)-3):
if (_isupper(str[i-3:i]) and _isupper(str[i+1:i+4]) and str[i].islower()):
if ( ( (i-4)<0 or str[i-4].islower() ) and ( (i+4)>=len(str) or str[i+4].islower() ) ):
res += str[i]
print res
def level4(str):
print "level4"
proxy_support = urllib2.ProxyHandler({"http":"http://espcolo-webproxy00:8080"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
nextURL = ''
while (1):
if (len(nextURL )== 0):
nextURL = raw_input('Enter the url:')
if (len(nextURL )== 0):
break
content = urllib2.urlopen(nextURL).read()
patt = '.* the next nothing is (\d+)'
m = re.match(patt, content)
if(m is None):
nextURL = ''
print 'Next url cannot parsed, The page content is:' + content
continue
nextID = m.group(1)
patt2 = '(.+nothing=)\d+'
m = re.match(patt2, nextURL)
if (m is None):
nextURL = ''
continue
nextURL = m.group(1) + nextID
print nextURL
def geturlobj(str):
proxy_support = urllib2.ProxyHandler({"http":"http://espcolo-webproxy00:8080"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
nextURL=str
if (len(nextURL )== 0):
nextURL = raw_input('Enter the url:')
if (len(nextURL )== 0):
return
return urllib2.urlopen(nextURL)
def level5():
urlobj = geturlobj('http://www.pythonchallenge.com/pc/def/banner.p')
pickobj = pickle.load(urlobj)
for item in pickobj:
#print item
#print "".join(i[0] * i[1] for i in item) #print characters
mylist = []
for i in item:
mylist.append( i[0] * i[1] )
print ''.join(mylist)
def level6():
print 'level 6'
def main():
printascii.print_ascii()
level0()
level1(str)
level2(str)
#level3(str) # linkedlist
#level4(r"http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345")
level5()
'''
class A(object):
ta = 'abc'
@classmethod
def c_f(cls):
print('c_f')
def m_f(self):
print('m_f')
print(self.ta)
self.c_f()
class B(object):
def __init__(self,val, res):
self.val = val
self.res_file = res
if __name__ == '__main__':
# main()
a = A()
a.m_f()
b1 = B(3, 'fdf')
b2 = B(4, 'xxx')
b3 = B(5, 'aaa')
not_in_t2 = [b1, b2, b3]
print (not_in_t2)
not_in_t2.sort(key=lambda x:x.res_file)
print (not_in_t2)
|
#!/bin/python3
import math
import os
import random
import re
import sys
import copy
#
# Complete the 'crosswordPuzzle' function below.
#
# The function is expected to return a STRING_ARRAY.
# The function accepts following parameters:
# 1. STRING_ARRAY crossword
# 2. STRING words
#
def crosswordPuzzle(crossword, words):
# Write your code here
# orgnize words
boards = [crossword]
words = words.split(';')
for w in words:
print(w)
print(boards)
nextBoards = []
for crossword in boards:
nextBoards.extend(fillWordByRow(crossword, w))
nextBoards.extend(fillWordByCol(crossword, w))
boards = nextBoards
return boards[0] if boards else []
def fillWordByRow(crossword, w):
l = len(w)
ws = [w, w[::-1]] # reversed string of w need check as well
boards = [] # possible states of crossword after put w
for i, row in enumerate(crossword):
delms = row.split('+')
for j, delm in enumerate(delms):
for w in ws:
if len(delm) == l and all((w[i] == delm[i] or delm[i] == '-' for i in range(l))):
delms[j] = w
b = copy.deepcopy(crossword)
b[i] = '+'.join(delms)
boards.append(b)
return boards
def fillWordByCol(crossword, w):
# rotate crossword
r = zip(*crossword)
r = [''.join(row) for row in r]
boards = fillWordByRow(r, w)
# revert back
boards = [zip(*b) for b in boards]
return [[''.join(row) for row in b] for b in boards ]
if __name__ == '__main__':
fptr = open(r'd:/test.txt', 'w')
crossword = []
for _ in range(10):
crossword_item = input()
crossword.append(crossword_item)
words = input()
result = crosswordPuzzle(crossword, words)
fptr.write('\n'.join(result))
fptr.write('\n')
fptr.close()
|
class Test(object):
def __init__(self):
self.name = 'abc'
def __enter__(self):
print("created")
return self
def __exit__(self, exc_type, exc_value, traceback):
print("exit")
def test(self):
print(self.name)
print('before')
test = Test()
test.test()
print('after')
with Test() as tt:
print("in with")
print(tt.name)
tt.test()
print("in with")
|
class MinHeap():
__data = []
__size = 0
def push(self, val):
self.__data.append(val)
self.__size += 1
self.__ascend()
return
def size(self):
return self.__size
def pop(self):
temp = self.__data[0]
self.__data[0] = self.__data[self.__size-1]
self.__data.pop()
self.__size -= 1
self.__descend()
return temp
def p(self):
print(self.__data)
def __parent(self, index):
return (index - 1) // 2
def __descend(self):
current = 0
childLeft = current * 2 + 1
childRight = current * 2 + 2
while childLeft < self.__size:
compareTo = childRight
if childRight >= self.__size or self.__data[childLeft] < self.__data[childRight]:
compareTo = childLeft
if self.__data[current] > self.__data[compareTo]:
self.__data[current] , self.__data[compareTo] = self.__data[compareTo], self.__data[current]
current = compareTo
else:
break # small than child
childLeft = current * 2 + 1
childRight = current * 2 + 2
def __ascend(self):
last = self.__size - 1
parent = self.__parent(last)
while self.__data[last] < self.__data[parent] and last > 0:
self.__data[parent],self.__data[last] = self.__data[last],self.__data[parent]
last = parent
parent = self.__parent(last)
if __name__ == '__main__':
mHeap = MinHeap()
a = [11,24,45,22,14,89,8,19,45,67,88,28, 4, 2, 9, 3]
for e in a:
mHeap.push(e)
for i in range(mHeap.size()):
print(mHeap.pop())
mHeap.p()
|
#Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.
def ex_3(a, b, c):
z = [a, b, c]
z.remove(min(a, b, c))
return sum(z)
def ex_3_use():
print(ex_3(4, 1, 9)) |
#Funcion para convertir las letras en números
def convertir(letra): #Utilicé una lista para representar el tablero del juego, esta me permite almacenar
lista = ['A', 'B', 'C', 'D'] #tanto valores enteros (1, 2, 3 y 4) como caracteres (A, B, C y D). No podríamos hacer esto
lista[0] = 1 #en un array si programamos en C
lista[1] = 2
lista[2] = 3
lista[3] = 4
if letra == lista[0]:
letra = int(lista[0])
elif letra == lista[1]:
letra = int(lista[1])
elif letra == lista[2]:
letra = int(lista[2])
elif letra == lista[3]:
letra = int(lista[3])
return letra
x1_l = input("x1: ")
x1 = convertir(x1_l)
y1 = input("y1: ")
nave1 = x1,y1 #Cada nave la almacené en una tupla
print("Nave 1:" , nave1)
x2_l = input("x2: ")
x2 = convertir(x2_l)
y2 = input("y2: ")
nave2 = x2,y2
print("Nave 2: ", nave2)
x3_l = input("x3: ")
x3 = convertir(x3_l)
y3 = input("y3: ")
nave3 = x3,y3
print("Nave 3: ", nave3)
nave = {'nave1': (x1,y1), 'nave2': (x2,y2), 'nave3': (x3,y3)}
print("Nave: ", nave)
np = 40 #np = numero de protones
p_restante = np
a = True
b = True
if x1 == x2 == x3 and y1 != y2 != y3 or x1 != x2 != x3 and y1 == y2 == y3:
print("Continuar")
c = 1
else:
print("La nave está oblicua. Vuelva a intentarlo.")
c = 2
if c == 1:
esc1 = int(input("Escudo 1: "))
esc2 = int(input("Escudo 2: "))
esc3 = int(input("Escudo 3: "))
if 1 <= esc1 <= 9 and 1 <= esc2 <= 9 and 1 <= esc3 <= 9 and c == 1:
print("Continuar")
else:
print("Error. Debe ser una cantidad entre 1 y 9. Vuelva a intentarlo.") #No aclara que pasa si se sale del rango (1-9)
a = False
else:
a = False
while a == True and b == True:
x_l = input("x: ")
x = convertir(x_l)
y = input("y: ")
ataque = x,y
print("Coordenadas de ataque: ", ataque)
carga = int(input("Dispara con: "))
if carga < 1 or carga > 9:
print("No puede disparar menos de 1 protón o más de 9 protones. Vuelva a intentarlo.")
b = False
else:
if carga <= p_restante:
if ataque != nave1 and ataque != nave2 and ataque != nave3:
print("Espacio!")
else:
if ataque == nave1:
if carga > esc1:
print("Sin efecto.")
else:
print("Ataque efectivo.")
r1 = esc1 - carga
esc1 = r1
if esc1 == 0:
print("Escudo neutralizado.")
else:
print("Escudo no neutralizado.")
elif ataque == nave2:
if carga > esc2:
print("Sin efecto.")
else:
print("Ataque efectivo.")
r2 = esc2 - carga
esc2 = r2
if esc2 == 0:
print("Escudo neutralizado.")
else:
print("Escudo no neutralizado.")
elif ataque == nave3:
if carga > esc3:
print("Sin efecto.")
else:
print("Ataque efectivo.")
r3 = esc3 - carga
esc3 = r3
if esc3 == 0:
print("Escudo neutralizado.")
else:
print("Escudo no neutralizado.")
p_restante -= carga
print("En el reactor de protones queda: ", p_restante)
escudo = esc1 + esc2 + esc3
print("Cantidad de electrones que quedan: ", escudo)
if escudo == 0 and p_restante != 0:
print("Ganó el atacante.")
b = False
elif p_restante == 0:
print("Ganó el defensor.")
b = False
else:
print("No puede disparar con una carga mayor a la de protones restantes en el reactor.")
b = False
|
from typing import List
import pandas as pd
from pandas import DataFrame
from sklearn.utils import resample
def balance(frame: DataFrame, label: str, amount: float) -> DataFrame:
"""
:param frame: Data which should be balanced for a label
:param label: label name for which data should be balanced
:param amount: a ratio for balancing 0 => data is not balanced, 1 => both classes are
represented equally.
:return: New balanced DataFrame with reset index
"""
df_majority = frame[frame[label] == False]
df_minority = frame[frame[label] == True]
target_amount = int(df_minority.shape[0] + (1.0 - amount) * (df_majority.shape[0] - df_minority.shape[0]))
df_majority_downsampled = resample(df_majority, replace=False,
n_samples=target_amount, random_state=42)
frame = pd.concat([df_minority, df_majority_downsampled]).sample(frac=1).reset_index(drop=True)
# Display new class counts
print("balanced by amount " + str(amount))
print(frame[label].value_counts())
return frame
def balance_train(x_train, y_train, label: str, amount: float):
xy = pd.concat([x_train, y_train], axis=1, sort=False)
bal = balance(xy, label, amount)
return bal[list(x_train)], bal[list(y_train)]
def relabel_data(frame: DataFrame, new_label: str, features: List[str]) -> DataFrame:
"""
If items have the same feature values but different labels, this function will make a
majority decision which label is correct.
"""
group_by_identical = frame.groupby(features).mean()
comment_percentage_df = frame.merge(group_by_identical,
on=features,
how='inner', suffixes=('_x', '_percentage'))
comment_percentage_df[new_label] = comment_percentage_df['commented_percentage'] >= 0.5
shuffled_frame = comment_percentage_df.sample(frac=1).reset_index(drop=True)
print("Previously false: ", frame.loc[frame['commented'] == False].shape[0])
print("Previously true: ", frame.loc[frame['commented'] == True].shape[0])
now_false_df = shuffled_frame.loc[shuffled_frame[new_label] == False]
now_true_df = shuffled_frame.loc[shuffled_frame[new_label] == True]
print("Now False: ", now_false_df.shape[0])
print("Now True: ", now_true_df.shape[0])
print("Previously trues that became false ", now_false_df.count().comment)
print("Previously false that became true ",now_true_df.shape[0] - now_true_df.count().comment)
print('Pure trues: ', comment_percentage_df.loc[comment_percentage_df['commented_percentage']
>= 1.0].shape[0])
print('Pure False: ', comment_percentage_df.loc[comment_percentage_df['commented_percentage']
<= 0].shape[0])
return shuffled_frame
|
#by Kenzin Igor
TARIFF_11 = 0.244618
TARIFF_31 = 0.136928
def electricity_bill_v1():
print("Electricity Bill Estimator V1.0")
cents_per_kwh = float(input("Enter Cents per kWh: "))
use_in_kwh = float(input("Enter Daily use in kWh: "))
days = float(input("Enter Billing Days"))
total = (use_in_kwh*(cents_per_kwh/100))*days
print("Estimated Bill: $",total)
def electricity_bill_v2():
print("Electricity Bill Estimator V2.0")
tariff= int(input("Which Tariff 11 or 31: "))
use_in_kwh = float(input("Enter Daily use in kWh: "))
days = float(input("Enter Billing Days"))
if(tariff == 11):
total = use_in_kwh*days*TARIFF_11
elif(tariff == 31):
total = use_in_kwh*days*TARIFF_31
print("Estimated Bill: $",total)
def main():
electricity_bill_v1()
electricity_bill_v2()
if __name__ == "__main__":
main() |
"""
CP1404/CP5632 - Practical Solution
Broken program to determine score status
Update: FIXED
by Kenzin Igor
"""
# todo: Fix this!
# Update: FIXED
#Update: From Week 1's source code instead of printing the output i have returned the statement
def fixed_solution(score):
if(0 < score < 50):
return "Bad"
elif(50 <= score < 90):
return "Passable"
elif(90 <= score <= 100):
return "Excellent"
else:
return "Invalid Score"
"""def invalid_solution(score):
if score < 0:
print("Invalid score")
else:
if score > 100:
print("Invalid score")
if score > 50:
print("Passable")
if score > 90:
print("Excellent")
if score < 50:
print("Bad")"""
def main():
flag = True
while flag:
try:
score = float(input("Enter score: "))
except ValueError:
print("Invalid Option Try Again..!!")
print(fixed_solution(score))
if __name__ == "__main__":
main()
|
#by Kenzin Igor
numbers = [3,1,4,1,5,9,2]
print(numbers[0])
print(numbers[-1])
print(numbers[3])
print(numbers[:-1])
print(numbers[3:4])
print(5 in numbers)
print(7 in numbers)
print("3" in numbers)
print(numbers + [6, 5, 3])
# Change the first element of numbers to "ten"
print(numbers)# Change the last element of numbers to 1
print(numbers[2:]) # Get all the elements from numbers except the first two
print(9 in numbers) # Check if 9 is an element of numbers |
import unittest
from stacks_queues.p32 import Stack
class TestStack(unittest.TestCase):
def setUp(self) -> None:
self.stack = Stack()
def test_push(self):
"""
stack << 1 << 4
stack.arr should contain two elements, 1 and 4
:return: void
"""
self.stack.push(1)
self.stack.push(4)
self.assertTrue(len(self.stack.arr) == 2)
self.assertEqual(self.stack.arr[0], 1)
self.assertEqual(self.stack.arr[1], 4)
def test_push_None(self):
"""
stack << None
stack should raise invalid value exception
:return: void
"""
try:
self.stack.push(None)
self.fail("The stack's push function should not accept other values than integers")
except ValueError:
pass
def test_push_str(self):
"""
stack << "hopa"
stack should raise invalid value exception
:return: void
"""
try:
self.stack.push("jora")
self.fail("The stack's push function should not accept other valuers that integers")
except ValueError:
pass
def test_pop(self):
"""
stack << 1 << 4
stack >> 1 >> 4
If 1 then 4 were pushed to stack then first pop should return 4 and second 1
:return: void
"""
self.stack.push(1)
self.stack.push(4)
self.assertEqual(self.stack.pop(), 4)
self.assertEqual(self.stack.pop(), 1)
def test_pop_empty(self):
"""
If the stack is empty the stack should raise a runtime exception.
:return: void
"""
try:
self.stack.pop()
self.fail("Pop on empty stack should raise runtime error.")
except RuntimeError:
pass
def test_min(self):
"""
stack.arr << 3 << 4 << 2 << 5 << 6 << 9 << 0 << 5 << 6
stack.min << 3 << 2 << 0
This test is a sequence of push/pop operation on stack and min interrogation.
:return: void
"""
self.stack.push(3)
self.assertEqual(self.stack.get_min(), 3)
self.stack.push(4)
self.assertEqual(self.stack.get_min(), 3)
self.stack.push(2)
self.assertEqual(self.stack.get_min(), 2)
self.stack.push(5)
self.assertEqual(self.stack.get_min(), 2)
self.stack.push(6)
self.assertEqual(self.stack.get_min(), 2)
self.stack.push(9)
self.assertEqual(self.stack.get_min(), 2)
self.stack.push(0)
self.assertEqual(self.stack.get_min(), 0)
self.stack.push(5)
self.assertEqual(self.stack.get_min(), 0)
self.stack.pop()
self.assertEqual(self.stack.get_min(), 0)
self.stack.pop()
self.assertEqual(self.stack.get_min(), 2)
self.stack.pop()
self.assertEqual(self.stack.get_min(), 2)
self.stack.pop()
self.assertEqual(self.stack.get_min(), 2)
self.stack.pop()
self.assertEqual(self.stack.get_min(), 2)
self.stack.pop()
self.assertEqual(self.stack.get_min(), 3)
self.stack.pop()
self.assertEqual(self.stack.get_min(), 3) |
import unittest
from recursivity.p6 import towers_of_hanoi
class TestTowersOfHanoi(unittest.TestCase):
def test_move(self):
"""
Input:
stack1: [3, 2, 1]
stack2: []
stack3: []
Output:
stack1: []
stack2: []
stack3: [3, 2, 1]
:return: void
"""
stack1 = [3, 2, 1]
stack2 = []
stack3 = []
towers_of_hanoi(stack1, stack2, stack3, 3)
self.assertEqual([3, 2, 1], stack3)
def test_move_bigger(self):
"""
Input:
stack1: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
stack2: []
stack3: []
Output:
stack1: []
stack2: []
stack3: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
:return: void
"""
stack1 = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
stack2 = []
stack3 = []
towers_of_hanoi(stack1, stack2, stack3, 10)
self.assertEqual([10, 9, 8, 7, 6, 5, 4, 3, 2, 1], stack3)
|
"""
Minimal Tree: Given a sorted (increasing order) array with unique integer elements,
write an algorithm to create a binary search tree with minimal height.
Source: Cracking the Coding Interview: 189 Programming Questions and Solutions
by Gayle Laakmann McDowell
"""
class Node:
def __init__(self, data: int):
self.data = data
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def add(self, value: int):
if not isinstance(value, int):
raise ValueError("The argument should be a valid integer.")
if self.root is None:
self.root = Node(value)
else:
curr = self.root
while curr is not None:
if value < curr.data:
if curr.left is not None:
curr = curr.left
else:
curr.left = Node(value)
break
else:
if curr.right is not None:
curr = curr.right
else:
curr.right = Node(value)
break
def add_middle(numbers: list, tree : BinaryTree):
if len(numbers) == 0:
return
if len(numbers) == 1:
tree.add(numbers[0])
else:
middle_idx = int(len(numbers) / 2)
tree.add(numbers[middle_idx])
add_middle(numbers[:middle_idx], tree)
add_middle(numbers[middle_idx + 1:], tree)
def create_minimal_tree(numbers: list) -> BinaryTree:
tree = BinaryTree()
add_middle(numbers, tree)
return tree |
"""
Successor: Write an algorithm to find the "next" node (i.e., in-order successor) of a given node in a
binary search tree. You may assume that each node has a link to its parent.
Source: Cracking the Coding Interview: 189 Programming Questions and Solutions
by Gayle Laakmann McDowell
"""
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
self.parent = None
def get_most_left(n: Node) -> Node:
if n is None:
return None
while n.left is not None:
n = n.left
return n
def get_next(n: Node) -> Node:
if n is None:
raise ValueError("Invalid value. Argument cannot be None.")
next_node = get_most_left(n.right)
if next_node is not None:
return next_node
while n.parent is not None and n.parent.left is not n:
n = n.parent
return n.parent
|
import unittest
from graphs.p4_1 import Node
from graphs.p4_1 import route_exists
class TestRouteExists(unittest.TestCase):
def setUp(self) -> None:
"""
Create graph:
1: 2, 4
2: 3
3: 4
4: 5
5: _
:return: void
"""
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n4 = Node(4)
n5 = Node(5)
n1.children.append(n2)
n1.children.append(n4)
n2.children.append(n3)
n3.children.append(n4)
n4.children.append(n5)
self.start = n1
self.end = n3
def test_route_exists(self):
"""
The function route_exists should return True for start and end nodes.
:return: void
"""
self.assertTrue(route_exists(self.start, self.end))
def test_route_exists_non_existing_route(self):
"""
The function route_exists should return False for start and a new node.
:return: void
"""
self.assertFalse(route_exists(self.start, Node(6)))
def test_route_exists_None(self):
"""
The function route_exists should raise ValueError for None as argument.
:return: void
"""
try:
route_exists(None, None)
self.fail()
except ValueError:
pass
def test_route_exists_int_str(self):
"""
The function route_exists should raise ValueError for int and str as args.
:return: void
"""
try:
route_exists(4, "hopa")
self.fail()
except ValueError:
pass
|
def h(s):
if len(s)<2:
return True
elif s[0]!=s[-1]:
return False
else:
return h(s[1:-1])
if __name__=='__main__':
s=input("请输入一个整数")
if h(s):
print("这个数是回文数")
else:
print("这个数不是回文数")
|
def ctof(c):
# 3 operations
return c*9/5 + 35
def mysum(x):
# 1
total = 0
# 1x
for i in range(x):
# 2x
total += i
return total
# num ops = 1 + 3*x |
def gentest():
yield 1
yield 2
# a = gentest()
# b = gentest()
# print(next(a))
# print(next(a))
# print(next(b))
# print(a.__next__())
def genFib():
fibn_1 = 1 #fib(n-1)
fibn_2 = 0 #fib(n-2)
while True:
# fib(n) = fib(n-1) + fib(n-2)
next = fibn_1 + fibn_2
yield next
fibn_2 = fibn_1
fibn_1 = next
fib = genFib()
print(next(fib))
print(next(fib))
print(next(fib))
print(next(fib))
print(next(fib))
print(next(fib)) |
def applyToEach(L, f):
"""Apply the function to each element in the list"""
for i in range(len(L)):
L[i] = f(L[i])
def fib(n):
if n == 1:
return 1
elif n == 2:
return 2
else:
return fib(n-1) + fib(n-2)
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
L = [1, -2, 3.4]
print(applyToEach(L, abs))
print(applyToEach(L, int))
print(applyToEach(L, factorial))
print(applyToEach(L, fib))
# ==========================================================================================
def applyFuns2(L, x):
"""Apply all functions in the list to integer x"""
for f in L:
print(f(x))
print(applyFuns2([abs, int, factorial, fib], 4))
# ==========================================================================================
# Generation of Higher Order Procedure (HOP) (map)
# - Python provides a general purpose HOP, map
# - Simple form - a unary function (a function that expects only one argument) and
# a collection of suitable arguments
map(abs, [1, -2, 3, -4])
# Produces an 'iterable', so need to walk it down
for elt in map(abs, [1,-2, 3, 4]):
print(elt)
# General form with N-ary functions:
L1 = [1, 28, 36]
L2 = [2, 57, 9]
map(min, L1, L2)
for elt in map(min, L1, L2):
print(elt)
# This returns the minimum of the two lists in each place
|
a=int(input("Enter 1 for Even\n Enter 2 for odd\n"))
if(a==1):
b=2
elif(a==2):
b=3
else:
print("Wrong input -1")
for i in range(1,100):
if(i%b==0):
print(i)
|
nome = input("Digite um nome: ")
y = len(nome)
while y != 0:
print("%s" %nome[0:y])
y = y-1
|
#!/usr/bin/env python3
#
# connections.py is responsible for converting a connection string
# in URI form to component parts for MySQL or SQLite3 databases.
#
import os
from urllib.parse import urlparse
class ConnectionInfo:
'''ConnectionInfo provides a means to parse a URI containing a
DB connection and split it into a components.
Examples:
con_info = ConnectionInfo()
# Parse a MySQL connection string
if con_info.parse("mysql://USER:PASSWD@example.edu/DB_NAME"):
print(f'host: {con_info.host}:{con_info:port}')
print(f'DB Name: {con_info.name}')
else:
print("Can't parse URL for DB connect')
# Parse an SQLite3 connection string
if con_info.parse("sqlite3://PATH_TO_DB/DB_NAME"):
print(f'host (None:None): {con_info.host}:{con_info:port}')
print(f'DB Name (Path to Sqlite3 DB): {con_info.name}')
else:
print("Can't parse URL for DB connect')
'''
db_type = None
host = None
port = None
name = None
user = None
password = None
def __init__(self, host = None, port = None, name = None, user = None, password = None):
self.host, self.port, self.name = host, port, name
self.user, self.password = user, password
def parse(self, uri):
u = urlparse(uri)
if u.scheme == 'sqlite3':
self.db_type = 'sqlite3'
self.host, self.port, self.name = None, None, None
self.user, self.password = None, None
if u.host and u.path:
self.name = os.path.join(u.host, u.path)
elif u.path:
self.name = u.path
else:
return False
if u.scheme == 'mysql':
self.db_type = u.scheme
self.name, self.user, self.password = '', '', ''
if u.hostname:
self.host = u.hostname
else:
self.host = 'localhost'
if u.port:
self.port = u.port
else:
self.port = '3306'
if len(u.path) > 1:
self.name = u.path[1:]
if u.username:
self.user = u.username
if u.password:
self.password = u.password
def to_dict(self):
if self.db_type == 'mysql':
return { 'user': self.user, 'password': self.password,
'host': self.host, 'port': self.port,
'database': self.name, 'raise_on_warnings': True }
elif self.db_type == 'sqlite3':
return { 'db': self.name }
else:
return None
|
"""
This script start the generation of random TestBench, it ask how many testbench
to generate
"""
import generator
print("inserisci il numero di test da generare")
num = int(input())
while(num>0):
print("Sto generando")
generator.generate()
num = num -1
input("Premi per terminare")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.