text
stringlengths 37
1.41M
|
---|
mood = int(input("How do you feel? (1-10) "))
if mood == 1:
print("A suitable smiley would be :'(")
elif mood == 10:
print("A suitable smiley would be :-D")
elif (7 < mood < 10):
print("A suitable smiley would be :-)")
elif (4 <= mood <= 7):
print("A suitable smiley would be :-|")
elif (1 < mood < 4):
print("A suitable smiley would be :-(")
else:
print("Bad input!")
|
player1 = input("Player 1, enter your choice (R/P/S): ")
player2 = input("Player 2, enter your choice (R/P/S): ")
if ((player1 == "P" and player2 == "R") or (player1 == "R" and player2 == "S") or (player1 == "S" and player2 == "P")):
print("Player 1 won!")
elif ((player2 == "P" and player1 == "R") or (player2 == "R" and player1 == "S") or (player2 == "S" and player1 == "P")):
print("Player 2 won!")
else:
print("It's a tie!")
|
# in this tutorial we learn how to use special methods to enable a logarithmic and special operations for the objects
class employee:
def __init__(self,first,last,salary):
self.first = first
self.last = last
self.email = self.first+'.'+self.last+'@gmail.com'
self.salary = salary
# an example of using instance method
def employee_details(self):
return 'the employee is {} {},his email is {} and get paid a salary of {}'.format(self.first, self.last, self.email, self.salary)
def __repr__(self):
return "Employee('{}', '{}', {})".format(self.first, self.last, self.salary)
def __str__(self):
return "Employee('{}', '{}')".format(self.first, self.last)
def __add__(self, other):
return self.salary+other.salary
def __len__(self):
return len('{} {}'.format(self.first, self.last))
# return len(self.first, self.last)
employee1 = employee('ahmed', 'mostafa', 2000)
employee2 = employee('mahmoud', 'hassan', 2200)
employee3 = employee('hosaam', 'ali', 2400)
print(employee1+employee2)
print(employee1+employee3)
print(len(employee1))
print(employee1) # runs the __str__ method to represent the instance in string format
print(employee1.__repr__())
|
def mirror_tree(root):
if root == None: return
# Do a post-order traversal of the binary tree
if root.left != None:
mirror_tree(root.left)
if root.right != None:
mirror_tree(root.right)
# Swap the left and right nodes at the current level
temp = root.left
root.left = root.right
root.right = temp
|
def fruits_into_baskets(fruits):
window_start = 0
max_length = 0
fruit_frequency = {}
# In this loop, we extend the range [window_start, window_end]
for window_end in range(len(fruits)):
right_fruit = fruits[window_end]
if right_fruit not in fruit_frequency:
fruit_frequency[right_fruit] = 0
fruit_frequency[right_fruit] += 1
# Shrink the sliding window, until we are left with 2 fruits in the fruit_frequency
while len(fruit_frequency) > 2:
left_fruit = fruits[window_start]
fruit_frequency[left_fruit] -= 1
if fruit_frequency[left_fruit] == 0:
del fruit_frequency[left_fruit]
window_start += 1 # shrink the window
# remember the maximum length so far
max_length = max(max_length, window_end - window_start + 1)
return max_length
|
class stack_using_queues:
def __init__(self):
self.queue1 = deque()
self.queue2 = deque()
def push(self, data):
self.queue1.append(data)
def isEmpty(self):
return len(self.queue1) + len(self.queue2) == 0
def pop(self):
if self.isEmpty():
raise Exception("Stack is empty")
while len(self.queue1) > 1:
self.queue2.append(self.queue1.popleft())
value = self.queue1.popleft()
self.swap_queues()
return value
def swap_queues(self):
self.queue3 = self.queue1
self.queue1 = self.queue2
self.queue2 = self.queue3
|
def can_segment_string(s, dict):
for i in range (1, len(s) + 1):
first = s[0:i]
if first in dict:
second = s[i:]
if not second or second in dict or can_segment_string(second, dict):
return True
return False
|
# Exercises for chapter 3: Problems 3.1, 3.2, 3.3, and 3.4 in Think Python
# chrisvans - Chris Van Schyndel
# 3.1
# NameError: name 'repeat_lyrics' is not defined
# 3.2
# The program runs properly. Function order does not matter, as long as it
# is defined before it is called.
# 3.3
def right_justify(s):
print ' ' * (70 -len(str(s))) + str(s)
right_justify("bagel")
# 3.4
def do_twice(f, s):
f(s)
f(s)
def print_spam():
print 'spam'
def print_twice(message):
print message
print message
do_twice(print_twice, 'spam')
def do_four(function, value):
do_twice(function, value)
do_twice(function, value)
do_four(print_twice, 'spam')
|
l=[1,2,3,3,3,4,1]
a=set(l)
#print a
b=list(a)
print b
l1=[]
for i in a:
result=l.count(i)
l1.append(result)
print l1
d=dict(zip(b,l1))
print d
|
l=[]
def f():
for i in range(1,21):
l.append(i**2)
print l
print l[0:5]
t=tuple(l)
print t
f()
|
import time
credit = 700
total = 1200
class Debitcard():
def debitvalue(self, count):
global total
string = raw_input("you want to pay(p),withdraw(w) and exit(e)")
if string == 'pay':
value = int(input("enter value"))
total += value
print("Your total Balance is = {} (Time : {})".format(total, time.asctime()))
elif string == 'wid':
value = int(input("enter value"))
total -= value
print("Your total Balance is = {} (Time : {})".format(total, time.asctime()))
elif string == 'exit':
count = 3
print ("Thank You")
class Creditcard(Debitcard):
def creditvalue(self, count):
global credit
global total
s = raw_input("You want to pay, Withdraw and exit:")
if s == 'pay':
value = int(input("enter value"))
total = total - value
print("Total Balance of debitcard is = {} (Time : {})".format(total, time.asctime()))
credit = credit + value
print("Total Balance of creditcard is = {} (Time : {})".format(credit, time.asctime()))
elif s == 'wid':
value = int(input("enter value"))
credit = credit - value
print("Total Balance is = {} (Time : {})".format(credit, time.asctime()))
elif s == 'exit':
count = 3
print('Thank You')
class main:
def main():
count = 0
debit = Debitcard()
credit = Creditcard()
while count < 3:
count = count + 1
account = raw_input("Enter Options :- credit or debit")
if account == 'debit':
debit.debitvalue(count)
elif account == 'credit':
credit.creditvalue(count)
elif account == 'exit':
print("Thank You")
break
if __name__ == "__main__": main()
|
s=raw_input()
d={"UPER CASE":0,"LOWER CASE":0}
for i in s:
if (i.isupper()):
d["UPER CASE"]+=1
elif (i.islower()):
d["LOWER CASE"]+=1
print "UPER CASE",d["UPER CASE"]
print "LOWER CASE",d["LOWER CASE"]
|
def choose(a, b):
res = 0
for i in range()
#Calculates how much one powerball ticket is worth based on EV
#These are odds as of 10/30/22
def ticket_worth(jackpot):
total_possibilities = 69*68*67*66*65*26
prizes = [jackpot, 1000000, 50000, 100, 100, 7, 7, 4, 4]
poss_for_each = [1, 25, 64, 64*25, 64*63, 64*63*25, 64*63*62, 64*63*62*61, 64*63*62*61*60]
odds_for_each = [x/total_possibilities for x in poss_for_each]
EV = 0
for i in range(len(prizes)):
EV += prizes[i] * odds_for_each[i]
print(odds_for_each)
return EV
print(ticket_worth(1000000000))
|
class Cell():
''' This enumeration represents the possible states of a cell on the board '''
empty = 46
w = 119
W = 87
b = 98
B = 66
def isWhite(c):
return c == Cell.w or c == Cell.W
def isBlack(c):
return c == Cell.b or c == Cell.B
def isMan(c):
return c == Cell.w or c == Cell.b
def isKing(c):
return c == Cell.W or c == Cell.B
def invertColor(c):
if c == Cell.empty: return Cell.empty
return v + 42*(1-v%2) - 21
def promoted(c):
assert(Cell.isMan(c))
return c-32
def toString(c):
return chr(c)
|
# 1. Letter Summary
# Write a letter_histogram program that asks the user for input, and prints a dictionary containing the tally of how many times each letter in the alphabet was used in the word. For example:
# def letter_histogram(word):
# my_letters = {}
# for letter in word:
# if letter in my_letters:
# my_letters[letter] += 1
# else:
# my_letters[letter] = 1
# return my_letters
# print(letter_histogram("Wolverine"))
# 2. Word Summary
# Write a word_histogram program that asks the user for a sentence as its input,
# and prints a dictionary containing the tally of how many times each word in the alphabet was used in the text.
def word_histogram(paragraph):
dict_of_letters = {}
paragraph = input("What is your sentence? : ")
paragraph = paragraph.lower().split()
for word in paragraph:
if word in dict_of_letters:
dict_of_letters[word] += 1
else:
dict_of_letters[word] = 1
return dict_of_letters
print(word_histogram("To be or not to be."))
def most_common(word_histogram):
c = []
for key, value in word_histogram.items():
c.append((value, key))
c.sort(reverse=True)
return c
c = most_common(word_histogram)
print('The most common words are:')
for freq, word in c[:3]:
print(word, freq, sep='\t')
# This kind of works, but I keep getting errors so...
|
def findSum():
with open('input.txt', 'r') as f:
array = []
for line in f:
array.append(int(line))
#print ("did a line \n")
numSum = 0
for i in range(len(array)):
numSum += array[i]
#print ("added one from array \n")
print (numSum)
findSum()
|
def sumOfSquares(num):
sums= 0
for i in range(1, num+1, +1):
sums = sums + (i*i)
return sums
def squareOfSum(num):
sums = 0
for i in range(1, num+1, +1):
sums = sums + i
squares = sums*sums
return squares
num =100
difference = squareOfSum(num) - sumOfSquares(num)
print "%d" % difference
|
print('What is your name?: ')
name = input()
print('Your age please!: ')
age = int(input())
if name == 'Mary':
print('Hello Mary')
elif age < 12:
print('You are not Mary, Kiddo.')
else:
print('Stranger!')
print('Gimme your password: ')
password = input()
if password == 'swordfish' :
print('Access granted.')
else:
print('wrong!')
|
print('Python과 Ruby공통 : ceil은 반올림,floor는 내림')
print("Python에서 복잡한 사칙연산을 할 때는 가장 위에 import math를 입력해야 함")
print("Python에서는 'math ceil(2.24)'와 같은 형식으로 입력해야 함")
print('Ruby에서는 "puts(2.24.floor())"와 같은 형식으로 입력해야 함')
print('hello '+'world')
print('python '*3)
print('hello' [1], '<-hello의 2번째 문자 추출. []를 이용해서 특정 문자를 추출할 수 있음')
|
class Cal(object):
def __init__(self, v1, v2):
self.v1 = v1
self.v2 = v2
def add(self):
return self.v1 + self.v2
def subtract(self):
return self.v1 - self.v2
def setV1(self, v1):
if isinstance(v1, int):
self.v1 = v1
def getV1(self):
return self.v1
class CalMultiply(Cal):
def multiply(self):
return self.v1 * self.v2
class CalDivide(CalMultiply):
def divide(self):
return self.v1 / self.v2
# 상속을 활용하면 재활용성의 증대임
# 장기적으로는 재활용성 외에 다른 면에서도 유용함
c1 = CalMultiply(10, 10)
print(c1, c1.add())
print(c1, c1.multiply())
c2 = CalDivide(20, 10)
print(c2, c2.subtract())
print(c2, c2.divide())
|
print(type('har'))
name = 'har'
print(name)
print(type(['har', 'new year', 'korean']))
names = ['har', 'new year', 'korean', 33, True]
print(names[4])
names[1] = 2019
print(names)
|
a = int(input("Enter the 1st Number :- "))
b = int(input("Enter the 2nd Number :- "))
c = int(input("Enter the 3rd Number :- "))
if a>b and a>c:
print("A is Greater than B and C .")
if b>a and b>c :
print("B is greater than A and C .")
if c>a and c>a:
print("C is greater than A and B .")
|
import os
# operating system
# get file names in a folder in Python
# get the files from here
# https://s3.amazonaws.com/udacity-hosted-downloads/ud036/prank.zip
def rename_files():
#(1) get file names from a folder
file_list = os.listdir("/Users/bp/Documents/takeBreakProgram/prank")
# for windows os.listdir(r"c:\oop\prank") r for row path
# print(file_list)
saved_path = os.getcwd()
print(saved_path)
os.chdir("/Users/bp/Documents/takeBreakProgram/prank")
#(2) for each file, rename fileName
# use file_name.translate function
for file_name in file_list:
print("Old Name of the File:-" + file_name)
print("New Name of the File:-" + file_name.translate(None, "0123456789"))
os.rename(file_name, file_name.translate(None, "0123456789"))
os.chdir(saved_path)
rename_files()
'''
What would happen if
1) We try to rename a file that does not exist
2) We try to rename a file to a name that already exists in the folder
we have to learn the concept called exception
'''
|
from math import sqrt
from time import time
primes = [2]
def new_square(old_n):
n = old_n + 1
square = n ** 2
return square, n
def inner_loop(num, base_in):
for x in primes:
if num % x == 0:
return False
if x >= base_in:
return True
start = time()
square, base = new_square(1)
for i in range(3, 25000000, 2):
if i > square:
square, base = new_square(base)
is_prime = inner_loop(i, base)
if is_prime:
primes.append(i)
end = time()
print(primes[-1])
print(end - start)
|
# https://en.wikipedia.org/wiki/United_States_presidential_election
# This Wikipedia page has a table with data on all US
# presidential elections. Goal is to scrape this data
# into a CSV file.
# Columns:
# order
# year
# winner
# winner electoral votes
# runner-up
# runner-up electoral votes
# Use commas as delimiter.
# Ex: 1st, 1788-1789, George Washington, 69, John Adams, 34
# Hint: Use the pdb debugger
import bs4
import urllib.request
import csv
import os
url = "https://en.wikipedia.org/wiki/United_States_presidential_election"
data = urllib.request.urlopen(url).read()
soup = bs4.BeautifulSoup(data, "html.parser")
years = [str(year) for year in range(1788,2016,4)] # list of years as strings
os.remove("elections.csv")
with open("elections.csv", "a") as csvfile:
data_writer = csv.writer(csvfile, delimiter=",")
data_writer.writerow(["Order","Year","Winner","Winner Electoral Votes","Runner-up","Runner-up Electoral Votes"])
data_writer = csv.writer(csvfile, delimiter=",")
# for year in years:
year = years[0]
tables = soup.findAll('table.wikitable')
for table in tables:
anchor = table.find('a', text="1796")
print(anchor)
# anchors = [soup.find('a', text=year) for year in years]
year_DOM = anchor.parent.parent
# print(year)
#winner = anchor.findNext('td').findNext('td') # George Washington
winner = anchor.parent
# winner_name = winner.text # George Washington
# winner_elec_votes = winner.findNext('td').findNext('td').findNext('td').findNext('td').text.split("/")
# winner_elec_votes = winner.parent.find("span.nowrap")
print(year,winner.text)
# winner_elec_votes = float(winner_elec_votes[0])
# print(winner_elec_votes) # 69
# print(runner_up_elec_votes) #138
# runner-up
runner_up = year_DOM.findNext('tr').find('td').findNext('td')
if "[" in runner_up.text:
runner_up_name = runner_up.text.split("[")[0]
else:
runner_up_name = runner_up.text
# print(runner_up.text.split("[")[0]) # John Adams
runner_up_elec_votes = runner_up.findNext('td').findNext('td').findNext('td').findNext('td').text.split("/")
# runner_up_elec_votes = float(runner_up_elec_votes[0])
# print to CSV
# data_writer.writerow([1,year,winner.text,winner_elec_votes,runner_up_name,runner_up_elec_votes])
# print(anchors)
# first_rows = [soup.find(anchor.parent) for anchor in anchors]
# winners = [soup.find(first_rows).findNext('td').findNext('td')]
# print(winners)
|
def reverse(i,word):
j=len(i)
k=len(word)
x=0
y=0
flag=0
while x<j:
if (i[x]==word[0]):
while(k>y):
if(i[k]==" ")and(i[k]!=word[y]):
break
k=k-1
y=y+1
else:
flag=1
x=x+1
if(flag==1):
return True
else:
return False
|
def swap(x,y):
temp=x
x=y
y=temp
x=2
y=3
swap(x,y)
print("x is",x)
print("y is",y)
|
def fib(n):
if (n==0)or(n==1):
return n
else:
r=fib(n-1)+fib(n-2)
return r
terms=int(input("enter an integer"))
for i in range(terms):
f=fib(i)
print(f)
|
num=int(input("enter a number"))
k=""
while num>0:
remainder=num%2
num=num//2
k=str(remainder)+k
print(k)
|
a,b,c,d=int(input("enter 4 numbers")),int(input()),int(input()),int(input())
if(a>b):
if(a>c):
if(a>d):
print(a,"is te greatest number")
else:
print(d,"is the greatest number")
elif(c>d):
print(c,"is the greatest number")
elif(b>c):
if(b>d):
print(b,"is the greatest number")
else:
print(d,"is the greatest number")
else:
if(c>d):
print(c,"is the greatest number")
else:
print(d," is the greatest number")
|
a=int(input("enter a number"))
if(a>=0):
print(0-a)
elif(a==0):
print(0)
else:
print(0-a)
|
def sum1(n):
if n<=1:
return n
else:
return n+sum1(n-1)
print(sum1(6))
|
x=[[0,0,0],[0,0,0],[0,0,0]]
for i in range(len(x)):
for j in range(len(x[0])):
x[i][j]=int(input("ente
for k in x:
print(k)
|
items = [float, list, 5, 3, 4, 234,4435,34, 34, 2,3,32]
for item in items:
if str(item).isnumeric() and item>6:
print(item)
|
#Faulty calculator
# 45 * 3 =555, 56 + 9 = 77, 56/6 = 4
N1 = int(input("Enter first number: "))
print("What to do? +,-,/,*")
operator = input()
N2 = int(input("Enter second number: "))
if N1==45 and N2==3 and operator=="*":
print("N1","*", "N2", "=" , 555)
elif N1==56 and N2==9 and operator=="+":
print("N1", "+", "N2", "=" , 77)
elif N1==56 and N2==6 and operator=="/":
print("N1", "/" , "N2", "=" , 4)
elif operator == "+":
Sum = N1 + N2
print("Sum is", Sum)
elif operator == "*":
Multiplication = N1 * N2
print("Multiplication is", Multiplication)
elif operator == "-":
Sub = N1 - N2
print("Subtraction is", Sub)
elif operator == "/":
div = N1/N2
print("Division is", div)
else:
print("Error! It is not valid")
|
"""Finds the maximum product of adjacent numbers."""
from operator import mul
def _load_grid(file_name):
"""Loads a grid of numbers from a file.
Args:
file_name - Name of the grid file.
Returns:
List of lists of ints.
"""
grid = list()
with open(file_name, 'r') as grid_file:
for line in grid_file:
gridLine = list()
for n in line.split(' '):
gridLine.append(int(n))
grid.append(gridLine)
return grid
def find_max_adjacent(grid, agg, num):
"""Finds the maximum set of adjacent (including diagonals) numbers
determined by the aggregator function.
Args:
grid - List of lists of numbers
agg - Aggregator function to maximize
num - Number of sequential numbers to test.
Returns:
Maximum number.
"""
dp_grid = [[0 for i in xrange(len(grid[0]))]
for j in xrange(len(grid))]
for i in xrange(len(dp_grid)):
for j in xrange(len(dp_grid[0])):
max_up = 0 if i == 0 else dp_grid[i-1][j]
max_left = 0 if j == 0 else dp_grid[i][j-1]
if j <= len(grid[0]) - num:
right = reduce(agg, grid[i][j:j+num])
else:
right = 0
if i <= len(grid) - num:
down_vector = [grid[i+k][j] for k in xrange(num)]
down = reduce(agg, down_vector)
else:
down = 0
if j <= len(grid[0]) - num and i <= len(grid) - num:
diag_right_vector = [grid[i+k][j+k] for k in xrange(num)]
diag_right = reduce(agg, diag_right_vector)
else:
diag_right = 0
if j >= num and i <= len(grid) - num:
diag_left_vector = [grid[i+k][j-k] for k in xrange(num)]
diag_left = reduce(agg, diag_left_vector)
else:
diag_left = 0
dp_grid[i][j] = max([max_up, max_left, right, down, diag_right, diag_left])
return dp_grid[-1][-1]
def main():
grid = _load_grid('problem-11/grid.txt')
# NOTE: We could use a lambda function combining sum and checking to see
# that not all 4 are 0, but this way we can do it in 1 pass. This is far
# slower than the alternative.
print find_max_adjacent(grid, mul, 4)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 5 14:19:30 2020
@author: mboodagh
"""
""" The purpose of this program is to read and write data related to the behavior of a Racoon named George based on the given instructions"""
#import required modules
import math
##### Required functions section begin
# A function for finding the mean
def meanofrac(a):
s=0;
for i in range(len(a)):
s=s+a[i]
average=s/len(a)
return average
# A function for finding the cumulative sum
def cumsumrac(b):
for j in range(len(b)):
for i in range(j):
if j>0 :
b[j]=b[i]+b[j]
return b
# A function for finding the distance traveled
def distanceofrac(X,Y):
d=[3]*(len(X))
for i in range(0,len(X)-1):
d[0]=0
d[i+1]=math.sqrt((X[i+1]-X[i])**2+(Y[i+1]-Y[i])**2)
return d
##### Required functions section end
#####opening the file section beging
#directory of the file
file_dir="/home/mboodagh/ABE65100/using-Files-and-simple-data-structures-with-python/03-working-with-files-in-python-mboodagh/"
#name of the file you would like to open
file_to_open="2008Male00006.txt"
#open the file
fin = open( file_dir+file_to_open, "r" )
#####opening the file section end
#####Dictionary of the given data section begin
#find the header values by reading the first line
header_nonsplit=fin.readline()
# get rid of the new line character \n
header=header_nonsplit.strip().split(",")
# read lines from line2
lines = fin.readlines()
#store the last line information
last_message=lines[len(lines)-1]
#closing the file
fin.close()
#Creating a file named Data to store all the information
Data = [0]*len(lines)
for lidx in range(len(lines)):
Data[lidx] = lines[lidx].strip().split(",")
#defining a new Dictionary
Rac_behavior=dict()
#determining keys by assigning initial values to them
for i in range(len(header)):
Rac_behavior[header[i]]=Data[0][i]
# adding to the values associated with each key by the separtor','
for i in range(len(header)):
for j in range(1,len(lines)-1):
Rac_behavior[header[i]]+=','
Rac_behavior[header[i]]+=(Data[j][i])
#columns having floating numbers
float_column=[4,5,8,9,10,11,12,13,14]
#columns having integers there are no integer columns in the data
integer_column=[]
#turning related strings into floating ones
for i in float_column:
ch=(Rac_behavior[header[i]].strip().split(","))
for j in range(len(ch)):
ch[j]=float(ch[j])
Rac_behavior[header[i]]=ch
#turning related strings into integers
for i in integer_column:
ch=(Rac_behavior[header[i]].strip().split(","))
for j in range(len(ch)):
ch[j]=int(ch[j])
Rac_behavior[header[i]]=ch
#####Dictionary section of the given data end
##### Defining a new dictionary section begin
#finding the distance that the racoon has traveled
dis=distanceofrac(Rac_behavior[header[4]],Rac_behavior[header[5]])
#adding the distane to the dictionary
Rac_behavior['Distance']=dis
disp=dis
##### Defining a new dictionary section end
######calculating average and total values section begin
#finding the averge of X
ave_X=meanofrac(Rac_behavior[header[4]])
#finding the averge of y
ave_Y=meanofrac(Rac_behavior[header[5]])
#finding the mean energy level
ave_Energy=meanofrac(Rac_behavior['Energy Level'])
#finding the total distance geoerge has travelel through his journey
total_dis=cumsumrac(dis)[len(dis)-1]
######calculating average and total values section end
#####writing the ouput data section begin
#name of the ouput file
output_filename="Georges_life.txt"
#create the file
f=open(file_dir+output_filename,"w")
Racoon_name='George'
#create the lines you want to print
newlines="Racoon name: {} \nAverage location: {}, {}\nDistance traveled: {}\nAverage energy level: {}\nRaccoon end state: {} ".format(Racoon_name,ave_X,ave_Y,total_dis,ave_Energy,last_message)
#write the header lines
f.writelines(newlines)
#write a black line
f.write('\n')
#defining the new headers
col_toprint=['Day', 'Time', ' X', ' Y', ' Asleep', 'Behavior Mode', 'Distance']
bibi=[0]*len(col_toprint)
#separating strings in the dictionary defining a variable bibi for storing the data
for i in range(len(col_toprint)):
if i==2 :
bibi[i]=Rac_behavior[col_toprint[i]]
elif i==3 :
bibi[i]=Rac_behavior[col_toprint[i]]
elif i==6 :
bibi[i]=Rac_behavior[col_toprint[i]]
else:
bibi[i]=Rac_behavior[col_toprint[i]].split(",")
bibi[len(bibi)-1]=distanceofrac(Rac_behavior[header[4]],Rac_behavior[header[5]])
# write the header
for i in range(len(col_toprint)):
f.write(col_toprint[i]+' ')
# write the rows
for j in range(len(lines)-1):
f.write('\n')
for i in range(len(bibi)):
f.write("{} ".format(bibi[i][j]))
#####writing the ouput data section end
|
# Solution of Question2
# No any input validations.
# Usage: $python3 question2.py
# Enter number of strings you will entered in the first line.
# Enter strings line by line starting from the second line.
# =============
# Example input:
# Number of strings you will entered: 2
# ababaa
# aa
# =============
# getPrefixes gets a string, and returns the list of its prefixes.
def getPrefixes(string):
counter = 0
result = []
while counter < len(string):
result.append(string[counter : len(string) + 1])
counter += 1
return result
# findSimilarity gets two strings, and returns the number of matched prefixes of two.
def findSimilarity(first, second):
result = 0
counter = 0
while counter < len(first) and counter < len(second):
if first[counter] == second[counter]:
result += 1
else:
break
counter += 1
return result
# calculateSumOfString gets a string, and calculate the total similarity result with its prefixes.
def calculateSumOfString(string):
prefixes = getPrefixes(string)
result = 0
for prefix in prefixes:
result += findSimilarity(string, prefix)
return result
# main calls calculateSumOfString n times where n will be the number of strings you will entered.
def main():
n = int(input('Number of strings you will entered: '))
stringList = []
for i in range(n):
stringList.append(input())
# we get the strings above part, now calculate similarities for each below.
print("== OUTPUT == ")
for string in stringList:
print(calculateSumOfString(string))
main()
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
self.total = 0
def sum_left(node, is_left = False):
if not node:
return
sum_left(node.left, True)
if not node.left and not node.right and is_left:
self.total += node.val
sum_left(node.right)
sum_left(root)
return self.total
|
#!/usr/bin/python3
# -*- conding:utf-8 -*-
import sys
import pygame
from Button import Button
from register_window import register_window
from login_window import login_window
from success_window import *
#小程序的main函数,调用登录和注册两个函数
def run_game():
pygame.init()
while True: #main loop for the game
pygame.display.set_caption("Sudoku World") #window name
screen = pygame.display.set_mode((400,500),0,32) #window size
background = pygame.Surface(screen.get_size())#draw the background
bg_color = (230,230,230)#designate the background's color
background.fill(bg_color)
font = pygame.font.Font('Calib.ttf',30)#设定字体
text = font.render("Welcome to Sudoku World!",True,(50,150,255))#设定文本与颜色
center = (background.get_width()/2, background.get_height()/2-100)#get the corrdinates of the center
textposition = text.get_rect(center = center)
button_register = Button('Graphs/register_btn_on.png','Graphs/register_btn_off.png',(200,300))
button_login = Button('Graphs/login_btn_on.png','Graphs/login_btn_off.png',(200,400))
background.blit(text, textposition)#add text to background according to coordiante
screen.blit(background,(0,0))#paste backgroud to the screen
button_register.render(screen)#render the button
button_login.render(screen)#render the button
for main_event in pygame.event.get():#event decision
if main_event.type == pygame.QUIT:
sys.exit()
elif (main_event.type == pygame.MOUSEBUTTONDOWN and button_register.isOver() == True):
register_window(screen,background,bg_color)
elif (main_event.type == pygame.MOUSEBUTTONDOWN and button_login.isOver() == True):
login_window(screen,background,bg_color)
pygame.display.update() #update the display
run_game()
|
"""
This file implements diffusion of a bunch of particles
put in a bath. the system description id given in diffusion_models.py
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation
from diffusion_models import *
step = infinite_surface # check diffusion_models.py for more
N = 5000 # Number of particles
x = np.random.random(N)-0.5
y = np.random.random(N)-0.5
vx = np.zeros_like(x)
vy = np.zeros_like(y)
dt = 0.001
# Plots
fig = plt.figure()
fig.subplots_adjust(left = 0,
right = 1,
bottom = 0,
top = 1)
ax = fig.add_subplot(111, aspect='equal',
autoscale_on=False,
xlim=(-10, 10),
ylim=(-10, 10))
plt.axis("off")
p, = ax.plot(x, y, 'o', c="#2E30FF", ms=1)
def animate(i):
"""
animation routine for matplotlib.animation
"""
global x, y, vx, vy
x, y, vx, vy = step(x, y, vx, vy, dt)
# updating plot
p.set_data(x, y)
return p,
ani = animation.FuncAnimation(fig, animate,
frames=2000,
interval=10,
blit=True)
# ani.save('output/diffusion.mp4', fps=100)
plt.show()
|
'''
This is an animation showing a standing wave in a cavity
'''
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
n = 2
a = 10
E0 = 5
c = 3
x = np.linspace(0,a,100)
t = np.linspace(0,10,100)
E = E0*np.sin(n*(np.pi/a)*x)
fig = plt.figure()
ax = fig.add_subplot(111,xlim=(0,a), ylim=(-E0-5,E0+5))
plt.title("n = {}".format(n))
line, = ax.plot([], [])
def init():
line.set_data([], [])
return line
def animate(i):
time = np.sin(1000*np.pi*(n/a)*i)
Et = E*time
line.set_data(x,Et)
return line
ani = animation.FuncAnimation(fig, animate, t,
interval=25, init_func=init)
plt.show()
|
"""
Student Naam: Wouter Dijkstra
Student Nr. : 1700101
Klas : ??
Docent : [email protected]
"""
class ListNode:
def __init__(self,data, next_node):
self.data = data
self.next = next_node
def __repr__(self):
return str(self.data)
class MyCircularLinkedList:
def __init__(self):
self.tail = None
def __repr__(self):
s = ''
if not self.tail:
return "Empty list"
current = self.tail.next
if current:
s = str(current)
current = current.next
while current is not None and current != self.tail.next: # while not looped
s = s + ", " + str(current)
current = current.next
return s
def append(self, e):
if not self.tail:
self.tail = ListNode(e, None)
self.tail.next = self.tail
else:
self.tail.next = ListNode(e, self.tail.next)
self.tail = self.tail.next
def delete(self, e):
if self.tail:
if self.tail.data == e:
if self.tail.next == self.tail:
self.tail = None
else:
current = self.tail
while current.next is not self.tail:
current = current.next
current.next = self.tail.next
self.tail = current
else:
current = self.tail
while current.next is not self.tail and current.next.data != e:
current = current.next
if current.next.data == e:
current.next = current.next.next
self.tail = current
if __name__ == '__main__':
my_list = MyCircularLinkedList()
print(my_list)
my_list.append(1)
my_list.append(2)
my_list.append(3)
my_list.append(4)
print(my_list)
print('-------')
my_list.delete(4)
print(str(my_list) + " <------- 4 was deleted")
my_list.delete(1)
print(str(my_list) + " <------- 1 was deleted")
my_list.delete(3)
print(str(my_list) + " <------- 3 was deleted")
my_list.delete(2)
print(str(my_list) + " <------- 2 was deleted")
|
"""
Student Naam: Wouter Dijkstra
Student Nr. : 1700101
Klas : ??
Docent : [email protected]
"""
"""
Description
-----------
Takes an integer n to return all the prime numbers from 2 to n
Parameters
----------
n : integer
amount of numbers to check
Return
------
primes : list
list of prime numbers
"""
def eratosthenes(n): # Zeef van Eratosthenes
primes = []
sieve = [True] * (n + 1)
for p in range(2, n + 1):
if sieve[p]:
primes.append(p)
for i in range(p * p, n + 1, p):
sieve[i] = False
return primes
# Main
print(eratosthenes(100))
|
def convert_to_binary_from_decimal(n):
'''Argument should be an integer'''
arr = []
while(n!=0 and n!=1):
k= n%2
arr.append(str(k))
n = int(n/2)
arr.append("1")
arr.reverse()
return str("".join(arr))
def convert_to_decimal_from_binary(n):
'''Argument can be in both string or integer form'''
n = str(n)
sum = 0
for i in range(len(n)):
k = int(n[i])
sum += (2**(len(n)-i-1))*k
return sum
# utility function
def toCharacterArray(string):
array = []
for i in range(len(string)):
array.append(string[i])
return array
def convert_to_binary_from_string(string):
array = toCharacterArray(string)
arr = []
for i in range(len(array)):
arr.append(convert_to_binary_from_decimal(ord(array[i])))
return " ".join(arr)
def convert_to_string_from_binary(n):
'''Argument should be in string'''
array = n.split(" ")
string = []
for i in range(len(array)):
string.append(chr(convert_to_decimal_from_binary(array[i])))
return ("".join(string))
def convert_to_octal_from_decimal(n):
'''Argument should be an integer'''
k = 0
arr = []
if n<8:
return n
while(n!=0 and n!=1 and n!=2 and n!=3 and n!=4 and n!=5 and n!=6 and n!=7):
k = n%8
arr.append(str(k))
n = int(n/8)
arr.append(f"{n}")
arr.reverse()
return str("".join(arr))
def convert_to_decimal_from_octal(n):
'''Argument can be in both string or integer form'''
n = str(n)
sum = 0
for i in range(len(n)):
k = int(n[i])
sum += (8**(len(n)-i-1))*k
return sum
# For Testing
if __name__ == '__main__':
print(convert_to_binary_from_decimal(90))
a = convert_to_binary_from_string("Paras Punjabi Program")
print(a)
p = convert_to_string_from_binary("1010000 1100001 1110010 1100001 1110011 100000 1010000 1110101 1101110 1101010 1100001 1100010 1101001 100000 1010000 1110010 1101111 1100111 1110010 1100001 1101101")
print(p)
print(convert_to_decimal_from_binary(100))
print(convert_to_octal_from_decimal(2050))
print(convert_to_decimal_from_octal(4002))
|
"""
Exple from ChaseMathis
https://www.youtube.com/watch?v=qNlKO0L4gMI
https://github.com/ChaseMathis/Speech-Recognition
"""
import webbrowser
import string
import speech_recognition as sr
# obtain audio
r = sr.Recognizer()
with sr.Microphone() as source:
print("Hello, what can i help you find?[Player lookup,Weather,resturants, or just to search the web: ]")
audio = r.listen(source)
if "player" in r.recognize_google(audio):
# obtain audio from the microphone
r2 = sr.Recognizer()
url = 'https://en.wikipedia.org/wiki/'
with sr.Microphone() as source:
print("Say any sports players name to see there Bio: ")
audio2 = r2.listen(source)
try:
print("Google Speech Recognition thinks you said " + r2.recognize_google(audio2))
webbrowser.open_new(url+r2.recognize_google(audio2))
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
if "weather" in r.recognize_google(audio):
# obtain audio from the microphone
r3 = sr.Recognizer()
url3 = 'https://www.wunderground.com/us/'
with sr.Microphone() as source:
print("Please say a city and state: ")
audio3 = r3.listen(source)
try:
print("Google Speech Recognition thinks you said " + r3.recognize_google(audio3))
webbrowser.open_new(url3+r3.recognize_google(audio3))
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
if "restaurants" in r.recognize_google(audio):
# obtain audio from the microphone
r4 = sr.Recognizer()
url4 = 'https://www.yelp.com/search?cflt=restaurants&find_loc='
with sr.Microphone() as source:
print("Please state a location to search for restaurants: ")
audio4 = r4.listen(source)
try:
print("Google Speech Recognition thinks you said " + r4.recognize_google(audio4))
webbrowser.open_new(url4+r4.recognize_google(audio4))
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
if "search" in r.recognize_google(audio):
# obtain audio from the microphone
r5 = sr.Recognizer()
with sr.Microphone() as source:
print("what website would you like me to search for you? ")
audio5 = r5.listen(source)
url5= r5.recognize_google(audio5)
try:
print("Google Speech Recognition thinks you said " + r5.recognize_google(audio5))
webbrowser.open_new("https://"+url5+".com")
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
|
#binary string to int
def btoi(str_to_bin):
# count = len(str_to_bin) -1
# value = 0
# for char in str_to_bin:
# value += int(char) * (2 ** count)
# count -= 1
# return value
return int(str_to_bin,2)
#gray string to bin striny
def gtob(gray):
binary = gray[0] #msb always same
for bit in range(1,len(gray)):
if gray[bit] == '1' and binary[bit-1] == '1':
binary += '0'
elif gray[bit] == '1' and binary[bit-1] == '0':
binary += '1'
else:
binary += binary[bit-1]
return binary
def gtoi(gray):
# return btoi(gtob(gray))
return int(gtob(gray),2)
|
"""List utility functions part 2."""
__author__ = "730385108"
def only_evens(x: list[int]) -> list[int]:
"""This function will print the even numbers in the list."""
i: int = 0
evens = list()
while (i < len(x)):
if x[i] % 2 == 0:
evens.append(x[i])
i += 1
else:
i += 1
return evens
def sub(z: list[int], x: int, y: int) -> list[int]:
"""This function creates a subset."""
i: int = 0
lists = list()
end: int = y
start: int = x
if len(z) == 0 or end <= 0 or len(z) < start:
return lists
elif len(z) < end:
while len(z) > start:
lists.append(z[start])
start += 1
return lists
elif start >= 0:
while end > start:
lists.append(z[start])
start += 1
return lists
elif start < 0:
while end > i:
lists.append(z[i])
i += 1
return lists
return z
def concat(x: list[int], y: list[int]) -> list[int]:
"""This function concats two lists."""
con = list()
i: int = 0
count: int = 0
while len(y) > i:
con.append(y[i])
i += 1
while len(x) > count:
con.append(x[count])
count += 1
return con
|
# encoding: utf-8
"""
@version: python3.5.2
@author: kaenlee @contact: [email protected]
@software: PyCharm Community Edition
@time: 2017/7/19 17:14
purpose:
"""
from itertools import chain
ch = chain([1, 2, 3], ["a", "b"], range(3))
print(list(ch))
def myChain(*x):
for i in x:
for j in i:
yield j
mych = myChain([1, 2, 3], [2, 3, 2])
print(list(mych))
ch_ = chain.from_iterable([[1, 2, 3], ["a", "b"]])
print(list(ch_))
def myChainIters(iterable):
for it in iterable:
for j in it:
yield j
|
#!/usr/bin/env python
#coding:utf-8
"""
Author: kaen.lee--<[email protected]>
Purpose:
Created: 2017/2/9
Version: python3.5.2
"""
import unittest
class montyHall:
#----------------------------------------------------------------------
def __init__(self, choice, montyopen):
""""""
self.choice = choice
self.montyopen = montyopen
self.propbA = None
self.propbB = None
self.propbC = None
#----------------------------------------------------------------------
def __str__(self):
"""choice:the first choice
montyopne: monty open the door"""
if (self.choice == 'A')&(self.montyopen == 'B'):
#situation1: car behind A
priori1 = 1/3
likelihood1 = 1/2
#situation2: car behind B
priori2 = 1/3
likelihood2 = 0
#situation3: car behind C
priori3 = 1/3
likelihood3 = 1
stardardize_constance = priori1*likelihood1 + priori2*likelihood2 + priori3*likelihood3
self.probA = priori1*likelihood1/stardardize_constance
self.probB = priori2*likelihood2/stardardize_constance
self.probC = priori3*likelihood3/stardardize_constance
elif (self.choice == 'A')&(self.montyopen == 'C'):
#situation1: car behind A
priori1 = 1/3
likelihood1 = 1/2
#situation2: car behind B
priori2 = 1/3
likelihood2 = 1
#situation3: car behind C
priori3 = 1/3
likelihood3 = 0
stardardize_constance = priori1*likelihood1 + priori2*likelihood2 + priori3*likelihood3
self.probA = priori1*likelihood1/stardardize_constance
self.probB = priori2*likelihood2/stardardize_constance
self.probC = priori3*likelihood3/stardardize_constance
elif (self.choice == 'B')&(self.montyopen == 'C'):
#situation1: car behind A
priori1 = 1/3
likelihood1 = 1
#situation2: car behind B
priori2 = 1/3
likelihood2 = 1/2
#situation3: car behind C
priori3 = 1/3
likelihood3 = 0
stardardize_constance = priori1*likelihood1 + priori2*likelihood2 + priori3*likelihood3
self.probA = priori1*likelihood1/stardardize_constance
self.probB = priori2*likelihood2/stardardize_constance
self.probC = priori3*likelihood3/stardardize_constance
elif (self.choice == 'B')&(self.montyopen == 'A'):
#situation1: car behind A
priori1 = 1/3
likelihood1 = 0
#situation2: car behind B
priori2 = 1/3
likelihood2 = 1/2
#situation3: car behind C
priori3 = 1/3
likelihood3 = 1
stardardize_constance = priori1*likelihood1 + priori2*likelihood2 + priori3*likelihood3
self.probA = priori1*likelihood1/stardardize_constance
self.probB = priori2*likelihood2/stardardize_constance
self.probC = priori3*likelihood3/stardardize_constance
elif (self.choice == 'C')&(self.montyopen == 'A'):
#situation1: car behind A
priori1 = 1/3
likelihood1 = 0
#situation2: car behind B
priori2 = 1/3
likelihood2 = 1
#situation3: car behind C
priori3 = 1/3
likelihood3 = 1/2
stardardize_constance = priori1*likelihood1 + priori2*likelihood2 + priori3*likelihood3
self.probA = priori1*likelihood1/stardardize_constance
self.probB = priori2*likelihood2/stardardize_constance
self.probC = priori3*likelihood3/stardardize_constance
elif (self.choice == 'C')&(self.montyopen == 'B'):
#situation1: car behind A
priori1 = 1/3
likelihood1 = 1
#situation2: car behind B
priori2 = 1/3
likelihood2 = 0
#situation3: car behind C
priori3 = 1/3
likelihood3 = 1/2
stardardize_constance = priori1*likelihood1 + priori2*likelihood2 + priori3*likelihood3
self.probA = priori1*likelihood1/stardardize_constance
self.probB = priori2*likelihood2/stardardize_constance
self.probC = priori3*likelihood3/stardardize_constance
return("""the probility of car behind the x
A: %f
B: %f
C: %f""" % (self.probA, self.probB, self.probC))
if __name__ == '__main__':
test = montyHall('A', 'B')
print(test)
unittest.main()
|
# coding=UTF-8
'''
#Created on 2016年7月12日@author: kaen
'''
'''===================================文件模式
r: 读模式
w: 写入模式
a: 追加模式
+(可组合): 读/写模式
b(可组合): 二进制模式,处理声音剪辑,图片,就需要,’rb‘,用来读取一个二进制文件
'''
'''==================================缓冲
第3个参数为缓冲参数 0/False;无缓存直接对硬盘数据进行读写,比较慢
1/true; 缓存,使用flush/close才会对硬盘数据更新,程序运行较快
'''
f = open('firstfile.txt', 'w')
f.write('hello file\n')
f.write('hello file')
f.close() # 完成一个文件的调用使用
f = open('firstfile.txt', 'r') # 默认模式‘r’
print(f.read(4)) # 指定读取字符截数
print(f.read()) # 接下来读取剩下的
'''================================不按循序读取:(默认按循序从0(不断在变)开始)'''
f = open('firstfile.txt', 'w')
f.write('0123456789')
f.seek(5) # 位置跳到了第6个字符
f.write('hello')
f.close()
f = open('firstfile.txt', 'r')
print(f.read())
# out: 01234hello
print(f.read(2)) # 已经读取过了, 此句没有输出
f.close()
f = open('firstfile.txt', 'r')
print(f.read(2)) # 此处已经改变了0 的位置
# o ut: 01
print(f.read(2)) # 所以此处返回的是接着上面来
# out: 23
print(f.tell())
# out: 4 #返回相对于原始文件0所处的字符段位置
f.close()
'''==================================读写'''
winequality = open(r'E:\eclip\machineL\svm\winequality.txt')
'''读取当前行:当前0到一个\n'''
print(winequality.readline())
# out: ixed acidity;"volatile acidity";"citric acid";"residual sugar";"chlorides";"free sulfur dioxide";"total sulfur dioxide";"density";"pH";"sulphates";"alcohol";"quality"
'''读取所有行:列表形式保存'''
x = winequality.readlines()
print(type(x))
'''========================================内容迭代处理
按字节:
while 1:
f.read(1)
if not read(1):
break
按行:改成readline()
for i in f。read():
for line in f.readlines():
import fileinput
for line in fileinput.input(filename)
for line in list(open(xxx)):
'''
|
# Objective
# In this challenge, we learn about conditional statements. Check out the Tutorial tab for learning materials and an instructional video.
# Task
# Given an integer, , perform the following conditional actions:
# If N is odd, print Weird
# If N is even and in the inclusive range of 2 to 5, print Not Weird
# If N is even and in the inclusive range of 6 to 20, print Weird
# If N is even and greater than 20, print Not Weird
# Complete the stub code provided in your editor to print whether or not is weird.
# Input Format
# A single line containing a positive integer, .
# Constraints
# Output Format
# Print Weird if the number is weird; otherwise, print Not Weird.
# Sample Input 0
# 3
# Sample Output 0
# Weird
# Sample Input 1
# 24
# Sample Output 1
# Not Weird
# Explanation
# Sample Case 0:
# N is odd and odd numbers are weird, so we print Weird.
# Sample Case 1:
# N > 20 and N is even, so it is not weird. Thus, we print Not Weird.
import math
import os
import random
import re
import sys
# If N is odd, print Weird
# If N is even and in the inclusive range of 2 to 5, print Not Weird
# If N is even and in the inclusive range of 6 to 20, print Weird
# If N is even and greater than 20, print Not Weird
if __name__ == '__main__':
N = int(input())
if N % 2 == 0 and N > 1 and N < 6 or N % 2 == 0 and N > 20:
print("Not Weird")
elif N % 3 == 0 or N % 2 == 0 and N > 6 or N % 2 == 0 and N < 21:
print("Weird")
else:
print("Weird")
|
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console
import simplegui
import random
import math
# initialize global variables used in your code
num_range = 100
secret_num = 0
guesses_left = 0
# helper function to start and restart the game
def new_game():
global num_range
global secret_num
global guesses_left
secret_num = random.randrange(0, num_range)
if num_range == 100:
guesses_left = 7
elif num_range == 1000:
guesses_left = 10
print
"New game. The range is from 0 to", num_range, ". Good luck!"
print
"Number of remaining guesses is ", guesses_left, "\n"
pass
# define event handlers for control panel
def range100():
global num_range
num_range = 100 # button that changes range to range [0,100) and restarts
new_game()
pass
def range1000():
global num_range
num_range = 1000 # button that changes range to range [0,1000) and restarts
new_game()
pass
def input_guess(guess):
# main game logic goes here
global guesses_left
global secret_num
won = False
print
"You guessed: ", guess
guesses_left = guesses_left - 1
print
"Number of remaining guesses is ", guesses_left
if int(guess) == secret_num:
won = True
elif int(guess) > secret_num:
result = "Lower!"
else:
result = "Higher!"
if won:
print
"That is correct! Congratulations!\n"
new_game()
return
elif guesses_left == 0:
print
"Game over. You didn't guess the number in time!"
new_game()
return
else:
print
result
pass
# create frame
f = simplegui.create_frame("Game: Guess the number!", 250, 250)
f.set_canvas_background('Green')
# register event handlers for control elements
f.add_button("Range is [0, 100)", range100, 100)
f.add_button("Range is [0, 1000)", range1000, 100)
f.add_input("Enter your guess", input_guess, 100)
# call new_game and start frame
new_game()
f.start()
|
'''
Mainīgais dictionaries
a = {1:1,2:2,3:3}
'''
#Elementiem var būt dažādi datu tipi
#Teksts
pirmais = {'atsl1':'vertiba1','atsl2':'vertiba2'}
print(pirmais)
#Skaitļi int,float
otrais = {'atsl1':2, 'atsl2':2.5}
print(otrais)
#Lists
tresais = {'atsl1':[1,2,3], 'atsl2':[4,5,6]}
print(tresais)
#Dictionary
ceturtais = {'atsl1':{'atsl2':[2,5,7]}}
print(ceturtais, end = '\n\n')
#Piekļuve elementiem
print(pirmais['atsl1'])
print(otrais['atsl2'])
print(tresais['atsl2'][1])
print(ceturtais['atsl1']['atsl2'][2], end = '\n\n')
#
otrais['atsl1'] = otrais ['atsl1'] - 2
print(otrais['atsl1'])
#
otrais['atsl1'] -= 4
print(otrais['atsl1'], end = '\n\n')
#Tukšas dictionary radīšana
d = {}
d['atsl1'] = 'Kā iet?'
d['atsl2'] = 'Man labi, kā tev?'
print(d)
print(d['atsl1'], end = '\n\n')
#Parādīt visas atslēgas
print(pirmais.keys())
#Parādīt visus elementus
print(pirmais.values())
#Parādīt tuples
print(pirmais.items(), end = '\n\n')
|
import math
class TCircle:
def __init__(self, r, x, y):
self.r = r
self.x = x
self.y = y
def S(self):
return self.r**2 * math.pi
def R(self, n, m):
return (self.x - n) ** 2 + (self.y - m) ** 2 == self.r ** 2
def __add__(self, other):
return TCircle(other.r + self.r)
def __sub__(self, other):
return TCircle(self.r - other.r)
def __mul__(self, other):
return TCircle(other * self.r)
def __str__(self):
return str(self.r)
x = TCircle(2, 5, 4)
print("S=", x.S())
print("r_xy", x.R())
|
# Implement a receipt function that takes as an input a cart with items
# and their corresponding prices, tax and promos and returns the total
def calculate(cart):
net = 0
tax = 0
promo = 0
total = 0
for items in cart:
net += cart[items]["net"]
tax += cart[items]["tax"]
promo += cart[items]["promo"]
total = net + tax - promo
return total, net, tax, promo
item1 = {"net": 120, "tax": 12, "promo": 2}
item2 = {"net": 110, "tax": 11, "promo": 1}
item3 = {"net": 100, "tax": 10, "promo": 0}
cart = {}
cart[0] = item1
cart[1] = item2
cart[2] = item3
total, net, tax, promo = calculate(cart)
print("\nCart net: ", net)
print("Cart tax: ", tax)
print("Cart promos: ", promo)
print("Cart total: ", total, "\n")
|
if __name__ == '__main__':
a = [0]
pos = 0
step = 359
n = 2017
for val in range(1,n+1):
#val is also the length of a at top of loop
pos = (pos+step)%val
a.insert(pos+1, val)
pos += 1
final_index = a.index(n)
answer_index = (final_index+1)%len(a)
print(a[answer_index])
|
import math
class Circle(object): # new-style classes inherit from object
'An advanced circle analytics toolkit'
'''
- When you are going to create many instances of the Circle class,
you can make them lightweight by using the flyweight design pattern.
- The flyweight design pattern suppresses the instance dictionary.
- The __slots__ will allocate only one pointer for the radius,
and nothing more. This will save lots of memory space, and scale up
the application.
- A dict is therefore not created for each instance.
- Only use this when you need to scale
- More info at:
http://stackoverflow.com/questions/472000/python-slots/28059785#28059785
'''
__slots__ = ['radius']
# version is a class variable. Class variables are essential for
# shared data (data that's shared between instances)
version = '0.1'
# init is not a constructor, it just initializes the instance variables
def __init__(self, radius):
'''
- instance variable, i.e. the data that is unique to each instance of
the class
- self is the instance, and its already been made by the time init gets
called
- so all that init does is populate the self instance with data
'''
self.radius = radius
def area(self):
'Get the area of the circle'
return math.pi * self.radius ** 2.0
def perimeter(self):
return 2.0 * math.pi * self.radius
'''
- The following is a way of providing an alternative constructor
- Do this when you wish to have more than one way to construct an instance
of the object
- This is similar to method overloading in other languages
- An example is datetime, which allows one to create an object using the
following ways:
datetime(2013, 3, 16) => default
datetime.fromtimestamp(1363383616)
datetime.fromordinal(734000)
datetime.now()
- All of these are datetime constructors
- In our example, to call this constructor, simply do:
Circle.from_bbd(12)
- Having the cls (Class) argument ensures that we know which class/subclass
called the constructor.
'''
@classmethod
def from_bbd(cls, bbd):
'Construct a circle from a bounding box diagonal (bbd)'
radius = bbd / 2.0 / math.sqrt(2.0)
return cls(radius)
def get_radius(self):
return self.radius
'''
- When you have a method in your class that does not require an object,
it is best to have it as a static method
- E.g. in our case, we dont need an object of Circle to convert an angle to
a percentage grade
- The reason of having static methods as opposed to standalone functions
is to improve the findability of the method, and to make sure people are
using the method in the right context. It's good API design.
- They can be useful to group some utility function(s) together with
a class - e.g. a simple conversion from one type to another - that
doesn't need access to any information apart from the parameters
provided (and perhaps some attributes global to the module.)
- an example is a Locale class, whose instances will be locales.
A getAvailableLocales() method would be a nice example of a static method
of such class: it clearly belongs to the Locale class, while also
clearly does not belong to any particular instance.
- In our case, to call the method, do:
Circle.angle_to_grade(90)
'''
@staticmethod
def angle_to_grade(angle):
'Convert angle in degree to a percentage grade'
return math.tan(math.radians(angle)) * 100.0
class Tire(Circle):
'Tires are circles with a corrected perimeter'
def perimeter(self):
'Circumference corrected for the rubber'
return Circle.perimeter(self) * 1.25
|
# ECE-467 Project 1
# Layth Yassin
# Professor Sable
# This program is an implementation of the CKY algorithm as a parser.
import re
# function returns the grammar rules (A -> B C or A -> w) in a dict where the keys are the non-terminal A, and the items are
# either a list of tuples (B, C) or a list of strings w
def storeCNF(fileCNFobj):
dictCNF = {}
while(1):
tempLine = fileCNFobj.readline()
line = tempLine.rstrip() # gets a single CNF grammar rule at a time
if not line: # if statement is true, the EOF has been reached
break
count = 0
index = [] # list that stores the indexes of the whitespaces in the grammar, which allows for obtaining the individual terminals and non-terminals
for i in range(len(line)):
if line[i] == ' ':
index.append(i)
count += 1
if count == 2: # if true, the CNF is of the form of A -> w
A = line[0:index[0]]
w = line[index[1] + 1:]
if A in dictCNF.keys(): # if true, the terminal value is added to the end of the list of terminals corresponding to the non-terminal
dictCNF[A].append(w)
else: # if true, a list is created to serve as the item of dictCNF[A], which stores the first terminal corresponding to the non-terminal
dictCNF[A] = [w]
if count == 3: # if true, the CNF is of the form of A -> B C
A = line[0:index[0]]
B = line[index[1] + 1:index[2]]
C = line[index[2] + 1:]
if A in dictCNF.keys(): # if true, the non-terminal values are added to the end of the list of terminals corresponding to the non-terminal as a tuple
dictCNF[A].append((B, C))
else: # if true, a list is created to serve as the item of dictCNF[A], which stores the first pair of non-terminals corresponding to the non-terminal as a tuple
dictCNF[A] = [(B, C)]
return dictCNF
# implementation of binary tree to keep track of backpointers
class TreeNode:
def __init__(self, nonTerminal, leftChild, rightChild = None): # right child of node is set to "None" for the case that a terminal is the only child
self.nt = nonTerminal # the non-terminal points to its child nodes from which its grammar is derived
self.lc = leftChild # left child of parent node
self.rc = rightChild # right child of parent node
# recursive function that prints the bracketed format of the parse
def printBracketed(node):
if not (node.rc == None): # both child nodes are recursively called until base case is reached
return "[" + node.nt + " " + printBracketed(node.lc) + " " + printBracketed(node.rc) + "]"
else: # base case where the only child the parent node has is a terminal
return "[" + node.nt + " " + node.lc + "]"
# function to print the textual parse tree
def printTree(bracketParse):
numTabs = 1 # keeps track of the number of tabs to output the correct amount of tabs
prevIndex = 1 # index that keeps track of the last element that was not printed
print('[', end = '') # prints the initial opening bracket before the 'S'
for i in range(1, len(bracketParse)): # loops through the input sentence
if bracketParse[i] == '[': # if true, the substring from prevIndex to the current index i is output (i.e., not including the '[')
print(bracketParse[prevIndex:i] + '\n' + numTabs * '\t', end = '')
numTabs += 1
prevIndex = i
if bracketParse[i] == ']': # if true, the substring from prevIndex to the current index i + 1 is output (i.e., including the ']')
print(bracketParse[prevIndex:i + 1] + '\n' + (numTabs - 2) * '\t', end = '')
numTabs -= 1
prevIndex = i + 1
# populates the cells along the diagonal of the matrix with the possible part of speech tags of each word from the input sentence
def populateDiagonal(words, dictCNF, table, j):
for A in dictCNF:
if words[j - 1] in dictCNF[A]: # if the word (the terminal) is found in the grammar, store the appropriate POS
table[j - 1][j].append(TreeNode(A, words[j - 1])) # node appended to list of possible nodes that could be formed
return table
# populates the non-diagonal cells with the proper nodes; binary tree essentially formed that keeps track of the parse
def populateOther(dictCNF, table, i, j, k):
listB = table[i][k] # list of the nodes at position [i, k]
listC = table[k][j] # list of the nodes at position [k, j]
if len(listB) > 0 and len(listC) > 0: # condition checks if both positions contain at least one node
for A in dictCNF.keys():
for BNode in listB:
for CNode in listC:
if (BNode.nt, CNode.nt) in dictCNF[A]: # if there is a matching rule in the CNF, a new node is added to the position [i, j]
table[i][j].append(TreeNode(A, BNode, CNode))
return table
# implementation of the CKY algorithim
def CKY(words, dictCNF, n):
table = [[[] for col in range(n + 1)] for row in range(n)] # creation of the matrix
for j in range(1, n + 1): # iterates over columns of matrix
populateDiagonal(words, dictCNF, table, j)
for i in range(j - 2, -1, -1): # iterates over the rows of the matrix
for k in range(i + 1, j): # iterates over all the cells where a substring spanning i to j in the input can be split into 2
populateOther(dictCNF, table, i, j, k)
return table
# handling of cnf input file
fileCNF = input("Enter the name of the file containing the CFG in CNF: ")
fileCNFobj = open(fileCNF, 'r')
dictCNF = storeCNF(fileCNFobj)
fileCNFobj.close()
print("Loading grammar...\n")
while (1): # the system prompts the user for input repeatedly until the user inputs "quit" to exit
parseTreeYN = input("Do you want textual parse trees to be displayed (y/n)?: ")
sentence = input("Enter a sentence or type \"quit\" to exit: ")
if sentence == "quit":
print("Goodbye!")
break
# processing of input sentence
sentence = sentence.lower() # converts the input to all lowercase, allowing for the user to input capital letters
words = re.findall('[A-Za-z0-9]+', sentence) # only stores words and numbers, allowing for the user to input punctuation
n = len(words)
table = CKY(words, dictCNF, n)
parseList = [] # this list will store the the nodes that have 'S' as their root node, which means it's a valid parse
parseNum = 0
for value in table[0][n]:
if value.nt == 'S':
parseList.append(value)
parseNum += 1
if parseNum > 0: # if true, then there exists at least 1 valid parse
print("VALID SENTENCE\n")
else:
print("NO VALID PARSES\n")
# outputs the parses in bracketed form and as parse trees if the user chooses to have them displayed
count = 0
while count < parseNum:
for node in parseList:
count += 1
print(f"Valid parse #{count}: ")
bracketParse = printBracketed(node)
print(bracketParse + '\n')
if parseTreeYN == 'y':
printTree(bracketParse)
print(f"\nNumber of valid parses: {parseNum}\n")
|
'''
str.find(sub[, start[, end]])
Return the lowest index in the string where substring sub is found within the slice s[start:end].
Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.
'''
'''查找字符串,仅在需要返回索引时调用,否则使用in'''
print('sssSSS'.find('SS'))
print('SS' in 'sssSSS')
|
'''
Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict. This is useful if for example mapping is a dict subclass:
>>> class Default(dict):
... def __missing__(self, key):
... return key
...
>>> '{name} was born in {country}'.format_map(Default(name='Guido'))
'Guido was born in country'
'''
'''New in version 3.2.暂时放置'''
|
'''
str.lower()
Return a copy of the string with all the cased characters [4] converted to lowercase.
'''
'''将字符串中的字母转化为小写'''
print('123'.lower())
|
'''str.encode(encoding="utf-8", errors="strict") '''
'''Return an encoded version of the string as a bytes object.
Default encoding is 'utf-8'.
errors may be given to set a different error handling scheme.
The default for errors is 'strict', meaning that encoding errors raise a UnicodeError.
Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any
other name registered via codecs.register_error(), see section Error Handlers.
For a list of possible encodings, see section Standard Encodings.'''
str = 'sssSSS'.encode()
print(str)
|
def hello():
name = input("Enter name: ")
month = input("Enter month: ")
print("Happy birthday " + name)
if month.lower() == "august":
print("Happy birthday " + month)
hello()
|
import math
"""
Uwaga: Proxy i Calculator powinny dziedziczyć z tej samej klasy-matki
"""
class Proxy:
def __init__(self):
self.memory = {}
def square_equation(self, a, b, c):
try:
print(str(a) + "x^2 + " + str(b) + "x + " + str(c))
print("Szukam rozwiązania w proxy...")
return self.memory[(a, b, c)]
except KeyError:
print("Nie znaleziono rozwiązania w bazie. Nastąpi obliczenie wyniku.")
self.memory[(a, b, c)] = Calculator.square_equation(a, b, c)
return self.memory[(a, b, c)]
class Calculator:
@staticmethod
def square_equation(a, b, c):
delta = (b * b) - (4 * a * c)
if delta > 0:
sq = math.sqrt(delta)
x1 = (-b - sq) / (2 * a)
x2 = (-b + sq) / (2 * a)
return x1, x2
elif delta == 0:
x = -b / (2 * a)
return x
else:
return "Brak miejsc zerowych"
if __name__ == '__main__':
proxy = Proxy()
print(proxy.square_equation(2, 1, 2))
print()
print(proxy.square_equation(2, 1, 2))
print()
print(proxy.square_equation(1, 2, 1))
print()
print(proxy.square_equation(1, 2, 1))
print()
print(proxy.square_equation(-1, 3, 4))
print()
print(proxy.square_equation(-1, 3, 4))
print()
print("Zapamiętane rozwiązania:")
print(proxy.memory)
|
# input the sentences file and output a pickle file, meanwhile display first three output
# Run by: python BrownCluster.py input.txt output.txt
import csv
import nltk
import pickle
import sys
# Load the Twitter Word Clusters into a dictionary
def get_cluster_dic(file):
f = open(file)
cluster_dic = {}
csv_f = csv.reader(f, delimiter='\t')
for row in csv_f:
try:
cluster_dic[row[1]].append(row[0])
except KeyError:
cluster_dic[row[1]] = [row[0]]
except IndexError:
break
return cluster_dic
# Get 1000 clusters' names, file is the name of corpus
def get_cluster_name(file):
f = open(file)
cluster = {}
csv_f = csv.reader(f, delimiter='\t')
for row in csv_f:
cluster[row[0]] = 0
namelist = cluster.keys()
return namelist
# Given a sentence then tokenizer it into list of tokens, return a list of tuples of
# tokens which are in the Brown Cluster and a count of '1'.
def Map(L):
L = nltk.word_tokenize(L)
print "Sentence Tokenizers:", L
results = []
for word in L:
if(cluster_dic.get(word)):
results.append ((cluster_dic[word], 1))
return results
"""
Group the sublists of (token, 1) pairs into a term-frequency-list
map, so that the Reduce operation later can work on sorted
term counts. The returned result is a dictionary with the structure
{token : [([token], 1), ...] .. }
"""
def Partition(L):
tf = {}
for p in L:
try:
tf[p[0][0]].append(p)
except KeyError:
tf[p[0][0]] = [p]
return tf
"""
Given a (token, [([token], 1) ...]) tuple, collapse all the
count tuples from the Map operation into a single term frequency
number for this token, and return a list of final tuple [(token, frequency),...].
"""
def Reduce(Mapping):
return (Mapping[0], sum(pair[1] for pair in Mapping[1]))
if __name__ == '__main__':
cluster_dic = get_cluster_dic("Twc.csv")
try:
arg1 = sys.argv[1]
arg2 = sys.argv[2]
except IndexError:
print "You need to type input name and output name"
sys.exit(1)
outputlist = []
inputfile = open(arg1, 'r')
outputfile = open(arg2, 'w')
count = 0
# Read the sentences in inputfile and process them by Brown Clustering
# Load the resultlist into outputfile and display first 3 results
for sentence in inputfile.readlines():
count = count + 1
sentence_map = Map(sentence)
sentence_reduce = map(Reduce, Partition(sentence_map).items())
if(count < 4):
print "result", count, ":", sentence_reduce
print "-"*50
outputlist.append(sentence_reduce)
pickle.dump(outputlist, outputfile)
# To read it back: outputlist = pickle.load(outputfile)
inputfile.close()
outputfile.close()
|
import numpy as np
class Ant():
def __init__(self, board, rules, startPosition=None):
self.rules = rules
self.board = board
if startPosition:
self.position = np.array(startPosition)
else:
self.position = np.array([0, 0]) # x, y tuple (or NP array)
self.directions = (
np.array([-1, 0]), # up
np.array([0, 1]), # right
np.array([1, 0]), # down
np.array([0, -1]), # left
)
self.directionIndex = 0
def direction(self):
return self.directions[self.directionIndex]
def move(self):
self.position += self.direction()
def iterate(self):
# 1) change colour of square
oldColour = self.board.getValue(*self.position)
# if the ant doesn't have this colour (number), wrap it by length of
# this ant's rules
nextColour = self.rules[oldColour % len(self.rules)]["nextColour"]
self.board.setValue(*self.position, nextColour)
# 2) update direction based on new colour
turnDirection = self.rules[nextColour]["turnDirection"]
self.directionIndex += turnDirection
self.directionIndex %= len(self.directions) # wrap
# 3) move to new square
self.move()
|
print("This is a hello application");
name = input("Write your name: ");
age = input("Enter your age: ");
print("Hello", name, "you are", age, "years old");
|
def oddoreven(a):
if a%2 is 0:
print("This number is even.")
else:
print("This number is odd.")
oddoreven(int(input("Enter a number: ")))
|
from math import ceil
minute = int(input("Enter parking time in minutes: "))
print(f"Parking fee is {ceil(minute/60)*25} baht.")
|
#=========== answer =================
def decrypt(msg):
return "".join(list(msg.replace('G','d').replace('D','o').replace('O','g').upper())[::-1])
"""
#for debuging
msg = msg.replace('G','d')
msg = msg.replace('D','o')
msg = msg.replace('O','g')
msg = msg.upper()
msg = list(msg)
msg.reverse()
msg = "".join(msg)
return msg
"""
#====================================
def encrypt(msg):
secret = []
for c in msg:
if c == "G":
secret.append("O")
elif c == "O":
secret.append("D")
elif c == "D":
secret.append("G")
else:
secret.append(c)
secret.reverse()
return "".join(secret)
|
class Solution:
def isMatch(self, s, p):
s_len = len(s)
p_len = len(p)
f = [[False for i in range(s_len)] for j in range(p_len)]
if s_len == 0 and p_len == 0:
return True
if s_len == 0:
res = True
for i in range(p_len):
if p[i] != '*': res = False
return res
if p_len == 0:
return False
f[0][0] = True if (p[0] == s[0] or p[0] == '*' or p[0] == '?') else False
# colone 1
once = True if p[0] != '*' else False
for i in range(1, p_len):
if p[i] == '*':
f[i][0] = f[i-1][0]
elif p[i] == '?':
if not once:
f[i][0] = f[i-1][0]
once = True
else:
if p[i] == s[0]:
if not once:
f[i][0] = f[i-1][0]
once = True
else:
f[i][0] = False
once = True
# row 1
for i in range(1, s_len):
if p[0] == '*':
f[0][i] = True
else:
f[0][i] = False
for i in range(1, s_len):
for j in range(1, p_len):
if p[j] == '*':
f[j][i] = (f[j][i-1] | f[j-1][i-1] | f[j-1][i])
elif (p[j] == '?') or (p[j] == s[i]):
f[j][i] = f[j-1][i-1]
else:
f[j][i] = False
return f[p_len-1][s_len-1]
|
prive_of_house = 1000000
down_payment = (prive_of_house - 200000)
goof_credit = ()
bad_credit = ()
if goof_credit == True:
print("your payment is; ", (prive_of_house - 100000))
elif bad_credit == True:
print("Yuor down payment will be:", down_payment)
else:
print("you dont ahve enough credit")
|
# AI Car
# import the pygame module, so you can use it
import pygame
# define a main function
def main():
screen_width = 900
screen_height = 900
# initialize the pygame module
pygame.init()
pygame.display.set_caption("minimal program")
# create a surface on screen that has the size of 240 x 180
screen = pygame.display.set_mode((screen_width,screen_height))
image = pygame.transform.scale(pygame.image.load("car.png"), (100,50))
image.set_colorkey((255,255,255))
screen.fill((255,255,255))
#Initial location of Car
xpos = 50
ypos = 50
#amount to step through each frame
step_x = 5
step_y = 5
screen.blit(image, (xpos,ypos))
pygame.display.flip()
# define a variable to control the main loop
running = True
# main loop
while running:
if xpos >screen_width-64 or xpos<0:
step_x = -step_x
if ypos >screen_width-64 or ypos<0:
step_y = -step_y
pygame.display.flip()
# event handling, gets all event from the event queue
for event in pygame.event.get():
# only do something if the event is of type QUIT
if event.type == pygame.QUIT:
# change the value to False, to exit the main loop
running = False
if event.type == pygame.KEYDOWN:
ypos -= step_y
if event.type == pygame.KEYUP:
ypos += step_y
screen.fill((255,255,255))
screen.blit(image, (xpos, ypos))
# run the main function only if this module is executed as the main script
# (if you import this as a module then nothing is executed)
if __name__=="__main__":
# call the main function
main()
|
import string
def text_analyzer(text = None):
''' This function counts the number of upper characters, lower characters,
punctuation and spaces in a given text. '''
if text == None:
text = input("What is the text to analyze ?\n")
while (len(text) == 0):
text = input("What is the text to analyze ?\n")
print("The text contains", len(text) ,"characters:")
print("-", sum(map(str.islower, text)), "lower letters")
print("-", sum(map(str.isupper, text)), "upper letters")
print("-", sum((map(lambda char: char in string.punctuation , text))), "punctuations")
print("-", len(text.split(" ")), "spaces")
|
import sys
if len(sys.argv) == 2 and sys.argv[1].isdigit():
if sys.argv[1] == 0:
print("I'm Zero")
elif int(sys.argv[1]) % 2 == 0:
print("I'm Even")
else:
print("I'm Odd")
else:
print("ERROR")
|
def inversa(array):
for i in range(len(array)):
print(array[0][i])
lista = ["amor"]
array = lista[0]
print(enumerate(array))
inversa(lista)
#print()
|
mascotas = {'gato': {'Maria', 'Luis'},
'perro': {'Maria', 'Karen', 'Ana'},
'rana':set(),
'conejo': {'Maria', 'Karen', 'Juan'}}
test = (mascotas['perro'] & mascotas['conejo']) - mascotas['gato']
print(test)
mascotas['rana'] = "pollas"
print(mascotas)
var = list("ba127342b598d6ea5aba28109bc8dc57")
var2 = []
for i in var:
if i not in var2:
var2.append(i)
print(i, end= ' ')
|
import sys
if len(sys.argv) > 3:
print("Input error: too many arguments")
sys.exit("Usage: python operations.py <number1> <number2> \nExample: python operations.py 10 3")
if len(sys.argv) < 3:
sys.exit("Usage: python operations.py <number1> <number2> \nExample: python operations.py 10 3")
if sys.argv[1].isdigit() == False or sys.argv[2].isdigit() == False:
print("Input error: only number")
sys.exit("Usage: python operations.py <number1> <number2> \nExample: python operations.py 10 3")
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
print("Sum : "+str(num1 + num2))
print("Difference : "+str(num1 - num2))
print("Product : "+str(num1 * num2))
if (num2 != 0):
print("Quotient : "+str(num1 / num2))
print("Remainder : "+str(num1 % num2))
else:
print("Quotient : "+ "Error (div by zero")
print("Remainder : "+ "Error (modulo by zero")
|
palindromo = input("Introduce una palabra\n")
j = 1
for i in palindromo:
if (i == palindromo[-j]):
ispa = True
j += 1
else:
ispa = False
break
if ispa:
print("Es un palíndromo")
else:
print("No es un palíndromo")
|
val = input().split()
N = int(val[0])
M = int(val[1])
def BackTrack(stack, num, currHeight):
stack[currHeight] = num
if currHeight == M:
answer = ''
for i in range(1, M + 1):
answer += (str(stack[i]) + ' ')
print(answer)
else:
for i in range(1, N + 1):
BackTrack(stack, i, currHeight + 1)
stack[currHeight] = 0
stack = [0] * (M + 1)
BackTrack(stack, 0, 0)
|
import sys
# BFS
class Queue:
queue = []
def enqueue(self, x):
self.queue.append(x)
def dequeue(self):
val = self.queue[0]
del self.queue[0]
return val
def getSize(self):
return len(self.queue)
val = sys.stdin.readline().split()
S = int(val[0]) # Start
D = int(val[1]) # Destination
PQ = Queue() # Parent Queue(queue of upper depth nodes)
CQ = Queue() # Child Queue(queue of lower depth nodes)
V = set() # Visited position set
depth = 0 # depth = second(answer we want)
CQ.enqueue(S)
V.add(S)
while CQ.getSize() > 0:
PQ.queue = CQ.queue
CQ.queue = []
depth += 1
while PQ.getSize() > 0: # make child queue until parent queue is empty
currPos = PQ.dequeue() # current position
if currPos == D: # finished
CQ.queue = []
depth -= 1
break
x = currPos * 2
y = currPos + 1
z = currPos - 1
if x <= 100000 and x not in V:
CQ.enqueue(currPos * 2)
V.add(x)
if y <= 100000 and y not in V:
CQ.enqueue(currPos + 1)
V.add(y)
if z >= 0 and z not in V:
CQ.enqueue(currPos - 1)
V.add(z)
print(depth)
|
"""
File: cooling.py
Copyright (c) 2016 Krystal Lee
License: MIT
<find cooling rate of tea of every minute>
"""
t = 0 #minutes
T_tea = 100 #degrees C, temperature of the tea
T_air = 20 #degrees C, temperature of the room
k = 0.055
# - k(T_tea - T_air) #the rate of cooling; after 1 min the tea temp will be k(T_tea-T_air) colder
user_input = raw_input ("Enter the initial tea temperature in Celsius:")
T_tea= int(user_input)
user_input = raw_input ("Enter the room temperature in Celsius:")
T_air = int(user_input)
user_input = raw_input ("Enter the number of minutes for which the tea was cooling down:")
num_minutes = float(user_input)
t = 0
print "Temperature of the air: 20"
print "Number of minutes: 20"
print "Minute Temperature"
while t < 20:
print "%3.1d %4.1f"%(t, T_tea)
T_tea -= k*(T_tea - T_air)
t += 1
print (t, T_tea)
|
def _sanitize_char(input_char, extra_allowed_characters):
input_char_ord = ord(input_char)
if (ord('a') <= input_char_ord <= ord('z')) \
or (ord('A') <= input_char_ord <= ord('Z')) \
or (ord('0') <= input_char_ord <= ord('9')) \
or (input_char in ['@', '_', '-', '.']) \
or (input_char in extra_allowed_characters):
result = input_char
else:
result = '_'
return result
def _sanitize_name(input_string, extra_allowed_characters, assert_sanitized):
result = ''.join(_sanitize_char(character, extra_allowed_characters)
for character in input_string)
if assert_sanitized:
assert input_string == result, \
'Input string was expected to be sanitized, but was not.'
return result
def sanitize_domain_name(input_string, assert_sanitized=False):
return _sanitize_name(input_string, {}, assert_sanitized)
def sanitize_service_name(input_string, assert_sanitized=False):
return _sanitize_name(input_string, {'+'}, assert_sanitized)
|
# -*- coding:utf-8 -*-
import itertools
class Solution:
def Permutation(self, ss):
# write code here
if len(ss)==0:
return []
temp = itertools.permutations(ss)
temp = [''.join(i) for i in temp]
temp = list(set(temp))
temp = sorted(temp)
return temp
class Solution1:
def Permutation(self, ss):
# write code here
result_set = set()
if not ss:
return []
def permutation(cs, current_s):
if not cs:
result_set.add(current_s)
return
for index, c in enumerate(cs):
new_cs = [char for i,char in enumerate(cs) if index!=i]
permutation(new_cs, current_s+cs[index])
return
permutation([c for c in ss], "")
return sorted(list(result_set))
if __name__=='__main__':
s = Solution()
print(s.Permutation('abc'))
itertools.count()
for key, group in itertools.groupby('AAABBBCCAAA'):
print(key, list(group))
|
## queue
class Queue ():
def __init__(self):
self.songs = []
def isEmpty(self):
return self.songs == []
def enqueue(self, song, userid, url):
if self.isEmpty():
self.songs.append((0, song, [], url))
else:
if (self.search(song) == -1):
self.songs.append((1, song, [userid], url))
self.sort()
else:
self.vote(song, userid, 1)
def next(self):
song = self.songs[0][1]
self.songs.pop(0)
return song
def dequeue(self):
return self.songs.pop()
def size(self):
return len(self.songs)
def sort(self):
self.songs.sort(reverse=True)
def search(self, song):
for i in range(1, self.size(), 1):
if (self.songs[i][1] == song):
return i
return -1
# votes on song -> pass in +1 or -1 (up v down vote)
def vote(self, song, userid, num):
print self.songs
index = [x[1] for x in self.songs].index(song)
if (not userid in self.songs[index][2]):
self.songs[index][2].append(userid)
print self.songs[index]
self.songs[index] = (self.songs[index][0] + num, self.songs[index][1], self.songs[index][2], self.songs[index][3])
## testing
''''
q = Queue()
q.enqueue('Hello', 'user1', 'n')
q.enqueue('7 Years', 'user1', 'm')
q.enqueue('Stressed Out', 'user1', 'n')
q.enqueue('I Was Wrong', 'user1')
print q.songs
q.vote('7 Years', 'user1', 1)
q.vote('7 Years', 'user2', 1)
q.vote('Hello', 'user1', 1)
q.vote('Stressed Out', 'user2', -1)
q.enqueue('Sorry', 'user1')
q.vote('7 Years', 'user3', 1)
q.vote('Hello', 'user3', 1)
q.vote('Sorry', 'user4', 1)
q.sort()
print q.songs
q.dequeue()
print q.songs
print q.size()
print q.next()
print q.songs
'''
|
import sys
def get_key(dic, search_value):
for k,v in dic.items():
if v == search_value:
return k
def get_state(capital):
if len(capital) != 1:
exit()
else:
if get_key(capital_cities,capital[0]) != None:
print(get_key(states,get_key(capital_cities,capital[0])))
else:
print("Unknown capital city")
def all_in(lstr):
# split with comma
lstr = lstr.split(",")
# remove empty/space elements
lstr = list(filter(str.strip, lstr))
# remove beginning whitespace
lstr = [x.lstrip() for x in lstr]
# print(lstr)
for element in lstr:
element_cap = element.title()
# check if element is a state
if element_cap in states:
print(capital_cities[states[element_cap]] + " is the capital of " + element_cap)
# else check if element is a capital
elif get_key(capital_cities,element_cap) != None:
print(element_cap + " is the capital of " + get_key(states,get_key(capital_cities,element_cap)))
else:
print(element + " is neither a capital city nor a state")
if __name__ == '__main__' :
states = {
"Oregon" : "OR",
"Alabama" : "AL",
"New Jersey": "NJ",
"Colorado" : "CO"
}
capital_cities = {
"OR": "Salem",
"AL": "Montgomery",
"NJ": "Trenton",
"CO": "Denver"
}
all_in(sys.argv[1])
|
#Funciones para la base de datos
import sqlite3
"""has(userid int, ingredient varchar(20), PRIMARY KEY(userid, ingredient)) """
""" recipes (recid int, name varchar(20), n int, ingredients varchar(255), pic varchar(20), PRIMARY KEY(recid))''') """
'''users (userid int, username varchar(20), password varchar(20), PRIMARY KEY(userid))'''
class DBConsults:
def __init__(self):
self.connection = sqlite3.connect("./1.db")
self.c = self.connection.cursor()
def close(self):
self.connection.close()
def get_user_id(self,username):
user_id = self.c.execute("""SELECT userid from Users where username = "{}"; """.format(username)).fetchone()[0]
return user_id
def get_ingredients(self,user_id):
pass
def new_user(self,username,hashpass,fb_id):
if "," in username:
return False
#Evita sql injection
users_list = self.c.execute("""SELECT username from Users where username != "{}" """.format(username)).fetchall()
if len(users_list) == 0:
return False
tup = (fb_id, username, hashpass)
add_user = self.c.execute("""INSERT into Users VALUES({},"{}","{}");""".format(*tup))
self.connection.commit()
return True
def add_match(self, username, ingredient):
user_id = self.get_user_id(username)
tup = user_id,ingredient
a = self.c.execute("""INSERT into has VALUES({},"{}");""".format(*tup))
self.connection.commit()
self.close()
return str(user_id)
def remove_match(self, username, ingredient):
user_id = self.get_user_id(username) #DELETE
#a = self.c.execute("""INSERT into Users VALUES({},{});""".format(*tup))
#self.connection.commit()
if __name__ == "__main__":
a = DBConsults()
a.add_match("pipe","caca")
a.close()
|
"""
Tic Tac Toe Player
"""
import math
import copy
X = "X"
O = "O"
EMPTY = None
def initial_state():
"""
Returns starting state of the board.
"""
return [[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY],
[EMPTY, EMPTY, EMPTY]]
def player(board):
"""
Returns player who has the next turn on a board.
"""
# x starts first
x = 0
o = 0
for i in range(3):
for j in range(3):
if (board[i][j]=="X"):
x += 1
if (board[i][j]=="O"):
o += 1
if (x>o):
return O
elif (not terminal(board) and x==o):
return X
else:
return None
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
if terminal(board):
return None
actions = []
for i in range(3):
for j in range(3):
if (board[i][j]==EMPTY):
actions.append((i,j))
actions_ = set(actions)
return actions_
def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
if actions(board) is not None:
if action not in actions(board):
raise ValueError('Not permitted action')
else:
return board
p = player(board)
i = action[0]
j = action[1]
new_board = copy.deepcopy(board)
new_board[i][j] = p
return new_board
def winner(board):
"""
Returns the winner of the game, if there is one.
"""
# Check the rows
sumx = 0
sumo = 0
for i in range(3):
sumx = 0
sumo = 0
for j in range(3):
if board[i][j]==X:
sumx += 1
if board[i][j]==O:
sumo += 1
if sumx==3:
return X
if sumo==3:
return O
# check the columns
sumx = 0
sumo = 0
for j in range(3):
sumx = 0
sumo = 0
for i in range(3):
if board[i][j]==X:
sumx += 1
if board[i][j]==O:
sumo += 1
if sumx==3:
return X
if sumo==3:
return O
# check the diagonals
sumx = 0
sumo = 0
for i in range(3):
if board[i][i]==X:
sumx += 1
if board[i][i]==O:
sumo += 1
if sumx==3:
return X
if sumo==3:
return O
sumx = 0
sumo = 0
for i in range(2,-1,-1):
if board[i][2-i]==X:
sumx += 1
if board[i][2-i]==O:
sumo += 1
if sumx==3:
return X
if sumo==3:
return O
return None
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
over = True
win = winner(board)
if win != None:
return True
# if no-one has won yet, we check if there is
# an empty tile. If yes, we are not in a terminal state
for i in range(3):
for j in range(3):
if board[i][j]==EMPTY:
over = False
return over
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
win = winner(board)
if win==X:
return 1
elif win==O:
return -1
else:
return 0
def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
p = player(board)
best_action = (0,0)
if terminal(board):
return None
# calculate the value for the current state
# with respect to all possible actions
if p == X:
value = float('-inf')
for action in actions(board):
next_state = result(board,action)
v = min_value(next_state)
if v >= value:
value = v
best_action = action
elif p == O:
value = float('inf')
for action in actions(board):
next_state = result(board,action)
v = max_value(next_state)
if v <= value:
value = v
best_action = action
return best_action
def max_value(board):
if terminal(board):
return utility(board)
v = float('-inf')
# for any action that starts from this state
# recursively check the value of the state
for action in actions(board):
v = max(v,min_value(result(board,action)))
return v
def min_value(board):
if terminal(board):
return utility(board)
v = float('inf')
for action in actions(board):
v = min(v,max_value(result(board,action)))
return v
|
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import sqlite3
'''
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
'''
def import_db(db_name):
try:
conn = sqlite3.connect(db_name)
print("Database opened successfully")
cur=conn.cursor()
records=cur.execute("SELECT * FROM Tweets where airline_sentiment='positive'")
count_pos=0
for row in records:
count_pos=count_pos+1
print("Positive Reviews :",count_pos)
records=cur.execute("SELECT * FROM Tweets where airline_sentiment='negative'")
count_neg=0
for row in records:
count_neg=count_neg+1
print("Negative Reviews :",count_neg)
records=cur.execute("SELECT * FROM Tweets where airline_sentiment='neutral'")
count_neutral=0
for row in records:
count_neutral=count_neutral+1
print("Neutral Reviews :",count_neutral)
except Exception as e:
print("Encountered error during connecting datasets: ",str(e))
conn.close()
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
import_db('database.sqlite')
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
#!/usr/bin/python3
"""Script to print a square
Attributes:
size(int): is the size of the square
if it fails raise a error
Example: ./4-main.py"""
def print_square(size):
"""print the a square
:argument
size(int): is the size of the square
:return
No return nothing"""
if type(size) is not int:
raise TypeError('size must be an integer')
if size < 0:
raise ValueError('size must be >= 0')
for _ in range(size):
for _ in range(size):
print('#', end='')
print(end='\n')
|
#!/usr/bin/python3
def uppercase(words):
for word in words:
if ((ord(word) >= 97) and (ord(word) <= 122)):
word = chr(ord(word) - 32)
print("{}".format(word), end="")
print("")
|
#!/usr/bin/python3
def update_dictionary(a_dictionary, key, value):
for a_key in a_dictionary:
if a_key is key:
a_dictionary[a_key] = value
return a_dictionary
a_dictionary.update({key: value})
return a_dictionary
|
#!/usr/bin/python3
for word in range(ord('a'), ord('z')+1):
if ((word is not 113) and (word is not 101)):
print("{:c}".format(word), end="")
|
#!/usr/bin/python3
"""simple script"""
def add_attribute(Class_v, class_att, fill_atr):
"""this functio track how many t"""
if isinstance(Class_v, type):
setattr(Class_v, class_att, fill_atr)
else:
raise Exception('can\'t add new attribute')
# class_v.counter = getattr(class_v, "counter", 0) + 1
# if getattr(class_v, "counter") > 1:
# raise Exception('can\'t add new attribute')
|
#!/usr/bin/python3
"""Test if the object is inherent of a class"""
BaseGeometry = __import__('7-base_geometry').BaseGeometry
class Square(BaseGeometry):
""" it seems is a figure that it will be a sum of an operatiom"""
def __init__(self, size):
self.__size = super().integer_validator("size", size)
def area(self):
"""calculate the area of the class"""
return self.__size * self.__size
def __str__(self):
return '[Square] {0}/{0}'.format(self.__size)
|
#!/usr/bin/python3
def multiply_by_2(a_dictionary):
if not a_dictionary:
return a_dictionary
new_dict = a_dictionary.copy()
for a_key in new_dict:
new_dict[a_key] = new_dict[a_key] * 2
return new_dict
# new_dic = {doub: v * 2 for doub, v in a_dictionary.items()}
|
r"""test_emails.txt
$"""
import re
re.findall(pattern, string)
re.search()
# matches the first instance of a pattern in a string, and returns it as a re match object.
# we can’t display the name and email address by printing it directly.
# Instead, we have to apply the group() function to it first.
# We’ve printed both their types out in the code above.
# As we can see, group() converts the match object into a string.
# We can also see that printing match displays properties beyond the string itself, whereas printing match.group() displays only the string.
re.split("@", line)
re.sub()
# takes three arguments. The first is the substring to substitute, the second is a string we want in its place, and the third is the main string itself.
|
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if board:
for i in range(len(board)):
if board[i][0]=='O':
self.bfs(board,i,0)
if board[i][len(board[0])-1]=='O':
self.bfs(board,i,len(board[0])-1)
for j in range(len(board[0])):
if board[0][j]=='O':
self.bfs(board,0,j)
if board[len(board)-1][j]=='O':
self.bfs(board,len(board)-1,j)
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j]=='O':
board[i][j]='X'
if board[i][j]=='2':
board[i][j]='O'
def bfs(self,board,i,j):
q = [[i,j]]
while q!=[]:
pos = q.pop(0)
a = pos[0]
b = pos[1]
board[a][b] = '2'
if 0<=a+1<len(board):
if board[a+1][b]=='O':
board[a+1][b]='2'
q.append([a+1,b])
if 0<=a-1<len(board):
if board[a-1][b]=='O':
board[a-1][b]='2'
q.append([a-1,b])
if 0<=b+1<len(board[0]):
if board[a][b+1]=='O':
board[a][b+1] = '2'
q.append([a,b+1])
if 0<=b-1<len(board[0]):
if board[a][b-1]=='O':
board[a][b-1] = '2'
q.append([a,b-1])
|
class Solution:
def twoSum(self, nums, target):
"""
The function inputs are list of integers and an target integer
Function then scan an array for numbers wich will add up to make a target integer
Output is a list of indices of those numbers in a list
"""
numbers = {}
for i, num in enumerate(nums):
if target - num in numbers:
return [numbers[target-num], i]
numbers[num] = i
return []
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.