text
stringlengths 37
1.41M
|
---|
# Write classes for the following class hierarchy:
#
# [Vehicle]->[FlightVehicle]->[Starship]
# | |
# v v
# [GroundVehicle] [Airplane]
# | |
# v v
# [Car] [Motorcycle]
#
# Each class can simply "pass" for its body. The exercise is about setting up
# the hierarchy.
#
# e.g.
#
# class Whatever:
# pass
#
# Put a comment noting which class is the base class
#Base class
class Vehicle:
"""Vehicle creates a generic Vehicle object."""
pass
class FlightVehicle(Vehicle):
"""FlightVehicle inherits from Vehicle"""
def __init__(self):
super(Vehicle, self).__init__()
self.arg = arg
pass
class Airplane(FlightVehicle):
"""Airplane inherits from FlightVehicle which inherits from Vehicle"""
def __init__(self, arg):
super(Airplane, self).__init__()
self.arg = arg
class Starship(FlightVehicle):
"""Starship inherits from FlightVehicle class which inherits from Vehicle"""
def __init__(self, arg):
super(FlightVehicle, self).__init__()
self.arg = arg
class GroundVehicle(Vehicle):
"""GroundVehicle inherits from Vehicle"""
def __init__(self, arg):
super(Vehicle, self).__init__()
self.arg = arg
class Motorcycle(GroundVehicle):
"""Motorcycle inherits from GroundVehicle"""
def __init__(self, arg):
super(GroundVehicle, self).__init__()
self.arg = arg
class Car(GroundVehicle):
"""Car inherits from GroundVehicle which inherits from Vehicle"""
def __init__(self, arg):
super(GroundVehicle, self).__init__()
self.arg = arg
|
#Feb 3, lecture
#example: find the smallest integer n such that
#1**3 + 2**3 + 3**3 + ... + n**3 < 10**6
#solution 1: use for loop
s = 0
for i in range(1, 100):
s += i**3
if (s >= 10**6):
print('largest n=', i-1)
s -= i**3
break #this is an important command to break out of loop
#print ('i=', i)
print('s=',s)
#solution 2: use while loop
s=0; i=1
while s < 10**6 - i**3:
s += i**3
i += 1
print(s) #a bug of extra n=45 which violate s <10**6
s=0; i=1
while s < 10**6:
s += i**3
i += 1
if (s> 10**6): s -= (i-1)**3
print(s) #a bug of extra n=45 which violate s <10**6
s=0; i=1
while i < 100:
if (s + i**3 < 10**6):
s += i**3
else:
break
i += 1
print(s)
s=0; i=1
while i < 100:
s += i**3
if s > 10**6:
s -= i**3
break
i += 1
print(s) #this fixed the bug of extra n=45 above
#use while loop to print out all integers n such that
# 100 < n**3/n**(1/2) <10**4
n = 1
while n < 10**4:
if 100 < n**3/n**(0.5) < 10**4:
print ('n=', n)
if n**3/n**(0.5) >= 10**4:
break
n += 1
##find all the integers n such that
# 10**6 <= 2**2 + 4**4 + 6**6 + ... (2*n)**n <= 10**90
s = 0;
nlist = []
for i in range(2, 100, 2): #use step length==2
s += i**i
if (s >= 10**6) and (s <= 10**90):
nlist.append(i/2)
if (s > 10**90):
break
nlist
s = 0;
nlist2 = []
for i in range(1, 100): #use step length==1
s += (2*i)**(2*i)
if (s >= 10**6) and (s <= 10**90):
nlist2.append(i)
if (s > 10**90):
break
nlist2
|
'''
fractions_opretions.py
'''
from fractions import Fraction
def add(a, b):
print('Result of adding {0} and {1} is {2}'.format(a, b, a+b))
def substract(a, b):
print('Result of Subtract: {0}'.format(a, b, a-b))
if __name__ == '__main__':
try:
a = Fraction(input('Enter first fraction: '))
b = Fraction(input('Enter second fraction: '))
op = input('Operation to perform - Add, Subtract, Divide, Multiply: ')
if op == 'Add':
add(a,b)
|
# First full line comment of the file
# Second comment of the file
import re # First instruction in block main
print('fgb') # First instruction in main block
print('fghfgh') # Second instruction in the main block
print('dfgdfg') # Now going to the for block, indent 1
for line in content: # First for loop, indent 1
print('xxxxx') # First instruction in for block, indent 1
if sub_line[0] != '': # First if, indent 2
term = sub_line[0].split()[0].lower()
# Now going for the for, indent 3
for i in mykeys:
# Going for the for the if block, indent 4
if re.search(i,term): # Here we can count the number of spaces or tabs upfront to determine the indentation for Python
left = list((re.findall(r'\s+', line)))
nbchars = len(left[0])
mymap[i](nbchars)
break
# End of the if block indent 4
# Back to block for, indent 3
print('gototot')
print('tutu')
# End of block for, indent 3
# Back to block if, indent 2
print('titi')
# New block if, indent 3
if len(sub_line) > 1:
print(f'Comment: ',sub_line[1])
# End of block if, indent 3
print('tata')
# End of block if, indent 2
# New block else, indent 2
else:
# New block if, indent 3
if len(sub_line) > 1:
print(f'Comment: ',sub_line[1])
# End of block if, indent 3
print('ok')
# End of block block else, indent 2
# Back to block for, indent 1
print('dududud')
# Back to block main
f.close()
print('ttitit')
print('dsfgdsg')
# End of block main
|
You are given an integer N. You need to print the series of all prime numbers till N.
Input Format
The first and only line of the input contains a single integer N denoting the number till where you need to find the series of prime number.
Output Format
Print the desired output in single line separated by spaces.
Constraints
1<=N<=1000
SLOUTION:
IN C++
#include <bits/stdc++.h>
using namespace std;
void SieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
bool prime[n+1];
memset(prime, true, sizeof(prime));
for (int p=2; p*p<=n; p++)
{
// If prime[p] is not changed, then it is a prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i=p*2; i<=n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int p=2; p<=n; p++)
if (prime[p])
cout << p << " ";
}
// Driver Program to test above function
int main()
{
int n;
/*cout << "Following are the prime numbers smaller "
<< " than or equal to " << n << endl;
*/
cin>>n;
SieveOfEratosthenes(n);
return 0;
}
IN PYTHON 3
|
n = int(input())
words = set()
for _ in range(n):
words.add(input())
for word in sorted(words, key=lambda x: (len(x), x)):
print(word) |
# Advent of Code 2020
# Day 7, Part 2
# December 13, 2020
def bag_contains(bag_color, bag_cnt):
global rules
global total_bags
global recur_level
outer_bag_cnt = 0
temp_bag_cnt = 0
print('\nLooking for bag colors contained in',bag_cnt,' ',bag_color,'bags:')
for curr_rule in rules:
if (curr_rule.find(bag_color) == 0):
#print(curr_rule)
# strip off the first bag color to get the list of remaining bag colors
new_rule = curr_rule[curr_rule.find(':') + 2:]
#print(new_rule)
# recurse through the list of bag colors contained in the current bag color
while new_rule != '':
loc1 = new_rule.find(',')
if (loc1 != -1):
loc2 = new_rule.find(' ')
outer_bag_cnt = new_rule[:loc2]
outer_bag_color = new_rule[loc2 + 1:new_rule.find(',')]
temp_bag_cnt = temp_bag_cnt + int(new_rule[:loc2])
print(new_rule)
#print(outer_bag_cnt)
#print(outer_bag_color)
recur_level += 1
print('entering recursion level ',recur_level,'for ',outer_bag_cnt,outer_bag_color,' bags')
#bag_contains(outer_bag_color, outer_bag_cnt)
total_bags = total_bags + int(bag_cnt) + (int(bag_cnt) * (bag_contains(outer_bag_color, int(outer_bag_cnt))))
print('total',total_bags)
print('back from recursion level',recur_level)
recur_level += -1
new_rule = new_rule[loc1+2:]
else:
# handle the last bag color
loc1 = len(new_rule)
loc2 = new_rule.find(' ')
outer_bag_cnt = new_rule[:loc2]
outer_bag_color = new_rule[loc2 + 1:]
temp_bag_cnt = temp_bag_cnt + int(new_rule[:loc2])
print(new_rule)
#print(outer_bag_cnt)
#print(outer_bag_color)
recur_level += 1
print('entering recursion level ',recur_level,'for ',outer_bag_cnt,outer_bag_color,' bags')
#bag_contains(outer_bag_color, outer_bag_cnt)
total_bags = total_bags + int(bag_cnt) + (int(bag_cnt) * (bag_contains(outer_bag_color, int(outer_bag_cnt))))
print('total',total_bags)
print('back from recursion level',recur_level)
recur_level += -1
new_rule = ''
if (temp_bag_cnt == 0):
# the current bag color contained no other bags
print('returning 1')
return bag_cnt
else:
print('returning ',temp_bag_cnt)
return (temp_bag_cnt * bag_cnt)
#if (recur_level != 0):
#print('bag color:',bag_color)
#print('total bags:',total_bags)
#print('temp_bag_cnt:',temp_bag_cnt)
#print('bag_cnt:',bag_cnt)
#total_bags = total_bags + (int(bag_cnt) * temp_bag_cnt)
#print('**leaving recursion ',recur_level,'for ',bag_color,', total bags = ',total_bags)
#else:
# print('total bags:',total_bags)
# print('temp_bag_cnt:',temp_bag_cnt)
# print('bag_cnt:',bag_cnt)
# total_bags = total_bags * bag_cnt
# print('leaving recursion ',recur_level,'for ',bag_color,', total bags = ',total_bags)
# end bag_contains()
# *** main program begins here ***
file_name = "day7-input2.dat"
with open(file_name) as file_contents:
line_content = file_contents.readlines()
# initialize variables and set file length
rule_cnt = 0
curr_row = 0
bag_cnt = 1
total_bags = 0
recur_level = 0
rules = set()
bag_color = 'shiny gold'
length = len(line_content) - 1
# load in and parse the rules
while curr_row <= length:
curr_rule = line_content[curr_row].rstrip()
# strip ending period
curr_rule = curr_rule.rstrip('.')
# remove the word 'bags' or 'bag'
curr_rule = curr_rule.replace(' bags', '')
curr_rule = curr_rule.replace(' bag', '')
# replace 'contains'
curr_rule = curr_rule.replace(' contain', ':')
# replace 'no other'
curr_rule = curr_rule.replace(' no other', '')
#print('Rule #', rule_cnt + 1, ': ', curr_rule)
# add the current, revised rule to the set
rules.add(curr_rule)
rule_cnt += 1
curr_row += 1
#print('\nTotal # of rules loaded and parsed: ', rule_cnt)
bag_color = input('\nBag color: ')
# recurse through all the bag colors contained in the bag we're interested in
bag_contains(bag_color, bag_cnt)
#print('\nBag colors: ', bags)
print('\nTotal # of bags contained in ',bag_cnt,' ',bag_color,'bag(s):', total_bags, '\n')
|
# Advent of Code 2020
# Day 1, Part 2
# December 1, 2020
file_name = "day1-input.dat"
with open(file_name) as file_contents:
list1 = file_contents.readlines()
list2 = list1
list3 = list1
for line1 in range(len(list1)):
val1 = int(list1[line1].rstrip())
for line2 in range(len(list2)):
val2 = int(list2[line2].rstrip())
for line3 in range(len(list3)):
val3 = int(list3[line3].rstrip())
val_sum = val1 + val2 + val3
if val_sum == 2020:
print("\nFound the thruple that equals 2020:")
print("{} + {} + {} = {}".format(val1, val2, val3, val_sum))
print("\nSo the answer is:")
aoc_answer = val1 * val2 * val3
print("{} * {} * {} = {}\n".format(val1, val2, val3, aoc_answer))
quit()
|
from random import normalvariate, randint
from maxQLearning import QLearningAgent
from matplotlib import pyplot as plt
from numpy import arange
# the actions that the agent will be allowed to perform
actions = ['forward', 'backward', 'stay still']
# the state dimensions
time = arange(-12, 12, 1)
localDemand = arange(-2, 2, 1)
priceOfProduction = arange(-5, 5, 1)
priceOfRetail = arange(-5, 5, 1)
charge = arange(-3, 3, 1)
agent = QLearningAgent(actions)
agent.startExploring()
# this list will hold the reward the agent recieves at each timestep, it will be used to plot the agent's performance
performance = []
# the state variables are randomly initialized
timeIndex = randint(0, len(time))-1
localDemandIndex = randint(0, len(localDemand))-1
priceOfProductionIndex = randint(0, len(priceOfProduction))-1
priceOfRetailIndex = randint(0, len(priceOfRetail))-1
chargeIndex = randint(0, len(charge))-1
print('running simulation')
numIterations = 300000
for i in range(0,numIterations):
if (i%1000 == 0):
agent.updatePolicy(agent.Q)
# resets reward
reward = 0
# gets action from agent
action = agent.getAction([time[timeIndex], localDemand[localDemandIndex], priceOfProduction[priceOfProductionIndex], priceOfRetail[priceOfRetailIndex], charge[chargeIndex]])
if (action == 'forward'):
# the index in each dimenison is incremented upwards
timeIndex = (timeIndex+1)%len(time)
localDemandIndex = (localDemandIndex+1)%len(localDemand)
priceOfProductionIndex = (priceOfProductionIndex+1)%len(priceOfProduction)
priceOfRetailIndex = (priceOfRetailIndex+1)%len(priceOfRetail)
chargeIndex = (chargeIndex+1)%len(charge)
elif (action == 'backward'):
# the agent to recieves an award
reward = time[timeIndex] + localDemand[localDemandIndex] + priceOfProduction[priceOfProductionIndex] + priceOfRetail[priceOfRetailIndex] + charge[chargeIndex]
# the index in each dimenison is incremented downwards, with no reward, this will test if the agent can think ahead
timeIndex = (timeIndex-1)%len(time)
localDemandIndex = (localDemandIndex-1)%len(localDemand)
priceOfProductionIndex = (priceOfProductionIndex-1)%len(priceOfProduction)
priceOfRetailIndex = (priceOfRetailIndex-1)%len(priceOfRetail)
chargeIndex = (chargeIndex-1)%len(charge)
elif (action == 'stay still'):
pass
else:
print("this shouldn't happen")
# the state variables are randomly altered
timeIndex = (timeIndex+randint(-1,1))%len(time)
localDemandIndex = (localDemandIndex+randint(-1,1))%len(localDemand)
priceOfProductionIndex = (priceOfProductionIndex+randint(-1,1))%len(priceOfProduction)
priceOfRetailIndex = (priceOfRetailIndex+randint(-1,1))%len(priceOfRetail)
chargeIndex = (chargeIndex+randint(-1,1))%len(charge)
# prints progress, WILL NOT WORK WITH PYTHON2
# erases the last output
print('\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b', end = '')
# produces new output
print(' %'+str(100*i/numIterations), end = '')
# gives agent the reward
agent.giveReward(reward)
# adds reward to parformance so that it may be plotted
performance.append(reward)
# time to calculate the average reward across a time period of num iterations
# adds new line
print()
print('forming results')
num = 300
toPlot = []
numIterations = len(performance)-num
for i in range(0, numIterations):
sum = 0
for j in range(i,i+num):
sum += performance[j]
toPlot.append(sum/num)
# prints progress, WILL NOT WORK WITH PYTHON2
# erases the last output
print('\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b', end = '')
# produces new output
print(' %'+str(100*i/numIterations), end = '')
# adds new line
print()
x = range(0, len(toPlot))
plt.plot(x, toPlot)
plt.show()
|
from face import Face
class Cubie(object):
"""
Class representing one of the small sub-divisions of the Rubik's cube.
A standard 3x3x3 Rubik's cube has 27 of these.
"""
def __init__(self, matrix):
"""
Initializes a cubie
:param matrix: PMatrix3D placing the cubie in 3D-space
"""
self.matrix = matrix
self.faces = [0 for i in range(6)]
def set_faces(self, index, num_layers):
"""
Populates the six faces of the cubie with Face-objects,
and assigns the correct color to these.
:param index: ID number of the cubie
:param numLayers: Number of layers in the cube
"""
self.faces[0] = Face(PVector(0,0,1))
self.faces[1] = Face(PVector(0,0,-1))
self.faces[2] = Face(PVector(0,1,0))
self.faces[3] = Face(PVector(0,-1,0))
self.faces[4] = Face(PVector(1,0,0))
self.faces[5] = Face(PVector(-1,0,0))
if (index % num_layers == num_layers -1):
self.faces[0].set_color("#FFFFFF") # White
if (index % num_layers == 0):
self.faces[1].set_color("#FFD500") # Yellow
if (index % (num_layers ** 2) >= (num_layers * (num_layers - 1))):
self.faces[2].set_color("#FF5900") # Orange
if (index % (num_layers ** 2) < num_layers):
self.faces[3].set_color("#B90000") # Red
if (index >= num_layers ** 2 * (num_layers - 1)):
self.faces[4].set_color("#009B48") # Green
if (index < num_layers ** 2):
self.faces[5].set_color("#0045AD") # Blue
def turn_faces(self, dir, axis):
"""
Handles the turning of the cubies faces, when a move is made
:param dir: Direction of the turn. Clockwise; 1, Counterclockwise: -1, Double: 2
:param axis: Axis of rotation; 'x', 'y' or 'z'
"""
angle = dir * HALF_PI
for f in self.faces:
f.turn(angle, axis)
def update(self, x, y, z):
"""
Updates the cubies placement in 3D space after a move
:param x: The cubie's new x-coordinate
:param y: The cubie's new y-coordinate
:param z: The cubie's new z-coordinate
"""
self.matrix.reset()
self.matrix.translate(x, y, z)
def show(self):
"""
Defines the look of the cubie, and shows it's faces
"""
noFill()
stroke(0)
strokeWeight(0.15)
pushMatrix()
applyMatrix(self.matrix)
box(1)
for f in self.faces:
f.show()
popMatrix()
def get_x(self):
return self.matrix.m03
def get_y(self):
return self.matrix.m13
def get_z(self):
return self.matrix.m23
|
# Dictionaries in Python
# Key: State
# Value: Capital
statesToCapitals = {}
statesToCapitals["Kansas"] = "Topeka"
statesToCapitals["Arizona"] = "Phoenix"
statesToCapitals["Michigan"] = "Lansing"
# To access values:
print(statesToCapitals["Arizona"])
|
print("Nhập 1 số bất kì lớn hơn 0")
sobatki = int(input(">>>"))
for i in range(sobatki + 1):
print(i) |
from turtle import *
speed(0)
print("Nạp các màu")
mau = input(">>>")
mau = mau.split(",")
for i in mau:
color(i)
forward(30)
mainloop() |
color_list=["red","blue","purple",]
while True:
new_color=input("New color?")
color_list.append(new_color)
print("*"*10)
for color in color_list:
print(color)
print("*"*10) |
print("Nhập họ mày vào")
ho = input(">>>")
print("Nhập tên mày vào")
ten = input(">>>")
print("Tên bạn đã được chuyển thành chữ hoa:", ho.upper(), ten.upper()) |
x = 10
y = 20
z = 100
w = (x + y) * z / 100
print(w)
print("este texto será impresso no console")
print(x)
print("texto e duas variáveis", x, ", ", z)
m = "python"
print("tipo da variável m: ", type(m))
print("tipo da variável x: ", type(x))
print("informe o valor 1:")
i = input()
print(type(i))
var = input("informe o valor 2:")
var = int(var)
print(type(var))
var = float(var)
print(type(var))
# teste de comentário
'''
comentário em várias linhas
teste1
teste2
teste3
teste4
'''
print("fim dos comentários")
|
import unittest
from check_permutation import check_permutation
class CheckPermutationTest(unittest.TestCase):
def test_is_permutation(self):
self.assertEqual(True, check_permutation("is", "si"))
def test_is_permutation_longer(self):
self.assertEqual(True, check_permutation("aaabbbccc", "abcabcabc"))
def test_is_not_permutation(self):
self.assertEqual(False, check_permutation("lol", "lol2"))
def test_is_not_permutation_longer(self):
self.assertEqual(False, check_permutation("lololol", "looool"))
if __name__ == '__main__':
unittest.main()
|
# Linked list implementation in Python
class Node:
# Creating a node
def __init__(self, item):
self.item = item
self.next = None
class LinkedList:
def __init__(self):
self.head = None
|
def merge_sort(arr):
result = []
# 7
length = len(arr)
if length <= 1:
# print(f'floor of {arr}')
return arr
# 4
mid = length // 2
# print(f'length {length}')
# print(f'mid {mid}')
# 0,1,2,3
left = merge_sort(arr[:mid])
# 4,5,6
right = merge_sort(arr[mid:])
# print(f'left {left}')
# print(f'right {right}')
left_index = right_index = 0
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
while left_index < len(left):
result.append(left[left_index])
left_index += 1
while right_index < len(right):
result.append(right[right_index])
right_index += 1
return result
result = merge_sort([38, 27, 43, 3, 9, 82, 10])
if not result == [3, 9, 10, 27, 38, 43, 82]:
raise Exception("common case failed")
print(f'Success common case: {result}')
result = merge_sort([1, 2, 3, 4, 5, 6, 7])
if not result == [1, 2, 3, 4, 5, 6, 7]:
raise Exception("ordered case failed")
print(f'Success ordered case: {result}')
|
class Prefix_Tree():
def __init__(self, character=None, level=0, *leaves):
self.character = character
self.leaves = set(leaves)
self.level = level
self.word = ''
def find_words_for_prefix(self, prefix):
current_leaf = self
for character in prefix:
current_leaf = current_leaf.find_leaf(character)
if not current_leaf:
return []
return current_leaf.get_words_from_leaf()
def get_words_from_leaf(self, found_words=[]):
if self.word:
found_words.append(self.word)
for leaf in self.leaves:
leaf.get_words_from_leaf(found_words)
return found_words
def add_word(self, word):
current_leaf = self
for character in word:
found_leaf = current_leaf.find_leaf(character)
if not found_leaf:
found_leaf = Prefix_Tree(character, current_leaf.level + 1)
current_leaf.leaves.add(found_leaf)
current_leaf = found_leaf
current_leaf.word = word
def find_leaf(self, character):
if self.leaves:
for leaf in self.leaves:
if leaf.character == character:
return leaf
return None
def print_leaves(self):
for leaf in self.leaves:
indent = leaf.level * '\t'
print(f'{indent}{leaf.character}{leaf.word}')
leaf.print_leaves()
def __str__(self):
print('\n')
return f'{self.print_leaves()}'
# def print_leaves(self, output_matrix):
# for leaf in self.leaves:
# if leaf.level == 1:
# for index in range(len(output_matrix)):
# output_matrix[index] += '\t'
# if len(output_matrix) < leaf.level:
# output_matrix.append('')
# # indent = leaf.level * '\t'
# have_word = leaf.word if leaf.word else ''
# output_matrix[leaf.level - 1] += f'{leaf.character} {have_word}'
# leaf.print_leaves(output_matrix)
# def __str__(self):
# print('\n')
# output_matrix = []
# f'{self.print_leaves(output_matrix)}'
# output = ''
# for level in output_matrix:
# output += f'{level}\n'
# return output
def __repr__(self):
return self.__str__()
|
class Stack():
def __init__(self):
self.elements = []
self.top = -1
def push(self, element):
self.elements.append(element)
self.top += 1
#print(f'push: {self.top}: {self.elements}')
def pop(self):
if self.top == -1:
return None
element = self.elements[self.top]
self.elements.remove(element)
self.top -= 1
return element
def peek(self):
if self.top == -1:
return None
return self.elements[self.top]
def __str__(self):
return f'{self.elements}'
def __repr__(self):
return self.__str__()
|
primes = []
upto = 100
for n in range(upto + 1):
is_prime = True
for divisor in range(2, n):
if n % divisor == 0:
is_prime = False
break
if is_prime and n > 1:
primes.append(n)
print(primes)
|
a = dict()
b = {}
c = dict(A=1, B=-1)
print(a, b, c)
a.update({'A': 'apple'})
print(a)
a.update(B='banana')
print(a)
a.pop('A')
print(a)
print(a.get('B'))
a.update(A='apple')
print(a)
for key, value in a.items():
print(key, value)
|
import statistics
import random
example_list = [random.randint(1, 100) for i in range(1000000)]
print('list is', example_list)
# mean 平均數
x = statistics.mean(example_list)
print('mean is', x)
# standard Deviation 標準差
y = statistics.stdev(example_list)
print('standard deviation is', y)
# variance 變異數
z = statistics.variance(example_list)
print('variance is', z)
# count mind
# 1,2,3,4,5
# n1 + n2 + n3 + n4 + n5 / n
# stdev = (n1-mean)**2 + (n2-mean)**2 + ... / n
# mean = 15/5 = 3
# variance = stdev ** 2
|
late = True
if late:
print('I need to call my manager!')
else:
print('no need to call my manager...')
income = 15000
if income < 10000:
print()
elif income < 20000 and income >= 10000:
print()
else:
print()
# ternary operator
order_total = 247
discount = 25 if order_total > 100 else 0
# errors alert
alert_system = 'console'
errror_severity = 'critical'
error_message = 'OMG! Something terrible happened!'
if alert_system == 'console':
print(error_message)
elif alert_system == 'email':
if error_severity == 'critical':
send_email('[email protected]', error_message)
elif error_severity == 'medium':
send_email('[email protected]', error_message)
else:
send_email('[email protected]', error_message)
|
num_list = [12,23,2,2,3,1,3,52,44,65,4,12]
fruit_list = ['apple', 'banana', 'cherry']
student_dict = {
'id' : 1,
'name' : 'chris',
}
for i in num_list:
print(i)
for i in range(10):
print(i)
for i in range(1,100,3):
print(i)
for fruit in fruit_list:
print(fruit)
for key in student_dict:
print(key)
for key, value in student_dict.items():
print(key, value)
|
class Solution:
#Function to reverse a linked list.
def reverseList(self, head):
if head is None:
return None
#taking three pointers to store the current, previous and next nodes.
prev = None
current = head
next = current.next
while current is not None:
#taking the next node as next.
next = current.next
#storing the previous node in link part of current node.
current.next = prev
#updating prev from previous node to current node.
prev = current
#updating current node to next node.
current = next
return prev
class Node:
def __init__(self):
self.head = None
self.tail = None
def insert(self, val):
if self.head is None:
self.head = Node(val)
self.tail = self.head
else:
self.tail.next = Node(val)
self.tail = self.tail.next
def printList(head):
tmp = head
while tmp:
print(tmp.data, end = '')
tmp = tmp.next
print()
|
#!/usr/bin/env python2
# Author: Elliot Sayes
# Generates distance to beacons from a given position
import math
x = input("x: ")
y = input("y: ")
X_S = 0;
Y_S = 0;
beacon_locations =[
[X_S+10600, Y_S+1400 ],
[X_S+0, Y_S+2500 ],
[X_S+0, Y_S+2500+12300],
[X_S+10600, Y_S+11400 ]
]
d = []
for beacon in beacon_locations:
d.append( math.sqrt((x-beacon[0])**2+(y-beacon[1])**2) )
print(d)
|
#!/usr/bin/env python3
"""
v3 - class
by Richard White https://www.youtube.com/watch?v=wYYzteRKU7U
"""
# Inheritance: Multiple classes than inherit from each other
class Person(object):
"""
The person class defines a person in terms of a name, phone and email)
"""
#Constructor
def __init__(self, theName, thePhone, theEmail):
self.name = theName
self.phone = thePhone
self.email = theEmail
#Accesor Methods (getters)
def getName(self):
return self.name
def getPhone(self):
return self.phone
def getEmail(self):
return self.email
#Mutator Methods (setters)
def setPhone(self, newPhoneNumber):
self.phone = newPhoneNumber
def setEmail(self, newEmail):
self.email = newEmail
def __str__(self): #Method that returns string
# Overriding the method and will return the following string
return "Person[name=" + self.name + \
",phone=" + self.phone + \
",email=" + self.email + \
"]"
def main():
friend1 = Person("Jill", "555-1234", "[email protected]")
print(friend1.getEmail())
friend1.setEmail("[email protected]")
print(friend1)
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
#
# Print a diff summary like:
#
# $ git diff 'master~10..master' | gn
# 293 lines of diff
# 185 lines (+200, -15)
# 650 words (+10, -660)
#
# or:
#
# $ gn my-awesome-patch.diff
# 293 lines of diff
# 185 lines (+200, -15)
# 650 words (+10, -660)
import fileinput
import os
import re
import sys
def get_lines(diff_lines):
# Added lines start with '+' (but not '+++', because that marks a new
# file). The same goes for removed lines, except '-' instead of '+'.
def condition(char):
return lambda l: l.startswith(char) and not l.startswith(char * 3)
is_added = condition("+")
is_removed = condition("-")
added_lines = [line for line in diff_lines if is_added(line)]
removed_lines = [line for line in diff_lines if is_removed(line)]
return added_lines, removed_lines
def get_words(added_lines, removed_lines):
def word_count(lines):
return [
word for line in lines for word in line.split() if re.match(r"^\w+", word)
]
return word_count(added_lines), word_count(removed_lines)
def display(diff_lines, added_lines, added_words, removed_lines, removed_words):
def delta(added, removed):
d = added - removed
return ["", "+"][d > 0] + str(d)
delta_lines = delta(added_lines, removed_lines)
delta_words = delta(added_words, removed_words)
print(
f"{diff_lines} lines of diff\n"
f"{delta_lines} lines (+{added_lines}, -{removed_lines})\n"
f"{delta_words} words (+{added_words}, -{removed_words})"
)
def main(fileinput):
diff_lines = list(fileinput)
added_lines, removed_lines = get_lines(diff_lines)
added_words, removed_words = get_words(added_lines, removed_lines)
display(
len(diff_lines),
len(added_lines),
len(added_words),
len(removed_lines),
len(removed_words),
)
if __name__ == "__main__":
try:
main(fileinput.input())
except KeyboardInterrupt:
pass
|
# Import create_engine function
from sqlalchemy import create_engine
# Create an engine to the census database
engine = create_engine("postgresql+psycopg2://student:[email protected]:5432/census")
# Use the .table_names() method on the engine to print the table names
print(engine.table_names())
# Create a select query: stmt
stmt = select([census])
# Add a where clause to filter the results to only those for New York : stmt_filtered
stmt = stmt.where(census.columns.state == "New York")
# Execute the query to retrieve all the data returned: results
results = engine.connect().execute(stmt).fetchall()
# Loop over the results and print the age, sex, and pop2000
for result in results:
print(result.age, result.sex, result.pop2000)
|
class RadixTree:
def __init__(self):
self.root = self.Node(False)
def insert(self, value):
# We don't permit inserting blank values
if len(value) == 0:
return False
# Start at the root
curr_node = self.root
curr_index = 0
# As long as we have not reached the end of our value, continue
while curr_index < len(value):
# Track whether our current index changed
# i.e. whether we found a matching prefix
change = 0
# Look through all the edges in our current node
for edge in curr_node.edges:
# Calculate the prefix
pref = self.is_prefix(edge.value, value[curr_index:])
# Prefix greater than 0 means there was a match up to pref
if pref > 0:
# If pref is as long as edge.value, it means that edge.value was a
# perfect prefix (i.e. it fit completely)
if pref == len(edge.value):
# So we update our flag and current node and break out of this
# inner loop, since there can be at most one matching prefix
change = pref
curr_node = edge.node
break
# Otherwise there was a mismatch at some point, but at least one
# character matched
else:
# So we split the edge at the trouble point, inserting the new
# value in the process
edge.split(pref, value[(curr_index + pref):])
return True
# If pref is negative, it means there was an over-match. In other words
# the value we are trying to insert is itself a prefix of edge.value
# So we split the offending edge and insert a blank edge for our new
# value
elif pref < 0:
edge.split(len(edge.value) + pref)
return True
# Adjust the current index by our change
curr_index += change
# If we did not change at all, it means that no matching prefix was found
# in the last iteration of this loop, so we should break and insert a new
# edge
if change == 0 or curr_index == len(value):
break
# The value is already in the tree
if curr_index == len(value):
if curr_node.leaf:
return False
else:
curr_node.set_leaf(True)
else:
# Insert a new edge with any remaining characters in our value
curr_node.add_edge(self.Edge(value[curr_index:], self.Node()))
return True
def contains(self, value):
return self.find_helper(value) != None
def delete(self, value):
res = self.find_helper(value)
if res == None:
return False
parent, node = res
node.set_leaf(False)
if len(node.edges) == 0:
if parent == None:
return False
else:
parent.delete_child(node)
elif len(node.edges) == 1:
parent.get_edge(node).join(node.edges[0])
return True
def find_helper(self, value):
if len(value) == 0:
return None
parent = None
curr_node = self.root
curr_index = 0
while curr_index < len(value):
change = 0
for edge in curr_node.edges:
pref = self.is_prefix(edge.value, value[curr_index:])
if pref > 0:
if pref == len(edge.value):
change = pref
parent = curr_node
curr_node = edge.node
else:
return None
elif pref < 0:
return None
curr_index += change
if change == 0:
break
if curr_node.leaf and curr_index == len(value):
return (parent, curr_node)
else:
return None
def is_prefix(self, a, b):
idx = 0
for ch in a:
if idx >= 0 and idx < len(b) and ch != b[idx]:
return idx
elif idx == len(b):
idx = -1
elif idx < 0:
idx -= 1
else:
idx += 1
return idx
class Node:
def __init__(self, leaf=True):
self.leaf = leaf
self.edges = []
def add_edge(self, edge):
self.edges.append(edge)
def set_leaf(self, value):
self.leaf = value
def delete_child(self, node):
for i in range(len(self.edges)):
if self.edges[i].node == node:
del self.edges[i]
return True
return False
def get_edge(self, node):
for edge in self.edges:
if edge.node == node:
return edge
return None
class Edge:
def __init__(self, value, node):
self.value = value
self.node = node
def join(self, other):
self.value += other.value
self.node = other.node
def split(self, index, new_prefix=""):
if index >= len(self.value) or index == 0:
raise IndexError(f"Index { index } is out of bounds of 1-{ len(self.value) }")
# Create new edges
next_edge = RadixTree.Edge(self.value[index:], self.node)
leaf_node = RadixTree.Node()
# Create branch node
branch_node = RadixTree.Node(False)
branch_node.add_edge(next_edge)
if len(new_prefix) > 0:
branch_edge = RadixTree.Edge(new_prefix, leaf_node)
branch_node.add_edge(branch_edge)
else:
branch_node.set_leaf(True)
# Update current edge
self.value = self.value[0:index]
self.node = branch_node |
import os, json
usage = '''
Usage:
python "path_to_this_folder/main.py" [Option]
Option:
-n --new <name> <path>: Create a new shortcut
-o --open <name> [args...]: Open a shortcut with optional arguments
-i --info <name>: View the information of a shortcut
-l --list: View the list of shortcuts
-m --modify [-n --name][-p --path] <name> <change>: Modify the name and/or the path of a shortcut
-d --delete <name>: Delete a shortcut
-b --base: Show the directory in which this script is saved
'''
path = os.path.join(os.path.dirname(__file__), 'data.json')
data = {}
def exist(name):
return name in data
def data_exist():
if not os.path.isfile(path):
with open(path, 'w') as file:
file.write('{}')
print('Initialized new data.')
def split_dir(name):
return name.replace('\\', '/').split('/')
def join_path(name):
path = data[name[0]]
it = iter(name)
_ = next(it)
for subdir in it:
path = os.path.join(path, subdir)
return path
def load():
global data
data_exist()
with open(path, 'r') as file:
data = json.loads(file.readline())
def save(data):
data_exist()
with open(path, 'w') as file:
file.write(json.dumps(data, sort_keys=True))
def error(id, msg=''):
error_list = {
1: 'Parameter <name> is not specified.',
2: 'Parameter <path> is not specified.',
3: 'Parameter <change> is not specified.',
4: 'Modification option is not specified.',
5: f'Unrecognized modification option: {msg}.',
6: f'Unrecognized flag: {msg}.',
7: f'"{msg}" is not found in database.',
8: f'"{msg}" already exists.',
9: 'Name cannot exceed 15 characters.',
10: f'The system cannot find the file specified: "{msg}".'
}
print(error_list.get(id, 'Unknown error.'))
if id in [1, 2, 3, 4, 5]:
print(usage)
def open_shortcut(path, args):
if (args == []):
os.startfile(path)
else:
os.system(f'"{path}" ' + ' '.join(args))
def opt_new(name, path):
if len(name) < 16:
data[name] = path
# print('Added element {name}.')
else:
error(9)
def opt_open(name, args):
# print(f'Opening element {name} with {args}...')
path = data[name[0]]
if len(name) > 1:
path = join_path(name)
if os.path.exists(path):
open_shortcut(path, args)
else:
error(10, path)
else:
open_shortcut(path, args)
def opt_info(name):
print(f'Name: {name}')
print(f'Path: {data[name]}')
def opt_list():
print('Name\t\tPath')
print('-' * 80)
for key in data:
print(key + ('\t\t' if len(key) < 8 else '\t') + data[key])
def opt_modify(option, name, change):
if option == '-n' or option == '--name':
if exist(change):
error(8, change)
elif len(change) > 15:
error(9)
else:
data[change] = data.pop(name)
elif option == '-p' or option == '--path':
data[name] = change
else:
error(5, option)
def opt_delete(name):
del data[name]
# print('Deleted element {name}.')
|
# The depth-first search algorithm of maze generation is frequently implemented using backtracking.
# This can be described with a following recursive routine:
#
# 1. Given a current cell as a parameter,
# 2. Mark the current cell as visited
# 3. While the current cell has any unvisited neighbour cells
# 1. Choose one of the unvisited neighbours
# 2. Remove the wall between the current cell and the chosen cell
# 3. Invoke the routine recursively for a chosen cell
#
# which is invoked once for any initial cell in the area.
from common import *
import random
width = 10
height = 10
# set start position
start_x = random.randint(0, width)
start_y = random.randint(0, height)
pos = Vector2(start_x, start_y)
def RDFSrecursive():
"""RDFS, recursive version
Using plain *visited* 2d-list and a *paths* to indicate
possible movement between cells
"""
visited = [[False for x in range(width)] for y in range(height)]
visited[pos.y][pos.x] = True
paths = []
def move(current_pos):
# While the current cell has any unvisited neighbor cells
m = movable(current_pos, visited)
while len(m) > 0:
# Chose one randomly
next_pos = random.choice(m)
if not visited[next_pos.y][next_pos.x]:
# Mark the chosen cell as visited and set as movable path
visited[next_pos.y][next_pos.x] = True
paths.append((current_pos, next_pos))
# Invoke the routine recursively
move(next_pos)
# Remove the chosen cell from neibors
m.remove(next_pos)
move(pos)
# Convert to enclosed cells
result = draw_paths(width, height, paths)
# Print the result
[print(' '.join(x)) for x in result]
RDFSrecursive()
### Draft section ###
def RDFSrecursive_Cells():
"""RDFS, recursive version
Transform the result to *Cell* data structure
"""
cells = [[Cell(Vector2(x, y)) for x in range(width)] for y in range(height)]
def move(current_pos):
current_cell = Cell(current_pos)
movable_cells = []
for d in directions:
next_pos = Vector2.add(current_cell.pos, d)
if next_pos.x < 0 or next_pos.x >= width or \
next_pos.y < 0 or next_pos.y >= height:
continue
movable_cells.append(next_pos)
while len(movable_cells) > 0:
next_pos = random.choice(movable_cells)
next_cell = cells[next_pos.y][next_pos.x]
if not next_cell.visited:
Cell.connect(current_cell, next_cell)
next_cell.visited = True
move(next_pos)
movable_cells.remove(next_pos)
move(pos)
draw_Cells(cells) |
dic = {'k1': 'v1', 'k2': 'v2', 'k3': [11, 22, 33]}
for k in dic:
print(k)
for v in dic.values():
print(v)
for k, v in dic.items():
print(k, ':', v)
dic['k4'] = 'v4'
print(dic)
dic['k1'] = 'alex'
print(dic)
dic['k3'].append(44)
print(dic)
dic['k3'].insert(0, 18)
print(dic)
|
# 编写装饰器,为多个函数加上认证的功能,用户的账号密码来自于文件
# 要求登录成功一次,后续的函数无需再输入用户名和密码
auth = False
def verify(func):
"""
认证,密码来自文件
:return: 是否认证成功
"""
def inner(*args, **kwargs):
global auth
if auth:
ret = func(*args, **kwargs)
return ret
with open('auth', encoding='utf-8') as f:
li_verify = []
for line in f:
li = line.split(':', 1)
username = li[0].strip()
password = li[1].strip()
li_verify.append({'username': username, 'password': password})
username = input('请输入用户名:')
password = input('请输入密码:')
for i in li_verify:
if i['username'] == username and i['password'] == password:
print('认证成功')
auth = True
ret = func(*args, **kwargs)
return ret
else:
print('认证失败')
return inner
@verify
def f1():
print('f1')
@verify
def f2():
print('f2')
@verify
def f3():
print('f3')
f1()
f2()
f3()
|
dic = {
'name': ['jason', 'tiko'],
'py': {'num': 71, 'age': 18}
}
print(dic.get('name'))
print(dic.get('name')[0])
print(dic.get('py').get('num'))
|
# 写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
# 字典中的value只能是字符串或列表
def check_len(dic):
"""
检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
:param dic: 传入的字典
:return: 保留2个长度的新字典
"""
if isinstance(dic, dict):
for k, v in dic.items():
if isinstance(v, (str, list)) and len(v) > 2:
dic[k] = v[0:2]
return dic
print(check_len({'k1': 'v1'}))
print(check_len({'k1': 'v1', 'k2': 'v23'}))
print(check_len({'k1': 'v1', 'k2': 'v2', 'k3': [1, 2, 3, 4]}))
|
pythons = {'alex', 'egon', 'yuanhao', 'wupeiqi', 'gangdan', 'biubiu'}
linuxs = {'wupeiqi', 'oldboy', 'gangdan'}
# 1. 求出即报名python又报名linux课程的学员名字集合
print(pythons.intersection(linuxs))
# 2. 求出所有报名的学生名字集合
print(pythons.union(linuxs))
# 3. 求出只报名python课程的学员名字
print(pythons.difference(linuxs))
# 4. 求出没有同时这两门课程的学员名字集合
print(pythons.symmetric_difference(linuxs))
|
li = [1, 2, 3, 4]
li2 = list(reversed(li))
print(li2)
si = slice(2, 3)
print(li2[si])
print(format('23', '>20'))
print(bytes('你好', encoding='utf-8'))
print(ord('a'))
print(chr(97))
print('%r' % 'hello world')
print(repr('hello world'))
list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1, 1):
print(index, item)
print(any(['1', None]))
print(all(['1', None]))
for i in zip(li, li2):
print(i)
def lower(x):
if x < 3:
return x
def x2(x):
return 2 * x
for i in filter(lower, li):
print(i)
for i in map(x2, li):
print(i)
li3 = sorted(li, reverse=True)
print(li3)
|
# 测试一个输入的字符串中,大写字母,小写字母,数字,其他符号的个数
list_upper = []
for i in range(65, 91):
list_upper.append(chr(i))
list_lower = []
for i in range(97, 123):
list_lower.append(chr(i))
list_digit = []
for i in range(48, 58):
list_digit.append(chr(i))
count_upper = 0
count_lower = 0
count_digit = 0
count_other = 0
str_input = input('请输入一个字符串:')
if str_input:
for i in str_input:
if i in list_upper:
count_upper += 1
elif i in list_lower:
count_lower += 1
elif i in list_digit:
count_digit += 1
else:
count_other += 1
else:
print('字符串为空,请重新输入')
print('该字符串中大写字母有%d个,小写字母有%d个,数字有%d个,其他字符有%d个'
% (count_upper, count_lower, count_digit, count_other))
|
# 实现一个整数加法计算器
# 如:content = input(‘请输入内容:’)
# 如用户输入:5+8+7....(最少输入两个数相加),
# 然后进行分割再进行计算,将最后的计算结果添加到此字典中(替换None):
# dic={‘最终计算结果’:None}。
def is_int(number):
for n in number:
if not 48 <= ord(n) <= 57:
return False
else:
return True
def add_int(content):
result = 0
if content and '+' in content:
li_content = content.split('+')
for i in li_content:
i = i.strip()
if i and is_int(i):
result += int(i)
else:
print('最少输入两个整数相加')
return
else:
print('最少输入两个整数相加')
return
return result
input_content = input('请输入整数加法的内容:')
dic = {'最终计算结果': add_int(input_content)}
print(dic)
|
# 注册界面
while True:
print('<--注册界面-->')
username = input('请输入用户名:')
if username:
password = input('请输入密码:')
if password:
password_verify = input('请再次输入密码确认:')
if password == password_verify:
with open('auth', mode='w', encoding='utf-8') as f:
f.write('username:%s\npassword:%s' % (username, password))
print('注册成功!')
break
else:
print('两次密码输入不一致,请重新注册!')
else:
print('密码不能为空,请重新注册!')
else:
print('用户名不能为空,请重新注册!')
# 登录界面
count = 3
dict_auth = {}
with open('auth', mode='r', encoding='utf-8') as f:
for line in f:
list_line = line.strip().partition(':')
dict_auth[list_line[0]] = list_line[2]
print(dict_auth)
while count > 0:
print('<--登录界面-->')
username = input('请输入用户名:')
password = input('请输入密码:')
if (username == dict_auth['username']) and (password == dict_auth['password']):
print('登录成功!')
break
count -= 1
if count != 0:
print('登录失败!请重新登录!您还有%d次输入密码的机会' % count)
else:
print('登录失败!您已经连续输错3次,用户名已经锁住,请联系管理员!')
|
def sum_num(a, b, *args):
"""
求数字的和
:param a: 第一个数字
:param b: 第二个数字
:param args: 更多数字
:return: 所有数字的和
"""
sum_all = a + b
if args:
for i in args:
sum_all += i
return sum_all
print(sum_num(3, 4))
print(sum_num(3, 4, 5))
print(sum_num(3, 4, 5, 6))
|
#Linear Regression with placeholder
#Linear Regression이 뭔지 이전 프로그램에서 알아봤으니 변수바꾸는 placeholder을 사용해보자.
#시작하기 전에 코드를 보자.
import tensorflow as tf
x_data = [1.,2.,3.]
y_data = [1.,2.,3.]
# 기울기 W와 y절편 b를 찾아서 y_data = W * x_data +b를 계산할거야.
# 솔직히 간단해서 우리가 바로 보고 알 수 있지만텐서플로우가 직접 찾게 만들자.
#random uniform의 뜻이 뭐더라?
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
#float형 변수 X와 Y.
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
#가설 함수. x_data를 바로 넣어주지 않은 것을 볼 수 있다. Our Hypothesis
#placeholder을 사용한 이유는 hypothesis 식을 새로만들 필요가 없기 때문에.
#자바 기초에서 변수가 왜 필요하다고 했지? 일일이 만들기 귀찮으니까.
hypothesis = W*X+b
#간단하게 만든 cost function x_data를 바로 넣어주지 않은 것을 볼 수 있다..
cost = tf.reduce_mean(tf.square(hypothesis - Y))
a = tf.Variable(0.1) #Learning rate, alpha
optimizer = tf.train.GradientDescentOptimizer(a)
train = optimizer.minimize(cost)
#시작하기전에 변수들을 모두 초기화 시킨다. 이 초기화 시키는 것도 'run' 해야한다.
#TF 1.0 미만 버전에서는 init = tf.initialize_all_variables()
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for step in range(2001):
sess.run(train, feed_dict={X:x_data, Y:y_data}) #placeholder 부분에 x_data, y_data를 넣어줬다.
#함수를 실행시킬 때마다 feed_dict로 변수 넣어줘야한다.
if step %20 == 0:
print(step, sess.run(cost , feed_dict={X:x_data, Y:y_data}),sess.run(W),sess.run(b))
|
#/bin/python
#coding: utf-8
#author: ourfor
#date: 20190123
#description: 练习python里面的列表
print("练习Python里面的列表这种数据结构")
test=[1,2,4,8,'a']
print(test[3])
test[3]=test[3]+4
print(test[3])
print(test[0:4:2]) |
def prime():
x = int(input("What is the limit of prime numbers that you want to see?"))
for i in range (2, x+1):
count = 0
for j in range (2, i):
# Made another array so that it can divide the number in the first array too see if it is prime and is
# stops at i because if we are finding if 5 is a prime we divide up to 5 instead of 11 in our example.
if (i%j != 0):
count += 1
if count == i-2:
print (i)
# Prime numbers will have a count 2 less than itself because the mod will only equal 0 with 1 and itself.
prime()
# Will print 2, 3, 5, 7, 11 if the user inputs 11.
def primefac():
x = int(input("Prime factors for which number?"))
for i in range (2, x+1):
count = 0
for j in range (2, i):
if (i%j != 0):
count += 1
if count == i-2 and x%i == 0:
print (i)
# Same code as before but with an additional condition that it has to be a factor of the user input
primefac()
# Will print 2, 13 if the user inputs 26
def lettergrade():
x = int(input("What is your number grade?"))
if x >= 90 and x <= 100:
return ("A")
elif x >= 80 and x <= 89:
return ("B")
elif x >= 70 and x <= 79:
return ("C")
elif x >= 60 and x <= 69:
return ("D")
elif x >= 0 and x <= 59:
return ("F")
else:
return ("Invalid input!")
lettergrade()
# Will print A if the user inputs 100
def collatz():
x = int(input("What number do you want to start with?"))
print (x)
while x > 1:
if x%2 == 0:
x = x/2
print (x)
else:
x = (3*x)+1
print (x)
# Divides by 2 if even, and multiply by 3 and adds 1 if it is odd.
collatz()
# Will print 10, 5, 16, 8, 4, 2, 1 if the user inputs 10 |
from tkinter import *
#import tkinter.messagebox as tmsg
def click(event):
global scvalue
text = event.widget.cget("text")
print(text)
if text == "=":
if scvalue.get().isdigit():
value = int(scvalue.get())
else:
value = eval(screen.get())
scvalue.set(value)
screen.update()
elif text == "C":
scvalue.set("")
screen.update()
else:
scvalue.set(scvalue.get() + text)
screen.update()
root = Tk()
root.geometry("744x900")
root.title("MY CALCULATOR")
scvalue = StringVar()
scvalue.set("")
screen = Entry(root,textvar = scvalue, font = "lucida 40 bold")
screen.pack(fill=X,padx=15,pady=5)
f = Frame(root, bg="gray")
b = Button(f,text="9",font="lucida 36 bold",padx=15,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
b = Button(f,text="8",font="lucida 36 bold",padx=15,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
b = Button(f,text="7",font="lucida 36 bold",padx=15,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
b = Button(f,text="C",font="lucida 36 bold",padx=15,pady=5,bg="red")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
f.pack()
f = Frame(root, bg="gray")
b = Button(f,text="6",font="lucida 36 bold",padx=18,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
b = Button(f,text="5",font="lucida 36 bold",padx=18,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
b = Button(f,text="4",font="lucida 36 bold",padx=18,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
b = Button(f,text="/",font="lucida 36 bold",padx=18,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
f.pack()
f = Frame(root, bg="gray")
b = Button(f,text="3",font="lucida 36 bold",padx=17,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
b = Button(f,text="2",font="lucida 36 bold",padx=17,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
b = Button(f,text="1",font="lucida 36 bold",padx=17,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
b = Button(f,text="*",font="lucida 36 bold",padx=17,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
f.pack()
f = Frame(root, bg="gray")
b = Button(f,text=".",font="lucida 36 bold",padx=16,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
b = Button(f,text="0",font="lucida 36 bold",padx=16,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
b = Button(f,text="%",font="lucida 36 bold",padx=16,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
b = Button(f,text="+",font="lucida 36 bold",padx=16,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
f.pack()
f = Frame(root, bg="gray")
b = Button(f,text="(",font="lucida 36 bold",padx=20,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
b = Button(f,text=")",font="lucida 36 bold",padx=20,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
b = Button(f,text="-",font="lucida 36 bold",padx=20,pady=5,bg="green")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
b = Button(f,text="=",font="lucida 36 bold",padx=20,pady=5,bg="red")
b.pack(side = LEFT,padx=15,pady=5)
b.bind("<Button-1>",click)
f.pack()
root.mainloop() |
#dIFFERENCE BETWEEN AN ARRAY ANDA LIST
import numpy as np
x = np.array([1,3,5,7,9])
#divides every value in array by 3
print(x/3)
y = [1,3,5,7,9]
#wont work withought numpy array its not cmputational enough.
print(y/3) |
import sqlite3
from sqlite3 import Error
def create_connection(db_NEA):
""" creates a databse connection to sqlite database by specified db_file """
try:
conn = sqlite3.connect(db_NEA)
return(conn)
except Error as e:
print(e)
return None
def create_table(conn, create_table_sql):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)
def main():
database = "NEA.db"
sql_create_Teacher_table = """ CREATE TABLE IF NOT EXISTS Teacher (
id autonumber PRIMARY KEY
REFERENCES Student (id),
name text NOT NULL
); """
sql_create_Student_table = """CREATE TABLE IF NOT EXISTS Student (
id autonumber PRIMARY KEY,
name text NOT NULL
);"""
# create a database connection
conn = create_connection(database)
if conn is not None:
# create projects table
create_table(conn, sql_create_Teacher_table)
# create tasks table
create_table(conn, sql_create_Student_table)
else:
print("Error! cannot create the database connection.")
main()
|
#coding=utf-8
# Given a collection of intervals, merge all overlapping intervals.
# For example,
# Given [1,3],[2,6],[8,10],[15,18],
# return [1,6],[8,10],[15,18].
def merge(vs):
if vs==[]:
return vs
vs.sort(key=lambda x:x[0])
new=[]
for i in range(len(vs)-1):
if vs[i][1]<vs[i+1][0]:
new.append(vs[i])
else:
vs[i+1]=[vs[i][0],max(vs[i][1],vs[i+1][1])]
new.append(vs[-1])
return new
|
'''
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 = 25.
'''
|
'''
There are a number of spherical balloons spread in two-dimensional space.
For each balloon, provided input is the start and end coordinates of the horizontal diameter.
Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice.
Start is always smaller than end. There will be at most 10^4 balloons.
An arrow can be shot up exactly vertically from different points along the x-axis.
A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend.
There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely.
The problem is to find the minimum number of arrows that must be shot to burst all balloons.
Example:
Input:
[[10,16], [2,8], [1,6], [7,12]]
Output:
2
Explanation:
One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).
'''
def findMinArrowShots(points):
if len(points) == 0: return 0
points = sorted(points, key = lambda x:x[1])
res, end = 0, -float('inf')
for item in points:
if item[0] > end:
res += 1
end = item[1]
return res |
#
# Given 2 int values, return True if one is negative and one is positive.
# Except if the parameter "negative" is True, then return True only if both are negative.
#
#
# pos_neg(1, -1, False) → True
# pos_neg(-1, 1, False) → True
# pos_neg(-4, -5, True) → True
num1 = int(input('Enter the first num: '))
num2 = int(input('Enter the second num: '))
if num1 or num2 == -=:
print('Negative') |
import random
while True:
bullet_position = 2
def fire_gun():
camber_position = random.randint(1, 6)
print(camber_position)
if camber_position == bullet_position:
print("you are dead!")
else:
print("keep playing!")
answer = input('Do you want to play again? (Y/N)')
if answer.lower() == 'y' or answer.lower() == 'yes':
fire_gun()
else:
break
print(fire_gun())
|
def leap(year):
if year % 4 == 0 and year % 100 != 0 or year % 100 == 0 and year % 400 == 0:
return True
else:
return False
def datefinder(days,year):
months = {'JANUARY':31, 'FEBRUARY':28, 'MARCH':31, 'APRIL':30, 'MAY':31, 'JUNE':30, 'JULY':31, 'AUGUST':31, 'SEPTEMBER':30, 'OCTOBER':31, 'NOVEMBER':30,
'DECEMBER':31}
copy_days = days
m = 0
day = 0
if leap(year):
months['FEBRUARY'] = 29
for month in months.keys():
m = month
if copy_days < months[month]:
break
copy_days -= months[month]
return str(copy_days) +' TH ' + m +','+str(year)
n = int(input('DAY NUMBER: '))
y = int(input('YEAR: '))
nd = int(input('DATE AFTER (N DAYS):'))
if not 0 < n < 366:
print('DAY NUMBER OUT OF RANGE')
exit()
if not 0 < nd < 101:
print('DATE AFTER (N DAYS) OUT OF RANGE')
exit()
print(datefinder(n,y))
if n + nd > 365:
print(datefinder((n + nd) - 365, y+1))
elif n + nd > 364:
print(datefinder((n + nd) - 364, y+1))
else:
print(datefinder(n + nd, y))
|
def bin(n):
#generate binary
res = ''
n = int(n)
while n:
r = n%2
res = res + str(r)
n = n//2
return res[::-1]
n = input('INPUT: ')
if int(n) > 100:
print('OUT OF RANGE')
exit()
binary = bin(n)
print(f'BINARY EQUIVALENT: {binary}',f"NUMBER OF 1's: {binary.count('1')}", sep='\n')
print({True:"EVIL", False:"Not Evil"}[binary.count('1')%2 == 0]) |
sent = input('')
if sent[-1] not in '?.!':
print('Invalid Input')
exit()
op =''
input('WORD TO BE DELETED: ')
dpos = int(input('WORD POSITION IN THE SENTENCE: '))
for k, word in enumerate(sent.split(), start=1):
word.strip()
if k == dpos:
pass
else:
op = op + word + ' '
print(op)
|
def prime(num):
for i in range(2, num):
if num % i == 0:
return False
return True
m = int(input('M = '))
n = int(input('N = '))
if not 0 < m < 3000 or not 0 < n < 3000 or m > n:
print('INVALID/OUT OF RANGE')
exit()
pnum_lis = []
for num in range(m, n +1):
if str(num)[::-1] == str(num) and prime(num):
pnum_lis.append(num)
print('THE PRIME PALINDROME INTEGERS ARE: ')
print(*pnum_lis,sep=', ')
print(f' FREQUENCY OF PRIME PALINDROME INTEGERS : {len(pnum_lis)}') |
# import turtle
# name = input("What is your name?")
# print("Hello, " + name + "!")
# turtle.speed(5)
# turtle.goto(0,0)
# for i in range(4):
# turtle.forward(100)
# turtle.right(100)
# turtle.home()
# turtle.circle(50,270) # turtle包在python3可能不兼容
# 打印圆的周长: (注释)
pi = 3.14
radius = 6
print(2 * pi * radius)
# 'Let\'s go!' 对引号进行转义
print("Hello,\nworld") # \n表示换行
print('''This is a very long string. It continues here.
And it's not over yet. "Hello, world!"
Still here.''') # 三引号表示长字符串s
print(r"C:\nowhere")
print(r'This is illegal\\')
print(r'C:\Program Files\foo\bar' '\\')
print(r'This is illegal' '\\') |
import math, pylab, scipy, numpy
g = 9.81 # acceleration
ax = 0 # acceleration from x
ay = -9.81 # acceleration from y
v0 = 30.0 # initial velocity
angle = 30.0 # launch angle (degrees)
dt= numpy.arange(0,5,0.001) # time intervalle
pylab.xlim(0,80)
pylab.ylim(0,12)
old_dx = 0.0 # displacement dx (X-axis) at the initial position = 0
old_dy = 0.0 # displacement dy (Y-axis) at the initial position = 0
vx = v0*math.cos(angle*math.pi/180.0) # velocity vx (X-axis)
vy = v0*math.sin(angle*math.pi/180.0) # velocity vy (Y-axis)
# calcul of the displacement
def calcul_displacement(dx,dy,vxi,vyi,dt):
vxi,vyi = calcul_velocity(ax,ay,dt)
dxi = dx + vxi*dt + (1/2)*ax*dt**2
dyi = dy + vyi*dt + (1/2)*ay*dt**2
return 2*dxi,2*dyi # 2* is here to make up the intervalle error
# calcul of the velocity
def calcul_velocity(ax,ay,dt):
vxi = vx + ax * dt
vyi = vy + ay * dt
return vxi,vyi
# MAIN
r=(2*vx*vy)/g # range of the shoot
h=(v0*v0*(math.sin(math.radians(angle))**2))/(2*g) # height of the shoot
print"Range =", r, "meters"
print"Height =", h, "meters"
new_dx,new_dy=calcul_displacement(old_dx,old_dy,vx,vy,dt)
old_dx=new_dx
old_dy=new_dy
pylab.plot(new_dx,new_dy)
pylab.show()
|
def say_hello():
# block belonging to the function
print('hello world')
# end of function
say_hello() # call the function
#say_hello() # call the function again
# New function from here
def print_max(a, b):
if a > b:
print(a, 'is maximu')
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')
# Directly pass literal values
print_max(3, 4)
x = 5
y = 7
# pass variable as arguments
print_max(x,y) |
class SchoolMember:
'''Represent any school member'''
def __int__(self,name,age): #What does __init__ do ????
self.name = name
self.age = age
print('(Initializing schoolMember: {})'.format(self.name))
def tell(self):
'''Tell my details'''
print('Name: "{}" Age: "{}"'.format(self.name, self.age), end='')
class Teacher(SchoolMember):
'''Represent a teacher'''
def __init__(self, name, age,salary):
SchoolMember.__init__(self,name, age)
self.salary = salary
print('(Initialized Tacher: {})'.format(self.name))
def tell(self):
SchoolMember.tell(self)
print('Salary: "{d}"'.format(self.salary))
class Student(SchoolMember):
'''Represent student'''
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print('(Initialized student: {})'.format(self.name))
def tell(self):
SchoolMember.tell(self)
print('Marks: {}'.format(self.marks))
t = Teacher('Major Mbinda', 40, 5000000)
s = Student('2Lt David', 30, 95)
# Print a blank line
print()
members = [t, s]
for member in members:
# Works for both teacher and student
member.tell()
|
def and_(a,b,c):
result=list()
if (a and b)==c:result.append("AND")
if(a or b)==c:result.append("OR")
if(a != b)==c:result.append("XOR")
return result
def print_(rel):
if len(rel)==0:
print("IMPOSSIBLE")
return
for x in range(len(rel)):print(rel[x])
return
keyin=list(map(int,input().split()))
print_(and_(bool(keyin[0]),bool(keyin[1]),bool(keyin[2])))
|
while True:
# > The problem requires multiple test materials.
try:i,j=map(int,input().split())
# > i,j is the range of data entered by user.
except:break
# > Stop the program when the input is over.
def lenghgenerater(n,step):
while True:
# > start to caculate the 3n+1 of n.
step+=1
# > Recording steps.
if n==1:return step
# > Stop calculation until the calculated value is equal to 1.
n=(3*n+1 if n%2 !=0 else n/2)
# > If the number is odd, multiply by 3 and add 1 else divide by 2.
lengh=list()
print(i,j,end=' ')
if i>j:i,j=j,i
for x in range(i,j+1):lengh.append(lenghgenerater(x,-1))
print(max(lengh))
|
def kioro (num):#判斷奇數偶數
if(num%2)==0:return 1
else:return 0
def count_(num):#計算3n+1的次數
len_=0
while num!=1:
if(kioro(num)==0):
num=num*3+1
len_+=1
else:
num=num//2
len_+=1
return len_+1
def findmax(x,y):#取得數據之中的計算結果的最大值
print(x,y,end=" ")
if x>y:x,y=y,x
max_=0
for k in range(x,y+1,1):
if count_(k)>max_:max_=count_(k)
print(max_)
return
while True:#多測資
try:line=input()
except:break;
data=list(map(int,line.split()))
findmax(data[0],data[1])
|
#-#-# Question 2 -: write a Program Using for loop to print prime nos between 1-1000. #-#-#
# HEy I am using Pycharm IDE
print("Prime Number between 1-1000 are -: ")
for num in range(1,1000 + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print("\t",num)
|
#Try 5 different functions of Lists in python ?
# Hey! I am using the PyCharm Editor for Python coding
print("Functions of List")
Lst=["Saurabh","Pawar",1,2,3,1.2,1.3,["Daund",1,1.2],44]
#Accessing the last element of list
print(Lst[-1])
#Getting the position of specific element
print(Lst.count("Pawar"))
#Removing Element From the list
Lst.remove(44)
print(Lst)
#Inserting Element
Lst.insert(3,55)
print(Lst)
#inserting the element at last by append method
Lst.append("XYZ")
print(Lst)
#Reversing the List
Lst.reverse()
print(Lst)
#Copying the List
Lst1=Lst.copy()
print(Lst1)
#Clear the whole List
Lst.clear()
print(Lst) |
# Assignment 5: Implement Heapsort and Quicksort accordingly.
# Pranpreya Samasutthi (st122602)
import math
from random import randint
random_list = []
def build_max_heap(arr):
half_to_root = math.ceil(len(arr)/2)
for i in range(half_to_root-1, -1, -1):
max_heapify(arr, len(arr), i)
def max_heapify(arr, n, i):
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[i]:
largest = left
else:
largest = i # largest = root (heap.size)
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i: # When root is not biggest number
# exchange arr[i] with arr[largest]
temp = arr[i]
arr[i] = arr[largest]
arr[largest] = temp
max_heapify(arr, n, largest)
def heapsort(arr):
n = len(arr)
build_max_heap(arr)
for i in range(n - 1, 0, -1):
# exchange arr[0] with arr[i]
temp = arr[0]
arr[0] = arr[i]
arr[i] = temp
max_heapify(arr, i, 0)
def quicksort(arr, p, r):
if p < r:
x = partition(arr, p, r)
quicksort(arr, p, x - 1)
quicksort(arr, x + 1, r)
def partition(arr, p, r):
x = arr[r]
i = (p - 1)
for j in range(p, r):
if arr[j] <= x:
i = i + 1
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
temp1 = arr[i + 1]
arr[i+1] = arr[r]
arr[r] = temp1
return i + 1
def random():
random_amount = int(input("Enter amount that you want to sort: "))
print("Random numbers are: ")
# Random number follow amount that user input
for _ in range(random_amount):
value = randint(-50, 50)
print(value, end=" ")
random_list.append(value)
def main():
# Input Type of sort
sort = input("Enter 'H' for Heapsort sort or 'Q' for Quicksort: ")
if sort == 'H' or sort == 'h':
random()
heapsort(random_list)
print('\nAfter finishing Heapsort: ')
for i in range(len(random_list)):
print(random_list[i], end=" ")
elif sort == 'Q' or sort == 'q':
random()
quicksort(random_list, 0, len(random_list)-1)
print('\nAfter finishing Quicksort: ')
for i in range(len(random_list)):
print(random_list[i], end=" ")
else:
print("Your input is incorrect, please try again.")
main()
|
def prime_factorize(n):
a = []
while n % 2 == 0:
a.append(2)
n //= 2
f = 3
while f * f <= n:
if n % f == 0:
a.append(f)
n //= f
else:
f += 2
if n != 1:
a.append(n)
return a
# import numpy as np
t = int(input())
ans = []
for _ in range(t):
n = int(input())
l = prime_factorize(n)
L = l[0]
R = l[-1]
if L == R and len(l) > 3:
R *= l[-2]
l.pop(-1)
if len(l) >=3 and L != R:
# prod = np.prod(l[1:-1])
prod = 0
for i in range(len(l[1:-1])):
prod = prod*(l[1+i]) if prod != 0 else l[1]
if prod != L and prod != R:
ans.append('YES')
ans.append(str(L) + ' ' + str(prod) + ' ' + str(R))
else:
ans.append('NO')
else:
ans.append('NO')
for i in range(len(ans)):
print(ans[i]) |
n = int(input())
ans = 'Bad'
if n == 100:
ans = 'Perfect'
elif 90 <= n:
ans = 'Great'
elif 60 <= n:
ans = 'Good'
print(ans)
|
import sys
while True :
n_time = []
c = ''
time = raw_input('Type the time in the format"hh:mm:ss(AM/PM)":\n').strip()
for i in time:
if (not i.isdigit()) and (not i == ':'):
n_time.append(i)
t = ''.join(n_time)
while int(time[0:2]) > 12:
print "Something is wrong with your input. Try again."
time = raw_input('Type the time in the format"hh:mm:ss(AM/PM)":\n').strip()
if t == 'PM':
if int(time[0:2]) == 12:
c = int(time[0:2])
else:
c = int(time[0:2]) + 12
elif t == 'AM':
if int(time[0:2]) == 12:
c = '00'
else:
c = int(time[0:2])
print str(c)+ time[2:-2]
|
import matplotlib
import matplotlib.pyplot as plt
import csv
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
def graph():
with open("monte-carlo-liberal.csv") as montecarlo:
data = csv.reader(montecarlo, delimiter=',') # Easily read contents from csv file (We could have used Pandas
for line in data:
percentROI = float(line[0])
wager_size_percent = float(line[1])
wager_count = float(line[2])
p_color = line[3]
ax.scatter(wager_size_percent, wager_count, percentROI, color=p_color) # Graph 3D
ax.set_xlabel('wager percent size')
ax.set_ylabel('wager count')
ax.set_zlabel('Percent ROI')
plt.show()
graph() |
import sys
import random #only for random_bot
#player switcher
def player_switcher(cp):
if cp == "X":
return("O")
elif cp == "O":
return("X")
else:
return(None)
#starting variables
current_player = "X"
win = 0
winner = "temp"
free_spots = [1,2,3,4,5,6,7,8,9]
starting_field = ["1","2","3","4","5","6","7","8","9"]
X_spots = []
O_spots = []
player_spots = []
bot_spots = []
bot = None
bot_player = None
while bot not in ["y","n"]:
bot = input("Would you like to play against a bot? y/n\n")
if bot == "y":
while bot_player not in ["X","O"]:
bot_player = player_switcher(input("Do you want to have the first (X) or second (O) turn?\n"))
current_player = player_switcher(bot_player)
#play agaist a bot
def show_field():
for i in range(len(starting_field)):
if (i+1) % 3 == 1:
print(starting_field[i]+"|"+starting_field[i+1]+"|"+starting_field[i+2])
#win conndition
def winning(starting_field):
if starting_field[0] == starting_field[1] == starting_field[2]:
return([starting_field[0], 1])
elif starting_field[3] == starting_field[4] == starting_field[5]:
return([starting_field[3], 1])
elif starting_field[6] == starting_field[7] == starting_field[8]:
return([starting_field[6], 1])
elif starting_field[0] == starting_field[3] == starting_field[6]:
return([starting_field[0], 1])
elif starting_field[1] == starting_field[4] == starting_field[7]:
return([starting_field[1], 1])
elif starting_field[2] == starting_field[5] == starting_field[8]:
return([starting_field[2], 1])
elif starting_field[0] == starting_field[4] == starting_field[8]:
return([starting_field[0], 1])
elif starting_field[2] == starting_field[4] == starting_field[6]:
return([starting_field[2], 1])
else:
return(["temp", 0])
#runnig the game against a friend
while(len(free_spots) != 0 and win == 0 and bot == "n"):
show_field()
new_value = int(input("\n"+"Player "+current_player+" choose a field: "))
while new_value not in free_spots:
print("Wrong input or spot already taken.")
new_value = int(input("\n"+"Player "+current_player+" choose a field: "))
free_spots.remove(new_value)
starting_field[new_value-1] = current_player
if current_player == "X":
X_spots.append(new_value)
else:
O_spots.append(new_value)
print(X_spots, O_spots)
current_player = player_switcher(current_player)
winner, win = winning(starting_field)
#runnig the game against a bot
def random_decision():
return random.choice(free_spots)
def perfect_decision():
#print(starting_field)
if 5 in free_spots:
return(5)
elif len(free_spots) == 1:
return(free_spots[0])
elif starting_field[5] != "5" and len(free_spots) == 8:
return(random.choice([1,3,7,9]))
#deadlock preventions:
elif all(elem in player_spots for elem in [1,9]) and 4 in free_spots:
return(4)
elif all(elem in player_spots for elem in [3,7]) and 4 in free_spots:
return(4)
#all horizontal wins
elif all(elem in bot_spots for elem in [1,2]) and 3 in free_spots:
return(3)
elif all(elem in bot_spots for elem in [1,3]) and 2 in free_spots:
return(2)
elif all(elem in bot_spots for elem in [2,3]) and 1 in free_spots:
return(1)
elif all(elem in bot_spots for elem in [4,5]) and 6 in free_spots:
return(6)
elif all(elem in bot_spots for elem in [4,6]) and 5 in free_spots:
return(5)
elif all(elem in bot_spots for elem in [5,6]) and 4 in free_spots:
return(4)
elif all(elem in bot_spots for elem in [7,8]) and 9 in free_spots:
return(9)
elif all(elem in bot_spots for elem in [7,9]) and 8 in free_spots:
return(8)
elif all(elem in bot_spots for elem in [8,9]) and 7 in free_spots:
return(7)
#all vectical wins
elif all(elem in bot_spots for elem in [1,4]) and 7 in free_spots:
return(7)
elif all(elem in bot_spots for elem in [1,7]) and 4 in free_spots:
return(4)
elif all(elem in bot_spots for elem in [4,7]) and 1 in free_spots:
return(1)
elif all(elem in bot_spots for elem in [2,5]) and 8 in free_spots:
return(8)
elif all(elem in bot_spots for elem in [2,8]) and 5 in free_spots:
return(5)
elif all(elem in bot_spots for elem in [5,8]) and 2 in free_spots:
return(2)
elif all(elem in bot_spots for elem in [3,6]) and 9 in free_spots:
return(9)
elif all(elem in bot_spots for elem in [3,9]) and 6 in free_spots:
return(6)
elif all(elem in bot_spots for elem in [6,9]) and 3 in free_spots:
return(3)
#all diagonal wins
elif all(elem in bot_spots for elem in [1,5]) and 9 in free_spots:
return(9)
elif all(elem in bot_spots for elem in [1,9]) and 5 in free_spots:
return(5)
elif all(elem in bot_spots for elem in [5,9]) and 1 in free_spots:
return(1)
elif all(elem in bot_spots for elem in [3,5]) and 7 in free_spots:
return(7)
elif all(elem in bot_spots for elem in [3,7]) and 5 in free_spots:
return(5)
elif all(elem in bot_spots for elem in [5,7]) and 3 in free_spots:
return(3)
#all horizontal preventions:
elif all(elem in player_spots for elem in [1,2]) and 3 in free_spots:
return(3)
elif all(elem in player_spots for elem in [1,3]) and 2 in free_spots:
return(2)
elif all(elem in player_spots for elem in [2,3]) and 1 in free_spots:
return(1)
elif all(elem in player_spots for elem in [4,5]) and 6 in free_spots:
return(6)
elif all(elem in player_spots for elem in [4,6]) and 5 in free_spots:
return(5)
elif all(elem in player_spots for elem in [5,6]) and 4 in free_spots:
return(4)
elif all(elem in player_spots for elem in [7,8]) and 9 in free_spots:
return(9)
elif all(elem in player_spots for elem in [7,9]) and 8 in free_spots:
return(8)
elif all(elem in player_spots for elem in [8,9]) and 7 in free_spots:
return(7)
#all vectical preventions
elif all(elem in player_spots for elem in [1,4]) and 7 in free_spots:
return(7)
elif all(elem in player_spots for elem in [1,7]) and 4 in free_spots:
return(4)
elif all(elem in player_spots for elem in [4,7]) and 1 in free_spots:
return(1)
elif all(elem in player_spots for elem in [2,5]) and 8 in free_spots:
return(8)
elif all(elem in player_spots for elem in [2,8]) and 5 in free_spots:
return(5)
elif all(elem in player_spots for elem in [5,8]) and 2 in free_spots:
return(2)
elif all(elem in player_spots for elem in [3,6]) and 9 in free_spots:
return(9)
elif all(elem in player_spots for elem in [3,9]) and 6 in free_spots:
return(6)
elif all(elem in player_spots for elem in [6,9]) and 3 in free_spots:
return(3)
#all diagonal preventions
elif all(elem in player_spots for elem in [1,5]) and 9 in free_spots:
return(9)
elif all(elem in player_spots for elem in [1,9]) and 5 in free_spots:
return(5)
elif all(elem in player_spots for elem in [5,9]) and 1 in free_spots:
return(1)
elif all(elem in player_spots for elem in [3,5]) and 7 in free_spots:
return(7)
elif all(elem in player_spots for elem in [3,7]) and 5 in free_spots:
return(5)
elif all(elem in player_spots for elem in [5,7]) and 3 in free_spots:
return(3)
else:
(print("should never happen"))
return(free_spots[0])
if current_player == "X":
bot_turn = 1
else:
bot_turn = 0
while(len(free_spots) != 0 and win == 0 and bot == "y"):
show_field()
if bot_turn == 0:
print("\nThe Bots turn:")
# new_value_bot = random_decision()
new_value_bot=perfect_decision()
bot_spots+=[new_value_bot]
starting_field[new_value_bot-1] = bot_player
free_spots.remove(new_value_bot)
bot_turn += 1
else:
new_value = int(input("\n"+"Player "+current_player+" choose a field: "))
while new_value not in free_spots:
print("Wrong input or spot already taken.")
new_value = int(input("\n"+"Player "+current_player+" choose a field: "))
bot_turn -= 1
player_spots+=[new_value]
starting_field[new_value-1] = current_player
free_spots.remove(new_value)
winner, win = winning(starting_field)
print(bot_spots, player_spots)
#final lines
show_field()
if len(free_spots) == 0:
print("Tie!")
else:
print("The winner is "+winner+"!") |
"""
Strategy class with all implemented strategies
"""
import random
def closest_pos(pos):
"""
Return figure that is closest to home
"""
completed_board_list = [] # figures that completed board, but aren't finished yet
closest_list = []
closest = None
# pylint:disable=invalid-name
for p in pos:
if p[1] is True and p[0] != -2:
completed_board_list.append(p)
else:
closest_list.append(p)
if len(completed_board_list) > 0:
closest = max(completed_board_list)
else:
closest = max(closest_list)
return closest
def closest_pos_to_enemy(pos, game, roll):
"""
Return figure that would destroy enemy when moved
"""
if game.turn == 0:
enemy_turn = 1
if game.turn == 1:
enemy_turn = 0
closest_list = []
# pylint:disable=invalid-name
for p in pos:
for enemy_p in game.players[enemy_turn].pos:
if p[1] is False and enemy_p[1] is False:
if (p[0] + roll) == enemy_p[0]:
closest_list.append(p)
# print(f"Closest to enemy: {p[0]} -- {enemy_p[0]}")
if len(closest_list) > 0:
return random.choice(closest_list)
return None
class Strategy:
"""
Main Strategy class structure
"""
def move_place_choice(self, game, player, roll):
"""
If you roll 6, have at least one figure and at least one figure available at start.
You will decide to move or place.
"""
def move_choice(self, game, player, roll):
"""
If you have more than one figure on board.
You will decide which figure to move.
"""
class Random(Strategy):
"""
Strategy: Randomly choose to place a figure or move and randomly choose figure to move.
"""
def move_place_choice(self, game, player, roll):
place_or_move = random.randint(0, 1)
if place_or_move == 0:
player.place_figure(game)
else:
figure = random.choice(player.figures_on_board())
game.move(player, figure, roll)
def move_choice(self, game, player, roll):
figure = random.choice(player.figures_on_board())
game.move(player, figure, roll)
class MoveCloserToHome(Strategy):
"""
Strategy: When you roll 6 and there is figure that is close to home then move with it.
Else, place a new figure.
"""
def move_place_choice(self, game, player, roll):
closest = closest_pos(player.pos)
if game.turn == 0 and closest[0] >= 7:
figure = player.pos.index(closest)
game.move(player, figure, roll)
elif game.turn == 1 and closest[0] >= 2:
figure = player.pos.index(closest)
game.move(player, figure, roll)
else:
player.place_figure(game)
def move_choice(self, game, player, roll):
figure = player.pos.index(closest_pos(player.pos))
game.move(player, figure, roll)
class MoveCloserToEnemy(Strategy):
"""
Strategy: When there is figure that you can destroy then destroy it,
else move closest figure to home.
Move with figure that will destroy enemy.
"""
def move_place_choice(self, game, player, roll):
# code from MoveCloserToHome strategy
closest_enemy = closest_pos_to_enemy(player.pos, game, roll)
closest = closest_pos(player.pos)
if closest_enemy is not None:
figure = player.pos.index(closest_enemy)
game.move(player, figure, roll)
else:
if game.turn == 0 and closest[0] >= 7:
figure = player.pos.index(closest)
game.move(player, figure, roll)
elif game.turn == 1 and closest[0] >= 2:
figure = player.pos.index(closest)
game.move(player, figure, roll)
else:
player.place_figure(game)
def move_choice(self, game, player, roll):
closest = closest_pos_to_enemy(player.pos, game, roll)
if closest is not None:
figure = player.pos.index(closest)
else:
figure = player.pos.index(closest_pos(player.pos))
game.move(player, figure, roll)
|
#PASSWORD GENERATOR
from numpy import random
set_alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
set_upper_alphabet = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
set_number = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
set_symbol = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '-', '=', '+', '/', '?']
random.shuffle(set_alphabet)
random.shuffle(set_upper_alphabet)
random.shuffle(set_number)
random.shuffle(set_symbol)
user_input1 = input("How long they want their password to be?. Minimum 6 characters: ")
print("The password is", user_input1, "characters long")
user_input_alphabet = input("How many letters you want in your password? ")
user_input_upper_alphabet = input("How many upper letters you want in your password? ")
user_input_number = input("How many digits you want in your password? ")
user_input_symbol = input("How many symbols you want in your password? ")
password = set_alphabet[0:int(user_input_alphabet)] + set_upper_alphabet[0:int(user_input_upper_alphabet)] + set_number[0:int(user_input_number)] + set_symbol[0:int(user_input_symbol)]
random.shuffle(password)
strPassword = ''.join(password)
print(strPassword) |
# For Testing:
# Naive solution for generating the Recamann sequence
# Put numbers into a dict as they are generated
import sys
def main(end):
n = 0
database = {}
while jump < end:
key = n - jump
if key in database or key < 0:
n = n + jump
else:
n = key
print(n, "\t\t\t\t", jump + 1)
database[n] = True
jump = jump + 1
if __name__ == "__main__":
main(int(sys.argv[1])) |
import sys
import os
from PIL import Image
#grab first and second argument with the image's paths arguments in sys would be JPGtoPNGconverter.py [0] Pokedex/ [1] new/ [2]
#which means that the terminal comand will be: python3 JPGtoPNGconverter.py Pokedex/ New/
image_folder = sys.argv[1]
output_folder = sys.argv[2]
#check if the output folder exists if not it should be created
if not os.path.exists(output_folder):
os.makedirs(output_folder)
#loop through the folder grab each image and convert them to the new folder
for filename in os.listdir(image_folder):
clean_name = os.path.splitext(filename)[0] #function output would be a tupple ('nameofthefile', 'extension') that's why [0] was used
img = Image.open(f'{image_folder}{filename}')
img.save(f'{output_folder}/{clean_name}.png', 'png')
print('Images converted and saved on new folder')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 27 20:14:29 2019
@author: tylersschwartz
"""
def get_start_balance():
"""Requests the user's current loan balance, returns an int."""
while True:
try:
balance = int(input("Enter your starting balance: "))
if balance > 0:
return balance
else:
print("Starting balance must be greater than zero.")
except ValueError:
print("Starting balance must be an integer.")
def get_annual_interest():
"""Requests the user's annual interest rate, returns a float."""
while True:
try:
annual_interest_rate = float(input("Enter your annual interest rate percentage: "))
if annual_interest_rate > 0:
return annual_interest_rate
else:
print("Interest rate must be more than zero.")
except ValueError:
print("Interest rate must be a percentage, ie: 0.25.")
def calc_lowest_payment(balance: int, annual_interest_rate: float):
"""Calculates the lowest payment required to pay off the balance in 12 months,
factoring in compound interest. Takes in an int and a float. Returns a float."""
lowest_pay = 0
balance_left = balance
low = balance / 12
high = (balance * (1 + annual_interest_rate) ** 12) / 12
while abs(balance_left) >= 0.01:
balance_left = balance
for i in range(12):
balance_left = balance_left - (lowest_pay)
balance_left = balance_left + (balance_left * annual_interest_rate / 12)
if balance_left < 0.01:
high = lowest_pay
else:
low = lowest_pay
lowest_pay = (high + low) / 2.0
return lowest_pay
balance = get_start_balance()
annual_interest_rate = get_annual_interest()
lowest_pay = calc_lowest_payment(balance, annual_interest_rate)
print("Your minimum monthly payment to payoff balance in 12 months is:" , round(lowest_pay, 2))
|
# ================================================== Hash Functions =================================================
def hash_string_unweighted(astring, table_size):
"""Simple Hash Function for Strings."""
temp = 0
for pos in range(len(astring)):
temp = temp + ord(astring[pos])
print(f'The value of "{astring}" is {temp}. The table size is {table_size}. The hash value is {temp%table_size}.')
return temp % table_size
def hash_string_weighted(astring, table_size):
"""Simple Weighted Hash Function for Strings. The letter index, starting at 1, is multiplied with ord."""
temp = 0
for counter, pos in enumerate(range(len(astring)), start=1):
temp = temp + (ord(astring[pos])*counter)
print(f'The value of "{astring}" is {temp}. The table size is {table_size}. The hash value is {temp%table_size}.')
return temp % table_size
def hash_string_custom(astring, table_size):
"""Simple Custom Hash Function for Strings. Uses hash value of previous letter."""
temp = 0
for pos in range(len(astring)):
temp = temp + (ord(astring[pos])*(ord(astring[pos-1]) % table_size))
print(f'The value of "{astring}" is {temp}. The table size is {table_size}. The hash value is {temp%table_size}.')
return temp % table_size
def hash_string_test():
print(hash_string_unweighted('cat', 11))
print(hash_string_weighted('cat', 11))
print(hash_string_custom('cat', 11))
items = ['Ryan', 'John', 'Chris', 'Rebbecca', 'Michael', 'Issac', 'Kevin', 'Andrew', 'Sally', 'Samantha'] # len 10
hash_list = [None] * len(items)
counter = 0
for item in items:
hash_value = hash_string_custom(item, len(items))
if hash_value not in hash_list:
hash_list[counter] = hash_value
counter += 1
collisions = 0
for hash_value in hash_list:
if hash_value is None:
collisions += 1
print(f'Our Hash List is: {hash_list} meaning there were {collisions} collisions.\n')
# Perfect hash function attempt.
items = ['a', 'aa', 'aaa', 'A', 'AA', 'AAA', 'AaA', 'aAa', 'Aaa', 'aAA']
hash_list = []
for item in items:
hash_list.append(hash(item))
print(hash_list)
hash_string_test()
# ================================================ Hash Table Linear ===============================================
class HashTableLinear:
"""This is the hash table class"""
def __init__(self, size):
"""Initialize hash table variables."""
self.size = size
self.slots = [None] * self.size
self.data = [None] * self.size
def __len__(self):
"""Return hash table size. O(1)."""
return int(self.size)
def __contains__(self, key):
"""Determines if key is in hash table. O(1)."""
if self.__getitem__(key) is None:
return False
return True
def __getitem__(self, key):
"""Get data from hash table. O(1)."""
return self.get(key)
def __setitem__(self, key, data):
"""Put data in hash table. O(1)."""
self.put(key, data)
def __str__(self):
"""Returns a string of all occupied slots and data from the hash table. O(N)."""
return "Slot List " + str(self.slots) + " \nData List " + str(self.data)
def put(self, key, data):
"""Stores key and data into hash table. If load factor exceeds 70%, resize hash table. O(1)."""
# Get hash value of key.
hash_value = self.hash_function(key, len(self.slots))
hash_value_start = hash_value
# Allowed hash table to dynamically adjust size as load increases.
load_factor = len([a for a in self.data if a is not None]) / len(self)
if load_factor >= .7:
temp_slots = [None] * self.size
temp_data = [None] * self.size
self.size *= 2
self.slots = self.slots + temp_slots
self.data = self.data + temp_data
# If slot corresponding to hash value is empty, set slot and data.
if self.slots[hash_value] is None:
self.slots[hash_value] = key
self.data[hash_value] = data
else:
# If slot corresponding to hash value is equal to key, replace data.
if self.slots[hash_value] == key:
self.data[hash_value] = data
else:
# If slot corresponding to hash value is not equal to key and is not empty, rehash hash value.
next_slot = self.rehash(hash_value, len(self.slots))
while self.slots[next_slot] is not None and self.slots[next_slot] != key:
next_slot = self.rehash(next_slot, len(self.slots))
# Set slot and data.
if self.slots[next_slot] is None:
self.slots[next_slot] = key
self.data[next_slot] = data
else:
self.data[next_slot] = data
def get(self, key):
"""Returns the data corresponding to key from hash table. If slot for key is not found, return None. O(1)."""
# Gets hash value of key.
start_slot = self.hash_function(key, len(self.slots))
position = start_slot
# Search slots for key.
while self.slots[position] is not None:
# If key is found, return data.
if self.slots[position] == key:
return self.data[position]
# If key is not found, rehash new position.
position = self.rehash(position, len(self.slots))
if position == start_slot:
return None
def hash_function(self, key, size):
"""Returns remainder of being divided by hash table size. O(1)."""
return key % size
def rehash(self, old_hash, size):
"""Increases hash slot by 1 if previous hash value had collision. O(1)."""
return (old_hash + 1) % size
def test_1():
hash_table.put(193, 193)
hash_table.put(241, 241)
hash_table.put(92, 92)
hash_table.put(50, 50)
hash_table.put(51, 51)
hash_table.put(140, 140)
print(hash_table.get(193))
if len(hash_table) > 10:
print('Hash size is greater than 10.')
for number in range(1, 300):
if number in hash_table:
print(f'{number} is in the hash table.')
print(hash_table)
def test_2():
hash_table.put(50, 50)
hash_table.put(1, 1)
hash_table.put(2, 2)
hash_table.put(3, 3)
hash_table.put(4, 4)
hash_table.put(5, 5)
hash_table.put(6, 6)
print(hash_table)
if 50 in hash_table:
print(f'50 is in the hash table.')
hash_table.put(55, 55)
print(hash_table)
hash_table = HashTableLinear(10)
test_1()
test_2()
# ================================================ Hash Table Quadratic ===============================================
class HashTableQuadratic:
def __init__(self, size):
self.table_size = int(size)
self.slot_list = [None] * self.table_size
self.data_list = [None] * self.table_size
self.max_load_factor = .7
self.rehash_counter = 1
def __len__(self):
return self.table_size
def __str__(self):
return "Slot List " + str(self.slot_list) + " \nData List " + str(self.data_list)
def __contains__(self, key):
if self.get(key) is not None:
return True
return False
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, data):
self.put(key, data)
def __delitem__(self, key):
self.delete(key)
def delete(self, key):
start = self.hash_function(key)
position = start
self.rehash_counter = 1
while self.slot_list[position] is not None:
if self.slot_list[position] == key:
# If key is found, set to None and reset all positions that appear after it until None is hit.
# This is because all collided values will need to be readjusted.
print(f'Deleted {self.slot_list[position]}')
self.slot_list[position] = None
self.data_list[position] = None
self.rehash_counter = 1
while True:
position = self.rehash(position)
if self.slot_list[position] is None:
break
temp_rehash_counter = self.rehash_counter
temp_key = self.slot_list[position]
temp_data = self.data_list[position]
self.slot_list[position] = None
self.data_list[position] = None
self.__setitem__(temp_key, temp_data)
self.rehash_counter = temp_rehash_counter
break
position = self.rehash(position)
if position == start:
# Otherwise, if starting position found, stop.
break
def get(self, key):
start = self.hash_function(key)
position = start
data = None
self.rehash_counter = 1
while self.slot_list[position] is not None:
if self.slot_list[position] == key:
# If key is found, set data and stop.
data = self.data_list[position]
break
position = self.rehash(position)
if position == start:
# If starting position found, stop.
break
# Data is either an element or None.
return data
def put(self, key, data):
self.rehash_counter = 1
hash_value = self.hash_function(key)
while self.fill_data(key, data, hash_value):
hash_value = self.rehash(hash_value)
self.calc_load()
def calc_load(self):
filled = 0
for key in self.slot_list:
if key is not None:
filled += 1
if filled / self.table_size >= self.max_load_factor:
print('Load Limit Reached. Resizing Table.')
new_hash_table = HashTableQuadratic(self.table_size * 2)
for index, element in enumerate(self.slot_list):
temp_key = self.slot_list[index]
temp_item = self.data_list[index]
if temp_key is not None:
new_hash_table.__setitem__(temp_key, temp_item)
self.slot_list = new_hash_table.slot_list
self.data_list = new_hash_table.data_list
self.table_size = new_hash_table.table_size
def fill_data(self, key, data, hash_value):
if self.slot_list[hash_value] is None or self.slot_list[hash_value] == 'DUMMY':
# If slot is None, we input key and data.
self.slot_list[hash_value] = key
self.data_list[hash_value] = data
return False
elif self.slot_list[hash_value] == key:
# If slot is equal to key, we replace data.
self.data_list[hash_value] = data
return False
# If we can't do either, do open addressing.
return True
def hash_function(self, key):
"""This recalculates the hash value so it fits in a list slot."""
return key % self.table_size
def rehash(self, hash_value):
"""In collision event, changes hash value by +1"""
rehash_value = hash_value + (self.rehash_counter**2)
self.rehash_counter += 1
return rehash_value % self.table_size
def test_3():
hash_table = HashTableQuadratic(11)
hash_table.__setitem__(9, 9)
hash_table.__setitem__(10, 10)
hash_table.__setitem__(0, 0)
hash_table.__setitem__(11, 11)
hash_table.__setitem__(22, 22)
hash_table.__setitem__(33, 33)
print(hash_table)
hash_table.__delitem__(0)
print(hash_table)
test_3()
# ================================================ Hash Table Chaining ===============================================
class HashTableChaining:
def __init__(self, size):
self.table_size = int(size)
self.slot_list = [None] * self.table_size
self.data_list = [None] * self.table_size
for index, element in enumerate(self.slot_list):
self.slot_list[index] = [None]
self.data_list[index] = [None]
def __len__(self):
return self.table_size
def __str__(self):
return "Slot List " + str(self.slot_list) + " \nData List " + str(self.data_list)
def __contains__(self, key):
if self.get(key) is not None:
return True
return False
def __getitem__(self, key):
return self.get(key)
def __setitem__(self, key, data):
self.put(key, data)
def __delitem__(self, key):
self.delete(key)
def delete(self, key):
hash_value = self.hash_function(key)
for index, element in enumerate(self.slot_list[hash_value]):
if self.slot_list[hash_value][index] == key:
# If slot is equal to key, we pop the element. We do not set dummy variables for the following example:
# Put (1, 1), Put (11, 11), Delete (1, 1), Put (11, 11).
# The last put will not replace the previous key but insert a new key. There are now two 11 keys.
self.slot_list[hash_value].pop(index)
self.data_list[hash_value].pop(index)
break
def get(self, key):
hash_value = self.hash_function(key)
data = None
for index, element in enumerate(self.slot_list[hash_value]):
if self.slot_list[hash_value][index] == key:
# If slot is equal to key, we set data.
data = self.data_list[hash_value][index]
break
return data
def put(self, key, data):
hash_value = self.hash_function(key)
placed = False
for index, element in enumerate(self.slot_list[hash_value]):
if self.slot_list[hash_value][index] is None or self.slot_list[hash_value][index] == 'DUMMY':
# If slot is None or dummy, we input key and data.
self.slot_list[hash_value][index] = key
self.data_list[hash_value][index] = data
placed = True
break
elif self.slot_list[hash_value][index] == key:
# If slot is equal to key, we replace data.
self.data_list[hash_value][index] = data
placed = True
break
if not placed:
# We append to end of chain if neither above condition was met.
self.slot_list[hash_value].append(key)
self.data_list[hash_value].append(data)
def hash_function(self, key):
"""This recalculates the hash value so it fits in a list slot."""
return key % self.table_size
def test_4():
hash_table = HashTableChaining(10)
hash_table.__setitem__(62, 62)
hash_table.__setitem__(81, 81)
hash_table.__setitem__(24, 24)
hash_table.__setitem__(19, 19)
hash_table.__setitem__(13, 13)
hash_table.__setitem__(1, 1)
hash_table.__setitem__(33, 33)
hash_table.__setitem__(41, 41)
hash_table.__setitem__(51, 51)
print(hash_table)
print(hash_table.__getitem__(1))
print(hash_table.__getitem__(24))
print(hash_table.__getitem__(33))
print(hash_table.__getitem__(41))
print(hash_table.__getitem__(51))
hash_table.__setitem__(41, 51)
print(hash_table.__getitem__(41))
hash_table.__delitem__(24)
hash_table.__delitem__(81)
hash_table.__delitem__(51)
hash_table.__setitem__(1, 1)
hash_table.__delitem__(62)
hash_table.__setitem__(62, 62)
print(hash_table)
test_4()
|
# first_numbers
# for value in range(6):
# print(value)
# numbers = list(range(1, 6))
# print(numbers)
# Even Numbers
# even_numbers = list(range(2,11,2))
# print(even_numbers)
# functions with numbers
# digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
# print(min(digits))
# print(max(digits))
# print(sum(digits))
# Squares
# squares = []
# for value in range(1,1001):
# squares.append(value ** 2)
# print(squares)
# List Comprehensions - Combine list, for and range to create lists
# squares = [value**2 for value in range(1, 11)]
# print(squares)
# for value in range (1, 21):
# print(value)
# numbers = list(range(1, 1000001))
# for value in numbers:
# print(value)
# print(min(numbers))
# print(max(numbers))
# print(sum(numbers))
# numbers = list(range(1, 21, 2))
# for value in numbers:
# print(value)
# numbers = list(range(3, 31, 3))
# for value in numbers:
# print(value)
# Cubes
# cubes = []
# for value in range(1,11):
# cubes.append(value ** 3)
# print(cubes)
cubes = [value**3 for value in range(1, 11)]
print(cubes) |
S=input()
res=""
lens=len(S)
while(lens>0):
rev=S[lens-1]
lens-=1
res=res+rev
if S==res:
print("YES")
else:
print("NO") |
print("This is another test")
ans = input("Is this working")
if ans=="yes":
print("okay cool")
else:
print("oh, too bad :(")
|
file1=open("file1.txt",'r')
file1_content=file1.readlines()
file1.close()
file2=open('file2.txt','r')
file2_content=file2.readlines()
file2.close()
result_file=open('file3.txt','w')
class Fileloop :
def __init__(self,file1,file2):
self.file1=file1
self.file2=file2
def __iter__(self):
self.i=0
self.a=""
self.b=""
self.res=""
return self
def __next__(self):
if len(self.file1)>self.i or len(self.file2)>self.i:
self.a=str(self.file1[self.i])
self.b=str(self.file2[self.i])
self.res=self.a+self.b
self.i=self.i+1
return self.res
else:
raise StopIteration
myfile=Fileloop(list(file1_content),list(file2_content))
file_iter=iter(myfile)
while True:
try:
print(next(file_iter))
except:
break
|
from datetime import date as d
name=""
age=""
while name=="":
name=input("\nEnter name :\t")
while age=="":
age=input("\nEnter age:\t")
try:
age=int(age)
except:
print("\nenter valid integer")
age=""
continue
def calcAge(uage):
today=d.today()
diff=100-uage
return today.year+diff
print(f"\nHello {name}, you will turn 100yr old in year {calcAge(age)}") |
# sixth chapter
# function
# bank
def open_account():
print("New account is created.")
def deposit(balance, money):
print("deposit completed. your balance : {0}".format(balance + money))
return balance + money
def withdraw(balance, money):
if balance >= money:
print("withdraw completed. your balance : {0}".format(balance - money))
return balance - money
else:
print("withdraw not completed your balance : {0}".format(balance))
return balance
def withdraw_night(balance, money):
commission = 100
return commission, balance - money - commission
open_account()
balance = 0
balance = deposit(balance, 1000)
# balance = withdraw(balance, 500)
# print(balance)
commission, balance = withdraw_night(balance, 500)
print("commission : {0}, balance : {1}".format(commission, balance))
# default value
def profile1(name, age=17, main_lang="python"):
print("name : {0}, age : {1}, main_lang : {2}".format(name, age, main_lang))
profile1("Ella")
# keyword value
def profile2(name, age, main_lang):
print(name, age, main_lang)
profile2(name = "Ella", main_lang = "python", age = 20)
# variable argument
# def profile3(name, age, lang1, lang2, lang3, lang4, lang5):
# print("name : {0}\tage : {1}\t".format(name, age), end = " ")
# print(lang1, lang2, lang3, lang4, lang5)
# profile3("Ella", 20, "python", "java", "C", "C++", "C#")
def profile3(name, age, *lang):
print("name : {0}\tage : {1}\t".format(name, age), end = " ")
for l in lang:
print(l, end=" ")
print()
profile3("Ella", 20, "python", "java")
# local variable & global variable
gun = 10
def checkpoint(soldiers):
# gun = 20 # local variable
global gun # to use global variable gun
'''not recommended, hard to manage global variables'''
gun = gun - soldiers
print("gun cnt in checkpoint: {0}".format(gun))
def checkpoint_ret(gun, soldiers):
gun = gun - soldiers
print("gun cnt in checkpoint: {0}".format(gun))
return gun
print("gun cnt : {0}".format(gun))
# checkpoint(2)
gun = checkpoint_ret(gun, 2)
print("gun cnt : {0}".format(gun))
# quiz 6
def std_weight(height, gender): # height unit : m
if gender == "male":
return height*height*22
else:
return height*height*21
height = 175 # unit cm
gender = "male"
weight = round(std_weight(height/100, gender), 2)
print("height {0}cm {1} - std_height : {2}kg".format(height, gender, weight)) |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 30 01:11:39 2020
@author: berka
"""
from rent_a_vehicle import CarRent, BikeRent, Customer
bike = BikeRent(100)
car = CarRent(25)
customer = Customer()
main_menu = True
while True:
if main_menu:
print("""
***** Vehicle Rental Shop *****
A. Bike Menu
B. Car Menu
Q. Exit
""")
main_menu = False
choice = input('Enter choice:')
if choice == 'A' or choice == 'a':
print("""
***** BIKE MENU *****
1. Display available bikes
2. Request a bike on hourly basis (3 TRY)
3. Request a bike on daily basis (54 TRY)
4. Return a bike
5. Main Menu
6. Exit
""")
choice = input('Enter choice:')
try:
choice = int(choice)
except ValueError:
print('Entry should be number')
continue
if choice == 1:
bike.displayCount()
choice = 'A'
elif choice == 2:
customer.rentalTime_b = bike.rentHourly(customer.requestVehicle('bike'))
customer.rentalBasis_b = 1
main_menu = True
print('-------------------')
elif choice == 3:
customer.rentalTime_b = bike.rentDaily(customer.requestVehicle('bike'))
customer.rentalBasis_b = 2
main_menu = True
print('-------------------')
elif choice == 4:
customer.bill = bike.returnVehicle(customer.returnVehicle('bike'), 'bike')
customer.rentalBasis_b, customer.rentalTime_b, customer.bikes = 0,0,0
print('Thanks for choosing us.')
main_menu = True
elif choice == 5:
main_menu = True
elif choice == 6:
break
else:
print('Invalid input, Please enter a number between 1-6')
main_menu = True
elif choice == 'B' or choice == 'b':
print("""
***** CAR MENU *****
1. Display available cars
2. Request a car on hourly basis (8 TRY)
3. Request a car on daily basis (163,2 TRY)
4. Return a car
5. Main Menu
6. Exit
""")
choice = input('Enter choice:')
try:
choice = int(choice)
except ValueError:
print('Entry should be number')
continue
if choice == 1:
car.displayCount()
choice = 'B'
elif choice == 2:
customer.rentalTime_c = car.rentHourly(customer.requestVehicle('car'))
customer.rentalBasis_c = 1
main_menu = True
print('-------------------')
elif choice == 3:
customer.rentalTime_c = car.rentDaily(customer.requestVehicle('car'))
customer.rentalBasis_c = 2
main_menu = True
print('-------------------')
elif choice == 4:
customer.bill = car.returnVehicle(customer.returnVehicle('car'), 'car')
customer.rentalBasis_c, customer.rentalTime_c, customer.cars = 0,0,0
print('Thanks for choosing us.')
main_menu = True
elif choice == 5:
main_menu = True
elif choice == 6:
break
else:
print('Invalid input, Please enter a number between 1-6')
main_menu = True
elif choice == 'Q' or choice == 'q':
break
else:
print('Invalid input. Please Enter A-B-Q')
main_menu = True
|
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 8 19:01:48 2019
@author: berka
"""
"""
OOP : Object Oriented Programming
: class / object/constructor
: attirubutes / methods
: encapsulation / abstraction
: inheritance
: overriding / polymorphism
"""
from abc import ABC, abstractmethod # import abstract
class Shape(ABC): # created super class with inherited ABC
@abstractmethod
def area(self) : pass
@abstractmethod
def perimeter(self) : pass
def toString(self) : pass #overriding and polymorphism
class Square(Shape): # child
def __init__(self,edge):
self.__edge = edge # encapsulation, private attribute
def area(self):
result = self.__edge**2
print("Square Area :",result)
def perimeter(self):
result = self.__edge * 4
print("Square perimeter :",result)
def toString(self):
print("Square Edge : ",self.__edge)
class Circle(Shape):
PI = 3.14 # constant variable (sonucu hiçbir yerde değişmeyecek değişken)
def __init__(self,radius):
self.__radius = radius # encapsulation, private attribute
def area(self):
result = self.PI * self.__radius ** 2
print("Circle Area :",result)
def perimeter(self):
result = 2 * self.PI * self.__radius
print("Circle perimeter :",result)
def toString(self):
print("Circle radius : ",self.__radius)
c = Circle(5)
c.area()
c.perimeter()
c.toString()
s = Square(5)
s.area()
s.perimeter()
s.toString()
|
__author__ = 'rsimpson'
"""
I started with minimax code that I found here:
http://callmesaint.com/python-minimax-tutorial/
That code was written by Matthew Griffin
Then I added in code I got from here:
https://inventwithpython.com/tictactoe.py
That code was written by Al Sweigart
Then I started adding my own code
"""
from gobbletConstants import *
from gobbletMachine import *
import copy
DEPTHLIMIT = 4
class AlphaBetaMachine(Machine):
def __init__(self, _name):
# call constructor for parent class
Machine.__init__(self, _name)
def evaluationFunction(self, _board):
"""
This function is used by minimax to evaluate a non-terminal state.
Things to keep in mind:
_board is an object of type Board, which is defined in gobbletMain.py
You can modify the Board class, if you want.
The _board object contains a list of stacks: _board.board. The last item in the stack (_board.board[-1])
is on top.
Your evaluation function should return a value between BIG_POSITIVE_NUMBER and BIG_NEGATIVE_NUMBER, both
of which are defined in gobbletConstants.py
A better evaluation function will allow you to prune more aggressively, which will allow you to increase
the search depth limit (DEPTHLIMIT) defined at the top of this file.
"""
currentvalue=0
middleIndex=[5,6,9,10] #middle 4 index
for x in middleIndex: #loops into middle index(5,6,9,10)
if(len(_board.board[x])> 0 and _board.board[x][-1] in Y_PIECES): #if statement checks to see if the top piece in the index is your bigpiece
currentvalue +=2 # add 3 to you currentvalue
if(len(_board.board[x])> 0 and _board.board[x][-1] in X_PIECES): #same as if statment above but checks if the piece is your opponents
currentvalue -=2 #if its your opponents piece subtract 3 from currentvalue
squareTuples = [(5, 6, 4, 7),(5,4,6,7),(5,7,4,6),(4,6,5,7),(4,7,5,6), (6,7,4,5),
(5, 9, 1, 13),(5,1,9,13),(5,13,1,9),(1,9,5,13),(1,13,5,9),(9,13,5,1),
(5,10,0,15),(5,0,10,15),(5,15,10,0),(0,10,5,15),(0,15,5,10),(15,10,0,5),
(9,6,3,12),(6,3,9,12),(6,12,3,9),(3,9,6,12),(3,12,6,9),(9,12,3,6),
(9,10,8,11),(9,8,10,11),(9,11,10,8),(8,10,9,11),(8,11,9,10),(10,11,8,9),
(10,6,2,14),(10,14,6,2),(10,2,14,6),(14,6,10,2),(14,2,10,6),(6,2,10,14),
# 0 * * 3 checks all * 1 2 *
# * 5 6 * <-- 3 in a row--> 4 5 6 7
# * 9 10 * above(code) 8 9 10 11
# 12 * * 15 * 13 14 *
(0,1,2,3),(0,2,1,3),(0,3,1,2),(1,2,0,3),(1,3,0,2),(2,3,0,1),
(0,4,8,12),(0,8,4,12),(0,12,4,8),(4,8,0,12),(4,12,0,8),(12,8,4,0),
(12,13,14,15),(12,14,13,15),(12,15,13,14),(13,14,12,15),(13,15,12,14),(15,14,12,13),
(3,7,11,15),(3,11,7,15),(3,15,7,11),(7,11,3,15),(7,15,3,11),(15,11,3,7)]
# 0 1 2 3 check all
# 4 * * 7 <-- 3 in a row
# 8 * * 11 above(code)
# 12 13 14 15
for st in squareTuples:
if( len(_board.board[st[0]])> 0 and _board.board[st[0]][-1] in Y_PIECES and len(_board.board[st[1]])> 0 and _board.board[st[1]][-1] in Y_PIECES ):
if( len(_board.board[st[2]])> 0 and _board.board[st[2]][-1] in Y_PIECES or len(_board.board[st[3]])> 0 and _board.board[st[3]][-1] in Y_PIECES ):
currentvalue +=5
#^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# The first If statment will check 2 specific index's to see if you have your piece in them, which is part of a possible 3-in-a-row (row/column/diagonal)
# The second If statment will check if you have any pieces in the same row/column/diagonal of the 2 index's checked in the first If statement
# which will let us there is a 3-in-a-row then add 5 to you currentvalue
if( len(_board.board[st[0]])> 0 and _board.board[st[0]][-1] in X_PIECES and len(_board.board[st[1]])> 0 and _board.board[st[1]][-1] in X_PIECES ):
if( len(_board.board[st[2]])> 0 and _board.board[st[2]][-1] in X_PIECES or len(_board.board[st[3]])> 0 and _board.board[st[3]][-1] in X_PIECES ):
currentvalue -=5
# same as above If statements but checks for other player and subtract 5 form currentvalue
return currentvalue
def atTerminalState(self, _board, _depth):
"""
Checks to see if we've reached a terminal state. Terminal states are:
* somebody won
* we have a draw
* we've hit the depth limit on our search
Returns a tuple (<terminal>, <value>) where:
* <terminal> is True if we're at a terminal state, False if we're not
* <value> is the value of the terminal state
"""
global DEPTHLIMIT
# Yay, we won!
if _board.isWinner(self.myPieces):
# Return a positive number
return (True, BIG_POSITIVE_NUMBER)
# Darn, we lost!
elif _board.isWinner(_board.opponentPieces(self.name)):
# Return a negative number
return (True, BIG_NEGATIVE_NUMBER)
# if we've hit our depth limit
elif (_depth >= DEPTHLIMIT):
# use the evaluation function to return a value for this state
return (True, self.evaluationFunction(_board))
return (False, 0)
def alphaBetaMax(self, _board, _depth = 0, _alpha = NEGATIVE_INFINITY, _beta = POSITIVE_INFINITY):
'''
This is the MAX half of alpha-beta pruning. Here is the algorithm:
int alphaBetaMax( int alpha, int beta, int depthleft ) {
if ( depthleft == 0 ) return evaluate();
for ( all moves) {
score = alphaBetaMin( alpha, beta, depthleft - 1 );
if( score >= beta )
return beta; // fail hard beta-cutoff
if( score > alpha )
alpha = score; // alpha acts like max in MiniMax
}
return alpha;
}
'''
#
# At a terminal state
#
# check to see if we are at a terminal state - someone won or we hit our search limit
terminalTuple = self.atTerminalState(_board, _depth)
# if we are at a terminal state
if terminalTuple[0] == True:
# return the value of this state
return (0, terminalTuple[1])
#
# Not at a terminal state, so search further...
#
# get all my legal moves
possibleMoves = _board.possibleNextMoves(self.myPieces)
# pick a random move as a default
bestMove = random.choice(possibleMoves)
# loop through all possible moves
for m in possibleMoves:
if (_depth == 0):
print 'considering ' + str(m) + '...'
# keep a copy of the old board
oldBoard = copy.deepcopy(_board.board)
# make the move - move is a tuple: (piece, square)
_board.makeMove(m[0], m[1])
# get the minimax vaue of the resulting state - returns a tuple (move, score)
(mv, score) = self.alphaBetaMin(_board, _depth+1, _alpha, _beta)
# undo the move
_board.board = copy.deepcopy(oldBoard)
# compare score to beta - can we prune?
if (score >= _beta):
return (mv, _beta)
# compare score to alpha - have we found a better move?
if (score > _alpha):
# keep the better move
bestMove = m
# update alpha
_alpha = score
# return the best move we found
return (bestMove, _alpha)
def alphaBetaMin(self, _board, _depth, _alpha, _beta):
'''
This is the MIN half of alpha-beta pruning. Here is the general algorithm:
int alphaBetaMin( int alpha, int beta, int depthleft ) {
if ( depthleft == 0 ) return -evaluate();
for ( all moves) {
score = alphaBetaMax( alpha, beta, depthleft - 1 );
if( score <= alpha )
return alpha; // fail hard alpha-cutoff
if( score < beta )
beta = score; // beta acts like min in MiniMax
}
return beta;
}
'''
#
# At a terminal state
#
# check to see if we are at a terminal state - someone won or we hit our search limit
terminalTuple = self.atTerminalState(_board, _depth)
# if we are at a terminal state
if terminalTuple[0] == True:
# return the value of this state
return (0, terminalTuple[1])
#
# Not at a terminal state, so search further...
#
# get all my opponent's legal moves
possibleMoves = _board.possibleNextMoves(_board.opponentPieces(self.name))
# pick a random move as a default
bestMove = random.choice(possibleMoves)
# consider all possible moves
for m in possibleMoves:
# keep a copy of the old board
oldBoard = copy.deepcopy(_board.board)
# make the move
_board.makeMove(m[0], m[1])
# get the minimax vaue of the resulting state - returns a tuple (move, score)
(mv, score) = self.alphaBetaMax(_board, _depth+1, _alpha, _beta)
# undo the move
_board.board = copy.deepcopy(oldBoard)
# compare score to alpha - can we prune?
if (score <= _alpha):
return (m, _alpha)
# compare score to the best move we found so far
if (score < _beta):
_beta = score
# send back the best move we found
return (bestMove, _beta)
def move(self, _board):
m = self.alphaBetaMax(_board)[0]
print "move = " + str(m)
return m
|
#!/usr/bin/python
import time, random
def merge(a, start1, start2, end):
index1 = start1
index2 = start2
'''length is the total length of two groups of number'''
length = end - start1
aux = [None] * length
for i in range(length):
'''two groups compare,merge to aux'''
if ((index1 == start2) or
'''if first group is bigger'''
((index2 != end) and (a[index1] > a[index2]))):
'''put in the smaller one'''
aux[i] = a[index2]
index2 += 1
else:
aux[i] = a[index1]
index1 += 1
'''put back from aux to original'''
for i in range(start1, end):
a[i] = aux[i - start1]
def mergeSort(a):
n = len(a)
step = 1
while (step < n):
for start1 in range(0, n, 2*step):
start2 = min(start1 + step, n)
'''end is 2-way merge scope'''
end = min(start1 + 2*step, n)
merge(a, start1, start2, end)
'''from 2-way scan first'''
step *= 2
a = [5,2,4,6,1,3]
startTime = time.time()
mergeSort(a)
endTime = time.time()
elapsedTime = endTime - startTime
print a
print("%20s n=%d time =%6.3fs" % (mergeSort.__name__, len(a), elapsedTime))
|
#!/usr/bin/env python3
#-*- coding:UTF-8 -*-
class result(object):
wheatNum = 0
wheatTotalNum = 0
class getWheatTotalNum(object):
'''
函数说明:使用递归嵌套, 进行数学归纳法证明
Param: k - 表示放到第几格 result - 表示当前格子的麦粒数
Return: boolean - 放到第K格时是否成立
'''
def prove(self, k, result):
if k == 1:
if (2 ** 1 - 1) == 1:
result.wheatNum = 1
result.wheatTotalNum = 1
return True
else:
return False
else:
proveOfPreviousOne = self.prove(k - 1, result)
result.wheatNum *= 2
result.wheatTotalNum += result.wheatNum
proveOfCurrentOne = False
if result.wheatTotalNum == (2 ** k - 1):
proveOfCurrentOne = True
if (proveOfPreviousOne & proveOfCurrentOne):
return True
else:
return False
if __name__ == '__main__':
grid = 64
result = result()
g = getWheatTotalNum()
print(g.prove(grid, result)) |
N = int(input())
myList = list()
for i in range(N):
cmd = input().split()
if cmd[0] == "append":
myList.append(int(cmd[1]))
elif cmd[0] == "insert":
myList.insert(int(cmd[1]),int(cmd[2]))
elif cmd[0] == "remove":
myList.remove(int(cmd[1]))
elif cmd[0] == "pop":
myList.pop()
elif cmd[0] == "index":
myList.index(int(cmd[1]))
elif cmd[0] == "count":
myList.count(int(cmd[1]))
elif cmd[0] == "sort":
myList.sort()
elif cmd[0] == "reverse":
myList.reverse()
elif cmd[0] == "print":
print(myList)
else:
print("Commande non reconnue") |
import requests
from decimal import Decimal
def get_eurusd():
""" Return the current EUR/USD exchange rate from Yahho Finance API.
:return: Current EUR/USD exchange rate
"""
# See:
# http://code.google.com/p/yahoo-finance-managed/wiki/csvQuotesDownload
# http://code.google.com/p/yahoo-finance-managed/wiki/enumQuoteProperty
url = 'http://download.finance.yahoo.com/d/quotes.csv'
params = {
'f': 'l1',
's': 'EURUSD=X',
}
response = requests.get(url, params=params)
if response.status_code != 200:
raise Exception('Failed to get EURUSD exchange rate')
return Decimal(response.text)
|
mylist = [2,1,4,5,9,12,45]
print map(str,mylist) # ['2', '1', '4', '5', '9', '12', '45']
#---------------
names = ['Anne', 'Amy', 'Bob', 'David', 'Carrie', 'Barbara', 'Zach']
lengths = map(len, names)
print lengths # [4, 3, 3, 5, 6, 7, 4]
#--------------------
# lambda usage
print (lambda x, y: x*y)(3, 4) # 12
# or
g = lambda x, y: x*y
print g(10, 10) #100
#---------------------------
# Map and lambda together
squares = map(lambda x: x**2, range(10))
print squares # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81
# Other example linking map and filter
square = map(lambda x: x**2 ,range(10))
evensquare = filter(lambda x: x % 2 == 0, square)
print evensquare
|
# In the following situation diamond problem is the order in which the call() is taken
# Initially it will taken as B2,B1,B3 and if we restuctures it will take as itsown
class A:
def call(self):
pass
class B1(A):
def call(self):
print "I am parent B1"
class B2(A):
def call(self):
print "I am parent B2"
class B3(A):
def call(self):
print "I am parent B3"
class C(A):
def call(self):
print "I (C) was not invited"
class ME(B2, B1, B3):
def whichCall(self):
print self.call()
def restructure(self, parent1, parent2, parent3):
self.__class__.__bases__ = (parent1, parent2, parent3, )
def printBaseClasses(self):
print self.__class__.__bases__
me = ME()
me.printBaseClasses()
me.whichCall()
me.restructure(B3,B2,B1)
me.printBaseClasses()
me.whichCall()
|
# SOlution for the problem no-6
# Program to find the difference between the sum of the squares
# of the first ten natural numbers and the square of the sum
import logging
def diff_sumsquare(max):
N = int(max)
sum1, sum2 = 0, 0
for i in range(1, N + 1):
sum1 += i
sum2 += pow(i,2)
return pow(sum1,2) - sum2
def main ():
logging.basicConfig(filename='problem6.log',level=logging.INFO)
max = raw_input("Program to find the diff of the sum of natural numbers square and their sum's square n:\nEnter the range:")
if max.isdigit() :
result = diff_sumsquare(max)
logging.info("The sum is " + str(result))
print "The sum is",result
else:
logging.error("Invalid max range: " + max + " \nUsage: Integer value only ")
print "Invalid max range: " + max + " \nUsage: Integer value only "
if __name__ == '__main__':
main()
|
__author__ = 'Student'
#lab 5 opdracht 2: (the infamous) Scrambled Eggs
#samenvatting: het gebruiken van een array binnen een forloop in een functie
#onze pseudocode om te beginnen:
#een nieuwe functie die def Scramble heet met 2 parameters (woord1 en woord2)
#een nieuwe variable maken voor het gescramble woord
#een for loop maken om om-en-om letters toe te voegen
#return het gescramble woord
#einde pseudocode
#deze functie staat boven Scramble(), want Python ;-;
def GeefLetterOfNul(woord, positie):
#wanneer de positie die we willen checken, groter is dan het woord lang is
if positie >= len(woord):
return "0"
else:
#anders de letter op positie terug sturen
return woord[positie]
#bovenstaande pseudocode uitgewerkt:
def Scramble(word1, word2):
#wederom eerst aanmaken en vertellen dat hij een lege string is
scrambledword = ""
#kijken welk woord het langste is:
lettersInLangsteWoord = max(len(word1), len(word2))
#voor for loops, koop een premium account of kijk in bijles #1
for letter in range(0, lettersInLangsteWoord):
#letter op plek nr 0 pakken uit word1, en vervolgens toevoegen
scrambledword += GeefLetterOfNul(word1, letter)
#omdat we willen ritsen:
scrambledword += GeefLetterOfNul(word2, letter)
#het returnen van het nieuwe woord, note: het tabje staat binnen de functie, maar buiten de forloop
return scrambledword
#print kipje[234]
geschudWoord = Scramble("kipje", "autogarage")
print geschudWoord
|
class Car(object):
def __init__(self, x,y,w,h,xSpeed,ySpeed,rotSpeed):
self.x = x
self.y = y
self.w = w
self.h =h
self.xSpeed =xSpeed
self.ySpeed =ySpeed
self.rotSpeed = rotSpeed
self.angle = 0
def update(self):
pushMatrix()
self.move()
self.display()
popMatrix()
def move(self, xDir,yDir):
#movement and keep object in screen
self.x += self.xSpeed * xDir
self.y += self.ySpeed * yDir
if self.x < self.w:
self.x = self.w
if self.x + self.w > width:
self.x = width -self.w
if self.y < self.h:
self.y = self.h
if self.y + self.h > height:
self.y = height -self.h
def display(self):
#draw a small ball to show rotation
rect(self.x,self.y,self.w,self.h)
|
def key_assign(key):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
key_list = list(range(len(key)))
#print all in list to check
key_num = 0
for row in range(len(alphabet)):
for column in range(len(key)):
if alphabet[row] == key[column]:
key_num += 1
key_list[column] = key_num
return key_list
def numeric_pos(key, key_list):
#gets numeric position of each letter
pos = ""
for row in range(len(key) + 1):
for column in range(len(key)):
if key_list[column] == row:
pos += str(column)
return pos
def columnar_encrypt(text, key):
text = text.replace(" ", "").upper()
key = key.upper()
#assign list of keys
key_list = key_assign(key)
#print to check
for index in range(len(key)):
print(key[index], end=" ", flush=True)
print()
for index in range(len(key)):
print(str(key_list[index]), end=" ", flush=True)
print()
print("-------------------------")
#if all letters don't fit in grid properly
extras = len(text) % len(key)
fillers = len(key) - extras
if extras != 0:
for index in range(fillers):
text += "|"
rows = int(len(text) / len(key))
#convert to grid
grid = [[0] * len(key) for index in range(rows)]
n = 0
for row in range(rows):
for column in range(len(key)):
grid[row][column] = text[n]
n += 1
#print to check
for row in range(rows):
for column in range(len(key)):
print(grid[row][column], end=" ", flush=True)
print()
#get number locations
location = numeric_pos(key, key_list)
print(location)
# begin cipher
encrypted = ""
k = 0
for i in range(rows):
if k == len(key):
break
else:
d = int(location[k])
for j in range(rows):
encrypted += grid[j][d]
k += 1
return encrypted
def columnar_decrypt(cipher, key):
cipher = cipher.replace(" ", "").upper()
# print(msg)
key = key.upper()
# assigning numbers to keywords
kywrd_num_list = key_assign(key)
num_of_rows = int(len(cipher) / len(key))
# getting locations of numbers
num_loc = numeric_pos(key, kywrd_num_list)
# Converting message into a grid
arr = [[0] * len(key) for i in range(num_of_rows)]
# decipher
decrypted = ""
k = 0
itr = 0
# print(arr[6][4])
# itr = len(msg)
for i in range(len(cipher)):
d = 0
if k == len(key):
k = 0
else:
d: int = int(num_loc[k])
for j in range(num_of_rows):
arr[j][d] = cipher[itr]
# print("j: {} d: {} m: {} l: {} ". format(j, d, msg[l], l))
itr += 1
if itr == len(cipher):
break
k += 1
print()
for i in range(num_of_rows):
for j in range(len(key)):
decrypted += str(arr[i][j])
# for
# for
return decrypted
#Driver Code to test the above functions
def main():
while True:
choice = int(input("Enter 1 to Encrypt, 2 to Decrypt, 3 to Quit: "))
if choice == 1:
text = input("Enter text to encrypt: ")
key = input("Enter keyword: ")
enc_text = columnar_encrypt(text, key)
print('Encrypted Text: {}'.format(enc_text))
elif choice == 2:
text = input("Enter text to decrypt: ")
key = input("Enter keyword: ")
dec_text = columnar_decrypt(text, key)
print('Decrypted Text: {}'.format(dec_text))
elif choice == 3:
print("End Program")
break
if __name__ == '__main__':
main() |
#You are given two sequences. Write a program to determine the longest common subsequence between the two
# strings (each string can have a maximum length of 50 characters). NOTE: This subsequence need not be
# contiguous. The input file may contain empty lines, these need to be ignored.
#The first argument will be a path to a filename that contains two strings per line, semicolon delimited.
# You can assume that there is only one unique subsequence per test case.
test_cases = ['XMJYAUZ;MZJAWXU']
#import sys
#test_cases = open(sys.argv[1], 'r')
def find_LCS(arg1,arg2):
print(arg1)
print(arg2)
LCS = ['']
for test in test_cases:
if test:
lst = test.split(';')
LCS=find_LCS(lst[0],lst[1])
print(LCS)
#test_cases.close() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.