text stringlengths 37 1.41M |
|---|
import string
upper = ""
if __name__ == '__main__':
print("This program will encrypt your input using ROT13.")
print("Please enter the text to be encrypted")
encrypt = input()
for k in encrypt:
if k.isalpha() == False:
print(k, end='')
else:
if k.isupper():
upper = True
else:
upper = False
outputL = chr(ord(k.lower())-13)
outputU = chr(ord(k.lower())+13)
if (ord(k.lower())) > 109:
if upper == True:
print(outputL.upper(), end='')
else:
print(outputL, end='')
else:
if upper == True:
print(outputU.upper(), end='')
else:
print(outputU, end='')
print("")
print("Please enter the text to be encrypted")
encrypt = input()
for k in encrypt:
if k.isalpha() == False:
print(k, end='')
else:
if k.isupper():
upper = True
else:
upper = False
outputL = chr(ord(k.lower())+13)
outputU = chr(ord(k.lower())-13)
if (ord(k.lower())) < 110:
if upper == True:
print(outputL.upper(), end='')
else:
print(outputL, end='')
else:
if upper == True:
print(outputU.upper(), end='')
else:
print(outputU, end='')
|
#return a sequence reversed (just with slicing)
#original seuqence
seq1 = [1,2,3,4,5,6,7,8,9,10,'a','b','c','d']
#print the original sequence
print("original sequence",seq1)
seq2 = seq1[::-1]
print("sequence reversed is:.......",seq2)
|
val=[]
continuar=True
# x=x3[:] é o mesmo que x=x1[o:len(x1)]
while continuar==True:
numero=input("digite um número:")
if "0"<=numero<="9":
int(numero)
val.append(numero)
elif numero=="":
continuar=False
else:
print("por favor, digite um número valido")
soma=0
u=0
while u<len(val):
if (val[u]==""):
pass
else:
soma+=float(val[u])
u+=1
media=soma/len(val)
print(media)
|
def max_recursivo(lista):
i = len(lista) -1
if len(lista) == 1:
return lista[0]
else:
if lista [i] > lista[i-1]:
lista.pop(i-1)
return max_recursivo(lista)
else:
lista.pop(i)
return max_recursivo(lista)
lista1 = [76,34,5,6,200,7,8,103]
print(max_recursivo(lista1))
|
# Your code here
# Read from the file.
with open("robin.txt") as f:
words = f.read()
word_list = words.split(' ')
# create a hash table
histogram = {}
# iterate through the word list and make each word the key, and the value a list
# if the word is in the hash table already, add a hash symbol to the value list.
for word in word_list:
if word.lower() not in histogram:
histogram[word.lower()] = '#'
else:
histogram[word.lower()] += '#'
frequency = list(histogram.items())
frequency.sort(key=lambda x: x[1], reverse=True)
for key, value in frequency:
print(f'{key:} {value}') |
## Challenge 1: PyBank
#* In this challenge, you are tasked with creating a Python script for analyzing the financial records of your company.
# [budget_data.csv](PyBank/Resources/budget_data.csv).
# The dataset is composed of two columns: `Date` and `Profit/Losses`.
#* Your task is to create a Python script that analyzes the records to calculate each of the following:
# 1. The total number of months included in the dataset
# 2. The total net amount of "Profit/Losses" over the entire period
# 3. The average change in "Profit/Losses" between months over the entire period
# 4. The greatest increase in profits (date and amount) over the entire period
# 5. The greatest decrease in losses (date and amount) over the entire period
#* As an example, your analysis should look similar to the one below:
#Financial Analysis
#----------------------------
#Total Months: 86
#Total: $38382578
#Average Change: $-2315.12
#Greatest Increase in Profits: Feb-2012 ($1926159)
#Greatest Decrease in Profits: Sep-2013 ($-2196167)
#* In addition, your final script should both print the analysis to the terminal and export a text file with the results.
# import os and csv
import os
import csv
# set filepath
PyBankcsv = os.path.join("Resources","budget_data.csv")
# create lists for data
profit = []
monthly_changes = []
date = []
# variables
count = 0
total_profit = 0
total_change_profits = 0
initial_profit = 0
with open(PyBankcsv, newline="") as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
csv_header = next(csvreader)
for row in csvreader:
# use count to count the number months in this dataset
count = count + 1
# use for the greatest increase and decrease in profits
date.append(row[0])
# append the profit information & calculate the total profit
profit.append(row[1])
total_profit = total_profit + int(row[1])
#calculate the avg change in profits month to month then calulate the avg change in profits
final_profit = int(row[1])
monthly_change_profits = final_profit - initial_profit
#store monthly changes in a list
monthly_changes.append(monthly_change_profits)
total_change_profits = total_change_profits + monthly_change_profits
initial_profit = final_profit
#calculate the average change in profits
average_change_profits = (total_change_profits/count)
#find the max and min change in profits and the corresponding dates these changes were obeserved
greatest_increase_profits = max(monthly_changes)
greatest_decrease_profits = min(monthly_changes)
increase_date = date[monthly_changes.index(greatest_increase_profits)]
decrease_date = date[monthly_changes.index(greatest_decrease_profits)]
print("----------------------------------------------------------")
print("Financial Analysis")
print("----------------------------------------------------------")
print("Total Months: " + str(count))
print("Total Profits: " + "$" + str(total_profit))
print("Average Change: " + "$" + str(int(average_change_profits)))
print("Greatest Increase in Profits: " + str(increase_date) + " ($" + str(greatest_increase_profits) + ")")
print("Greatest Decrease in Profits: " + str(decrease_date) + " ($" + str(greatest_decrease_profits)+ ")")
print("----------------------------------------------------------")
with open('financial_analysis.txt', 'w') as text:
text.write("----------------------------------------------------------\n")
text.write(" Financial Analysis"+ "\n")
text.write("----------------------------------------------------------\n\n")
text.write(" Total Months: " + str(count) + "\n")
text.write(" Total Profits: " + "$" + str(total_profit) +"\n")
text.write(" Average Change: " + '$' + str(int(average_change_profits)) + "\n")
text.write(" Greatest Increase in Profits: " + str(increase_date) + " ($" + str(greatest_increase_profits) + ")\n")
text.write(" Greatest Decrease in Profits: " + str(decrease_date) + " ($" + str(greatest_decrease_profits) + ")\n")
text.write("----------------------------------------------------------\n")
|
#!/usr/bin/python
# Pseudo code: controller loop for house heating
from datetime import datetime
class Schedule:
pass
class EnvironmentSensor:
pass
class HeatingSystem:
pass
class House:
pass
schedule = Schedule()
sensor = EnvironmentSensor() # the Particle
heating_system = Lyric() # the Honeywell
house = House(sensor, heating_system)
def is_time_to_start_heating(
required_time,
required_temperature,
current_temperature,
warm_up_gradient
):
"""
Returns True if it is time to start heating the house
"""
warm_up_time = (required_temperature - current_temperature) / warm_up_gradient
warm_up_start_time = required_time - warm_up_time
return now() > warm_up_start_time
# main loop
while True:
current_temperature = house.sensor.indoor_temperature
required_temperature = schedule.minimum_temperature
is_too_cold = current_temperature < required_temperature
if schedule.is_active_period():
if is_too_cold:
house.heating_system.turn_on()
else:
house.heating_system.turn_off()
else:
required_time = schedule.period.end_time
warm_up_gradient = house.warm_up_gradient
if is_too_cold or is_time_to_start_heating(
required_time,
required_temperature,
current_temperature,
warm_up_gradient):
house.heating_system.turn_on()
else:
house.heating_system.turn_off()
|
print "Biology Testing on Ecology"
print "By Joshua Bingham"
print "This test will test your knowledge about Ecology and show you what areas you need to improve in."
print "When answering a question, type the number of the answer you think is true."
#name = str(input("What is your name?"))
score = 0
score = int(score)
print "Question One: What specifically is Ecology?"
print "1: The science of all life on earth"
print "2: Cell division"
print "3: The interactions between organisms and their environment"
print "4: The origins of life"
q1r = input("Selection: ")
if q1r == 3:
print "correct!"
score = score + 1
print "Score:" + str(score)
else:
print "Wrong!"
print "Score:" + str(score)
print "Question Two: What is the highest level of Ecology listed?"
print "1: Population"
print "2: Ecosystem"
print "3: Community"
print "4: Species"
q2r = input("Selection: ")
if q2r == 2:
print "correct!"
score = score + 1
print "Score:" + str(score)
else:
print "Wrong!"
print "Score:" + str(score)
print "Question Three: Which of the following is not a defense against predation?"
print "1: Commensalism"
print "2: Hiding/feeding"
print "3: Chemical poisons"
print "4: Spines and thorns"
qr3 = input("Selection: ")
if qr3 == 1:
print "correct!"
score = score + 1
print "Score:" + str(score)
else:
print "Wrong!"
print "Score:" + str(score)
print "Question Four: What limits the number of individuals that can occupy an area at a time?"
print "1: Limiting factors"
print "2: Carrying capacity"
print "3: Low resources"
print "4: Predators"
qr4 = input("Selection: ")
if qr4 == 2:
print "correct!"
score = score + 1
print "Score:" + str(score)
else:
print "Wrong!"
print "Score:" + str(score)
print "Question Five: Which of the following is an example of a keystone species?"
print "1: Jaguar"
print "2: Coral"
print "3: Sea Star"
print "4: All of the above"
qr5 = input("Selection: ")
if qr5 == 4:
print "correct!"
score = score + 1
print "Score:" + str(score)
else:
print "Wrong!"
print "Score:" + str(score)
print "Question Six: Which of the following is a density-dependent factor?"
print "1: Weather"
print "2: Rain"
print "3: Competition for food"
print "4: feeding"
qr6 = input("Selection: ")
if qr6 == 3:
print "correct!"
score = score + 1
print "Score:" + str(score)
else:
print "Wrong!"
print "Score:" + str(score)
print "Question Seven: What is the name for the most abundant species in a community?"
print "1: Dominant"
print "2: Recessive"
print "3: Keystone"
print "4: Producer"
qr7 = input("Selection: ")
if qr7 == 1:
print "correct!"
score = score + 1
print "Score:" + str(score)
else:
print "Wrong!"
print "Score:" + str(score)
print "Question Eight: Which of the following is not a name for an interaction within a community?"
print "1: Predation"
print "2: Mutualism"
print "3: Commensalism"
print "4: Consumerism"
qr8 = input("Selection: ")
if qr8 == 4:
print "correct!"
score = score + 1
print "Score:" + str(score)
else:
print "Wrong!"
print "Score:" + str(score)
print "Question Nine: What is an example of two species that have a symbiotic relationship?"
print "1: Bears and deers"
print "2: Bees and flowers"
print "3: Sea stars and humans"
print "4: wolves and moose"
qr9 = input("Selection: ")
if qr9 == 2:
print "correct!"
score = score + 1
print "Score:" + str(score)
else:
print "Wrong!"
print "Score:" + str(score)
print "Question Ten: What is an abiotic factor?"
print "1: The Nonliving factors of an environment"
print "2: The factors that effect population growth"
print "3: The resources of an environment"
print "4: The factors that effect the lifespan of an organism"
qr10 = input("Selection: ")
if qr10 == 1:
print "correct!"
score = score + 1
print "Score:" + str(score)
else:
print "Wrong!"
print "Score:" + str(score)
print "Results:"
Percentage = score * 10
if Percentage >= 90:
print "A"
else:
if Percentage == 80:
print "B"
else:
if Percentage == 70:
print "C"
else:
if Percentage == 60:
print "D"
else:
print "F"
print "Bonus Questions!"
bscore = 0
bscore = int(bscore)
print "Question 1: what colour is red?"
print "1: the best colour"
print "2: the worst colour"
print "3: warm"
print "4: a dark pink"
qr = input("Selection: ")
if qr == 1:
print "correct!"
bscore = bscore + 1
print "Score:" + str(bscore)
else:
print "Wrong!"
print "Score:" + str(bscore)
print "Question 2: If you have 2 buckets with 3 stones in them, and I have 7 buckets with 2 stones in each of them, how many buckets do you have?"
print "1: 10"
print "2: 3"
print "3: 2"
print "4: 1"
qr = input("Selection: ")
if qr == 3:
print "correct!"
bscore = bscore + 1
print "Score:" + str(bscore)
else:
print "Wrong!"
print "Score:" + str(bscore)
print "Question 3: What is the best way to play Bastion?"
print "1: You don't"
print "2: For throwing purposes"
print "3: find the best position before engaging the opposition"
print "4: spray and pray in turret mode"
qr = input("Selection: ")
if qr == 3:
print "correct!"
bscore = bscore + 1
print "Score:" + str(bscore)
else:
print "Wrong!"
print "Score:" + str(bscore)
print "Question 4: why do people hate Bastion so much?"
print "1: Becasue he was OP at game launch, and he was always killing everyone, which scared the Overwatch community and made them hate Bastion"
print "2: Because theyre always getting destroyed by him, and cant figure out how to counter him even though most people claim to know how"
print "3: Because all of the sheild heros (Reinhardt, Orisa, Winston, and Briggite) are always getting countered by him, causing them to spread lies about Bastion in hopes of having him gone from competitive Overwatch forever"
print "4: Because a lot of Overwatch players are toxic, and get mad when people play heros that they think are bad"
qr = input("Selection: ")
if qr == 4:
print "correct!"
bscore = bscore + 1
print "Score:" + str(bscore)
else:
print "Wrong!"
print "Score:" + str(bscore)
print "Question 5: What Overwatch hero takes the most skill?"
print "1: Widowmaker"
print "2: Genji"
print "3: McCree"
print "4: Bastion"
qr = input("Selection: ")
if qr == 2:
print "correct!"
bscore = bscore + 1
print "Score:" + str(bscore)
else:
print "Wrong!"
print "Score:" + str(bscore)
if bscore == 5:
print "Not bad, kid!"
else:
print "You need to: Seek help in many ways."
|
'''
dictionary.py
Leif Anderson 7/8/17
'''
dojo = {
'Ninjas': [
{'fname' : 'Blaze', 'lname' : 'Hayes'},
{'fname' : 'Master', 'lname' : 'Chief'},
{'fname' : 'Steve', 'lname' : 'Jobs'},
{'fname' : 'Bill', 'lname' : 'Gates'}
],
'Sensei': [
{'fname' : 'The', 'lname' : 'Authman'},
{'fname' : 'Socrates', 'lname' : 'Athens'}
]
}
def printDictionary(dictionary):
keys = dictionary.keys()
keys.reverse()
keyslen = len(keys)
for i in range(0, keyslen):
print keys[i] + ' : ' + dictionary[keys[i]]
# modified for the names exercise ...
def nprintDictionary(dojo_member):
return dojo_member['fname'] + ' ' + dojo_member['lname'] + ' ' + str(len(dojo_member['fname']) + len(dojo_member['lname']))
def printDojo(nested_dict):
keys = nested_dict.keys()
keys.reverse()
keyslen = len(keys)
for i in range(0, keyslen):
print keys[i] + ' :'
lst = nested_dict[keys[i]]
lstlen = len(lst)
for j in range(0, lstlen):
printDictionary(lst[j])
# modified for names exercise
def nprintDojo(nested_dict):
keys = nested_dict.keys()
keys.reverse()
keyslen = len(keys)
for i in range(0, keyslen):
print keys[i] + ' '
lst = nested_dict[keys[i]]
lstlen = len(lst)
for j in range(0, lstlen):
print str(j+1) + ' - ' + nprintDictionary(lst[j])
printDojo(dojo)
print '>>>>>>>>>>>>>>>>'
nprintDojo(dojo)
|
def longest_oscillation(L):
"""
this is the bottom-up DP solution for the task 1
@param L: a list
@return: a tuple with the length if longest oscillation and the list of longest oscillation
@time complexity: O(N^2) where n is the size of the list
@space complexity: O(N) where n is the size of the list
"""
n = len(L)
memoIncrease = [1] * n #len of longest oscillation from index 0 to i with last two element increasing
memoDecrease = [1] * n #len of longest oscillation from index 0 to i with last two element decreasing
memo = [1] * n
for i in range(n):
for j in range(i):
if (L[j] < L[i]) and (memoIncrease[i] < (memoDecrease[j] + 1)):
memoIncrease[i] = memoDecrease[j] + 1
elif (L[j] > L[i]) and (memoDecrease[i] < (memoIncrease[j] + 1)):
memoDecrease[i] = memoIncrease[j] + 1
else:
pass
memo[i] = max(memoIncrease[i], memoDecrease[i]) # update memo by identifying the maximum len of oscillation from 0 to i
### the algorithm has finished creating memo array ###
# construct the longest oscillation using memo
lgs_osl = []
for i in range(n):
try:
if memo[i+1] > memo[i]:
lgs_osl.append(L[i])
except IndexError:
lgs_osl.append(L[i])
return (max(memo), lgs_osl)
def longest_oscillation_optimize(L):
"""
this is the bottom-up DP solution for the task 1
@param L: L list
@return: L tuple with the length if longest oscillation and the list of longest oscillation
@time complexity: O(N) where n is the size of the list
@space complexity: O(N) where n is the size of the list
"""
if L == []:
return []
memo = [L[0]]
try:
memo.append(L[1])
except IndexError:
return (1, L)
for current in L[1:]:
if len(memo) == 1:
memo.append(current)
continue
# We need to see if the current is the local maximum/minimum depending on the current trend.
# Indicate this using signs.
# Show the current trend by substracting the second-last element from last element,
# if positive, the next element should be smaller, otherwise it should be greater
# If the current element is greater than the last element in memo and this one should be
# greater according to the trend, the equation will be negative and append this to memom
# Otherwise the current element is the new local extreme, so we replace it with the last
# element in the memo
if (current - memo[-1]) * (memo[-1] - memo[-2]) < 0:
memo.append(current)
continue
memo[-1] = current
return (len(memo), memo)
print(longest_oscillation_demo([1,5,7,4,6,8,6,7,1]))
print(longest_oscillation_demo([1, 2])) |
import math
def get_digit(num, digit):
"""
this function simplyt get the right most digit for the input number
@param num: a integer
@param digit: the which digit should it get
@return the specific digit of the integer
@time complexity: O(1)
@space complexity: O(1)
"""
return num[-digit]
def convert_base_b(num, b, digit):
"""
this function converts decimal integer into base b
@param num: the decimal integer
@param b: the target base
@param digit: the target digit
@return: the input integer in base b
@time complexity: O(n) where n is the digit
@space complexity: O(n) where n is the digit
"""
result = []
for _ in range(digit):
reminder = num % b
quotient = num // b
num = quotient
result.append(reminder)
return result[::-1]
def convert_base_10(num, b):
"""
this function converts integer in base b to decimal
@param num: number in base b
@param b: the target base
@return: the input number in decimal
@time complexity: O(n) where n is the digit
@space complexity: O(n) where n is the digit
"""
result = 0
for n in num:
result *= b
result += n
return result
def radix_aux(array, b, digit):
"""
this function performs counting sort for each single row of specific digit in the array
@param array: the array which need to sorted
@param b: the target base
@param digit: the target digit
@return: the sorted array in the order of specific digit
@time complexity: O(n) where n is size of the array
@space complexity: O(n) where n is size of the array
"""
size = len(array)
count = [0] * (b)
for i in range(0, size):
count[get_digit(array[i], digit)] += 1
position = [0] + ([0] * b)
for i in range(1, b+1):
position[i] = position[i-1] + count[i-1]
temp = [0] * size
for i in range(0, size):
temp_digit = get_digit(array[i], digit)
temp[position[temp_digit]] = array[i]
position[temp_digit] += 1
for i in range(size):
array[i] = temp[i]
return array
def radix_sort(array, b):
"""
this function performs radix sort by sorting each digit of element from right most to left most
@param array: the array which need to sorted
@param b: the target base
@return: the sorted array
@time complexity: O(nm) where n is the size of array and m is the number of digit
@space complexity: O(nm) where n is the size of array and m is the number of digit
"""
digits = 0
base = min(b, 10)
for i in range(len(array)):
digits = max(digits, math.ceil(math.log(array[i] + 1, base))) # use upperbound of log to find the maximum digits in the array
base_b = [convert_base_b(num, b, digits) for num in array]
for digit in range(1, digits+1):
array = radix_aux(base_b, b, digit)
array = [convert_base_10(nums, b) for nums in array]
return array |
a=int(input("enter a number"))
temp=a
rev=0
while(a>0):
remainder=a%10
rev=(rev*10)+remainder
a=a//10
if(rev==temp):
print("is palindrome")
else:
print("not a palindrome") |
def reverse(arr):
n = len(arr) - 1
for i in range(len(arr)/2):
arr[i], arr[n - i] = arr[n - i], arr[i]
return arr
def palindrome(s):
n = len(s) - 1
for i in range(len(s)/2):
if s[i] != s[n - i]:
return False
return True
if __name__ == "__main__":
#in_arr = [int(i) for i in raw_input("Enter the array: ").split(",")]
#print reverse(in_arr)
string = raw_input("Enter the string: ")
print palindrome(string)
|
def subset_sum(subsets):
output = []
for subset in subsets:
if not reduce(lambda x,y: x + y, subset):
output.append(subset)
return output
def subset(arr):
if not len(arr):
return [""]
sub = subset(arr[1:])
return [arr[0] + el for el in sub] + sub
if __name__ == "__main__":
in_str = raw_input("Enter the array: ").split(',')
print subset(in_str)
|
def subset(arr):
if not len(arr):
return [[]]
sub = subset(arr[1:])
return [[arr[0]] + s for s in sub] + sub
if __name__ == "__main__":
in_arr = [int(i) for i in raw_input("Enter the array: ").split(",")]
print subset(in_arr)
|
def find_all_nums(n):
out = []
if n == 0:
return [[]]
for i in range(1, n + 1):
nums = find_all_nums(n-i)
for v in nums:
out.append(v + [i])
return out
if __name__ == "__main__":
print find_all_nums(int(raw_input("Enter the number: ")))
|
def intersect_all(arr):
return reduce(intersection, arr)
def intersection(a, b):
return [el for el in a if el in b]
if __name__ == "__main__":
in_str = raw_input("Enter the array: ").split(',')
print intersect_all(in_str)
|
#!/usr/bin/python
import sys
#Create list of alphabetic chars to check against
CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
CHAR = dict.fromkeys(list(CHAR))
def main():
#Input validation
argc = len(sys.argv) - 1
if argc != 1:
print("Improper number of arguments")
quit()
elif (not sys.argv[1] == "-e") and (not sys.argv[1] == "-d"):
print("Only '-e' and '-d' arguments accepted")
quit()
#Send input string to fix_string in order to get needed format
string = input("Please enter input: ").upper()
string = fix_string(string)
#send key to fix_key in order to get needed format
key = input("Please enter key: ").upper()
key = fix_key(dict.fromkeys(key))
#toadd is list of chars in already in key, add to key matrix
toadd = [x for x in CHAR if x not in key]
#now that key has been fixed, test that there is at least one char and no more than 10
if len(key) > 10:
print("Key value may not contain more than 10 unique charcters")
quit()
elif len(key) < 1:
print("Key value must contain at least one character")
quit()
#add chars to key matrix, remove J char, slice into 2d list
key_matrix = key.copy()
key_matrix.extend(toadd)
key_matrix.remove("J")
key_matrix = [key_matrix[i:i+5] for i in range(0, len(key_matrix), 5)]
#if '-e', encrypt data and print out
if sys.argv[1] == "-e":
print("Encrypting data...")
string = encrypt(string, key_matrix)
l=[]
for item in string:
l.extend(item)
l = ''.join(l)
print(l)
#if '-d', decrypt data and print out
elif sys.argv[1] == "-d":
print("Decrypting data...")
string = decrypt(string, key_matrix)
l=[]
for item in string:
l.extend(item)
l = ''.join(l)
print(l)
def encrypt(string_list, matrix):
for item in string_list:
if len(item) >= 2:
pos1 = get_position(item[0], matrix)
pos2 = get_position(item[-1], matrix)
if pos1[0] == pos2[0]:
item[0] = matrix[pos1[0]][(pos1[1]+1)%4]
item[-1] = matrix[pos2[0]][(pos2[1]+1)%4]
elif pos1[1] == pos2[1]:
item[0] = matrix[(pos1[0]+1)%4][pos1[1]]
item[-1] = matrix[(pos2[0]+1)%4][pos2[1]]
else:
item[0] = matrix[pos1[0]][pos2[1]]
item[-1] = matrix[pos2[0]][pos1[1]]
return string_list
def decrypt(string_list, matrix):
for item in string_list:
if len(item) >= 2:
pos1 = get_position(item[0], matrix)
pos2 = get_position(item[-1], matrix)
if pos1[0] == pos2[0]:
item[0] = matrix[pos1[0]][(pos1[1]-1)%5]
item[-1] = matrix[pos2[0]][(pos2[1]-1)%5]
elif pos1[1] == pos2[1]:
item[0] = matrix[(pos1[0]-1)%5][pos1[1]]
item[-1] = matrix[(pos2[0]-1)%5][pos2[1]]
else:
item[0] = matrix[pos1[0]][pos2[1]]
item[-1] = matrix[pos2[0]][pos1[1]]
return string_list
#'fixes' key by
def fix_key(key):
key = list(key)
for i in key:
if i not in CHAR:
key.remove(i)
return key
def fix_string(string):
string = list(string)
i=0
for a in range(len(string)//2):
if string[i]==string[i+1]:
string.insert(i+1, 'X')
i=+2
charcount=0
for a in string:
if a in CHAR:
charcount+=1
if charcount%2==1:
string.append('X')
i=0
new_string = []
for a in range(len(string)):
if i<len(string) and string[i] in CHAR:
start = i
i+=1
while i<len(string) and string[i] not in CHAR:
i+=1
seg = string[start:i+1]
new_string.append(seg)
i+=1
elif i<len(string) and string[i] not in CHAR:
new_string.append(string[i])
i+=1
return new_string
def get_position(character, matrix):
if character != "J":
for i in range(5):
for j in range(5):
if matrix[i][j]==character:
return i, j
else:
return 0, 0
main() |
all_frutes=["mango","orange","bnana"]
for frutes in all_frutes:
print(frutes)
# _in a for loops
n=1
for _ in range(100):
print(n)
n+=1
|
import time
class meas:
def __init__(self, message="Time measured", average_on=1):
self.time_a = 0
self.time_b = 0
self.times = []
self.message = message
self.average_on = average_on
def start(self):
self.time_a = time.time()
def end(self):
self.time_b = time.time()
self.times.append(self.time_b - self.time_a)
if len(self.times) >= self.average_on:
print("{0}: {1:.2f}s".format(self.message, sum(self.times) / len(self.times)))
self.average_on *= 2
|
class Solution:
def maxValue(self, n, x):
# We want to separate between two cases where the integer n is
# negative and where it is positive.
if n[0] == '-':
# We start at i =1 to bypass the negative sign
i = 1
length = len(n)
end_loop = False
# We loop while our index is within the bounds of the string
# and we have not reached an end of loop condition
while not end_loop and (i <= length - 1):
# We advance our index if our current insert is larger
# than the i'th digit in n ( we don't want to make
# a negative number more negative! )
if x >= int(n[i]):
i+=1
# Otherwise, we have found a place to put our insert and
# we can stop the loop
else:
end_loop = True
# If we looped through the whole string, we can simply tack
# on the insert at the end
if i == length:
return n + str(x)
# Otherwise we just splice n and insert x in between
else:
return n[:i] + str(x) + n[i:]
else:
# We start at 0 since there is no negative sign
i = 0
length = len(n)
end_loop = False
# Same loop procedure as before
while not end_loop and (i <= length - 1):
# If the insert is less than the i'th digit, we move on
# ( we want to make a positive number more positive)
if x <= int(n[i]):
i += 1
# Otherwise we have our insert location
else:
end_loop = True
if i == length:
return n + str(x)
else:
return (n[:i] + str(x) + n[i:])
sol = Solution()
print(sol.maxValue(n = "-13", x = 2))
print(sol.maxValue(n = "99", x = 9))
print(sol.maxValue(n = "134265", x = 3))
print(sol.maxValue(n = "-123456", x = 7))
print(sol.maxValue(n = "-132", x = 3))
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def list_repr(self):
# Here we will list the numbers in the ListNode in a list
# representation
list_integer = []
# We store our current node's value in a variable
current_node = self
# If the ListNode doesn't link to another ListNode, we append its
# value into the list
if self.next == None:
list_integer.append(current_node.val)
# Otherwise, we will loop over the ListNodes and append their values
else:
while current_node != None:
list_integer.append(current_node.val)
current_node = current_node.next
return list_integer
'''
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
'''
def list_to_integer(nums):
"""Creates ListNode representation of an integer given by a list"""
# Store the length of the list
length = len(nums)
# Check for invalid leading zeros unless the size of nums is zero
if nums[0] == 0 and length != 1:
return -1
# Set up our first node and create a variable for the value of the next
# node
initial_node = ListNode(nums[0])
temp_node = initial_node
# For each element in nums, we want to link it to the initial node
for i in (range(length - 1)):
initial_node.next = ListNode(nums[i+1])
initial_node = initial_node.next
return temp_node
def add_list_node_integers(l1, l2):
"""
Returns a ListNode representing the result of the addition of ListNode
integers, l1 and l2.
"""
# We want to add up the integers only up to the maximum length of the
# smaller integer.
length = min(len(l1), len(l2))
# Reverse the lists since the lists l1 and l2 represent the reverse of the
# numbers we want to add up
l1_reverse = l1[::-1]
l2_reverse = l2[::-1]
# We will store the summation in here
sum = []
if len(l1) < len(l2):
sum = l2.copy()
elif len(l1) > len(l2):
sum = l1.copy()
print(sum)
# We loop over the length of the smaller integer and add up the integers
# by their individual digits
for i in range(length):
sum[i] = (l1_reverse[i] + l2_reverse[i])
# Next we loop over the length of the sum list.
# First we define the carryover
carryover = 0
print(sum)
for i in range(len(sum)):
# We add the carryover to the element
sum[i] += carryover
carryover = 0
# If the element is larger than or equal to 10, we set it to 0 and distribute the
# remainder into carryover
if sum[i] >= 10:
sum_to_str = str(sum[i])
# We add the carryover from sum[i] and set sum[i] to 9
carryover += int(sum_to_str[0])
sum[i] = int(sum_to_str[1])
# If we still have carryover leftover, we must add it to the fron of sum
if carryover != 0:
carryover_to_str = str(carryover)
for i in range(len(carryover_to_str)):
sum.append(int(carryover_to_str[i]))
return sum
# testing ListNode.list_repr()
print("Testing ListNode.list_repr()")
node_1 = ListNode(1)
node_2 = ListNode(2)
node_3 = ListNode(3)
node_4 = ListNode(4)
node_5 = ListNode(5)
node_2.next = node_3
node_3.next = node_4
node_4.next = node_5
print(node_1.list_repr())
print(node_2.list_repr())
print('---------------------------------------------------------------------')
print('\n')
# Testing list_to_integer
print("Testing list_to_integer")
integer_invalid = [0, 1, 2, 3]
integer_1 = [1, 2, 3, 4]
integer_2 = [12, 23, 43, 111]
integer_3 = [1,2,3,4,5,6,7,8,9,10]
integer_1_node = list_to_integer(integer_1)
print(integer_1_node.list_repr())
integer_2_node = list_to_integer(integer_2)
print(integer_2_node.list_repr())
integer_3_node = list_to_integer(integer_3)
print(integer_3_node.list_repr())
print('---------------------------------------------------------------------')
print('\n')
# Testing with example input
print("Testing with example input l1, l2")
# 2 -> 4 -> 3
l1 = [2, 4, 3]
# 5 -> 6 -> 4
l2 = [5, 6, 4]
# Convert the list into ListNode representation
l1_int = list_to_integer(l1)
l2_int = list_to_integer(l2)
# Express it back in the list form, which should be equivalent to the input
print(l1_int.list_repr())
print(l2_int.list_repr())
print('---------------------------------------------------------------------')
print('\n')
# Testing with example input
print("Testing addition with l1 and l2")
# Add together using add_list_node_integers
print(add_list_node_integers(l1, l2))
l1 = [9,9,9,9,9,9,9]
l2 = [9,9,9,9]
print(add_list_node_integers(l1, l2)) |
#Name:Andrew Hunter, Greg Francis, Preston Fry
#Date:September 18, 2014
#Assignment:Ch. 3 Programming Excercises
#Problem: 11
#Purpose of the program:display the points earned for the number of books
#purchased by the customer
#Assumptions:if the customer doesn't purchase any books, they don't get any points
#if they purchase 2 books they earn 5 points, if they purchase 4 books
#they earn 15 points, if they purchase 6 books they earn 30 points, and
#if they purchase 8 or more books they earn 60 points
books=int(input('How many books did you purchase?'))#asks the user how many books they purchased and sets variable books to the value
if books==2: #the elif statement determines how many books were purchased and displays the amount of points earned
print('Your purchase has earned you 5 points!')
elif books==4:
print('Your purchase has earned you 15 points!')
elif books==6:
print('Your purchase has earned you 30 points!')
elif books>=8:
print('Your purchase has earned you 60 points!')
else:
print('Your purchase did not earn any points today!')
|
#Name:Andrew Hunter, Greg Francis, Preston Fry
#Date:October 7, 2014
#Assignment:Ch. 5 Programming Excercise
#Problem: 21
import random
def main():
computernumber=random.randint(1,3)
humanword=input('rock, paper, or scissors')
humannumber=from_word(humanword)
computerword=from_number(computernumber)
decision=winner(computernumber,humannumber)
print('You have chosen',humanword,
'and the computer has chosen',computerword,
'Therefore',decision)
def from_word(one):
if one=='rock':
return 1
elif one=='paper':
return 2
elif one=='scissors':
return 3
def from_number(one):
if one==1:
return 'rock'
elif one==2:
return 'paper'
elif one==3:
return 'scissors'
def winner(one,two):
difference=one-two
if difference%3==1:
return 'the computer wins'
elif difference%3==2:
return 'you win!'
elif difference==0:
return 'you have tied with the computer. Please run the program again.'
elif difference==0:
return restart()
def restart():
main()
main()
|
#Name:Andrew Hunter
#Date:October 7, 2014
#Assignment:Ch. 4 Programming Excercises
#Problem: 14
#Purpose of the program:
steps=6
for r in range(steps):
print('#', end='')
for c in range(r):
print(' ', end='')
print('#')
|
#Name:Andrew Hunter, Greg Francis, Preston Fry
#Team Name:Funky Town Monkey Pimps
#Date:September 2, 2014
#Assignment:Ch. 2 Programming Excercises
#Problem: 2
#Purpose of the program:Display profit from total sales.
#Assumptions:Profit is 23% of total sales
#Other Comments:
total_sales=float(input('What are the total sales?'))
profit=total_sales*.23
print('Given that your total sales are $',
format(total_sales, '.2f'),
sep='',)
print(', your profit is $',
format(profit, '.2f'),
sep='')
|
#Name:Andrew Hunter, Greg Francis, Preston Fry
#Date:September 18, 2014
#Assignment:Ch. 3 Programming Excercises
#Problem: 14
#Purpose of the program:to calculate a persons body mass index(BMI)
#Assumptions:BMI = weight * 703//height**2
#Other Comments:optimal bmi is between 18.5 and 25
#if bmi is under 18.5 the person is considered to be underweight
#and over 25 considered overweight
weight=float(input('What is your weight in pounds?'))
height=float(input('What is your height in inches?'))
bmi=weight*703//height**2
if bmi>=18.5 and bmi<=25:
print('Your BMI is',bmi,'and is optimal for your weight and height.')
elif bmi>25:
print('Your BMI is',bmi,'and you are overweight for your height.')
elif bmi<18.5:
print('Your BMI is',bmi,'and you are underweight for your height.')
|
#Name:Andrew Hunter, Greg Francis, Preston Fry
#Team Name: The Funky Town Monkey Pimps
#Date:September 2, 2014
#Assignment:Ch. 2 Programming Excercises
#Problem:10
#Purpose of the program:To find amount of ingredients needed
#Assumptions:The recipe is correct
#Other Comments:
cookies=int(input('How many cookies do you wish to bake?'))
sugar=1.5/48*cookies
butter=1/48*cookies
flour=2.75/48*cookies
print('You will need',
format(sugar, '.2f'))
print('cups of sugar,',
format(butter, '.2f'))
print('cups of butter, and',
format(flour, '.2f'))
print('cups of flour.')
|
# 328 Odd Even Linked List
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
return
pointer1 = head
pointer2 = head.next
conn = head.next
while pointer1.next and pointer2.next:
pointer1.next = pointer1.next.next
pointer2.next = pointer2.next.next
pointer1 = pointer1.next
pointer2 = pointer2.next
pointer1.next = conn
return head
|
def shift(li):
temp = li[0]
for i in range(1, len(li)):
li[i-1] = li[i]
li[-1] = temp
return li
class Solution(object):
def productExceptSelf(self, nums):
output = []
for i in range(len(nums)):
shift(nums) # [2, 3, 4, 1]
multi = 1
for i in range(len(nums) -1):
multi *= nums[i]
output.append(multi)
return output
## Time exceeded 뜸.
## 근데 testcase가 너무한거 같다..
|
"""
Задание 4.
Приведены два алгоритма. В них определяется число,
которое встречается в массиве чаще всего.
Сделайте профилировку каждого алгоритма через timeit
Попытайтесь написать третью версию, которая будет самой быстрой.
Сделайте замеры и опишите, получилось ли у вас ускорить задачу.
"""
from timeit import timeit
array = [1, 3, 1, 3, 4, 5, 1]
def func_1():
m = 0
num = 0
for i in array:
count = array.count(i)
if count > m:
m = count
num = i
return f'Чаще всего встречается число {num}, ' \
f'оно появилось в массиве {m} раз(а)'
def func_2():
new_array = []
for el in array:
count2 = array.count(el)
new_array.append(count2)
max_2 = max(new_array)
elem = array[new_array.index(max_2)]
return f'Чаще всего встречается число {elem}, ' \
f'оно появилось в массиве {max_2} раз(а)'
def func_3():
a = max(array, key=array.count)
return f'Чаще всего встречается число {a}, ' \
f'оно появилось в массиве {array.count(a)} раз(а)'
print("First: " + str(timeit("func_1()", "from __main__ import func_1, array", number=100000)))
print("Second: " + str(timeit("func_2()", "from __main__ import func_2, array", number=100000)))
print("Fird: " + str(timeit("func_3()", "from __main__ import func_3, array", number=100000)))
|
"""
Задание 3.
Определить количество различных подстрок с использованием хеш-функции.
Дана строка S длиной N, состоящая только из строчных латинских букв.
Подсказка: примените хеши и множества
рара:
рар
ра
ар
ара
р
а
"""
count = 0
my_str = "papa"
uniq = []
for i in range(len(my_str)):
for j in range(len(my_str), 0, -1):
if my_str[i:j] not in uniq and my_str[i:j] != my_str:
uniq.append(my_str[i:j])
count += 1 |
from datastructures.linked_list.linked_list import LinkedList
def test_instance():
ll = LinkedList()
assert isinstance(ll, LinkedList)
#Add_First To Empty LinkedList
def test_LinkedList_insert():
test_LinkedList = LinkedList()
test_LinkedList.insert(0)
assert test_LinkedList.head.value == 0
#Add_ To Not Empty LinkedList From the beginning
def test_LinkedList_insert_second_Test():
test_LinkedList = LinkedList()
test_LinkedList.insert(0)
assert test_LinkedList.head.value == 0
test_LinkedList.insert(1)
assert test_LinkedList.head.next.value == 0
#To Check if the LinkedList contain a node with specific value
def test_LinkedList_includes():
test_LinkedList = LinkedList()
test_LinkedList.insert(0)
test_LinkedList.insert(1)
assert test_LinkedList.includes(1) == True
assert test_LinkedList.includes(100) == False
#To Check if the LinkedList contain a node with specific value
def test__str__():
test_LinkedList = LinkedList()
test_LinkedList.insert('9')
test_LinkedList.insert('1')
test_LinkedList.insert('-')
test_LinkedList.insert('D')
test_LinkedList.insert('I')
test_LinkedList.insert('V')
test_LinkedList.insert('O')
test_LinkedList.insert('C')
test_LinkedList.insert('_')
test_LinkedList.insert('0')
test_LinkedList.insert('2')
test_LinkedList.insert('0')
test_LinkedList.insert('2')
assert test_LinkedList.__str__() == "{ 2 } -> { 0 } -> { 2 } -> { 0 } -> { _ } -> { C } -> { O } -> { V } -> { I } -> { D } -> { - } -> { 1 } -> { 9 } -> NULL"
def test_kthFromEnd():
test_LinkedList = LinkedList()
test_LinkedList.insert(5)
test_LinkedList.insert(3)
test_LinkedList.insert(2)
test_LinkedList.insert('raneem')
# test_LinkedList.append(88)
print(test_LinkedList)
actual = test_LinkedList.kth_from_the_end(1)
excpected = 3
assert excpected == actual
def test_kthFromEnd2():
test_LinkedList = LinkedList()
test_LinkedList.insert(5)
test_LinkedList.insert(3)
test_LinkedList.insert(2)
test_LinkedList.insert('raneem')
actual = test_LinkedList.kth_from_the_end(15)
excpected = 'Sorry, the value is larger than the linked list'
assert excpected == actual
|
x = str(input("Введіть слово:"))
y = ""
for i in x[::-1]:
y = y + i
print(y) |
def longest(s):
"""
:type s: str
:rtype: int
"""
max_before = max_now = start = 0
dict = {}
for index, i in enumerate(s):
if i in dict and dict[i] >= start:
max_before = max(max_before, max_now)
max_now = index - start - 1
start = dict[i] + 1
else :
max_now = max_now + 1
dict[i] = index
count = max(max_before, max_now)
return count
if __name__ == '__main__':
s = "aflhdjkcdgaiucv;weklq.fdvcxio;lkw.efbvdsu"
print(longest(s)) |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data_main=pd.read_csv("Medals.csv")
print data_main.head()
a=data_main["Athlete"].unique().tolist()
print "Valor de a::",len(a)
data_country=pd.read_csv("Athelete_Country_Map.csv")
print data_country.head()
print len(data_country)
duplicado=data_country[data_country["Athlete"]=="Aleksandar Ciric"]
print duplicado
data_sport=pd.read_csv("Athelete_Sports_Map.csv")
print data_sport.head()
print len(data_sport)
duplicado2=data_sport[(data_sport["Athlete"]=="Chen Jing") | ( data_sport["Athlete"]=="Richard Thompson") |
(data_sport["Athlete"]=="Matt Ryan")]
print duplicado2
data_country_dp=data_country.drop_duplicates(subset="Athlete")
data_sport_dp=data_sport.drop_duplicates(subset="Athlete")
print len(data_country_dp)
print len(data_sport_dp)
data_main_country=pd.merge(left=data_main, right=data_country_dp, left_on="Athlete", right_on="Athlete")
print data_main_country.head()
print data_main_country.shape
print data_main_country[data_main_country["Athlete"]=="Aleksandar Ciric"]
data_finaly=pd.merge(left=data_main_country, right=data_sport_dp, left_on="Athlete", right_on="Athlete")
print data_finaly.head()
print data_finaly.shape
|
# https://adventofcode.com/2020/day/5
file = open("day5_data", "r")
ticket_list = file.read().splitlines()
def parse(ticket, row_min, row_max, col_min, col_max):
row = None
column = None
for letter in ticket[0:8]: # parse the first 7 characters
if letter == "F":
row_max = row_min + ((row_max - row_min) // 2)
elif letter == "B":
row_min += (row_max - row_min) // 2 + ((row_max - row_min) % 2 > 0) # round UP
if row_max == row_min: # means we have our row
row = row_max
for letter in ticket[7:]:
if letter == "L":
col_max = col_min + ((col_max - col_min) // 2)
elif letter == "R":
col_min += (col_max - col_min) // 2 + ((col_max - col_min) % 2 > 0) # round UP
if col_max == col_min: # means we have our column
column = col_max
return row, column
# part 1 and 2 meshed
highest_seat = 0
seats = set()
for element in ticket_list:
row_start = 0
row_finish = 127
column_start = 0
column_finish = 7
position = parse(element, row_start, row_finish, column_start, column_finish)
# create a set with all the seats ID
seats.add(position[0] * 8 + position[1])
if (position[0] * 8 + position[1]) > highest_seat:
highest_seat = position[0] * 8 + position[1]
# part 2: need to find the missing seat ID knowing that the +1 element and the -1 element are present in the set
for element in seats:
if (element + 1 not in seats) and (element + 2 in seats):
print(element + 1)
break
print(highest_seat)
file.close()
|
# https://adventofcode.com/2020/day/7
import re
file = open("day7_data", "r")
data = file.read().splitlines()
graph = {}
for line in data:
if re.search('contain\sno\sother\sbags', line):
continue
# building the graph backwards, with the keys being the bags contained by their values
# this simplifies the research of the bags that need to contain our target
contained = re.findall('^\w*\s\w*', line)[0]
to_parse = re.findall('\d\s\w*\s\w*', line)
for el in to_parse:
key = el[2:]
if key not in graph.keys():
graph[key] = [contained]
else:
graph[key].append(contained)
def find_contained(bag, found):
"""
searches through the graph adding the values found in a set
"""
for x in graph[bag]:
found.add(x)
if x in graph:
find_contained(x, found)
return found
values = find_contained('shiny gold', set())
print(len(values))
# part 2
# rebuilding the graph topdown this time, because we need to search from shiny gold to bottom
graph = {}
for line in data:
if re.search('contain\sno\sother\sbags', line):
continue
key = re.findall('^\w*\s\w*', line)[0]
parsed = re.findall('\d\s\w*\s\w*', line)
nodes = []
for element in parsed:
nodes.append(element)
graph[key] = nodes
results = []
def hasNumbers(string):
"""
checks if string has a number in it
"""
return any(char.isdigit() for char in string)
# performing a DFS search
def DFSutil(g, n, c, visited):
if hasNumbers(n):
# parsing the values, splitting the bag count and the name of the bag
c *= int(n[0])
n = n[2:]
visited.add(n)
results.append((c, n))
try:
for neighbour in g[n]:
if neighbour not in visited:
DFSutil(g, neighbour, c, visited)
except KeyError:
pass
def DFS(g, n):
visited = set()
DFSutil(g, n, 1, visited)
DFS(graph, 'shiny gold')
final = 0
results.pop(0)
for bag in results:
final += bag[0]
print(final)
file.close()
|
a = input()
b = [1,0,0]
for move in a:
if move == 'A':
b[0],b[1] = b[1],b[0]
elif move == 'B':
b[1],b[2] = b[2],b[1]
else:
b[0],b[2] = b[2],b[0]
for i in range(len(b)):
if b[i] == 1: print(i+1)
|
a = int(input())
for i in range(a):
print("{} Abracadabra".format(i+1)) |
class Animal (object):
def __init__(self,sound,name,age,favorite_color):
self.sound=sound
self.name=name
self.age=age
self.favorite_color-favorite_color
def eat(self,food):
print("yummy!!"+self.name+"is eating"+ food)
def description(self):
print(self.name + "is" + self.age+ "years old and loves the color" + self.favorite_color)
def make_sound(self):
print(self.sound*3)
dog=Animal("barks","lucky","2","red")
dog.eat("pizza")
dog.description()
dog.make_sound()
|
from turtle import *
#import random
# colormode(255)
class Rectangle(Turtle):
def __init__(self,width,height):
Turtle.__init__(self)
register_shape("rectangle",((0,0),(0,height),(width,height),(width,0),(0,0)))
self.shape("rectangle")
self.setheading(90)
class Square(Turtle):
def __init__(self,size):
Rectangle.__init__(self,size,size)
def random_color(self):
r=random.randint(0,255)
g=random.randint(0,255)
b=random.randint(0,255)
self.color(r,g,b)
square10=Square(50)
# rect1= Rectangle(50,50)
# self.shapesize(shapesize)
# self.shape("square")
# square1=Square(10)
# square1.random_color()
# 0
# class Rectangle(Turtle):
# def __init__(self,width,height):
# Turtle.__init__(self)
# register_shape("rectangle",((0,0),(0,height),(width,height),(width,0),(0,0)))
# self.shape("rectangle")
# self.setheading(90)
# rect1= Rectangle(50,100)
mainloop()
# turtle.register_shape("Hexagone",((0,0),(30,-20),(0,-70),(-30,-50),(-30,-20),(0,0)))
# turtle.shape("Hexagone")
# turtle.mainloop()
# class Hexagon(Turtle):
# def __init__(self,shapesize):
# Turtle.__init__(self)
# self.shapesize(shapesize)
# self.shape("Hexagone")
|
a, b = (int(s) for s in input().strip().split(' '))
if a <= 0 and 0 <= b:
print('Zero')
elif 0 < a or (b-a)%2 == 1:
print('Positive')
else:
print('Negative')
|
from math import sqrt
from sympy import factorint
def isSquare(n):
return n == (int(sqrt(n)))**2
n = 10**12
ans = 0
for r in range(1, int(sqrt(n))):
fac = factorint(r)
_r = 1
for f in fac:
_r *= f ** ((fac[f]+1) // 2)
d = r + _r
a = d**3 // r + r
while a < n:
if isSquare(a):
ans += a
d += _r
a = d**3 // r + r
print(ans)
|
#!/usr/bin/python3
"""
Contains the definition of the read_file function
"""
def read_file(filename=""):
"""Reads a text file and prints it to stdout
Args:
filename (str): name of the file to be read
"""
with open(filename, encoding="UTF-8") as f:
for line in f:
print(line, end="")
|
#!/usr/bin/python3
'''
check if a especific object is a kind of instance of a class
'''
def is_kind_of_class(obj, a_class):
'''
check if object belongs a class or heritance
args:
obj: object
a_class: class to check
Return:
True or false
'''
return isinstance(obj, a_class)
|
#!/usr/bin/python3
def uniq_add(my_list=[]):
adds = 0
for i in set(my_list):
adds += i
return(adds)
|
#!/usr/bin/python3
def multiply_by_2(a_dictionary):
a_dictionary2 = {}
for key, val in a_dictionary.items():
a_dictionary2[key] = 2 * val
return(a_dictionary2)
|
#!/usr/bin/python3
"""
Contains the definition of the class Square.
"""
from models.rectangle import Rectangle
class Square(Rectangle):
"""Definition of class Square that inherits from class Rectangle"""
def __init__(self, size, x=0, y=0, id=None):
"""Initialize an instance of class Square"""
super().__init__(size, size, x, y, id)
@property
def size(self):
"""Initialize and return size attribute"""
return self.width
@size.setter
def size(self, value):
if type(value) is int:
if value <= 0:
raise ValueError("width must be > 0")
self.width = value
self.height = value
else:
raise TypeError("width must be an integer")
def __str__(self):
"""Return a string representation of an instance of class Square"""
return "[{}] ({}) {}/{} - {}".format(type(self).__name__, self.id,
self.x, self.y, self.width)
def update(self, *args, **kwargs):
"""Assigns an argument to each attribute
Args:
args (pointer): a "pointer" to an array of strings
kwargs (double pointer): "double pointer" to a dictionary that has
keyword:value pairs
"""
if len(args) != 0:
for i, arg in enumerate(args):
if i == 0:
self.id = arg
elif i == 1:
self.size = arg
elif i == 2:
self.x = arg
elif i == 3:
self.y = arg
if kwargs is not None and len(args) == 0:
for key, val in kwargs.items():
self.__setattr__(key, val)
def to_dictionary(self):
"""Returns dictionary representation of instance of class Rectangle"""
keys = ["id", "size", "x", "y"]
return {a: getattr(self, a) for a in keys}
|
#!/usr/bin/python3
"""
Contains the definition of the append_write function
"""
def append_write(filename="", text=""):
"""Appends a string at the end of the text file and returns the
number of chars written
Args:
filename (str): name of the file to be written to
text (str): text to be appended to the end of the file
"""
with open(filename, mode="a", encoding="UTF-8") as f:
return (f.write(text))
|
#!/usr/bin/python3
'''
Class BaseGeometry
'''
BaseGeometry = __import__("7-base_geometry").BaseGeometry
class Rectangle(BaseGeometry):
'''
Represent a class Rectangle heritance from BaseGeometry
'''
def __init__(self, width, height):
'''
define width and height of Rectangle class
call the method of the superclass
'''
self.integer_validator("width", width)
self.integer_validator("height", height)
self.__width = width
self.__height = height
def area(self):
'''
method to define the area of rectangle
'''
return self.__height * self.__width
def __str__(self):
'''
print the rectangle width and height
'''
return "[{}] {}/{}".format(type(self).__name__,
self.__width, self.__height)
|
class Solution:
def simplifyPath(self, path):
"""
:type path: str
:rtype: str
"""
path_list = path.split("/")
path_stack = []
for path in path_list:
if path != "/" and path != "." and path != ".." and path != "":
path_stack.append(path)
if path == "..":
if len(path_stack) > 0:
path_stack.pop()
res = "/" + "/".join(path_stack)
return res
x = Solution()
print(x.simplifyPath("/a/./b/../../c/"))
print(x.simplifyPath("/../"))
print(x.simplifyPath("/home//foo/")) |
# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
class NestedInteger:
def __init__(self, value=None):
"""
If value is not specified, initializes an empty list.
Otherwise initializes a single integer equal to value.
"""
def isInteger(self):
"""
@return True if this NestedInteger holds a single integer, rather than a nested list.
:rtype bool
"""
def add(self, elem):
"""
Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
:rtype void
"""
def setInteger(self, value):
"""
Set this NestedInteger to hold a single integer equal to value.
:rtype void
"""
def getInteger(self):
"""
@return the single integer that this NestedInteger holds, if it holds a single integer
Return None if this NestedInteger holds a nested list
:rtype int
"""
def getList(self):
"""
@return the nested list that this NestedInteger holds, if it holds a nested list
Return None if this NestedInteger holds a single integer
:rtype List[NestedInteger]
"""
class Solution:
def getNumber(self, s):
for i in range(0, len(s)):
if not s[i].isdigit() and s[i] != '-':
return int(s[:i])
return None
def findNextPair(self, s):
stack = []
if s[0] != '[':
return -1
stack.append(s[0])
for i in range(1, len(s)):
if s[i] == ']':
stack.pop()
elif s[i] == '[':
stack.append('[')
if len(stack) == 0:
return i + 1
return -1
def deserializeList(self, s: str):
def deserialize(self, s: str) -> NestedInteger:
res = None
if len(s) == 0 or not s:
return NestedInteger()
if s[0] == '[':
# is list
ni = self.findNextPair(s)
res.add(self.deserialize[s[0:ni]])
res = NestedInteger()
index = s.find(',')
if index > 0:
res.add(self.deserialize(s[:index]))
res.add(self.deserialize(s[index+1:]))
else:
res.add(self.deserialize(s))
else:
num = self.getNumber(s)
res = NestedInteger()
if num:
res.setInteger(num)
return res
print(Solution().deserialize("[2,[],5,[3,4]]")) |
class Solution:
def search(self, nums: list, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
def search_index(nums: list, low: int, high: int):
if len(nums) == 0:
return -1
mid = (int)((low + high) / 2)
if nums[mid] == target:
return mid
if (high - low) <= 0:
return -1
if nums[mid] <= nums[high]:
if target > nums[mid] and target <= nums[high]:
return search_index(nums, mid + 1, high)
else:
return search_index(nums, low, mid - 1)
if nums[mid] >= nums[low]:
if target >= nums[low] and target < nums[mid]:
return search_index(nums, low, mid - 1)
else:
return search_index(nums, mid + 1, high)
low = 0
high = len(nums) - 1
return search_index(nums, low, high)
x = Solution()
print(x.search([3,1], 0))
|
class TrieNode:
def __init__(self, ch):
self.subs = [None] * 26
self.isEnd = False
self.ch = ch
def addWord(self, word):
nodePoint = self
for i, ch in enumerate(word):
if nodePoint.subs[ord(ch) - ord('a')] == None:
nodePoint.subs[ord(ch) - ord('a')] = TrieNode(ch)
if i == len(word) - 1:
nodePoint.subs[ord(ch) - ord('a')].isEnd = True
nodePoint = nodePoint.subs[ord(ch) - ord('a')]
def hasWord(self, word):
nodeP = self
for i, ch in enumerate(word):
if nodeP.subs[ord(ch) - ord('a')] != None:
nodeP = nodeP.subs[ord(ch) - ord('a')]
else:
return False
return nodeP.isEnd
class Solution:
def findAllConcatenatedWordsInADict(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
root = TrieNode(None)
for word in words:
root.addWord(word)
def dfs(word, count):
# if the current word could be formed by two subs word
cur = root
if len(word) == 0:
return count > 1
for i, ch in enumerate(word):
if cur.subs[ord(ch) - ord('a')] == None:
return False
if cur.subs[ord(ch) - ord('a')].isEnd:
if dfs(word[i + 1:], count + 1):
return True
cur = cur.subs[ord(ch) - ord('a')]
return False
res = []
for word in words:
if dfs(word, 0):
res.append(word)
return res
print(Solution().findAllConcatenatedWordsInADict(["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"])) |
class Solution:
def groupAnagrams(self, strs: list):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
def generate_tuple_key(_str):
a = [0] * 26
for char in _str:
a[ord(char) - ord('a')] += 1
return tuple(a)
stored = dict()
for _str in strs:
key = generate_tuple_key(_str)
if key in stored.keys():
stored[key].append(_str)
else:
stored[key] = [_str]
result = []
for key in stored.keys():
result.append(stored[key])
return result
x = Solution()
print(x.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))
|
import sys
import matplotlib
matplotlib.use('TkAgg')
import numpy as np
import scipy.io
import scipy.spatial
import matplotlib.pyplot as plt
import math
from pca import PCA
# TODO: Implement euclidean distance between two vectors
def euclideanDistance(a, b):
'''
:param a: vector
:param b: vector
:return: scalar
'''
return math.sqrt(sum([(x - y) ** 2 for x, y in zip(a, b)]))
# TODO: Implement mahalanobis distance between two vectors
def mahalanobisDistance(a, b, invS):
'''
:param a: vector
:param b: vector
:param invS: matrix
:return: scalar
'''
return scipy.spatial.distance.mahalanobis(a, b, invS)
def faceRecognition():
'''
Train PCA with with 25 components
Project each face from 'novel' into PCA space to obtain feature coordinates
Find closest face in 'gallery' according to:
- Euclidean distance
- Mahalanobis distance
Redo with different PCA dimensionality
What is the effect of reducing the dimensionality?
What is the effect of different similarity measures?
'''
numOfPrincipalComponents = 25
# TODO: Train a PCA on the provided face images
pca = PCA(numOfPrincipalComponents)
(X, data_labels, gall_faces) = data_matrix()
pca.train(X)
alphagal = pca.to_pca(X)
# TODO: Plot the variance of each principal component - use a simple plt.plot()
f = plt.figure(1)
plt.plot(np.var(alphagal, 1, dtype=np.float64))
f.show()
# TODO: Implement face recognition
(novel, novel_labels, nov_faces) = load_novel()
alphanov = pca.to_pca(novel)
matches_e = []
matches_m = []
invS = np.diag(1. / pca.S)
for i in range(alphanov.shape[1]):
lowest_e = (sys.maxsize, 0)
lowest_m = (sys.maxsize, 0)
for j in range(alphagal.shape[1]):
euclidean = euclideanDistance(alphanov[:, i], alphagal[:, j])
if euclidean < lowest_e[0]:
lowest_e = euclidean, j
maha = mahalanobisDistance(alphanov[:, i], alphagal[:, j], invS)
if maha < lowest_m[0]:
lowest_m = maha, j
matches_e.append((i, lowest_e[1]))
matches_m.append((i, lowest_m[1]))
print(matches_e)
print(matches_m)
correct_m = 0
correct_e = 0
correct_classified = 0
correct_partner = 0
wrong_classified = 0
wrong_partner = 0
for x in range(len(matches_e)):
if data_labels[matches_e[x][0]] == novel_labels[matches_e[x][1]]:
correct_e += 1
correct_classified = x
correct_partner = matches_e[x][1]
else:
wrong_classified = x
wrong_partner = matches_e[x][1]
if data_labels[matches_m[x][0]] == novel_labels[matches_m[x][1]]:
correct_m += 1
print("Correct Euclidian Classification in percent: {}".format(correct_e / len(matches_e) * 100))
print("Correct Mahalanobis Classification in percent: {}".format(correct_m / len(matches_m) * 100))
# TODO: Visualize some of the correctly and wrongly classified images (see example in exercise sheet)
# Show correct classified
fig = plt.figure(2)
columns = 3
rows = 2
titles = ("correct test", "wrong test", "projected test", "correct train", "wrong train", "projected train")
# plt.title(titles[i])
# correct
sub = fig.add_subplot(rows, columns, 1)
sub.set_title("Novel to test")
sub.set_ylabel("Correct Classified")
plt.imshow(nov_faces.item(correct_classified)[1], cmap='gray')
sub = fig.add_subplot(rows, columns, 2)
sub.set_title("Closest from training")
plt.imshow(gall_faces.item(correct_partner)[1], cmap='gray')
sub = fig.add_subplot(rows, columns, 3)
sub.set_title("Novel projected")
correct_projected = pca.project(novel, numOfPrincipalComponents)[:, correct_classified].reshape(
gall_faces.item(correct_partner)[1].shape)
plt.imshow(correct_projected, cmap='gray')
# wrong
sub = fig.add_subplot(rows, columns, 4)
sub.set_title("Novel to test")
sub.set_ylabel("Wrong Classified")
plt.imshow(nov_faces.item(wrong_classified)[1], cmap='gray')
sub = fig.add_subplot(rows, columns, 5)
sub.set_title("Closest from training")
plt.imshow(gall_faces.item(wrong_partner)[1], cmap='gray')
sub = fig.add_subplot(rows, columns, 6)
sub.set_title("Novel projected")
wrong_projected = pca.project(novel, numOfPrincipalComponents)[:, wrong_classified].reshape(
gall_faces.item(wrong_partner)[1].shape)
plt.imshow(wrong_projected, cmap='gray')
fig.show()
def load_novel_faces():
matnov = scipy.io.loadmat('../data/novel.mat')
nov = matnov['novel'][0]
return nov
def load_novel():
matnov = scipy.io.loadmat('../data/novel.mat')
nov = matnov['novel'][0]
numOfFaces = nov.shape[0]
[N, M] = nov.item(0)[1].shape
print("NumOfFaces in novel dataset", numOfFaces)
data_matrix = np.zeros((N * M, numOfFaces))
novID = np.zeros(numOfFaces)
for i in range(numOfFaces):
facefirst = nov.item(i)[1]
faceId = nov.item(i)[0][0]
data_matrix[:, i] = facefirst.flatten().T
novID[i] = faceId
return (data_matrix, novID, nov)
def data_matrix():
'''
Hint: In order to do this, you must assemble a data matrix by stacking each image m x n
into a a column vector mn x 1 and concatenate all column vectors horizontally.
'''
matgal = scipy.io.loadmat('../data/gallery.mat')
gall = matgal['gall'][0]
numOfFaces = gall.shape[0]
[N, M] = gall.item(0)[1].shape
print("NumOfFaces in gallery dataset", numOfFaces)
data_matrix = np.zeros((N * M, numOfFaces))
dataID = np.zeros(numOfFaces)
for i in range(numOfFaces):
facefirst = gall.item(i)[1]
faceId = gall.item(i)[0][0]
data_matrix[:, i] = facefirst.flatten().T
dataID[i] = faceId
return (data_matrix, dataID, gall)
def faceLoaderExample():
'''
Face loader and visualizer example code
'''
matgal = scipy.io.loadmat('../data/gallery.mat')
gall = matgal['gall'][0]
numOfFaces = gall.shape[0]
[N, M] = gall.item(0)[1].shape
print("NumOfFaces in dataset", numOfFaces)
# Show first image
plt.figure(0)
plt.title('First face')
n = 0
facefirst = gall.item(n)[1]
faceId = gall.item(n)[0][0]
print('Face got face id: {}'.format(faceId))
plt.imshow(facefirst, cmap='gray')
plt.show()
if __name__ == "__main__":
print(sys.version)
print("##########-##########-##########")
print("PCA images!")
# faceLoaderExample()
faceRecognition()
print("Fertig PCA!")
|
"""
4. Median of Two Sorted Arrays
Hard
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
"""
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
index1 = 0
index2 = 0
mergedList = []
while index1 < len(nums1) and index2 < len(nums2):
if nums1[index1] <= nums2[index2]:
mergedList.append(nums1[index1])
index1 += 1
if index1 == len(nums1):
break
if nums2[index2] < nums1[index1]:
mergedList.append(nums2[index2])
index2 += 1
while index2 < len(nums2):
mergedList.append(nums2[index2])
index2 += 1
while index1 < len(nums1):
mergedList.append(nums1[index1])
index1 += 1
mergedLength = len(mergedList)
if (mergedLength % 2 == 1):
return mergedList[((int) (mergedLength / 2))]
return (mergedList[(int)(mergedLength / 2)] + mergedList[((int)(mergedLength / 2)) - 1] ) / 2 |
def checkParity(byte):
parity = True
for bit in byte:
if bit == '1':
parity = not parity
return parity
for line in open('temp.txt'):
for byte in line.split():
if(checkParity(byte)):
print(byte[:-1])
|
## Victor Fabio and Dan Wolf
##
## 11/17/13
##
## This program runs a game in which hamburgers fly across the screen and the player has to catch
## them and eat them before they leave the screen. If they miss too many, the game is over.
##
## For this game we used the python and pygame documentation.
#import modules
import pygame
import random
import math
#this function finds the distance between two points
def distance (x1, y1, x2, y2):
"""Calculates the distance between two points (x1, y1) and
(x2,y2)."""
return math.sqrt((x1-x2)**2 + (y1-y2)**2)
#set up indices
WIDTH = 0
X = 1
Y = 2
XVEL = 3
YVEL = 4
COLOR = 5
COLLIDE = 6
HEIGHT = 7
#define all helping functions to create and filter the burgers, to read and
#write the high score file, and order the high scores.
def create_burger(width, height,w2):
x = width-w2
y = random.randint(w2, height-w2)
xvel = 2
yvel = 0
color = (0,240,0)
collide = False
burger = [w2, x, y, xvel, yvel, color, collide]
return burger
def filter_burgers(burgers):
burgers2 = []
for burger in burgers:
if burger[X] > 0:
burgers2 += [burger]
return burgers2
def read_file():
f = open("hiscores.txt", "r")
dict = {}
for line in f:
n = line.strip("\n")
n = n.split(":")
key = n[0]
value = int(n[1])
dict[key] = value
return dict
f.close()
def order_dict(dict):
first = 0
second = 0
third = 0
scores = []
for key, value in dict.items():
if value > first:
first = value
name = key
scores += [name + ": " + str(first)]
for key, value in dict.items():
if value > second and value < first:
second = value
name = key
scores += [name + ": " + str(second)]
for key, value in dict.items():
if value > third and value < second:
third = value
name = key
scores += [name + ": " + str(third)]
return scores
def write_file(dict):
f= open("hiscores.txt","w")
for key,value in dict.items():
entry = str(key)+":"+str(value)+"\n"
f.write(entry)
f.close()
#main game function
def run_game():
## Initialize the pygame submodules and set up the display window.
pygame.init()
flames = pygame.image.load("Flames.png")
# pictures and sound
width = flames.get_width()
height = flames.get_height()
my_win = pygame.display.set_mode((width,height))
myFont = pygame.font.Font(None,30)
endFont = pygame.font.Font(None,80)
hamburger = pygame.image.load("hamburger.png")
hamburger = hamburger.convert_alpha()
w2 = hamburger.get_width()
skull = pygame.image.load("Skull.png")
skull = skull.convert_alpha()
bite_sound = pygame.mixer.Sound("bite_sound.wav")
pygame.mixer.music.load("valkyries.ogg")
pygame.mixer.music.play(-1)
pygame.mixer.music.set_volume(.5)
# starting position, size, and velocity for the player character
w = skull.get_width()
h = skull.get_height()
x = 0
y = random.randint(0, height-w)
yvel = 0
#variables for key presses
up = False
down = False
replay = False
#variables for high scores
score = 0
dict = read_file()
# create a list of burgers
burgers = []
missed_burgers = 0
## setting up the clock
clock = pygame.time.Clock()
dt = 0
time = 0
n = 1
# initialize the player name
name = ""
## INTRO SCREEN LOOP: This program uses a sequence of loops to go
## through an intro screen, the main game, and a game over screen.
keepGoingIntro = True
keepGoing = True
keepGoingGameOver = True
while (keepGoingIntro):
dt = clock.tick()
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
keepGoingIntro = False
# During the intro screen, record the characters the
# player types (he is inputting his player name). End the
# intro phase when the player hits 'Enter'.
elif event.type==pygame.KEYDOWN:
if event.key >= 65 and event.key <= 122:
name += chr(event.key)
elif event.key == 13:
keepGoingIntro = False
# Draw picture and update display.
my_win.fill(pygame.color.Color("darkgreen"))
# draw the intro message
label = myFont.render("Move the skull up and down with w and s to catch the burgers.", True, pygame.color.Color("black"))
x3, y3 = 50, 50
my_win.blit(label, (x3,y3))
label = myFont.render("If you miss ten, you lose.", True, pygame.color.Color("black"))
y3 += 45
my_win.blit(label, (x3,y3))
label = myFont.render("Please enter your name: "+name, True, pygame.color.Color("black"))
y3 += 45
my_win.blit(label, (x3,y3))
label = myFont.render("Then hit 'Enter' to start.", True, pygame.color.Color("black"))
y3 += 45
my_win.blit(label, (x3,y3))
pygame.display.update()
## The game loop starts here.
while (keepGoing):
dt = clock.tick(60)
draw = random.randint(1,75)
## Handle events.
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
keepGoing = False
keepGoingGameOver = False
elif event.type == pygame.KEYDOWN:
if pygame.key.name(event.key) == "w":
up = True
elif pygame.key.name(event.key) == "s":
down = True
elif event.type == pygame.KEYUP:
if pygame.key.name(event.key) == "w":
up = False
elif pygame.key.name(event.key) == "s":
down = False
#spawn burgers
if keepGoing == True:
burger = create_burger(width, height,w2)
if len(burgers) < 5:
if draw == 50:
burgers += [burger]
## Simulate game world
# update velocity according to player input
if up and not down:
yvel = -7
elif down and not up:
yvel = 7
else:
yvel = 0
if y <= 0:
up = False
y = 0
if y >= height-h:
down = False
y = height-h
# move burger/update burger position
for burger in burgers:
burger[X] = burger[X] + burger[XVEL]
burger[Y] = burger[Y] + burger[YVEL]
# make sure burger stays inside pygame window and update burger
# velocity
for burger in burgers:
if (burger[X] > width - burger[WIDTH]):
burger[X] = width - burger[WIDTH]
burger[XVEL] = -1 * burger[XVEL]
if (burger[Y] < burger[WIDTH]):
burger[Y] = burger[WIDTH]
burger[YVEL] = -1 * burger[YVEL]
if (burger[Y] > height - burger[WIDTH]):
burger[Y] = height - burger[WIDTH]
burger[YVEL] = -1 * burger[YVEL]
# move player character
y += yvel
# collision detection
for burger in burgers:
if burger[COLLIDE] == False:
if (burger[Y]+burger[WIDTH]) < y:
burger[COLLIDE] = False
elif burger[Y] > (y + (h-10)):
burger[COLLIDE] = False
elif burger[X] > (x + w-5):
burger[COLLIDE] = False
else:
burger[COLLIDE] = True
score += 1
bite_sound.play()
if burger[COLLIDE] == True:
burger[X] = width - w
burger[Y] = random.randint(w, height-w)
burger[COLLIDE] = False
if burger[X] <= 0:
missed_burgers += 1
# variable speed
if score >= 5*n:
n+=1
for burger in burgers:
burger[XVEL]-=1
burger[XVEL]-=1
## Draw picture and update display
my_win.blit(flames,(0,0))
msg = myFont.render(str(name)+": "+str(score), True, pygame.color.Color("darkgreen"))
my_win.blit(msg, (20,height-40))
msg = myFont.render("Missed: "+str(missed_burgers), True, pygame.color.Color("darkgreen"))
my_win.blit(msg, (20,0))
for burger in burgers:
my_win.blit(hamburger, (burger[X],burger[Y]))
my_win.blit(skull, (x,y))
burgers = filter_burgers(burgers)
if missed_burgers >= 10:
keepGoing = False
pygame.display.update()
#game over screen
while (keepGoingGameOver):
## Handle events.
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
keepGoingGameOver = False
elif event.type == pygame.KEYDOWN:
if pygame.key.name(event.key) == "r":
replay = True
elif event.type == pygame.KEYUP:
if pygame.key.name(event.key) == "r":
replay = False
#deal with high scores
for key, value in dict.items():
if name == key:
if score > value:
dict[name] = score
elif name not in dict.keys():
dict[name] = score
write_file(dict)
scores = order_dict(dict)
#draw game over screen with high scores and replay option
my_win.fill(pygame.color.Color("black"))
top_scores = myFont.render("Top Scores:", True, pygame.color.Color("darkgreen"))
my_win.blit(top_scores, (width/2-50,height/2+20))
scores_first = myFont.render(str(scores[0]), True, pygame.color.Color("darkgreen"))
my_win.blit(scores_first, (width/2-50,height/2+50))
scores_second = myFont.render(str(scores[1]), True, pygame.color.Color("darkgreen"))
my_win.blit(scores_second, (width/2-50,height/2+70))
scores_third = myFont.render(str(scores[2]), True, pygame.color.Color("darkgreen"))
my_win.blit(scores_third, (width/2-50,height/2+90))
pygame.mixer.music.stop()
end_msg = endFont.render("Game Over", True, pygame.color.Color("darkred"))
my_win.blit(end_msg, (width/2-160,height/2-100))
msg = myFont.render(str(name)+": "+str(score), True, pygame.color.Color("darkred"))
my_win.blit(msg, (width/2-50,height/2-20))
replay_msg = myFont.render("Press r to replay", True, pygame.color.Color("darkred"))
my_win.blit(replay_msg, (width-250,height-40))
#replay option
if replay:
run_game()
pygame.display.update()
## The game loop ends here.
pygame.quit()
## Call the function run_game.
run_game()
|
#!/usr/bin/python
#coding:utf-8
#内置函数open()
#打开一个文件
#打开一个参数,标识我要打开的文件名为python.txt
#第二个参数,表示打开文件的模式是w,
# 表示打开文件的模式是ww打开一个文件只用于写入,如果该文件已存在则打开文件
# 并从头开始编辑,即原有内容被删除,
# 如果该文件不存在,穿件新文件
#open()后会返回一个对象,file = open()把这个对象保存在file
# file =open('F:/pythonlanguage2/cxy/test.txt','w')
# file.close()
# print('文件名称',file.name)
# print('文件是否关闭',file.closed)
# print('文件访问模式',file.mode)
# f = open('F:/pythonlanguage2/cxy/test.txt','r')
# print(f)
import chardet
import os
# data =open(r"/Users/xudongma/python/pythonLanguage/cxy/python.txt", "rb").read()
file = open('/Users/xudongma/python/pythonLanguage/cxy/python.txt','r',encoding='GB2312')
# print(chardet.detect(data))
s = file.read()
#\n充当回车键
print('文件的内容是:\n',s)
#往文件里写内容,会覆盖原来的内容
file = open('/Users/xudongma/python/pythonLanguage/cxy/python.txt','w',encoding='GB2312')
s = file.write('i am learning python.\nI loge python')
file.close()
#格式:file = open("文件路径\\文件名","w")
#修改文件(改名rename("原来的名字","修改后的名字"))
# os.rename("Users/xudongma/python/pythonLanguage/cxy/python.txt","python2.txt")
#删除这个文件(remove("要删除的文件名"))
os.remove("Users/xudongma/python/pythonLanguage/cxy/python.txt")
|
from player import Player
from human import Human
from computer import Computer
class Game:
# 1. A “friendly” welcome, and display the rules
# 2. Choose single player (Human vs. AI) or multiplayer (Human vs. Human)
# 3. Players enter names
# 4. How many rounds? (Remember that only three are required for the user story)
# 5. Display the options for gestures
# 7. Display the gestures that have been chosen
# 8. Compare gestures
# 9. Determine who won that round
# 10. Track score (round wins) and check to see if someone has won the whole game (best of 3 minimum) (check every round)
# 11. Display the winner
# 12. Do you want to play the entire game again?
def __init__(self):
player_one = ''
player_two = ''
print("Welcome to Rock, Paper, Scissors, Lizard, Spock!")
print("Here are the rules: Rock crushes Scissors, Scissors cuts Paper, Paper covers Rock, Rock crushes Lizard, Lizard poisons Spock, Spock smashes Scissors, Scissors decapitates Lizard, Lizard eats Paper, Paper disproves Spock, Spock vaporizes Rock")
def set_name(self):
self.name = input("Enter player name:")
print("player name: ", self.name)
def run_game(self):
# self.new_game = Game()
self.new_game.game_type()
self.new_game.player_one.set_name()
self.new_game.player_one.gesture_choice()
self.new_game.player_two.gesture_choice()
# player_one = ''
# player_two = ''
def game_type(self):
game_type = input("Please choose '1' for Single Player (Player vs. Computer) or '2' Multiplayer (Player 1 vs. Player 2)")
if game_type == "1":
self.player_one = Human()
self.player_two = Computer()
elif game_type == "2":
self.player_one = Human()
self.player_two = Human()
else:
print("Invalid Entry")
# def gesture_choice(self):
# print("Please enter one of the following gestures: rock, paper, scissors, lizard, or spock")
# self.player_one.chosen_gesture = input("Enter your gesture:")
# while True:
# game_type = input("Please choose '1' for Single Player (Player vs. Computer) or '2' Multiplayer (Player 1 vs. Player 2)")
# if game_type == "1" or game_type == "2":
# break
# print("Invalid Entry")
# player_one = Human()
# if game_type == "1":
# player_two = Computer()
# else:
# player_two = Human ()
# def run_game(self):
# self.welcome()
# self.choose_players()
# #game rounds
# #end game
# pass
0
# def welcome(self):
# print("Welcome to Rock, Paper, Scissors, Lizard, Spock!")
# print("Here are the rules: Rock crushes Scissors, Scissors cuts Paper, Paper covers Rock, Rock crushes Lizard, Lizard poisons Spock, Spock smashes Scissors, Scissors decapitates Lizard, Lizard eats Paper, Paper disproves Spock, Spock vaporizes Rock")
# def choose_players(self):
# input("Please choose Single Player (Player vs. Computer) or Multiplayer (Player 1 vs. Player 2)")
# def player_gesture(self):
# Need to pull variable from self.chose_gesture
# player_gesture =
# if player_gesture == gesture_choice
# print("Try Again")
# # run 'select a gesture'
# elif self.player_one.gesture == "rock" and self.player_two.gesture == "lizard" or "scissors":
# print("Player One Wins!")
# # add 1 to player one counter
# elif self.player_one.gesture == "paper" and self.player_two.gesture == "rock" or "spock":
# print("Player One Wins!")
# # add 1 to player one counter
# elif self.player_one == "scissors" and self.player_two == "lizard" or "paper":
# print("Player One Wins!")
# # add 1 to player one counter
# elif self.player_one.gesture == "lizard" and self.player_two.gesture == "paper" or "spock":
# print("Player One Wins!")
# # add 1 to player one counter
# elif self.player_one.gesture == "spock" and self.player_two.gesture == "rock" or "scissors":
# print("Player One Wins!")
# # add 1 to player one counter
# else:
# print("Player Two Wins!")
# # add 1 to player two counter
|
'''
Python Homework Assignment #6
Advanced Loops
By: Hieu Nguyen
'''
# Details:
# Create a function that takes in two parameters: rows, and columns, both of which are integers. The function should then proceed to draw a playing board (as in the examples from the lectures) the same number of rows and columns as specified. After drawing the board, your function should return True.
# Extra Credit:
# Try to determine the maximum width and height that your terminal and screen can comfortably fit without wrapping. If someone passes a value greater than either maximum, your function should return False.
#Create function to display playing board
# Start Global rows and columns at 0 because positive numbers.
rows = 0
columns = 0
def GridBoard(rows,columns):
if rows <=100 and columns <=100:
for r in range(1, rows + 1):
if r % 2 != 0:
for c in range(columns):
if c%2 == 0:
if c != columns - 1:
print(" ",end="")
else:
print("|",end="")
else:
print("")
else:
print("-" * columns)
print(True)
else:
print(False)#Otherwise
GridBoard(21,21)#True
GridBoard(90,101)#False
GridBoard(50,100)#True
GridBoard(90,101)#False
GridBoard(100,100)#True
GridBoard(90,101)#False |
'''
calculate chi squared distance between two histograms
'''
def chisquared(a,b):
chi = 0.0
for x,y in zip(a,b):
#print x,y
if(x+y>0):
chi += (float(x-y)**2 / float(x+y))
return chi
if __name__=='__main__':
print chisquared([1,2],[3,4])
|
# Factorial digit sum
# Problem 20
# n! means n (n 1) ... 3 2 1
# For example, 10! = 10 9 ... 3 2 1 = 3628800,
# and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
# Find the sum of the digits in the number 100!
from math import factorial
digits = list(str(factorial(100)))
print reduce(lambda x, y: x + y, map(lambda x: int(x), digits)) |
# Smallest multiple
# Problem 5
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
def divisible_by(n, divisor):
return n % divisor == 0
i, n = 20, 20
while i > 1:
for i in reversed(range(1, 21)):
if not divisible_by(n, i):
n += 20
i = 20
print n |
from tkinter import *
import random
from tkinter import messagebox
answers = [
"python",
"java",
"swift",
"canada",
"india",
"america",
"london",
]
words = [
"nptoyh",
"avja",
"wfsit",
"cdanaa",
"aidin",
"aiearcm",
"odnlon",
]
num = random.randrange(0,7,1)
def default():
global words,answers,num
lbl.config(text=words[num])
def checkans():
global words, answers, num
var = e1.get()
if var == answers[num]:
messagebox.showinfo("Sucess!","This is correct answer")
res()
else:
messagebox.showerror("Error","Answer is incorrect try another.")
e1.delete(0,END)
def res():
global words,answers,num
num = random.randrange(0,7,1)
lbl.config(text=words[num])
e1.delete(0,END)
root = Tk()
root.title("Jumbbled words game")
root.geometry("300x300")
root.config(background = "Black")
lbl = Label(root,text="Your here",font=("Vardana",20),fg="blue",bg="black")
lbl.pack(padx=10,pady=20)
# ans1 = StringVar()
e1 = Entry(root,font="Vardana,15")
e1.pack()
buttn1 = Button(root,text="Check",font=("comic sans ms",16),width=7,height=0,bg="#616C6F",fg="#6AB04A",relief=GROOVE,command=checkans)
buttn1.pack(pady=20)
buttn2 = Button(root,text="Reset",font=("comic sans ms",16),width=7,height=0,bg="#616C6F",fg="#D63031",relief=GROOVE,command=res)
buttn2.pack()
default()
root.mainloop()
|
import random
from random import shuffle
Playerchar = [{"name": "Ronaldo", "Shoot" : 9.5, "Passing": 6.0, "Speed": 9.0},
{"name": "Messi", "Shoot" : 9.0, "Passing": 9.5, "Speed": 7.0},
{"name": "Ramos", "Shoot" : 7.0, "Passing": 7.0, "Speed": 5.0},
{"name": "Buffon", "Shoot" : 6.0, "Passing": 4.0, "Speed": 3.0},
{"name": "Neymar", "Shoot" : 8.5, "Passing": 9.0, "Speed": 9.5},
{"name": "Iniesta", "Shoot" : 7.5, "Passing": 10.0, "Speed": 5.5},
{"name": "Pele", "Shoot" : 9.8, "Passing": 9.7, "Speed": 9.8},
{"name": "Maradona", "Shoot" : 10.0, "Passing": 9.9, "Speed": 10.0},
{"name": "Mbappe", "Shoot" : 8.4, "Passing": 9.1, "Speed": 9.9},
{"name": "Suarez", "Shoot" : 9.2, "Passing": 7.5, "Speed": 7.5}]
class Deck :
def __init__(self) :
print("Creating New Ordered Deck")
self.allcards = [(key)for key in Playerchar]
def shuffle(self):
print("Shuffling Deck")
shuffle(self.allcards)
def split_in_half(self):
return (self.allcards[:5],self.allcards[5:])
class Hand:
"""
This is for the players. Each player has a Hand and can add or remove cards from that hand.
So we will perform the add and remove operation here.
"""
def __init__(self,cards):
self.cards = cards
def __str__(self):
return "Contains {} cards".format(len(self.cards))
def add(self,added_cards):
self.cards.extend(added_cards)
def remove_card(self):
return self.cards.pop()
class Player:
"""
This class will has the name of the player.
It will also has the instance of Hand class object.
"""
def __init__(self,name,hand):
self.name = name
self.hand = hand
def play_card(self):
drawn_card = self.hand.remove_card()
print("{} has placed: {}".format(self.name,drawn_card))
print('\n')
return drawn_card
def still_has_cards(self):
"""
Returns True if player still has cards
"""
return len(self.hand.cards) != 0
print ("Let's start the game")
# Create New Deck and split in half
d = Deck()
d.shuffle()
half1,half2 = d.split_in_half()
# Create Both Players
name1 = input("What is your name player1? ")
user1 = Player(name1,Hand(half1))
name2 = input("What is your name player2? ")
user2 = Player(name2,Hand(half2))
# Set Counters
total_rounds = 0
User1_score = 0
User2_score = 0
Outdated = []
#Dice roll for the two players
user1_roll = random.randint(1,6)
user2_roll = random.randint(1,6)
#Dice roll winner will specify the characteristic choice : This applies only for the first round.
if user1_roll == user2_roll :
print ("Rolling the dice again")
user1_roll = random.randint(1,6)
user2_roll = random.randint(1,6)
if user1_roll > user2_roll :
print( user1.name + " will start ")
StartingPlayer = (user1)
else :
print( user2.name + " will start ")
StartingPlayer = (user2)
while user1.still_has_cards() and user2.still_has_cards():
total_rounds += 1
print("It is time for a new round!")
print("Here are the current standings: ")
print(user1.name+" card count: "+str(len(user1.hand.cards)))
print(user2.name+" card count: "+str(len(user2.hand.cards)))
print("Both players play a card!")
print('\n')
#Spells counter
Godspell_counter = [0,0]
Resurrectspell_counter = [0,0]
if total_rounds <= 1 :
if StartingPlayer == (user1) :
first_user = user1.play_card()
choice = input(user1.name + " what is your choice for characteristics of players?(Shoot, Passing, Speed) ")
second_user = user2.play_card()
if StartingPlayer == (user2) :
second_user = user2.play_card()
choice = input(user2.name + " what is your choice for characteristics of players?(Shoot, Passing, Speed) ")
first_user = user1.play_card()
if choice == 'Shoot' :
var1 = first_user['Shoot']
print("The card value of " + user1.name + " is " , var1)
if choice == 'Passing' :
var1 = first_user['Passing']
print("The card value of " + user1.name + " is " , var1)
if choice == 'Speed' :
var1 = first_user['Speed']
print("The card value of " + user1.name + " is " , var1)
if choice == 'Shoot' :
var2 = second_user['Shoot']
print("The card value of " + user2.name + " is " , var2)
if choice == 'Passing' :
var2 = second_user['Passing']
print("The card value of " + user2.name + " is " , var2)
if choice == 'Speed' :
var2 = second_user['Speed']
print("The card value of " + user2.name + " is " , var2)
#Points calculation
if var1 > var2 :
print( user1.name + " gets a point! ")
StartingPlayer = (user1)
User1_score = User1_score + 1
if var2 > var1 :
print( user2.name + " gets a point! " )
StartingPlayer = (user2)
User2_score = User2_score + 1
print('\n')
Outdated.append(first_user)
Outdated.append(second_user)
print(user1.name , " scored " , User1_score , " point! ")
print(user2.name , " scored " , User2_score , " point! ")
if Resurrectspell_counter[0] == 1 :
print(user1.name + " : You have already used Resurrectspell. You cannot use again in this round! ")
if Godspell_counter[0] == 1 :
print (user1.name + " : You have already used Resurrectspell. You cannot use again in this round!")
if Resurrectspell_counter[1] == 1 :
print(user2.name + " : You have already used Resurrectspell. You cannot use again in this round! ")
if Godspell_counter[1] == 1 :
print (user1.name + " : You have already used Resurrectspell. You cannot use again in this round!")
if total_rounds > 1 :
if StartingPlayer == (user1) :
spellchoice1 = input("Do you want to select any of Spells " + user1.name + " ? Y/N ")
if spellchoice1 == "Y" :
spellchoice_user1 = input ("Which spell do you want to use? (G, R) ")
if spellchoice_user1 == "R" :
Resurrectspell_counter[0] =+ 1
random.choice(Outdated)
user1.hand.cards[0] = random.choice(Outdated)
first_user = user1.play_card()
choice = input(user1.name + " what is your choice for characteristics of players?(Shoot, Passing, Speed) ")
second_user = user2.play_card()
if spellchoice_user1 == "G" :
Godspell_counter[0] =+ 1
n = input("Please mention the card number you want to choose from 0 to" + str({len(user2.hand.cards)-1}))
n = int(n)
user2.hand.cards[n]
user2.hand.cards[0] = (user2.hand.cards[n])
first_user = user1.play_card()
choice = input(user1.name + " what is your choice for characteristics of players?(Shoot, Passing, Speed) ")
second_user = user2.play_card()
else :
first_user = user1.play_card()
choice = input(user1.name + " what is your choice for characteristics of players?(Shoot, Passing, Speed) ")
second_user = user2.play_card()
if StartingPlayer == (user2) :
spellchoice2 = input("Do you want to select any of Spells " + user2.name + " ? Y/N ")
if spellchoice2 == "Y" :
spellchoice_user2 = input ("Which spell do you want to use? (G, R) ")
if spellchoice_user2 == "R" :
Resurrectspell_counter[1] =+ 1
random.choice(Outdated)
user2.hand.cards[0] = random.choice(Outdated)
second_user = user2.play_card()
choice = input(user1.name + " what is your choice for characteristics of players?(Shoot, Passing, Speed) ")
first_user = user1.play_card()
if spellchoice_user2 == "G" :
Godspell_counter[1] =+ 1
n = input("Please mention the card number you want to choose from 0 to" + str({len(user1.hand.cards)-1}))
n = int(n)
user1.hand.cards[n]
user1.hand.cards[0] = (user1.hand.cards[n])
second_user = user2.play_card()
choice = input(user2.name + " what is your choice for characteristics of players?(Shoot, Passing, Speed) ")
first_user = user1.play_card()
else :
first_user = user1.play_card()
choice = input(user1.name + " what is your choice for characteristics of players?(Shoot, Passing, Speed) ")
second_user = user2.play_card()
# Check to see who had higher rank
if choice == 'Shoot' :
var1 = first_user['Shoot']
print("The card value of " + user1.name + " is " , var1)
if choice == 'Passing' :
var1 = first_user['Passing']
print("The card value of " + user1.name + " is " , var1)
if choice == 'Speed' :
var1 = first_user['Speed']
print("The card value of " + user1.name + " is " , var1)
if choice == 'Shoot' :
var2 = second_user['Shoot']
print("The card value of " + user2.name + " is " , var2)
if choice == 'Passing' :
var2 = second_user['Passing']
print("The card value of " + user2.name + " is " , var2)
if choice == 'Speed' :
var2 = second_user['Speed']
print("The card value of " + user2.name + " is " , var2)
#Points calculation
if var1 > var2 :
print( user1.name + " gets a point! ")
StartingPlayer = (user1)
User1_score = User1_score + 1
if var2 > var1 :
print( user2.name + " gets a point! " )
StartingPlayer = (user2)
User2_score = User2_score + 1
print('\n')
Outdated.append(first_user)
Outdated.append(second_user)
print(user1.name , " scored " , User1_score , " point! ")
print(user2.name , " scored " , User2_score , " point! ")
if User1_score > User2_score :
print( user1.name + " is the winner! ")
else :
print( user2.name + " is the winner! ") |
class Padlock(object):
def __init_(self, combination):
self.combination = combination
self.isOpen = False
def open(self, combination_entered):
if self.isOpen:
print("The lock is alread open")
else:
if self.combination != combination_entered:
print("You entered the wrong combination")
else:
print("You opened the lock")
self.isOpen = True
def close(self):
if self.isOpen:
print("The lock is now closed")
self.isOpen = False
else:
print("The lock is closed")
def change_combination(self, newcombination):
self.combination = newcombination
|
import datetime
class LecturerDirectory:
def __init__(self, name, tele_Num, office_Num, subject, start_Year):
self.name = name
self.tele = tele_Num
self.office = office_Num
self.subject = subject
self.start_Y = start_Year
def change_Name(self, newName):
if newName == self.name:
print("No change")
else:
self.fName = newName
def change_Tele(self, newTele):
self.tele = newTele
def change_Office(self, newOffice):
self.office = newOffice
def change_Subject(self, newSub):
self.subject = newSub
def duration(self):
date = datetime.date
duration = date.today() - self.start_Y
return duration
def dis_Info(self):
print(self.name, self.tele, self.office, self.subject) |
import graphics as g
import math
def areaOfCircle(radius):
return math.pi * (radius ** 2)
def circumferenceOfCircle(radius):
return 2 * math.pi * radius
def areaOfCircle(radius):
return math.pi * radius ** 2
def circleInfo():
radius = float(input("Enter for radis: "))
print("Area: ", areaOfCircle(radius), "\n"
"Circumference: ", circumferenceOfCircle(radius))
def drawCircle(window, centre, radius, colour):
circle = g.Circle(centre, radius)
circle.setFill(colour)
circle.setWidth(2)
circle.draw(window)
def drawStars(height, width):
for i in range(height):
print("*" * width)
def drawLetter_E():
drawStars(8, 3)
drawStars(2, 3)
drawStars(6, 3)
drawStars(2, 3)
drawStars(8, 3)
def drawBrownEye(window, centre, radius):
drawBrownEye(window, g.Point(centre, 100), radius, "White")
drawBrownEye(window, g.Point(centre, 100), radius / 2, "Brown")
drawBrownEye(window, g.Point(centre, 100), radius / 4, "Black")
def drawBrownEye_NoPoint(window, centre, radius):
drawBrownEye(window, centre, radius, "White")
drawBrownEye(window, centre, radius / 2, "Brown")
drawBrownEye(window, centre, radius / 4, "Black")
def drawBrownEyes_Pair(window, centre, radius):
window = g.GraphWin()
drawBrownEye(window, g.Point(90, 100))
drawBrownEye(window, g.Point(100, 120))
window.getMouse()
def distBetweenPoints(a, b):
return math.sqrt((b.getX() - a.getX()) ** 2 + (b.getY() - a.getY()) ** 2)
def drawStars_Gap(gap_One, star_One, gap_Two, star_Two, row):
for i in range(row):
print(" " * gap_One, end= "")
print("*" * star_One, end="")
print(" " * gap_Two, end="")
print("*" * star_Two, end="")
def drawLetter_A():
drawStars_Gap(1, 8, 0, 0, 2)
drawStars_Gap(0, 2, 6, 2, 2)
drawStars_Gap(0, 10, 0, 0, 2)
drawStars_Gap(0, 2, 6, 2, 3)
def drawBrownEyes_Two_Pairs():
window = g.GraphWin("4 Eyes", 1000, 1000)
for i in range(4):
coord_Left = window.getMouse()
coord_Right = coord_Left.getX() + radius
radius = distBetweenPoints(coord_Left, window.getMouse())
drawBrownEye_NoPoint(window, coord_Left, radius)
drawBrownEye_NoPoint(window, g.Point(coord_Left.getY(), coord_Right),
radius)
window.getMouse()
def displayTextWithSpaces(window, text, size, pos):
text = text.replace("", " ")
text_Display = g.Text(pos, text).draw(window).setSize(size)
def constructVisionChart():
window = g.GraphWin("Chart", 400, 400)
font_Sizes = [30, 25, 20, 15, 10, 5]
dx = 100
dy = 50
for size in font_Sizes:
usr_In = g.Entry(g.Point(40, 40), 10).draw(window)
window.getMouse()
displayTextWithSpaces(window, usr_In.getText(), size,
g.Point(dx, dy))
dx -= 10
dy += 30
window.getMouse()
def drawStickFigure(window, size, pos):
coord_X = pos.getX()
coord_Y = pos.getY()
head = g.Circle(g.Point(100, 60), 20).draw(window)
body = g.Line(g.Point(100, 80), g.Point(100, 120)).draw(window)
left_Arm = g.Line(g.Point(80, 80), g.Point(100, 90)).draw(window)
right_Arm = g.Line(g.Point(120, 80), g.Point(100, 90)).draw(window)
left_Leg = g.Line(g.Point(100, 120), g.Point(80, 140)).draw(window)
right_Leg = g.Line(g.Point(100, 120), g.Point(120, 140)).draw(window)
window.getMouse()
def drawStickFigure_Family():
window = g.GraphWin("It da Peeeps", 400, 400)
drawStickFigure(window, 40, g.Point(100, 100)) |
from Polygon import Polygon
import math
class Rectangle(Polygon):
def __init__(self, height, width):
Polygon.__init__(self, [height, width, height, width])
def calculateRectangleArea(self):
a = self.sides[0]
b = self.sides[1]
return a * b
def calculateDiagonalLength(self):
a = self.sides[0]
b = self.sides[1]
return math.sqrt((a**2) + (b**2))
def printRectangleInformation(self):
print("Rectangle Information")
sideString = "Sides: "
for i in self.sides:
sideString += str(i)
sideString += " "
print(sideString)
print("Diagonal Length: ", self.calculateDiagonalLength())
print("Area: ", self.calculateRectangleArea())
print("Perimeter: ", self.calculatePerimeter()) |
def sayName():
print("Will")
def sayHelloWorld():
print("Hello...")
print("... World!")
def euros2pounds():
euro = float(input("Please enter value: "))
print("Converted = £", euro * 1.09)
def addNum():
num1 = int(input("Enter Num1: "))
num2 = int(input("Enter Num2: "))
sum = num1 + num2
print(sum)
def changeCounter():
one_p = 0.01
two_p = 0.02
five_p = 0.05
one_p_v = int(input("Enter amount of 1p coins:"))
two_p_v = int(input("Enter amount of 2p coins:"))
five_p_v = int(input("Enter amount of 5 couns:"))
print("You have: ", one_p_v * one_p, " in 1ps\n "
"You have: ", two_p_v * two_p, " in 2ps\n "
"You have: ", five_p_v * five_p, " in 2ps")
def hhhhhhhhhh():
for x in range(0, 10):
print("Hello World!")
def weightsTable():
print("KG - LBS")
for kg in range(0+10, 110, 10):
for lb in range(1):
print(kg, " ", kg * 2.2)
def futureValue():
value = int(input("Enter investment: "))
year = int(input("Enter duration: "))
print("Compound interest value: ", value * (5.5 ** year))
sayName()
sayHelloWorld()
euros2pounds()
addNum()
changeCounter()
hhhhhhhhhh()
weightsTable()
futureValue() |
kilos = eval(input("Enter a weight in kilograms: "))
pounds = 2.2 * kilos
print("The weight in pounds is", pounds)
|
from Polygon import Polygon
import math
class Hexagon(Polygon):
def __init__(self, side):
Polygon.__init__(self, [side] * 6)
def calculateHexagonArea(self):
a = self.sides[0]
area = ((3 * math.sqrt(3))/2)* (a**2)
return area
def calculateLongDiagonalLength(self):
a = self.sides[0]
return 2 * a
def printHexagonInformation(self):
print("Hexagon Information")
sideString = "Sides: "
for i in self.sides:
sideString += str(i)
sideString += " "
print(sideString)
print("Long Diagonal Length: ", self.calculateLongDiagonalLength())
print("Area: ", self.calculateHexagonArea())
print("Perimeter: ", self.calculatePerimeter()) |
from nltk.tokenize import sent_tokenize
def lines(a, b):
"""Return lines in both a and b"""
#take in string inputs a, b, split each string into lines, compute a list of all lines that appear in both a and b
lines_a = set(a.split('\n'))
lines_b = set(b.split('\n'))
#return the list
return lines_a & lines_b
def sentences(a, b):
"""Return sentences in both a and b"""
sentences_a = set(sent_tokenize(a))
sentences_b = set(sent_tokenize(b))
return sentences_a & sentences_b
def substrings(a, b, n):
"""Return substrings of length n in both a and b"""
substrings_a = []
substrings_b = []
for i in range (len(a)-n +1):
substrings_a.append(a[i: i+n])
for j in range (len(b)-n+1):
substrings_b.append(b[j: j+n])
#s[i:j] - return substrings of s from index i to (but not including) j
return (set(substrings_a) & set(substrings_b))
|
# Import libraries necessary for this project
import numpy as np
import pandas as pd
from IPython.display import display # Allows the use of display() for DataFrames
# Set a random seed
import random
random.seed(42)
# Load the dataset
in_file = 'titanic_data.csv'
# Store the 'Survived' feature in a new variable and remove it from the dataset
outcomes = full_data['Survived']
features_raw = full_data.drop('Survived', axis = 1)
#preprocess the data
features = pd.get_dummies(features_raw)
features = features.fillna(0.0)
display(features.head
#splitting the dataset
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(features, outcomes, test_size=0.2, random_state=42)
#Train the model
new_model= DecisionTreeClassifier(max_depth=,min_samples_leaf=5)
new_model.fit(X_train,y_train)
#Make predictions
ytrainpred = new_model.predict(X_train)
ytestpred = new_model.predict(X_test)
#Calculate the accuracy
from sklearn .metrics import accuracy_score
trainaccuracy = accuracy_score(y_train, ytrainpred)
testaccuracy = accuracy_score(y_test, ytestpred)
print('training accuracy',trainaccuracy)
print('testing accuracy', testaccuracy)
|
import tkinter as tk
from tkinter import ttk
class Aplicacion:
def __init__(self):
self.ventana1=tk.Tk()
self.label1=ttk.Label(text="Ingrese nombre")
self.label1.grid(column=0, row=0)
self.nombre=tk.StringVar()
self.entry1=ttk.Entry(self.ventana1, width=40, textvariable=self.nombre)
self.entry1.grid(column=0, row=1)
self.label2=ttk.Label(text="Seleccione país")
self.label2.grid(column=0, row=2)
self.pais=tk.StringVar()
paises=("Argentina","Chile","Bolivia","Paraguay","Brasil","Uruguay","México")
self.combobox1=ttk.Combobox(self.ventana1,
width=10,
textvariable=self.pais,
values=paises,
state='readonly')
#self.combobox1.current(0)
self.combobox1.grid(column=0, row=3)
self.boton1=ttk.Button(self.ventana1, text="Recuperar", command=self.mostrardatos)
self.boton1.grid(column=0, row=4)
self.ventana1.mainloop()
def mostrardatos(self):
self.ventana1.title("Nombre:"+self.nombre.get()+" Pais:"+self.combobox1.get())
aplicacion1=Aplicacion() |
import sys
if sys.version_info.major == 2:
nombre1=raw_input("Ingrese el primer nombre:")
nombre2=raw_input("Ingrese el segundo nombre:")
else:
if sys.version_info.major == 3:
nombre1=input("Ingrese el primer nombre:")
nombre2=input("Ingrese el segundo nombre:")
print("Listado alfabetico:")
if nombre1<nombre2:
print(nombre1)
print(nombre2)
else:
print(nombre2)
print(nombre1) |
while True:
try:
valor1=int(input("Ingrese primer valor:"))
valor2=int(input("Ingrese segundo valor:"))
suma=valor1+valor2
print("La suma es",suma)
except ValueError:
print("debe ingresar números.")
respuesta=input("Desea ingresar otro par de valores?[s/n]")
if respuesta=="n":
break |
numero=int(input("Ingrese un numero positivo de 1 o 2 digitos:"))
if numero > 9:
print('el numero tiene dos digitos')
else:
print('el numero tiene un digito')
|
def cargar():
empleados={}
continua="s"
while continua=="s":
legajo=int(input("Ingrese el numero de legajo:"))
nombre=input("Ingrese el nombre del empleado:")
profesion=input("Ingrese el nombre de la profesion:")
sueldo=float(input("Ingrese el sueldo:"))
empleados[legajo]=[nombre,profesion,sueldo]
continua=input("Ingresa los datos de otro empleado[s/n]:")
return empleados
def imprimir(empleados):
print("Listado completo de empleados")
for legajo in empleados:
print(legajo,empleados[legajo][0],empleados[legajo][1],empleados[legajo][2])
def modificar_sueldo(empleados):
legajo=int(input("Ingrese el numero de legajo para buscar empleado:"))
if legajo in empleados:
sueldo=float(input("Ingrese nuevo sueldo:"))
empleados[legajo][2]=sueldo
else:
print("No existe un empleado con dicho numero de legajo")
def imprimir_analistas(empleados):
print("Listado de empleados con profesion \"analista de sistemas\"")
for legajo in empleados:
if empleados[legajo][1]=="analista de sistemas":
print(legajo,empleados[legajo][0],empleados[legajo][2])
# bloque principal
empleados=cargar()
imprimir(empleados)
modificar_sueldo(empleados)
imprimir(empleados)
imprimir_analistas(empleados)
|
lista=[]
for x in range(5):
valor=int(input("Ingrese valor:"))
lista.append(valor)
menor=lista[0]
posicion=0
for x in range(1,5):
if lista[x]<menor:
menor=lista[x]
posicion=x
print("Lista completa")
print(lista)
print("Menor de la lista")
print(menor)
print("Posicion del menor en la lista")
print(posicion) |
class Lista:
def __init__(self, lista):
self.lista=lista
def imprimir(self):
print(self.lista)
def __add__(self,entero):
nueva=[]
for x in range(len(self.lista)):
nueva.append(self.lista[x]+entero)
return nueva
def __sub__(self,entero):
nueva=[]
for x in range(len(self.lista)):
nueva.append(self.lista[x]-entero)
return nueva
def __mul__(self,entero):
nueva=[]
for x in range(len(self.lista)):
nueva.append(self.lista[x]*entero)
return nueva
def __floordiv__(self,entero):
nueva=[]
for x in range(len(self.lista)):
nueva.append(self.lista[x]//entero)
return nueva
# bloque principal
lista1=Lista([3,4,5])
lista1.imprimir()
print(lista1+10)
print(lista1-10)
print(lista1*10)
print(lista1//10)
|
numero1 = int(input('Ingresar primer numero:'))
numero2 = int(input('Ingresar segundo numero:'))
numero3 = int(input('Ingresar tercer numero:'))
numero4 = int(input('Ingresar cuarto numero:'))
suma = numero1+numero2
producto = numero3*numero4
print('la suma del primero con el segundo es:')
print(suma)
print('el producto del tercero y el cuarto es:')
print(producto) |
from urllib import request
import json
codigo=input("Ingrese el código de artículo a consultar:")
pagina=request.urlopen(f"http://localhost/pythonya/retornarunarticulo.php?codigo={codigo}")
datos=pagina.read().decode("utf-8")
lista=json.loads(datos)
if len(lista)>0:
print(f"Descripción:{lista[0]['descripcion']}")
print(f"Precio:{lista[0]['precio']}")
else:
print("No existe un artículo con el código ingresado") |
def cargar():
alumnos={}
for x in range(3):
dni=int(input("Ingrese el numero de dni:"))
listamaterias=[]
continua="s"
while continua=="s":
materia=input("Ingrese el nombre de materia que cursa:")
nota=int(input("Ingrese la nota:"))
listamaterias.append((materia,nota))
continua=input("Desea cargar otra materia para dicho alumno [s/n}:")
alumnos[dni]=listamaterias
return alumnos
def listar(alumnos):
for dni in alumnos:
print("Dni del alumno",dni)
print("Materias que cursa y notas.")
for nota,materia in alumnos[dni]:
print(materia,nota)
def consulta_notas(alumnos):
dni=int(input("Ingrese el dni a consultar:"))
if dni in alumnos:
for nota,materia in alumnos[dni]:
print(materia,nota)
# bloque principal
alumnos=cargar()
listar(alumnos)
consulta_notas(alumnos)
|
lado=input("Ingrese la medida del lado del cuadrado:")
lado=int(lado)
superficie=lado*lado
print("La superficie del cuadrado es")
print(superficie) |
sueldo=int(input("Ingrese sueldo:"))
antiguedad=int(input("Ingrese antiguedad:"))
print("Sueldo a pagar")
if sueldo<500 and antiguedad>=10:
sueldoapagar = sueldo * 1.20
else:
if sueldo<500:
sueldoapagar = sueldo * 1.05
else:
sueldoapagar=sueldo
print(sueldoapagar) |
class Socio:
def __init__(self):
self.nombre=input("Ingrese el nombre del socio:")
self.antiguedad=int(input("Ingrese la antiguedad:"))
def imprimir(self):
print(self.nombre,"tiene una antiguedad de",self.antiguedad)
def retornar_antiguedad(self):
return self.antiguedad
class Club:
def __init__(self):
self.socio1=Socio()
self.socio2=Socio()
self.socio3=Socio()
def mayor_antiguedad(self):
print("Socio con mayor antiguedad")
if (self.socio1.retornar_antiguedad()>self.socio2.retornar_antiguedad() and
self.socio1.retornar_antiguedad()>self.socio3.retornar_antiguedad()):
self.socio1.imprimir()
else:
if self.socio2.retornar_antiguedad()>self.socio3.retornar_antiguedad():
self.socio2.imprimir()
else:
self.socio3.imprimir()
# bloque principal
club=Club()
club.mayor_antiguedad()
|
lista1=[0,1,2,3,4,5,6]
print(lista1)
print(lista1[-1]) # 6
print(lista1[-2]) # 5
|
def menor_valor():
valor1=int(input("Ingrese primer valor:"))
valor2=int(input("Ingrese segundo valor:"))
valor3=int(input("Ingrese tercer valor:"))
print("Menor de los tres")
if valor1<valor2 and valor1<valor3:
print(valor1)
else:
if valor2<valor3:
print(valor2)
else:
print(valor3)
# bloque principal
menor_valor()
menor_valor() |
num1=int(input("Ingrese primer valor:"))
num2=int(input("ingrese segundo valor:"))
print("El valor mayor es")
if num1>num2:
print(num1)
else:
print(num2) |
def cargar_empleados():
empleados=[]
for x in range(5):
nom=raw_input("Ingresar el nombre del Empleado: ")
sue1=int(input("Ingrese Sueldo 1: "))
sue2=int(input("Ingrese Sueldo 2: "))
sue3=int(input("Ingrese Sueldo 3: "))
empleados.append([nom,(sue1,sue2,sue3)])
return empleados
def imprimir(empleados):
print("Empleados y su sueldo")
for x in range(len(empleados)):
sueldo=empleados[x][1][0]+empleados[x][1][1]+empleados[x][1][2]
print(empleados[x][0],sueldo)
def ingreso_mayor(empleados):
print('Empleados con sueldo mayor a 10000')
for x in range(len(empleados)):
suma = empleados[x][1][0]+empleados[x][1][1]+empleados[x][1][2]
if suma>10000:
print(empleados[x][0],suma)
# bloque principal
empleados=cargar_empleados()
imprimir(empleados)
ingreso_mayor(empleados) |
meses=("enero","febrero","marzo","abril","mayo","junio",
"julio","agosto","septiembre","octubre","noviembre","diciembre")
try:
nromes=int(input("Ingrese un número de mes [1-12]:"))
print(meses[nromes-1])
except IndexError:
print("En número de mes debe ir entre 1 y 12") |
largo = 0
clave = raw_input('Ingrese la clave: ')
largo = len(clave)
if largo < 10 and largo > 20:
print('Error: numero de caracteres no valido.')
else:
print('Correcto.') |
"""
Mostrar la tabla de 5 con las estructuras repetitivas:
while
y
for
"""
#utilizando el while
print("Tabla del 5 empleando el while")
x=5
while x<=50:
print(x)
x=x+5
#utilizando el for
print("Tabla del 5 empleando el for")
for x in range(5,51,5):
print(x) |
def cargar():
lista=[]
for x in range(5):
num=int(input("Ingrese un valor:"))
lista.append(num)
return lista
def imprimir(lista):
print("Lista completa")
for elemento in lista:
print(elemento)
def mayor(lista):
may=lista[0]
for elemento in lista:
if elemento>may:
may=elemento
print("El elemento mayor de la lista es",may)
def sumar_elementos(lista):
suma=0
for elemento in lista:
suma=suma+elemento
print("La suma de todos sus elementos es",suma)
# bloque principal
lista=cargar()
imprimir(lista)
mayor(lista)
sumar_elementos(lista) |
import tkinter as tk
class Aplicacion:
def __init__(self):
self.valor=1
self.ventana1=tk.Tk()
self.ventana1.title("Controles Button y Label")
self.label1=tk.Label(self.ventana1, text=self.valor)
self.label1.grid(column=0, row=0)
self.label1.configure(foreground="red")
self.boton1=tk.Button(self.ventana1, text="Incrementar", command=self.incrementar)
self.boton1.grid(column=0, row=1)
self.boton2=tk.Button(self.ventana1, text="Decrementar", command=self.decrementar)
self.boton2.grid(column=0, row=2)
self.ventana1.mainloop()
def incrementar(self):
self.valor=self.valor+1
self.label1.config(text=self.valor)
def decrementar(self):
self.valor=self.valor-1
self.label1.config(text=self.valor)
aplicacion1=Aplicacion() |
paises=[]
for x in range(5):
valor=raw_input("Ingrese pais:")
paises.append(valor)
print("Lista sin ordenar")
print(paises)
for k in range(4):
for x in range(4-k):
if paises[x]>paises[x+1]:
aux=paises[x]
paises[x]=paises[x+1]
paises[x+1]=aux
print("Lista ordenada")
print(paises) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.