text
stringlengths 37
1.41M
|
---|
class DLNode:
def __init__(self, val=None):
self.val = val
self.next = None
self.prev = None
class MovingAverage:
def __init__(self, size: int):
"""
Initialize your data structure here.
"""
self.capacity = size
self.head = DLNode()
self.tail = DLNode()
self.head.next = self.tail
self.tail.prev = self.head
self.sum = 0
self.size = 0
def next(self, val: int) -> float:
if self.size == self.capacity:
removed_elem = self.del_top()
print(removed_elem, val)
self.sum -= removed_elem
self.size -= 1
self.sum += val
self.size += 1
newelem = DLNode(val)
self.add_bottom(newelem)
return self.sum/self.size
def del_top(self):
removedNode = self.head.next
self.head.next = removedNode.next
removedNode.next.prev = self.head
return removedNode.val
def add_bottom(self, node):
self.tail.prev.next = node
node.next = self.tail
node.prev = self.tail.prev
self.tail.prev = node
# Your MovingAverage object will be instantiated and called as such:
# obj = MovingAverage(size)
# param_1 = obj.next(val)
|
class UF:
def __init__(self, vars):
self.parents = {var: var for var in vars}
self.size = {var: 1 for var in vars}
def find(self, var):
root = self.parents[var]
while root != self.parents[root]:
root = self.parents[root]
while self.parents[var] != root:
var, self.parents[var] = self.parents[var], root
return root
def union(self, var1, var2):
root_1, root_2 = self.find(var1), self.find(var2)
if root_1 == root_2: return
if self.size[root_1] < self.size[root_2]:
self.parents[root_1] = root_2
self.size[root_2] += self.size[root_1]
else:
self.parents[root_2] = root_1
self.size[root_1] += self.size[root_2]
class Solution:
def equationsPossible(self, equations: List[str]) -> bool:
vars = set()
for eqn in equations:
vars.add(eqn[0])
vars.add(eqn[-1])
uf = UF(vars)
for eqn in equations:
if eqn[1:-1] == "==":
uf.union(eqn[0], eqn[-1])
for eqn in equations:
if eqn[1:-1] == "!=" and uf.find(eqn[0]) == uf.find(eqn[-1]):
return False
return True
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def str2tree(self, s: str) -> TreeNode:
"""
"4 (2(3)(1)) (6(5)(7))"
"""
n = len(s)
def dfs(start, end):
if start >= end: return None
currEnd = start
while currEnd < end and s[currEnd] != "(":
currEnd += 1
node = TreeNode(s[start:currEnd])
if currEnd == end: return node
leftParans, rightParans = 0, 0
for partition in range(currEnd, end):
leftParans += s[partition] == "("
rightParans += s[partition] == ")"
if leftParans == rightParans: break
node.left = dfs(currEnd+1, partition)
node.right = dfs(partition + 2, end-1)
return node
return dfs(0, n)
|
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children if children is not None else []
"""
O(N) | O(1)
class Solution:
def findRoot(self, tree: List['Node']) -> 'Node':
valSum = 0
for i in range(len(tree)):
valSum += tree[i].val
for child in tree[i].children:
valSum -= child.val
for node in tree:
if node.val == valSum:
return node
return None
O(N) | O(N)
class Solution:
def findRoot(self, tree: List['Node']) -> 'Node':
inDegrees = {node.val: 0 for node in tree}
for node in tree:
for child in node.children:
inDegrees[child.val] += 1
for i in range(len(tree)):
if inDegrees[tree[i].val] == 0:
return tree[i]
return None
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rob(self, root: TreeNode) -> int:
"""
Rob(node) = max amount possible at that node
Base case:
Rob(node) = 0 if not node
general case
Rob(node) = max(node.val + Rob(node.next.next) (if not none), Rob(node.next))
"""
memo = {}
def Rob(node):
if not node: return 0
if node in memo: return memo[node]
robNowLeft = 0 if node.left is None else Rob(node.left.left) + Rob(node.left.right)
robNowRight = 0 if node.right is None else Rob(node.right.left) + Rob(node.right.right)
robNow = robNowLeft + robNowRight + node.val
skipNow = Rob(node.left) + Rob(node.right)
memo[node] = max(robNow, skipNow)
return memo[node]
return Rob(root)
|
class Solution:
def reverseVowels(self, s: str) -> str:
sarr = list(s)
i, j = 0, len(sarr)-1
vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'}
while i < j:
if sarr[i] not in vowels:
i += 1
elif sarr[j] not in vowels:
j -= 1
else:
sarr[i], sarr[j] = sarr[j], sarr[i]
i += 1
j -= 1
return "".join(sarr)
|
# Path with Maximum Probability 1514.
# You are given an undirected weighted graph of n nodes (0-indexed), represented by an edge list where edges[i] = [a, b] is an undirected edge connecting the nodes a and b with a probability of success of traversing that edge succProb[i].
# Given two nodes start and end, find the path with the maximum probability of success to go from start to end and return its success probability.
# If there is no path from start to end, return 0. Your answer will be accepted if it differs from the correct answer by at most 1e-5.
# Example 1:
# Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.2], start = 0, end = 2
# Output: 0.25000
# Explanation: There are two paths from start to end, one having a probability of success = 0.2 and the other has 0.5 * 0.5 = 0.25.
# Example 2:
# Input: n = 3, edges = [[0,1],[1,2],[0,2]], succProb = [0.5,0.5,0.3], start = 0, end = 2
# Output: 0.30000
# Example 3:
# Input: n = 3, edges = [[0,1]], succProb = [0.5], start = 0, end = 2
# Output: 0.00000
# Explanation: There is no path between 0 and 2.
# Constraints:
# 2 <= n <= 10^4
# 0 <= start, end < n
# start != end
# 0 <= a, b < n
# a != b
# 0 <= succProb.length == edges.length <= 2*10^4
# 0 <= succProb[i] <= 1
# There is at most one edge between every two nodes.
class Solution:
def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
# sol 1:
# time O(n*m) space O(n*m)
# construct a graph
graph = collections.defaultdict(list)
deque = collections.deque([start])
for i, (a, b) in enumerate(edges):
graph[a].append((b,i))
graph[b].append((a,i))
p = [0.0]*n
p[start] = 1.0
# for each element, calculate if max probs to its neighbors is higher to update.
while deque:
cur = deque.popleft()
for neighbor,i in graph[cur]:
if p[cur]*succProb[i] > p[neighbor]:
p[neighbor] = p[cur]*succProb[i]
deque.append(neighbor)
return p[end]
|
# Can Make Arithmetic Progression From Sequence 1502
# [email protected]
# Given an array of numbers arr. A sequence of numbers is called an arithmetic progression if the difference between any two consecutive elements is the same.
# Return true if the array can be rearranged to form an arithmetic progression, otherwise, return false.
# Example 1:
# Input: arr = [3,5,1]
# Output: true
# Explanation: We can reorder the elements as [1,3,5] or [5,3,1] with differences 2 and -2 respectively, between each consecutive elements.
# Example 2:
# Input: arr = [1,2,4]
# Output: false
# Explanation: There is no way to reorder the elements to obtain an arithmetic progression.
# Constraints:
# 2 <= arr.length <= 1000
# -10^6 <= arr[i] <= 10^6
class Solution:
def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
# sol 1: sort
# time O(nlogn) space O(1)
arr.sort() # O(nlogn)
diff = abs(arr[1]-arr[0])
for i in range(1,len(arr)):
if abs(arr[i]-arr[i-1])!=diff:
return False
return True
# sol 2:
# time O(n) space O(1)
minarr = min(arr)
gap = (max(arr) - minarr)/(len(arr)-1)
if gap==0: return True
i = 0
while i < len(arr):
# compare curr val to the min val plus number of gaps.
if arr[i] == minarr + i*gap:
i += 1
else:
diff = arr[i] - minarr
if diff % gap !=0: return False
# swap to the right index.
index = int(diff/gap)
if arr[index] == arr[i]: return False
arr[index], arr[i] = arr[i], arr[index]
return True
|
#Library
import csv
import math
from sklearn import preprocessing
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_regression
from sklearn.feature_selection import mutual_info_regression
#Variables
X = []
y = []
features = ('X','Y','month','day','FFMC','DMC','DC','ISI','temp','RH','wind','rain')
month_dict = {'jan':1,'feb':2,'mar':3,'apr':4,'may':5,'jun':6,
'jul':7,'aug':8,'sep':9,'oct':10,'nov':11,'dec':12,}
day_dict = {'mon':1,'tue':2,'wed':3,'thu':4,'fri':5,'sat':6,'sun':7}
#modifiable
fs_rounds = None
final_dim = None
function = None
#Retrieve user input
fs_rounds = int(input("Enter # of feature selection rounds: "))
final_dim = int(input("Enter # of desired features: "))
print("Choose a feature selection function:\n1. correlation\n2. mutual information")
choice = int(input("Enter 1 or 2: "))
if choice == 1:
function = f_regression
if choice == 2:
function = mutual_info_regression
#Load data
print("\nLoading data...", end=' ')
with open("../resource/forestfires.csv", 'r') as csvfile:
reader = csv.reader(csvfile)
for i, row in enumerate(reader):
if i > 0: #skipping the header
temp = [row[0],row[1],month_dict[row[2]],day_dict[row[3]],row[4],row[5],
row[6],row[8],row[9],row[10],row[11]]
X.append([float(i) for i in temp])
#natural log transform function
y.append(math.log(float(row[-1])+1))
print("Done")
#Standardize attributes to have a mean of zero and a standard deviation of one
X_std = preprocessing.scale(X)
#Feature Selection
print("\nPerforming feature selection...", end=' ')
fs_totals = [0,0,0,0,0,0,0,0,0,0,0,0]
for fs_round in range(fs_rounds):
fs = SelectKBest(score_func=function, k=final_dim)
fs.fit(X_std, y)
for i,score in enumerate(fs.scores_):
fs_totals[i] += score
fs_avgscores = [i/fs_rounds for i in fs_totals]
print("Done")
#Determine columns of selected features
keep_col = sorted(range(len(fs_avgscores)), key=lambda i: fs_avgscores[i], reverse=True)[:final_dim]
print("\nUse feature columns: " + str(keep_col))
|
#
# Implementation of Knuth-Morris-Pratt (KMP) Algorithm
# anontated.
#
# Algorithm creates a text table for use with searches.
#
# Running Time is O(n+m), where 'n' is length of the searched text (typically large)
# and 'm' is the length of pattern (or pattern, typically small).
#
# Assumptions: length of pattern <= length of text, e.g. m <= n, otherwise
# function will not find the pattern
#
import itertools
def kmp_match(text, pattern):
# By checking the largest word suffix which matches the word prefix, we can
# generate a 'prefix table' that can then be used as a state machine, where 0 is the
# initial state and the last character in the table being the accpeting state.
#
# We generate the prefix table by maintaining a running count of character matches
# starting from the 2nd character as we are walking the word character by character.
#
# The reason this works is because the prefix count reveals how many prefix
# matches at any point in the string. The prefix matches will let us know where in
# the word to jump to (state change) if we see a mismatch as we are actually
# matching the word.
#
def init_prefix_table(word):
prefix_table = [0] * (len(word) + 1)
prefix_table[0] = -1
i, j = 0, -1
while i < len(word):
if j == -1 or word[i] == word[j]:
i += 1
j += 1
prefix_table[i] = j
else:
j = prefix_table[j]
return prefix_table[1:]
prefix_table = init_prefix_table(pattern)
#print ('prefix table:', prefix_table)
# now that we have the state_table (aka prefix table) created, we can do the string matching
# using it as a guide for state transitions
pattern_index = 0
for text_index, text_ch in enumerate(text):
# Check for failure; if failure, then transition to the correct
# intermediate state. If no intermediate state is found, then we will go
# to the initial state and thus exit the while loop
# the state variable also informs the correct index into the pattern string
while pattern_index > 0 and text_ch != pattern[pattern_index]:
pattern_index = prefix_table[pattern_index-1]
if text_ch == pattern[pattern_index]:
if pattern_index == len(pattern)-1:
return text_index-pattern_index
# update the automaton pattern_index
pattern_index+=1
return -1
def main():
print('Knuth Morris Pratt (KMP) string search algorithm')
Input = 'y ababaca siifjae', 'ababaca'
print(Input)
res = kmp_match(Input[0], Input[1])
print('len:', len(Input[1]))
print('result:', res, "'{}'".format(Input[0][res:res+len(Input[1])]))
assert Input[0][res:res+len(Input[1])] == Input[1]
print('correct:', Input[0].find(Input[1]))
assert res == Input[0].find(Input[1])
Input = 'y ababac siifjae', 'ababac'
print(Input)
res = kmp_match(Input[0], Input[1])
print('len:', len(Input[1]))
print(res, "'{}'".format(Input[0][res:res+len(Input[1])]))
assert Input[0][res:res+len(Input[1])] == Input[1]
print('correct:', Input[0].find(Input[1]))
assert res == Input[0].find(Input[1])
Input = 'abababacsiifjae', 'ababac'
print (Input)
res = kmp_match(Input[0], Input[1])
print ('len:', len(Input[1]))
print (res, "'{}'".format(Input[0][res:res+len(Input[1])]))
print ('correct:', Input[0].find(Input[1]))
assert Input[0][res:res+len(Input[1])] == Input[1]
assert res == Input[0].find(Input[1])
Input = 'adfbec dsfoeifj asdfjww abyyabcdefg siifjae', 'aba'
print (Input)
res = kmp_match(Input[0], Input[1])
print ('len:', len(Input[1]))
print (res)
print ('correct:', Input[0].find(Input[1]))
assert res == Input[0].find(Input[1])
Input = 'adfbec dsfoeifj asdfjww sifmyy abcdefg siifjae', 'ab'
print (Input)
res = kmp_match(Input[0], Input[1])
print ('len:', len(Input[1]))
print (res, "'{}'".format(Input[0][res:res+len(Input[1])]))
print ('correct:', Input[0].find(Input[1]))
assert res == Input[0].find(Input[1])
Input = 'adfbec dsfoeifj asdfjww sifmyy abcdefg siifjae', 'a'
print (Input)
res = kmp_match(Input[0], Input[1])
print ('len:', len(Input[1]))
print (res, "'{}'".format(Input[0][res:res+len(Input[1])]))
print ('correct:', Input[0].find(Input[1]))
assert res == Input[0].find(Input[1])
Input = 'adfbec dsfoeifj asdfjww sifmyy abcdefg siifjae', 'aa'
print (Input)
res = kmp_match(Input[0], Input[1])
print ('len:', len(Input[1]))
print (res, "'{}'".format(Input[0][res:res+len(Input[1])]))
print ('correct:', Input[0].find(Input[1]))
assert res == Input[0].find(Input[1])
Input = "ababac", "ababac",
print (Input)
res = kmp_match(Input[0], Input[1])
print ('len:', len(Input[1]))
print (res, "'{}'".format(Input[0][res:res+len(Input[1])]))
print ('correct:', Input[0].find(Input[1]))
assert res == Input[0].find(Input[1])
Input = "aabaaabaaac", "aabaaac"
print (Input)
res = kmp_match(Input[0], Input[1])
print ('len:', len(Input[1]))
print (res, "'{}'".format(Input[0][res:res+len(Input[1])]))
print ('correct:', Input[0].find(Input[1]))
assert res == Input[0].find(Input[1])
Input = 'bacbababaabcbab', 'ababababca'
print (Input)
res = kmp_match(Input[0], Input[1])
print ('len:', len(Input[1]))
print ('res:', res, "'{}'".format(Input[0][res:res+len(Input[1])]))
print ('correct:', Input[0].find(Input[1]))
assert res == Input[0].find(Input[1])
if __name__ == "__main__":
main()
|
#!/bin/python
import sys
def capitalize(string):
s = string.split(" ")
temp = []
for word in s:
word = list(word)
if len(word) != 0:
word[0] = word[0].upper()
word = "".join(word)
temp.append(word)
temp.append(" ")
else:
temp.append(" ")
return "".join(temp) |
import re
for i in range(int(raw_input())):
uid = raw_input()
if bool(re.search(r"([A-Z].*){2}", uid)) and bool(re.search(r"([0-9].*){3}", uid)) and bool(re.search(r"^[a-zA-Z0-9]{10}$", uid)) and not bool(re.search(r"([a-zA-Z0-9]).*\1", uid)):
print "Valid"
else:
print "Invalid" |
n = input("Ingrese un número: ")
n = int(n)
if n < 100:
print(False)
else:
print(True)
|
def counting_valleys(path):
altitude = 0
count_valleys = 0
is_in_valley = False
for step in path:
# Update altitude
if step == "U":
altitude += 1
else:
altitude -= 1
if altitude < 0 and not is_in_valley:
# Check if going into valley
count_valleys += 1
is_in_valley = True
elif altitude >= 0:
# If above ground level then not in valley
is_in_valley = False
return count_valleys
|
# reverse_integer
# Input: Number
# Output: Number
# Side effects: None
def reverse_integer(num):
str_num = str(num).replace('-', '')[::-1]
if num < 0:
str_num = '-' + str_num
rev_num = int(str_num)
if rev_num > 2147483647:
return 0
if rev_num < -2147483648:
return 0
return rev_num
|
#program 02 from coursera.
hrs = input("Enter hours: ")
hours= int(hrs)
rate = input("Enter rate: ")
rate= float(rate)
pay = hours *rate
Pay =float(pay)
|
import turtle as t
import random
plantArray=[]
t.bgcolor("orange")
file = open("file.txt","w")
def tdefault():
t.speed(0)
t.pensize(3)
t.hideturtle()
def Printmap():
tdefault()
t.penup()
t.goto(0,-300)
t.pendown()
t.color(0,1,0)
t.begin_fill()
t.circle(300)
t.end_fill()
def turtleDistance(x,y):
tdefault()
t.penup()
t.goto(x,y)
return t.distance(0,0)
def isrange(x,y):
tdefault()
t.penup()
for i,j in plantArray:
if abs(i-x)<50 and abs(j-y)<50:
t.goto(i,j)
if t.distance(x,y)<20:
return 1
return 0
def setPlant():
tdefault()
index=0
x=random.randrange(-300,300)
y=random.randrange(-300,300)
for _ in range(10):
while 270<=turtleDistance(x,y) or [x,y] in plantArray or isrange(x,y):
x=random.randrange(-300,300)
y=random.randrange(-300,300)
plantArray.append([x,y])
t.goto(x,y)
t.pendown()
t.color(1,0,0)
t.begin_fill()
t.circle(7)
t.end_fill()
print(index+1,":plant planted")
index+=1
Printmap()
setPlant()
FRAMERATE=100000
setkey=int(input("[1]방치 [2]선택적 보존(관람객 허용) [3]전적 보존(관람객 불가)"))
if setkey==1:
die=0.1
grow=0.9
if setkey==2:
die=0.25
grow=0.7
if setkey==3:
die=0.4
grow=0.5
for runtime in range(FRAMERATE):
appendArray=[]
deleteArray=[]
print("FRAME:::",runtime,"FOR_NUM:::",len(plantArray))
line = '%d %d'%(runtime,len(plantArray))
file.write(line)
if runtime%10==1:
print("winter")
for x,y in plantArray:
if random.random()>0.5:
pgrow=random.random()
pdie=random.random()
if runtime%10==1:
pgrow=1
pdie-=0.05
if pdie<die:
tdefault()
t.penup()
t.goto(x,y)
t.color(0,1,0)
t.begin_fill()
t.circle(7)
t.end_fill()
deleteArray.append([x,y])
elif pgrow<grow:
tdefault()
xx=random.randrange(0,31)-15
yy=random.randrange(0,31)-15
t.penup()
t.goto(xx+x,yy+y)
if [xx+x,y+yy] not in plantArray and 300>t.distance(0,0):
tdefault()
t.penup()
t.goto(x+xx,y+yy)
appendArray.append([x+xx,y+yy])
t.color(1,0,0)
t.begin_fill()
t.circle(7)
t.end_fill()
for x,y in appendArray:
if [x,y] not in plantArray:
plantArray.append([x,y])
for x,y in deleteArray:
del plantArray[plantArray.index([x,y])]
|
# The prime factors of 13195 are 5, 7, 13 and 29.
# What is the largest prime factor of the number 600851475143 ?
def is_prime(number):
if number <= 1:
return False
elif number <= 3:
return True
elif (number % 2 == 0) or (number % 3 == 0):
return False
i = 5
while i * i <= number:
if (number % i == 0) or (number % (i+2) == 0):
return False
i = i + 6
return True
def find_largest_p_factor(number):
# we will assume the number is odd for simplicity's sake
factor_to_test = 1
current_candidate = factor_to_test
while factor_to_test * factor_to_test < number:
# print(factor_to_test)
if number % factor_to_test == 0: # first test if number is a factor at all
complement = number // factor_to_test
# print(factor_to_test)
# print("complement: " + str(complement))
if is_prime(complement):
return complement
elif is_prime(factor_to_test) and (factor_to_test > current_candidate):
current_candidate = factor_to_test
factor_to_test += 2 # ignore all even numbers as possible factors
return current_candidate
def main():
# print(is_prime(600851475143))
print(find_largest_p_factor(600851475143))
if __name__ == "__main__":
main() |
fahrenheit = float(input("Digite o valor em Graus Celsius para a Conversão : "))
celsius = 5 * (fahrenheit-32)/9
print ("O seu valor convertido de {} fahrenheit para Celsius foi de : {}".format(fahrenheit,celsius))
|
# import Tkinter as tk # Python 2
import tkinter as tk # Python 3
root = tk.Tk()
# The image must be stored to Tk or it will be garbage collected.
root.image = tk.PhotoImage(file='startup.gif')
label = tk.Label(root, image=root.image, bg='white')
root.overrideredirect(True)
root.geometry("+850+250")
# root.lift()
T = tk.Text(root, height=2, width=40, fg='yellow')
T.pack()
T.insert(tk.END, "Just a text Widget\nin two lines\n")
# root.wm_attributes("-topmost", True)
# root.wm_attributes("-disabled", True)
# root.wm_attributes("-transparentcolor", "white")
# label.pack()
# label.mainloop()
T.pack()
T.insert(tk.END, "Just a text Widget\nin two lines\n")
tk.mainloop()
|
def countdown(num):
if num <= 0:
print('카운트다운을 하려면 0보다 큰 입력이 필요합니다.')
else:
for i in range(num,0,-1):
print(i)
countdown(0)
countdown(10) |
import sys
input=sys.stdin.readline
words=input().strip()
ans=0
for word in words:
if word=='A' or word=='B' or word=='C': ans+=3
elif word=='D' or word=='E' or word=='F': ans+=4
elif word=='G' or word=='H' or word=='I': ans+=5
elif word=='J' or word=='K' or word=='L': ans+=6
elif word=='O' or word=='M' or word=='N': ans+=7
elif word=='R' or word=='Q' or word=='P' or word=='S': ans+=8
elif word=='T' or word=='U' or word=='V': ans+=9
elif word=='Z' or word=='Y' or word=='W' or word =='X': ans+=10
print(ans) |
word=input()
if 65<=ord(word)<=90:
print('{}(ASCII: {}) => {}(ASCII: {})'.format(word,ord(word),chr(ord(word)+32),ord(word)+32))
elif 97<=ord(word)<=122: #ord string 아스키 10진수로
print('{}(ASCII: {}) => {}(ASCII: {})'.format(word,ord(word),chr(ord(word)-32),ord(word)-32))
else:
print(word) |
import sys
input = sys.stdin.readline
def make_it(word):
global is_pattern
if not word: # 빈 문자열이 됐다면 제대로 된 패턴임
is_pattern = True
return
if word.startswith("01"): # 01로 시작할 때
make_it(word[2:])
elif word.startswith("100"): # 100으로 시작할 때
i = 3
while i < len(word) and word[i] == "0": # 1이 나올때까지 i+1
i += 1
if i == len(word): # 1이나오지 않고 끝나게 되면 return(1은 무조건 한번 이상 나와야 하기때문)
return
j = i
while j < len(word) and word[j] == "1": # 0이 나올때까지 j+1
j += 1
if j == len(word) or j-i == 1: # 0이 안나왔거나 1이 한번만 나온경우 재귀 ㄱㄱ
make_it(word[j:]) # 100100 인 경우때문에 1이 한번만 나온 경우를 따로 분리함
elif j == len(word)-1: # 10010 인 경우 때문
return
else:
word = word[j:]
if word[1] == "0": word = "1" + word # 1001101 과 1001100 두 경우를 나누기 위함
make_it(word)
t = int(input())
ans = []
for _ in range(t):
word = input().strip()
is_pattern = False
make_it(word)
if is_pattern:
ans.append("YES")
else:
ans.append("NO")
print("\n".join(ans)) |
a=input()
dict1={}
for i in a:
if i in dict1:
dict1[i]+=1
else:
dict1[i]=1
for key,value in dict1.items():
print("{},{}".format(key,value)) |
beer = {'하이트': 2000, '카스': 2100, '칭따오': 2500, '하이네켄': 4000, '버드와이저': 500}
print(beer,' # 인상 전')
beer = {key:value*1.05 for key,value in beer.items()}
print(beer,' # 인상 후') |
def find(x):
if parents[x]==x:
return x
else:
y=find(parents[x])
parents[x]=y
return y
def union(x,y):
root1=find(x)
root2=find(y)
if root1!=root2:
parents[root2]=root1
V,E=map(int,input().split())
dist=[]
parents=[i for i in range(V+1)]
for _ in range(E):
a,b,c=map(int,input().split())
dist.append([c,a,b])
dist.sort(key=lambda x:x[0])
mst_cost=0
cnt=0
for val,s,e in dist:
if find(s) != find(e):
union(s,e)
mst_cost += val
cnt+=1
if cnt==V-1:break
print(mst_cost) |
def solution(numbers, hand):
answer = ''
left=[0]*8
right=[0]*10
left_num=0
right_num=0
for num in numbers:
if num==1 or num==4 or num==7:
left_num=num
answer+='L'
elif num==3 or num==6 or num==9:
right_num=num
answer+='R'
else:
pass
return answer |
# coding=utf8
import copy
import random
# 冒泡排序 时间复杂度:O(n2)
def bubbleSort(arr):
pass
# 选择排序 时间复杂度:O(n2)
def selectSort(arr):
pass
# 插入排序 时间复杂度:最优O(n) 最差O(n2) 不稳定
def insertSort(arr):
if len(arr) < 2 or arr is None:
return
for i in range(len(arr)):
for j in range(i, 0, -1):
if (j > 0 and arr[j] < arr[j - 1]):
temp = arr[j]
arr[j] = arr[j - 1]
arr[j - 1] = temp
return arr
# 生成一组随机数组
def generateRandomArray(maxSize, maxValue):
return [random.randint(0, maxValue) for i in range(maxSize)]
# 默认排序方式
def comparator(arr):
arr.sort()
# 使用对数器的方式检测排序是否ok
if __name__ == '__main__':
testTimes = 1000
maxSize = 100
maxValue = 100
succeed = True
for i in range(testTimes):
arr1 = generateRandomArray(maxSize, maxValue)
arr2 = copy.deepcopy(arr1)
insertSort(arr1)
comparator(arr2)
if (arr1 != arr2):
succeed = False
print(arr1)
print(arr2)
break
print("Nice" if succeed else "Error")
a1 = generateRandomArray(maxSize, maxValue)
print(a1)
insertSort(a1)
print(a1)
|
#import math module
import math
#while loop
while True:
#print the user option
print("\nchoose the operation.\n\n0-add\n1-sub\n2-mul\n3-div\n4-modulo\n5-power\n6-square root\n7-log\n8-sine\n9-cosine\n10-tangent")
#opiton selection
oper=input("\nYour option")
#add
if oper=="0":
v1 = float(input("\nFirst value: "))
v2 = float(input("\nSecond value: "))
print("\nthe result is :" +str(v1+v2)+"\n")
#go back to main menu or exit
back = input("\ngo back to the menu (y/n)")
if back == "y":
continue
else:
break
#sub
elif oper=="1":
v1 = float(input("\nFirst value: "))
v2 = float(input("\nSecond value: "))
print("\nthe result is :" +str(v1-v2)+"\n")
#go back to main menu or exit
back = input("\ngo back to the menu (y/n)")
if back == "y":
continue
else:
break
#mul
elif oper=="2":
v1 = float(input("\nFirst value: "))
v2 = float(input("\nSecond value: "))
print("\nthe result is :" +str(v1*v2)+"\n")
#go back to main menu or exit
back = input("\ngo back to the menu (y/n)")
if back == "y":
continue
else:
break
#div
elif oper=="3":
v1 = float(input("\nFirst value: "))
v2 = float(input("\nSecond value: "))
print("\nthe result is :" +str(v1/v2)+"\n")
#go back to main menu or exit
back = input("\ngo back to the menu (y/n)")
if back == "y":
continue
else:
break
#modulo
elif oper=="4":
v1 = float(input("\nFirst value: "))
v2 = float(input("\nSecond value: "))
print("\nthe result is :" +str(v1%v2)+"\n")
#go back to main menu or exit
back = input("\ngo back to the menu (y/n)")
if back == "y":
continue
else:
break
#power
elif oper=="5":
v1 = float(input("\nFirst value: "))
v2 = float(input("\nSecond value: "))
print("\nthe result is :" +str(math.pow(v1,v2))+"\n")
#go back to main menu or exit
back = input("\ngo back to the menu (y/n)")
if back == "y":
continue
else:
break
#sqrt
elif oper=="6":
v1 = float(input("\nEnter the value for square root: "))
print("\nthe result is :" +str(math.sqrt(v1))+"\n")
#go back to main menu or exit
back = input("\ngo back to the menu (y/n)")
if back == "y":
continue
else:
break
#log
elif oper=="7":
v1 = float(input("\enter the value: "))
print("\nthe value for log base :" +str(math.log(v1,2))+"\n")
#go back to main menu or exit
back = input("\ngo back to the menu (y/n)")
if back == "y":
continue
else:
break
#sine
elif oper=="8":
v1 = float(input("\nenter the value(in degree): "))
print("\nthe value for sin :" +str(math.sin(math.radians(v1)))+"\n")
#go back to main menu or exit
back = input("\ngo back to the menu (y/n)")
if back == "y":
continue
else:
break
#cos
elif oper=="9":
v1 = float(input("\nenter the value(in degree): "))
print("\nthe value for cos :" +str(math.cos(math.radians(v1)))+"\n")
#go back to main menu or exit
back = input("\ngo back to the menu (y/n)")
if back == "y":
continue
else:
break
#tan
elif oper=="10":
v1 = float(input("\nenter the value(in degree): "))
print("\nthe value for tan :" +str(math.tan(math.radians(v1)))+"\n")
#go back to main menu or exit
back = input("\ngo back to the menu (y/n)")
if back == "y":
continue
else:
break
#handling invalid input
else:
print("\nInvalid option!\n")
continue
#end of pgm |
#!/bin/python3
# Link: https://www.hackerrank.com/challenges/py-if-else/problem
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
if (n % 2 == 1):
print('Weird')
elif (n % 2 == 0 and n in range(2, 6, 1)):
print('Not Weird')
elif (n % 2 == 0 and n in range(6, 21, 1)):
print('Weird')
elif (n % 2 == 0 and n > 20):
print('Not Weird') |
import hashlib
# https://www.hackerrank.com/challenges/python-tuples/problem
if __name__ == '__main__':
n = int(input())
integer_list = map(int, input().split())
mylist = tuple(integer_list)
answer = 0
for x in range(0,n):
answer = answer + mylist[x]
answers= hash(mylist)
print(answers) |
'''
very efficient!
but need to cheat, sorted
Time Complexity O(log_2 n)
Space Complexity O(1)
psudocode
TODO 或許需要雙指標來跳出死回圈
middle = (len(input) + 1) // 2
if not middle:
return false
if middle > value_you_want:
find the left
if middle < value_you_want:
find the right
if middle == value_you_want:
return middle
'''
def binary_search(value_you_want: float, sordted_input_list: list) -> int:
_length = len(sordted_input_list)
mid = (_length + 1) // 2
while True:
if mid == 0 or mid > _length:
return -1
if sordted_input_list[mid] > value_you_want:
mid = (mid + 0) // 2
elif sordted_input_list[mid] < value_you_want:
mid = (mid + _length) // 2
else:
return mid
# def bsearch(l, value):
# lo, hi = 0, len(l) - 1
# while lo <= hi:
# mid = (lo + hi) / 2
# if l[mid] < value:
# lo = mid + 1
# elif value < l[mid]:
# hi = mid - 1
# else:
# return mid
# return -1
if __name__ == "__main__":
sorted_input_list_1 = [5, 11, 12, 30, 44, 50, 57]
print(binary_search(value_you_want=44, sordted_input_list=sorted_input_list_1))
print(binary_search(value_you_want=57, sordted_input_list=sorted_input_list_1))
print(binary_search(value_you_want=11, sordted_input_list=sorted_input_list_1))
print(binary_search(value_you_want=4, sordted_input_list=sorted_input_list_1))
print(binary_search(value_you_want=14, sordted_input_list=sorted_input_list_1))
print(binary_search(value_you_want=31, sordted_input_list=sorted_input_list_1))
|
import os.path
def check_file(path):
if os.path.isfile(path) == False:
print ("File not exist")
exit()
def init():
f = open('translate.txt', 'r')
big_text = f.read()
parts = big_text.split('\n')
f.close
return parts
def create_dictionary(parts):
words=[]
i=0
while i < len(parts):
my_dict = {'english':parts[i], 'persian':parts[i+1]}
words.append(my_dict)
i += 2
return words
def check_duplication(words, new_word, language):
for i in range(len(words)):
if words[i][language] == new_word:
return True
break
else:
return False
def main():
check_file("translate.txt")
print("1- Add new word")
print("2- tranlate english2persian")
print("3- translate persian2english")
print("4- Exit")
while (True):
user_choice_index = int(input("\nPlease enter option#:"))
if user_choice_index == 4:
print("Good bye...")
break
elif user_choice_index == 1:
en_word = input('english word:')
if check_duplication(create_dictionary(init()), en_word,'english') == False:
fa_word = input('farsi word:')
f = open('translate.txt', 'a')
f.write('\n')
f.write(en_word)
f.write('\n')
f.write(fa_word)
print('word added successfully')
f.close()
else:
print('word is duplicate!!!')
elif user_choice_index == 2:
print('please enter your english text:')
user_string = input()
sentences = user_string.split('.')
for s in sentences:
user_words = s.split(' ')
words = create_dictionary(init())
for j in range(len(user_words)):
for i in range(len(words)):
if words[i]['english'] == user_words[j]:
print(words[i]['persian'], end=' ')
break
else:
print(user_words[j], end=' ')
print('.', end='')
elif user_choice_index == 3:
print('please enter your finglish text:')
user_string = input()
sentences = user_string.split('.')
for s in sentences:
user_words = s.split(' ')
words = create_dictionary(init())
for j in range(len(user_words)):
for i in range(len(words)):
if words[i]['persian'] == user_words[j]:
print(words[i]['english'], end=' ')
break
else:
print(user_words[j], end=' ')
print('.', end='')
main() |
# Create a class Ball.
# Ball objects should accept one argument for "ball type" when instantiated.
# If no arguments are given, ball objects should instantiate with a "ball type" of "regular."
class Ball(object):
def __init__(self, argument=None):
self.ball_type = "regular"
if argument != None:
self.ball_type = "super"
|
# Створити батьківський клас Figure з методами __init__: ініціалізується колір,
# get_color: повертає колір фігури,
# info: надає інформацію про фігуру та колір,
# від якого наслідуються такі класи як Rectangle,
# Square, які мають інформацію про ширину,
# висоту фігури, метод square, який знаходить площу фігури.
class Figure:
def __init__(self, color):
self.color = color
def get_color(self):
return "The color of figure is {}".format(self.color)
def info(self):
return "This is figure - and the color of figure is {}".format(self.color)
class Rectangle(Figure):
def __init__(self, color):
Figure.__init__(self, color)
self.a = float(input("Enter height of rectangle: "))
self.b = float(input("Enter width of rectangle: "))
def square_of_rectangle(self):
return "The S of rectangle = a * b = {}".format(self.a * self.b)
class Square(Figure):
def __init__(self, color):
Figure.__init__(self, color)
self.a = float(input("Enter side of square: "))
def sguare_of_square(self):
return "The S of square = a ** 2 = {}".format(self.a ** 2)
f = Figure("black")
print(f.info())
print(f.get_color())
rect = Rectangle("black")
print(rect.square_of_rectangle())
sqr = Square("white")
print(sqr.sguare_of_square())
|
# Write a program that finds the summation
# of every number from 1 to num.
# The number will always be a positive integer greater than 0.
def summation(num):
numbers = []
for i in range(1, num + 1):
numbers.append(i)
return sum(numbers)
|
r=float(input("enter radius"))
import math
area=math.pi*r**2
print(area)
|
#!/usr/local/bin/python3.9
# -*- coding: utf-8 -*-
# write program to convert temperatures to and from celsius,fahrenheit
#temperature = int(input("saisir une temperature :")
#degre = str(input("indiquer si la temperature rentrée est en C (celsius) ou F (fahrenheit)"))
#définition des fonctions de conversion
def cel_far():
temperatureC = int(input("saisir une temperature :"))
conversionF = int(9 * temperatureC / 5 + 32)
print(temperatureC,"°C is", conversionF, "in Fahrenheit")
#test
#cel_far(60)
def far_cel():
temperatureF = int(input("saisir une temperature :"))
conversionC = int((temperatureF - 32) / 9 *5)
print(temperatureF,"°F is", conversionC, "in Celsius")
#test
#far_cel(45)
#main program
while True:
choix = input("\n1: °C to °F\n2: °F to °C\nq : quit\n> ")
if choix == "q":
quit()
elif choix == "1":
cel_far()
elif choix == "2":
far_cel()
else:
print("Input error")
|
menu = {}
print("""----order----
1: Add item
2: Remove item
3: View order
4: Cancel order
""")
option = int(input("Enter an option: "))
while option != 0:
if option == 1:
item = input("Enter an item: ")
price = int(input("Enter the price: "))
menu[item] = price
elif option == 2:
item = input("Enter an item: ")
del(menu[item])
elif option == 3:
for item in menu:
print(item, ":", menu[item])
elif option != 0:
print("You didn't enter a valid number.")
option = int(input("\n\nEnter an Option: "))
else:
print("Order canceled! Have a nice day.")
|
import argparse
import math
import marble_path
"""
Produces the bottom part of a limacon curve, specifically, the loop.
The defaults produce a nice looking curve.
python generate_limacon.py
The hole can be generated as follows:
python generate_limacon.py --tube_radius 10.5 --wall_thickness 11 --tube_start_angle 0 --tube_end_angle 360
There are parameters to make the limacon stretched in different directions.
"""
def limacon_derivative(theta, x_scale, y_scale, a, b):
# x(t) = math.cos(theta) * (a - b * math.cos(theta))
# y(t) = math.sin(theta) * (a - b * math.cos(theta))
# derivatives are fun!
# x(t) = -math.sin(theta) * (a - b * math.cos(theta)) + b * math.cos(theta) * math.sin(theta)
# y(t) = math.cos(theta) * (a - b * math.cos(theta)) + b * math.sin(theta) * math.sin(theta)
# and then of course we scale it by x_scale, y_scale
return (x_scale * (-math.sin(theta) * (a - b * math.cos(theta)) + b * math.cos(theta) * math.sin(theta)),
y_scale * ( math.cos(theta) * (a - b * math.cos(theta)) + b * math.sin(theta) * math.sin(theta)))
def get_normal_rotation(theta, x_scale, y_scale, a, b):
# there is a discontinuity in the derivative at theta = 0.0
# fortunately, we know it will be heading south at that point
if theta == 0.0:
return 180
dx, dy = limacon_derivative(theta, x_scale, y_scale, a, b)
rotation = math.asin(dx / (dx ** 2 + dy ** 2) ** 0.5)
if dx > 0 and dy > 0:
# this gives us a negative rotation, meaning to the right
rotation = -rotation
elif dx > 0 and dy < 0:
rotation = rotation + math.pi
elif dx < 0 and dy > 0:
rotation = -rotation
else: # dx < 0 and dy < 0
rotation = rotation + math.pi
return rotation * 180 / math.pi
def generate_limacon(args):
# the domain of the limacon will be -domain_size to +domain_size
domain_size = args.domain_size
min_time = -domain_size
time_step_width = (domain_size * 2) / (args.time_steps)
def theta_t(time_step):
return min_time + time_step_width * time_step
def x_t(time_step):
theta = theta_t(time_step)
r = args.constant_factor - args.cosine_factor * math.cos(theta)
return math.cos(theta) * r
def y_t(time_step):
theta = theta_t(time_step)
r = args.constant_factor - args.cosine_factor * math.cos(theta)
return math.sin(theta) * r
min_y = min(y_t(y) for y in range(0, args.time_steps+1))
max_y = max(y_t(y) for y in range(0, args.time_steps+1))
y_scale = args.length / (max_y - min_y)
min_x = min(x_t(x) for x in range(0, args.time_steps+1))
max_x = max(x_t(x) for x in range(0, args.time_steps+1))
if args.width is None:
x_scale = y_scale
else:
x_scale = args.width / (max_x - min_x)
def scaled_x_t(time_step):
return (x_t(time_step) - min_x) * x_scale
def scaled_y_t(time_step):
return (y_t(time_step) - min_y) * y_scale
z_t = marble_path.arclength_height_function(scaled_x_t, scaled_y_t, args.time_steps, args.slope_angle)
def r_t(time_step):
theta = theta_t(time_step)
return get_normal_rotation(theta, x_scale, y_scale, args.constant_factor, args.cosine_factor)
print("Center of tube at time step 0: ", scaled_x_t(0), scaled_y_t(0))
print("Angle of tube: ", r_t(0))
for triangle in marble_path.generate_path(x_t=scaled_x_t, y_t=scaled_y_t, z_t=z_t, r_t=r_t,
tube_args=args,
num_time_steps=args.time_steps):
yield triangle
def balance_domain(constant_factor, cosine_factor):
"""
Given the parameters of the curve, find a theta for which the mass
on both sides of the line between the endpoints is balanced.
Calculation method is to sum x * m (approximated numerically) and
return when sum(x * m) / m crosses x. We note that the theta
where the x derivative is 0 is a good place to start looking for
this crossing, since it is impossible to be balanced before then.
-math.sin(theta) * (a - b * math.cos(theta)) + b * math.cos(theta) * math.sin(theta) = 0
-> drop the sin, since this will not be theta = 0 or theta = pi
-a + 2b * math.cos(theta) = 0
math.cos(theta) = a/2b
theta = math.acos(a/2b)
As an approximation, we treat the tube as a point mass, although
this changes the effect of the tube.
return value is theta, in radians
"""
mass = 0.0
torque = 0.0
theta = math.acos(constant_factor / 2.0 / cosine_factor)
for i in range(math.floor(math.pi * 2 * 1000)):
t = i / 1000
x1 = math.cos(t) * (constant_factor - cosine_factor * math.cos(t))
x2 = math.cos(t+0.001) * (constant_factor - cosine_factor * math.cos(t + 0.001))
y1 = math.cos(t) * (constant_factor - cosine_factor * math.cos(t))
y2 = math.cos(t+0.001) * (constant_factor - cosine_factor * math.cos(t + 0.001))
delta_mass = ((y2 - y1) ** 2 + (x2 - x1) ** 2) ** 0.5
mass = mass + delta_mass
torque = torque + x1 * delta_mass
if t > theta and torque / mass > x1:
print("Balanced at t =", t)
return t
raise ValueError("Could not find balance point!")
def parse_args(sys_args=None):
parser = argparse.ArgumentParser(description='Arguments for an stl limacon. Graph of r = a - b cos(theta)')
marble_path.add_tube_arguments(parser, default_slope_angle=12.0, default_output_name='limacon.stl')
parser.add_argument('--constant_factor', default=1, type=float,
help='The a in the "a - b cos(theta)"')
parser.add_argument('--cosine_factor', default=2, type=float,
help='The b in the "a - b cos(theta)"')
parser.add_argument('--time_steps', default=200, type=int,
help='How refined to make the limacon')
parser.add_argument('--length', default=134, type=float,
help='Distance from one end to the other, ignoring the tube')
parser.add_argument('--width', default=None, type=float,
help='Distance from left to right, ignoring the tube. If None, the curve will be scaled to match the length')
parser.add_argument('--domain_size', default=1.806, type=float,
help='Theta goes from -domain_size to domain_size')
parser.add_argument('--auto_domain', dest='auto_domain',
default=True, action='store_true',
help='Dynamically calculate the domain by trying to balance the torque')
parser.add_argument('--no_auto_domain', dest='auto_domain',
action='store_false',
help="Don't dynamically calculate the domain by trying to balance the torque")
parser.set_defaults(tube_start_angle=-60)
args = parser.parse_args(args=sys_args)
if args.cosine_factor == 1.0:
raise ValueError("Sorry, but b=1.0 causes a discontinuity in the derivative")
if args.cosine_factor == 0.0:
raise ValueError("Consider using generate_helix if you just want a circle")
if args.cosine_factor < 0.0:
raise ValueError("You can simply mirror the resulting curve and set cosine_factor > 0.0")
if args.cosine_factor < 1.0:
raise ValueError("0.0<b<1.0 not implemented yet")
if args.auto_domain:
args.domain_size = balance_domain(args.constant_factor, args.cosine_factor)
return args
def main(sys_args=None):
args = parse_args(sys_args)
marble_path.print_args(args)
marble_path.write_stl(generate_limacon(args), args.output_name)
if __name__ == '__main__':
main()
|
import argparse
import math
import marble_path
def calculate_slope_angle(helix_radius, vertical_displacement):
"""
tube_radius is adjacent, vertical_displacement is opposite
returns asin in degrees
this is the slope of the ramp
"""
helix_distance = helix_radius * math.pi * 2
slope_distance = (helix_distance ** 2 + vertical_displacement ** 2) ** 0.5
# currently in radians
slope_angle = math.asin(vertical_displacement / slope_distance)
return slope_angle / math.pi * 180
def helix_x_t(args):
num_helix_subdivisions = math.ceil(args.rotations * args.helix_sides)
if args.clockwise:
def x_t(helix_subdivision):
helix_angle = args.initial_rotation - 360 / args.helix_sides * helix_subdivision - 180
r_x_disp = args.helix_radius * math.cos(helix_angle / 180 * math.pi)
# helix_radius + tube_radius so that everything is positive
return args.helix_radius + args.tube_radius + r_x_disp
else:
def x_t(helix_subdivision):
helix_angle = 360 / args.helix_sides * helix_subdivision + args.initial_rotation
r_x_disp = args.helix_radius * math.cos(helix_angle / 180 * math.pi)
# helix_radius + tube_radius so that everything is positive
return args.helix_radius + args.tube_radius + r_x_disp
return x_t
def helix_y_t(args):
num_helix_subdivisions = math.ceil(args.rotations * args.helix_sides)
if args.clockwise:
def y_t(helix_subdivision):
helix_angle = args.initial_rotation - 360 / args.helix_sides * helix_subdivision - 180
r_y_disp = args.helix_radius * math.sin(helix_angle / 180 * math.pi)
# helix_radius + tube_radius so that everything is positive
return args.helix_radius + args.tube_radius + r_y_disp
else:
def y_t(helix_subdivision):
helix_angle = 360 / args.helix_sides * helix_subdivision + args.initial_rotation
r_y_disp = args.helix_radius * math.sin(helix_angle / 180 * math.pi)
# helix_radius + tube_radius so that everything is positive
return args.helix_radius + args.tube_radius + r_y_disp
return y_t
def helix_r_t(args):
if args.clockwise:
def r_t(helix_subdivision):
helix_angle = args.initial_rotation - 360 / args.helix_sides * helix_subdivision
return helix_angle % 360.0
else:
def r_t(helix_subdivision):
helix_angle = 360 / args.helix_sides * helix_subdivision + args.initial_rotation
return helix_angle % 360.0
return r_t
def generate_helix(args):
"""
helix_radius is the measurement from the axis to the center of any part of the ramp
tube_radius is the measurement from the center of ramp to its outer wall
wall_thickness is how thick to make the wall
special case: if wall_thickness >= tube_radius, there is no inner opening
tube_start_angle and tube_end_angle represent which part of the ramp to draw.
0 represents the part furthest from the axis
180 represents the part closest to the axis
0..180 covers the bottom of the arc. for the top, for example, do 180..0
special case: if 0..360 or any rotation of that is supplied, the entire circle is drawn
tube_sides is how many sides a complete tube would have.
tube_start_angle and tube_end_angle are discretized to these subdivisions
helix_sides is how many sides a complete helix rotation has
vertical_displacement is how far to move up in one complete rotation
tube_radius*2 means the next layer will be barely touching the previous layer
rotations is how far around to go. will be discretized using helix_sides
"""
num_helix_subdivisions = math.ceil(args.rotations * args.helix_sides)
print("Num helix: {}".format(num_helix_subdivisions))
if num_helix_subdivisions <= 0:
raise ValueError("Must complete some positive fraction of a rotation")
x_t = helix_x_t(args)
y_t = helix_y_t(args)
r_t = helix_r_t(args)
def z_t(helix_subdivision):
# tube_radius included again to keep everything positive
# negative sign in slope is on account of the decision that positive slope means down
return args.tube_radius - math.sin(args.slope_angle / 180 * math.pi) * 2 * math.pi * args.helix_radius * helix_subdivision / args.helix_sides
for triangle in marble_path.generate_path(x_t=x_t, y_t=y_t, z_t=z_t, r_t=r_t,
tube_args=args,
num_time_steps=num_helix_subdivisions):
yield triangle
def parse_args(sys_args=None):
# TODO: add an argument which does the math for rotations if you give it the angle of helix you want, for example
parser = argparse.ArgumentParser(description='Arguments for an stl helix.')
marble_path.add_tube_arguments(parser,
default_slope_angle=2.0,
default_output_name='helix.stl')
parser.add_argument('--helix_radius', default=19, type=float,
help='measurement from the axis to the center of any part of the ramp')
parser.add_argument('--helix_sides', default=64, type=int,
help='how many sides it takes to go around the axis once')
parser.add_argument('--vertical_displacement', default=None, type=float,
help='how far to move up in one complete rotation. tube_radius*2 means the next layer will be barely touching the previous layer')
parser.add_argument('--rotations', default=1, type=float,
help='rotations is how far around to go. will be discretized using helix_sides')
parser.add_argument('--initial_rotation', default=0, type=float,
help='How much to offset the rotation of the helix curve')
parser.add_argument('--clockwise', dest='clockwise', default=False, action='store_true',
help='Rotate clockwise. Note that rotating clockwise will make the initial rotation start from the left side of the helix')
parser.add_argument('--counterclockwise', dest='clockwise', action='store_false',
help="Rotate counterclockwise")
args = parser.parse_args(sys_args)
if args.vertical_displacement is not None:
# slope_angle is the angle of the slope as it goes up the spiral
# faces will be tilted this much to allow better connections with
# the next piece
slope_angle = calculate_slope_angle(args.helix_radius,
args.vertical_displacement)
print("Derived slope angle:", slope_angle)
args.slope_angle = slope_angle
return args
def main(sys_args=None):
args = parse_args(sys_args)
marble_path.print_args(args)
marble_path.write_stl(generate_helix(args), args.output_name)
if __name__ == '__main__':
main()
|
sum=0
num=0
while num<15:
num1=int(input("enter the number"))
sum=sum+num1
num=num+1
print("average is",sum/15) |
"""
Project Euler
Problem 2
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
"""
import time
fibonacci_list = [1]
sum_of_fibonacci = 0
t0 = time.time()
for i, e in enumerate(fibonacci_list):
fibonacci_list.append(fibonacci_list[i] + fibonacci_list[i - 1]) # O(n)
if e % 2 == 0:
sum_of_fibonacci = sum_of_fibonacci + e
if 4000000 < e:
break
t1 = time.time()
print(t1 - t0)
print(sum_of_fibonacci)
|
import time
import math
n = 2000000
counter = 2
sum_of_primes = 0
def is_prime(prime):
for i in range(2, int(math.sqrt(prime)) + 1):
if prime % i == 0:
return False
return True
t0 = time.time()
while True:
if is_prime(counter):
sum_of_primes += counter
if counter == n:
break
counter += 1
t1 = time.time()
print(t1 - t0)
print(sum_of_primes)
|
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
import math
st.write("# Hello")
x = 1000
x
"""
# Docstrings get rendered as markdown
* markdown is simplfied HTML
* to get some examples: [visit stackedit.io](https://stackedit.io)
"""
st.sidebar.header("Sidebar")
st.sidebar.selectbox(label = "Choose one...", options = ["Eeeny", "Meeny", "Miny", "Mo"])
y = np.random.standard_normal(10000)
st.line_chart(y)
scale_hist = np.array(range(0,1500, 250))
fig, (axes1,axes2) = plt.subplots(2,1, figsize=(2,2))
axes1.set_yticks(scale_hist)
axes1.set_yticklabels(scale_hist, fontsize=3)
axes1.set_xticks(list(range(-3,4,1)))
axes1.set_xticklabels(list(range(-3,4,1)), fontsize=3)
axes1.hist(y, bins = 25, edgecolor = 'w')
axes2.plot(y.cumsum())
y_max = math.ceil(max(y.cumsum())/ 10) * 10
y_min = min(y.cumsum())// 10 * 10
axes2.set_yticks(np.linspace(y_min,y_max,11))
axes2.set_yticklabels(np.linspace(y_min,y_max,11), fontsize= 3)
axes2.set_xticklabels("", fontsize = 3)
y_max
y_min
st.pyplot(fig)
st.line_chart(y.cumsum()) |
"""
Author: Mark Frydenberg
Description: text file examples
"""
REGFILE = "registration.txt"
def linebyline():
print("Line By Line")
# print all the records in the file within range specified
lowAge = int(input("Enter the lower age :"))
highAge = int(input("Enter the upper age: "))
# find all the people in the file whose ages are in the range above
f = open(REGFILE, 'r') # open file for read
done = False
while not done:
line = f.readline()
if line == "": # end of file
done = True
continue
record = line.split("|")
name = record[0]
addr = record[1]
city = record[2]
state = record[3]
zip = record[4]
age = int(record[5])
if lowAge <= age <= highAge:
print(f"{name:20s}\t{age:3d}")
f.close() # input files don't need to be closed explicitly
def filetolist():
print("Read File to List of Strings")
lowAge = int(input("Enter the lower age :"))
highAge = int(input("Enter the upper age: "))
f = open(REGFILE, 'r') # open file for read
ftext = f.read() # read the entire file into a string
print(ftext)
f.close()
lines = ftext.split("\n") # split the file at new line characters
first = True # skip the header row in the file
for line in lines:
if first:
first = False #skip the first line
continue
if line == "": # end of file
break
else:
record = line.split("|")
name = record[0]
addr = record[1]
city = record[2]
state = record[3]
zip = record[4]
age = int(record[5])
if lowAge <= age <= highAge:
print(f"{name:20s}\t{age:3d}")
def modifyfile():
print("Modify File")
years = int(input("Enter years to add to each age: "))
f = open(REGFILE, 'r') # open file for read
ftext = f.read() # read the entire file into a string
f.close()
lines = ftext.split("\n") # split the file at new line characters
f = open(REGFILE, "w")
for line in lines:
if line == "": # end of file
break
else:
record = line.split("|")
name = record[0]
addr = record[1]
city = record[2]
state = record[3]
zip = record[4]
age = int(record[5])
age += years
# you could do it this way
# newLine = name + "|" + addr + "|" + city + "|" + \
# state + "|" + zip + "|" + str(age) + "\n"
# but this is a good use of the join method with a list
listItems = [name, addr, city, state, zip, str(age)]
newLine = "|".join(listItems) + "\n" # create the new line to write
f.write(newLine)
f.close()
done = False
while not done:
choice = input("""
1 Read File Line By Line
2 Read File to String
3 Modify File
4 Print File with Line Numbers (to be filled in by you)
5 Write Matching Records to a New File (to be filled in by you)
Q Quit
Enter choice:""")
if choice == "1":
linebyline()
elif choice == "2":
filetolist()
elif choice == "3":
modifyfile()
elif choice == "Q":
print("Quit. Thank you.")
done = True
else:
print("Enter a valid choice.")
|
# The plot server must be running
import numpy as np
from bokeh.plotting import *
x = np.linspace(-7, 7, 100)
y = np.sin(x)
# Go to http://localhost:5006/bokeh to view this plot
output_server("color example")
hold(True)
scatter(x,y, tools="pan,zoom,resize")
scatter(x,2*y, tools="pan,zoom,resize")
scatter(x,3*y, color="green", tools="pan,zoom,resize")
figure()
plot(x,y, points=True, radius=2, tools="pan,zoom,resize,select")
plot(x,2*y, points=False)
plot(x,3*y, points=True, color="green", radius=2)
|
height = int(input("Please enter your height in inches: "))
age = int(input("Please enter your age in years: "))
can_ride_rollercoaster = height > 48 and age >= 10
if can_ride_rollercoaster:
print("Welcome aboard the Iron Dragon")
print("Please keep your hands an feed inside the coaster at all times")
else:
print("Sorry, but you cannot ride this ride")
if height <= 48 and age < 10:
print("Please visit the kids park by the food court")
elif height <= 48:
print("You are too short to be safe on this ride")
elif age < 10:
print("You are too young to ride this ride")
else:
print("Something went wrong...")
|
#!/usr/bin/python
'''
Stage II: Needle in a haystack
================================
Next, let’s check your skills for working with collections.
We’re going to send you a dictionary with two values and keys. The first value, needle, is a string.
The second value, haystack, is an array of strings. You’re going to tell the API where the needle is in the array.
'''
import requests
import json
url = 'http://challenge.code2040.org/api/haystack'
data = '{"token": "24DVHp6MNU"}'
needleRequests=requests.post(url, data=data)
hay = json.loads(needleRequests.text)
'''
Both haystack and needle have the same dictionary key.In order to access the values of the haystack array and the needle array
I used the .get method.
'''
stack = hay["result"].get("haystack")
needle = str(hay["result"].get("needle")) #turned needle value into a string so with will be easy to search the array
needleLoca =0
for s in stack: #loop through the haystack array
if needle in str(s):
needleLoca = stack.index(s)
key1={"needle": needleLoca, "token":"24DVHp6MNU"}
key=json.dumps(key1)
reversePost2 = requests.post('http://challenge.code2040.org/api/validateneedle', data=key)
reversePost2.text
|
if input("Is de kaas geel? (J/N) : ") == 'J':
if input("zitten er gaten in? (J/N) : ") == 'J':
if input("Is de kaas blechelijk duur? (J/N) : ") == 'J':
print("Emmenthaler")
else:
print("Leerdammer")
else:
if input("Is de kaas hard als steen? (J/N) : ") == 'J':
print("Pamigiano Reggiano")
else:
print("Goudse Kaas")
else:
if input ("Heeft de kaas blauwe schimmels? (J/N) : ") == 'J':
if input ("Heeft de kaas een korst? (J/N) : ") == 'J':
print("Blue de Rochbaron")
else:
print("Foume d'Ambert")
else:
if input ("Heeft de kaas een korst? (J/N) : ") == 'J':
print("Camembert")
else:
print("Mozzerella")
|
class AdvancedArithmetic(object):
def divisorSum(n):
raise NotImplementedError
class Calculator(AdvancedArithmetic):
def divisorSum(self, n):
i = 1
total = 0
while i <= n:
if (n % i == 0):
total += i
i += 1
return total
# n = int(input())
# my_calculator = Calculator()
# s = my_calculator.divisorSum(n)
# print("I implemented: " + type(my_calculator).__bases__[0].__name__)
# print(s) |
#!/usr/bin/env python3
'''
input: n, i, pv, pmt, fv
calc: Financial functions
return: dict and json
'''
# -*- coding: utf-8 -*-
# Code styled according to pycodestyle
# Code parsed, checked possible errors according to pyflakes and pylint
import locale
import json
locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')
__author__ = "Marcos Aurelio Barranco"
__copyright__ = "Copyright 2016, The MIT License (MIT)"
__credits__ = ["Marcos Aurelio Barranco", ]
__license__ = "MIT"
__version__ = "2"
__maintainer__ = "Marcos Aurelio Barranco"
__email__ = ""
__status__ = "Production"
def logaritmo(periods):
'''
Function to calcule ln, logarithm
'''
return 1000 * ((periods ** (1 / 1000)) - 1)
def main(n=0, i=0, pv=0, pmt=0, fv=0):
'''
1. to calculate "n" the followings are required: i, pv and fv
to calculate "i" the followings are required: n, pv, and fv
to calculate "PV" the followings are required: n, i, and fv
to calculate "PMT" the followings are required: n, i and fv
OR n, i and pv
to calculate "FV" the followings are required: n, i and pv
2. The PV value should only be negative on the HP 12C because
this calculator works with concept of cash flow and initial
disbursement of cash flow is considered negative
3. The HP 12C rounds off the periods in months.
HP 12 C --> FV=1.126.825,03, PV=1000000, i=1%
n equal to 12 months
3.1. This function doesn't round it
--> main(i=1, pv=1000000, fv=1126825.03)
n equal to 12.000654059154352 months/days
according to 3.1 you'll receive this one:
0 n 12.000654059154352
where:
0 is just the index inside the python dictionary
n is Periods
12.000654059154352 is months/days
4. The calculations were double checked with the HP 12C
Coded by Marcos Aurelio Barranco
'''
dict_retorno = {}
if i > 0 and pv > 0 and fv > 0:
# n = Periods
nCalc = logaritmo(fv / pv) / logaritmo(1 + (i / 100))
dict_retorno['n'] = nCalc
if n > 0 and pv > 0 and fv > 0:
# i = Interest rate
iCalc = ((fv / pv)**(1 / n)) - 1
locale.setlocale(locale.LC_ALL, '')
dict_retorno['i'] = iCalc * 100
if n > 0 and i > 0 and fv > 0:
# PV = Present value
pvCalc = fv / ((1 + (i / 100))**n)
locale.setlocale(locale.LC_ALL, '')
dict_retorno['PV'] = locale.currency(
pvCalc, grouping=True, symbol=True)
if n > 0 and i > 0 and fv > 0:
# PMTFV_GT0 = Periodic Payment Amount when FV > 0
CalcUpFV = fv
CalcDownFV = (i / 100) / (((1 + (i / 100))**n) - 1)
pmtCalcFV = CalcUpFV * CalcDownFV
dict_retorno['PMTFV_GT0'] = locale.currency(
pmtCalcFV, grouping=True, symbol=True)
if n > 0 and i > 0 and pv > 0:
# PMTPV_GT0 = Periodic Payment Amount when PV > 0
CalcUpPV = pv
CalcDownPV = ((
(i / 100) * ((1 + (i / 100))**n)) / (((1 + (i / 100))**n) - 1))
pmtCalcPV = CalcUpPV * CalcDownPV
dict_retorno['PMTPV_GT0'] = locale.currency(
pmtCalcPV, grouping=True, symbol=True)
if n > 0 and i > 0 and pv > 0:
# Future value(FV)
fvCalc = pv * ((1 + (i / 100))**n)
locale.setlocale(locale.LC_ALL, '')
dict_retorno['FV'] = locale.currency(
fvCalc, grouping=True, symbol=True)
json_retorno = json.dumps(dict_retorno, ensure_ascii=False)
# dictionary and json
return dict_retorno, json_retorno
if __name__ == '__main__':
try:
dict_ret, json_ret = main(i=1, pv=1000000, fv=1126825)
print(dict_ret) # Dict
print(json_ret) # JSON
for i, j in enumerate(dict_ret):
# index, key, value
print(i, j, dict_ret[j])
except Exception as err:
raise Exception("ErrValFinFunc-1 : {0}".format(err))
|
from Command import Command
from utils.Direction import Direction
class DirectionHelper:
"""
Helper class that helps robot turn left or right
"""
@classmethod
def turn(cls, current_direction: Direction, instruction: tuple[Command, int]) -> Direction:
"""
It uses robot`s current direction as base direction, and uses instruction to help the robot towards
the right direction
:param current_direction:
:param instruction:
:return: The right direction enum
"""
current_direction_enum_value = current_direction.value
target_direction: Command = instruction[0]
steps: int = instruction[1]
if target_direction is Command.RIGHT:
total_steps = current_direction_enum_value + steps
final_direction_value = total_steps % 4
if final_direction_value == 0:
return Direction(4)
else:
return Direction(final_direction_value)
if target_direction is Command.LEFT:
final_steps = current_direction_enum_value - steps
if final_steps % 4 == 0:
return Direction(4)
# the left turn based on deduction of the direction enum. That if the final steps > 0 means
# the final steps must fall into one of the direction enum values, so that would be the right
# direction
if final_steps > 0:
return Direction(final_steps)
# transfer the left turn to right turn. For example, if the current direction is East (enum val = 2),
# the instruction is turn left 3 times, the final steps would be -1, it means we only need to turn right
# once to get the final direction, South in this case.
final_direction = current_direction_enum_value + (abs(final_steps)) % 4
return Direction(final_direction)
|
import random
sc=0
ch=1
print("""
WELCOME TO THE FIRST EVER GAME BY SWAPNIL GARG,
THIS IS THE ADDITION QUIZ,
YOU CAN PLAY A GAME OF YOUR PREFERRED LENGTH
AND VIEW YOUR FINAL SCORE AT THE END""")
while ch==1:
n=int(input("How long of a game you wish to play?"))
r=0
while r<n:
x=random.randint(1,100)
y=random.randint(1,100)
z=x+y
print(x,"+",y,"=?")
ans=int(input())
if ans==z:
print("The answer is correct!")
sc=sc+1
print("Current score is",sc)
else:
print("Sorry,The answer is wrong!")
print("The correct answer is",z)
sc=sc-1
print("Current score is",sc)
r=r+1
print("Your final score is",sc,"out of",n)
ch=int(input("Wanna play again,then press 1"))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 16 18:17:04 2018
@author: David
"""
#%%
#from functools import reduce
#def create_product(name,price):
# return {"name":name, "price":price}
def create_product(name,price):
return {"name":name, "price":price}
def print_cart(cart):
print("Checkout:")
for item in cart:
print(item["name"], "price:", item["price"])
print("Total price:", checkout(cart))
def checkout(cart):
total = 0
insurance_added = False
priority_mail_added = False
for item in cart:
if item["name"] == "Insurance":
if not insurance_added:
total = total + item["price"]
insurance_added = True
elif item["name"] == "Priority mail":
if not priority_mail_added:
total = total + item["price"]
priority_mail_added = True
else:
total = total + item["price"]
return total
################
#def add_to_inventory (inventory,product):
# return inventory + [product]
guitar = create_product ("Guitar",1000)
pick_box = create_product ("Pick box", 5)
guitar_strings = create_product ("Guitar strings",10)
insurance = create_product ("Insurance",5)
priority_mail = create_product ("Priority mail",10)
cart = [guitar,insurance,priority_mail,insurance, priority_mail]
print_cart(cart)
#cart_2= add_to_inventory (inventory_1,cart_2)
#inventory = [
# {"name": "Guitar",
# "price": 1000},
# {"name": "Pick box",
# "price": 5},
# {"name": "Guitar strings",
# "price": 10}
# ] |
var=[40,12,60,70,4,11]
z=var[0]
for x in var:
if z > x :
z=x
print('The string is var:', z)
|
import matplotlib.pyplot as plt
from pandas import read_csv
import os
# Load data
data_path = os.path.join(os.getcwd(), "data/blood-pressure.txt")
dataset = read_csv(data_path, delim_whitespace=True)
# We have 30 entries in our dataset and four features. The first feature is the ID of the entry.
# The second feature is always 1. The third feature is the age and the last feature is the blood pressure.
# We will now drop the ID and One feature for now, as this is not important.
dataset = dataset.drop(['ID', 'One'], axis=1)
# And we will display this graph
# %matplotlib inline
dataset.plot.scatter(x='Age', y='Pressure')
# Now, we will assume that we already know the hypothesis and it looks like a straight line
h = lambda x: 84 + 1.24 * x
# Let's add this line on the chart now
ages = range(18, 85)
estimated = []
for i in ages:
estimated.append(h(i))
plt.plot(ages, estimated, 'b')
plt.show() |
import pandas as pd
# Define function for cleaning dataframe
def clean_lineups(df):
"""Removes the posistions from each of the lineups dataframes in order to better combine with the names from the batting/pitching stats
dataframes"""
positions = ['1','2','3','4','5','6','7','8','9']
pos_count = 0
for row in positions:
# New data frame with split value columns
new = df[positions[pos_count]].str.split("-", n = 1, expand = True)
# Making separate name column from new data frame
df[positions[pos_count]] = new[0]
# Making separate position column from new data frame
df["Position"]= new[1]
df.drop(columns = 'Position')
pos_count += 1
# Define function for cleaning Game column
def clean_game_column(df):
"""Takes the 'Game' column in the lineups dataframe and splits teh date to make it easier to read and removes the final score"""
new = df['0'].str.split(" ", n = 5, expand = True)
df['Game Date'] = new[1]
df['Opponent'] = new[3]
df['Win Loss'] = new[4]
new_date = df['Game Date'].str.split('/', n = 1, expand = True)
df['Month'] = new_date[0]
df['Date'] = new_date[1]
new_month = df['Month'].str[3]
df['Month'] = new_month |
i=0
while i<10:
if i%2==0:
i=i+1
continue
else:
print(i)
i=i+1: |
import random
correct = 'you guessed correctly!'
too_low = 'too low'
too_high = 'too high'
min_range = 1
max_range = 100
def configure_range():
'''Set the high and low values for the random number'''
while True:
try:
low = 0
while low <= min_range or low >= max_range:
low = int(input("Enter low end of guessing range. Must be > {} and < {} \n".format(min_range, max_range)))
break
except ValueError:
print("Did you enter a number?")
while True:
try:
high = 0
while high >= 100 or high <= low:
high = int(input("Enter high end of guessing range. must be > {} and < {} \n".format(low, max_range)))
break
except ValueError:
print("Did you enter a number?")
return low, high
def generate_secret(low, high):
'''Generate a secret number for the user to guess'''
return random.randint(low, high)
def get_guess():
'''get user's guess'''
return int(input('Guess the secret number? '))
def check_guess(guess, secret):
'''compare guess and secret, return string describing result of comparison'''
if guess == secret:
return correct
if guess < secret:
return too_low
if guess > secret:
return too_high
def main():
#variable to track number of guesses made
numOfGuesses = 0
(low, high) = configure_range()
secret = generate_secret(low, high)
while True:
#add one every time a guess is made to track guesses
numOfGuesses += 1
guess = get_guess()
result = check_guess(guess, secret)
print(result)
#print number of guesses
print('You have guessed ' + str(numOfGuesses) + ' times')
if result == correct:
break
if __name__ == '__main__':
option = input("\nPress Any Key To Start. Press Q To Quit.\n")
while option.lower() != "q":
main()
menu = input("\nPlay Game? Press any Key. Press Q to Quit.\n")
exit()
|
times = input("How many times do I have to tell you?")
times = int(times)
for times in range(times):
print(f"time {times + 1}: CLEAN UP YOUR ROOM!!!") |
#String Formatting
name = "John"
age = 23
print("%s is %d years old." % (name, age))
print ("%f" % age) |
import re
import sys
def load_file(filepath):
with open(filepath, "r", encoding="utf-8") as file:
# first line is text
text = file.readline().strip()
# second line is word bank
word_bank = file.readline().strip().split(" ")
return text, word_bank
def cut_words(text):
"""
cut text into words and non-words (delimiters + non-words before and after every word)
search for words and save them, everything before and after those gets saved to non_words
"""
# add first empty string, so that after every word there comes a non_word -> easier to loop through
words = [""]
non_words = []
# gets shorter with every search
current_text = text
# find underlines or word chars
match = re.search(r"(_|\w)+", current_text)
# when there isn't a single word in the text
if match is None:
raise ValueError("No word found!")
while match:
# beginning index of word
start = match.span(0)[0]
# index directly after end of word
end = match.span(0)[1]
# non_word is part before word
non_words.append(current_text[0:start])
# word itself
words.append(current_text[start:end])
# remove just saved separator and word from current_text
current_text = current_text[end:]
# search for another word
match = re.search(r"(_|\w)+", current_text)
# save chars after last word as separator
non_words.append(current_text)
return words, non_words
def does_match(word, possible_replacement):
"""
is possible_replacement able to replace incomplete_word?
"""
# does the length match?
if len(word) != len(possible_replacement):
return False
# check every character
for char_word, char_replacement in zip(word, possible_replacement):
# when the current char in the replacement word is not unknown (isn't "_"),
# it has to match with the current char of the word otherwise there is no chance of replaceability
if char_word != "_" and char_word.upper() != char_replacement.upper():
return False
return True
def find_replacements(word, word_bank):
"""
find every word from the word bank that could replace the word
"""
# indices of possible replacements
replacement_indices = []
# search through every word from the word bank
for word_idx, possible_replacement in enumerate(word_bank):
# when the current word can be used as a replacement
if does_match(word, possible_replacement):
# save replacement index
replacement_indices.append(word_idx)
return replacement_indices
def replace_incomplete_words(words, word_bank):
"""
recursive function
take incomplete words and a word bank and replace every word with a suitable replacement from the word bank
"""
# there are no words left to be replaced -> break recursion
if len(words) == 0:
return []
# result words
result = []
# no blanks in the current word -> word is already complete
if "_" not in words[0]:
following_replacements = replace_incomplete_words(words[1:], word_bank)
# when a solution (for every following word) can be found
if following_replacements is not None:
# save the word itself, and the following replacements
result = [words[0]] + following_replacements
hit = True
else:
hit = False
else:
# find replacements for the first word
replacement_indices = find_replacements(words[0], word_bank)
# True when at least one of the replacements doesn't produce any problems with the following words
hit = False
for replacement_idx in replacement_indices:
# copy word bank so that the original list doesn't get altered
current_word_bank = word_bank.copy()
# save found replacement and remove it from the current bank
replacement = current_word_bank.pop(replacement_idx)
# execute this function without the first word and without the used replacement from the bank
following_replacements = replace_incomplete_words(words[1:], current_word_bank)
# when a solution (for every following word) with the used replacement can be found, break and return result
if following_replacements is not None:
result = [replacement] + following_replacements
hit = True
break
if hit:
return result
else:
# no solution can be found, even if there might be a suitable replacement for the first word
return None
def main():
if len(sys.argv) != 2:
raise ValueError("Specify filepath of the input file!")
text, word_bank = load_file(sys.argv[1])
words, non_words = cut_words(text)
words = replace_incomplete_words(words, word_bank)
if words is None:
print("No solution could be found!")
else:
# print result, one word always comes before a separator
for word, separator in zip(words, non_words):
print(word, separator, sep="", end="")
if __name__ == "__main__":
main()
|
import re
import sys
class Student:
"""
representing a single student with references to their wished packages
"""
def __init__(self, number, wishes):
self.number = number
# tuple with one package number per wish (1st wish, 2nd wish...)
self.wishes = wishes
def __repr__(self):
return f"id: {self.number}; wishes: {self.wishes}"
class Package:
"""
representing a single package with references to all the students wanting this package
"""
def __init__(self, number, wishers):
self.number = number
# tuple with one list per wish (1st wish, 2nd wish...) with all the students (wishers) wanting this package
self.wishers = wishers
def __repr__(self):
return f"id: {self.number}; wishers: {self.wishers}"
class Selection:
"""
containing all the students and packages
methods can assign students to packages in three different ways:
1. assign_all_cleanly:
try to assign packages that are only wanted by a single student
-> no package gets taken away from a different student wanting it the same way or more
2. assign_all_uncleanly:
assign students to packages with taking packages away from students wanting it the same way
leaving only completely unwanted packages
3. assign_all_dirtily:
assign packages to students, including completely unwanted packages
no packages or student stays unassigned
"""
def __init__(self, students, packages):
if len(students) != len(packages):
raise ValueError("The amount of students doesn't match the amount of packages!")
# key: student number, value: Student instance
self.students = students
# key: package number, value: Package instance
self.packages = packages
# key: package number, value: student number
self.assigned_students = {}
self.amount_wishes = len(self.students[1].wishes)
def __repr__(self):
return f"{len(self.students)} students with {self.amount_wishes} wishes each; " \
f"{len(self.assigned_students)} students already have a package assigned to them"
def get_unassigned_wishers(self, package_number, wish_id):
"""
get all the students wanting this package (according to wish_id) that aren't assigned yet
"""
# get Package object
package = self.packages[package_number]
# get all students having this package as their wish (according to wish_id) that aren't assigned
return [wisher for wisher in package.wishers[wish_id] if wisher not in self.assigned_students.keys()]
def assign(self, student_number, package_number):
"""
assign student to package
"""
if student_number in self.assigned_students.keys() or package_number in self.assigned_students.values():
raise ValueError("Trying to assign an already assigned student or an already assigned package!")
self.assigned_students[student_number] = package_number
def assign_package_if_possible(self, package_number, wish_id):
"""
recursive function (calling resolve_after_assignment)
see if this package is only wanted by one student (according to wish_id)
and then assign it
return True when this is a package wanted by multiple students, else False
"""
# get unassigned wishers
unassigned_wishers = self.get_unassigned_wishers(package_number, wish_id)
# when only a single student wants this package, they get it
if len(unassigned_wishers) == 1:
this_student_number = unassigned_wishers[0]
# assign this student to the wanted package if they aren't assigned yet
if this_student_number not in self.assigned_students.keys():
self.assign(this_student_number, package_number)
# see if that assignment resolved a problem with a more important wish
# <- one student less to find a package for
self.resolve_after_assignment(this_student_number, wish_id - 1)
# when this package is wanted by multiple students
elif len(self.packages[package_number].wishers[wish_id]) > 1:
return True
return False
def resolve_after_assignment(self, student_number, wish_id):
"""
recursive function (calling itself and assign_package_if_possible)
see if an assignment (student_number got assigned) resolved a problem with a more important wish (wish_id)
"""
# when this wish doesn't exists
if wish_id < 0:
return
# now this package has one student less wanting it
package_number = self.students[student_number].wishes[wish_id]
# when this package is not assigned yet
if package_number not in self.assigned_students.values():
# see if it can be assigned -> resolve even more problems if possible
self.assign_package_if_possible(package_number, wish_id)
# do the same with the next more important wish
self.resolve_after_assignment(student_number, wish_id - 1)
def assign_packages(self, wish_id, disallowed_packages):
"""
(cleanly) assign all packages that are wanted by only one student (according to wish_id)
and check if that assignment solved a problem with a more important wish
return all the packages that are wanted by multiple students
"""
# numbers of all packages wanted by multiple students
highly_wanted_package = []
for package_number in self.packages.keys():
# don't try to assign this package if it is disallowed or already assigned
if package_number not in disallowed_packages and package_number not in self.assigned_students.values():
# assign if possible
is_highly_wanted = self.assign_package_if_possible(package_number, wish_id)
# add this package if it is highly wanted
if is_highly_wanted:
highly_wanted_package.append(package_number)
return highly_wanted_package
def assign_all_cleanly(self):
"""
try to assign packages that are only wanted by a single student
-> no package gets taken away from a different student wanting it the same way or more
"""
# these packages are wanted so much that less relevant wishes can't be used to assign it
highly_wanted_packages = []
for wish_id in range(self.amount_wishes):
# assign everything possible for this wish_id
# and try to resolve as many problems in more important wishes as possible
highly_wanted_packages += self.assign_packages(wish_id, highly_wanted_packages)
def assign_all_uncleanly(self):
"""
go through all wishes and just assign the first student with their wished package
-> other students wanting this package in the same way won't get it
"""
# go through all unassigned students
for wish_id in range(self.amount_wishes):
for student_number in self.students.keys():
if student_number in self.assigned_students.keys():
# this student is already assigned
continue
wished_package = self.students[student_number].wishes[wish_id]
# just assign it if the package is not assigned yet
if wished_package not in self.assigned_students.values():
self.assign(student_number, wished_package)
def assign_all_dirtily(self):
"""
go through all unassigned students and unassigned packages and just assign with no regard to their wishes
should only be used when there are only unwanted packages left to be assigned
"""
# get all unassigned packages
unassigned_package_numbers = [package_number for package_number in self.packages.keys()
if package_number not in self.assigned_students.values()]
for wish_id in range(self.amount_wishes):
for student_number in self.students.keys():
if student_number not in self.assigned_students.keys():
# just take and delete the last unassigned package number and assign it
self.assign(student_number, unassigned_package_numbers.pop())
def load_file(filepath):
with open(filepath, "r", encoding="utf-8") as file:
lines = [line.strip() for line in file]
# the first line only contains the amount of students, which won't be used
return lines[1:]
def load_students_and_packages(lines):
"""
get lines read from the file and create a Selection object
"""
# get the amount of wishes every student has
wishes_amount = len(re.split(r"[\W]+", lines[0]))
# key: package number, value: Package instance
# fill it with no student wanting any packages
packages = {number: Package(number, tuple([] for _ in range(wishes_amount))) for number in range(1, len(lines) + 1)}
# key: student number, value: Student instance
students = {}
for student_idx, line in enumerate(lines):
"""
fill students
"""
# split line into words
wishes = tuple(int(package_number) for package_number in re.split(r"[\W]+", line))
# create Student instance and add to dict
student = Student(student_idx + 1, wishes)
students[student.number] = student
"""
fill packages
"""
# go through every wished package
for wish_idx, package_number in enumerate(student.wishes):
# append student number to the wished-by-list
packages[package_number].wishers[wish_idx].append(student.number)
return Selection(students, packages)
def main():
if len(sys.argv) != 2:
raise ValueError("Specify filepath of the input file!")
# load students and packages form file
lines = load_file(sys.argv[1])
selection = load_students_and_packages(lines)
# assign all packages and students
selection.assign_all_cleanly()
selection.assign_all_uncleanly()
selection.assign_all_dirtily()
# print results
print("student number, [wishes], assigned package")
for student_number in selection.students:
# convert this student's wishes into a usable string
wishes = [str(wish) for wish in selection.students[student_number].wishes]
wishes_string = "\t".join(wishes)
# get the package that got assigned to this student
assigned_package = selection.assigned_students[student_number]
print(f"{student_number}\t\t{wishes_string}\t\t{assigned_package}")
if __name__ == "__main__":
main()
|
from typing import Iterable, List, Tuple
FORMAT = """
followed: {}
navigated: {}
"""
def solve(instream):
instructions = read(instream)
return manhattan(follow(instructions)), manhattan(navigate(instructions))
def read(source: Iterable[str]) -> List[Tuple[str, int]]:
return [(arg[0], int(arg[1:])) for arg in source]
# use complex numbers of x+yj as 2D coordinates
NORTH = 1j
SOUTH = -1j
EAST = 1+0j
WEST = -1+0j
# rotations
ROT = {0: 1, 90: 1j, 180: -1, 270: -1j}
def manhattan(position: complex) -> int:
return int(abs(position.real) + abs(position.imag))
def follow(instructions: List[Tuple[str, int]]) -> complex:
position, orientation = 0j, EAST
for op, arg in instructions:
if op == 'N':
position += NORTH * arg
elif op == 'S':
position += SOUTH * arg
elif op == 'E':
position += EAST * arg
elif op == 'W':
position += WEST * arg
elif op == 'F':
position += orientation * arg
elif op == 'L':
orientation *= ROT[arg % 360]
elif op == 'R':
orientation *= ROT[-arg % 360]
else:
raise ValueError(f"Unknown operation: {op!r}")
return position
def navigate(instructions: List[Tuple[str, int]]) -> complex:
position, waypoint = 0j, NORTH + 10 * EAST
for op, arg in instructions:
if op == 'N':
waypoint += NORTH * arg
elif op == 'S':
waypoint += SOUTH * arg
elif op == 'E':
waypoint += EAST * arg
elif op == 'W':
waypoint += WEST * arg
elif op == 'F':
position += waypoint * arg
elif op == 'L':
waypoint *= ROT[arg % 360]
elif op == 'R':
waypoint *= ROT[-arg % 360]
else:
raise ValueError(f"Unknown operation: {op!r}")
return position
|
n=input()
sum=0
for i in str(n):
x=int(i)
sum=sum+(x*x)
print sum
|
number=int(raw_input())
sum=0
for i in range(number+1):
sum+=i
print sum
|
# Define your "TreeNode" Python class below
class TreeNode:
def __init__(self, value):
self.value = value
self.children = []
def add_child(self, child_node):
print("Adding " + child_node.value)
self.children.append(child_node)
root = TreeNode("I am Root")
child = TreeNode("A wee sappling")
root.add_child(child) |
class MinHeap:
def __init__(self):
self.heap_list = [None]
self.count = 0
# HEAP HELPER METHODS
# DO NOT CHANGE!
def parent_idx(self, idx):
return idx // 2
def left_child_idx(self, idx):
return idx * 2
def right_child_idx(self, idx):
return idx * 2 + 1
# END OF HEAP HELPER METHODS
def add(self, element):
self.count += 1
print("Adding: {0} to {1}".format(element, self.heap_list))
self.heap_list.append(element)
self.heapify_up()
def heapify_up(self):
print("Heapifying up")
idx = self.count
while self.parent_idx(idx) > 0:
child = self.heap_list[idx]
parent = self.heap_list[self.parent_idx(idx)]
if parent > child:
print("swapping {0} with {1}".format(parent, child))
self.heap_list[idx] = parent
self.heap_list[self.parent_idx(idx)] = child
idx = self.parent_idx(idx)
print("Heap Restored {0}".format(self.heap_list))
|
# TODO
# input: total, per_page, page
# output:
# a range of item numbers to display for each page (showing 1-10, 10-20, ..etc)
# has next method (whether the next page exists)
# has previous method (whether the previous page exists)
import math
from math import ceil
class Pagination():
def __init__(self, total, per_page, page):
self.total = total
self.per_page = per_page
self.num_pages = int(ceil(self.total/self.per_page))
self.page = page
self.from_item = (self.page -1)*self.per_page + 1
self.to_item = min(self.page*self.per_page, self.total)
self.pagediv = int(ceil(self.page/5))
self.from_page = (self.pagediv -1)*5 + 1
self.to_page = min(self.pagediv*5, self.num_pages)
# # has next
def has_next(self):
return self.page < self.num_pages
# # has_previous
def has_previous(self):
return self.page > 1
# How to use:
# p= Pagination(0, 6, 1)
# print("num_pages = {0}".format(p.num_pages))
# print("\n")
# print("from_item = {0}".format(p.from_item))
# print("to_item = {0}".format(p.to_item))
# print("\n")
# print(p.has_next())
# print(p.has_previous())
# print("\n")
# print("from_page = {0}".format(p.from_page))
# print("to_page = {0}".format(p.to_page))
# print("pagediv = {0}".format(p.pagediv))
|
import random
import re
class GameDie:
@classmethod
def roll(cls, name, args: tuple):
if len(args) == 0:
count = 1
sides = 20
elif len(args) == 1:
count, sides = cls.parse_dice(args[0])
else:
return "Sorry, combining dice is not implemented yet." # TODO eventually if I ever need it
rolls = []
for i in range(count):
rolls.append(random.randint(1, sides))
text = '{0} rolled a :game_die: **{1}**!'.format(name, sum(rolls))
if count > 1:
text = text + " All rolls: " + " ".join([":game_die:{0}".format(roll) for roll in rolls])
return text
@staticmethod
def parse_dice(arg):
""" Parse strings like "2d6" or "1d20" and roll accordingly """
pattern = re.compile(r'^(?P<count>[0-9]*d)?(?P<sides>[0-9]+)$')
match = re.match(pattern, arg)
if not match:
raise ValueError() # invalid input string
sides = int(match.group('sides'))
try:
count = int(match.group('count')[:-1])
except (TypeError, ValueError):
count = 1
return count, sides
|
print ("____________________")
print ("Rock, Paper, Scissors, account setup")
print ("____________________")
while True:
username = raw_input ("Pick a username: ")
password = raw_input ("Pick a password: ")
password_confirm = raw_input ("please confirm your password: ")
if password != password_confirm:
print ("your passwords don't match, please try again.")
if password == password_confirm:
print ("your account has been set up.")
text_file = open("accounts.txt", "a")
text_file.write("\n")
text_file.write(username)
text_file.write("\n")
text_file.write(password)
text_file.close()
break
|
def validate_tiny_int(val):
return val >= 0 and val <= 255
def validate_val(val):
try:
return isinstance(int(val),int)#aca valida si es una instancia de la clase int
#en python todo es un objeto
#se intenta convertir un string a entero con int(val)
except ValueError as error:
return False |
'''
什么是队列,队列是一系列元素的集合,新元素的加入在队列的一端,这一端叫做“队尾(rear)”
已有元素的移除发生在队列的另一端,叫做“队首(front)”
---------------------------------------------
rear front
---------------------------------------------
特点:先进先出(FIFO)
抽象数据类型(ADT)
Queue():创建一个空队列对象,无需参数,返回空的队列
enqueue(item):将数据项添加到队尾,有参数,无返回值
dequeue(): 从对首移出数据项,无需参数,返回值为队首数据项
isEmpty():测试队列是否为空,无需参数,返回值为布尔值
size():返回队列中的数据项的个数,无需参数
'''
# class Queue():
# def __init__(self):
# self.items = []
# def enqueue(self,item):
# self.items.insert(0,item)
# def dequeue(self):
# return self.items.pop()
# def isEmpty(self):
# return self.items == []
# def size(self):
# return len(self.items)
# q = Queue()
# q.enqueue("a")
# q.enqueue("b")
# q.enqueue("c")
# print(q.size())
# print(q.dequeue())
# print(q.size())
'''
马铃薯游戏(击鼓传花)选定一个人作为开始的人,数到num个人,将此人淘汰
['零','一','二','三','四','五','六','七','八','九'] 七
['八','九','零','一','二','三','四','五','六'] 五
['六','八','九','零','一','二','三','四'] 四
['六','八','九','零','一','二','三'] 六
['八','九','零','一','二','三'] 九
['零','一','二','三','八'] 二
['三','八','零','一',] 一
['三','八','零'] 八
['零','三'] 三
['零']
'''
from pythonds.basic.queue import Queue
name_list = ['零','一','二','三','四','五','六','七','八','九']
num = 7
def send_flowers(name_list,num):
simaueue = Queue()
for name in name_list:
simaueue.enqueue(name)
while simaueue.size()>1:
for i in range(num):
simaueue.enqueue(simaueue.dequeue())
print(simaueue.dequeue())
return simaueue.dequeue()
send_flowers(name_list,num)
|
class TitleToNumber(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
slist = list(s)
l = len(s)
num = 0
for a in slist:
num *= 26
num += ord(a) - 64
return num
if __name__ == '__main__':
s = 'AZ'
solution = TitleToNumber()
print solution.titleToNumber(s) |
class IntersectionOfTwoArrays(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
s1 = set(nums1)
s2 = set(nums2)
ss = s1 & s2
return list(ss)
if __name__ == '__main__':
nums1 = [1, 2, 2, 1]
nums2 = [2, 2]
solution = IntersectionOfTwoArrays()
print solution.intersection(nums1, nums2)
|
class Fib(object):
def __init__(self):
self.a=0
self.b=1
def __str__(self):
return str(self.a)
__repr__ = __str__
def __iter__(self):
return self
def __next__(self):
self.a, self.b = self.b, self.a + self.b # 计算下一个值
return self.a # 返回下一个值
def __getitem__(self, n):
a,b=1,1
if isinstance(n,int):
for x in range(n):
a,b=b,a+b
return a
if isinstance(n, slice):
start = n.start
stop = n.stop
if start is None:
start = 0
L = []
for x in range(stop):
if x >= start:
L.append(a)
a, b = b, a + b
return L
def __call__(self, *args, **kwargs):
print(self)
fib = Fib()
for i in range(10):
print(fib[i])
fib = Fib()
for i in fib:
print(i)
if(i>10000):
break
print(fib[:10])
fib() |
dl320@soetcse:~/udaya$ python3 add6.py
enter the value of a56
enter the value of b65
enter the value of c67
c is greater than b
dl320@soetcse:~/udaya$ python3 add6.py
enter the value of a01
enter the value of b69
enter the value of c96
c is greater than b
dl320@soetcse:~/udaya$ python3 add6.py
enter the value of a87
enter the value of b87
enter the value of c98
c is greater than b
dl320@soetcse:~/udaya$ python3 add8.py
0
1
a is even number
2
3
a is even number
4
5
a is even number
6
7
a is even number
8
9
a is even number
10
11
a is even number
12
13
a is even number
14
15
a is even number
16
17
a is even number
18
19
a is even number
20
21
a is even number
22
23
a is even number
24
25
a is even number
26
27
a is even number
28
29
a is even number
30
31
a is even number
32
33
a is even number
34
35
a is even number
36
37
a is even number
38
39
a is even number
40
41
a is even number
42
43
a is even number
44
45
a is even number
46
47
a is even number
48
49
a is even number
50
51
a is even number
52
53
a is even number
54
55
a is even number
56
57
a is even number
58
59
a is even number
60
61
a is even number
62
63
a is even number
64
65
a is even number
66
67
a is even number
68
69
a is even number
70
71
a is even number
72
73
a is even number
74
75
a is even number
76
77
a is even number
78
79
a is even number
80
81
a is even number
82
83
a is even number
84
85
a is even number
86
87
a is even number
88
89
a is even number
90
91
a is even number
92
93
a is even number
94
95
a is even number
96
97
a is even number
98
99
a is even number
100
101
a is even number
102
103
a is even number
104
105
a is even number
106
107
a is even number
108
109
a is even number
110
111
a is even number
112
113
a is even number
114
115
a is even number
116
117
a is even number
118
119
a is even number
120
121
a is even number
122
123
a is even number
124
125
a is even number
126
127
a is even number
128
129
a is even number
130
131
a is even number
132
133
a is even number
134
135
a is even number
136
137
a is even number
138
139
a is even number
140
141
a is even number
142
143
a is even number
144
145
a is even number
146
147
a is even number
148
149
a is even number
150
151
a is even number
152
153
a is even number
154
155
a is even number
156
157
a is even number
158
159
a is even number
160
161
a is even number
162
163
a is even number
164
165
a is even number
166
167
a is even number
168
169
a is even number
170
171
a is even number
172
173
a is even number
174
175
a is even number
176
177
a is even number
178
179
a is even number
180
181
a is even number
182
183
a is even number
184
185
a is even number
186
187
a is even number
188
189
a is even number
190
191
a is even number
192
193
a is even number
194
195
a is even number
196
197
a is even number
198
199
a is even number
200
201
a is even number
202
203
a is even number
204
205
a is even number
206
207
a is even number
208
209
a is even number
210
211
a is even number
212
213
a is even number
214
215
a is even number
216
217
a is even number
218
219
a is even number
220
221
a is even number
222
223
a is even number
224
225
a is even number
226
227
a is even number
228
229
a is even number
230
231
a is even number
232
233
a is even number
234
235
a is even number
236
237
a is even number
238
239
a is even number
240
241
a is even number
242
243
a is even number
244
245
a is even number
246
247
a is even number
248
249
a is even number
250
a is odd number
dl320@soetcse:~/udaya$ python3 add9.py
29
dl320@soetcse:~/udaya$ python3 add9.py
26
dl320@soetcse:~/udaya$ python3 add9.py
29
dl320@soetcse:~/udaya$ ^C
dl320@soetcse:~/udaya$ python3 add9.py
31
dl320@soetcse:~/udaya$ python3 add9.py
34
dl320@soetcse:~/udaya$ python3 add9.py
27
dl320@soetcse:~/udaya$ python3 add9.py
27
dl320@soetcse:~/udaya$ python3 add9.py
33
dl320@soetcse:~/udaya$ python3 add9.py
33
dl320@soetcse:~/udaya$ python3 add9.py
31
dl320@soetcse:~/udaya$ python3 add8.py
dl320@soetcse:~/udaya$ python3 add9.py
27
dl320@soetcse:~/udaya$ python3 add9.py
34
dl320@soetcse:~/udaya$ python3 add9.py
29
dl320@soetcse:~/udaya$ python3 add9.py
28
dl320@soetcse:~/udaya$ python3 add9.py
31
dl320@soetcse:~/udaya$ python3 add9.py
25
dl320@soetcse:~/udaya$
dl320@soetcse:~/udaya$ python3 add9.py
31
dl320@soetcse:~/udaya$ python3 add9.py
12
dl320@soetcse:~/udaya$ python3 add9.py
1
dl320@soetcse:~/udaya$ mkdir udaya
dl320@soetcse:~/udaya$ python3 add9.py
12
dl320@soetcse:~/udaya$ python3 add9.py
9
dl320@soetcse:~/udaya$ python3 add9.py
15
dl320@soetcse:~/udaya$ python3 add9.py
18
dl320@soetcse:~/udaya$ python3 add9.py
13
dl320@soetcse:~/udaya$ python3 add9.py
13
dl320@soetcse:~/udaya$ python3 add9.py
11
dl320@soetcse:~/udaya$ python3 add9.py
6
dl320@soetcse:~/udaya$ python3 add9.py
12
dl320@soetcse:~/udaya$ python3 add9.py
20
dl320@soetcse:~/udaya$ python3 add9.py
dl320@soetcse:~/udaya$ python3 add10.py
enter q to quit and r to roll the diser
6
dl320@soetcse:~/udaya$ python3 add10.py
enter q to quit and r to roll the diseq
bye
dl320@soetcse:~/udaya$ python3 add10.py
enter q to quit and r to roll the diser
6
dl320@soetcse:~/udaya$ python3 add10.py
enter q to quit and r to roll the diser
6
dl320@soetcse:~/udaya$ python3 add10.py
enter q to quit and r to roll the diseq
bye
dl320@soetcse:~/udaya$ python3 add10.py
enter q to quit and r to roll the diser
4
dl320@soetcse:~/udaya$ python3 add10.py
enter q to quit and r to roll the diser
3
dl320@soetcse:~/udaya$ python3 add10.py
enter q to quit and r to roll the diseq
bye
dl320@soetcse:~/udaya$ python3 add10.py
enter q to quit and r to roll the diser
4
|
def fibonacci(n):
fib_n = [0, 1]
for i in range(2, n + 1):
fib_n[0], fib_n[1] = fib_n[1], fib_n[0] + fib_n[1]
return fib_n[1]
n = int(input())
print(fibonacci(n))
|
import sqlite3
# conectando...
conn = sqlite3.connect('clientes.db')
# definindo um cursor
cursor = conn.cursor()
# criando a tabela (schema)
cursor.execute("""CREATE TABLE IF NOT EXISTS clientes (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
nome TEXT NOT NULL,
idade INTEGER,
cpf VARCHAR(11) NOT NULL,
email TEXT NOT NULL,
fone TEXT,
cidade TEXT,
uf VARCHAR(2) NOT NULL);""")
##################################################
reg = 'S'
while reg == 'S':
reg = input('Cadastrar um novo cliente? [S/N] ').strip().upper()
while reg not in 'sSnN':
reg = input('Cadastrar um novo cliente? [S/N] ').strip().upper()
if reg == 'S':
# solicitando os dados ao usuário
p_nome = input('Nome: ')
p_idade = input('Idade: ')
p_cpf = input('CPF: ')
p_email = input('Email: ')
p_fone = input('Fone: ')
p_cidade = input('Cidade: ')
p_uf = input('UF: ')
# inserindo dados na tabela
cursor.execute("""INSERT INTO clientes (nome, idade, cpf, email, fone, cidade, uf)
VALUES (?,?,?,?,?,?,?)""", (p_nome, p_idade, p_cpf, p_email, p_fone, p_cidade, p_uf))
conn.commit()
print('Dados inseridos com sucesso.')
print('<>' * 30)
else:
break
##################################################
# lendo os dados
print('\nOs dados salvos na base de dados são:')
cursor.execute("""
SELECT * FROM clientes;
""")
for linha in cursor.fetchall():
print(linha)
##################################################
# desconectando...
conn.close()
|
import os
def treewalk(root, nspaces=0):
# nspaces : aantal spaties dat ingesprongen wordt
a = os.listdir(root)
for f in a:
print(' '*nspaces,end = '')
if os.path.isdir(root + '/' + f):
print('[' + f + ']')
treewalk(root + '/' + f,nspaces+3) # recursieve aanroep
else:
print(f)
root = os.getcwd()
treewalk(root + '/../..') |
a = [1,99,2,98,3,97]
print(a[-1])
print(a[-3])
print()
a1 = [1,2,3]
a2 = [101,102,103]
print(a1+a2)
print()
a1 = [1,2,3]
a2 = [101,102,103]
print(4*a1)
print(a2*3)
print()
n = 25
b = [0]*n
print(b)
print()
a = [1,2,3,4,5,6,7,8]
del a[6] ; print(a) # verwijder het zevende element
del a[1:3] ; print(a) # verwijder het 2e en het 3e element
del a[:2] ; print(a) # verwijder de eerste twee elementen
del a[1:] ; print(a) # verwijder alle elementen behalve het eerste element
del a[:] ; print(a) # verwijder alle elementen
print()
a = [1,2,3,2,1] ; print(a)
a.remove(2) ; print(a) # alternatief:
# del a[b.index(2)]
print()
a = [1,2,3,2,1,2,3,2,1] ; print(a)
while 2 in a:
a.remove(2) ; print(a)
print()
a = [1,2,3,4,5,6,7,8] ; print(a)
a[2] = 99 ; print(a)
print()
a = [1,2,3,4,5,6,7,8] ; print(a)
a[1:3] = [88] ; print(a) # a[1:3] = 88 niet toegestaan
a[1:3] = [77,177,277] ; print(a)
a[2:5]= [] ; print(a)
print()
a = [1, 1, 1, 1] ; print(a)
a.insert(0,6) ; print(a) # voor de lijst plaatsen
a.insert(3,7) ; print(a) # toevoegen voor het element met positie 3
a.insert(len(a),8) ; print(a) # achter de lijst plaatsen
a.append(8) ; print(a) # methode 2
a = a + [8] ; print(a) # methode 3
print()
a = [1, 1, 1, 1] ; print(a)
a[:0] = [6,66] ; print(a) # voor de lijst plaatsen
a[4:4] = [7,77] ; print(a) # toevoegen voor het element met positie 3
a[len(a):] = [8,88] ; print(a) # achter de lijst plaatsen
a.extend([8,88]) ; print(a) # methode 2
a = a + [8,88] ; print(a) # methode 3
print()
print(min([6,3,5,9]))
print(min('noot','aap','mies'))
print(min('102','13'))
print()
a = [1,-2,3,-4,1,-2,3,-4] ; print(a)
a.sort() ; print(a)
a.sort(reverse = True) ; print(a)
a.reverse() ; print(a)
i = a.pop() ; print('na pop-aanroep: i:',i,'a:',a)
i = a.pop(2) ; print('na pop(2)-aanroep: i:',i,'a:',a)
print(a.count(-4))
print(a.index(1))
print()
|
class myqueue(list):
def __init__(self,a=[]):
list.__init__(self,a)
def dequeue(self):
return self.pop(0)
def enqueue(self,x):
self.append(x)
class Vertex:
def __init__(self, data):
self.data = data
def __repr__(self): # voor afdrukken
return str(self.data)
def __lt__(self, other): # voor sorteren
return self.data < other.data
import math
INFINITY = math.inf
def vertices(G):
return sorted(G.keys())
def edges(G):
a = []
for u in vertices(G):
for v in G[u].keys():
a.append((u,v,G[u][v]))
a.sort()
return a
v = [Vertex(i) for i in range(7)]
v = [Vertex(i) for i in list('abcdefg')]
G = {v[0]:{v[1]:72,v[4]:31,v[6]:84},
v[1]:{v[0]:72,v[2]:19,v[4]:25},
v[2]:{v[1]:19,v[3]:72,v[4]:22},
v[3]:{v[2]:72,v[5]:38},
v[4]:{v[0]:31,v[1]:25,v[2]:22,v[5]:45,v[6]:16},
v[5]:{v[3]:38,v[4]:45},
v[6]:{v[0]:84,v[4]:16}}
print("vertices(G):",vertices(G))
print("edges(G):",edges(G))
def clear(G):
for v in vertices(G):
k = [e for e in vars(v) if e != 'data']
for e in k:
delattr(v,e)
def MST_Prim(G,s):
Q = vertices(G)
for v in Q:
v.key = INFINITY
v.predecessor = None
s.key = 0
while Q:
# print([(q,q.key) for q in Q])
u = min(Q,key=lambda x: x.key)
Q.remove(u)
for v in G[u].keys():
if v in Q and G[u][v] < v.key:
v.predecessor = u
v.key = G[u][v]
MST_Prim(G,v[0])
def tree_edges(G):
a = []
for v in vertices(G):
if hasattr(v,'predecessor') and v.predecessor != None:
a.append((v,v.predecessor,G[v][v.predecessor]))
a.append((v.predecessor,v,G[v.predecessor][v]))
a.sort()
return a
print('tree_edges(G):',tree_edges(G))
print([(v,v.key) for v in vertices(G)])
print(sum([v.key for v in vertices(G)]))
|
"""
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
"""
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 动态规划
sums = 0
max_sum = nums[0] #储存当前的最大和
for i in range(len(nums)):
max_sum = max(sums+nums[i], max_sum) # 倘若子数组和大于当前最大和,则替换
sums = max(sums + nums[i], 0) # 倘若子数组和小于0,则舍去
return max_sum
"""
思路:采用动态规划,当子数组和小于0时,这部分和对于最大和来说不应该有贡献,因此需舍去。(分治法还没搞懂...)
"""
|
def get(a,l,r):
# 递归(分治法)
if l==r:
return {'isum':a[l],'lsum':a[l],'rsum':a[l],'msum':a[l]}
m = int((l+r)/2)
isum = get(a,l,m)['isum'] + get(a,m+1,r)['isum'] # isum为[l,r]的区间和
# lsum为[l,r]内以l为左端点的最大子段和
lsum = max(get(a,l,m)['lsum'] , get(a,l,m)['isum'] + get(a,m+1,r)['lsum'])
# rsum为[l,r]内以r为右端点的最大子段和
rsum = max(get(a,m+1,r)['rsum'] , get(a,m+1,r)['isum'] + get(a,l,m)['rsum'])
# msum为[l,r]内最大子段和
msum = max(get(a,l,m)['msum'],get(a,m+1,r)['msum'],get(a,l,m)['rsum']+get(a,m+1,r)['lsum'])
return {'isum':isum,'lsum':lsum,'rsum':rsum,'msum':msum}
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return get(nums,0,len(nums)-1)['msum']
"""
思路:分治法,维护四个量(见注释),区间长度为1时结束递归。但事实上DP时间复杂度为O(n),而分治法时间复杂度为O(nlogn)。精妙是精妙,但架不住代码长,复杂度高啊。
"""
|
"""
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
Ex_1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Ex_2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
"""
class Solution:
def longestValidParentheses(self, s: str) -> int:
if not s or len(s)==1:
return 0
store=[0 for i in range(len(s))]
for i in range(len(s)):
if s[i]=='(': # The ending parenthesis of a valid parentheses substring can only be closing parenthesis.
continue
if i-1>=0 and s[i-1]=='(':
if i-2>=0:
store[i]=store[i-2]+2
else:
store[i]=2
if (i-1>=0 and s[i-1]==')') and (i-store[i-1]-1>=0 and s[i-store[i-1]-1]=='('):
if i-store[i-1]-2>=0:
store[i]=store[i-1]+store[i-store[i-1]-2]+2
else:
store[i]=store[i-1]+2
return max(store)
"""
My thinking: We make use of a "store" array where ith element of "store" represents the length of the longest valid substring ending at ith
index. Using dynamic programming. It's obvious that the valid substrings must end with '('. Time complexity of the algorithm is O(n),
because single traversal of string to fill "store" array is done. Space complexity of the algorithm is O(n), because "store" array of size
n is used.
"""
|
"""
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Note:There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Ex_1:
input:"III"
output:3
Ex_2:
input: "IV"
output: 4
Ex_3:
input: "IX"
output: 9
Ex_4:
input: "LVIII"
output: 58
Ex_5:
input: "MCMXCIV"
output: 1994
"""
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
#My code starts here
num=0
dict={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
for i in range(len(s)):
num=num+dict[s[i]]
if i>0:
if (s[i]=='M' or s[i]=='D') and s[i-1]=='C':
num=num-200
if (s[i]=='L' or s[i]=='C') and s[i-1]=='X':
num=num-20
if (s[i]=='V' or s[i]=='X') and s[i-1]=='I':
num=num-2
return num
"""
My thinking: Use a dictionary to store correspondence, and pay attention to special cases
"""
|
"""
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSameTree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
# 终止条件,两个结点都为空,则相等
if not p and not q:
return True
# 如果两个结点一个为空,那肯定两棵树不相等
# 或者两个结点的值不相等,那肯定两棵树也不相等
elif not p or not q or p.val != q.val:
return False
# 否则则递归返回两棵树的左右结点是否对应相等
else:
return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
"""
思路:递归法,时间复杂度为:O(N),其中 N 是树的结点数,因为每个结点都访问一次。空间复杂度: 最优情况(完全平衡二叉树)时为O(log(N)),最坏情况下(完全不平衡二叉树)时为O(N),用于维护递归栈。
"""
|
"""
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
# 递归算法
# 如果前序遍历的数组为空,则返回根节点为空
if not preorder:
return None
# 前序遍历数组的第一个元素为树的根节点
root = TreeNode(preorder[0])
# 在中序遍历的数组中找到根节点对应元素的下标
index = inorder.index(preorder[0])
# 那么我们就可以知道左子树节点数以及右子树节点数,并且中序遍历数组中这个下标前的元素对应的左子树部分,这个下标后的元素对应的右子树部分。
# 采用递归算法进行构建即可。
root.left = self.buildTree(preorder[1:index + 1], inorder[0:index])
root.right = self.buildTree(preorder[index + 1:], inorder[index + 1:])
return root
"""
思路:因为二叉树前序遍历的顺序为:先遍历根节点,随后递归地遍历左子树,最后递归地遍历右子树。二叉树中序遍历的顺序为:先递归地遍历左子树,随后遍历根节点,最后递归地遍历右子树。因此,对于任意一颗树而
言,前序遍历的形式总是[根节点, [左子树的前序遍历结果], [右子树的前序遍历结果]],即根节点总是前序遍历中的第一个节点。而中序遍历的形式总是[[左子树的中序遍历结果], 根节点, [右子树的中序遍历结果]]。
因此本题采用递归算法,详见注释。时间复杂度为O(n),其中n是树中的节点个数。空间复杂度为O(h),因为我们需要O(h)(其中 h 是树的高度)的空间表示递归时栈空间。
"""
|
"""
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
"""
class Solution(object):
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
#My code starts here
if not nums:
return []
flag=0
for i in range(len(nums)-2,-1,-1):
if nums[i]<nums[i+1]:
#To find the first pair of two successive numbers nums[i] and nums[i+1] from the right, which satisfy nums[i+1] > nums[i]
flag=1
index=i
break
if flag==0: #If not find, rearrange it as the lowest possible order
return nums.reverse()
j=1
while index+j<len(nums):
#We need to find number which is just larger than nums[i] among the numbers lying to its right section
if nums[index]<nums[index+j]:
j+=1
else:
break
tmp=nums[index+j-1]
nums[index+j-1]=nums[index]
nums[index]=tmp
#Swap nums[i] and nums[i+j-1]
nums[index+1:]=list(reversed(nums[index+1:]))
#At last, reverse the numbers following nums[i] to get the next smallest lexicographic permutation
return nums
"""
My thinking: First, we observe that for any given sequence that is in descending order, no next larger permutation is possible. Then, we
need to find the first pair of two successive numbers nums[i] and nums[i+1] from the right, which satisfy nums[i+1]> nums[i]. After that,
we need to find number which is just larger than nums[i] among the numbers lying to its right section. We swap nums[i] and nums[i+j-1].
At last, reverse the numbers following nums[i] to get the next smallest lexicographic permutation.
"""
|
#fizzbuzz
def fizzbuzz(num, i, j):
for n in range(1,num+1):
result = ""
if n%i == 0:
result = "fizz"
if n%j == 0:
result += "buzz"
if not result:
result = n
print(result)
def main():
n = int(input("a number: "))
n1 = int(input("a number less than {} :".format(n)))
n2 = int(input("a number less than {} :".format(n)))
fizzbuzz(n,n1,n2)
if __name__ == "__main__" :
main() |
"""
1155. Number of Dice Rolls With Target Sum
You have d dice, and each die has f faces numbered 1, 2, ..., f.
Return the number of possible ways (out of fd total ways) modulo 10^9 + 7 to roll the dice so the sum of the face up numbers equals target.
Example 1:
Input: d = 1, f = 6, target = 3
Output: 1
Explanation:
You throw one die with 6 faces. There is only one way to get a sum of 3.
Example 2:
Input: d = 2, f = 6, target = 7
Output: 6
Explanation:
You throw two dice, each with 6 faces. There are 6 ways to get a sum of 7:
1+6, 2+5, 3+4, 4+3, 5+2, 6+1.
Example 3:
Input: d = 2, f = 5, target = 10
Output: 1
Explanation:
You throw two dice, each with 5 faces. There is only one way to get a sum of 10: 5+5.
Example 4:
Input: d = 1, f = 2, target = 3
Output: 0
Explanation:
You throw one die with 2 faces. There is no way to get a sum of 3.
Example 5:
Input: d = 30, f = 30, target = 500
Output: 222616187
Explanation:
The answer must be returned modulo 10^9 + 7.
Constraints:
1 <= d, f <= 30
1 <= target <= 1000
"""
def dice_rolls(d,f,t):
if t > f*d: return 0
result = 0
final = 0
for i in range(1,min(f+1,t+1)):
if i == t:
result += 1
if d > 1:
result = dice_rolls(d-1, f, t-i)
final += result
return(final%(10e9+7))
def main():
dices = int(input("number of dices: "))
faces = int(input("number of faces on a dice: "))
target = int(input("target number (< dices*faces): "))
print(dice_rolls(dices,faces,target))
main()
|
"""
Merge Sort
----------
Uses divide and conquer to recursively divide and sort the list
Time Complexity: O(n log n)
Space Complexity: O(n) Auxiliary
"""
def merge(left, right):
"""Compares and Merges arrays."""
left_index, right_index = 0, 0
result = []
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
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(array):
"""Merge sort algorithm implementation."""
if len(array) <= 1: # base case
return array
half = len(array) // 2
left = merge_sort(array[:half])
right = merge_sort(array[half:])
return merge(left, right)
a = [17,2,4,3, 444, 5546, 7, 6, 63, 2, 5,6 ,7 ,77,15,10]
print merge_sort(a)
|
import random
board = {}
end = False
win_commbinations = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
def board():
print(' | | ')
#print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | | ')
print('------------------')
print(' | | ')
#print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | | ')
print('------------------')
print(' | | ')
#print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | | ')
def playerletter():
plylt = raw_input("what letter do you want to play with [O or X]: ")
plylt = plylt.upper()
if plylt == "X":
return ['X', 'O' ]
firstmove(plylt)
elif plylt == "O":
return ['O', 'X']
firstmove(plylt)
else:
print "Please select the right option, it has to be from X or O"
playerletter()
def firstmove(plylt):
if random.randint(0,1) == 0:
print "computer's move"
else:
print "your move, you have chosen " + plylt
registermoves(plylt)
def registermoves(plylt):
a = int (raw_input("enter a number from 1 to 9"))
if board[a] == "X" or "O":
print "please enter a new number"
registermoves()
else:
board[a] = plylt
def gamecheck(plylt):
count = 0
for a in win_commbinations:
if board[a[0]] == board[a[1]] == board[a[2]] == plylt:
print("Player 1 Wins!\n")
print("Congratulations!\n")
return True
if board[a[0]] == board[a[1]] == board[a[2]] != plylt:
print("Player 2 Wins!\n")
print("Congratulations!\n")
return True
for a in range(9):
if board[a] == "X" or board[a] == "O":
count += 1
if count == 9:
print("The game ends in a Tie\n")
#playerletter()
|
#Largest Continuous Sum
#Given an array of integers (positive and negative) find the largest continuous sum.
def largestcontsum(arr):
if len(arr) == 0:
return
currentSum = maxSum = int(arr[0])
print currentSum, maxSum
for num in arr[1:]:
print num, currentSum + num, currentSum
currentSum = max(num, currentSum+num)
maxSum = max(currentSum, maxSum)
print maxSum
return maxSum
print largestcontsum([-1, -5, -2, -6, -7, -9, -5]) |
# print tuple elements
a = [('a',4), ('b',9), ('c',16), ('d', 25)]
for k, v in a:
print "%s has value %s" % (k,v)
|
## SHUFFLING A DECK OF CARDS
## A deck of cards has 13 cards each of 4 suits: heart(♥), spade(♠), diamond(♦), club(♣).
## THOUGHT PROCESS: Construct an unshuffled deck by using two lists, one for suits, another for cardValues
## Shuffle the deck by iterating over all cards one by one using their indexes, and swapping the index with any random index.
import random
import itertools
def deck_crete():
suits = [ "Hearts", "Spade", "Diamond" , "Club" ]
faces = list(range(2,11))
faces.extend(["Jack", "Queen", "King"])
faces.insert(0,"Ace")
suits = ['Spade', 'Heart', 'Diamond', 'Club']
deck = list(itertools.product(faces, suits))
deck = shuffleDeck(deck)
draw_card(deck)
def shuffleDeck(deck):
for i, card in enumerate(deck):
insert_at = random.randrange(52)
deck[i], deck[insert_at] = deck[insert_at], deck[i]
return deck
def draw_card(deck):
t = int(input("How many cards are we drawing? : "))
print("//// You Hand ///")
for r in range(t):
r = random.choice(deck)
print("{0[0]} of {0[1]}" .format(r))
deck_crete() |
def bubbleSort(array):
tamanhoDoArray = len(array) - 1
for i in range( tamanhoDoArray ):
for j in range( tamanhoDoArray - i ):
if array[j] < array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return array
array = [2, 1, 5, 4, 3]
bubbleSort(array) |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 13 09:06:01 2018
@author: Acer
"""
a=[1,2,3,4,5,6,7,8,9,10]
sum = 0
n = len(a) #ความยาวใน array
number = 1
for i in range (sum,n): #i คือตัวที่ อยู่ใน array ไล่ไปจนครบจำนวน n
if number < len(a) : #จำนวนลูป น้อยกว่าจำนวนใน array
sum = sum + a[i]
number += 1 #เพิ่มค่านับทีละ 1
else :
sum = sum + a[i] # บวกเพิ่มตัวสุดท้าย ก่อนแสดงผล
print ("Sum of number in array loop " ,number, '=' ,sum)
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.