text
stringlengths 37
1.41M
|
---|
salario = float(input('Digite o salário do funcionário: R$'))
if salario > 1250:
print('O salário atualizado com o aumento é de R${:.2f}'.format(salario * 10 / 100 + salario))
else:
print('O salário atualizado com o aumento é de R${:.2f}'.format(salario + salario * 15 / 100)) |
from random import shuffle
n1 = input('Digite o nome do primeiro aluno: ')
n2 = input('Digite o nome do segundo aluno: ')
n3 = input('Digite o nome do terceiro aluno: ')
n4 = input('Digite o nome do quarto aluno: ')
lista = [n1, n2, n3, n4]
shuffle(lista)
print ('A ordem de apresentação é: {}'.format(lista)) |
nomecompleto = str(input('Digite seu nome completo: ')).strip()
print('Analisando seu nome...\n')
print('Seu nome em maiúsculo é:',nomecompleto.upper())
print('Seu nome em minúsculo é: ',nomecompleto.lower())
print('O seu nome completo tem {} letras'.format(len(nomecompleto) - nomecompleto.count(' ')))
print('O seu primeiro nome tem {} letras'.format(nomecompleto.find(' ')))
|
'''def somar(a=0, b=0, c=0):
"""[Mostra a soma dos parâmetros passados]
Arguments:
a {[int or float]} -- [Primeiro parametro passados]
b {[int or float]} -- [Segundo parametro passados]
Keyword Arguments:
c {int or float} -- [Terceiro parametro opcional] (default: {0})
Função criada por Thiago Ximenes para aula 20 de python
"""
s = a + b + c
print(f'A soma de {a}, {b} e {c} é {s}' if c != 0 else
f'A soma de {a} e {b} é {s}')
somar(3, 3, 5)
somar(2, 5)
somar()
somar(c = 3, b = 2)
help(somar) '''
'''def teste():
global n
n = 8 # escopo local
print(f'Na função teste n vale {n}')
print(f'Na função teste x vale {n}')
# Programa principal
n = 2 # escopo global
teste()
print(f'No programa principal, n vale {n}')'''
'''def somar(a=0, b=0, c=0):
"""Mostra a soma dos parâmetros passados
Arguments:
a {[int or float]} -- [Primeiro parametro passados]
b {[int or float]} -- [Segundo parametro passados]
Keyword Arguments:
c {int or float} -- [Terceiro parametro opcional] (default: {0})
Função criada por Thiago Ximenes para aula 20 de python
"""
s = a + b + c
return s
r = list()
r.append(somar(3, 3, 2))
r.append(somar(2, 5, 10))
r.append(somar(4, 7))
print(f'Meus resultados são {r[0]}, {r[1]} e {r[2]}.') '''
'''def fatorial(num=1):
#from math import factorial
#s = factorial(num)
f = 1
for c in range(num, 0, -1):
f *= c
return f
#n = int(input('Digite um número: '))
#print(f'O fatorial do número {n} é {fatorial(n)}')
f1 = fatorial(5)
f2 = fatorial(4)
f3 = fatorial()
print(f'Os resultados foram {f1}, {f2} e {f3}') '''
def par(n=0):
if n % 2 == 0:
return True
else:
return False
num = int(input('Digite um número: '))
'''n = par(num)
print(f'O número é passado é par? {n}') '''
if par(num):
print('É par!')
else:
print('Não é par!')
|
#lanche = 'Hambúrguer', 'Suco', 'Pizza', 'Pudim', 'Batata Frita'
#Tuplas são imutáveis!
#for c in range(0, len(lanche)):
# print(f'Eu vou comer {lanche[c]} na posição {c}')
#for comida in lanche:
# print(f'Eu vou comer {comida}')
#for pos, comida in enumerate(lanche):
# print(f'Eu vou comer {comida} e na posição {pos}')
#print(sorted(lanche))
#print('Já acabou?')
#a = 2, 5, 4
#b = 5, 8, 1, 2
#c = b + a
#print(c)
#print(c.index(2, 4)) #depois da , é a partir daquela posição
pessoa = 'Thiago', 27, 'M', 90.00
del(pessoa) #deleta qualquer coisa no python #deleta tupla inteiro, não posso deletar só 1 item
print(pessoa) |
"""
Author: Nguyen Tan Loc
Date: 25/08/2021
Problem: Write an algorithm that describes the second part of the process of making change
(counting out the coins and bills)
Solution: example, if you buy a dozen eggs at the farmers’ market for $2.39 and you give the farmer a
$10 bill, she should return $7.61 to you. To produce this amount, the merchant selects the
appropriate coins and bills that, when added to $2.39, make $10.00.
According to another method, the merchant starts with the purchase price and goes toward
the amount given. First, coins are selected to bring the price to the next dollar amount (in
this case, $0.61 3 5 dimes, 1 nickel, and 4 pennies), then dollars are selected to bring the
price to the next 5-dollar amount (in this case, $2), and then, in this case, a $5 bill completes
the transaction
""" |
"""
Author: Nguyen Tan Loc
Date: 7/10/2021
Problem:
What is a mutator method? Explain why mutator methods usually return the
value None.
Solution:
Mutator methods are the methods that are used to modify the internal elements of the mutable objects. The Mutable object means which can be modified.
For example consider the "list" which is the mutable object.
The "list" is having its own methods such as insert, append, pop which are used to modify the elements in the list. These methods are the mutator methods.
....
""" |
"""
Author: Nguyen Tan Loc
Date: 7/10/2021
Problem:
A file concordance tracks the unique words in a file and their frequencies. Write
a program that displays a concordance for a file. The program should output the
unique words and their frequencies in alphabetical order. Variations are to track
sequences of two words and their frequencies, or n words and their frequencies
Solution:
....
"""
filename=input('Enter the input file name: ')
inputFile = open(filename,"r+")
list={}
for word in inputFile.read().split():
if word not in list:
list[word] = 1
else:
list[word] += 1
inputFile.close();
print();
for i in sorted(list):
print("{0} {1} ".format(i, list[i])); |
"""
Author: Nguyen Tan Loc
Date: 16/10/2021
Problem:
Darkening an image requires adjusting its pixels toward black as a limit, whereas
lightening an image requires adjusting them toward white as a limit. Because
black is RGB (0, 0, 0) and white is RGB (255, 255, 255), adjusting the three RGB
values of each pixel by the same amount in either direction will have the desired
effect. Of course, the algorithms must avoid exceeding either limit during the
adjustments.
Lightening and darkening are actually special cases of a process known as color
filtering. A color filter is any RGB triple applied to an entire image. The filtering
algorithm adjusts each pixel by the amounts specified in the triple. For example,
you can increase the amount of red in an image by applying a color filter with a
positive red value and green and blue values of 0. The filter (20, 0, 0) would make
an image’s overall color slightly redder. Alternatively, you can reduce the amount
of red by applying a color filter with a negative red value. Once again, the algorithms must avoid exceeding the limits on the RGB values.
Develop three algorithms for lightening, darkening, and color filtering as three
related Python functions, lighten, darken, and colorFilter. The first two
functions should expect an image and a positive integer as arguments. The third
function should expect an image and a tuple of integers (the RGB values) as arguments. The following session shows how these functions can be used with the
images image1, image2, and image3, which are initially transparent:
>>> image1 = Image(100, 50)
>>> image2 = Image(100, 50)
>>> image3 = Image(100, 50)
>>> darken(image1, 128) # Converts to gray
>>> darken(image2, 64) # Converts to dark gray
>>> colorFilter(image3, (255, 0, 0)) # Converts to red
Note that the function colorFilter should do most of the work.
Solution:
....
"""
|
"""
Author: Nguyen Tan Loc
Date: 22/10/2021
Problem:
Write the code for a mapping that generates a list of the absolute values of the numbers in a list named numbers
Solution:
Map Function
• Map is one of the higher order functions in python used to apply a specific function on all the elements
of an iterable object.
• Iterable objects are those that contains group of elements entitled under a single name like lists,
dictionaries, tuples and so on.
• The function that is applied using map can be a built-in function or any user defined function.
• Map function returns a map object which should be casted according to our requirement.
• The general syntax of map function will be as follows
map (function, iterable object)
• According to the requirement of the problem a mapping that generates a list of absolute values of the
numbers in a list named “numbers” should be written.
• The code for mapping will be as follows
print (list (map (abs, numbers)))
• “abs” is the name of the function that takes a single value as an argument and return the absolute value
of that respective argument.
• “numbers” is the list data structure that contains a list of numbers
• “map” is the function that maps each element of the list “numbers” to the function “abs”.
"""
#example
myList = [2,3,-3,-2]
print (map(abs, myList))
|
"""
Author: Nguyen Tan Loc
Date: 16/10/2021
Problem:
The edge-detection function described in this chapter returns a black-and-white
image. Think of a similar way to transform color values so that the new image is still
in its original colors but the outlines within it are merely sharpened. Then, define a
function named sharpen that performs this operation. The function should expect
an image and two integers as arguments. One integer should represent the degree
to which the image should be sharpened. The other integer should represent the
threshold used to detect edges. (Hint: A pixel can be darkened by making its RGB
values smaller.)
Solution:
....
"""
|
"""
Author: Nguyen Tan Loc
Date: 10/09/2021
Problem:
Assume that x refers to a number. Write a code segment that prints the number’s
absolute value without using Python’s abs function.
Solution:
x=int(input("Enter x:"))
if x < 0:
x = –x
print("x: ",x)
....
""" |
"""
Author: Nguyen Tan Loc
Date: 10/09/2021
Problem:
Write a loop that prints your name 100 times. Each output should begin on a
new line.
Solution:
for count in range(100): print('LeVanThe!')
....
"""
|
"""
Author: Nguyen Tan Loc
Date: 15/10/2021
Problem:
The Turtle class includes a method named circle. Import the Turtle class, run
help(Turtle.circle), and study the documentation. Then use this method to
draw a filled circle and a half moon.
Solution:
....
""" |
"""
Author: Nguyen Tan Loc
Date: 1/09/2021
Problem: Light travels at 3 *108
meters per second. A light-year is the distance a light beam
travels in one year. Write a program that calculates and displays the value of a
light-year.
Solution:
"""
# Compute the result
rate = 3 * 10 ** 8
seconds = 365 * 24 * 60 ** 2
distance = rate * seconds
# Display the result
print("Light travels", distance, "meters in a year, ")
|
"""
Author: Nguyen Tan Loc
Date: 1/09/2021
Problem: Write a string that contains your name and address on separate lines using embeded newline characters. Then write the same string literal without the newline
characters.
Solution:
"""
print("TAN LOC \nQuang Ngai ") |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countSort function below.
def countSort(arr):
highest = int(arr[0][0])
for i in arr:
if highest < int(i[0]):
highest = int(i[0])
li = []
for i in range(highest + 1):
li.append([])
lenarr = len(arr)
for i in range(lenarr):
if i < (lenarr // 2):
li[int(arr[i][0])].append('-')
else:
li[int(arr[i][0])].append(arr[i][1])
for i in li:
for j in i:
print(j,end=' ')
if __name__ == '__main__':
n = int(input().strip())
arr = []
for _ in range(n):
arr.append(input().rstrip().split())
countSort(arr)
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the anagram function below.
def makingAnagrams(s1, s2):
splited = [s1, s2]
alphaCount = [{},{}]
asciia = ord('a')
for i in range(26):
alphaCount[0][chr(i + asciia)] = 0
alphaCount[1][chr(i + asciia)] = 0
for i in range(2):
for j in splited[i]:
alphaCount[i][j] += 1
diff = []
for i in alphaCount[0].keys():
if alphaCount[0][i] != alphaCount[1][i]:
diff.append(abs(alphaCount[0][i] - alphaCount[1][i]))
return sum(diff)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
s1 = input()
s2 = input()
result = makingAnagrams(s1, s2)
fptr.write(str(result) + '\n')
fptr.close()
|
# Learner: Truong Vi Thien (14520874)
# Generate Gaussian blobs and clustering using K-Mean.
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use("ggplot")
from sklearn.cluster import KMeans
from sklearn.datasets.samples_generator import make_blobs
# Create data
n_samples = 1000
n_features = 2
x, _ = make_blobs(n_samples=n_samples, n_features=n_features)
# Using KMeans
n_clusters = 4
kmeans = KMeans(n_clusters=n_clusters)
kmeans.fit(x)
centroids = kmeans.cluster_centers_
labels = kmeans.labels_
#Visualize
print(centroids)
print(labels)
colors = ["c.","m.","y.","k.","r.","g.","b."]
for i in range(len(x)):
print("coordinate: ", x[i], "label: ", labels[i])
plt.plot(x[i][0], x[i][1], colors[labels[i]], markersize = 5)
plt.title('Generate Gaussian blobs and clustering using K-Mean')
plt.scatter(centroids[:,0], centroids[:,1], marker = "o", c="#000000", edgecolors="#ffffff", alpha=0.5, s = 150, linewidths= 5, zorder = 10)
plt.show()
|
li = input()
if '-0' in li:
print('Sorry! Please enter valid integers')
else:
try:
li = li.split(',')
li = [int(number) for number in li]
li.sort()
li.reverse()
prime = []
other = []
for number in li:
s = 0
for j in range(1, number + 1):
if number % j == 0:
s += 1
if s == 2:
prime.append(number)
else:
other.append(number)
print("prime=", prime)
print("other=", other)
except ValueError:
print('Sorry! Please enter valid integers')
|
"""
https://leetcode-cn.com/problems/lru-cache/
"""
class LRUCache(object):
def __init__(self, capacity):
"""
:type capacity: int
"""
self.capacity = capacity
self.dic = {}
self.head = None
self.tail = None
def get(self, key):
"""
:type key: int
:rtype: int
"""
val = -1
if self.dic.has_key(key):
element = self.dic[key]
if element.next is not None:
if element.pre is None:
self.head = element.next
element.next.pre = None
else:
element.pre.next = element.next
element.next.pre = element.pre
element.next = None
element.pre = self.tail
self.tail.next = element
self.tail = element
return element.val
else:
return -1
def put(self, key, value):
"""
:type key: int
:type value: int
:rtype: None
"""
if self.capacity == 0:
return
if self.dic.has_key(key):
self.dic[key].val = value
self.get(key)
return
if len(self.dic) == self.capacity:
del self.dic[self.head.key]
self.head = self.head.next
if self.head is not None:
self.head.pre = None
element = Element(value, key)
if self.head is None:
self.head = element
self.tail = element
else:
self.tail.next = element
element.pre = self.tail
self.tail = element
self.dic[key] = element
class Element(object):
def __init__(self, val, key):
self.val = val
self.key = key
self.pre = None
self.next = None
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)
|
"""
https://leetcode-cn.com/problems/card-flipping-game/
"""
class Solution(object):
def flipgame(self, fronts, backs):
"""
:type fronts: List[int]
:type backs: List[int]
:rtype: int
"""
same = []
diff = []
for i in range(len(fronts)):
if fronts[i] != backs[i]:
diff.append(fronts[i])
diff.append(backs[i])
else:
# 正反面都相同的不会是所需要的牌
same.append(fronts[i])
# 去掉正反面不同的牌中与淘汰掉的牌的数组相同的那一面,因为该面与正面的牌一定有重复的
for s in same:
while s in diff:
diff.remove(s)
if diff:
diff.sort()
return diff[0]
return 0
|
"""
https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/
"""
class Solution(object):
def searchRange(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
if len(nums) == 0:
return [-1, -1]
return self.bisearch(nums, 0, len(nums) - 1, target)
def bisearch(self, nums, left, right, target):
if left < 0 or right > len(nums) - 1 or left > right:
return [-1, -1]
mid = left + (right - left) / 2
i = mid
j = mid
while i > 0 and nums[i] == nums[i - 1]:
i -= 1
while j < len(nums) - 1 and nums[j] == nums[j + 1]:
j += 1
if target == nums[mid]:
return [i, j]
elif target > nums[mid]:
return self.bisearch(nums, j + 1, right, target)
else:
return self.bisearch(nums, left, i - 1, target)
|
import pandas as pd
friends=[
{'name':'Jone','age':20,'job':'student'},
{'name':'Jenny','age':30,'job':None},
{'name':'Nate','age':30,'job':'teacher'}
]
df=pd.DataFrame(friends)
df=df[['name','age','job']]
print(df.head())
print(df[1:3])
print(df.loc[[0,2]])
print(df[df.age>25])
print(df.query('age>25'))
print(df[(df.age>25)&(df.name=='Nate')])
|
#!/usr/bin/python
# coding:utf-8
"""
This program reads in the CSV file, provide the option to manipulate per line
of the file and save the modified data into a new CSV file.
Usage:
ManipulateCSVFile.py input.csv
@author: Haiyang Cui
"""
import sys
from pathlib import Path
def main(argv):
if len(sys.argv) != 2:
sys.exit("Usage: ManipulateCSVFile.py input.csv")
inputFile = argv[1]
m_file = Path(inputFile)
if not m_file.exists():
sys.exit("The input file does not exist.")
print('The input file is ' + inputFile)
ManipulateCSVFile(inputFile)
def ManipulateCSVFile(inputFile):
print("Processing the csv file....")
import csv
import os
head, tail = os.path.split(inputFile)
newFileName=""
if head == "":
newFileName="Modified_" + tail
else:
newFileName = head +"\Modified_" + tail;
with open(newFileName,'wt',newline='') as resultFile:
wr = csv.writer(resultFile, dialect='excel')
reader = csv.reader(open(inputFile, "rt"))
for row in reader:
if not row:
continue
newRowData = ManipulateRowData(row)
wr.writerow(newRowData)
print("The data has been saved to file: " + newFileName)
print("Done!!")
# This is just an example of how to manipulate the row data.
def ManipulateRowData(rowData):
newRowData=[]
for i in range(len(rowData)):
cellData = rowData[i]
if cellData == "Nunavut":
newRowData.append("ExampleData")
else:
newRowData.append(cellData)
return newRowData
if __name__ == "__main__":
main(sys.argv) |
import random
import os
'''This file is to quickly build sample test data by outputing text files
with randomized data and check computational speed'''
#Time points for different sizes:
# 50x50
# 100x100
# 300x300
# 500x500
# 800x800
# 1000x1000
def check_lines(my_file, max_user_number, new_file):
f = open(my_file)
lines = f.readlines()
lines.pop(0)
f.close()
test_data = open(new_file, 'w')
for line in lines:
individual_rating = line.split(",")
user_id = int(individual_rating[0])
if user_id <= max_user_number:
test_data.write(line)
test_data.close()
def make_lines(max_user_number, new_file, movie_id):
test_data = open(new_file, 'w')
movie_id_line = "%s:\n" % movie_id
test_data.write(movie_id_line)
for i in range(max_user_number):
if i%5 == 0: #To determine what percentage ratings exist
line = "%s,%s,date\n" % ((i+1), (random.randint(0, 5)))
test_data.write(line)
else:
pass
test_data.close()
def create_file(max_movie_number, directory_name, max_user_number, test_size):
if not os.path.exists(test_size):
os.makedirs(directory_name + "/" + test_size)
for i in range(max_movie_number):
filepath = directory_name + "/" + test_size +"/"+ str(i+1)
movie_id = str(i+1)
make_lines(max_user_number, filepath, movie_id)
def main():
create_file(max_movie_number=50, directory_name = "time_test_data",
max_user_number=50, test_size = "50x50")
if __name__ == '__main__':
main() |
# IfSpiral.py
# Billy Ridgeway
# Creates a square spiral.
# Asks the user if they want to see a spiral.
answer = input("Do you want to see a spiral? y/n:")
if answer == 'y': # If the anser is yes, run the program.
print("Working...") # Display a message the the program is working.
import turtle # Import turtle graphics.
t = turtle.Pen() # Creates a new turtle called t.
t.speed(0) # Sets the pen's speed to fast.
t.width(2) # Sets the width of the pen to 2.
# Creates a for loop.
for x in range(100): # Sets the variable 'x' to 100.
t.forward(x*2) # Moves the pen forward the value of 'x' times 2.
t.left(89) # Turns the pen left by 89 degrees.
print("Okay, we're done!") # Prints "Okay, we're done! if the answer was no,
# or the for loop completed successfully.
|
from matplotlib.pyplot import plot, axis, show, legend
mortgage_amount = float(input("How much is the mortgage for? "))
interest_rate = float(input("What is the interest rate (as a percentage)? "))/100
payment = float(input("How much are you paying per month? "))
max_months = 360 # Don't figure for more than 30 years
month = 0
month_list = [0]
mortgage_list = [mortgage_amount]
principal_paid_list = [0]
interest_paid_list = [0]
while (mortgage_amount > 0.0) and (month < max_months):
month += 1
month_list.append(month)
# Determine new interest
interest = mortgage_amount * (interest_rate/12)
interest_paid_list.append(interest+interest_paid_list[month-1])
# Determine principal paid and remaining
principal = payment - interest
mortgage_amount -= interest
mortgage_list.append(mortgage_amount)
principal_paid_list.append(principal+principal_paid_list[month-1])
plot(month_list, mortgage_list, label="Remaining Mortgage", color="red")
plot(month_list, principal_paid_list, label="Principal Paid", color="blue")
plot(month_list, interest_paid_list, label="Interest Paid", color="green")
axis([0, month, 0, max(interest_paid_list[month], mortgage_list[0])])
legend()
show()
|
'''
У даному випадку рекурмія займає бцльше пам'яті
Код доволі легко читати як в ітераційному так і в рекурсивному методах
'''
from time import time
def dig_root(number):
if number < 10: # якщо число однозначне то це і буде корінь
return number
else:
return dig_root(
number // 10 + number % 10) # рекурсі в якій чило ділиться на 10 для знаходження остачі та додання її та зменшення числа в 10 раз
# і підставлення зменшеного числа в функцію жоки не отримаємо однозначне
def dig_root_it(number):
if number < 10: # якщо число однозначне то це і буде корінь
return number
else:
while number > 9: # виконується до тих пір поки число двузначне
i = number % 10 # знаходження останьої цифри
number = number // 10 # число без останьої цифри
number = number + i # додання до числа останьої цифри
return number
number = int(input('enter number'))
if input('if you want to use recursion press Enter, if iteration write something and press Enter: ') == '':
tic = time()
print(dig_root(number))
toc = time()
else:
tic = time()
print(dig_root_it(number))
toc = time()
time = toc - tic
print(f'time: {time}')
|
import random
class sources_num_1():
def sources_choice(self):
a = ['广告','地推','老带新','上门']
return random.choice(a)
def num_sources(self,list,num):
for i in range(num):
list.append(self.sources_choice())
|
'''
Escriba una funcin que reciba un nmero entero del
1 al 7 y escriba en pantalla el correspondiente
da de la semana.
'''
def semanita():
numero=input("Introduce un numero del 1 al 7: ")
if numero==1:
print "Hoy es Lunes"
if numero==2:
print "Hoy es martes"
if numero==3:
print "Hoy es miercoles"
if numero==4:
print "Hoy es jueves"
if numero==5:
print "Hos es viernes"
if numero==6:
print "Hoy es sabado"
if numero==7:45
print "Hoy es domingo"
semanita()
|
import math
def findX(array, x):
"""
Given a sorted array, find the index
of x if it exists, -1 otherwise. This
can be done via binary search.
"""
left = 0
right = len(array)
while (left < right):
mid = int(math.floor((right + left)/2))
if (x == array[mid]):
return mid
if (x < array[mid]):
right = mid
else:
left = mid + 1
return -1
def run_tests():
# some simple tests
assert(findX([],1) == -1)
assert(findX([1],1) == 0)
assert(findX([2],1) == -1)
assert(findX([1,2],1) == 0)
assert(findX([1,2],2) == 1)
assert(findX([1,2],4) == -1)
assert(findX([1,2,3,4,6,7,8,10],9) == -1)
assert(findX([1,13,2,3,4,6,7,8,10,13],13) == 9)
|
'''
Fibonacci functions with recursion and
dynamic programming.
'''
def fibonacci(i):
'''
Calculates the ith fibonacci number.
Runs in O(2^n)
'''
if (i == 0): return 0
if (i == 1): return 1
return fibonacci(i-1) + fibonacci(i-2)
fibs = []
def fibonacciDP(i):
'''
Calculates the ith fibonacci number,
using dynamic programming.
Runs in O(N)
'''
if (i == 0):
fibs.insert(i, 0)
return 0
if (i == 1):
fibs.insert(i, 1)
return 1
# return cached result if it exists
if (len(fibs) >= i): return fibs[i]
# set ith fibonacci number
fibs.insert(i, fibonacciDP(i-1) + fibonacciDP(i-2))
return fibs[i]
|
def sort(A):
mergeSort(A, 0, len(A))
def mergeSort(A, p, r):
q = (p + r) // 2
if q > p:
mergeSort(A, p, q)
mergeSort(A, q, r)
merge(A, p, q, r)
def merge(A, p, q, r):
L = []
R = []
for i in range(p, q): # p .. q-1
L.append(A[i])
L.append(float("inf"))
for i in range(q, r): # q .. r-1
R.append(A[i])
R.append(float("inf"))
iL = 0
iR = 0
for i in range(p, r):
if L[iL] >= R[iR]:
A[i] = R[iR]
iR += 1
else: #L[iL] <= R[iR]
A[i] = L[iL]
iL += 1
# A = [9, 21, 213, 32, 45, 8,7 , 3423, 78, 53, 4, 1, 3]
# sort(A)
# print(A)
|
class Solution:
def reverseString(self, s) -> None:
"""
Do not return anything, modify s in-place instead.
"""
print(s.reverse())
l=Solution()
l.reverseString(["h","e","l","l","o"])
|
li1= [9,8,4,1,2,2,0,5,5]
# li2= list(set(li1))
# print(li2)
# for i in list(set(li1)):
# if i in li1:
# li1.remove(i)
nums= sorted(li1)
print(nums)
output=[]
for i in range(1,len(nums)):
if nums[i]==nums[i-1]:
output.append(nums[i])
print(output)
# print(li1) |
#! /usr/bin/python
import random
"""
Code for a presentation on dunder method basics
"""
class Color:
_primary_colors = ['red', 'yellow', 'blue']
_secondary_colors = ['orange', 'green', 'purple']
_instance = None
def __new__(cls, color):
return super(Color, cls).__new__(cls)
# Singleton
if not cls._instance:
cls._instance = super(Color, cls).__new__(cls)
return cls._instance
def __init__(self, color):
if color in Color._primary_colors:
self.color = color
elif color in Color._secondary_colors:
self.color = color
elif color is 'white':
self.color = 'white'
else:
self.color = 'black'
def __str__(self):
return self.color
def __repr__(self):
return "Color('{}')".format(self.color)
def __add__(self, color):
if self.color is color.color:
return Color(self.color)
if self.color is 'red':
return {'blue': Color('purple') ,
'yellow' : Color('orange')}[color.color]
if color.color is 'blue':
return Color('purple')
elif color.color is 'yellow':
return Color('orange')
elif self.color is 'blue':
if color.color is 'red':
return Color('purple')
elif color.color is 'yellow':
return Color('green')
elif self.color is 'yellow':
if color.color is 'blue':
return Color('green')
elif color.color is 'red':
return Color('orange')
else:
return Color('black')
def __sub__(self, color):
if self.color is color.color:
return Color('white')
if self.color in Color._primary_colors and color.color in Color._primary_colors:
return Color(self.color)
if self.color in Color._secondary_colors:
if self.color is 'orange':
if color.color is 'yellow':
return Color('red')
elif color.color is 'purple':
return Color('red')
elif color.color is 'red':
return Color('yellow')
elif color.color is 'green':
return Color('red')
elif color.color is 'blue':
return Color('orange')
elif self.color is 'green':
if color.color is 'yellow':
return Color('blue')
elif color.color is 'purple':
return Color('yellow')
elif color.color is 'red':
return Color('green')
elif color.color is 'orange':
return Color('green')
elif color.color is 'blue':
return Color('yellow')
elif self.color is 'purple':
if color.color is 'yellow':
return Color('purple')
elif color.color is 'green':
return Color('yellow')
elif color.color is 'red':
return Color('blue')
elif color.color is 'orange':
return Color('blue')
elif color.color is 'blue':
return Color('red')
else:
return Color('white')
def __eq__(self, other):
return self.color is other.color
def __hash__(self):
#return 0
return random.randint(1, 3)
if __name__ == "__main__":
red = Color('red')
blue = Color('blue')
yellow = Color('yellow')
print(red)
print(str(red))
print(repr(red))
print(red + blue)
print(str(red + blue))
print(repr(red + blue))
print(red + blue - yellow - blue)
print(str(red + blue - yellow - blue))
print(repr(red + blue - yellow - blue))
print(red + blue - yellow - blue - red)
print(str(red + blue - yellow - blue - red))
print(repr(red + blue - yellow - blue - red))
colors = {red : 'red', blue: 'blue', yellow: 'yellow'}
print(repr(colors[red]))
|
# 新建元组类型 只可以访问,不可以增删改
# 用在方法入参,只读
atuple = (1,2,3,4)
if __name__ == '__main__':
print(atuple[0])
print(atuple[0:4])
# 不能被更改,所以报黄
atuple[0] = 5
|
# Purpose of Descriptors
# without descriptors
# class Person:
# def __init__(self, name, age, bmi):
# self.name = name
# self.age = age
# self.bmi = bmi
# if isinstance(self.name, str):
# print(self.name)
# else:
# raise ValueError("Name of the person can never be an integer")
# if self.bmi < 0:
# raise ValueError("Bmi can never be less than zero")
#
# def __str__(self):
# return "{0} age is {1} with a bmi of {2}".format(self.name, self.age, self.bmi)
#
#
# person1 = Person("John", "25", 17)
# print(person1)
class Descriptors:
def __init__(self):
self.__bmi = 0
def __get__(self, instance, owner):
return self.__bmi
def __set__(self, instance, value):
if isinstance(value, int):
print(value)
else:
raise TypeError("Bmi can only be an integer")
if value < 0:
raise ValueError("Bmi can never be less than zero")
self.__bmi = value
def __delete__(self, instance):
del self.__bmi
class Person:
bmi = Descriptors()
def __init__(self, name, age, bmi):
self.name = name
self.age = age
self.bmi = bmi
def __str__(self):
return f"{self.name} age is {self.age} and his bmi is {self.bmi}"
person1 = Person("John", 25, 17)
print(person1)
person2 = Person("John", 25, 48)
print(person2)
|
#Python-to-AQA-psudocode converter
#By Andrew Mulholland aka gbaman
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#Enter the file name of the python file you want to convert below
#You should use its full file path
pythonFile = "droids.py"
import re
import time
from logging import debug, info, warning, basicConfig, INFO, DEBUG, WARNING
basicConfig(level=WARNING)
def getTextFile(filep):
"""
Opens the text file and goes through line by line, appending it to the svgfile list.
Each new line is a new object in the list, for example, if the text file was
----
hello
world
this is an awesome text file
----
Then the list would be
["hello", "world", "this is an awesome text file"]
Each line is a new object in the list
"""
file = open(filep)
svgfile = []
while 1:
line = file.readline()
if not line:
break
svgfile.append(line) #Go through entire SVG file and import it into a list
return svgfile
def removeN(svgfile):
"""
Removes the final character from every line, this is always /n, aka newline character.
"""
for count in range(0, len(svgfile)):
svgfile[count] = svgfile[count][0: (len(svgfile[count]))-1]
return svgfile
def blankLineRemover(svgfile):
"""
Removes blank lines in the file, these mess around with indentation tracing so are just removed.
"""
toremove = [ ]
#toremove.append(len(svgfile))
for count in range(0, len(svgfile)): #Go through each line in the text file
found = False
for i in range(0, len(svgfile[count])): #Go through each char in the line
if not (svgfile[count][i] == " "):
found = True
if found == False:
toremove.append(count)
#toremove.append(len(svgfile))
toremove1 = []
for i in reversed(toremove):
toremove1.append(i)
for r in range(0, len(toremove)):
svgfile.pop(toremove1[r])
debug("just removed " + str(toremove1[r]))
return svgfile
def multiLineCommentTracker(textFile):
"""
Goes through the file and finds multiline comments. If a multiline comment is found, it will ignore the entire line! You have been warned
"""
searchingForEnd = False
startLine = 0
endLine = 0
avoidLines = []
for count in range(0, len(textFile)):
found = textFile[count].find('"""')
if (found != -1):
if searchingForEnd == False:
searchingForEnd = True
startLine = count
foundMore = False
for count3 in range(found, len(textFile[count])-3):
if textFile[count][count3 : count3+3] == '"""':
searchingForEnd = False
else:
searchingForEnd = False
endLine = count
for count2 in range(startLine, endLine+1):
avoidLines.append(count2)
#print(textFile[count2])
return avoidLines
def wordReplacer(svgfile, linesToAvoid, clues, charCheck = True, removeEndChar = False): #Charcheck can be used to disable specific character checking, will remove words in middle of things though!
"""
wordReplacer goes through the program line by line removing the any items found in clues list. Think of it as a find and replacer.
"""
usefulLineNums = []
profind=False
retFind = False
for count in range(0, len(svgfile)):
for i in range(0, len(clues)):
found = svgfile[count].find(clues[i][0]) #Check if the current line in the SVG file has the required string
workingOn = svgfile[count]
if("#" in workingOn):
workingOnHash = workingOn.split("#")
if(workingOnHash[0]):
workingOn = workingOnHash[0]
else:
workingOn= ""
svgfile[count] = workingOn
#bodge fix for FOR LOOP
if ("FOR" in workingOn.upper() and "DO" not in workingOn):
workingOn = workingOn.replace(":"," DO")
iterableP = re.compile('^[FOR|for][^0-9]*\:$')
line = iterableP.search(svgfile[count])
if (line):
# print(line.group())
iterator = line.group().split(" ")[1]
#print (iterator)
iterable = line.group().split(" ")[-1]
iterable = iterable.replace(":","")
#print (iterable)
workingOn = "FOR EACH " + iterator + " FROM " + iterable + " DO"
else:
workingOn = workingOn.replace("for","FOR")
pattern = re.compile('([0-9]*,[0-9]*)')
numbers = pattern.findall(svgfile[count])
if (numbers):
numbersS = "".join(numbers)
number1 = numbersS.split(",")[0]
number2 = numbersS.split(",")[1]
workingOn = (re.sub('in range\([0-9]*,[0-9]*\)', 'FROM ' + number1 + " TO " + number2, svgfile[count]))
svgfile[count] = workingOn
#bodge fix for while loop :
if ("WHILE" in workingOn.upper() and "DO" not in workingOn):
workingOn = workingOn.replace(":"," DO")
workingOn = workingOn.replace("while","WHILE")
svgfile[count] = workingOn
#print(workingOn)
#very bodgy output fix
if ("PRINT" in workingOn.upper()):
tabs = workingOn.split("print")[0]
var = workingOn.split("print")[1]
if (var=="()"):
var=" BLANK LINE"
if (")" in workingOn):
workingOn = tabs + "SEND" + var + " TO SCREEN"
else:
workingOn = tabs + "SEND" + var
svgfile[count] = workingOn
#bodgy multiline fix
pattern = re.compile('.*"\)$')
multiLineP = pattern.match(workingOn)
pattern2 = re.compile('.*\'\)\s*$')
multiLineP2 = pattern2.match(workingOn)
if (multiLineP or multiLineP2):
#print (workingOn)
workingOn = workingOn + " TO SCREEN"
svgfile[count] = workingOn
if (not (found == -1)) and not (count in linesToAvoid):
if (found > 0) and (len(svgfile[count]) > (found+len(clues[i][0]))) and charCheck:
workingOn = svgfile[count]
debug(svgfile[count][found-1])
debug(svgfile[count][found+len(clues[i][0])])
#bodge fix for SET
if (" = " in workingOn and "SET" not in workingOn and "if" not in workingOn):
fixSet = workingOn.split(" ")
tabs = 1 + (len(fixSet[0]) - len(fixSet[0].lstrip()))
tabstring=""
for i in range(1,int(tabs)):
tabstring = tabstring + "\t"
fixSet[0] = tabstring + "SET " + fixSet[0].lstrip()
workingOn = " ".join(fixSet)
svgfile[count] = workingOn
#very bodgy input fix
if ("input" in workingOn):
#bodge fix for int --> INTEGER
intFlag = ""
if (" INT(" in workingOn.upper() and "INTEGER" not in workingOn ):
intFlag = "INTEGER"
workingOn = workingOn.replace("input","RECIEVE")
workingOn = workingOn.replace("INPUT","RECIEVE")
#print (workingOn)
var = workingOn.split("RECIEVE")[1].split(" ")[0]
try:
var = var + workingOn.split("RECIEVE")[1].split(" ")[1]
except:
pass
tabs = workingOn.split("RECIEVE")[0]
workingOn = tabs + "RECIEVE " + intFlag + var + " FROM KEYBOARD"
#print (workingOn)
svgfile[count] = workingOn
#bodge fix for INPUT/PRINT/IF BRACKETS/OUTPUT
if ("RECIEVE" in workingOn.upper() or "PRINT" in workingOn.upper() or "IF" in workingOn.upper()):
#workingOn = workingOn.replace("("," ")
#workingOn = workingOn.replace(")"," ")
workingOn = workingOn.replace(":"," THEN")
workingOn = workingOn.replace("INTEGER","(INTEGER) ")
svgfile[count] = workingOn
if count == 14:
pass
if ((svgfile[count][found-1] == " ") or (svgfile[count][found-1] == '"') or (svgfile[count][found-1] == '.')) and ((svgfile[count][found+len(clues[i][0])]== " ") or (svgfile[count][found+len(clues[i][0])] == '"') or (svgfile[count][found+len(clues[i][0])] == ".")):
workingOn = workingOn.replace("INTEGER","(INTEGER)")
svgfile[count] = workingOn
if ("SEND" not in svgfile[count]):
firstbit = svgfile[count][:found]
secondbit = svgfile[count][found+len(clues[i][0]):len(svgfile[count])]
fixed = firstbit + clues[i][1] + secondbit
svgfile[count] = fixed
#print (svgfile[count])
else:
firstbit = svgfile[count][:found]
secondbit = svgfile[count][found+len(clues[i][0]):len(svgfile[count])]
fixed = firstbit + clues[i][1] + secondbit
svgfile[count] = fixed
#bodge fix to remove : from else statements
if ("ELSE" in fixed.upper()):
fixed = fixed.replace(":","")
svgfile[count] = fixed
if removeEndChar:
WorkingOn = removeEndBit(svgfile[count], clues[i][2])
svgfile[count] = WorkingOn
#BODGIEST FIX YET FOR WEIRD OUTPUT BUG
pattern = re.compile('^SEND((?!TO SCREEN).)*$')
if re.match(pattern, svgfile[count]):
bodge = (svgfile[count].split(" "))
bodge[0] = "SEND ("
svgfile[count] = " ".join(bodge)
svgfile[count] = svgfile[count] + ") TO SCREEN"
#print (svgfile[count])
if("RETURN" in workingOn.upper()):
#print(svgfile[count])
retFind = True
for trackBack in range(count,0,-1):
#print(trackBack)
if ("PROCEDURE" in svgfile[trackBack] and "END" not in svgfile[trackBack] and "BEGIN" not in svgfile[trackBack] ):
# print(svgfile[trackBack])
svgfile[trackBack] = svgfile[trackBack].replace("PROCEDURE","FUNCTION")
#print(svgfile[trackBack])
break
for trackBack in range(count,len(svgfile)):
if ("PROCEDURE" in svgfile[trackBack]):
svgfile[trackBack] = svgfile[trackBack].replace("PROCEDURE","FUNCTION")
# print(svgfile[trackBack])
break
#print(workingOn)
return svgfile
def writeTextFile(svgfile, name = "/Users/andrew/PycharmProjects/Experiments/psudocode/pythonfixed.py"):
"""
Writes the final list to a text file.
Adds a newline character (\n) to the end of every sublist in the file.
Then writes the string to the text file.
"""
name = name[0:len(name)-3] + "-Psudocode" + name[(len(name)-3) : len(name)]
file = open(name, 'w')
mainstr = ""
for count in range(0, len(svgfile)):
#print(svgfile[count])
if ("PROCEDURE" in svgfile[count] and "BEGIN" not in svgfile[count] and "END" not in svgfile[count]):
svgfile.insert(count+1,"BEGIN PROCEDURE")
if ("FUNCTION" in svgfile[count] and "BEGIN" not in svgfile[count] and "END" not in svgfile[count]):
svgfile.insert(count+1,"BEGIN FUNCTION")
for i in range(0, len(svgfile)):
mainstr = mainstr + svgfile[i] + "\n"
file.write(mainstr)
file.close()
print("")
print("------------------------")
print("Psudocode file generated")
print("The file can be found at " + name)
print("------------------------")
print("")
def indentationFinder(svgfile, linesToAvoid):
"""
This function traces through the entire file tracing indentation to find where structures start and end.
The protocol for the lists is as follows
[WordSearchingFor, WordReplaceWith, EmptyList, EmptyList, AddANewLineAfter?]
The 2 emtpy lists are used to store the location and line number of where the items are found, which is passed onto the replacing function
A basic description of what is going on
We define the list of lists, searchFor which holds the stuff we are going to look for.
We then, using a for loop iterate through every line.
Inside that loop we have a second for loop which iterates through all the objects in searchFor.
Basically we are checking to see if any of the words are on the current line, 1 word at a time from searchFor.
If we find a word and it isn't a line we are meant to be avoiding (maybe it has a multiline comment?) we move down
We assign distance to how many characters in from the left the found word was, this will be the level in we are tracing with.
The program then searches each line that follows to see if it can find any character to the left (or equal) to distance on its current line.
If it finds and first character is else, # or ~~~ it ignores those lines.
If it isn't any of those special characters that has been found first, we can assume this structure has finished as it has unindentected.
We write the line number and how far in the structure started to the 2 empty lists inside the sublist.
Finally we return the searchFor list, hopefully with lots of line numbers and indentation distances.
"""
searchFor = [["if", "ENDIF", [], [], False], ["def", "END PROCEDURE", [], [] , True ], ["class", "ENDCLASS", [], [] , True ], ["WHILE", "ENDWHILE", [], [] , False ], ["FOR", "ENDFOR", [], [] , True]]
#print("CLEAR")
svgfile.append("print('converted from python source code')")
#for count in range(len(svgfile)):
for count in range(len(svgfile)-1,-1,-1): #Iterate through each line in the text file
for i in range(len(searchFor)): #For each line in text file, iterate through clues
currentClue = searchFor[i][0]
found = svgfile[count].find(searchFor[i][0]) #Check if the current line in the file has the required string
printLinePattern = re.compile('^\".*\"$')
printLines = printLinePattern.match(svgfile[count])
if (not (found == -1)) and not (count in linesToAvoid)and ("set" not in svgfile[count].lower()) and ("print" not in svgfile[count].lower()) and ("send" not in svgfile[count].lower() and printLines==False):
#print("found an indent on line " + str(count))
#print(svgfile[count])
#print("found is " + str(found))
#print (svgfile[count])
#time.sleep(0.1)
distance = found #Distance is basically how many characters it is indented in
lineDone = False
for a in range(count+1, len(svgfile)): #Iterate through rest of the lines
f = False
for x in range(0, distance + 1):
if distance == 0:
pass
try:
if not (svgfile[a][x] == " "):
if svgfile[a][distance:(distance+4)] == "else":
debug("else found" + str(a))
f = False
elif (svgfile[a][distance:(distance+1)] == "#"):
debug("# found "+ str(a))
f = False
elif (svgfile[a][distance:(distance+3)] == "~~~"):
debug(svgfile[a][distance:(distance+4)])
f = False
else:
f = True
except:
debug("error")
if f:
if lineDone == False:
searchFor[i][2].append(a)
searchFor[i][3].append(distance)
lineDone = True
break
debug("HI")
return searchFor
def rebuildList(svgfile, searchFor, toRemove = []):
"""
Rebuild list takes the current text file, the searchFor list and an option toRemove.
toRemove just stores line numbers of any lines we need to remove.
The subroutine goes line by line through the text file passed to it (in a list)
Then for each line, checks if anything in the searchFor list needs replaced.
If it is happy, it will append it to the new text file list.
"""
svgfile2 = []
for i in range(0, len(svgfile)): #iterate through the text file
for count in range(0, len(searchFor)): #Iterate through each of the words to be replaced
if i in searchFor[count][2]: #Checks if this line is being requested
for x in range(0, len(searchFor[count][2])): #If it is, lets iterate through and find the exact reference
if searchFor[count][2][x] == i: #Checks if it is the exact reference
workingWith = x
indented = ""
for z in range(0, searchFor[count][3][x]):
indented = indented + " "
svgfile2.append(indented + searchFor[count][1])
if searchFor[count][4]:
svgfile2.append("")
if not (i in toRemove):
svgfile2.append(svgfile[i])
#for i in range(0, len(svgfile2)):
#debug(svgfile2[i])
return svgfile2
def removeLines(svgfile, clues):
"""
Removes blank lines from text file
"""
toRemove = []
for i in range(0, len(svgfile)):
for cl in range(0, len(clues)):
found = svgfile[i].find(clues[cl])
if found != (-1):
toRemove.append(i)
return toRemove
def convertStringToList(string):
"""
Really simply converts a string to a list
"""
theList = []
for x in range(0, len(string)):
theList.append(string[x])
return theList
def convertListToString(theList):
"""
Really simply converts a list to a string
"""
string = ""
for x in range(0, len(theList)):
string = string + theList[x]
return string
def removeEndBit(theLine, toRemove):
"""
Removes characters at the end of any lines
"""
theLine = convertStringToList(theLine)
for i in range(len(theLine) -1, 0, -1):
if theLine[i] == toRemove:
theLine.pop(i)
break
return convertListToString(theLine)
def main(filename):
print("Now working on " + filename)
svgfile = getTextFile(filename) #Converts text file to a list of lists
svgfile = removeN(svgfile) #Removes \n (a special escape character that means newline)
svgfile = blankLineRemover(svgfile) #Removes all blank lines from the file, makes easier to work with
linesToAvoid = multiLineCommentTracker(svgfile) #Adds lines to be ignored by the replacers, mainly just multiline comments
print("Searching through file, this may take a while")
clues = [["elif", "~~~~~~"],]
for i in range(0, 6):
svgfile = wordReplacer(svgfile, linesToAvoid, clues) #Replaces every use of elif with ~~~~ to avoid confusing the indentation finder laster
searchfor = indentationFinder(svgfile, linesToAvoid) #Traces indentation through the file. It finds the start and end of structures, e.g. functions, loops etc. Returns a list containing locations of all of the items being searched for in the file.
svgfile = rebuildList(svgfile, searchfor, removeLines(svgfile, ["debug", "info", "warning", "#print"])) #Rebuilds the new text file based off the changes from indentationFinder
linesToAvoid = multiLineCommentTracker(svgfile)
#All these functions simply replace words with new words. They must be repeated as the wordReplacer function only counts the first find on a line.
for x in range(0, 10):
svgfile = wordReplacer(svgfile, linesToAvoid, [["def", "PROCEDURE"], ["self.", " "], ["return", "RETURN"], ["else:", "ELSE:"], ["==", "|"], ["if", "IF"], ["or", "OR"], ["and", "AND"],["and", "AND"], ["class", "CLASS"] ])
for x in range(0, 5):
svgfile = wordReplacer(svgfile, linesToAvoid, [["self.", " "],], False)
for x in range(0, 10):
svgfile = wordReplacer(svgfile, linesToAvoid, [["=", "TO"], ["~~~~~~", "ELSEIF"]])
for x in range(0, 10):
svgfile = wordReplacer(svgfile, linesToAvoid, [["|", "="],])
svgfile = wordReplacer(svgfile, linesToAvoid, [["OUTPUT(", "SEND ", ")"]], False, True)
svgfile = wordReplacer(svgfile, linesToAvoid, [["<- ?", "= ?"]])
svgfile = wordReplacer(svgfile, linesToAvoid, [["<- ?", "= ?"]])
del svgfile[-1]
writeTextFile(svgfile, filename) #Finally write the new text file!
#-----------------------------------Main program----------------------------------------
#-----------------------------------Main program----------------------------------------
#-----------------------------------Main program----------------------------------------
main(pythonFile)
print("")
print("")
print("----------------")
print("Process complete")
print("----------------")
|
#Q1) Take an input year from user and decide whether it is a leap year or not.
year=int(input("Enter The Year :- "))
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("%d is a leap year\n" %(year))
else:
print("%d is not a leap year\n" %(year))
else:
print("%d is a leap year\n" %(year))
else:
print("%d is not a leap year\n" %(year))
#Q2)Take length and breadth input from user and check whether the dimensions are of square or rectangle.
l=int(input("Enter Length :- "))
b=int(input("Enter Breadt :- "))
if (l==b):
print("The Dimensions are of Square\n")
else:
print("The Dimensions are of rectangle\n")
#Q3)Take the input age of 3 people and determine oldest and youngest among them.
x= int(input("Enter First Age :- "))
y=int(input("Enter Second Age :- "))
z=int(input("Enter Third Age :- "))
if (x>y and x>z):
print(" \nX is the Oldest\n")
else:
print(" X is the Youngest\n")
if (y>x and y>z):
print(" Y is the Oldest\n")
else:
print(" Y is the Youngest\n")
if (z>x and z>y):
print(" Z is the Oldest\n")
else:
print(" Z is the Youngest\n")
#Q4) Ask user to enter age, sex ( M or F ), marital status ( Y or N ) and then using following rules print their place of service.
age=(input("Enter Age :- "))
gen=input("Enter Gender :- ")
stat=input("Enter Marital Status :- ")
if(age.isnumeric()==1):
age=int(age)
if( gen=='F' or gen=='f'):
print("Employment in the Urban Areas")
elif(gen=='M' or gen=='m' and age>=20 and age<=40):
print("Emplyment can be anywhere")
elif(gen=='M' or gen=='m' and age>=40 and age<=60):
print("Employment in the Urban Areas\n")
else:
print("ERROR\n")
#Q5) A shop will give discount of 10% if the cost of purchased quantity is more than 1000.Ask user for quantity Suppose, one unit will cost 100. Judge and print total cost for user.
qty=int(input("Enter The Quantity of the Item"))
if(qty>1000):
cost=qty*100
dis=cost*0.1
tcost=cost-dis
print("The Total Cost is :- %d" %(tcost))
#<-----LOOPS----->
# Q.1- Take 10 integers from user and print it on screen.
for i in range (1,11):
num= (int(input("Enter Integers :- ")))
print(num)
#Q.2- Write an infinite loop.An infinite loop never ends. Condition is always true.
i=1
while(i>0):
print(i)
i=i+1
#Q.3- Create a list of integer elements by user input. Make a new list which will store square of elements of previous list.
list=[]
list_sq=[]
for i in range (1,6):
num=int(input("Enter Integers :- "))
list.append(i)
list_sq.append(i*i)
print(list)
print(list_sq)
#Q.4- From a list containing ints, strings and floats, make three lists to store them separately
list=[1,2,"python",12,"code",3,4,55,1.23,0.112,98.8976]
list_int=[]
list_str=[]
list_float=[]
for i in list:
if(isinstance(i,int)):
list_int.append(i)
elif(isinstance(i,str)):
list_str.append(i)
elif(isinstance(i,float)):
list_float.append(i)
print(list_int)
print(list_str)
print(list_float)
#Q.5- Using range(1,101), make a list containing only prime numbers.
print("Prime Numbers Between 1 and 101 are\n")
for num in range(1,101):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
#Q.6- Print the following patterns:
for i in range (0,4):
for j in range (0,i+1):
print("*" , end="")
print()
#Q.7- Take inputs from user to make a list. Again take one input from user and search it in the list and delete that element, if found. Iterate over list using for loop.
list=[]
for i in range (1,11):
num=int(input("Enter Elements :- "))
list.append(num)
print("List Before Deletion\n",list)
x=int(input("Enter Element to be Searched and deleted :- "))
for i in list:
if(x==i):
list.remove(i)
else:
print("List after Deletion\n",list)
|
import turtle
n=int(input("想畫幾邊形"))
hello=turtle.Turtle()
for i in range(n):
hello.forword(100)
hello.left(360/n)
while i<100:
hello.forword(10+i)
|
# coding: utf-8
"""Count words."""
def count_words(s, n):
"""Return the n most frequently occuring words in s."""
# TODO: Count the number of occurences of each word in s
# TODO: Sort the occurences in descending order (alphabetically in case of ties)
# TODO: Return the top n most frequent words.
splited=s.split()
listed=[]
for i in set(splited):
listed.append((i,splited.count(i)))
sort_0=sorted(listed,key=lambda x:x[0])
sort_1=sorted(sort_0,key=lambda x:x[1],reverse=True)
top_n=sort_1[:n]
return top_n
def test_run():
"""Test count_words() with some inputs."""
print(count_words("cat bat mat cat bat cat", 3))
print(count_words("betty bought a bit of butter but the butter was bitter", 3))
if __name__ == '__main__':
test_run()
|
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def findPath( root, path, k):
if root is None:
return False
path.append(root.key)
if root.key == k :
return True
if ((root.left != None and findPath(root.left, path, k)) or (root.right!= None and findPath(root.right, path, k))):
return True
path.pop()
return False
#########defining Tree############
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.left.left.left = Node(8)
root.left.left.right = Node(9)
root.left.right.left = Node(10)
root.left.right.right = Node(11)
root.right.left.left = Node(12)
root.right.left.right = Node(13)
root.right.right.left = Node(14)
root.right.right.right = Node(15)
##############EOD tree###############
path1 = []
findPath( root, path1, 8)
#print(path1)
path2 = []
findPath( root, path2, 11)
#print(path2)
l=0
n = len(path1)
for i in range(n):
if path1[n-i-1] != path2[n-1-i]:
l = l+1
print("generation gap between",8,'',11,"is = ",l)
print("where 0=same node 1 = sibling 2 = cousin 3 = 2nd cousin and so on")
print("Path length between the 2 nodes = ",2*l)
|
#赋值初始化值
list2=[]
list2=[1,2,3,4,5,"a",'b']
#print(list2[10],len(list2))#如果列表内数字大于列表的(长度-1),报错:IndexError: list index out of range
print(list2[1],list2[-1])#输出是2,b;当列表后数字为负数表示从右往左数,为正数是则为从左往右数。
list2.append(100)
print(list2)
list2.append([9,30,45])
print(list2)
list2.pop(0)#删除数组中第一个元素
print(list2)
#多维list
a=[[1,33],[2,44,55],[3]]
a[0][0]
a[1][1]#第一个数字代表整个大数组中小数组的位置,后一个数字代表元素在小数组中的位置
print(a[0][0],a[1][1])
"""
list3=[]
i=0
while i<100:
list3.append(1)
i=i+1
print(list3) #给列表赋值100个相同的元素"""
list_a=[1,2]
list_b=[3,4]
print(list_a+list_b) #"+"是连接功能,结果为[1,2,3,4]
#更新列表值
aa=[1,2,3]
aa[1]=10
print(aa)
#字典初始化
#一维
dict_a={}
dict_a={"name":"zhaoanxiang","age":24,"like":"唱、跳"}
name=dict_a["name"]
age=dict_a["age"]
like=dict_a["like"]
print(name,age,like)
#print(dict_a,type(dict_a))
#多维
dict_b={"message":{"name":"zhaoanxiang","age":24}}
print(dict_b["message"]["age"])
#print(dict_b["message"]["age1"])#如果key错误会报错
age=dict_b.get("message").get("age")
age=dict_b.get("message").get("age1")#不会报错,会报none提示没有这个
print(age)
dict_b["time"]="7月"
print(dict_b)
dict_b["time"]="7.27"
print(dict_b)
dict_b.pop("time")
print(dict_b)
#初始化
tuple_a=()
tuple_a=(1,2,3)
#tuple_a[0]=2 # 元组赋值过后不可以更改
print(tuple_a[0])
#初始化一个集合
set_a=set()
list_c=[1,2,3,4,5,6]
set_a=set(list_c)
print(set_a)
list_d=[1,2,3,4,5,6,7,2,1,]
set_b=set(list_d)
list_h=list(set_b)
print(set_b) #set()能去除列表中重复元素
print(list_h)
listA=[1,2,3,4,5]
listB=[1,2,4,6]
ret=list(set(listA).difference(set(listB)))
print(ret)
ret=list(set(listA).union(set(listB)))
print(ret)
ret=list(set(listA).intersection(set(listB)))
print(ret)
#条件语句
if True:
print(1)
if True:
print(2)
if "a" not in "acsfv":
print(3)
else:
print(4)
while True:
input_c=input("请输入一个成绩")
input_c=float(input_c)
if input_c>100 or input_c<0:
print("输入数据错误")
elif input_c>=90:
print("优秀")
elif input_c>=80:
print("良好")
elif input_c>=70:
print("一般")
elif input_c>=60:
print("及格")
elif input_c==59:
print("真可惜,差一分就及格了")
else:
print("不及格")
|
class Person:
def __init__(self, age, weight, height, first_name, last_name, catch_phrase):
self.age = age
self.weight = weight
self.height = height
self.first_name = first_name
self.last_name = last_name
self.catch_phrase = catch_phrase
user = Person(25, 80, 177, "Jon", "Snow", "You know nothing, Jon Snow")
print(user.catch_phrase)
print(user.weight)
print(f'You are {user.weight} kilos')
weight = int(input("How many kilos are you?: "))
height = float(input("What height are you in meters? "))
height_squared = height * height
pounds = weight * 2.2
poundsr = round(pounds,2)
print(f'You are {poundsr} pounds')
stone = pounds / 14
stoner = round(stone,2)
BMI = weight / height_squared
print(f'You are {stoner} stone')
BMIR = round(BMI,2)
print(f'Your BMI is {BMIR}')
|
day= input().split()
lis1={"Monday","Tuesday","Wednesday","Thursday","Friday"}
lis2={"Saturday","Sunday"}
i=0
n=len(day)
for i in range(n):
if day[i] in lis1:
print("no")
elif day[i] in lis2:
print("yes")
|
# A pure function does not have side effects
# functools is a toolbelt that can be used for functional tools that comes with python
from functools import reduce
# lambda expressions
# a lambda experssion is a function that is only going to be used once
# lambda param: action(param)
my_list = [1,2,3]
your_list = [10,20,30]
# def multiply_by2(li):
# new_list = []
# for item in li:
# new_list.append(item*2)
# return new_list
# return li*2
# print(multiply_by2(my_list))
# map
# map(action, data we want the action to take place on)
# map will loop through the list and then use the function multiply_by2 as the action
# list() turns it into a new list
# print(list(map(multiply_by2, my_list)))
# lambda version
print('lambda', list(map(lambda item: item*2, my_list)))
# FILTER
# filter(action, data we want the action to take place on)
def only_odd(item):
# true or false
return item % 2 != 0
# filter checks if the item is true or false, by using the action, and then adds the true to a new list
print(list(filter(only_odd, my_list)))
# ZIP
# zip takes to lists and puts them together in a tuple.
# [(mylist[0], your_list[0]), (mylist[1], your_list[1])], (mylist[2], your_list[2])
#IT CAN BE MORE THAN 2
print(list(zip(your_list, my_list)))
# REDUCE
def accumulator(acc, item):
print(acc, item)
return acc + item
print(reduce(accumulator, my_list, 10))
print('The Original My List', my_list)
print('The Original Your List', your_list)
|
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
plt.style.use('ggplot')
fig, ax = plt.subplots(figsize=(5, 3))
ax.set(xlim=(-3, 3), ylim=(-1, 1))
x = np.linspace(-3, 3, 91)
t = np.linspace(1, 25, 30)
X2, T2 = np.meshgrid(x, t)
sinT2 = np.sin(2 * np.pi * T2 / T2.max())
F = 0.9 * sinT2 * np.sinc(X2 * (1 + sinT2))
line = ax.plot(x, F[0, :], color='k', lw=2)[0]
def animate(i):
line.set_ydata(F[i, :])
anim = FuncAnimation(
fig, animate, interval=100, frames=len(t) - 1)
plt.draw()
plt.show()
|
'''print("This is simulating the TNOR gate\n")
print("Enter the following values : \n\n")
A1=int(input("Enter A1 : "))
A2=int(input("Enter A2 : "))
B1=int(input("Enter B1 : "))
B2=int(input("Enter B2 : "))
C1=int(input("Enter C1 : "))
C2=int(input("Enter C2 : "))
L=1'''
def blockpos(L, p1, p2):
o=0
if (L==0): #L=00
o= 0
if (p1 == 0 and p2 == 0):
o = 0
if (p1 == 1 and p2 == 1):
o = L
if (L==1): #L=01
if (p1 == 0 and p2 == 1):
o = 1
if (p1 == 1 and p2 == 0):
o = 0
if (L == 2): # L=10
if (p1 == 0 and p2 == 1):
o= 0
if (p1 == 1 and p2 == 0):
o = 2
if (L == 3): # L=11
if (p1 == 0 and p2 == 1):
o = 1
if (p1 == 1 and p2 == 0):
o = 2
return o
def blockneg(L, p1, p2):
p1=complementer(p1)
p2=complementer(p2)
if (L==0): #L=00
o=0
if ( p1 == 0 and p2 == 0):
o = 0
if (p1 == 1 and p2 == 1):
o = L
if (L==1): #L=01
if (p1 == 0 and p2 == 1):
o = 1
if (p1 == 1 and p2 == 0):
o = 0
if (L == 2): # L=10
if (p1 == 0 and p2 == 1):
o= 0
if (p1 == 1 and p2 == 0):
o = 2
if (L == 3): # L=11
if (p1 == 0 and p2 == 1):
o = 1
if (p1 == 1 and p2 == 0):
o = 2
return o
def beamcombiner (A,B):
sum=0
if A!=B:
sum=3
if A==0:
sum= B
if B==0:
sum= A
if A==3 or B==3:
sum= 3
if A==B:
sum=A
return sum
def complementer(p):
if p==1:
return 0
if p==0:
return 1
def displayer(R):
if R == 0:
print('00')
if R == 1:
print('01')
if R == 2:
print('10')
if R == 3:
print('11')
def beamsplitter(L):
if L == 0:
P1=0
P2=0
if L == 1:
P1 = 0
P2 = 1
if L == 2:
P1 = 1
P2 = 0
if L == 3:
P1 = 1
P2 = 1
return P1,P2
'''A0=blockpos(L,A1,A2) #Block A
B0=blockpos(L,B1,B2) #Block B
sum = beamcombiner(A0,B0)
v0=subblockspos(L,sum)#Block V
w0=subblockspos(L,sum)#Block W
C0=blockpos(v0,C1,C2) #Block C
x0=subblocksneg(L,w0) #Block X
y0=blockneg(x0,C1,C2) #Block Y
z0=subblockspos(v0,C0) #Block Z
R=beamcombiner(y0,z0)'''
|
class ListQ:
def __init__(self):
self.items = []
def isEmpty(self):
if self.items == []:
return True
else:
return False
def put(self, item):
self.items.insert(-1,item)
def get(self):
return self.items.pop(0)
"""class Sort(ListQ):
def __init__(self, unsortedList):
self.unsortedList = unsortedList
def magi(unsortedList):
# [3 1 4 2 5] [12 1 8 2 10 3 7 4 9 5 11 6 13]
unsortedList.put()
unsortedList[0] = get()"""
def sort(x):
def main():
question = input("Du har 5 kort. I vilken ordning vill du laegga dessa?")
numbers = question.split()
x = ListQ()
for i in numbers:
x.put(i)
print(x.isEmpty())
d = Sort(x)
print(d.magi())
# print("De kommer ut i ordningen: " + x[0] + x[1] + x[2] + x[3] +)
#if __name__== "main":
#Skapar en queue, init säger att den ska skapas tom. isEmpty kollar att den är tom.
#q = ListQ()
# if q.isEmpty():
# print("q.isEmpty() ger raett svar.")
# else:
# print("q.isEmpty() ger FEL svar".)
main()
|
# Problem 9 form Project Euler
# The goal is to find a pythagorean triple with a sum of 1000
#Authored by Steve Saltekoff on Fri 21 2015
def pythtriptester(a,b,c,n):
if a+b+c == n:
return 1,a,b,c
else:
return 0,a,b,c
def pythtrip(j,k,n):
a = j**2 + k**2
b = 2*j*k
c = j**2 - k**2
z = pythtriptester(a,b,c,n)
return(z)
def PythagTripPerim(n):
j = 2
k = 1
while j+k <= 2*j :
z = pythtrip(j,k,n)
if k!=j:
k += 1
else:
j += 1
k = 1
if z[0] == 1 and z[3] != 0:
return z[1],z[2],z[3]
if z[1]>n:
return 0
|
#Project Euler, Problem 5
#The goal is to find the value of the smallest number that is evenly divisible by the positive integers 1 through 20.
def primefactors(n):
'''find the prime factors of a number, not including 1 and itself'''
pdivs = []
i = 3
if n == 1 and i <= n**(1/2):
pdivs = 1
return pdivs
if n == 2:
pdivs = [1,2]
return pdivs
while n != 1:
while n%2 == 0:
pdivs += [2]
n //= 2
while n%i == 0:
pdivs += [i]
n //= i
i += 2
if len(pdivs)==0:
pdivs = [n]
return pdivs
return pdivs
def sortncount(n):
'''pass an array through to be sorted and counted as a dictionary'''
dictr = {}
for element in n:
if element in dictr:
dictr[element] += 1
else:
dictr[element] = 1
return dictr
def highestfreq(n):
'''returns a dictionary consisting of keys that are in each dictionary, and their highest frequency'''
dictr = {}
for x in n:
for p,b in x.items():
#print(p,b)
if p not in dictr:
dictr[p] = 1
if dictr[p]<b:
dictr[p] = b
return dictr
def powerdict(n):
'''This raises each dict key to a power of its value'''
y = 1
for x in k:
y *= x**k[x]
return y
l = []
for x in range(1,21,1):
l += [sortncount(primefactors(x))]
k = highestfreq(l)
print(powerdict(highestfreq(l)))
|
"""
Problem
=======
For every number i in range 1 to n, return the sum of the integer portions
of the equation i * sqrt(2).
S(n) = floor(sqrt(2)) + ... + floor(n * sqrt(2))
Example:
S(3) = floor(sqrt(2)) + floor(2 * sqrt(2)) + floor(3 * sqrt(2))
= 1 + 2 + 4
= 7
As numbers can be as large as 10^100 an iterative approach will not work.
References
==========
https://en.wikipedia.org/wiki/Beatty_sequence
http://mathworld.wolfram.com/BeattySequence.html
https://mathbitsnotebook.com/Algebra2/Sequences/SSGauss.html
https://www.wolframalpha.com
Beatty Sequences
================
"Sometimes, it's easier to take a step back and concentrate not on what you
have in front of you, but on what you don't."
This phrase is actually a surprising help in solving this particular
problem as it points us towards Beatty sequences (at least I felt it did).
A Beatty sequence (see references) is defined as the sequence of integers
found by taking the floor of the positive multiples of a positive
irrational number.
A positive irrational number r generates the Beatty sequence:
Br = |_r_|, |_2r_|, |_3r_|, ..., where |_x_| is the floor function
If r > 1, then s = r / (r - 1) is also a positive irrational number.
These two numbers satisfy the equation 1 / r + 1 / s = 1.
The two Beatty sequences these numbers generate are:
Br = (|_nr_|) for n >= 1 and
Bs = (|_ns_|) for n >= 1
These two sequences are complimentary, meaning that together they contain
every positive integer without repetition. In other words, every positive
integer belongs to exactly one of these two sequences.
Therefore:
(|_nr_|) and (|_ns_|) for n >= 1 partition N
As a matter of interest, OEIS provide numerous mathematical sequences, two
of which are of particular relevance to us:
Parameter OEIS Series
---------------------------------------------------------------
a = sqrt(2) A001951 1, 2, 4, 5, 7, 8, 9, 11, 12, ...
b = 2 + sqrt(2) A001952 3, 6, 10, 13, 17, 20, 23, 27, 30, ...
Gauss Formula
=============
Gauss's formula defines the sum, Sn of n terms of an arithmetic series, as:
Sn = n * (a1 + an) / 2, where n is the number of terms and a1 and an are
the first and last terms of the sequence
Solution
========
Using the definition of Beatty sequences above, we know that:
If r = sqrt(2), then:
r > 1 is true (see above)
Therefore:
s = r / (r - 1) (see above)
= sqrt(2) / (sqrt(2) - 1)
= 2 + sqrt(2)
We also know that:
(|_nr_|) and (|_ns_|) for n >= 1 partition N
Therefore:
(|_nr_|) = N - (|_ns_|)
So, if we let m = floor(n * r), then:
S(r, n) = m * (m + 1) / 2 - S(s, floor(m / s))
While the equation produces the correct results, it still only passes 3/10
tests, which we'll assume is down to the recursion depth and/or the
precision.
To tackle the precision we'll try using Decimal instead of float and adjust
the precision of the decimal module accordingly.
Next, we'll look at the simplifying the equation some more and specifically
try to find a way to increase the step sizes, in order to reduce the number
of recursions required.
So, if we let n' = floor(m / s), then:
n' = floor(m / s)
= floor(m / (r / (r - 1)) (see above)
= floor(m * (r - 1) / r)
= floor((m * r - m)) / r)
= floor(m - m / r)
And, we also know s = 2 + sqrt(2), so:
S(s, n) = S(2 + sqrt(2), n')
= S(2, n') + (sqrt(2), n')
So, simplifying with gauss's formula, we get:
S(s, n) = n' * (n' + 1) + (sqrt(2), n')
Therefore, our equation is now looking like:
m = floor(n * r)
n' = (m - (m / r))
S(r, n) = m * (m + 1) / 2 - n' * (n' + 1) - S(r, n')
TODO:
m and n' can be simplified further, but the equation works successfully as
is and manages to pass all tests.
"""
from decimal import Decimal, getcontext
getcontext().prec = 101 # Allow for at least 100 digits
SQRT2 = Decimal(2).sqrt() # Use decimal for better precision
def beatty(n, r=SQRT2):
"""
Return the sum of the integer portions of i * r for all numbers in the
range 1..n inclusive.
"""
if n < 1:
return 0
# Calculate m and n'
m = int(n * r)
n_prime = int(m - (m / r))
# m * (m + 1) / 2 - S(s, n')
return (
m * (m + 1) // 2
- n_prime * (n_prime + 1)
- beatty(n_prime, r) # Recurse from n'
)
def solution(str_n):
n = int(str_n)
# Initial bounds check
if n < 1 or n > 10**100:
return str(0)
# Special case for n = 1
if n == 1:
return str(1)
# Return the sum of the Beatty sequence S(sqrt(2), n)
return str(beatty(n, SQRT2))
|
# se define la clase robot
import random
class Robot:
x = 0
y = 0
max_x = 0
max_y = 0
min_x = 0
min_y = 0
def __init__ (self, max_x, max_y):
self.x = random.randint (0, max_x - 1)
self.y = random.randint (0, max_y - 1)
self.max_x = max_x
self.max_y = max_y
# mueve el robot a la derecha una unidad y
# verifica que no se puede salir de la maya
def derecha (self):
if self.x < self.max_x - 1:
self.x += 1
# mueve el robot a la izquierda una unidad
def izquierda (self):
if self.x > self.min_x:
self.x -= 1
# mueve el robot arriba una unidad
def arriba (self):
if self.y < self.max_y - 1:
self.y += 1
# mueve el robot para abajo una unidad
def abajo (self):
if self.y > self.min_y:
self.y -= 1
def mueve_hor (self):
mov_hor = random.randint (1, 2)
if mov_hor % 2 == 0:
self.derecha ()
else:
self.izquierda ()
def mueve_vert (self):
mov_vert = random.randint (1, 2)
if mov_vert % 2 == 0:
self.arriba ()
else:
self.abajo ()
def __str__ (self):
return ("x = %d, y = %d, min_x = %d, min_y = %d, max_x = %d, max_y = %d" %
(self.x, self.y, self.min_x, self.min_y, self.max_x, self.max_y ))
|
"""word count"""
# recieve the text
# split to words and save in a list
# loop thro the list conting and saving the out
def words(words):
try:
words = words.split()
dic_out = {}
for word in words:
if word.isdigit():
if int(word) in dic_out:
dic_out[int(word)] = dic_out[int(word)]+1
else:
dic_out[int(word)] = 1
else:
if word in dic_out:
dic_out[word] = dic_out[word]+1
else:
dic_out[word] = 1
return dic_out
except Exception:
return 'invalid'
print(words("hello there we hello we are people from planet earth 1 2 2 3")) |
#This is a simple Python program to print the weather at the user's location using their input city.
#Also writes the data onto a file called weatherInfo.txt
#Written by Suryanarayan Menon A (github.com/SuryaNMenon) for project submission for Shape-AI's free bootcamp.
import requests
import sys
from datetime import datetime
my_api_key = '0635eb506ca1dcd1cf426726521f8a04' #API Key from OpenWeather
my_location = input("Enter city name: ")
complete_api_link = "https://api.openweathermap.org/data/2.5/weather?q="+my_location+"&appid="+my_api_key
api_link = requests.get(complete_api_link)
api_data_json = api_link.json()
city_temp = ((api_data_json['main']['temp']) - 273.15)
weather_desc = api_data_json['weather'][0]['description']
humid = api_data_json['main']['humidity']
wind_spd = api_data_json['wind']['speed']
date_time = datetime.now().strftime("%d %b %Y | %I %M %S %p" )
print("Welcome to the Simple Weather App!")
print("Weather Statistics for - {} || {}".format(my_location.upper(), date_time))
print("-------------------------------------------------------------")
print("Current Temperature: {:.2f} degree Celcius".format(city_temp))
print("Description about the weather: ", weather_desc)
print("Humidity: ", humid)
print("Wind speed: ", wind_spd, 'kmph')
#Saving weather info to a text file - using example of Trivandrum
original_stdout = sys.stdout
sys.stdout = open("weatherInfo.txt", "w")
print("Welcome to the Simple Weather App!")
print("Weather Statistics for - {} || {}".format(my_location.upper(), date_time))
print("-------------------------------------------------------------")
print("Current Temperature: {:.2f} degree Celcius".format(city_temp))
print("Description about the weather: ", weather_desc)
print("Humidity: ", humid)
print("Wind speed: ", wind_spd, 'kmph')
sys.stdout.close()
sys.stdout = original_stdout |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 19 14:36:18 2017
@author: James
"""
import numpy as np
from ecdf_func import ecdf
from pmf_func import pmf_plot
import matplotlib.pyplot as plt
samples = np.random.poisson(6, size=10000)
x, y = ecdf(samples)
pmf_plot(samples)
_ = plt.plot(x, y, marker='.', linestyle='none')
plt.margins(0.02)
_ = plt.xlabel('number of sucesses')
_ = plt.ylabel('CDF')
plt.show()
plt.close()
#relationship between Binomial and Poisson distributions
# Draw 10,000 samples out of Poisson distribution: samples_poisson
samples_poisson = np.random.poisson(10, size = 10000)
# Print the mean and standard deviation
print('Poisson: ', np.mean(samples_poisson),
np.std(samples_poisson))
# Specify values of n and p to consider for Binomial: n, p
n = [20, 100, 1000]
p = [0.5, 0.1, 0.01]
# Draw 10,000 samples for each n,p pair: samples_binomial
for i in range(3):
samples_binomial = np.random.binomial(n[i], p[i], size =10000)
# Print results
print('n =', n[i], 'Binom:', np.mean(samples_binomial),
np.std(samples_binomial))
#Probability of getting 7 or more no hitters
# Draw 10,000 samples out of Poisson distribution: n_nohitters
n_nohitters = np.random.poisson(251/115, size = 10000)
# Compute number of samples that are seven or greater: n_large
n_large = np.sum(n_nohitters >= 7)
# Compute probability of getting seven or more: p_large
p_large = n_large/10000
# Print the result
print('Probability of seven or more no-hitters:', p_large)
|
"""Customers at Hackbright."""
class Customer(object):
"""Ubermelon customer."""
# TODO: need to implement this
def __init__(self, f_name, l_name, email, password):
self.f_name = f_name
self.l_name = l_name
self.email = email
self.password = password
def __repr__(self):
"""Convenience method to show information about melon in console."""
return "<Customer: {f_name}, {l_name}, {email} >".format(
f_name=self.f_name, l_name=self.l_name, email=self.email)
def read_customers_from_file(filepath):
"""Reads customers from file and creates customer instances."""
customers = {}
for line in open(filepath):
(f_name, l_name, email, password) = line.strip().split("|")
customers[email] = Customer(f_name, l_name, email, password)
return customers
def get_by_email(email):
"""takes in an email, returns customer if they exist"""
return customers.get(email)
customers = read_customers_from_file('customers.txt')
|
'''Objects to assign scores to ranks in ranked voting systems such as Borda.
A rank scorer returns a list of numerical scores to be assigned to ranks given
by voters. This is the essence of Borda count system, and rank scorers capture
most of the variations there are in that system.
'''
import abc
from fractions import Fraction
from typing import List, Any
from numbers import Number
def select_padded(sequence: List[Any], n: int, pad_with: Any = 0) -> List[Any]:
'''Select n leading elements from sequence, padding with pad_with.
Padding with pad_with is used when sequence is not long enough to select
n elements.
'''
selected = sequence[:n]
if n > len(selected):
selected += [pad_with] * (n - len(selected))
return selected
class RankScorer(metaclass=abc.ABCMeta):
'''An abstract base class for rank scorers.
Rank scorers must provide a `scores()` method that returns a list of scores
based on the number of ranks given. They may also provide a
`set_n_candidates()` method that sets the total number of candidates
participating in the election, which might be relevant for computing the
rank scores. If this method is defined, it must be called before the
`scores()` method is called first.
'''
@abc.abstractmethod
def scores(self, n_ranked: int) -> List[Number]:
raise NotImplementedError
class Borda(RankScorer):
'''Borda rank scorer, corresponding to the original Borda count variant.
Assigns the `base` score to the candidate ranked last, and one point more
for each higher rank.
This rank scorer needs to be initialized by the :func:`set_n_candidates()`
before calling :func:`scores()`.
:param base: The score to assign to the candidate ranked last. For the
truly original Borda, this equals to 1; some variants set it to zero,
and thus set the score for the first rank to the number of candidates
minus one.
'''
def __init__(self, base: int = 1):
self.base = base
self._scores = None
self.n_candidates = None
def set_n_candidates(self, n_candidates: int) -> None:
'''Set the total number of candidates that could be ranked.
This helps to account for rankings that do not rank all candidates.
:param n_candidates: The total number of candidates that could be
ranked on any ballot (i.e. the number of candidates participating
in the election in the particular constituency).
'''
self.n_candidates = n_candidates
top_score = self.n_candidates + self.base - 1
self._scores = [
top_score - rank
for rank in range(self.n_candidates)
]
def get_n_candidates(self) -> int:
return self.n_candidates
def scores(self, n_ranked: int) -> List[int]:
'''Return the scores for the first n_ranked ranks.
This gives (number of candidates + base - 1 - rank) for ranks running
from 0 (best rank) to n_ranked.
:param n_ranked: Number of ranks to be returned. Equal to the length
of the output list.
:raises RuntimeError: If the scorer has not been initialized first by
calling ``set_n_candidates()``.
'''
try:
if n_ranked > self.n_candidates:
raise ValueError(f'cannot rank {n_ranked} out of maximum'
f' {self.n_candidates} candidates')
else:
return select_padded(self._scores, n_ranked)
except TypeError:
raise RuntimeError(
'scorer not initialized, call set_n_candidates() first'
)
class Dowdall(RankScorer):
'''Dowdall (Nauru) rank scorer.
Assigns the numbers of the harmonic series (1, 1/2, 1/3...) to
progressively lower ranks.
'''
def scores(self, n_ranked: int) -> List[Fraction]:
'''Return the scores for the first n_ranked ranks.
This gives `1 / (rank + 1)` for ranks running
from 0 (best rank) to n_ranked.
:param n_ranked: Number of ranks to be returned. Equal to the length
of the output list.
'''
return [Fraction(1, rank + 1) for rank in range(n_ranked)]
class Geometric(RankScorer):
'''A geometric progression rank scorer.
Assigns the numbers of a chosen inverse geometric progression
(e.g. 1, 1/2, 1/4... for 2) to progressively lower ranks.
:param base: Base of the geometric progression.
'''
# http://www.geometric-voting.org.uk/index.htm
def __init__(self, base: int = 2):
self.base = base
def scores(self, n_ranked: int) -> List[Fraction]:
'''Return the scores for the first n_ranked ranks.
This gives `1 / (2 ** rank)` for ranks running
from 0 (best rank) to n_ranked.
:param n_ranked: Number of ranks to be returned. Equal to the length
of the output list.
'''
return [Fraction(1, self.base ** rank) for rank in range(n_ranked)]
class ModifiedBorda(RankScorer):
'''Modified Borda count rank scorer.
In this system, the score for the highest rank is not constant (as is the
case for the vanilla Borda count), but is equal to the number of ranked
candidates; therefore, it encourages voters to rank many candidates.
'''
def scores(self, n_ranked: int) -> List[int]:
'''Return the scores for the first n_ranked ranks.
This gives `n_ranked - rank` for ranks running
from 0 (best rank) to n_ranked.
:param n_ranked: Number of ranks to be returned. Equal to the length
of the output list.
'''
return [n_ranked - rank for rank in range(n_ranked)]
class FixedTop(RankScorer):
'''A rank scorer with fixed score for the top rank.
Assigns scores progressively decreased by one until hitting zero.
:param top: The score for the top (best) ranked candidate on the ballot.
'''
def __init__(self, top: int):
self.top = top
def scores(self, n_ranked: int) -> List[int]:
'''Return the scores for the first n_ranked ranks.
This gives `max(top - rank, 0)` for ranks running
from 0 (best rank) to n_ranked.
:param n_ranked: Number of ranks to be returned. Equal to the length
of the output list.
'''
return [max(self.top - rank, 0) for rank in range(n_ranked)]
class SequenceBased(RankScorer):
'''A rank scorer with a predetermined sequence of scores.
This is used in many competitions (Eurovision, Formula One, etc.)
Assigns scores according to the given sequence until hitting zero, and zero
scores afterwards.
:param sequence: The scores for the top candidates on the ballot.
'''
def __init__(self, sequence: List[Number]):
self.sequence = sequence
def scores(self, n_ranked: int) -> List[Number]:
'''Return the scores for the first n_ranked ranks.
This gives values from the initial sequence, then zeros.
:param n_ranked: Number of ranks to be returned. Equal to the length
of the output list.
'''
return select_padded(self.sequence, n_ranked)
|
import string
def get_bigrams(in_text):
"""
Problem 7
This function takes string as input and returns bigram list
"""
text_list = in_text.split()
bigram_list = []
for i in range(len(text_list)-1):
bigram_list.append((text_list[i], text_list[i+1]))
return bigram_list
def get_clean_bigrams(in_text):
"""
Problem 7
This function takes string as input and returns lowercase bigram list
removing punctuations and numbers
"""
in_text = in_text.lower().translate(None, string.punctuation + string.digits)
return get_bigrams(in_text)
|
def part_1():
total = 0
with open('input.txt') as lines:
for line in lines:
total += int(line)
print(total)
def part_2():
changes = []
with open('input.txt') as lines:
for line in lines:
changes.append(int(line))
frequencies = {0}
curr_freq = 0
found = False
while not found:
for change in changes:
curr_freq += change
if curr_freq in frequencies:
found = True
break
frequencies.add(curr_freq)
print(curr_freq)
if __name__ == '__main__':
part_1()
part_2()
|
#!/usr/bin/env python3
from collections import OrderedDict
def count_islands(grid):
rows, cols = len(grid), len(grid[0])
delta = [(-1, 0), (1, 0), (0, -1), (0, 1)] # (up, down, left, right)
count = 0
for row in range(rows):
for col in range(cols):
if grid[row][col] == '1':
count += 1
# clear adjacent ones with BFS
queue = OrderedDict()
queue[(row, col)] = 1
while queue:
(r, c), _ = queue.popitem(False)
grid[r][c] = '0'
for i, j in ((r+i, c+j) for i, j in delta):
if 0 <= i < rows and 0 <= j < cols and grid[i][j] == '1':
queue[(i, j)] = 1
return count
grid = [input().split() for _ in range(int(input()))]
print('Total {:d} islands'.format(count_islands(grid)))
|
#!/usr/bin/env python3
def add_binary(a, b):
if len(a) < len(b):
a, b = b, a
result, carry = [], 0
for i in range(len(a)):
va = int(a[-(i+1)])
vb = int(b[-(i+1)]) if i < len(b) else 0
carry, v = divmod(va + vb + carry, 2)
result.append(v)
if carry:
result.append(carry)
return ''.join(map(str, reversed(result)))
a, b = input().split()
print(add_binary(a, b))
print(format(int(a, 2) + int(b, 2), 'b')) |
#!/usr/bin/env python3
def rotate(nums, k):
'''
rotate the array to the right by k steps, k is non-negative
'''
n = len(nums)
k = k % n
for i, j in [(0, n-k-1), (n-k, n-1), (0, n-1)]:
while i < j:
nums[i], nums[j] = nums[j], nums[i]
i, j = i+1, j-1
if __name__ == "__main__":
k = int(input())
nums = [int(n) for n in input().split()]
rotate(nums, k)
print(nums)
|
#!/usr/bin/env python3
def find_distance(matrix, key):
"""Find the distance of the nearest key for each cell
"""
if not matrix or not matrix[0]:
return matrix
rows, cols = len(matrix), len(matrix[0])
delta = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def shortest(matrix, row, col, key):
q = [(row, col, 0)]
while q:
r, c, d = q.pop(0)
if matrix[r][c] == key:
return d
else:
for i, j in delta:
nr, nc = r+i, c+j
if 0 <= nr < rows and 0 <= nc < cols:
q.append((nr, nc, d+1))
result = [[0] * cols for _ in range(rows)]
for r in range(rows):
for c in range(cols):
result[r][c] = shortest(matrix, r, c, key)
return result
if __name__ == '__main__':
matrix = [input().split() for _ in range(int(input()))]
print(find_distance(matrix, '0'))
|
#!/usr/bin/env python3
from collections import deque
def unlock(target, deadends):
delta = {str(i): [str((i+1) % 10), str((i-1) % 10)] for i in range(10)}
def next_steps(current):
for i, v in enumerate(current):
for n in delta[v]:
yield current[:i] + n + current[i+1:]
steps, visited = 0, set(deadends)
queue = deque([('0000', 0)])
while queue:
current, steps = queue.popleft()
if current == target:
return steps
elif current not in visited:
visited.add(current)
for n in next_steps(current):
queue.append((n, steps+1))
return -1
if __name__ == '__main__':
print('Unlock a lock with several circular wheels')
target = input("Target code: ")
deadends = input("Dead ends: ").split()
steps = unlock(target, deadends)
print(f'Total {steps:d} steps are needed')
|
#!/usr/bin/env python
import text_processor as tp
if __name__ == '__main__':
words = tp.get_paragraph_from_file(file_path='words.txt')
words = tp.remove_special_char(text=words)
words = tp.make_list_of_lower_word(paragraph=words)
paragraph = tp.get_paragraph_from_file()
paragraph = tp.remove_special_char(text=paragraph)
paragraph = tp.make_list_of_lower_word(paragraph=paragraph)
word_frequency = {}
for w in paragraph:
if w in words:
if w not in word_frequency.keys():
word_frequency[w] = 0
word_frequency[w] += 1
if len(word_frequency.keys()) > 0:
print("Found following occurrences...")
print("-------------------------------")
for key, value in word_frequency.items():
print("{k}\t\t{v}".format(k=key, v=value))
print("-------------------------------")
else:
print("No matching word found.")
|
import pygame
import surfaces
#at this point what you have to do
# is create a configuration for surface
# create the surface(configuration can be reused)
# create
class SpritePlane(object):
"""
SpritePlane is a wrapper for Surface but it also contains sprites
for collision detection , it is intended to be a frontend to Surface
and to be used instead. It can be treated as a surface normally
"""
def __init__(self, surface):
self.surface = surface
self.sprites = set()
def update(self):
se
class SpriteConfig(dict):
def __init__(self, surfacecfg = surfaces.SurfaceConfig(), collidable = True):
self["surface"] = surfacecfg
self["collidable"] = collidable
class Sprite(object):
#WARNING: self.cfg["surface"] should not be altered and is there for setup purposes ONLY, alter self.surface.cfg instead
def __init__(self, cfg, surface=None, parent = None):
self.cfg = cfg.copy()
if not surface:
self.surface = surfaces.Surface(cfg["surface"])
else:
self.surface = surface
#parent surface
def update(self):
self.surface.update()
|
import datetime
now = datetime.datetime.today()
print(now.day)
print(now.weekday())
my_birthady = datetime.datetime(1974, 6, 19)
print(my_birthady.weekday())
print(datetime.datetime.today() - my_birthady)
|
def pole_trapezu(a, b, h):
"""
:param a: podstawa 1
:param b: podstawa 2
:param h: wysokość
:return: pole powierzchni
"""
a = 3
b = 9
h = 6.5
pole_tr = ((a + b) / 2) * h
return ((a + b) / 2) * h
print(f"pole trapezu o podstawach: {a}, {b} i wysokości: {h} wynosi: {pole_tr}")
|
# kwadraty = [x**2 for x in range (1, 101)]
# print([i/10] for i in range(1,11))
# print = {(x, x**2, x**3) for x in range(1, 101)}
zbior_napisow = {'abc', 'ala ma kota', 'slowacki wielkim poetą był', 'supermen'}
print({x:len(x) for x in zbior_napisow})
print([x for x in range(1,101) if x%3==0])
|
data = [1, 2, 3, 4, 5, 6, 7]
def przytnij(data, start, stop):
resylt = []
for element in data:
if start(element):
if stop(element):
break
result.append(element)
return result
# print(lista, lambda x: x > 3)
# print(lista, lambda x: x == 6)
|
# try:
# plik = open("plik.txt")
# print(plik)
# except FileNotFoundError:
# print("ni ma")
# plik = open("plik.txt")
# print(plik.read())
# plik.close() #ważne: zamykamy jak już skończymy korzystać
with open("plik.txt") as plik:
#to jest dobra praktyka. Wewnątrz tego bloku mamy otwarty plik.txt pod zmienną 'plik'. #na końcu on jest automatycznie zamykany więc nie trzeba robić close.
# print(plik.read()) #zwraca cały plik jako 1 napis
# print(plik.readlines()) #zwraca listę wierszy
for wiersz in plik:
print(wiersz)
#zadanie:
print("zadanie")
try:
with open("plik.txt") as plik:
for _ in range(1):
plik.readline() #czyta pierwszy wiersz ale nic z nim nie robi
for i, wiersz in enumerate(plik,1):
print(f"{i:3}: {wiersz}", end="") #i:3 to jest formatowanie fstringa że robi 3 znaki odstępu
except FileNotFoundError:
print("ni ma")
|
import time
licznik = 0
while licznik <= 10:
print(licznik)
time.sleep(1)
licznik += 1
while licznik <= 100:
print(licznik)
time.sleep(0.5)
licznik += 1
while licznik <= 500:
print(licznik)
time.sleep(0.25)
licznik += 1
while licznik <= 1000:
print(licznik)
time.sleep(0.1)
licznik += 1 |
#zbiór (set) - nieuporządkowana kolekcja elementów o szybkim czasie wstawienia/usunięcia/sprawdzenia czy element istnieje
#zbiór przechowuje tylko unikalne element (bez powtórzeń), i w zupełnie losowej kolejności
zbior = {1, 2, 3, 3, 3}
print(type(zbior))
print(zbior)
pusty = set() # nie można inaczej tworzyć pustego zbioru, bo '{}' tworzy pusty slownik
print(pusty)
podzielne = set()
for i in range(20):
if i % 2 == 0:
podzielne.add(i) # a nie append tak jak w listach.
print(podzielne)
print(f"{6 in podzielne=}")
podzielne.remove(6)
print(f"{6 in podzielne=}")
print(podzielne)
print(len(set("ala ma kota"))) # ile różnych znaków jest w napisie 'ala ma kota, bo to jest zbiór
A = {1,2,3,4}
B = {3,4,5,6}
print(f"{A=}")
print(f"{B=}")
print(f"{A | B=}") # suma zbiorów - wszystkie elementy z A i B
print(f"{A - B=}") # różnica rbiorów - wszystko z A co nie należy do B
print(f"{A & B=}") # iloczyn zbiorów - część wspólna z A i B
print(f"{A ^ B=}") # różnica symetryczna - elementy z A i B oprócz części wspólnej
print(f"{A - B | B - A=}") # to samo co A ^ B
print(f"{A.issuperset({1,3})=}")
#zadanie11
podane = set()
while True:
napis = input("podaj liczbę lub 'stop': ")
if napis == "koniec":
break
liczba = int(napis)
podane.add(liczba)
print(podane)
print(len(podane))
#parzyste = set()
#for i in range(101):
# if i % 2 == 0:
# parzyste.add(i)
# Bardziej optymalne tworzenie listy parzystych iczb: !!!!!!!!!!!!!!!!!!
parzyste = set(range(0, 101, 2)) # Range jest iterowalne więc można zrobić zbiór bezpośrednio
print(parzyste)
print(f"{podane & parzyste=}")
print(f"{len(podane & parzyste)=}") |
print("napis")
x= input ("podaj dane:")
print("podałeś:", x)
print(x*2)
#Input zawsze jest domyślnie stringiem. Jeżeli to ma być liczba to trzeba to określić
y = int(input("podaj dane:"))
print("podałeś:",y)
print(30*y)
#zadanie
miastoA = input("podaj miasto A:")
miastoB = input("podaj miasto B:")
DystansAB = int(input("podaj dystans AB:"))
cenapaliwa = float(input("podaj cenę paliwa:"))
spalanie = float(input("podaj spalanie:"))
spalonepaliwo = spalanie * DystansAB / 100
koszt = spalonepaliwo * cenapaliwa
print(f"koszt podróży z {miastoA} do{miastoB} to: {koszt:.2f} PLN") # .2f zaokrągla wynik do 2ch miejscy po przecinku
|
# Zad. Napisz funkcję czy_podzielna(), która zwróci informację True/False czy n jest podzielne przez k
#def czy_podzielna(n,k):
# if n % k == 0:
# return True
# return False
#print(czy_podzielna(4,3))
# Tak lepiej !!!!!!!!!!!!!! :
def czy_podzielna(n,k):
return n % k == 0
if czy_podzielna(10,2):
print("jest podzielne")
#Zad. Napisz funkcję suma cyfr(x), która zwróci sumę cyft liczby x
def suma_cyfr(n):
suma = 0
while n > 0: # chba tak nie jestem pewien
suma += n % 10
n //= 10 # to samo co n = n // 10
return suma
print(suma_cyfr(123))
#Zad - zliczanie ile razy trzeba dodać wszystkie cyfry w liczbie żeby dostać wynik jednocyfrowy (z pracy domowej)
def ile_razy_suma_cyfr(n):
licznik = 0
while n > 9:
n = suma_cyfr(n)
print(n)
licznik += 1
return licznik
print(ile_razy_suma_cyfr(1234567))
#Zad - napisz funkcję dzielniki(n) która wypisze wszystkie dzielniki liczby całkowitej n
def dzielniki(n):
dzielniki=[]
for i in range (1, n+1):
if n % i == 0:
dzielniki.append(i)
return dzielniki
print(dzielniki(6))
# Lepiej tak, za pomocą wyrażenia listowego:
def dzielniki_2(n):
return [i for i in range(1, n+1) if n % i == 0]
print(dzielniki_2(6)) |
# standard ieee_754 - przechowywanie liczb zmiennoprzecinkowych
# W systemach który muszą być precyzyjne nie używa się floatów tylko części dziesiętne też są int (tylko prezentowane jako dziesiętne)
if 0.1 == 0.1:
print("OK 1")
if 1.0 == 1.0:
print("OK 2")
if 0.1 + 0.1 == 0.2:
print("OK 3")
if 1.0 + 1.0 == 2.0:
print("OK 4")
if 0.1 + 0.1 + 0.1 == 0.3: #komputer nie jest w stanie przechować wartości 0.1
print("OK 5")
if 1.0 + 1.0 + 1.0 == 3.0:
print("OK 6")
if 0.125 + 0.125 == 0.250:
print("OK 7")
print(f"{0.1:.30f}")
print(f"{0.2:.30f}")
print(f"{0.3:.30f}")
print(f"{0.125:.30f}")
|
# **5. Napisz klasę Zolw, która będzie przechowywała informację o położeniu żółwia na płaszczyźnie (2 liczby _rzeczywiste_) oraz kierunku wyrażonym w stopniach, w którym jest zwrócony.
# Zolw powinien udostępniać metody:
# - wypisz() - wypisuje położenie i zwrot żólwia,
# - lewo(n) - obraca żółwia o n stopni w lewo,
# - prawo(n) - obraca żółwia o n stopni w prawo,
# - naprzod(n) - przemieszcza żółwia o n jednostek w kierunku, w którym obecnie jest zwrócony.
# Hint do zadania: `import math` i trygonometria. ;)
import math
class zolw:
def __init__(self):
self.x = 0.0
self.y = 0.0
self.zwrot = 0
|
#0. Napisz funkcję, która sprawdzi czy podana lista jest posortowana rosnąco.
def czy_rosnaca(lista):
for i in range(len(lista)-1):
if not lista[i] < lista[i+1]:
return False
return True
print(f"{czy_rosnaca([1,3,5,4])=}")
|
x = None # kiedy nie chcemy nic przypisywać do zmiennej
print(x)
print(type(x))
if x is None: #operator porownania == sprawdza czy elementy są takie same. Is sprawdza czy elementy są TE same.
print("x jest puste")
if x is not None:
print("x jest niepuste")
#zadanie , niedokończone
max = None
min = None
while True:
liczba = input("podaj liczbę")
if liczba == "koniec":
break
liczba = int(liczba)
if liczba > max:
max = liczba
if liczba < min:
min = liczba
print(f"max to {max}")
print(f"min to {min}") |
#### Zad: Napisz funkcję zaaplikuj(f, lista), która zwróci listę będącą wynikami funkcji f() wywołanej dla wszystkich elementów listy
# [a, b, b] -> [f(a), f(b), f(c)]
#zaaplikuj(dodaj10, [1,2,3,4]) == [11,12,13,14]
def zaaplikuj(f, lista):
wynik = []
for x in lista:
wynik.append(f(x))
return wynik
# return [f(x) for x in lista] #listowo
def dodaj10(x):
return x + 10
print(zaaplikuj(dodaj10, [1,2,3])) |
class Robot:
def __init__(self,x,y,kierunek):
self.x=x
self.y=y
self.kierunek = kierunek
def wypisz(self):
kierunki = ('N','E','S','W')
print(self.x,self.y,kierunki[self.kierunek])
def lewo(self):
self.kierunek = (self.kierunek -1) % 4 #modulo z liczb ujemnych w niektórych językach (np c) nie działa jak powinno. Tutaj jest OK.
def prawo(self):
self.kierunek = (self.kierunek + 1) % 4
def naprzod(self):
# if self.zwrot % 4 == 0:
# self.y += 1
# elif self.zwrot % 4 == 1:
# self.x += 1
# elif self.zwrot % 4 == 2:
# self.y -= 1
# elif self.zwrot % 4 == 3:
# self.x -= 1
x, y = ((0,1),(1,0), (0,-1), (-1,0))[self.kierunek]
self.x += x
self.y += y
def wykonaj(self,instrukcje: str): #tutaj znowu king że instrukcje mają być stringiem
# for i in instrukcje:
# if i == "P":
# self.prawo()
# elif i == "L":
# self.lewo()
# elif i == "N":
# self.naprzod()
metody = {'N':self.naprzod, 'L':self.lewo, 'P':self.prawo} # funkcje bez nawiasów bo nie chcemy wywoływać tych metod, tylko je przekazać.
for i in instrukcje:
metody[i]() #tutaj jest pusty nawias bo to tutaj wywołujemy te metody
r = Robot(0,0,0)
r.wypisz()
r.naprzod() |
def fun():
print("asdf")
x = fun #przypisujemy alias do funkcji
x() #to samo co wywołanie fun()
fun()
def wykonaj(f,x): #przyjmuję funkcje f, argument x i wykonuje f(x)
print("uwaga wywołuję f")
f(x) #wypisz_arg(20)
def wypisz_arg(x):
print("Argument to", x)
wykonaj(wypisz_arg, 20)
wykonaj(print, "Ala ma kota")
## Zadanie: napisz funkcję wybierz(f, lista), która zwróci listę elementów z 'lista', dla których f() zwraca True.
# Przykłady:
# wybierz(czy podzielne_przez_2, [1,2,3,4,5,6]) -> to ma zwrócić [2,4,6]
# wybierz(czy podzielne_przez_3, [1,2,3,4,5,6]) -> to ma zwrócić [3,6]
def wybierz(f, lista):
wynik = []
for x in lista:
if f(x):
wynik.append(x)
return wynik
def czy_podzielne_przez_2(x):
return x % 2 == 0
def czy_podzielne_przez_3(x):
return x % 3 == 0
def wybierz2(lista):
wynik = []
for x in lista:
if czy_podzielne_przez_2(x):
wynik.append(x)
return wynik
lista = [1,2,3,4,5,6,8,12]
print(wybierz2(lista))
print(f"{wybierz(czy_podzielne_przez_2, lista) = }")
print(f"{wybierz(czy_podzielne_przez_3, lista) = }")
|
""" Only three operations are premitted.
push, pop, top
"""
import random
from test import isSorted
def sortedInsert(stack, element):
if not stack or stack[-1] < element:
stack.append(element)
else:
temp = stack.pop()
sortedInsert(stack, element)
stack.append(temp)
def sortStack(stack):
if stack:
temp = stack.pop()
sortStack(stack)
sortedInsert(stack, temp)
if __name__ == "__main__":
res = []
for i in xrange(1001):
size = random.randint(10,100)
stack = [random.randint(0, 500) for _ in xrange(size)]
sortStack(stack)
res.append(isSorted(stack))
print("%s Pass."%(res.count(True)))
print("%s Fail."%(res.count(False)))
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
https://www.geeksforgeeks.org/check-if-two-nodes-are-on-same-path-in-a-tree/
"""
from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
self.inTime = {}
self.outTime = {}
self.t = 0
def addEdge(self, u, v):
self.graph[u].append(v)
def dfs(self, u):
visited = [False]*self.V
self.dfsUtil(u, visited)
print(self.inTime)
print(self.outTime)
def dfsUtil(self, u, visited):
visited[u] = True
self.inTime[u] = self.t
self.t +=1
for v in self.graph[u]:
if visited[v] is False:
self.dfsUtil(v, visited)
self.outTime[u] = self.t
def query(self, v, u):
if (self.inTime[u] < self.inTime[v] and self.outTime[u] > self.outTime[v]) or (self.inTime[v] < self.inTime[u] and self.outTime[v] > self.outTime[u]):
return True
return False
if __name__ == "__main__":
n = 7
g = Graph(n)
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(0, 3)
g.addEdge(1, 4)
g.addEdge(2, 5)
g.addEdge(3, 6)
g.dfs(0)
print(g.query(0, 4))
print(g.query(0, 2))
print(g.query(4, 5))
|
#!/usr/bin/python
__author__ = "Vishal Jasrotia. Stony Brook University"
__copyright__ = ""
__license__ = "GPL"
__version__ = "1.0"
__maintainer__ = "Vishal Jasrotia"
__email__ = "[email protected]"
__status__ = ""
import sys
class Node:
def validate(f):
def inner(*args, **kwargs):
f(*args, **kwargs)
return inner
def __init__(self, data, nextNode):
self._data=data
self._nexNode = nextNode
class Stack:
"""implementation of stack using python builtin list.
Stack can be implemeted using above node class.
"""
def __init__(self):
self._stack = []
def pop(self):
if len(self._stack) == 0:
raise Exception("Stack is empty")
data = self._stack.pop(0)
return data
def push(self, data):
self._stack.insert(0, data)
def peek(self):
return self._stack[0]
def size(self):
return len(self._stack)
def printstack(self):
for x in self._stack:
print("+----------------+")
print("| %s |"%str(x))
print("------------------")
if __name__ == "__main__":
stack = Stack()
print("psuh 6,5,4,3 and print stack")
stack.push(6)
stack.push(5)
stack.push(4)
stack.push(3)
stack.printstack()
print("Top is : %d"%stack.pop())
print("print after pop")
stack.printstack()
print("Peek top : %d "%stack.pop())
|
"""
Example : num = \"1234\"
sumofdigit[0] = 1 = 1
sumofdigit[1] = 2 + 12 = 14
sumofdigit[2] = 3 + 23 + 123 = 149
sumofdigit[3] = 4 + 34 + 234 + 1234 = 1506
Result = 1670
Solution:
For above example,
sumofdigit[3] = 4 + 34 + 234 + 1234
= 4 + 30 + 4 + 230 + 4 + 1230 + 4
= 4*4 + 10*(3 + 23 +123)
= 4*4 + 10*(sumofdigit[2])
In general,
sumofdigit[i] = (i+1)*num[i] + 10*sumofdigit[i-1]
"""
def findSum(string):
result = int(string[0])
sumdigits = [0]*(len(string))
sumdigits[0] = int(string[0])
for i in xrange(1,len(string)):
sumdigits[i] = (i+1)*int(string[i]) + 10*sumdigits[i-1]
result += sumdigits[i]
return result
if __name__ == "__main__":
print(findSum("1234"))
|
def activitySelection(activities):
"""
"""
activities = sorted(activities , key = lambda x : x[1])
count = 1
i = 0
print(i)
for j in xrange(1, len(activities)):
if activities[j][0] > activities[i][1]:
count += 1
i = j
print(i)
return count
if __name__ == "__main__":
#s = [1 , 3 , 0 , 5 , 8 , 5]
#f = [2 , 4 , 6 , 7 , 9 , 9]
activities = [[8,9], [1,2],[0,6],[5,7],[5,9], [3,4]]
print(activitySelection(activities))
|
def jobSequencing(jobs):
"""
O(n^2)
"""
slots = [False]*(len(jobs))
result = [-1]*(len(jobs))
jobs = sorted(jobs , key = lambda x :x [2], reverse = True)
for i in xrange(len(jobs)):
for j in xrange(min(len(jobs), jobs[i][1]) - 1 , -1, -1):
if slots[j] is False:
slots[j] = True
result[j] = jobs[i][0]
break
return slots, result
if __name__ == "__main__":
jobs = [['a', 2, 100], ['b', 1, 19], ['c', 2, 27],
['d', 1, 25], ['e', 3, 15]]
print(jobSequencing(jobs))
|
from __future__ import print_function
from linklist import SimpleNode as Node
from linklist import printlist
def reverseKNode(head, k ):
count = 0
curr = head
prev = None
while count < k and curr is not None:
next = curr.next
curr.next = prev
prev = curr
curr = next
count +=1
if curr is not None:
temp = reverseKNode(curr, k)
head.next = temp
return prev
if __name__ == "__main__":
head = None
for i in xrange(22, -1,-1 ):
node = Node(i, head)
head = node
printlist(head)
head = reverseKNode(head, 5)
printlist(head)
|
import random, time
def binarysearchIter(nums,val, left, right):
if left <= right:
mid = left + (right - left)/2
if nums[mid] == val:
return mid
elif val < nums[mid]:
return binarysearchIter(nums, val, left, mid - 1)
else:
return binarysearchIter(nums, val, mid + 1, right)
return -1
def binarysearch(nums, val):
left, right = 0 , len(nums) - 1
while left <= right:
mid = left + (right - left)/2
#print(mid)
if nums[mid] == val:
return mid
elif val < nums[mid]:
right = mid -1
else:
left = mid + 1
if nums[mid] == val:
return left
return -1
if __name__ == "__main__":
res = []
start = time.time()
for x in xrange(10000):
size = random.randint(4,100)
nums = [i for i in xrange(size)]
val = random.randint(1,size-1)
idx = binarysearch(nums, val)
if val == idx:
res.append(True)
else:
res.append(False)
#print(nums)
end = time.time()
print("%s Pass."%(res.count(True)))
print("%s Fail."%(res.count(False)))
print("Time : %s"%(end-start))
res = []
start = time.time()
for x in xrange(10000):
size = random.randint(4,100)
nums = [i for i in xrange(size)]
val = random.randint(1,size-1)
idx = binarysearchIter(nums, val, 0, size-1)
if val == idx:
res.append(True)
else:
res.append(False)
#print(nums)
end = time.time()
print("%s Pass."%(res.count(True)))
print("%s Fail."%(res.count(False)))
print("Time : %s"%(end-start)) |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Algorithm
1) Create a set mstSet that keeps track of vertices already included in MST.
2) Assign a key value to all vertices in the input graph. Initialize all key values as INFINITE. Assign key value as 0 for the first vertex so that it is picked first.
3) While mstSet doesn’t include all vertices
….a) Pick a vertex u which is not there in mstSet and has minimum key value.
….b) Include u to mstSet.
….c) Update key value of all adjacent vertices of u. To update the key values, iterate through all adjacent vertices. For every adjacent vertex v, if weight of edge u-v is less than the previous key value of v, update the key value as weight of u-v
Time : O(E log(V))
"""
import sys
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [ [0]*self.V for row in range(self.V)]
def minKey(self, key, mstSet):
min = sys.maxint
for v in xrange(len(key)):
if min > key[v] and mstSet[v] == False:
min = key[v]
min_idx = v
return min_idx
def printMst(self, key, parent):
print("---Edge--- = Weight")
for v in xrange(1, self.V):
print(str(parent[v]) + " ---- " + str(v) + " = " + str(key[v]))
def primMST(self):
"""find MST from a graph
"""
parent = [None]*self.V
key = [sys.maxint]*self.V
mstSet = [False] *self.V
key[0] = 0
parent[0] = -1
for count in range(self.V):
u = self.minKey(key, mstSet)
mstSet[u] = True
for v in xrange(self.V):
if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]:
key[v] = self.graph[u][v]
parent[v] = u
self.printMst(key, parent)
if __name__ == "__main__":
g = Graph(5)
g.graph = [ [0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0],
]
g.primMST()
|
"""
Construct Tree from given Inorder and Preorder traversals
Let us consider the below traversals:
Inorder sequence: D B E A F C
Preorder sequence: A B D E C F
"""
from __future__ import print_function
from tree import Node
from insertNode import insert
def search(inorder, val, low, high):
for i in xrange(low, high+1):
if inorder[i] == val:
return i
def buildTree(inorder, preorder, low, high):
if low > high:
return None
node = Node(preorder[buildTree.preorderIndex])
index = search(inorder, preorder[buildTree.preorderIndex], low, high)
buildTree.preorderIndex +=1
node.left = buildTree(inorder, preorder, low, index - 1)
node.right = buildTree(inorder, preorder, index + 1, high)
return node
if __name__ == "__main__":
# nums = [3,2,4,5,10,12,7,8,5,1,9,6, 11,13,14]
# root = None
# for i in xrange(len(nums)):
# root = insert(root, nums[i])
#
#
# root.prettyPrint()
buildTree.preorderIndex = 0
preorder = [3, 2, 5, 8, 5, 10, 1, 9, 4, 12, 6, 11, 7, 13, 14,]
inorder = [8 , 5 , 5 , 2 , 1 , 10 , 9 , 3 , 6 , 12 , 11 , 4 , 13 , 7 , 14]
root = buildTree(inorder, preorder, 0, len(inorder)-1)
root.prettyPrint()
|
printed = []
def fib(n):
if n<2:
if n not in printed:
printed.append(n)
print(n)
return n
else:
num = fib(n-2) + fib(n-1)
if n not in printed:
print(num)
printed.append(n)
return num
print(fib(10))
print(len(printed))
|
# -*- coding:utf-8 -*-
"""Kadane\’s Algorithm
"""
from sys import maxint
def findMax(nums):
maxsum = -maxint
max_so_far = 0
start = 0
end = 0
s = 0
for i in xrange(len(nums)):
max_so_far += nums[i]
if maxsum < max_so_far :
maxsum = max_so_far
start = s
end = i
if max_so_far < 0:
max_so_far = 0
s = i + 1
print("MAX SUM : " , maxsum)
print("Subarray :" , nums[start:end+1])
print("len : ", end - start + 1)
return maxsum , nums[start:end+1]
if __name__ == "__main__":
a = [-2, -3, 4, -1, -2, 1, 5, -3]
print(findMax(a)) |
from insertNode import insert
def deleteLast(root, last_val):
queue = [root]
while queue:
size = len(queue)
for i in xrange(size):
node = queue.pop(0)
if node.left:
if node.left.data == last_val:
del node.left
node.left = None
return
else:
queue.append(node.left)
if node.right:
if node.right.data == last_val:
del node.right
node.right = None
return
else:
queue.append(node.right)
def deleteNode(root, val):
queue = [root]
while queue:
size = len(queue)
for i in xrange(size):
node = queue.pop(0)
if node.data == val:
key_node = node
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
last_val = node.data
deleteLast(root, last_val)
key_node.data = last_val
return root
if __name__ == "__main__":
root = None
for i in xrange(31):
root = insert(root, i)
root.prettyPrint()
root = deleteNode(root, 5)
root.prettyPrint()
|
def towerofhanoi(n, from_rod, to_rod, aux_rod):
if n == 1:
print("Move disk %s from %s to %s"%(n, from_rod, to_rod))
return
towerofhanoi(n-1, from_rod, aux_rod, to_rod)
print("Move disk %s from %s to %s"%(n, from_rod, to_rod))
towerofhanoi(n-1, aux_rod, to_rod, from_rod)
def findLegalMovesBetween(rodSrc, rodDst, src, dst):
if rodSrc and rodDst:
if rodSrc[-1] < rodDst[-1]:
disk = rodSrc.pop()
print("Move disk %s from %s to %s"%(disk, src, dst))
rodDst.append(disk)
else:
disk = rodDst.pop()
print("Move disk %s from %s to %s"%(disk, dst, src))
rodSrc.append(disk)
elif rodSrc:
disk = rodSrc.pop()
print("Move disk %s from %s to %s"%(disk, src, dst))
rodDst.append(disk)
elif rodDst:
disk = rodDst.pop()
print("Move disk %s from %s to %s"%(disk, dst, src))
rodSrc.append(disk)
else:
print("Illegal move")
def towerofhanoiItr(n):
numofmoves = pow(2,n)
rodSrc = list(range(n, 0, -1))
rodDst = []
rodAux = []
src = "A"
dst = "C"
aux = "B"
print(rodSrc, rodAux, rodDst)
if n%2 == 0:
aux, dst = dst, aux
for i in xrange(1, numofmoves ):
if i%3 == 1:
findLegalMovesBetween(rodSrc, rodDst, src, dst)
elif i%3 == 2:
findLegalMovesBetween(rodSrc, rodAux, src, aux)
elif i%3 == 0:
findLegalMovesBetween(rodAux, rodDst, aux, dst)
print(rodSrc, rodAux, rodDst)
if __name__ == "__main__":
towerofhanoi(5, "A", "C", "B")
print("******************")
towerofhanoiItr(5) |
from linklist import SimpleNode as Node
from linklist import printlist
def evenodd(head):
head1 = Node(-1, None)
head2 = Node(-1, None)
h1 = head1
h2 = head2
while head is not None:
h1.next = head
h1 = h1.next
head = head.next
if head is not None:
h2.next = head
h2 = h2.next
head = head.next
h2.next = None
h1.next = head2.next
return head1.next
if __name__ == "__main__":
head = None
for i in xrange(11, 0, -1):
node = Node(i, head)
head = node
printlist(head)
head = evenodd(head)
printlist(head)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.