text
stringlengths 37
1.41M
|
---|
'''
PROBLEM SHERLOCK AND ANAGRAMS
Two strings are anagrams of each other if the letters of one string can be
rearranged to form the other string. Given a string, find the number of
pairs of substrings of the string that are anagrams of each other.
'''
'''
Approach is that,
First create a dictionary for each sequence consisting of number of letters of
a specific type it have.
Then check seq by seq whether they consist of same dictionary or not.
'''
import math
import os
import random
import re
import sys
import time
# Complete the sherlockAndAnagrams function below.
def sherlockAndAnagrams(s):
count = 0
# Looping over all sequences size
for i in range(1,len(s)+1):
sequences = []
# storing the sequencees of size i in a list called SEQUENCES
for k in range(len(s)-i+1):
sequences.append(s[k:k+i])
seq_dict = {}
# Dictionary development
for seq in sequences:
seq_dict[seq] = {}
if(seq[0] in list(seq_dict[seq].keys())):
continue
for letter in seq:
if letter not in list((seq_dict[seq]).keys()):
seq_dict[seq][letter] = 1
else:
seq_dict[seq][letter] += 1
# Checking over sequences of similar length for ANAGRAMS
for i in range(len(sequences)):
for j in range(i+1,len(sequences)):
k = 0
temp1 = set(list(sequences[i]))
for letter in temp1:
if(letter not in list((seq_dict[sequences[j]]).keys())):
break
else:
if(seq_dict[sequences[i]][letter] == seq_dict[sequences[j]][letter]):
k = k+1
else:
break
if(k == len(temp1)):
count += 1
return(int(count))
# APPROACH 2 (SIMPLE ARRAY TRAVERSAL)
#print(sequences)
# for seq1 in sequences:
# for seq2 in sequences:
# temp1 = list(seq1)
# temp2 = list(seq2)
# for letter in temp1:
# if(letter in temp2):
# temp2.remove(letter)
# else:
# break
# if(len(temp2)==0):
# count += 1
# count -= len(sequences)
# return(int(count/2))
# CALLING function
q = int(input("ENTER THE NUMBER OF SEQUENCES \n"))
for q_itr in range(q):
s = input("ENTER THE SEQUENCE \n")
result = sherlockAndAnagrams(s)
print(result, '\n')
|
'''
PROBLEM: LUCK BALANCE PROBLEM
Lena is preparing for an important coding competition that is preceded by a
number of sequential preliminary contests. She believes in "saving luck", and
wants to check her theory. Each contest is described by two integers, L[i] and T[i] :
L[i]: The amount of luck associated with a contest.
If Lena wins the contest, her luck balance will decrease by ; if she loses it,
her luck balance will increase by L[i].
T[i]: denotes the contest's importance rating. It's equal to 1 if the contest is important,
and it's equal to 0 if it's unimportant.
If Lena loses no more than k important contests, what is the maximum amount of
luck she can have after competing in all the preliminary contests? This value
may be negative.
'''
import math
import os
import random
import re
import sys
from functools import cmp_to_key
def luck(contest):
return(contest[0])
# Complete the luckBalance function below.
def luckBalance(k, contests):
data = sorted(contests, key = luck, reverse = True)
print(data)
luck_score = 0
lost = 0
for i in (data):
if i[1] == 0:
luck_score += i[0]
elif i[1] == 1 and lost < k:
luck_score += i[0]
lost += 1
else:
luck_score -= i[0]
return(luck_score)
# FUNCTION CALLING
nk = input("ENTER THE VALUES OF n AND k separated by spaces \n").split(" ")
n = nk[0]
k = nk[1]
for _ in range(n):
contests.append(list(map(int,input("Enter the luck and importance").rstrip().split())))
result = luckBalance(k, contests)
print("RESULT:", result, "\n")
|
'''
PROBLEM ALTERNATING_CHARACTER
You are given a string containing characters and only. Your task is to change
it into a string such that there are no matching adjacent characters. To do this,
you are allowed to delete zero or more characters in the string.
Your task is to find the minimum number of required deletions.
'''
import math
import os
import random
import re
import sys
# Complete the alternatingCharacters function below.
def alternatingCharacters(s):
t = 0
delete = 0
prev_char = None
for i,char in enumerate(s):
if i < len(s):
#print(char)
if char == prev_char:
t += 1
#print(t)
else:
if t>0:
delete += t
t = 0
prev_char = char
delete += t
return(delete)
## FUNCTION CALLING
s = input("Enter the string\n")
result = alternatingCharacters(s)
print(s)
|
import pygame
class Obstacle:
def __init__(self, screen, camera, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.screen = screen
self.camera = camera
def draw(self):
pygame.draw.rect(
self.screen,
(255, 200, 255),
(
self.x - self.camera.x,
self.y - self.camera.y,
self.width,
self.height
),
3
)
|
for _ in range(int(input())):
n = int(input())
i = 1
if(n==0):
print('1')
elif(n==1 or n== 2):
print('2')
else:
while(2**i <=n):
i+=1
tmp = 2**(i-1)
if(tmp == n):
print(n)
elif((tmp*2 -1) == n):
print(n+1)
else:
print(tmp)
|
# Let's edit the script
def sayHello(people_name):
print("hello " + people_name)
print("How are you doing ? ")
answer = str(input(">>> "))
if answer == "I'm fine" or answer == "Fine" or answer == "Good":
print("So you have a nice day!")
elif answer == "I am not good":
print("Oh come on make a smile !")
else:
pass
|
class Compagnie(object):
argent = 0
employes = 0
matiere = 0
mois = 1
def __init__(self, argent, employes, matiere, mois):
self.argent = argent
self.employes = employes
self.matiere = matiere
self.mois = mois
def achat(self, fournisseur, volume):
while volume > fournisseur.vol_max:
print("Volume demandé trop grand, veuillez commander maximum " + str(fournisseur.vol_max))
volume = int(input("Quel volume souhaitez-vous commander?: "))
print("Achat de " + str(volume) + "PPM au " + str(self.mois) + "em mois")
prix_unitaire = fournisseur.get_price(volume, self.mois)
print("Prix unitaire de " + str(prix_unitaire) + "$")
print("Fraix fixes de " + str(fournisseur.initial_cost) + "$")
print("Dépense de " + str(prix_unitaire*volume + fournisseur.initial_cost) + "$")
self.argent -= prix_unitaire*volume + fournisseur.initial_cost
self.matiere += volume
|
# Boxplot to find outliers
import matplotlib.pyplot as plt
import numpy as np
col1 = np.array([-5, 4, 5, 3, 2.3, 4.1, 5.4, -6, 3.6, 5.6, 12, 4.3, 4, 2, 5.1, 10])
col2 = np.array([-5, 4, 5, 13, 12.3, 14.1, 15.4, -6, 13.6, 15.6, 12, 14.3, 14, 12, 15.1, 30])
age = np.array([22, 21, 23, 25, 25, 21, -5, 33, 32, 70, 21, -1, 22, 23, 24])
data = [col1, col2, age]
fig = plt.figure()
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ax.boxplot(data) # red line in boxplot is 'mean' of data
plt.show()
|
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
y = x**2
y2 = x**3
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.1, 0.4, 0.4])
ax2 = fig.add_axes([0.5, 0.5, 0.4, 0.4])
ax1.set_title('SQUARE CURVE')
ax1.set_xlabel('Number')
ax1.set_ylabel('Square')
ax2.set_title('CUBE CURVE')
ax2.set_xlabel('Number')
ax2.set_ylabel('Cube')
ax1.plot(x, y)
ax2.plot(x, y2)
plt.show()
|
import pandas as pd
import numpy as np
student_data = {'Name': ['Suraj', 'Uttam', 'Anish', 'Rohit', 'Lalit', 'Shivam', 'Srikant', 'Aryan'],
'Roll': [101, 102, 103, 104, 105, 106, 107, 108],
'Marks': [56.5, 62.5, 68.8, 63.3, 65.5, 78.9, 80.9, 68.7],
'Age': [30, 31, 34, 28, 19, 28, 31, 20],
'Passing_Year': [2015, 2014, 2016, 2014, 2018, 2017, 2017, 2015],
'Branch': ['CS', 'IT', 'IT', 'IT', 'CS', 'CS', 'IT', 'CS']
}
df = pd.DataFrame(student_data)
df.to_csv("Student.csv")
df.to_csv('Student2.csv', index=None)
print("Data Converted in csv sucessfully!")
|
# WAP to check a given is odd or even
num = eval(input("Enter a number: ")) # eval() can store int or float both as an input
if(num%2 == 0):
print(num, "is even number.")
else:
print(num,"is odd number.")
|
'''
working on 'Series' one of Data Structure of pandas
'Series' is used for 1D data
'''
import pandas as pd
import numpy as np
print(pd.__version__)
arr1 = np.array([1, 2, 3, 4,5])
x1 = pd.Series(arr1) # 'S' is capital of Series data structure of pandas
print(x1)
arr2 = np.array([1, 2, 3.5, 5, 4, 5]) # if one element is in float then it print all data in flotting
x2 = pd.Series(arr2)
print(x2)
arr3 = np.array(['Anish', 'Rohit', 'Uttam', 'Lalit', 'Vivek'])
x3 = pd.Series(arr3)
print(x3)
arr4 = np.array(['Anish', 'Rohit', 'Uttam', 'Lalit', 'Vivek'])
x4 = pd.Series(arr3, index=np.arange(100, 105)) # modify index of data
print(x4)
arr5 = np.array(['Anish', 'Rohit', 'Uttam', 'Lalit', 'Vivek'])
x5 = pd.Series(arr3, index=np.array(['rank1', 'rank2', 'rank3', 'rank4', 'rank5'])) # modify index of data
print(x5)
dict = {1001: 'Rohit', 1002: 'Uttam', 1003: 'Anish', 1004: 'Lalit'}
x6 = pd.Series(dict)
print(x6)
x8 = pd.Series(50, index=['a', 'b', 'c'])
print(x8)
x7 = pd.Series([100, 200, 300, 400, 500], index=['a', 'b', 'c', 'd', 'e'])
print(x7)
print('x7[0]: ', x7[0])
print('x7[ :3] :', x7[:3])
print('x7[-3: ] :\n', x7[-3:])
print(x7['b'])
print(x7.mean())
print(x7.max())
print(x7.min())
print(x7.median())
|
import numpy as np
a = np.array([[1, 2, 3],[5, 6, 7], [10, 11, 12]])
print(a)
print(a.flatten()) # it covert in 1D array
print(a.flatten(order='F')) # it prints matrix in column bias
# order = c (print array in row bias by default)
# order = f (print array in column bias not by default)
print (a)
y = np.ravel(a)
print(y)
x1 = np.ravel(a, order='F') # flatten or ravel are same only syntax are differ
print(x1)
x = np.arange(8)
print(x)
x1 = x.reshape((2, 4))
print(x1)
x1 = x.reshape((2, 4), order='F')
print(x1)
x1 = x.reshape((4, 2))
print(x1)
x1 = x.reshape((2, 2, 2)) # 3D matrix (2 matrix of 2x2)
print(x1)
|
# tuple = it is immutable can't modify tuple
x = ()
print(type(x))
y = tuple()
print(type(y))
x = (1, 2, 3)
print(x, type(x))
'''
print(x[0])
x[0]= 5
print(x)
'''
y = (1, 2, 4.5, 'iit', 'kanpur')
print(y)
x = ("patna")
print(x, type(x))
x = ("patna",)
print(x, type(x))
x = (1,2,3,5,1,3,1,5,1,7)
print(x.count(1))
print(x.index(3))
|
print(help('for'))
print("-"*50) # line breaker for printing ------------ 50 times
print() # for one line space
a= [1,2,3,4,5]
for i in a:
print(i)
print("-"*50)
print()
b = ["Patna", "Noida", "Delhi", "Varanashi", "Kanpur"]
for i in b:
print(i)
print("-"*50)
print()
for x in "Delhi":
print(x)
|
crr=[]
def read():
with open("test.txt") as f:
# f.readline()
for line in f:
line=line.strip()
data=line.split(" ")
brr=split(data)
print(brr)
for index in range(len(brr)):
if data[10] == brr[index]:
print(index)
# brr.append(line[:4])
# print(data[2])
# print(add0)
# for x in range(len(data)):
# arr.append((data[x]))
#
# print(arr)
def split(arr):
if len(arr)==1:
return arr
else:
left=arr[:len(arr)//2]
right=arr[len(arr)//2:]
return mergeSort(split(left),split(right))
def mergeSort(left,right):
indexLeft=0
indexRight=0
arr=[]
while(indexLeft<len(left) and indexRight<len(right)):
if left[indexLeft]<right[indexRight]:
arr.append(left[indexLeft])
indexLeft+=1
elif right[indexRight]<left[indexLeft]:
arr.append(right[indexRight])
indexRight+=1
if indexLeft<len(left):
arr.extend(left[indexLeft:])
elif indexRight<len(right):
arr.extend(right[indexRight:])
return arr
def main():
read()
if __name__ == "__main__":
main()
|
# A simple mathematical function on which to try different testing frameworks
def square_plus_10(x):
"""
Doctest Example (Including one designed to fail)
>>> square_plus_10(2)
14
>>> square_plus_10(-2)
14
>>> square_plus_10(7)
A very surprised sperm whale
"""
return (x * x) + 10
def main():
print("This main function doesn\'t do anything")
if __name__ == "__main__":
main()
|
from Iterator import Iterator
class BookShelfIterator(Iterator):
def __init__(self, bookshelf):
self.index = 0
self.bookShelf = bookshelf
def hasNext(self):
if self.index < self.bookShelf.get_length():
return True
else:
return False
def next(self):
book = self.bookShelf.get_book_at(self.index)
self.index += 1
return book
|
import unittest
class Solution:
def isPerfectSquare(self, num: int) -> bool:
if (num**(1/2)).is_integer():
return True
else:
return False
def isPerfectSquareMethod2(self, num: int) -> bool:
if num < 2:
return True
left = 2
right = num // 2
while (left <= right):
mid = (left + right) // 2
if mid * mid == num:
return True
elif mid * mid < num:
left = mid + 1
elif mid * mid > num:
right = mid - 1
return False
class Test(unittest.TestCase):
t0=[
(16,True),
(14,False)
]
s=Solution()
def test0(self):
for testcase in self.t0:
input, expected = testcase[0],testcase[1]
result = self.s.isPerfectSquare(input)
result2 = self.s.isPerfectSquareMethod2(input)
self.assertEqual(result,expected)
self.assertEqual(result2, expected)
if __name__=="__main__":
unittest.main()
|
#Author: Brandon Fook Chong
#Student ID: 260989601
def get_iso_codes_by_continent(filename):
'''
(str) -> dict
Using a file containing the ISO codes of countries and their respective continents,
this function returns a dictionary with keys as the continents and associated to them
a list of ISO codes each representing a country that belongs that to continent
>>> d = get_iso_codes_by_continent("iso_codes_by_continent.tsv")
>>> d['ASIA'][34]
'KWT'
>>> d['ASIA'][35]
'MYS'
>>> len(d['EUROPE'])
48
>>> d['EUROPE'][22]
'SWE'
>>> d = get_iso_codes_by_continent("small_iso_codes_by_continent.tsv")
>>> len(d['EUROPE'])
9
>>> d['ASIA'][4]
'MDV'
>>> d = get_iso_codes_by_continent("even_smaller_iso_codes_by_continent.tsv")
>>> len(d['EUROPE'])
2
>>> d['ASIA'][2]
'LAO'
'''
#dict where we will store our countries mapped to ISO codes
new_dict = {}
#open to file in read mode to extract our countries and their codes
fobj = open(filename, "r", encoding="utf-8")
#list where we will store the ISO codes for each continent
Asia = []
South_America = []
Africa = []
North_America = []
Oceania = []
Europe = []
#empty string to temporarily hold our ISO codes
iso_code = ''
#iterate through each line in the file
for line in fobj:
#look at each character in the line
for char in line:
#when there is not a tab, it is our ISO code
if char != '\t':
#we thus add it to our empty string
iso_code += char
#if it is a tab then we have our code and we must add it
#to our list
else:
#check for each continent in the line
if "Asia" in line:
#if it is a certain continent, like in this case, Asia,
#we add the ISO code to our list for Asia
Asia.append(iso_code)
#do the same thing for the other continents
#but this time add them their respective lists
#each representing a continent
elif "South America" in line:
South_America.append(iso_code)
elif "Africa" in line:
Africa.append(iso_code)
elif "North America" in line:
North_America.append(iso_code)
elif "Oceania" in line:
Oceania.append(iso_code)
elif "Europe" in line:
Europe.append(iso_code)
#reset the iso code variable to an empty string
#to store the next one
iso_code = ''
#once we are done with adding the ISO code to our list,
#we can move on to the next line and exit the for loop
#for the characters in line
break
#once we added all the iso codes to our lists, we add them
#to our dictionaries with their respective continents as keys
new_dict['AFRICA'] = Africa
new_dict['ASIA'] = Asia
new_dict['OCEANIA'] = Oceania
new_dict['SOUTH AMERICA'] = South_America
new_dict['NORTH AMERICA'] = North_America
new_dict['EUROPE'] = Europe
return new_dict
def add_continents_to_data(input_filename, continents_filename, output_filename):
'''
(str, str, str) -> int
Adds a third column to the lines we formatted before which represents the continent
the country belongs to, we also must take into account that some countries will
be in 2 continents
>>> add_continents_to_data("small_clean_co2_data.tsv", "iso_codes_by_continent.tsv",
"small_co2_data.tsv")
10
>>> add_continents_to_data("smaller_clean_co2_data.tsv", "iso_codes_by_continent.tsv",
"smaller_co2_data.tsv")
6
>>> add_continents_to_data("even_smaller_clean_co2_data.tsv", "iso_codes_by_continent.tsv",
"even_smaller_co2_data.tsv")
4
'''
#create a dictionary with keys as the continents and
#every ISO codes associated to the continents
my_dict = get_iso_codes_by_continent(continents_filename)
fobj1 = open(input_filename, "r", encoding="utf-8")
fobj2 = open(output_filename, "w", encoding="utf-8")
line_counter = 0
for line in fobj1:
#empty list to store our continents
continent_list = []
line_counter += 1
#create a list with the line that we split based on tabs
line = line.split('\t')
#iterate through our dict
for key in my_dict:
#check if the iso code is in our dict
if line[0] in my_dict[key]:
#then we add it to our list of continents
continent_list.append(key)
#transform our list of continent into a string
continents = ','.join(continent_list)
#insert the continents to our line
line.insert(2, continents)
#transform the our line back into a string
line = '\t'.join(line)
fobj2.write(line)
fobj1.close()
fobj2.close()
return line_counter
|
import numpy as np
class Vector2d:
"""
Class object represents vector and allows performing basic vector operations
"""
def __init__(self, x=0., y=0.):
self.x = x
self.y = y
def rotate(self, angle):
"""
Rotates self object by the given :angle
"""
return Vector2d(
self.x*np.cos(angle) - self.y*np.sin(angle),
self.x*np.sin(angle) + self.y*np.cos(angle)
)
def __repr__(self):
return f"[{self.x}, {self.y}]"
def to_array(self):
"""
Returns
-------
Vector coordinates as an array [x,y]
"""
return [self.x, self.y]
|
from functools import reduce
def product(s):
list_s = map(int, list(s))
return reduce((lambda x, y: x*y), list_s)
def largest_product(series, size):
if size == 0:
return 1
if size < 0 or size > len(series) or not series.isdigit():
raise ValueError
length = len(series)
substrings = [series[i:i+size] for i in range(0, length)]
sub_products=[product(s) for s in substrings if len(s) == size]
return max(sub_products)
largest_product("99099", 3)
|
def abbreviate(words):
return ''.join([x[0].upper() for x in words.replace('-', ' ').split() if x[0].isalnum()])
|
"""
Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple like so: (index1, index2).
For the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted.
The input will always be valid (numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array).
Based on: http://oj.leetcode.com/problems/two-sum/
My solution:
Basially we need to add two integers in a list and check whether or not they add up to a target number.
For this I created a for loop which ran to the total length of the numbers -1. Why? Because we need
to add a second for loop which starts one AFTER the first integer. We then check if when we add these
indexes if they add u to the target which is passed into the function and then return them.
Since this is a Leetcode question I suppose the most 'optimal' way is to create a hash table,
but I'm practicing the fundamentals here and that's something I can work on later.
"""
def two_sum(numbers, target):
for i in range(len(numbers)-1):
for j in range(i+1, len(numbers)):
if numbers[i] + numbers[j] == target:
return [i, j]
|
#!/usr/bin/env python
def fix_indents(infile, show=False, detect=False):
"""
Tries to make YAML indentation a consistent 2-spaces.
Identifies inconsistent indenation by tracking the indentation jump
Parameters
----------
infile : str
Filename to use
show : bool
If True, print out an indication of which line was problematic
detect : bool
If True, only print out the filename if there were any issues found and
then stop.
"""
data = open(args.infile).readlines()
results = []
level = 0
last_indent = 0
for line in data:
current_indent = len(line) - len(line.strip(' '))
diff = current_indent - last_indent
was_indented = diff > 0
was_dedented = (diff < 0)
if was_indented:
level += 1
if was_dedented:
level -= 1
if current_indent == 0:
level = 0
correct_indentation = level * ' '
detected_indentation = current_indent * ' '
if correct_indentation != detected_indentation and detect:
print(infile)
break
if show and (correct_indentation != detected_indentation):
results.append(
'# The following line has incorrect indentation '
'({0} instead of {1} spaces):'
.format(current_indent, level * 2)
)
results.append(line)
if not args.detect:
if len(line.strip()) == 0:
results.append(line.strip())
else:
results.append(correct_indentation + line.strip())
last_indent = current_indent
results = '\n'.join(results) + '\n'
return results
if __name__ == "__main__":
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('infile', help='Input file to work on')
ap.add_argument('--inplace', '-i', action='store_true', help='Edit in-place')
ap.add_argument('--detect', '-d', action='store_true', help='''If specified, do
not do any edits but only print the filename to stdout if there
was an indentation inconsistency detected''')
ap.add_argument('--show', '-s', action='store_true', help='''If specified, will
also print out which line is problematic.''')
args = ap.parse_args()
results = fix_indents(args.infile, show=args.show, detect=args.detect)
if args.inplace:
with open(args.infile, 'w') as fout:
fout.write(results)
else:
print(results, end='')
|
def convert(fahr):
return (fahr - 32)*(5/9)
def main():
while True:
fahr = input('enter fahrenheit:')
cent = convert(int(fahr))
print('%s 华氏度等于 %.2f 摄氏度' % (fahr,cent))
if __name__ == "__main__":
main()
|
#crear menu con 3 opciones
import os
def Numeros():
#ingresar n numeros donde n es numero ingresado por teclado
#mostrar cantidad de numeros positivos, negativos y iguales a 0
pos=0
neg=0
cero=0
cant=int(input("ingrese cantidad de números a ingresar: "))
for i in range(cant):
nume=int(input(str(i+1)+" Digite los numeros: "))
if(nume>0):
pos=pos+1
elif(nume<0):
neg=neg+1
else:
cero=cero+1
print("La cantidad de numeros ingresados es " + str(cant))
print("La cantidad de numeros positivos es " + str(pos))
print("La cantidad de numeros negativos es " + str(neg))
print("La cantidad de numeros igual a cero es " + str(cero))
print("------------------------------------------------------")
pausa = input("Digite cualquier tecla para continuar: ")
def Personas():
#Ingresar para n personas: nombre y edad. Mostrar promedio de todas las edades ingresadas
suma=0
cont=0
can=int(input("Digite la cantidad de edades que desea ingresar: "))
for i in range(can):
nom=input(str(i+1) + " Ingrese el nombre: ")
edad=int(input(str(i+1) + " Ingrese la edad: "))
suma+=edad
cont+=1
print("EL promedio de las edades es: " + str(suma/cont))
print("------------------------------------------------------")
pausa = input("Digite cualquier tecla para continuar: ")
seguir=True
while (seguir):
os.system('cls')
print("1. Numeros")
print("2. Datos personales")
print("3. Finalizar")
op=int(input("Digite un numero: "))
if(op==1):
Numeros()
if(op==2):
Personas()
if(op==3):
print("Programa finalizado")
pausa = input("Digite cualquier tecla para continuar: ")
break
|
import adventure_game.my_utils as utils
room1_inventory = {
"knife" : 1,
}
room1_locked = {
"east" : True,
"west" : False,
"north" : False,
"south" : False
}
# # # # # # # # # # # # # # #
# This is the main room you will start in.
#
# GO: From this room you can get to Room 2 (SOUTH) and Room 3 (East)
# Take: There is nothing to take in this room
# Use: There is nothing to use in this room
#
def run_room(player_inventory):
description = '''
. . . Main Room . . .
You open your eyes. The room you see is unfamiliar. You see a brightly lit
doorway to the SOUTH. To the EAST you see a closed door.
'''
print(description)
# valid commands for this room
commands = ["go", "take", "drop", "use", "examine", "status", "unlock"]
no_args = ["examine", "status"]
# nonsense room number, we need to figure out which room they want in the loop
next_room = -1
done_with_room = False
while not done_with_room:
# Examine the response and decide what to do
response = utils.ask_command("What do you want to do?", commands, no_args)
the_command = response[0].lower()
response = utils.scrub_response(response)
if the_command == 'go':
direction = response[1].lower()
# Use your hand drawn map to help you think about what is valid
if direction == 'south':
next_room = 2
done_with_room = True
elif direction == 'east':
is_locked = room1_locked["east"]
if not is_locked:
next_room = 3
done_with_room = True
if is_locked:
print("door is locked")
else:
# In this room, there is nowhere else to go.
print("There is no way to go,", direction)
elif the_command == 'take':
utils.take(player_inventory, room1_inventory, response)
elif the_command == 'drop':
utils.drop(player_inventory, room1_inventory, response)
elif the_command == "status":
utils.player_status(player_inventory)
elif the_command == "examine":
utils.examine(room1_inventory)
elif the_command == "unlock":
utils.unlock(player_inventory, room1_inventory, room1_locked, response)
# end of while loop
return next_room
|
import adventure_game.my_utils as utils
# # # # #
# ROOM 10
#
# Serves as a good template for blank rooms
room10_description = '''
. . . 10th room ...
You are in a tall cave, the ceiling is shrouded in darkness and the only sound is the flutter of little,
leathery wings. There are doors leading north and west.'''
room10_inventory = {}
room10_locked = {
"east" : False,
"west" : True,
"north" : False,
"south" : False
}
bats_alive =True
def run_room(player_inventory):
# Let the user know what the room looks like
print(room10_description)
global bats_alive
# valid commands for this room
commands = ["go", "take", "drop", "use", "examine", "status", "unlock", "attack"]
no_args = ["examine", "status"]
# nonsense room number,
# In the loop below the user should eventually ask to "go" somewhere.
# If they give you a valid direction then set next_room to that value
next_room = -1
bats_health = 6
bats_atk = 5
done_with_room = False
while not done_with_room:
# Examine the response and decide what to do
response = utils.ask_command("What do you want to do?", commands, no_args)
the_command = response[0].lower()
response = utils.scrub_response(response)
# now deal with the command
if the_command == 'go':
go_where = response[1].lower()
if go_where == "west":
is_locked = room10_locked["west"]
if not is_locked:
next_room = 12
done_with_room = True
if is_locked:
print("door is locked")
elif go_where == "north":
next_room = 8
done_with_room = True
else:
print("That direction is not an option")
elif the_command == 'take':
utils.take(player_inventory, room10_inventory, response)
elif the_command == 'drop':
utils.drop(player_inventory, room10_inventory, response)
elif the_command == "status":
utils.player_status(player_inventory)
elif the_command == "examine":
utils.examine(room10_inventory)
elif the_command == "unlock":
utils.unlock(player_inventory, room10_inventory, room10_locked, response)
elif the_command == "attack":
x = utils.attack(player_inventory, "bats", bats_health, bats_alive, response)
bats_health = x
if x <= 0:
print("the bats are dead")
bats_alive = False
else:
print("The command:", the_command, "has not been implemented in room 10")
x = utils.creature_action(bats_alive, player_inventory, bats_atk, "bats")
if x:
next_room = 666
done_with_room = True
return next_room
|
#!/bin/python
import sys
def funnyString(s):
r = s[::-1]
for i in range(1, len(s)):
a = abs(ord(r[i]) - ord(r[i-1]))
b = abs(ord(s[i]) - ord(s[i-1]))
if a != b:
return "Not Funny"
return "Funny"
# Complete this function
q = int(raw_input().strip())
for a0 in xrange(q):
s = raw_input().strip()
result = funnyString(s)
print(result)
|
#!/bin/python
import sys
def solve(year):
if year < 1918:
if year % 4 == 0:
print "12.09." + str(year)
else:
print "13.09." + str(year)
elif year == 1918 :
print "26.09.1918"
else:
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print "12.09." + str(year)
else:
print "13.09." + str(year)
# Complete this function
year = int(raw_input().strip())
solve(year)
|
with open ("Sonia_fav_foods.txt") as sonia_foods:
sonia_list = sonia_foods.readlines()
sonia_faves = []
for item in sonia_list:
item = item.strip()
sonia_faves.append(item)
with open ("Ally_fav_foods.txt") as ally_foods:
ally_list = ally_foods.readlines()
ally_faves = []
for item in ally_list:
item = item.strip()
ally_faves.append(item)
def compare_faves(sonia_faves, ally_faves):
if sonia_faves == ally_faves:
print "Our favorite foods are the same!"
elif sonia_faves != ally_faves:
print "Our favorite foods are different!"
# compare_faves(sonia_faves, ally_faves)
def compare_faves2(sonia_faves, ally_faves):
for food in sonia_faves:
if food in ally_faves:
return "We both like %s" %(food)
# else:
# return "Our favorite foods are different"
print compare_faves2(sonia_faves, ally_faves)
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
#!/usr/bin/env python
"""mapper.py"""
import sys
# input comes from STDIN (standard input)
for line in sys.stdin:
# remove leading and trailing whitespace
line = line.strip()
# split the line into words
words = line.split()
# increase counters
topwords=["golf","football","game","soccer","play","league","college","good","baseball","basketball"]
for topword in topwords:
if topword in words:
for word in words:
if(word!=topword):
print('%s\t%s' % (topword+","+word, 1))
|
#写一个函数input_student()得到学生的姓名,年龄,年龄
# 输入一些学生信息;按照年龄从大到小排列,并输出
# 按照成绩从高到低排序后,并输出
#第一步,读取学生信息,形成字典后存入列表L中
def input_student():
L = []
while True:
name = input('请输入学生姓名:')
if not name:
break
age = int(input('请输入学生年龄:'))
score = int(input('请输入学生成绩:'))
d = {} #重新创建一个新的字典
d['name']=name
d['age']=age
d['score']=score
L.append(d)
return L
def output_student(L):
print('+'+'-'*12+'+'+'-'*6+'+'+'-'*7+'+')
print('|'+str('name').center(12)+'|'+str('age').center(6)+'|'+str('score').center(7)+'|')
print('+'+'-'*12+'+'+'-'*6+'+'+'-'*7+'+')
for d in L:
t = ((d['name']).center(12),
str (d['age']).center(6),
str (d['score']).center(7))
line = '|%s|%s|%s|'% t
print(line)
print('+'+'-'*12+'+'+'-'*6+'+'+'-'*7+'+')
#此函数用来打印菜单
def show_menu():
print('+------------+------+----------------------+')
print('| 1) 添加学生信息 |')
print('| 2) 查看所有学生信息 |')
print('| 3) 修改学生的成绩 |')
print('| 4) 删除学生信息 |')
print('| 5) 按成绩从高到低打印学生信息 |')
print('| 6) 按成绩从低到高打印学生信息 |')
print('| 7) 按年龄从高到低打印学生信息 |')
print('| 8) 按年龄从低到高打印学生信息 |')
print('| q) 退出 |')
print('+------------+------+----------------------+')
#此函数修改学生的信息
def modify_student_info(lst):
name = input('请输入要修改学生的姓名:')
for d in lst:
if d['name'] == name:
score = int(input('请输入新成绩:'))
d['score'] = score
print('修改',name,'的成绩为',score)
return
else:
print('没有找到名为:',name,'的学生信息')
#此函数删除学生信息
def delete_student_info(lst):
name = input('请输入要删除学生的姓名:')
for i in range(len(lst)):
if lst[i]['name'] == name:
del lst[i]
print('已成功删除:', name)
return
else:
print('没有找到名为:',name,'的学生信息')
#此函数年龄降序排列
def age_desc(lst):
L = sorted(lst,key= lambda d: d['age'], reverse = True)
output_student(L)
#此函数年龄升序排列
def age_asc(lst):
L = sorted(lst,key= lambda d: d['age'])
output_student(L)
#此函数年龄降序排列
def score_desc(lst):
L = sorted(lst,key= lambda d: d['score'], reverse = True)
output_student(L)
#此案函数年龄升序排列
def score_asc(lst):
L = sorted(lst,key= lambda d: d['score'])
output_student(L)
#定义主函数,用来获取键盘操作,实现选择功能
def main():
docs = [] # 此列表用来存储所有学生的信息的字典
while True:
show_menu()
s = input('请选择:')
if s == '1':
docs += input_student()
elif s == '2':
output_student(docs)
elif s == '3':
modify_student_info(docs)
elif s == '4':
delete_student_info(docs)
elif s == '5':
score_desc(docs)
elif s == '6':
score_asc(docs)
elif s == '7':
age_desc(docs)
elif s == '8':
age_asc(docs)
elif s == 'q':
return #结束此函数执行,直接退出
main()
|
"""
Mini-application: Buttons on a Tkinter GUI tell the robot to:
- Go forward at the speed given in an entry box.
This module runs on your LAPTOP.
It uses MQTT to SEND information to a program running on the ROBOT.
Authors: David Mutchler, his colleagues, and Ricardo Hernandez.
"""
import tkinter
from tkinter import ttk
import mqtt_remote_method_calls as com
def main():
""" Constructs and runs a GUI for this program. """
root = tkinter.Tk()
rl = RemoteLaptop()
mqtt_client = com.MqttClient(rl)
mqtt_client.connect_to_ev3()
setup_gui(root, mqtt_client)
root.mainloop()
def setup_gui(root_window, mqtt_client):
""" Constructs and sets up widgets on the given window. """
frame = ttk.Frame(root_window, padding=50)
frame.grid()
text = 'Press [W] to go FORWARD\n' \
'\n' \
'Press [S] to go BACKWARDS\n' \
'\n' \
'Press[D] to Turn RIGHT\n' \
'\n' \
'Press[A] to Turn LEFT\n' \
'\n' \
'Press [SPACE BAR] to STOP MOVING'
label = ttk.Label(frame, text=text)
label.grid()
speed_entry_box = ttk.Entry(frame)
go_forward_button = ttk.Button(frame, text="Go Forward")
speed_entry_box.grid()
go_forward_button.grid()
go_backwards_button = ttk.Button(frame, text="Go Backwards")
notice = 'Goes backwards the same speed it goes forward'
label = ttk.Label(frame, text=notice)
label.grid()
go_backwards_button.grid()
left_box = ttk.Entry(frame)
turn_left_button = ttk.Button(frame, text="Turn Left")
left_box.grid()
turn_left_button.grid()
right_box = ttk.Entry(frame)
turn_right_button = ttk.Button(frame, text="Turn Right")
right_box.grid()
turn_right_button.grid()
stop_button = ttk.Button(frame, text="STOP")
stop_button.grid()
notice1 = 'Press the button below to remove the focus away from the boxes above.'
label = ttk.Label(frame, text=notice1)
label.grid()
key_mode_button = ttk.Button(frame, text='Key Arrow Mode')
key_mode_button.grid()
go_forward_button['command'] = lambda: handle_go_forward(speed_entry_box, mqtt_client)
go_backwards_button['command'] = lambda: handle_backwards(speed_entry_box, mqtt_client)
turn_left_button['command'] = lambda: handle_turn_left(left_box, mqtt_client)
turn_right_button['command'] = lambda: handle_turn_right(right_box, mqtt_client)
stop_button['command'] = lambda: handle_stop(mqtt_client)
root_window.bind_all('<Key-w>', lambda event: handle_go_forward(speed_entry_box, mqtt_client))
root_window.bind_all('<Key-s>', lambda event: handle_backwards(speed_entry_box, mqtt_client))
root_window.bind_all('<Key-a>', lambda event: handle_turn_left(left_box, mqtt_client))
root_window.bind_all('<Key-d>', lambda event: handle_turn_right(right_box, mqtt_client))
root_window.bind_all('<Key-space>', lambda event: handle_stop(mqtt_client))
root_window.bind_all('<Key-c>', lambda event: handle_get_color(mqtt_client))
root_window.bind_all('<KeyRelease>', lambda event: handle_stop(mqtt_client))
root_window.mainloop()
def handle_go_forward(speed_entry_box, mqtt_client):
speed = speed_entry_box.get()
print('sending go forward with the speed:', speed)
mqtt_client.send_message('go_forward', [speed])
"""
Tells the robot to go forward at the speed specified in the given entry box.
"""
def handle_backwards(speed_entry_box, mqtt_client):
go_backwards = speed_entry_box.get()
print('Going backwards', go_backwards)
mqtt_client.send_message('go_backwards', [go_backwards])
def handle_turn_left(left_box, mqtt_client):
turn_left = left_box.get()
print('turning left this many degrees:', turn_left)
mqtt_client.send_message('turn_left_degrees', [turn_left])
def handle_turn_right(right_box, mqtt_client):
turn_right = right_box.get()
print('turning right this many degrees:', turn_right)
mqtt_client.send_message('turn_right_degrees', [turn_right])
def handle_stop(mqtt_client):
print('Stopping')
mqtt_client.send_message('stop')
def released_key(mqtt_client):
print('You released the key you were pressing')
mqtt_client.send_message('stop')
def handle_get_color(mqtt_client):
print('Getting the color in front of me')
mqtt_client.send_message('get_color')
class RemoteLaptop(object):
def __init__(self):
print('I got here')
def robot_orange(self):
print("I see orange")
window = tkinter.Toplevel()
photo = tkinter.PhotoImage(file='orange.gif')
label = ttk.Label(window, image= photo)
label.image = photo
label.grid()
def robot_yellow(self):
print('I see yellow')
window = tkinter.Toplevel()
photo = tkinter.PhotoImage(file='Yellow.gif')
label = ttk.Label(window, image=photo)
label.image = photo
label.grid()
def robot_blue(self):
print('I see blue')
window = tkinter.Toplevel()
photo = tkinter.PhotoImage(file='blue.gif')
label = ttk.Label(window, image=photo)
label.image = photo
label.grid()
def robot_red(self):
print('I see red')
window = tkinter.Toplevel()
photo = tkinter.PhotoImage(file='red.gif')
label = ttk.Label(window, image=photo)
label.image = photo
label.grid()
main()
|
# Class example. A class is nothing more than a way to wrap a bunch of
# variables and functions together under one 'roof'. Objects of a function
# have access to all the members (variables) of the class and can call
# the methods (functions) associated with the class. Here we have a class:
# Drawer. Drawer objects have 3 members: numForks, numSpoons, and
# numSpatulas. Representing (obviosuly) the number of forks, spoons, and
# spatulas associated with an object. Drawer objects also have 1 method
# addFork() which will increment the number of forks they have by 1.
class Drawer:
# this is the 'constructor' for our class. when we make an object of
# this class we will run this method
def __init__(self, numForks, numSpoons, numSpatulas):
# self.numForks is a 'member' of class Drawer
# this means it is a variable that is associated with this class
# all objects of this class will have access to these variables
# In this line we assign the number of forks that was passed to the
# constuctor to this variable
self.numForks = numForks
# obviously same thing here...but these are spoons
self.numSpoons = numSpoons
# you guessed it...these are spatulas
self.numSpatulas = numSpatulas
# this is a 'class method'. this means every object of this class
# can call this method. it will increase the fork count of this object
# by...one
def addFork(self):
self.numForks += 1
# Lets print the contents of the drawer. We will give it the 'id' of the
# drawer so we know what the hell we're printing.
def printContents(self, drawerID):
print 'drawer%s contains %s forks, %s spoons and %s spatulas' % \
(drawerID, self.numForks, self.numSpoons, self.numSpatulas)
def main():
# let's make a Drawer object. Imagine this is a drawer in your kitchen.
# You have lots of drawers in your kitchen, this particular one has 5
# forks, 7 spoons, and no spatulas
drawer0 = Drawer(5,7,0)
# lets print out the contents of the drawer. We could access each of the
# objects members.
print 'Drawer0: %s forks, %s spoons and %s spatulas' % \
(drawer0.numForks, drawer0.numSpoons, drawer0.numSpatulas)
# But wait! Drawer objects have a method to do this...why dont we use that?
drawer0.printContents(0)
# Now let's make another drawer for your kitchen. This one doesn't have
# forks and spoons...but a shit load of spatulas
drawer1 = Drawer(0,0,100)
# Better check whats in it
drawer1.printContents(1)
# Hey look! You've bought a new fork. Maybe you will put it with the
# spatulas...
drawer1.addFork()
# Let's check whats in drawer1 again...
drawer1.printContents(1)
# drawer0 and drawer1 are objects of class Drawer. They each have their
# own variables numForks, numSpoons and numSpatulas. Both objects can
# call addFork() and printContents()
# Does this line work?? Why / why not?
# printContents()
if __name__ == '__main__':
main()
|
import os
import re
f = open('paragraph_1.txt', 'r')
content = f.read()
words = re.split(r"[\s\.,\?]+",content)
characters = 0
#Calculate number of words
d = len(words)
#Calculate number of sentences
sentence = content.count('.')
#Calculate Average number of sentences
avg_sent_count = d/sentence
#Calculate Average Letter Count
for words in content:
if words not in [" ",",",";","."]:
characters += sum(len(letter) for letter in words)
average_char = characters/d
#Final Result
print ("Paragraph Analysis")
print ("-----------------")
print ("Approximate Word Count: " + str(d))
print ("Approximate Sentence Count: " + str(sentence))
print ("Average Sentence Length: " + str(avg_sent_count))
print ("Average Letter Count: " + str(average_char))
|
import numpy as np
# 균일한 간격으로 데이터 생성
array = np.linspace(0, 10, 5)
# 0: 시작값
# 10: 끝값
# 5: 시작값과 끝값 사이에 몇개의 데이터가 있는가
print(array)
# 난수의 재연(실행마다 결과 동일)
np.random.seed(7)
print(np.random.randint(0, 10, (2, 3)))
# Numpy 배열 객체 복사
array1 = np.arange(0, 10)
array2 = array1.copy()
array2[0] = 99
print(array1)
# 중복된 원소 제거
array = np.array([1, 1, 2, 2, 2, 3, 3, 4])
print(np.unique(array))
|
# 배열 형태 바꾸기
import numpy as np
array1 = np.array([1, 2, 3, 4])
# 2 * 2 행렬로 바뀜
array2 = array1.reshape((2, 2))
print(array2)
|
import numpy as np
array1 = np.array([1, 2, 3])
array2 = np.array([4, 5, 6])
# 배열을 합침
array3 = np.concatenate([array1, array2])
# 배열의 크기 출력
print(array3.shape)
print(array3)
|
import numpy as np
array1 = np.arange(0, 8).reshape(2, 4)
array2 = np.arange(0, 8).reshape(2, 4)
array3 = np.concatenate([array1, array2], axis=0)
array4 = np.arange(0, 4).reshape(4, 1) # (4 * 1)
print(array3 + array4)
|
# -*- coding: utf-8 -*-
"""
Write a Python function, `odd`, that takes in one number and returns `True` when the number is odd and `False` otherwise.
You should use the `%` (mod) operator, not `if`.
This function takes in one number and returns a boolean.
"""
def odd(x):
return x % 2 != 0
|
# -*- coding: utf-8 -*-
"""
Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month.
In this problem, we will not be dealing with a minimum monthly payment rate.
The following variables contain values as described below:
`balance` - the outstanding balance on the credit card
`annualInterestRate` - annual interest rate as a decimal
The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year, for example:
Lowest Payment: 180
Assume that the interest is compounded monthly according to the balance at the end of the month (after the payment for that month is made). The monthly payment must be a multiple of $10 and is the same for all months. Notice that it is possible for the balance to become negative using this payment scheme, which is okay. A summary of the required math is found below:
Monthly interest rate = (Annual interest rate) / 12.0
Monthly unpaid balance = (Previous balance) - (Minimum fixed monthly payment)
Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate * Monthly unpaid balance)
"""
def balance_after_one_month(balance, monthlyPayment, annualInterestRate):
"""Calculates credit card balance after one month
Args:
balance (int or float): Balance at the beginning of month
monthlyPayment (int or float): Fixed monthly payment
annualInterestRate(float): Interest charged on unpaid balance
Returns:
float: Balance at the end of the month. Calculated after
payments and charging monthly interest
"""
monthlyInterestRate = annualInterestRate / 12.0
monthlyUnpaidBalance = balance - monthlyPayment
updatedBalance = (monthlyUnpaidBalance
+ monthlyInterestRate * monthlyUnpaidBalance)
return updatedBalance
def balance_after_n_months(
balance,
monthlyPayment,
annualInterestRate,
months):
"""Calculates credit card balance after specified amount of months.
Calls `balance_after_one_month` `months`'s times
Args:
balance (int or float): Balance at the beginning of month
monthlyPayment (int or float): Fixed monthly payment
annualInterestRate(float): Interest charged on unpaid balance
months (int): Amount of months for which the balance is calculated
Returns:
float: Balance after specified amount of months,
rounded to 2 decimal digits.
"""
month_balance = balance_after_one_month(balance, monthlyPayment,
annualInterestRate)
for x in range(months - 1):
month_balance = balance_after_one_month(month_balance, monthlyPayment,
annualInterestRate)
return round(month_balance, 2)
def guess_monthly_payment(balance, annualInterestRate, months):
"""Roughtly guesses monthly payment needed to pay off a credit card
balance within 12 months.
Args:
balance (int or float): Balance at the beginning of month
annualInterestRate (float): Interest charged on unpaid balance
months (int): Number of months for which to guess the payment
Returns:
float: Divides overall balance by number of months, adds interest rate,
and rounds it to 10-ths
"""
return (balance / months) * (1 + annualInterestRate) // 10 * 10
def calculate_monthly_payment(balance, annualInterestRate, months):
"""Calculates fixed monthly payment required to pay off credit card debt.
Args:
balance (int or float): Balance at the beginning of month
annualInterestRate (float): Interest charged on unpaid balance
months (int): Number of months for which to guess the payment
Returns:
string: Guesses monthly payment and increases it if it's too small,
e.g. blance is greater than 0. Or decreases it if balance is to
less than 0. Returns concatenated string with text and value.
"""
guess = guess_monthly_payment(balance, annualInterestRate, months)
if balance_after_n_months(balance, guess, annualInterestRate, months) > 0:
monthlyPayment = increase_monthly_payment(balance, guess,
annualInterestRate, months)
else:
monthlyPayment = decrease_monthly_payment(balance, guess,
annualInterestRate, months)
return "Lowest Payment: " + str(monthlyPayment)
def increase_monthly_payment(balance,
monthlyPayment,
annualInterestRate,
months):
"""Increases fixed monthly payment by 10 dollars if it's too small.
Args:
balance (int or float): Balance at the beginning of month
monthlyPayment (int or float): Fixed monthly payment
annualInterestRate(float): Interest charged on unpaid balance
months (int): Amount of months for which the balance is calculated
Returns:
float: minimum monthly payment, so balance is less or equal 0.
"""
while balance_after_n_months(balance, monthlyPayment, annualInterestRate,
months) > 0:
monthlyPayment += 10
return monthlyPayment
def decrease_monthly_payment(balance,
monthlyPayment,
annualInterestRate,
months):
"""Decreases fixed monthly payment by 10 dollars if it's too large.
Args:
balance (int or float): Balance at the beginning of month
monthlyPayment (int or float): Fixed monthly payment
annualInterestRate(float): Interest charged on unpaid balance
months (int): Amount of months for which the balance is calculated
Returns:
float: minimum monthly payment, so balance is less or equal 0.
"""
while balance_after_n_months(balance, monthlyPayment, annualInterestRate,
months) < 0:
monthlyPayment -= 10
return monthlyPayment + 10
# Test Case 1:
balance = 3329
annualInterestRate = 0.2
print(calculate_monthly_payment(balance, annualInterestRate, 12))
# Result Your Code Should Generate:
# -------------------
# Lowest Payment: 310
# Test Case 2:
balance = 4773
annualInterestRate = 0.2
print(calculate_monthly_payment(balance, annualInterestRate, 12))
# Result Your Code Should Generate:
# -------------------
# Lowest Payment: 440
# Test Case 3:
balance = 3926
annualInterestRate = 0.2
print(calculate_monthly_payment(balance, annualInterestRate, 12))
# Result Your Code Should Generate:
# -------------------
# Lowest Payment: 360
|
"""
1. Convert the following into code that uses a while loop.
print '2'
prints '4'
prints '6'
prints '8'
prints '10'
prints 'Goodbye!'
"""
i = 0
while i < 10:
i += 2
print(i)
print("Goodbye!")
"""
2. Convert the following into code that uses a while loop.
prints 'Hello!'
prints '10'
prints '8'
prints '6'
prints '4'
prints '2'
"""
i = 10
print("Hello!")
while i > 0:
print(i)
i -= 2
"""
3. Write a while loop that sums the values 1 through 'end', inclusive. 'end' is a variable that we define for you. So, for example, if we define 'end' to be 6, your code should print out the result:
'21'
which is 1 + 2 + 3 + 4 + 5 + 6.
For problems such as these, do not include input statements or define variables we will provide for you. Our automating testing will provide values so write your code in the following box assuming these variables are already defined.
"""
sum_var = 0
num = 0
while num <= end:
sum_var += num
num += 1
print(sum_var)
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def insertafter(self, prev, new_data):
if prev == None:
return " Error 404"
new_node = Node(new_data)
new_node.next = prev.next
prev.next = new_node
def append(self, new_data):
new_node = Node(new_data)
if self.head == None:
self.head = new_node
return
last = self.head
while(last.next):
last = last.next
last.next =new_node
def printlist(self):
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
if __name__ == "__main__":
ll = LinkedList()
ll.head = Node(1)
second = Node(2)
third = Node(3)
ll.head.next = second
second.next = third
ll.push(9)
ll.insertafter(ll.head, 5)
ll.append(6)
ll.printlist()
|
#time complexity
def compress(string):
strlen = len(string)
compressL=[string[0]]
num = 1
indexc=0
for i in range(1,strlen):
if(string[i] != compressL[indexc]):
compressL.append(str(num))
compressL.append(string[i])
indexc+=2
num=1
else:
num+=1
compressL.append(str(num))
word= "".join(compressL)
if(len(word) <= strlen):
return word
else:
return string
string1 = input("enter string")
string2 = compress(string1)
print(string2)
|
import pandas as pd
df1 = pd.read_html('https://en.wikipedia.org/wiki/Sales_taxes_in_the_United_States')
df = df1[3].drop(df1[3].index[0]).drop([3,4,5,6,7,8], axis=1)
df.columns = ['State/territory/district' ,'Base sales tax' ,'Total with max local surtax']
#remove the % sign
df['Base sales tax']=df['Base sales tax'].apply(lambda x: str(x)[:-1]).apply(pd.to_numeric)
df['Total with max local surtax']=df['Total with max local surtax'].apply(lambda x: str(x)[:-1]).apply(pd.to_numeric)
#find the state or territory with the highest Base sales tax
df.loc[df['Base sales tax'].idxmax()]['State/territory/district']
# find the state or territory with the highest Total with max local surtax
df.loc[df['Total with max local surtax'].idxmax()]
# return a numpy array of states and territories with a zero percent base sales tax
pd.Series(df.loc[df['Base sales tax'] == 0]['State/territory/district']).values
# which state or territory has the lowest non-zero percent base sales tax
#tip: create a temporary dataframe and remove from it the rows with a zero percent base sales tax
# and then get the state or territory with the lowest tax
data = df
mask = data['Base sales tax']== 0 #should return an array of true/false
dq = data[~mask] # remove the falses
dq.loc[dq['Base sales tax'].idxmin()]['State/territory/district']
|
def txt_to_xml(filename):
# Open file and read the lines of the file and then close the file
file = open(filename, 'r')
lines = file.readlines()
file.close()
# Create count variable to index where the xml of the data table info begins
count = 0
for line in lines:
count += 1
if line.startswith("<informationTable xsi"): break
# Remove all lines up to the first line of the data table xml info
del lines[0:count]
# Remove last 4 lines of excess data
del lines[-4:]
# Write new info to new file which doesnt contain deleated files
new_file = open(filename[:-4] + ".xml", "w+")
new_file.write("<informationTable >\n")
for line in lines:
new_file.write(line)
|
import math
"""
NIFS3 (pl. Naturalna Interpolacyjna Funkcja Sklejana 3-go stopnia)
Polynomial interpolating function using given points (x, f(x))
Spline : https://en.wikipedia.org/wiki/Spline_interpolation#Algorithm_to_find_the_interpolating_cubic_spline
"""
class Spline:
_xs = []
_ys = []
_diff_quos = []
_moments = []
def __init__(self, xs, ys):
"""
Spline interpolation object.
Params:
@_xs, @_ys - list of x and y coords from the interpolations nodes
@_us, @_qs - list of values Pi and Qi needed to calculate interpolation moments
f(a) - f(b)
@_diff_quos - list of the differental quotients -----------
b - a
@_moments - list of the interpolation moments equal second derivative of the spline
Mi = Si''(x)
"""
self._xs = xs # sorted with ascending order
self._ys = ys # corresponding values = f(x)
if len(xs) > 2 :
self._diff_quos = Spline.differental_quotients_table(xs, ys)
self._moments = Spline.table_of_moments(xs, ys,self._diff_quos)
def __call__(self, x):
""" make object callable """
# for 2 points create line
if len(self._xs) == 2:
p = list(zip(self._xs, self._ys))
return Spline.line(p[0], p[1], x)
# for more points create polynomials
for i in range(1,len(self._xs)):
""" check which part of the function you should use """
if x <= self._xs[i]:
return Spline.s(i, self._xs, self._ys, self._moments,x)
return Spline.s(len(self._xs)-1, self._xs, self._ys, self._moments,x)
def add_point(self,x,y):
self._xs.append(x)
self._ys.append(y)
self._diff_quos.append()
def differental_quotients_row(self, x_n, y_n):
"""
f[n], f[n-1, n], f[n-2, n-1, n]
| x || y | f[i,j] | f[i,j,k] |
+------++----------+-------------+------------------+
| .. || ... | ... | ... |
| xn-1 || f[n-1] | f[n-2, n-1] | f[n-3, n-2, n-1] |
| || \ | \ | |
| || \ \ |
| xn || f[n] --- f[n-1, n] --- f[n-2, n-1, n] |
To calculate f[i-1, i, i+1] we need f[i-1, i] , f[i, i+1] , x[i+1] and x[i],
so we can calculate new rows in time O(1), because len(row) = 3
"""
n = len(self._diff_quos)
# f[n]
f_n = y_n
# f[n-1, n]
f_n_1__n = ( f_n - self._diff_quos[n-1][0] ) / ( x_n - self._xs[n-1] )
# f[n-2, n-1, n]
f_n_2__n_1__n = ( f_n_1__n - self._diff_quos[n-1][1] ) / ( x_n - self._xs[n-2])
self._diff_quos.append( [f_n, f_n_1__n, f_n_2__n_1__n] )
@staticmethod
def differental_quotients_table(x,y):
"""
returns 2d table 'f' contains differential quotients of the interpolated function
x || y = f[i] | f[i,j] | f[i,j,k]
---++-----------+------------+-------------
x0 || y0 | 0 | 0
x1 || y1 | f[0,1] | 0
x2 || y2 | f[1,2] | f[0,1,2]
x3 || y3 | f[2,3] | f[1,2,3]
x4 || y4 | f[3,4] | f[2,3,4]
.. || .. | ... | ...
f[j] - f[i] f[j,k] - f[i,j]
f[i,j] = ------------- , f[i,j,k] = ------------------
Xj - Xi Xk - Xi
self._diff_quos[i][0] == f[i]
self._diff_quos[i][1] == f[i-1, i]
self._diff_quos[i][2] == f[i-2, i-1, i]
We will be interested in self._diff_quos[i][2].
"""
n = len(y)
f = []
for i in range(0,n):
f += [ [y[i], 0, 0] ]
for i in range(1,n):
f[i][1] = ( f[i][0] - f[i-1][0] ) / (x[i] - x[i-1])
for i in range(2,n):
f[i][2] = ( f[i][1] - f[i-1][1] ) / (x[i] - x[i-2])
return f
@staticmethod
def table_of_moments(x,y,differental_quiotients_table):
"""
create Spline moments table after loading the set of interpolation nodes
Spline Moments satisfies equality:
l[k]*M[k-1] + 2*M[k] + (1-l[k])*M[k+1] = 6 * f[k-1, k, k+1]
so they are expressed by the formula:
D[k] - l[k]*M[k-1] - (1-l[k])*M[k+1]
M[k] = ----------------------------------------
2
But we can use the another algorithm!
Solve system of equations (matrix form): A*M = D
Where:
A M D
| 2, 1-l[1], 0, 0, 0, 0, ..., 0 | | M[1] | | d[1] |
| l[2], 2, 1-l[2], 0, 0, 0, ..., 0 | | M[2] | | d[2] |
| 0, l[3], 2, 1-l[3], 0, 0, ..., 0 | | M[3] | | d[3] |
| 0, 0, l[4], 2, 1-l[4], 0, ..., 0 | | ... | _____ | ... |
| 0, 0, 0, ..., ..., ..., 0, 0 | | ... | _____ | ... |
| ..., ..., ..., ..., ..., ..., ..., 0 | | ... | | ... |
| ..., ..., ..., ..., ..., ..., ..., 0 | | ... | | ... |
| 0, 0, 0, 0, 0, l[n-2], 2, 1-l[n-2] | | M[n-2] | | d[n-2] |
| 0, 0, 0, 0, 0, 0, l[n-1], 2 | | M[n-1] | | d[n-1] |
We can find Moment's in linear time! ( O(n) )
Algorithm to solve it:
+-----
|
| q[0] = 0
|
| U[0] = 0
|
| p[k] = l[k]*q[k-1] + 2
|
| l[k] - 1
| q[k] = ----------
| p[k]
|
|
| d[k] - l[k]*U[k-1]
| U[k] = ---------------------
| p[k]
|
|
| M[n-1] = U[n-1]
|
| M[k] = U[k] + q[k]*M[k+1]
|
+-----
where:
M[0] = M[n] = 0
d[k] = 6 * f[k-1, k, k+1]
q[0] = U[0] = 0
x[k] - x[k-1] h[k]
l[k] = ----------------- = ---------------
x[k+1] - x[k-1] h[k+1] + h[k]
h[k] = x[k] - x[k-1]
M[i] == S''(Xi)
"""
n = len(x)
Momoents = list(range(0,n))
Momoents[n-1] = 0
Momoents[0] = 0
U,q = Spline.U_q_table(x,differental_quiotients_table)
for i in range(n-2, 0, -1):
Momoents[i] = U[i] + q[i]*Momoents[i+1]
return Momoents
@staticmethod
def U_q_table(xs, differental_quiotients_table):
""" returns lists U and q needed to calculate moments (Mi - ith moment = s''(Xi)) """
n = len(xs)-1
U,q = [None],[None]
U += [3 * differental_quiotients_table[2][2]] # U1
q += [(1 - (xs[1]-xs[0]) / (xs[2]-xs[0])) / 2] # q1
for i in range(2,n):
li = ( xs[i]-xs[i-1] ) / ( xs[i+1]-xs[i-1] )
di = 6 * differental_quiotients_table[i+1][2]
pi = 2 + li*q[i-1]
q.append( ( 1 - li ) / pi )
U.append( (di - li*U[i-1]) / pi )
return U,q
@staticmethod
def s(k, x, y, Momoents, xx):
""" k-th part of the interpolating polynomial """
h = x[k] - x[k-1]
x_xk = xx - x[k-1]
xk_x = x[k] - xx
return 1/h*( 1/6 * Momoents[k-1] * xk_x**3 +
1/6 * Momoents[k] * x_xk**3 +
( y[k-1] - 1/6 * Momoents[k-1] * (h**2) ) * xk_x +
( y[k] - 1/6 * Momoents[k] * (h**2) ) * x_xk )
@staticmethod
def line(p1, p2, x):
a = (p1[1] - p2[1]) / (p1[0] - p2[0])
b = p1[1] - a*p1[0]
return a*x + b
|
some_list = ['one', 'two', 'three', 'four']
#Method :1
#Conver the list to string and then remove the first and last element
method_1 = str(some_list)[1:-1]
#Method :2
#Use join to seperate elements
method_2 = ', '.join(map(str, some_list))
|
random_list = [1,2,3,3,4,5,5,6,7,7,8,8]
#Using set we can remove duplicates from a sequence
remove_duplicates = set(random_list)
convert_to_list = list(remove_duplicates)
print convert_to_list
|
def readfile(): #reads str into memory calls it f
text_file = open("file.txt","r")
f = text_file.read()
return f
|
nome = input('Informe seu nome completo: ')
div = nome.split()
pn = div[0]
un = div[len(div)-1]
print('{} tem como primeiro nome {} e último nome {}.'.format(nome, pn, un))
|
cel = float(input('Informe a temperatura em ºC: '))
far = 1.8 * cel + 32
print('A temperatura de {}ºC corresponde a {}ºF.'.format(cel, far))
|
nome = input('Digite seu nome: ').strip()
print('Este é seu nome com letras maiúsculas: {}.'.format(nome.upper()))
print('Este agora com letras minúsculas: {}.'.format(nome.lower()))
div = nome.split()
joi = ''.join(div)
print('O número de letras do seu nome é: {}.'.format(len(joi))) # format(len(nome) - nome.count(' ')) also works
print('O número de letras do seu primeiro nome é: {}.'.format(len(div[0]))) # format(nome.find(' ')) also works
|
cont = 0
soma = 0
for c in range(3, 500, 3):
if c % 2 == 1:
soma += c
cont += 1
print(f'''A somatória entre todos os {cont} números ímpares
que são múltiplos de 3
no intervalo entre 1 e 500 é igual a {soma}.''')
|
from random import shuffle
print('Vamos sortear a ordem de apresentação do grupo de 4 alunos!')
a = input('Informe o nome do primeiro aluno: ')
b = input('Informe o nome do segundo aluno: ')
c = input('Diga o nome do terceiro aluno: ')
d = input('E finalmente insira o nome do quarto aluno: ')
l = [a, b, c, d]
shuffle(l)
print(f'A ordem sorteada é: {l}.')
|
sal = float(input('Informe o seu salário: R$'))
aum = sal * 1.15
print('O seu salário era R${:.2f} e com o aumento de 15% ficará R${:.2f}'.format(sal, aum))
|
# greeting = "Hello"
# name = input("Please enter your name ")
# print(greeting + " " + name)
spiltString = "This string has been\nsplit over\nseveral\nlines"
print(spiltString)
tabbedString = "1\t2\t3\t4\t5"
print(tabbedString)
print (""" THis is also working """)
|
from pet_goods import pet_goods
from pet_animals import pet_animals
class pet_rodents(pet_animals):
def __init__(self, name, price, kind_pet, age, rodent_breed):
pet_animals.__init__(self, name, price, kind_pet, age)
self.rodent_breed = rodent_breed
def display_rodents(self):
print(self.name, self.price, self.kind_pet, self.age, self.rodent_breed)
def add_rodent():
goods_array=[]
name=input("Please input name goods: ")
price=int(input("Please input price goods: "))
kind_pet=input("Please input kind of pet: ")
age=input("Please input age pet: ")
rodent_breed=input("Please input rodent breed: ")
goods_array.append(name)
goods_array.append(price)
goods_array.append(kind_pet)
goods_array.append(age)
goods_array.append(rodent_breed)
|
"""
Имя проекта: №27
Номер версии: 1.0
Имя файла: practicum-1(№27).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 26/11/2020
Дата последней модификации: 26/11/2020
Дано вещественное число А. Вычислить f(A), если f(x) = 0, при x<=0. f(x) = x^2 - x, при (x=>1), в противном случае f(x) = x^2 - sin (Пx^2)
Описание: Решение задач № 27 практикума № 1
#версия Python: 3.6
"""
"""
Оригинал публикации: Практикум №1 - набиваем руку (Бизнес-информатика 2020)
"""
import math
A = float(input("Введите число А:"))
x = A
if x <= 0:
fx = 0
print("x <= 0; f(a) =:", fx)
elif 0 < x < 1:
fx = math.pow(x, 2) - x
print("0 < x < 1; f(a) =:", fx)
else:
fx = math.pow(x, 2) - math.sin((math.pi * math.pow(x, 2)))
print("x >= 1; f(a) =:", fx)
|
"""
Имя проекта: №54
Номер версии: 1.0
Имя файла: practicum-1(№54).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 13/12/2020
Дата последней модификации: 13/12/2020
Описание: Решение задач № 54 практикума № 1
описание:
#версия Python: 3.6
"""
"""
Оригинал публикации: Практикум №1 - набиваем руку (Бизнес-информатика 2020)
"""
import re
M = 2
list_strings = []
for i in range(0, M):
print("Введите строку:", end=' ')
list_strings.append(input())
print("Введите слог:", end=' ')
syllable = input()
for string in list_strings:
count = len(re.findall(syllable, string))
print("В строке \"%s\" слог \"%s\" встречается %s раз"
% (string, syllable, count))
|
"""
Имя проекта: №91
Номер версии: 1.0
Имя файла: practicum-1(№91).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 24/05/2021
Дата последней модификации: 24/05/2021
Описание: Создать прямоугольную матрицу A, имеющую N строк и M столбцов со случайными элементами. Определить, сколько нулевых элементов содержится в каждом столбце и в каждой строке матрицы. Результат оформить в виде матрицы из N + 1 строк и M + 1 столбцов.
#версия Python: 3.8
"""
import numpy as np
N = 4
M = 5
V = np.random.randint(-10, 10, (N, M))
print("Матрица:\r\n{}\n".format(V))
bool = V == 0
col = np.sum(bool, axis=1)
V = np.insert(V, M, col, axis=1)
row = np.append(np.sum(bool, axis=0), 0)
V = np.insert(V, N, row, axis=0)
print("Новая матрица:\r\n{}\n".format(V))
|
"""
Имя проекта: №38
Номер версии: 1.0
Имя файла: practicum-1(№38).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 28/11/2020
Дата последней модификации: 28/11/2020
Дан одномерный массив числовых значений, насчитывающий N элементов.Исключить из него M элементов, начиная с позиции K
Описание: Решение задач № 38 практикума № 1
#версия Python: 3.6
"""
"""
Оригинал публикации: Практикум №1 - набиваем руку (Бизнес-информатика 2020)
"""
import numpy as np
import array
import random
N = int(input("Введите количество элементов массива "))
K = int(input("Позиция K "))
M = int(input("количество элементов для вычитания "))
A = [random.randint(0, 100) for i in range(0, N)]
print(A)
A.insert(K,M)
print(A)
A.delete(K,M)
|
"""
Имя проекта: №29
Номер версии: 1.0
Имя файла: practicum-1(№29).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 26/11/2020
Дата последней модификации: 26/11/2020
Известен ГОД. Определить, будет ли этот год високосным, и к какому веку этот год относится
Описание: Решение задач № 29 практикума № 1
#версия Python: 3.6
"""
"""
Оригинал публикации: Практикум №1 - набиваем руку (Бизнес-информатика 2020)
"""
X = int(input("Введите год для проверки:"))
if (X % 4 == 0 and X % 100 != 0) or (X % 400 == 0):
print("Год невисокосный:")
else:
print("Год високосный")
if X % 100 == 0:
X = X // 100
print(X," век")
elif X % 100 != 0:
X = (X // 100) + 1
print(X," век")
|
"""
Имя проекта: №82
Номер версии: 1.0
Имя файла: practicum-1(№82).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 24/05/2021
Дата последней модификации: 24/05/2021
Описание:Создать прямоугольную матрицу A, имеющую N строк и M столбцов со случайными элементами. Все элементы имеют целый тип. Дано целое число H. Определить, какие столбцы имеют хотя бы одно такое число, а какие не имеют.
#версия Python: 3.8
"""
import numpy as np
k=1
n=3
m=4
b = np.arange(1,13).reshape(n,m)
print (b,end='\n\n')
for i in range (1,n):
for j in range(k,m-1):
b[i][j]=b[i][j]
print (b,end='\n\n')
|
"""
Имя проекта: №56
Номер версии: 1.0
Имя файла: practicum-1(№56).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 18/12/2020
Дата последней модификации: 18/12/2020
Описание: Решение задач № 56 практикума № 1
описание: Заданы M строк символов, которые вводятся с клавиатуры. Напечатать все центральные буквы строк нечетной длины.
#версия Python: 3.6
"""
"""
Оригинал публикации: Практикум №1 - набиваем руку (Бизнес-информатика 2020)
"""
import math
M = 2
list_strings = []
for i in range(0, M):
print("Введите строку:", end=' ')
list_strings.append(input())
for string in list_strings:
strlen = len(string)
if strlen % 2 != 0:
print(string[math.ceil(strlen/2) - 1])
|
"""
Имя проекта: №19
Номер версии: 1.0
Имя файла: practicum-1(№19).py
Автор: 2020 © Н.Д.Кислицын, Челябинск
Лицензия использования: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
Дата создания: 21/11/2020
Дата последней модификации: 21/11/2020
Даный вещественные числа: X.Y.Z. Определить, существует ли треугольник с такими длинами сторон и если существует, будет ли он прямоугольным
Описание: Решение задач № 19 практикума № 1
#версия Python: 3.6
"""
"""
Оригинал публикации: Практикум №1 - набиваем руку (Бизнес-информатика 2020)
"""
X = int(input("сторона A:"))
Y = int(input("Сторона B:"))
Z = int(input("Сторона C:"))
if (X+Y <=Z) or (Y+Z <=X) or (Z+X <= Y):
print("Треугольника с такими сторонами не существует:")
if (X > Y and X > Z) and (X**2 == Y**2 + Z**2):
print("Треугольник прямоугольный:")
elif (Y > X and Y > Z) and (Y ** 2 == X ** 2 + Z ** 2):
print("Труегольник прямоугольный")
elif (Z > Y and Z > X) and (Z ** 2 == Y ** 2 + X ** 2):
print("Труегольник прямоугольный:")
else:
print("Труегольник не прямоугольный:")
|
"""Define the main controller."""
from typing import List
from models.deck import Deck
from models.player import Player
class Controller:
"""Main controller."""
def __init__(self, deck: Deck, view, checker_strategy):
"""Has a deck, a list of players and a view."""
# models
self.players: List[Player] = []
self.deck = deck
# views
self.view = view
# check strategy
self.checker_strategy = checker_strategy
def get_players(self):
while len(self.players) < 5: # nombre magique
name = self.view.prompt_for_player()
if not name:
return
player = Player(name)
self.players.append(player)
def evaluate_game(self):
"""Evaluate the game."""
return self.checker_strategy.check(self.players)
def rebuild_deck(self):
"""Rebuild the deck."""
for player in self.players:
while player.hand:
card = player.hand.pop()
card.is_face_up = False
self.deck.append(card)
self.deck.shuffle()
def start_game(self):
"""Shuffle the deck and makes the players draw a card."""
self.deck.shuffle()
for player in self.players:
card = self.deck.draw_card()
if card:
player.hand.append(card)
def run(self):
self.get_players()
running = True
while running:
self.start_game()
for player in self.players:
self.view.show_player_hand(player.name, player.hand)
self.view.prompt_for_flip_cards()
for player in self.players:
for card in player.hand:
card.is_face_up = True
self.view.show_player_hand(player.name, player.hand)
self.view.show_winner(self.evaluate_game())
running = self.view.prompt_for_new_game()
self.rebuild_deck()
|
from .charclass import count_digits
def is_valid_day (val):
""" Checks whether or not a two-digit string is a valid date day.
Args:
val (str): The string to check.
Returns:
bool: True if the string is a valid date day, otherwise false.
"""
if len(val) == 2 and count_digits(val) == 2:
day = int(val)
return day > 0 and day < 32
return False
def is_valid_month (val):
""" Checks whether or not a two-digit string is a valid date month.
Args:
val (str): The string to check.
Returns:
bool: True if the string is a valid date month, otherwise false.
"""
if len(val) == 2 and count_digits(val) == 2:
month = int(val)
return month > 0 and month < 13
return False
def is_ddmmyy (val):
""" Checks whether or not a six-digit string is a valid ddmmyy date.
Args:
val (str): The string to check.
Returns:
bool: True if the string is a valid ddmmyy date, otherwise false.
"""
if len(val) == 6 and count_digits(val) == 6:
return is_valid_day(val[0:2]) and is_valid_month(val[2:4])
return False
def is_mmddyy (val):
""" Checks whether or not a six-digit string is a valid mmddyy date.
Args:
val (str): The string to check.
Returns:
bool: True if the string is a valid mmddyy date, otherwise false.
"""
if len(val) == 6 and count_digits(val) == 6:
return is_valid_day(val[2:4]) and is_valid_month(val[0:2])
return False
def is_yymmdd (val):
""" Checks whether or not a six-digit string is a valid yymmdd date.
Args:
val (str): The string to check.
Returns:
bool: True if the string is a valid yymmdd date, otherwise false.
"""
if len(val) == 6 and count_digits(val) == 6:
return is_valid_day(val[2:4]) and is_valid_month(val[4:6])
return False
def is_date (val):
""" Checks whether or not a six-digit string is a valid date.
Args:
val (str): The string to check.
Returns:
bool: True if the string is a valid date, otherwise false.
"""
return is_ddmmyy(val) or is_mmddyy(val) or is_yymmdd(val)
|
#!/usr/bin/env python
"""circle class --
fill this in so it will pass all the tests.
"""
import math
class Circle(object):
def __init__(self, x):
self._radius = x
self._diameter = x * 2
def _getradius(self):
return self._radius
def _setradius(self, value):
self._radius = value
self._diameter = value * 2
radius = property(_getradius, _setradius)
def _getdiameter(self):
return self._diameter
def _setdiameter(self, value):
self._diameter = value
self._radius = value / 2
diameter = property(_getdiameter, _setdiameter)
def _getarea(self):
return math.pi * self._radius**2
area = property(_getarea)
##extra credit
@classmethod
def from_diameter(cls, y):
c = cls(x=y/2)
c.diameter = y
c.radius = y / 2
return c
def __str__(self):
return 'Circle with radius: %.6f' % self.radius
def __repr__(self):
return 'Circle(%i)' % self.radius
def __add__(self, other):
return Circle(self.radius + other.radius)
def __mul__(self, other):
return Circle(self.radius * other)
def __eq__(self, other):
return self.radius == other.radius
def __ge__(self, other):
return self.radius >= other.radius
# def __le__(self, other):
# return self.radius <= other.radius
def __lt__(self, other):
return self.radius < other.radius
|
#!/usr/bin/env python
def count_evens(nums):
return len([x for x in nums if not x % 2])
nums = [2, 1, 2, 3, 4]
print count_evens(nums)
|
from datetime import datetime
from aplication.salary import calculate_salary
def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
current_datetime = datetime.now()
print("Текущая дата и время: ",current_datetime)
current_date = datetime.now().date()
print("Текущая дата: ", current_date)
print("\nВывод отдельных атрибут:")
print("год: ", current_datetime.year) # 2019
print("месяц: ",current_datetime.month) # 12
print("день: ",current_datetime.day) # 13
print("часы: ",current_datetime.hour) # 12
print("минуты: ",current_datetime.minute) # 18
print("секунды: ",current_datetime.second) # 18
print("Микросекунды: ",current_datetime.microsecond) # 290623
print("Общая сумма заработной платы в рублях: ", calculate_salary())
|
#!/usr/bin/env python
import random
import sys
print 'Print out min and max from a list of numbers'
list = random.sample(range(1, 100), 20)
print list
min = sys.maxint
max = -1
for num in list:
if num < min:
min = num
if num > max:
max = num
print 'Min: ' + str(min)
print 'Max: ' + str(max)
|
# Uses python3
import argparse
import datetime
import random
import sys
# def get_majority_element_fast(nrcall, a, left, right):
# # if array is only 2 elements long, the base case is reached
# # and a majority element is determined
# if left == right:
# print('call ' + str(nrcall) + ': ' + str(left) + ' ' + str(right) )
# print('return ' + str(nrcall) + ': ' + str(a[left]))
# print('-----')
# return a[left]
# if left + 1 == right:
# if a[left] == a[right]:
# print('call ' + str(nrcall) + ': ' + str(left) + ' ' + str(right) )
# print('return A2 ' + str(nrcall) + ': ' + str(a[left]))
# print('-----')
# return a[left]
# else:
# print('call ' + str(nrcall) + ': ' + str(left) + ' ' + str(right) )
# print('return ' + str(nrcall) + ': -1')
# print('-----')
# return -1
# # in every other case
# # split array in half and determine majority on each halves
# mid = int(left + (right - left) / 2)
# length_left_halve = mid - left + 1
# length_right_halve = right - (mid + 1) + 1
# majority_left_halve = get_majority_element_fast(nrcall+1, a, left, mid)
# majority_right_halve = get_majority_element_fast(nrcall+1, a, mid+1, right)
# print('left_length is ' + str(length_left_halve))
# print('right_length is ' + str(length_right_halve))
# if length_left_halve > length_right_halve:
# print('call ' + str(nrcall) + ': ' + str(left) + ' ' + str(right) )
# print('return X: ' + str(nrcall) + ': ' + str(majority_left_halve))
# print('-----')
# return majority_left_halve
# elif length_right_halve > length_left_halve:
# print('call ' + str(nrcall) + ': ' + str(left) + ' ' + str(right) )
# print('return Y: ' + str(nrcall) + ': ' + str(majority_right_halve))
# print('-----')
# return majority_right_halve
# if majority_left_halve == -1 and majority_right_halve >= 0:
# return majority_right_halve
# elif majority_right_halve == -1 and majority_left_halve >= 0:
# return majority_left_halve
# if majority_left_halve == majority_right_halve:
# print('call ' + str(nrcall) + ': ' + str(left) + ' ' + str(right) )
# print('return B: ' + str(nrcall) + ': ' + str(majority_left_halve))
# print('-----')
# return majority_left_halve
# else:
# print('call ' + str(nrcall) + ': ' + str(left) + ' ' + str(right) )
# print('return C: ' + str(nrcall) + ': -1')
# print('-----')
# return -1
def get_majority_element_naive(a, left, right):
count = {}
for i in range(0, len(a)):
if a[i] in count:
count[a[i]] += 1
else:
count[a[i]] = 1
#print(count)
#print(max(count.values()))
#print(int(len(a)/2))
if (max(count.values()) > int(len(a)/2)):
return 1
else:
return -1
if __name__ == '__main__':
version = '0.1'
date = '2018-03-18'
parser = argparse.ArgumentParser(description='majority element',
epilog='author: [email protected] | version: ' + version + ' | date: ' + date)
# parser.add_argument('--stresstest', action='store_true',
# help='perform a stress test')
# parser.add_argument('--fast', action='store_true',
# help='use the fast algorithm')
# parser.add_argument('--naive', action='store_true',
# help='use the naive algorithm')
args = parser.parse_args()
# # perform stress test?
# if args.stresstest:
# while(True):
# n = random.randint(1, 5)
# print(n)
# a = []
# createSequenceWithMajority = bool(random.getrandbits(1))
# if(createSequenceWithMajority):
# print('creating a list with a majority element')
# # how often should the majority element be put in list
# amountMajorityElement = random.randint(int(n/2+1), n)
# # how often the other elements
# amountOtherElements = n - amountMajorityElement
# # what should the majority element be
# majorityElement = random.randint(0, 100)
# # put the majority element in list
# a = [majorityElement] * amountMajorityElement
# # fill list with other random elements
# for i in range(0, amountOtherElements):
# a.append(random.randint(0, 100))
# else:
# print('creating a list withOUT a majority element')
# # fill list with other random elements
# for i in range(0, n):
# a.append(random.randint(0, 100))
# # shuffle list
# random.shuffle(a)
# # print list
# print(' '.join(str(lulu) for lulu in a ))
# # run the algos
# current_time1 = datetime.datetime.now()
# res1 = get_majority_element_naive(a, 0, len(a)-1)
# res_naive = 0
# if res1 != -1:
# res_naive = 1
# current_time2 = datetime.datetime.now()
# res2 = get_majority_element_fast(1, a, 0, len(a)-1)
# res_fast = 0
# if res2 != -1:
# res_fast = 1
# current_time3 = datetime.datetime.now()
# if res_naive != res_fast:
# print("ERROR: result naive: " + str(res_naive))
# print("ERROR: result fast: " + str(res_fast))
# break
# else:
# print('OK: ' + str(res_naive))
# print('time consumed: naive:' + str(current_time2-current_time1) + ' fast:' + str(current_time3-current_time2))
# print('------')
# elif args.fast:
# input = sys.stdin.read()
# n, *a = list(map(int, input.split()))
# majority_element = get_majority_element_fast(1, a, 0, n-1)
# if majority_element != -1:
# #print('1 majority element is ' + str(majority_element))
# print(1)
# else:
# print(0)
# elif args.naive:
# input = sys.stdin.read()
# n, *a = list(map(int, input.split()))
# if get_majority_element_naive(a, 0, n-1) != -1:
# print(1)
# else:
# print(0)
# # this is called when no arguments are used
# else:
# input = sys.stdin.read()
# n, *a = list(map(int, input.split()))
# if get_majority_element_fast(1, a, 0, n-1) != -1:
# print(1)
# else:
# print(0)
input = sys.stdin.read()
n, *a = list(map(int, input.split()))
if get_majority_element_naive(a, 0, n-1) != -1:
print(1)
else:
print(0)
# original programming assignment
'''
### 4.2 Majority Element
#### Problem Introduction
Majority rule is a decision rule that selects the alternative which has a majority, that is, more than half the votes. Given a sequence of elements a_1 , a_2 , . . . , a_n , you would like to check whether it contains an element that appears more than n/2 times. A naive way to do this is the following.
```
MajorityElement(a_1 , a_2 , . . . , a_n ):
for i from 1 to n:
currentElement ← a_i
count ← 0
for j from 1 to n:
if a j = currentElement:
count ← count + 1
if count > n/2:
return a_i
return “no majority element”
```
The running time of this algorithm is quadratic. Your goal is to use the divide-and-conquer technique to
design an O(n log n) algorithm.
#### Problem Description
**Task:** The goal in this code problem is to check whether an input sequence contains a majority element.
**Input Format:** The first line contains an integer n, the next one contains a sequence of n non-negative
integers a_0, a_1, . . . , a_n−1 .
**Constraints:** 1 ≤ n ≤ 10^5 ; 0 ≤ a_i ≤ 10^9 for all 0 ≤ i < n.
**Output Format:** Output 1 if the sequence contains an element that appears strictly more than n/2 times,
and 0 otherwise.
#### Sample 1
*Input:*
5
2 3 9 2 2
*Output:*
1
2 is the majority element.
#### Sample 2
*Input:*
4
1 2 3 4
*Output:*
0
There is no majority element in this sequence.
#### Sample 3
*Input:*
4
1 2 31
*Output:*
0
This sequence also does not have a majority element (note that the element 1 appears twice and hence
is not a majority element).
#### What To Do
This problem can be solved by the divide-and-conquer algorithm in time O(n log n). Indeed, if a sequence of length n contains a majority element, then the same element is also a majority element for one of its halves. Thus, to solve this problem you first split a given sequence into halves and make two recursive calls. Do you see how to combine the results of two recursive calls?
It is interesting to note that this problem can also be solved in O(n) time by a more advanced (non-divide-and-conquer) algorithm that just scans the given sequence twice.
#### Implementation in Python
'''
|
# Uses python3
import argparse
import random
import sys
import datetime
from collections import namedtuple
def getGreaterOrEqual(digit, maxDigit):
a = str(digit) + str(maxDigit)
b = str(maxDigit) + str(digit)
if a > b:
return digit
else:
return maxDigit
def largest_number(a):
#write your code here
res = ''
while(len(a) > 0):
maxDigit = -9999
for digit in a:
maxDigit = getGreaterOrEqual(digit, maxDigit)
res += maxDigit
#print('remove digit ' + str(maxDigit) + ' from list ' + str(a))
a.remove(str(maxDigit))
return res
if __name__ == "__main__":
version = '0.1'
date = '2018-03-13'
parser = argparse.ArgumentParser(description='different summands',
epilog='author: [email protected] | version: ' + version + ' | date: ' + date)
parser.add_argument('--stresstest', action='store_true',
help='perform a stress test')
args = parser.parse_args()
# perform stress test?
if args.stresstest:
while(True):
n = random.randint(1, 10)
print(n)
numbers = []
for i in range(1, n):
numbers.append(str(random.randint(1, 1000)))
for number in numbers:
print(number, end=' ')
print("\n")
current_time1 = datetime.datetime.now()
res = largest_number(numbers)
current_time2 = datetime.datetime.now()
print(res)
print('runtime: ' + str(current_time2-current_time1))
print('------')
# this is called when no arguments are used
else:
input = sys.stdin.read()
data = input.split()
a = data[1:]
print(largest_number(a))
# original programming assignment
'''
### 3.6 Maximum Salary
#### Problem Introduction
As the last question of a successful interview, your boss gives you a few pieces of paper with numbers on it and asks you to compose a largest number from these numbers. The resulting number is going to be your salary, so you are very much interested in maximizing this number.
We considered the following algorithm for composing the largest number out of the given *single-digit numbers*.
```
LargestNumber(Digits):
answer ← empty string
while Digits is not empty:
maxDigit ← −∞
for digit in Digits:
if digit ≥ maxDigit:
maxDigit ← digit
append maxDigit to answer
remove maxDigit from Digits
return answer
```
Unfortunately, this algorithm works only in case the input consists of single-digit numbers. For example, for an input consisting of two integers 23 and 3 (23 is not a single-digit number!) it returns 233, while the largest number is in fact 323. In other words, using the largest number from the input as the first number is not a *safe move*.
The goal in this problem is to tweak the above algorithm so that it works not only for single-digit numbers, but for arbitrary positive integers.
#### Problem Description
**Task:** Compose the largest number out of a set of integers.
**Input Format:** The first line of the input contains an integer n. The second line contains integers
a_1 , a_2 , . . . , a_n .
**Constraints:** 1 ≤ n ≤ 100; 1 ≤ a_i ≤ 10^3 for all 1 ≤ i ≤ n.
**Output Format:** Output the largest number that can be composed out of a_1 , a_2 , . . . , a_n .
#### Sample 1
*Input:*
2
21 2
*Output:*
221
Note that in this case the above algorithm also returns an incorrect answer 212.
#### Sample 2
*Input:*
5
9 4 6 1 9
*Output:*
99641
In this case, the input consists of single-digit numbers only, so the algorithm above computes the right
answer.
#### Sample 3
*Input:*
3
23 39 92
*Output:
923923
As a coincidence, for this input the above algorithm produces the right result, though the input does
not have any single-digit numbers.
#### What To Do?
Interestingly, for solving this problem, all one need to do is to replace the check digit ≥ maxDigit with a call IsGreaterOrEqual(digit, maxDigit) for an appropriately implemented function IsGreaterOrEqual.
For example, IsGreaterOrEqual(2, 21) should return True.
#### Implementation in Python
'''
|
# Uses python3
import argparse
import random
import sys
import datetime
import time
def partition3(a, l, r):
m1 = l
m2 = r
i = l+1
x = a[l]
while(i <= m2):
if a[i] < x:
a[m1], a[i] = a[i], a[m1]
m1 += 1
i += 1
elif a[i] > x:
a[m2], a[i] = a[i], a[m2]
m2 -= 1
else:
i += 1
return m1, m2
def partition2(a, l, r):
x = a[l]
j = l;
for i in range(l + 1, r + 1):
if a[i] <= x:
j += 1
a[i], a[j] = a[j], a[i]
a[l], a[j] = a[j], a[l]
return j
def randomized_quick_sort(partitions, a, l, r):
if l >= r:
return
k = random.randint(l, r)
a[l], a[k] = a[k], a[l]
if partitions == 2:
m = partition2(a, l, r)
randomized_quick_sort(partitions, a, l, m-1);
randomized_quick_sort(partitions, a, m+1, r);
elif partitions == 3:
m1, m2 = partition3(a, l, r)
print('m1=' + str(m1) + ' m2=' + str(m2))
#time.sleep(5)
randomized_quick_sort(partitions, a, l, m1-1);
randomized_quick_sort(partitions, a, m2+1, r);
else:
print('only 2 or 3 partitions allowed')
sys.exit(1)
return a
if __name__ == "__main__":
version = '0.1'
date = '2018-03-19'
parser = argparse.ArgumentParser(description='majority element',
epilog='author: [email protected] | version: ' + version + ' | date: ' + date)
parser.add_argument('--stresstest', action='store_true',
help='perform a stress test comparing the results of the 2-way partiotioned with the 3-way-partioned algorithm')
parser.add_argument('--stresstest_qs3', action='store_true',
help='perform a stress test only on the 3-way partioned algorithm')
parser.add_argument('--qs2', action='store_true',
help='use the quicksort algorithm with 2 partitions')
parser.add_argument('--qs3', action='store_true',
help='use the quicksort algorithm with 3 partitions')
args = parser.parse_args()
# perform stress test?
if args.stresstest:
while(True):
# how long should the list be
n = random.randint(10, 100)
print(n)
a = []
# how often should the majority element be put in list
amountUniqeElements = random.randint(2, min(int(n/3), 50))
uniqueElements = []
print('generating a list with ' + str(amountUniqeElements) + ' unique elements')
# create elements
for i in range(0, amountUniqeElements):
rand_int = random.randint(1, 1000)
uniqueElements.append(rand_int)
#print(str(i) + ' ' + str(rand_int))
secure_random = random.SystemRandom()
# create list
for i in range(0, n):
random_choice = secure_random.choice(uniqueElements)
a.append(random_choice)
#print('adding unique element to list: ' + str(random_choice))
# shuffle list
random.shuffle(a)
#print(a)
current_time1 = datetime.datetime.now()
res1 = randomized_quick_sort(2, list(a), 0, len(a)-1)
#print(res1)
current_time2 = datetime.datetime.now()
res2 = randomized_quick_sort(3, list(a), 0, len(a)-1)
#print(res2)
current_time3 = datetime.datetime.now()
if(set(res1)^set(res2)):
print("ALARM: result quicksort with 2 partitions: " + ' '.join(str(res1)))
print("ALARM: result quicksort with 3 partitions: " + ' '.join(str(res2)))
break
else:
print('OK:' + str(res1))
print('time consumed: qs2:' + str(current_time2-current_time1) + ' qs3:' + str(current_time3-current_time2))
print('------')
elif args.stresstest_qs3:
while(True):
# how long should the list be
n = random.randint(10, 10)
print(n)
a = []
# how often should the majority element be put in list
amountUniqeElements = random.randint(1, min(int(n/3), 3))
uniqueElements = []
print('generating a list with ' + str(amountUniqeElements) + ' unique elements')
# create elements
for i in range(0, amountUniqeElements):
rand_int = random.randint(1, 100)
uniqueElements.append(rand_int)
#print(str(i) + ' ' + str(rand_int))
secure_random = random.SystemRandom()
# create list
for i in range(0, n):
random_choice = secure_random.choice(uniqueElements)
a.append(random_choice)
#print('adding unique element to list: ' + str(random_choice))
# shuffle list
random.shuffle(a)
#print(a)
current_time1 = datetime.datetime.now()
res2 = randomized_quick_sort(3, list(a), 0, len(a)-1)
#print(res2)
current_time3 = datetime.datetime.now()
print('OK:' + str(res2))
print('time consumed: qs3:' + str(current_time3-current_time1))
print('------')
elif args.qs3:
input = sys.stdin.read()
n, *a = list(map(int, input.split()))
randomized_quick_sort(3, a, 0, n - 1)
for x in a:
print(x, end=' ')
elif args.qs2:
input = sys.stdin.read()
n, *a = list(map(int, input.split()))
randomized_quick_sort(2, a, 0, n - 1)
for x in a:
print(x, end=' ')
# this is called when no arguments are used
else:
input = sys.stdin.read()
n, *a = list(map(int, input.split()))
# to check the coursera - algorithmic toolbox grader, I use the build in function in python for sorting
#a = sorted(list(a))
# instead of my own improved quicksort function
randomized_quick_sort(2, a, 0, n - 1)
for x in a:
print(x, end=' ')
# original programming assignment
'''
### 4.3 Improving Quick Sort
#### Problem Introduction
The goal in this problem is to redesign a given implementation of the random-
ized quick sort algorithm so that it works fast even on sequences containing
many equal elements.
#### Problem Description
**Task:** To force the given implementation of the quick sort algorithm to efficiently process sequences with
few unique elements, your goal is replace a 2-way partition with a 3-way partition. That is, your new
partition procedure should partition the array into three parts: < x part, = x part, and > x part.
**Input Format:** The first line of the input contains an integer n. The next line contains a sequence of n
integers a_0 , a_1 , . . . , a_n−1 .
**Constraints:** 1 ≤ n ≤ 10^5 ; 1 ≤ a_i ≤ 10^9 for all 0 ≤ i < n.
**Output Format:** Output this sequence sorted in non-decreasing order.
#### Sample 1
*Input:*
5
2 3 9 2 2
*Output:*
2 2 2 3 9
#### What To Do
Implement a 3-way partition procedure and then replace a call to the 2-way partition procedure by a call to
the 3-way partition procedure.
#### Implementation in Python
'''
|
# Uses python3
import argparse
import random
import sys
import datetime
import string
def knapsack_dynamic_programming(capacity, bars, solutiontable=False):
n = len(bars)
# create the matrix
# rows => gold_bars, columns => weight
matrix = [[None] * (capacity+1) for i in range(n+1)]
# initialize all values in row 0 with 0
matrix[0] = [0] * len(matrix[0])
# initialize all values in column 0 with 0
for i in range(0, len(matrix)):
matrix[i][0] = 0
for i in range(1, n+1):
for w in range(1, capacity+1):
matrix[i][w] = matrix[i-1][w]
if bars[i-1] <= w:
val = matrix[i-1][w-bars[i-1]] + bars[i-1]
# if existent value of cell is smaller, use the new value
if matrix[i][w] < val:
matrix[i][w] = val
if solutiontable:
for row in matrix:
print(row)
return matrix[n][capacity]
def knapsack_greedy(W, w):
result = 0
for x in w:
if result + x <= W:
result = result + x
return result
if __name__ == "__main__":
version = '0.1'
date = '2018-04-04'
parser = argparse.ArgumentParser(description='knapsack without repetitions and without fractions',
epilog='author: [email protected] | version: ' + version + ' | date: ' + date)
parser.add_argument('--stresstest', action='store_true',
help='perform a stress test')
parser.add_argument('--solutiontable', action='store_true',
help='print the solution table along with the result')
args = parser.parse_args()
# perform stress test?
if args.stresstest:
while(True):
capacity = random.randint(10, 20)
amount_gold_bars = random.randint(capacity//5, capacity//2)
print(str(capacity) + ' ' + str(amount_gold_bars))
gold_bars = []
for gold_bar in range(0, amount_gold_bars):
# print('min size: ' + str(capacity//8))
# print('max size: ' + str(capacity//3))
size_gold_bar = random.randint(capacity//8, capacity//3)
gold_bars.append(size_gold_bar)
for gold_bar in gold_bars:
print(gold_bar, end=' ')
print()
current_time1 = datetime.datetime.now()
maxweight = knapsack_dynamic_programming(capacity, gold_bars, solutiontable=True)
current_time2 = datetime.datetime.now()
print('result: ' + str(maxweight))
print('runtime: ' + str(current_time2-current_time1))
print('------')
# this is called when no arguments are used
else:
input = sys.stdin.read()
W, n, *w = list(map(int, input.split()))
if args.solutiontable:
print(knapsack_dynamic_programming(W, w, solutiontable=True))
else:
print(knapsack_dynamic_programming(W, w, solutiontable=False))
# original programming assignment
'''
### 6.1 Maximum Amount of Gold
#### Problem Introduction
You are given a set of bars of gold and your goal is to take as much gold as possible into your bag. There is just one copy of each bar and for each bar you can either take it or not (hence you cannot take a fraction of a bar).
#### Problem Description
**Task:** Given n gold bars, find the maximum weight of gold that fits into a bag of capacity W .
**Input Format:** The first line of the input contains the capacity W of a knapsack and the number n of bars of gold. The next line contains n integers w_0 , w_1 , . . . , w_n−1 defining the weights of the bars of gold.
**Constraints:** 1 ≤ W ≤ 10^4 ; 1 ≤ n ≤ 300; 0 ≤ w_0 , . . . , w_n−1 ≤ 10^5 .
**Output Format:** Output the maximum weight of gold that fits into a knapsack of capacity W .
#### Sample 1
*Input:*
10 3
1 4 8
*Output:*
9
Here, the sum of the weights of the first and the last bar is equal to 9.
#### Implementation in Python
'''
|
#Uses python3
import sys
#import pydot
import os
class Digraph(object):
'''
Returns a Graph-object
'''
# graph in format 'adjacency list'
adjacencyList = None
# graph in format 'edge list'
edgeList = None
# amount of vertices
count_vertices = 0
# weight
cost = None
# holds the distance from startVertex for all vertices
dist = None
# holds the information of previous vertex for all vertices
prev = None
'''
constructor
create a graph object in adjacency list representation
'''
def __init__(self, edgeListWithCost, count_vertices):
# calc adjacency list
self.adjacencyList = [[] for _ in range(count_vertices)]
self.edgeList = [[] for _ in range(count_vertices)]
self.cost = [[] for _ in range(count_vertices)]
for ((a, b), w) in edgeListWithCost:
self.adjacencyList[a - 1].append(b - 1)
self.cost[a - 1].append(w)
self.edgeList.append([a-1, b-1])
self.count_vertices = count_vertices
'''
bellman-ford algorithm allows to determine shortest paths from startVertex to every other vertex
it run slowlier than the bfs_dijkstra algorithm, graphs with negative edge weights are possible
startVertex: vertex id to start the traverse
returns: True if a negative cycle exists, False if no negative cycle exists
'''
def bfs_bellman_ford_negative_cycle(self, startVertex):
# set dist of all vertices to 'infinity'
#self.dist = [float('inf')] * self.count_vertices
# in some case float(inf) does not work to detect negative cycles
self.dist = [10**19] * self.count_vertices
# set prev for all vertices to none
self.prev = [None] * self.count_vertices
# set dist of startVertex to 0
self.dist[startVertex] = 0
# the shortests paths are found in at most (count_vertices - 1) iterations
# if there is a relaxation on the (count_vertices)th iteration, there must be a negative cycle
last_iteration = False
for i in range(0, self.count_vertices):
if i == self.count_vertices - 1:
last_iteration = True
# relax every edge
for current_vertex in range(0, self.count_vertices):
# go through all edges that leads away from the current vertex
for j in range(0, len(self.adjacencyList[current_vertex])):
# for readability: set the neighbor vertex id
pointing_vertex = self.adjacencyList[current_vertex][j]
# for readability: set the cost to travel from current to pointing vertex
cost_from_current_to_pointing_vertex = self.cost[current_vertex][j]
# if a shorter path (current -> pointing vertex) is found, than has been determined to date...
# perform relaxation if ...
if self.dist[pointing_vertex] > self.dist[current_vertex] + cost_from_current_to_pointing_vertex:
# if there is a relaxation on the last iteration, then there must exist a negative cycle
if last_iteration is True:
return True
# ... store it in the dist list
self.dist[pointing_vertex] = self.dist[current_vertex] + cost_from_current_to_pointing_vertex
# store the current vertex that has led to the pointing vertex
self.prev[pointing_vertex] = current_vertex
# if bellman-ford runs through all relaxations in count_vertices-1 times, there is no negative cycle in the graph
return False
'''
bellman-ford algorithm allows to determine shortest paths from startVertex to every other vertex
it run slowlier than the bfs_dijkstra algorithm, graphs with negative edge weights are possible
no negative cycles are allowed
startVertex: vertex id to start the traverse
returns: -
'''
def bfs_bellman_ford(self, startVertex):
# set dist of all vertices to 'infinity'
self.dist = [float('inf')] * self.count_vertices
# set prev for all vertices to none
self.prev = [None] * self.count_vertices
# set dist of startVertex to 0
self.dist[startVertex] = 0
# repeat for count_vertices - 1 times
for i in range(0, self.count_vertices - 1):
# relax every edge
for current_vertex in range(0, self.count_vertices):
# go through all edges that leads away from the current vertex
for j in range(0, len(self.adjacencyList[current_vertex])):
# for readability: set the neighbor vertex id
pointing_vertex = self.adjacencyList[current_vertex][j]
# for readability: set the cost to travel from current to pointing vertex
cost_from_current_to_pointing_vertex = self.cost[current_vertex][j]
# if a shorter path (current -> pointing vertex) is found, than has been determined to date...
if self.dist[pointing_vertex] > self.dist[current_vertex] + cost_from_current_to_pointing_vertex:
# ... store it in the dist list
self.dist[pointing_vertex] = self.dist[current_vertex] + cost_from_current_to_pointing_vertex
# store the current vertex that has led to the pointing vertex
self.prev[pointing_vertex] = current_vertex
'''
dijkstra algorithm for determining shortest paths from startVertex to every other vertex
it runs faster than the bellman-ford algorithm, but it cannot handle negative edge weights (cost)
startVertex: vertex id to start the traverse
returns: -
'''
def bfs_dijkstra(self, startVertex):
# set dist of all vertices to 'infinity'
self.dist = [float('inf')] * self.count_vertices
# set prev for all vertices to none
self.prev = [None] * self.count_vertices
# set dist of startVertex to 0
self.dist[startVertex] = 0
# create a datastructure for storing dist values
# it works as some kind of queue which makes it easy to retrieve the vertex with the smallest dist value
H = self.dist.copy()
# H.append(None)
# initialize infinity to avoid permanent initialization in the while condition
infinity = float('inf')
# while there are still vertices in the queue with a distance != infinity
# in the queue H 'infinity' is the marker that the optimal distance for the corresponding vertex has already been found)
# unlike in self.dist. there infitity means the vertex is unreachable from startVertex
while( len([x for x in H if x < infinity]) > 0 ):
# extract the vertex with the minimum distance as current vertex
current_vertex = min(range(len(H)), key=H.__getitem__)
# and set the entry to 'infinity' to mark that the real minimum distance of this vertex has been found
H[current_vertex] = float('inf')
# go through all edges that leads away from the current vertex
for i in range(0, len(self.adjacencyList[current_vertex])):
# for readability: set the neighbor vertex id
pointing_vertex = self.adjacencyList[current_vertex][i]
# for readability: set the cost to travel from current to pointing vertex
cost_from_current_to_pointing_vertex = self.cost[current_vertex][i]
# if a shorter path (current -> pointing vertex) is found, than has been determined to date...
if self.dist[pointing_vertex] > self.dist[current_vertex] + cost_from_current_to_pointing_vertex:
# ... store it in the dist list
self.dist[pointing_vertex] = self.dist[current_vertex] + cost_from_current_to_pointing_vertex
# store the current vertex that has led to the pointing vertex
self.prev[pointing_vertex] = current_vertex
# update the dist value in the queue.
H[pointing_vertex] = self.dist[pointing_vertex]
'''
determine if the graph is 'bipartite'
return: 0 if not, 1 if it is bipartite
'''
def minDistance(self, startVertex, targetVertex):
# perform the dijkstra algorithm (a modification of Breadth-First-Search) to determine the shortest paths from startVertex to every vertex in the graph
self.bfs_dijkstra(startVertex)
# after the dijkstra all dist values in self.dist are the optimal real distances from startVertex
if (self.dist[targetVertex] == float('inf')):
return -1
else:
return self.dist[targetVertex]
'''
determine whether graph has a negative cycle or not by using a modified Bellman-Ford Algorithm
return: 0 if no negative cycle, 1 if a negative cycle is detected
'''
def hasNegativeCycle(self):
if self.bfs_bellman_ford_negative_cycle(0):
return 1
else:
return 0
def plot(self, pngfile):
# create a pydot graph
pydot_graph = pydot.Dot(graph_type="graph")
# add all vertices
for i in range(0, self.count_vertices):
pydot_graph.add_node(pydot.Node(i+1, label=i+1))
for edge in self.edgeList:
pydot_edge = pydot.Edge(edge[0], edge[1])
pydot_graph.add_edge(pydot_edge)
pydot_graph.write_png(pngfile)
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n, m = data[0:2]
data = data[2:]
edges = list(zip(zip(data[0:(3 * m):3], data[1:(3 * m):3]), data[2:(3 * m):3]))
digraph = Digraph(edges, n)
# data = data[3 * m:]
# startVertex, targetVertext = data[0] - 1, data[1] - 1
# print(digraph.minDistance(startVertex, targetVertext))
print(digraph.hasNegativeCycle())
|
import turtle
import random
x=turtle.Turtle()
colors=['red','blue','green','purple','yellow','orange','black']
x.color('red','blue')
x.width(5)
x.begin_fill()
x.circle(50)
x.end_fill()
x.penup()
x.forward(150)
x.pendown()
x.color('yellow','black')
x.begin_fill()
for y in range(4):
x.forward(100)
x.right(90)
x.end_fill()
for y in range(5):
randColor=random.randrange(0,len(colors))
x.color(colors[randColor],colors[random.randrange(0,len(colors))])
rand1=random.randrange(-300,300)
rand2=random.randrange(-300,300)
x.penup()
x.setpos((rand1,rand2))
x.pendown()
x.begin_fill()
x.circle((random.randrange(0,80)))
x.end_fill()
|
#coding=utf-8
import math
x=input("请输入年纪:")
# floor函数将一个数取整为小于等于该数的最小的整数
# 与floor相对的函数是ceil,可以将给定的数值转换成为大于或者等于它的最小整数
age=int(math.floor(x))
print (u"年龄最小是%d" %age)
age2=math.ceil(x)
print (u"年龄最大是%d" %age2)
# 在确定不会导入多个同名函数(从不同模块导入)的情况下,可以使用import
# 的另外一种形式:
from math import sqrt
print sqrt(9)
|
#coding=utf-8
# 列表推导式是利用其他列表创建新列表的一种方法
print [x*x for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 只打印能被3整除的平方数
print [x*x for x in range(10) if x%3==0]
# [0, 9, 36, 81]
# 也可以增加更多for语句的部分:
print [(x,y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
# 作为对比,下面的代码使用两个for语句创建了相同的列表:
result=[]
for x in range(3):
for y in range(3):
result.append((x,y))
################################
# 也可以结合if子句联合使用,
girls=['alice','bernice','clarice']
boys=['chris','arrnold','bob']
print [b+'+'+g for b in boys for g in girls if b[0]==g[0]]
# ['chris+clarice', 'arrnold+alice', 'bob+bernice']
# 这样就得到了那些名字首字母相同的男孩和女孩
###更优方案
# 这个程序建造了一个叫做letterGirl的字典,其中每一项都把单字母作为键,以女孩名字组成的列表作为值。
letterGirls={}
for girl in girls:
# 如果字典中包含有给定键,则返回该键对应的值,否则返回为该键设置的值。
letterGirls.setdefault(girl[0],[]).append(girl)
print [b+'+'+g for b in boys for g in letterGirls[b[0]]]
|
#coding=utf-8
string1='Hello'
# 因为字符串不能像列表一样被修改,所以有时候根据字符串创建列表会很有用。list函数可以实现这个操作
# list函数适用于所有类型的序列,而不只是字符串
list1=list(string1)
# 可以使用下面的表达式将一个由字符组成的列表转换成为字符串:
string2=''.join(list1)
print list1
print string2
|
#coding=utf-8
name=list('Perl')
print name
# 输出:['P', 'e', 'r', 'l']
name[2:]=list('ar')
print name
# 输出:['P', 'e', 'a', 'r']
# 使用分片赋值时,可以使用与原序列不等长的序列将分片替换
name2=list('Lilei')
name2[1:]=list('python2.7')
print name2
# 分片赋值语句可以不需要替换原有元素的情况下插入新的元素
numbers=[1,5]
numbers[1:1]=[2,3,4]
print numbers
# 输出:[1, 2, 3, 4, 5]
# 通过分片赋值来删除元素也是可行的
numbers2=[1,2,3,4,5]
numbers2[1:4]=[]
print numbers2
# 输出:[1, 5]
|
#coding=utf-8
x=1
while x<=100:
print x
x += 1
name=''
# while not name:
# name=raw_input("Please enter your name:")
# print "Hello,%s!"%name
# 如果输入一个空格,程序也会接受这个名字,可以这样修改程序:
while not name or name.isspace():
name=raw_input("Please enter your name:")
print "Hello,%s!"%name
# 或者使用while not name.strip()
|
#coding=utf-8
# str、repr、和反引号是将Python值转换为字符串的3种方法。
# str函数会把值转换为合理形式的字符串
# 而repr会创建一个字符串,它以合法的Python表达式的形式来表示值
# 例:
print repr("Hello world!")
# 输出:'Hello world!'
print str("Hello world!")
# 输出:Hello world!
# repr(x)的功能也可以使用`x`实现(注意,`是反引号,而不是单引号)。
# 在python3.0中,已经不再使用反引号。
# 如果希望打印一个包含数字的句子,那么反引号就很有用了。比如:
temp=5
# 下面这个语句会报错:
# print "The temperature is"+temp
# 这个就可以正常打印:
print "The temperature is "+`temp`
print "The temperature is "+repr(temp)
print "The temperature is "+str(temp)
|
"""
A prison can be represented as a list of cells. Each cell contains exactly one prisoner.
A 1 represents an unlocked cell and a 0 represents a locked cell.
[1, 1, 0, 0, 0, 1, 0] Starting from the leftmost cell,
you are tasked with seeing how many prisoners you can set free, with a catch.
Each time you free a prisoner, the locked cells become unlocked, and the unlocked cells become locked again.
So, if we use the example above:
[1, 1, 0, 0, 0, 1, 0]
You free the prisoner in the 1st cell.
[0, 0, 1, 1, 1, 0, 1]
You free the prisoner in the 3rd cell (2nd one locked).
[1, 1, 0, 0, 0, 1, 0]
You free the prisoner in the 6th cell (3rd, 4th and 5th locked).
[0, 0, 1, 1, 1, 0, 1]
You free the prisoner in the 7th cell - and you are done!
Here, we have freed 4 prisoners in total.
Create a function that, given this unique prison arrangement, returns the number of freed prisoners.
Examples
freed_prisoners([1, 1, 0, 0, 0, 1, 0]) ➞ 4
freed_prisoners([1, 1, 1]) ➞ 1
freed_prisoners([0, 0, 0]) ➞ 0
freed_prisoners([0, 1, 1, 1]) ➞ 0
"""
def freed_prisoners(l):
count = 0
if l[0] == 0:
return 0
for i in range(len(l)):
if l[i] == 1:
count += 1
l = [0 if l[j] == 1 else 1 for j in range(len(l))]
return count
print(freed_prisoners([1, 1, 0, 0, 0, 1, 0]))
print(freed_prisoners([1, 1, 1]))
print(freed_prisoners([0, 0, 0]))
print(freed_prisoners([0, 1, 1, 1]))
|
"""
Mona has created a method to sort a list in ascending order.
Starting from the left of the list, she compares numbers by pairs.
If the first pair is ordered [smaller number, larger number], she moves on.
If the first pair is ordered [larger number, smaller number], she swaps the two integers
before moving on to the next pair. She repeats this process until she reaches the end of the list.
Then, she moves back to the beginning of the list and repeats this process until the entire list is sorted.
If the unsorted list is: [3, 9, 7, 4], she will perform the following steps (note Swaps here refers to cumulative swaps):
She starts with the first pair. [3, 9] is in order, move on. List: [3, 9, 7, 4].
Swaps: 0. [9, 7] is not. Swap. List: [3, 7, 9, 4]. Swaps: 1 [9, 4] is not. Swap. List: [3, 7, 4, 9]. Swaps: 2 Check if list is sorted. It is not, so start over at first pair. [3, 7] is in order, move on. List: [3, 7, 4, 9]. Swaps: 2 [7, 4] is not. Swap. List: [3, 4, 7, 9]. Swaps: 3. [7, 9] is in order, move on. List: [3, 4, 7, 9]. Swaps: 3. Check if list is sorted. It is. End. Sorting the list [3, 9, 7, 4] takes her 3 swaps. Write a function that takes in an unsorted list and returns the number of swaps it takes for the list to be sorted according to Mona's algorithm.
Examples
number_of_swaps([5, 4, 3]) ➞ 3
number_of_swaps([1, 3, 4, 5]) ➞ 0
number_of_swaps([5, 4, 3, 2]) ➞ 6
"""
def swap_counter(l1):
count = 0
while l1 != sorted(l1):
for i in range(0, len(l1)-1):
if l1[i] > l1[i+1]:
count += 1
l1[i], l1[i+1] = l1[i+1], l1[i]
return count
print(swap_counter([5, 4, 3]))
|
"""Create a function that removes all capital letters and punctuation in a string. Return the clean string."""
import string
def clean_string(s):
for i in s:
if i.isupper() or i in string.punctuation:
s = s.replace(i, '')
return s
print(clean_string('HELLO hello hi bye (*)^*&^(*&^(*&^ABCDefg!'))
|
"""Make a function that encrypts a given input with these steps:
Input: "apple"
Step 1: Reverse the input: "elppa"
Step 2: Replace all vowels using the following chart:
a => 0 e => 1 o => 2 u => 3
#"1lpp0"
Step 3: Add "aca" to the end of the word: "1lpp0aca"
Output: "1lpp0aca"
Examples
encrypt("banana") ➞ "0n0n0baca"
encrypt("karaca") ➞ "0c0r0kaca"
encrypt("burak") ➞ "k0r3baca"
encrypt("alpaca") ➞ "0c0pl0aca" """
def encrypt(string):
string = list(string[::-1])
for i in range(len(string)):
if string[i] == 'a':
string[i] = '0'
elif string[i] == 'e':
string[i] = '1'
elif string[i] == 'o':
string[i] = '2'
elif string[i] == 'u':
string[i] = '3'
string = ''.join(string) + 'aca'
return string
print(encrypt('banana'))
print(encrypt('karaca'))
print(encrypt('burak'))
print(encrypt('alpaca'))
|
"""Someone has attempted to censor my strings by replacing every vowel with a *, l*k* th*s. Luckily, I've been able to find the vowels that were removed.
Given a censored string and a string of the censored vowels, return the original uncensored string.
Example
uncensor("Wh*r* d*d my v*w*ls g*?", "eeioeo") ➞ "Where did my vowels go?"
uncensor("abcd", "") ➞ "abcd"
uncensor("*PP*RC*S*", "UEAE") ➞ "UPPERCASE"
"""
def uncensor(string, vowels):
current = 0
string = list(string)
for i in range(len(string)):
if string[i] == '*':
string[i] = vowels[current]
current += 1
return ''.join(string)
print(uncensor("Wh*r* d*d my v*w*ls g*?", "eeioeo"))
print(uncensor("abcd", ""))
print(uncensor("*PP*RC*S*", "UEAE"))
|
"""
Given a string, count all the lowercase letters.
Return a dictionary with the keys as the lowercase letters
and the values as the letters' counts respectively.
The keys should be sorted in alphabetical order.
Example:
Input:
"apple"
Output:
{'a': 1, 'e': 1, 'l': 1, 'p': 2}
"""
def dict_counter(string):
return {letter: string.count(letter) for letter in sorted(set(string))}
print(dict_counter('apple'))
|
from abc import ABC, abstractmethod
class Implementation(ABC):
"""
The Implementation defines the interface for all implementation classes. It
doesn't have to match the Abstraction's interface. In fact, the two
interfaces can be entirely different. Typically the Implementation
interface provides only primitive operations, while the Abstraction defines
higher-level operations based on those primitives.
"""
@abstractmethod
def operation_implementation(self) -> str:
pass
|
from abc import ABC, abstractmethod
from behavioral.visitor.component import ConcreteComponentA, ConcreteComponentB
class Visitor(ABC):
"""
The Visitor Interface declares a set of visiting methods that correspond to
component classes. The signature of a visiting method allows the visitor to
identify the exact class of the component that it's dealing with.
"""
@abstractmethod
def visit_concrete_component_a(self, element: ConcreteComponentA) -> None:
pass
@abstractmethod
def visit_concrete_component_b(self, element: ConcreteComponentB) -> None:
pass
"""
Concrete Visitors implement several versions of the same algorithm, which can
work with all concrete component classes.
You can experience the biggest benefit of the Visitor pattern when using it with
a complex object structure, such as a Composite tree. In this case, it might be
helpful to store some intermediate state of the algorithm while executing
visitor's methods over various objects of the structure.
"""
class ConcreteVisitor1(Visitor):
def visit_concrete_component_a(self, element: ConcreteComponentA) -> None:
print(f"{element.exclusive_method_of_concrete_component_a()} + ConcreteVisitor1")
def visit_concrete_component_b(self, element: ConcreteComponentB) -> None:
print(f"{element.special_method_of_concrete_component_b()} + ConcreteVisitor1")
class ConcreteVisitor2(Visitor):
def visit_concrete_component_a(self, element: ConcreteComponentA) -> None:
print(f"{element.exclusive_method_of_concrete_component_a()} + ConcreteVisitor2")
def visit_concrete_component_b(self, element: ConcreteComponentB) -> None:
print(f"{element.special_method_of_concrete_component_b()} + ConcreteVisitor2")
|
from abc import ABC, abstractmethod, abstractproperty
class Builder(ABC):
"""
The Builder interface specifies methods for creating the different parts of
the Product objects.
"""
@abstractproperty
def product(self) -> None:
pass
@abstractmethod
def produce_part_a(self) -> None:
pass
@abstractmethod
def produce_part_b(self) -> None:
pass
@abstractmethod
def produce_part_c(self) -> None:
pass
|
from abc import abstractmethod
from typing import Any, Optional
from behavioral.chain_responsibility.handler import Handler
class AbstractHandler(Handler):
"""
The default chaining behavior can be implemented inside a base handler
class.
"""
_next_handler: Handler = None
def set_next(self, handler: Handler) -> Handler:
self._next_handler = handler
# Returning a handler from here will let us link handlers in a
# convenient way like this:
# monkey.set_next(squirrel).set_next(dog)
return handler
@abstractmethod
def handle(self, request: Any) -> Optional[str]:
if self._next_handler:
return self._next_handler.handle(request)
return None
|
import numpy as np
import matplotlib.pyplot as plt
def step_function(x):
if x>0:
return 1
else:
return 0
def step_function2(x):
return np.array(x>0, dtype=np.int)
x = np.array([-1.0, 1.0, 2.0])
y = x > 0
y = y.astype(np.int)
print(y)
x = np.arange(-5.0, 5.0, 0.1)
y = step_function2(x)
plt.plot(x,y)
plt.ylim(-0.1,1.1)
plt.show()
def sigmoid(x):
return 1/(1 + np.exp(-x))
x= np.array([-1.0, 1.0, 2.0])
print(sigmoid(x))
x = np.arange(-5.0, 5.0, 0.1)
y = sigmoid(x)
plt.plot(x,y)
plt.ylim(-0.1,1.1)
plt.show()
def relu(x):
return np.maximum(0,x)
|
"""
Created by HerbertAnchovy in September 2017 as part of the 'Object-oriented Programming in Python'
FutureLearn course from the Raspberry Pi Foundation.
See https://www.futurelearn.com/courses/object-oriented-principles for details.
"""
class Item():
"""A class to create an item"""
# Constructor method used to create an Item object
def __init__(self, item_name, item_description):
"""Initialise an item object with name and description attributes"""
self.name = item_name
self.description = item_description
# Getters for the name and description of the item:
def get_name(self):
"""Returns the name of the item"""
return self.name
def get_description(self):
"""Returns the item description"""
return self.description
# Setters for the name and description of the item:
def set_name(self, item_name):
"""Sets the name of the item"""
self.name = item_name
def set_description(self, item_description):
"""Sets the description of the item"""
self.description = item_description
# Output info on item
def describe(self):
"""Describes the item"""
print("In this room is " + self.description + "\n")
|
# cluster companies using their daily stock price movements
# (i.e. the dollar difference between the closing and opening prices for each trading day).
# You are given a NumPy array movements of daily price movements from 2010 to 2015 (obtained from Yahoo! Finance),
# where each row corresponds to a company, and each column corresponds to a trading day.
# DataSet used : company-stock-movements-2010-2015-incl.csv
from sklearn.preprocessing import Normalizer
# Normalizer will separately transform each company's stock price to a relative scale before the clustering begins.
from sklearn.cluster import KMeans
from sklearn.pipeline import make_pipeline
import numpy as np
import pandas as pd
# read file into numpy array
movements = pd.read_csv('dataset/company-stock-movements-2010-2015-incl.csv', header=0, index_col=0)
print(movements.head())
data = movements.values
companies = movements.index.values
print(companies)
# Create a normalizer: normalizer
normalizer = Normalizer()
# Create a KMeans model with 10 clusters: kmeans
kmeans = KMeans(n_clusters=10)
# Make a pipeline chaining normalizer and kmeans: pipeline
pipeline = make_pipeline(normalizer, kmeans)
# Fit pipeline to the daily price movements
pipeline.fit(data)
# Predict the cluster labels: labels
labels = pipeline.predict(data)
# Create a DataFrame aligning labels and companies: df
df = pd.DataFrame({'labels': labels, 'companies': companies})
# Display df sorted by cluster label
print(df.sort_values('labels'))
ct = pd.crosstab(df['labels'], df['companies'])
print(ct)
ct.to_csv('Stock_clustering.csv')
|
# -*- coding:utf-8 -*-
# Tuple
# The item in the tuple can't modify , visited only,it's data type isn't limited.
tuple = ('a string',False,2.5,34)
print tuple
print type(tuple) # print: <type 'tuple'>
print tuple[0]
print tuple[1]
print tuple[2]
print tuple[3]
#print tuple1[4] # Will throw an Index Error:tuple index out of range
print
# List
# The item in the list can be modified and visited, it's data type isn't limited.
list = [True,45,'This is a good day!']
print list
print type(list) #print:<type 'list'>
print list[0]
print list[1]
print list[2]
#print list[4] # Will throw an Index Error:tuple index out of range
print
anotherlist = [1,[2,3,4],True]
print anotherlist
print anotherlist[1][1] #print : 3
print
emptylist = []
print emptylist
print
tuplewithlistitemcannotmodifyalso = ('a string',False,2.5,34,(2,3,'str'),[True,'asdf'])
#tuplewithlistitemcannotmodifyalso[4][0] =False # can't modify also.
print tuplewithlistitemcannotmodifyalso
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.