text
stringlengths 37
1.41M
|
---|
def overlapping(lst1, lst2):
lst= list(set(lst1) & set(lst2))
if lst!=[]:
return True
else:
return False
lst1 = [int(item) for item in input("Enter numbers space separated : ").split()]
lst2 = [int(item) for item in input("Enter numbers space separated : ").split()]
print(overlapping(lst1, lst2)) |
#---------------------------Clase Persona-------------------------------------------------->
class Persona():
#this java funcion constructor
def __init__(self, nombre, apellido, edad):
self.nombre = nombre
self.apellido = apellido
self.edad = edad
@property #cambiar la funcion en atributo
def mayor_de_edad(self): #siempre pasar el self
return self.edad >= 18 #devolvera true o false
def __str__(self):#toString de java
return self.nombre + " " + self.apellido + ", "+ str(self.edad)
|
entrada = input()
entrada = entrada.split()
n = int(entrada[0])
m = int(entrada[1])
A = ""
for i in range(n,m+1):
if i % 5 == 0:
A = A+str(i)+"|"
A = A.strip("|")
print(A)
|
x = input('enter the string:')
if (x == x[::-1]):
print("The string is a palindrome")
else:
print("Not a palindrome") |
print("Choose Options To Perform : ")
print("1.Addition")
print("2.Subtraction")
print("3.Multiplication")
print("4.Division")
choice = int(input("Enter Your Choice :"))
a = int(input("Enter First Number :"))
b = int(input("Enter Second number:"))
if (choice==1) :
print("Addition of A + B is : {} ".format(a+b))
elif (choice==2) :
print("Subtraction of A - B is : {} ".format(a-b))
elif (choice==3) :
print("Multiplication of A * B is : {} ".format(a*b))
elif (choice==4) :
if(b == 0) :
print("b cannot be 0(Zero) for Division operation")
else :
print("Division of A / B is : {} ".format(a/b))
else :
print("Invalid Choice") |
'''
Determine the prime factors of a given positive integer.
Construct a flat list containing the prime factors in ascending order.
Example:
* (prime-factors 315)
(3 3 5 7)
'''
def calcPrimeFactorsList(number):
divisor_number = 2
prime_factors_list = list()
while number > 1.0: # checking division of number is further possible or not
if number % divisor_number == 0: # checking divisor_number is root or not
temp = number
temp %= divisor_number # then dividing the number by divisor
number /= divisor_number # getting number after division
# and adding to the list of roots
prime_factors_list.append(divisor_number)
else:
divisor_number += 1 # increating divisor number to find next roots
return prime_factors_list # returning founded roots list
num = int(input('Enter the number: '))
print(calcPrimeFactorsList(num))
|
'''
Pack consecutive duplicates of list elements into sublists.
If a list contains repeated elements they should be placed in separate
sublists.
Example:
* (pack '(a a a a b c c a a d e e e e))
((A A A A) (B) (C C) (A A) (D) (E E E E))
'''
#taking input of list elements at a single time seperating by space and splitting each by split() method
demo_list = input('enter elements seperated by space: ').split(' ')
new_list = list() #creating new list as new_list
previous_item = demo_list[0] #assigning first element of demo_list to previous_item
temp_list = list() #creating new list as temp_list
for current_item in demo_list: #iterating through all elements of demo_list
if current_item == previous_item: #checking if previously added element is same as current element of list, for checking repetative elements
temp_list.append(current_item) #appending current element to temp_list. for creation of sublist
else: #if not repetative element
new_list.append(temp_list[:]) #appending previously created sublist(temp_list) copy to new_list
temp_list.clear() #clearing temp_list to create new sublist
temp_list.append(current_item) #appending current_item to temp_list
previous_item = current_item #assigning current_item to previous_item
else:
new_list.append(temp_list[:]) #appending temp_list copy to new_list
#printing new_list and demo_list
print(f"old list: {demo_list}")
print(f"newly created list: {new_list}")
|
'''
Generate a random permutation of the elements of a list.
Example:
* (rnd-permu '(a b c d e f))
(B A D C E F)
'''
#importingrandint function from random module
from random import randint
input_list = input("Enter list seperated by space(max 10): ").split(' ')
print(f"given list is: {input_list}")
#creating new lists
randomly_permuted_list = list()
visited_indexes_list = list()
while len(randomly_permuted_list) < len(input_list): #checking all elements are appended from input_list to randomly_permuted_list
#generating random index
random_index = randint(0,len(input_list)-1)
#checking randomly generated index is already visited or not
if random_index in visited_indexes_list:
continue #if visited already then terminating current iteration
visited_indexes_list.append(random_index) #if not visited then, is need to mark as visited
selected_element = input_list[random_index] #getting element present at generated index
randomly_permuted_list.append(selected_element) #and apeending to permuted list
print(f"Newly permuted list is: {randomly_permuted_list}")
|
'''
Eliminate consecutive duplicates of list elements.
If a list contains repeated elements they should be replaced with a
single copy of the element. The order of the elements should not be
changed.
Example:
* (compress '(a a a a b c c a a d e e e e))
(A B C A D E)
'''
#taking input of list elements at a single time seperating by space and splitting each by split() method
demo_list = input('enter elements seperated by space: ').split(' ')
new_list = list() #creating new list
def removeConsecutiveDuplicates(demo_list):
no_consecutive_dupliates_list = list(demo_list[0]) #appending first element to new_list
for item in demo_list: #iterating through all elements of demo_list
if no_consecutive_dupliates_list[-1] != item: #Checking if lastly added element to new_list is identical to to iterating item
no_consecutive_dupliates_list.append(item) #if not same then appending to new_list. Here we're just eliminating the consecutive duplicates
return no_consecutive_dupliates_list
no_repeatative_dupliates_list = removeConsecutiveDuplicates(demo_list)
#printing both lists
print(f'list before: {demo_list}')
print(f'list after removing repeatative duplicates: {no_repeatative_dupliates_list}')
|
'''
Truth tables for logical expressions (2).
Continue problem P46 by defining and/2, or/2, etc as being operators.
This allows to write the logical expression in the more natural way,
as in the example: A and (A or not B). Define operator precedence as
usual; i.e. as in Java.
Example:
* table(A,B, A and (A or not B)).
true true true
true fail true
fail true fail
fail fail fail
'''
def evaluate(expr, input_data):
# checking if expression contains any brackets, to solve bracket first
if '(' in expr:
# if found then solve that nested expression present in bracket first
new_expr = expr[:expr.find(')')+1] # taking that equation
# removing brackets
new_expr = new_expr.replace(
'(', '').replace(')', '')
# calling evaluate again with new expression
result = evaluate(new_expr, input_data)
# adding got result at its place from where expression is grabbed
expr = expr[:expr.find('(')]+str(result)+expr[expr.find(')')+1:]
# returing result after solving expression
return evaluate(expr, input_data)
else:
# converting string to list with seperated by space
new_list = list(expr.split(' '))
# if list contains only one element, element itself the result of whole expression
while len(new_list) > 1:
# if expression contains not operation then performing here
if 'not' in new_list:
i = new_list.index('not')
new_list[i+1] = str(not input_data[new_list[i+1]])
new_list.remove('not')
# if expression contains and operation then performing here
if 'and' in new_list:
i = new_list.index('and')
res = new_list[i-1] and new_list[i+1]
new_list.pop(i-1)
new_list.insert(i-1, str(res))
new_list.remove('and')
new_list.pop(i)
# if expression contains or operation then performing here
elif new_list[1] == 'or':
res = input_data[new_list[0]] or input_data[new_list[2]]
new_list = new_list[3:]
new_list.insert(0, str(res))
return new_list[0] # returning result
# taking expression as input
expr = input('Enter input: ')
# defining inputs
A = [True, True, False, False]
B = [True, False, True, False]
print(f"A\tB\tOutput")
for i in range(len(A)):
# creating dictionary for reference
data = {'A': A[i], 'B': B[i], 'True': True, 'False': False}
# calculating output by passing expression to evaluate along with data dictionary
output = evaluate(expr, data)
print(f"{A[i]}\t{B[i]}\t{output}")
|
'''
Binary search trees (dictionaries)
Use the predicate add/3, developed in chapter 4 of the course, to write a predicate to construct a binary search tree from a list of integer numbers.
Example:
* construct([3,2,5,7,1],T).
T = t(3, t(2, t(1, nil, nil), nil), t(5, nil, t(7, nil, nil)))
Then use this predicate to test the solution of the problem P56.
Example:
* test-symmetric([5,3,18,1,4,12,21]).
Yes
* test-symmetric([3,2,5,7,1]).
No
'''
class BinaryTree:
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
def addNode(self, data): # method that add nodes
if self.data == None:
self.data = data
if self.data > data:
if self.left == None:
self.left = BinaryTree(data)
else:
self.left.addNode(data)
if self.data < data:
if self.right == None:
self.right = BinaryTree(data)
else:
self.right.addNode(data)
# returns binary tree created with nodes_list
def createTree(nodes_list):
binary_tree = BinaryTree()
for node in nodes_list:
binary_tree.addNode(node)
return binary_tree
|
import fractions
import random
def perfect_power(n):
"""Get the integer and power that make up `n`.
Args:
n (int): The number to check.
Returns:
A tuple containing the values that correspond to the perfect powers of n
or None if they do not exist. For example:
(2, 3)
corresponds to 2 ** 3 which equals 8, while:
(None, None)
corresponds to the case when `n` is not a perfect power.
"""
i=2
while True:
s = int(pow(n, 1.0/i))
if s**i == n:
return (s,i)
if (s+1)**i == n: #since int basically rounds down
return (s+1,i)
elif s==1:
return (None, None)
i+=1
def mpower(n,s,p):
i = 1
m = n
if s == 1:
return n%p
else:
while True:
n = n**2 % p
i *=2
if i == s:
return n
if i*2 > s:
break
return (n%p)*(mpower(m,s-i,p)%p)%p
def sqrt(n, p):
"""Get the positive square root of n mod p if p is a prime and n is a
quadratic residue mod n.
There may be multiple square roots of n. For simplicity this function only
returns only a positive one.
Args:
n (int): n is a quadratic residue (mod p).
p (int): is an odd prime.
Returns:
The square root of n mod p.
"""
return mpower(n,(p+1)/4, p)
def silvio(n):
"""Test primality of the number `n`.
This function should return True with probablity 1.0 if `n` is prime and <=
0.5 if `n` is composite.
Args:
n (int): A positive integer.
Returns:
Whether or not n is a prime number.
"""
if n == 2:
return True
if n%2 == 0:
return False
if perfect_power(n)[0]:
return False
x = random.randrange(1,n)
if fractions.gcd(x,n) != 1:
return False
y=sqrt(x**2 % n, n)
if y != x %n and y != -x % n:
return False
return True
|
#Factorial workshop
def factorial(num):
toFactorial = 1
for numFactorial in range(1,(num+1)):
toFactorial *= numFactorial
return toFactorial
num = int(input("Enter a number :"))
if (num < 0) :
print("factorial of negative number cannot calculate")
else:
print(factorial(num)) |
#list
print("---- STUDENT ----")
students = ["Yusuf","Talha"]
print(students[1])
#append
print("---- APPEND ----")
students.append("Arda")
print(students[2])
#remove
print("---- REMOVE ----")
students.remove("Arda")
print("students[2] WILL BE SHOWING ERROR")
print("---- CITIES ----")
cities = list(("New york","Los Angelas"))
print(cities)
#count
print("---- COUNT ----")
print(cities.count("New york"))
print("index of new york : " ,cities.index("New york"))
#pop like remove
print("---- POP ----")
cities.pop(1)
print(cities)
#insert
print("---- INSERT ----")
cities.insert(1,"Los Angelas")
print(cities[1])
#reverse
print("---- REVERSE ----")
cities.reverse();
print(cities)
#copy
print("---- COPY ----")
cities2 = cities.copy()
print(cities2)
#extend
print("---- EXTEND ----")
cities.extend(cities2)
print(cities2)
#sort
print("---- SORT ----")
cities.sort()
cities.reverse()
print(cities)
#clear
print("---- CLEAR ----")
print(cities.clear())
print(cities)
#output
# ---- STUDENT ----
# Talha
# ---- APPEND ----
# Arda
# ---- REMOVE ----
# students[2] WILL BE SHOWING ERROR
# ---- CITIES ----
# ['New york', 'Los Angelas']
# ---- COUNT ----
# 1
# index of new york : 0
# ---- POP ----
# ['New york']
# ---- INSERT ----
# Los Angelas
# ---- REVERSE ----
# ['Los Angelas', 'New york']
# ---- COPY ----
# ['Los Angelas', 'New york']
# ---- EXTEND ----
# ['Los Angelas', 'New york']
# ---- SORT ----
# ['New york', 'New york', 'Los Angelas', 'Los Angelas']
# ---- CLEAR ----
# None
# [] |
# Variables
counter = 10 # An integer assignment
miles = 250.75 # A floating point
name ="Yusuf" # A string
boolean= True # A bool variable, its turn true and false
print(counter)
print(miles)
print(name)
print(boolean)
#Output
# 10
# 250.75
# Yusuf
# True |
#map
numbers = [1,2,3,4,5]
numbersSquared = list(map(lambda x: x**2,numbers))
# for i in numbers:
# numbersSquared.append(i*i)
print(numbersSquared)
#filter
numbersFiltered = list(filter(lambda x: x>2,numbers))
print(numbersFiltered)
#reduce
from functools import reduce
numbersFactorial = reduce(lambda x,y:x*y,numbers)
print(numbersFactorial) |
exit_choice="nothing"
while exit_choice !="EXIT":
intentos=5
contraseña="desactivar"
print("Te acabas de encontrar una bomba en tu casa")
print("Explotará a menos que pongas la contraseña correcta")
print("Tienes cinco intentos")
guess=input("Introduzca contraseña: ")
while guess !=contraseña:
print()
print("Contraseña incorrecta")
print()
intentos=intentos-1
print("Te quedan ",intentos," para la explosión")
if intentos==0:
break
print()
guess=input("Introduzca contraseña nuevamente, en minúsculas: ")
if intentos==0:
print("¡¡BOUUM!! MUERTO")
else:
print("Bomba desactivada")
exit_choice=input("presiona return si deseas reiniciar o EXIT si deseas finalizar: ")
|
import random
player_choice="nothing"
while player_choice != "EXIT":
number=random.randint(1,10)
adivinanza=int(input("Estoy pensando en un número entre el 1 y el 10...¿Cúal crees que es?: "))
while adivinanza !=number:
if adivinanza<number:
print("Ese número es demasiado bajo")
else:
print("Ese número es demasiado alto")
adivinanza=int(input("vuelve a intentarlo capullín: "))
print("¡¡Enhorabuena!! Ése es el número correcto")
player_choice=input("Pulsa enter para intertarlo otra vez o teclea EXIT en mayúsculas para salir: ")
|
from google_API import *
def main():
exit_code = True
while exit_code:
location = input("Enter address or zip code: ")
place_of_interest = input(f"What do you want to find at {location}? ")
location_radius = input(f"How far around {location} do you want to search?(meters) ")
client = GoogleMapsClient(api_key=GOOGLE_API_KEY, address=location)
client.download_info(place_of_interest, location_radius)
answer = input("Do you want to do another search? Y for yes, N for no ")
if(answer == "y" or answer == "Y" or answer == "yes" or answer == "YES"):
continue
else:
exit_code = False
main() |
# coding: utf-8
# 本项目要求矩阵统一使用二维列表表示,如下:
A = [[1,2,3],
[2,3,3],
[1,2,5]]
B = [[1,2,3,5],
[2,3,3,5],
[1,2,5,1]]
#TODO 创建一个 4*4 单位矩阵
def identity_matrix(n):
I = [0] * n
for i in range(0, n):
I[i] = [0]*n
I[i][i] = 1
return I
print identity_matrix(4)
# 使用len直接获取矩阵的行和列数
def shape(M):
i = len(M)
j = len(M[0])
return i,j
|
def func():
global x
print 'x beginning of func(): ',x
x=2
print 'x ending of func(): ',x
x=50
func()
print 'x after calling func(): ',x
|
# 10 nested squares
import turtle
def square(width):
turtle.forward(width)
turtle.left(90)
turtle.forward(width)
turtle.left(90)
turtle.forward(width)
turtle.left(90)
turtle.forward(width)
turtle.left(90)
turtle.shape('turtle')
y = 5
x = 0
for i in range(0, 25):
x += y
square(2 * x)
turtle.penup()
turtle.goto(-x, -x)
turtle.pendown()
|
numbers = range(10)
print(numbers)
print(type(numbers))
print(list(numbers)) # Если хотим посмотреть все элементы
numbers = range(0, 51, 5)
print(list(numbers)) |
# Write only positive numbers to the list
numbers = [1, 2, 3, 4, 5, -1, -2, -3]
# Classic method
result = []
for number in numbers:
if number > 0:
result.append(number)
print(result)
# Using 'filter' function
result = filter(lambda number: number > 0, numbers)
print(list(result))
# Using list-generator
result = [number for number in numbers if number > 0]
print(result) |
# Open the file for writing bytes
with open('bytes.txt', 'wb') as f:
str = 'Привет мир'
f.write(str.encode('utf-8'))
with open('bytes.txt', 'w', encoding='utf-8') as f:
f.write('Привет мир')
# Reading text as bytes
with open('bytes.txt', 'rb') as f:
result = f.read()
print(result)
print(type(result))
# decode to get the string
s = result.decode('utf-8')
print(s) |
# Написать функцию is_full_house, которая принимает список карт (руку, 5 карт иначе говоря)
# и определяет наличие комбинации Full House на руке.
# Возвращает True, если определён Full House, в противном случае - False.
# Full House это когда из пяти карт 2 одного достоинства и 3 одного достоинства (но отличающегося от пары).
# A - туз, J - валет, Q - дама, K - король, 2-10.
# Примеры Full House: (A, A, Q, Q, Q), (10, 10, 10, J, J)
def is_full_house(hand: list) -> bool:
return all([hand.count(i) >= 2 for i in hand])
def is_full_house_test():
print(f'Te test of the function is_full_house begin...')
print('#Test 1 was successful.' if is_full_house(['A', 'A', 'A', 'K', 'K']) is True else '#Test 1 failed.')
print('#Test 2 was successful.' if is_full_house(['3', 'J', 'J', 'J', '3']) is True else '#Test 2 failed.')
print('#Test 3 was successful.' if is_full_house(['3', '4', '2', 'J', '3']) is False else '#Test 3 failed.')
print('#Test 4 was successful.' if is_full_house(['J', 'J', 'J', 'J', '3']) is False else '#Test 4 failed.')
if __name__ == '__main__':
is_full_house_test()
|
friends = 'Максим Леонидович'
print(friends[0])
print(friends[1])
print(friends[-1])
print(len(friends))
print(friends.find('Лео'))
print(friends.split())
print(friends.isdigit())
print(friends.upper())
print(friends.lower())
help(list)
|
# Draw a spiral
import turtle
turtle.shape('turtle')
for i in range(1000):
turtle.forward(i * 0.001)
turtle.left(2)
|
import math
numbers = [4, 1, 2, 3, -4, -2, 7, 16]
# Create list from numbers that have square root of less than 2
result = []
# Classic method
for number in numbers:
if number > 0:
sqrt = math.sqrt(number)
if sqrt < 2:
result.append(number)
print(result)
result = []
# with AND
for number in numbers:
if number > 0 and math.sqrt(number) < 2:
result.append(number)
print(result)
# with generator
result = [number for number in numbers if number > 0 and math.sqrt(number) < 2]
print(result) |
# На вход программа получает набор чисел, заканчивающихся решеткой.
# Вам требуется найти: среднее, максимальное и минимальное число в последовательности.
# Так же нужно вывести cумму остатков от деления суммы троек на последнее число тройки
# (каждые 3 введеных числа образуют тройку).
#
# Для понимания рассмотрим пример входных данных: 1 2 3 4 5 6
# среднее: (1 + 2 + 3 + 4 + 5 + 6) / 6 = 3.5
# максимум: 6
# минимум: 1
# сумма остатков троек: (1 + 2 + 3) mod 3 + (4 + 5 + 6) mod 6 = 6 mod 3 + 15 mod 6 = 0 + 3 = 3
#
# Среднее выводить, округлив до трех знаков после запятой. Для этого нужно использовать функцию round(x, 3)
#
# Того ваша программа должна вывести: 3.5 6 1 3
#
# Подумайте, имеет ли смысл хранить всю последовательность.
#
# Формат входных данных
# Последовательность чисел, заканчивающися '#'.
# Все числа от 1 до 100. Количество чисел в последовательности кратно трем.
# Одно число на строку.
#
# Формат выходных данных
# Четыре числа, разделенных пробелом.
from sys import exit
numbers = [] # Empty list
len_list = 0 # List length
division = 0
while True:
x = input()
if x == '#':
break
elif len(x) > 3:
numbers = x.split(sep=' ')
tmp = int(numbers[0])
for i in range(len(numbers) - 1):
numbers[i] = int(numbers[i + 1])
numbers[len(numbers) - 1] = tmp
# for i in range(len(numbers)):
# print(numbers[i], end='')
# print(' ', end='')
print(*numbers)
exit()
else:
numbers.append(int(x))
len_list += 1
mean = sum(numbers) / len_list # Arithmetical mean value
max_value = max(numbers)
min_value = min(numbers)
def sum_of_triples():
"""
Функция считает сумму первых трех чисел списка,
удаляет их, затем делит сумму на последний элемент списка.
Function calculates the sum of the first three numbers of the list,
deletes them, then divides the sum by the last elements of the list.
:return: Остаток от деления.
Modulo
"""
sum_var = 0
divider = numbers[2]
for i in range(3):
sum_var += numbers.pop(0)
result = sum_var % divider
return result
while len_list != 0:
division += sum_of_triples()
len_list -= 3
print(round(mean, 3), max_value, min_value, division, sep=' ')
|
def check_sorted(A, ascending=True):
"""
Проверка отсортированности за О(len(A))
Function checks array sorting for O(n)
:param A:
:param ascending:
:return:
"""
flag = True
s = 2 * ascending - 1
for i in range(0, len(A) - 1):
if s * A[i] > s * A[i + 1]:
flag = False
break
return flag
list_1 = [1, 2, 3, 4, 5, 6]
list_2 = [6, 5, 4, 3, 2, 1]
list_3 = [1, 2, 4, 3, 6, 5]
print(check_sorted(list_1))
print(check_sorted(list_2, ascending=False))
print(check_sorted(list_3))
|
# слово -> СлОвО
word = 'рефрежератор'
result = []
for i in range(len(word)):
letter = word[i].lower() if i % 2 != 0 else word[i].upper()
result.append(letter)
result = ''.join(result) # conversion from list to string
print(result) |
# Вычислите XOR от двух чисел.
#
# Входные данные
# Два целых шестнадцатеричных числа меньших FF.
#
# Выходные данные
# Побитовый XOR этих чисел в шестнадцетиричном виде.
numbers = [int(n, 16) for n in input().split()]
a = numbers[0]
b = numbers[1]
# print(f'{a^b:02x}')
print("{0:x}".format(a ^ b))
|
# Python3 распознает ввод значений переменных
# в разных системах счислениях
# Запись начинается с 0, т.к Python3 понимает,
# что с буквы начинаются все переменные
x = 0b111101 # Ввод числа в двоичной системе "0b" - двоичная
print(x) # Вывод будет в 10-ой системе счисления
y = 0o0732 # Ввод числа в восьмеричной системе "0о" - восьмеричная
print(y)
z = 0xFA0B # Ввод числа в шестнадцатиричной системе "0x" - шестнадцатирична
t = int('Z3F', base=36) # base - именнованый парамет, указывающий на ситему счислений
print('Перменная t = ', t)
# Что бы сделать наоборот
a = 127
print(bin(a))
print(oct(a))
print(hex(a))
|
# Common string
s = 'Hello world'
# String bytes
sb = b'Hello bytes'
# Index of common string
print(s[1]) # The result will be 'e'
# Index of string bytes
print(sb[1]) # The result will be '101'
# Slice of common string
print(s[1:3]) # The result will be 'el'
# Slice of string bytes
print(sb[1:3]) # The result will be "b'el'"
# Iterate over the string bytes in cycle
for item in sb:
print(item) |
import random
def game_reverse():
user_number = int(input('Enter a number between 0 and 100: '))
result = None
min_result = 0
max_result = 100
while result != '=':
number = random.randint(min_result, max_result)
print(number)
result = input('Enter your decision (Exam.">","<","="): ')
if result == '<':
max_result = number - 1
elif result == '>':
min_result = number + 1
return print('Its WIN')
|
# Даны два списка фруктов. Получить список фруктов, присутствующих в обоих исходных списках.
# Примечание: Списки фруктов создайте вручную в начале файла.
fruit_list_1 = ['груша', 'яблоко', 'манго', 'абрикос', 'слива', 'алыча',
'вишня', 'папая', 'клубника', 'бананы', 'апельсин', 'мандарин']
fruit_list_2 = ['груша', 'яблоко', 'крыжовник', 'абрикос', 'слива', 'алыча',
'вишня', 'арбуз', 'клубника', 'бананы', 'апельсин', 'мандарин']
result = [fruit for fruit in fruit_list_1 if fruit in fruit_list_2]
print(result)
# Classic method
result = []
for fruit in fruit_list_1:
if fruit in fruit_list_2:
result.append(fruit)
print(result)
|
cities = {'Las Vegas', 'Paris', 'Moscow'}
print(cities)
cities.add('Berlin')
cities.add('London')
print(cities)
cities.remove('Moscow')
print(cities)
print(len(cities))
print('London' in cities)
for city in cities:
print(city) |
import turtle
corner = 0
turtle.shape('turtle')
while corner != 1000: # Result is circle
turtle.forward(2)
turtle.left(1)
corner += 1
|
from tkinter import *
def new_win():
win = Toplevel(root)
label1 = Label(win, text='Text on TopWindow level', font=20)
label1.pack()
def exit_app():
root.destroy() # Уничтожаем главное окно и всех его потомков
root = Tk()
main_menu = Menu(root)
root.configure(menu=main_menu)
first_item = Menu(main_menu)
main_menu.add_cascade(label='File', menu=first_item)
first_item.add_command(label='New', command=new_win)
first_item.add_command(label='Exit', command=exit_app)
second_item = Menu(main_menu, tearoff=0) # tearoff=0 запретит отрывать меню от гл. окна
main_menu.add_cascade(label='Edit', menu=second_item)
second_item.add_command(label='Item1')
second_item.add_command(label='Item2')
second_item.add_command(label='Item3')
second_item.add_separator()
second_item.add_command(label='Item4')
root.mainloop()
|
from matplotlib import pyplot as plt
def neighbours(x,y,image):
img = image.copy()
row, column = img.shape
x_left, x_right, y_down, y_up = neighbors = x-1, x+1, y-1, y+1
neighbours = -1
for i in range(x_left, x_right+1):
for j in range(y_down, y_up+1):
neighbours += image[j][i]
adjacent = False
if (all(i in range(0, column-1) for i in (x, x_left, x_right))):
if (all(j in range(0, row-1) for j in (y, y_down, y_up))):
adjacent = adjacentNeighbor(x,y,neighbors, image)
return neighbours,adjacent
def adjacentNeighbor(x,y,neighbors, image):
x_left, x_right, y_down, y_up = neighbors
adjacentNeighbor = False
if (image[y_up][x] == 1):
if (image[y_up][x_left] == 1 or image[y_up][x_right] == 1):
adjacentNeighbor = True
return adjacentNeighbor
if (image[y][x_right] == 1):
if (image[y_down][x_right] == 1 or image[y_up][x_right] == 1):
adjacentNeighbor = True
return adjacentNeighbor
if (image[y_down][x] == 1):
if (image[y_down][x_left] == 1 or image[y_down][x_right] == 1):
adjacentNeighbor = True
return adjacentNeighbor
if (image[y][x_left] == 1):
if (image[y_down][x_left] == 1 or image[y_up][x_left] == 1):
adjacentNeighbor = True
return adjacentNeighbor
return adjacentNeighbor
def find_nodes(image):
"Return a dict of nodes"
img = image.copy()
nodes = []
rows, columns = img.shape
# print(rows, columns)
for x in range(1, columns-1):
for y in range(1, rows-1):
if (img[y][x] == 1):
n, ad = neighbours(x,y,img)
if (not ad and n > 2):
nodes.append([x,y])
return nodes
def show_img(image):
plt.figure()
plt.imshow(image)
plt.show() |
edad = input('ingrese su edad \n==>')
if edad.isnumeric():
edad = int(edad)
if edad<18:
print('no pasas')
elif edad >= 17 and edad <21:
print('paga 60 tanto')
elif edad >22:
print('paga 70 dolares')
else:
print('paga 50 dolares especil')
else:
print('no ingresaste una edad')
|
""" Write a function distance_between_points(p1, p2) that takes two points
and returns the Cartesian distance between them.
"""
import math
class Point:
"""Represents a point in a 2D space"""
def distance(point_a,point_b):
dis=math.sqrt((point_a.x-point_b.x)**2+(point_a.y-point_b.y)**2)
return dis
point_a=Point()
point_b=Point()
point_a.x=0
point_a.y=1
point_b.x=4
point_b.y=2
""" Create a Fraction() class with only the basic attributes. Assume that the inputs are numbers.
a. Override some operators so that you can add a Fraction to an integer (Fraction() + int only,
not int + Fraction()).
b. Override the operator that allows you to check which fraction is larger between the two.
"""
class Fraction:
"""
Models a fraction with a numerator and a denominator, assuming the inputs are numbers
Attributes:
num - int, float - numerator
denom - int, float - denomerator
value - num/denom
Methods:
Can be added and compared to other fractions
"""
def __init__(self, num=int, denom=int):
self.num=num
self.denom=denom
if self.denom == 0:
self.value = None
else:
self.value = num / denom
def __str__(self):
return f"{self.num}/{self.denom} (= {self.value})"
def __add__(self, other):
if isinstance(other, int):
num_int=self.denom*other
return Fraction(self.num+num_int,self.denom)
def __gt__(self, other):
if isinstance(other, Fraction):
return self.value > other.value
elif isinstance(other, int):
return self.value > other
""" Create a Path() class, symboling a directory in a mock filesystem.
The class should at least one attribute, named files, containing the list of files in the folder,
and three methods, not including the mandatory __init__ method:
Path.get_parent() - returns the name of the parent folder of our Path (not the entire path).
The Path.get_size() - returns a number corresponding to the size in KB of the folder,
which should depend on the number of files in the folder.
Path.set_path(Path()) - Change the current directory to the one given (as a Path() instance).
After you've created it, overload the division operator / (__truediv__) to concatenate a Path class instance with a string pointing to a folder."""
import os, os.path
class Path:
"""
File system path to folders, allows the use of "/" to move between folders
Attributes:
path - str
files - list of str
Methods:
get_parent - returns parent folder as Path
get_size - returns size of current folder in KB
set_path(new_path) - changes current path to the .path attribute of new_path
"""
def __init__(self, path, files=['a.txt', 'b.py', 'c.c']):
self.path=path
self.files=files
def get_parent(self):
return os.path.abspath(os.path.join(self.path, os.pardir))
def get_size(self):
folder_size = 0
for (path, dirs, files) in os.walk(self.path):
for file in files:
filename = os.path.join(path, file)
folder_size += os.path.getsize(filename)
return folder_size/1024
def set_path(self, new_path):
self.path = new_path.path
self.files = new_path.files
def __truediv__(self, other):
"""
Traverse the filesystem using the / sign, assuming that
other isn't an absolute path.
Returns a new instance
"""
assert type(other) in (str, int)
new_path = self.path + os.sep + str(other)
new_files = []
return Path(path=new_path, files=new_files) |
firstnumber = int(raw_input("Enter first number"))
secondnumber = int(raw_input ("Enter the number that you wich to multiply by"))
print "Are this the numbers that you which?"
print firstnumber, "X", secondnumber
for i in range(1, secondnumber + 1):
print firstnumber, 'times', i, '=', secondnumber * i
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 22 19:16:49 2021
@author: nitinsinghal
"""
# Chapter 10 - Unsupervised Learning - Clustering
# KMeans and Kmeans++ Clustering
#Import libraries
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn import metrics
import matplotlib.pyplot as plt
# Use the data science process steps given in chapter 6 to build the Kmeans++ Clustering model
# Import the data
data = pd.read_csv('/Users/nitinsinghal/DataScienceCourse/Part1-MachineLearningDataAnalytics/Data/nbarookie5yrsinleague.csv')
# view top 5 rows for basic EDA
print(data.head())
# Data wrangling to replace NaN with 0, drop duplicate rows
data.fillna(0, inplace=True)
data.drop_duplicates(inplace=True)
# Get the X variables for training the clustering model.
# The y variables are only used for accuracy metrics, not for training the model
X = data.iloc[:, [1,3]].values
y = data.iloc[:, -1:].values
y = y.ravel()
# No need to split the data into training and test sets as it is an unsupervised algorithm
# No need to scale the data as different feature scales are used for different clusters
# Plot the Inertia (Within Cluster Sum of Squares) for different no of clusters and
# different random number for centroid initialization
# Used to identify the elbow of the curve to determine optimal value
# default n_clusters=8, but we can try from 1 to 10 and increase as necessary
for i in (42,50):
inertia = []
for j in range(1,10):
clustermodel = KMeans(init='k-means++', n_clusters=j, n_init=10, max_iter=300, random_state=i).fit(X)
inertia.append(clustermodel.inertia_)
fig, ax = plt.subplots()
ax.plot(range(1,10), inertia)
plt.title('Inertia(WCSS)- Seed: '+ str(i))
plt.xlabel('Clusters')
plt.ylabel('inertia(wcss)')
plt.tight_layout()
plt.show()
# Using the model fit and predict y values using X
clustermodel = KMeans(init='k-means++', n_clusters=2, n_init=10, max_iter=300, random_state=42)
y_pred = clustermodel.fit_predict(X)
# Plot the trained model clusters in 2D
labels = np.unique(clustermodel.labels_)
colours = ['red','green','blue','darkorange','cyan','magenta']
fig, ax = plt.subplots()
for i in labels:
ax.scatter(X[y_pred == i, 0], X[y_pred == i, 1], c=colours[i], label=i)
ax.scatter(clustermodel.cluster_centers_[:,0],clustermodel.cluster_centers_[:,1],s=100,color='black',label='Centroid')
x_min, x_max = X[:, 0].min()-2, X[:, 0].max()+2
y_min, y_max = X[:, 1].min()-2, X[:, 1].max()+2
ax.set_xlim(x_min, x_max)
ax.set_ylim(y_min, y_max)
plt.title('Clustering KMeans++ (Training Set)')
plt.xlabel('GP')
plt.ylabel('PTS')
plt.legend()
plt.tight_layout()
plt.show()
# Accuracy metrics
print('silhouette_score: ', metrics.silhouette_score(X, clustermodel.labels_, metric='euclidean'))
print('adjusted_rand_score: ', metrics.adjusted_rand_score(y, y_pred))
print('homogeneity_score: ', metrics.homogeneity_score(y, y_pred))
print('completeness_score: ', metrics.completeness_score(y, y_pred))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 16:47:15 2021
@author: nitinsinghal
"""
# Chapter 2 - Pandas - Data Analysis Library
import pandas as pd
import numpy as np
d = {'item': ['a','b','c','d','e','f'],
'price': [10, 25, 33.43, 51.2, 9, np.nan],
'quantity': [48, 12, 7, 3, 80, 100]}
df = pd.DataFrame(d)
df['value'] = df['price']*df['quantity']
print(df)
#View
print(df.dtypes)
print(df.index)
print(df.columns)
print(df.axes)
print(df.head(3))
print(df.tail(4))
df1 = df.copy()
print(df1)
#Indexing/Slicing
df.loc[:,'value']
df.iloc[2, 3]
df[2:]
df[['quantity', 'value']]
# conditional operations
print(df[df['price'] > 10])
print(df[df['quantity'].isin([7])])
df.loc[6,'item'] = 'g'
df.iloc[6,1] = 70
df.iloc[6,2] = 20
df.loc[6,'value'] = 70*20
print(df)
# Apply Function
df['price'] = df['price'].apply(lambda a: a*10)
print(df)
# Using axis. 0 means index or rows, 1 means columns.
print(df.sum(axis=0))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 13:27:51 2021
@author: nitinsinghal
"""
# Chapter 1 – Programming – Python
# Data Structures
# Lists
mylist = [1,3,6,8,9,9,15]
print(mylist)
print(mylist[1])
mylist[5] = 18
print(mylist)
mylist.append(32)
print(mylist)
words = ['car', 'fruit', 'ball']
print(words)
print(words[2])
words.append('book')
print(words)
print(words.pop())
print(words)
combolist = [2,10,78.5,-54.2,'bat','city']
print(combolist)
#Indexing/Slicing
print(mylist[:])
print(mylist[0])
print(mylist[2:4])
print(mylist[3:])
print(mylist[:3])
print(mylist[-2:])
print(mylist[:-4])
print(words[1])
print(words[0:2])
print(words[-2])
#Array - not native. Created using lists
myArray=[[1,2],[3,4],[5,6]]
print(myArray)
print(myArray[0])
print(myArray[0][1])
comboarray = [[1,-9,3.6],['orange','apple'],[-173,0,83.14,'john','sea']]
print(comboarray)
print(comboarray[1])
print(comboarray[2][3])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 13:27:51 2021
@author: nitinsinghal
"""
# Chapter 1 – Programming – Python
# Data Structures
#Sets
myset = {'cow', 'cat', 'dog'}
print(myset)
print(myset[0])
myset.add('rat')
print(myset)
myset.remove('cow')
print(myset)
print(myset.pop())
myset.add('cat')
print(myset)
#Tuples
mytuple = (2,4,6,8)
print(mytuple)
print(mytuple[1])
mytuple.remove(2)
mytuple.add(10)
mytuple.pop()
#Dictionary
mydictionary = {'Name': 'Tom', 'Age': '22', 'City': 'London'}
for key, value in mydictionary.items():
print(key, value)
for value in mydictionary.values():
print(value)
mydictionary.get('Name')
mydictionary.update({'Name':'Jerry'})
print(mydictionary)
mydictionary.pop('Name')
print(mydictionary)
dictcollection = {
'person1': {'Name': 'Tom', 'Age': '22', 'City': 'London'},
'person2': {'Name': 'Jerry', 'Age': '24', 'City': 'New York'},
'person3': {'Name': 'Bruno', 'Age': '26', 'City': 'Paris'}
}
for key, value in dictcollection.items():
print(key, value)
|
fresh_tea_list = [ {'name':'阿里山冰茶', 'price':"25",'尺寸':'L'},
{'name':'日月潭紅玉', 'price':"30",'尺寸':'L'},
{'name':'文山包種茶', 'price':"35",'尺寸':'XL'},
]
fresh_tea_list_price1 = int(fresh_tea_list[0]['price'])
fresh_tea_list_price2 = int(fresh_tea_list[1]['price'])
fresh_tea_list_price3 = int(fresh_tea_list[2]['price'])
total = fresh_tea_list_price1 + fresh_tea_list_price2 + fresh_tea_list_price3
print(total)
# fresh_tea_list_price=int(fresh_tea_list[0]['price'])+int(fresh_tea_list[1]['price'])+int(fresh_tea_list[2]['price'])
# print(fresh_tea_list_price) |
import sys
def reverse(string):
print(string[::-1])
if __name__ == "__main__":
input = sys.argv[1]
reverse(input) |
def binary_search(A, toFind):
left = 0
right = len(A) - 1
while left <= right:
mid = (left + right) // 2
if A[mid] == toFind: # Returns index
return mid
elif A[mid] < toFind: # If smaller than toFind, discard current and left side.
left = mid + 1
else: # If greater than toFind, discard current and left side.
right = mid -1
return -1
test_list = [1,3,9,11,15,19,29]
test_val1 = 15
print(binary_search(test_list, test_val1)) |
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
carry = 0
root = l3 = ListNode(0)
while l1 or l2 or carry:
if l1:
val1 = l1.val
l1 = l1.next
else:
val1 = 0
if l2:
val2 = l2.val
l2 = l2.next
else:
val2 = 0
carry,val3 = divmod(val1+val2+carry,10)
l3.next = ListNode(val3)
l3 = l3.next
return root.next
|
a=int(input('Enter range of series: '))
b=0
c=1
r=" "
print('FIBONACCI SERIES: ')
for i in range(a+1):
print(b, r)
d=b+c
b=c
c=d
|
R = float(input())
v = (4/3.0) * 3.14159 * (R*R*R)
print("VOLUME = {:.3f}".format(v))
|
d = input().split()
a = float(d[0])
b = float(d[1])
c = float(d[2])
tri = a*c/2
cir = 3.14159*(c*c)
tra = (a+b)/2 *c
qua = b*b
ret = a*b
print("TRIANGULO: {:.3f}\nCIRCULO: {:.3f}\nTRAPEZIO: {:.3f}\nQUADRADO: {:.3f}\nRETANGULO: {:.3f}".format(tri, cir, tra, qua, ret)) |
for i in range(int(input())):
stack = list()
a = input()
for j in a:
if(j == '(') :
stack.append('(')
elif(j == ')') :
if (len(stack) == 0 or stack[0] != '(') : stack.append("Error")
else : stack.pop()
if(len(stack)==0) : print("YES")
else : print("NO") |
""" Linear Algebra Project 1
202011353 이호은 """
import cv2
import numpy as np
# N by N Haar Matrix 생성
def MakeNHaarMatrix(n):
array_A = np.array([[1], [1]])
array_B = np.array([[1], [-1]])
# n이 1이면
if n == 1:
return np.array([1])
# n이 2 이상이면
else:
m = 1
H_m = np.array([1])
for i in range(2, n + 1):
new_array = np.hstack([np.kron(H_m, array_A), np.kron(np.eye(m), array_B)])
m *= 2
if m == n:
return new_array
else:
H_m = new_array
# N x N 행렬에서 좌측 상단 k x k만큼 잘라 행렬에 넣고 다시 복원
def MakeCroppedImage(B, normalized_H_n, k, n):
# 파일 이름 설정
file_name = "result_" + str(k) + ".bmp"
# Crop (자르기)
Bhat = np.zeros((n, n))
temp_Bhat = B[0: int(n / k), 0: int(n / k)]
for i in range(int(n / k)):
for j in range(int(n / k)):
Bhat[i][j] = temp_Bhat[i][j]
# 복원
Ahat = (normalized_H_n.dot(Bhat)).dot(normalized_H_n.T)
# 복원된 A hat 출력
print("======================================")
print(f"Ahat Matrix of result_{k} : \n{Ahat}")
# 이미지 파일로 저장
cv2.imwrite(file_name, Ahat)
print(f"\n{file_name} created successfully!")
print("======================================", end='\n\n')
# 종료
# 이미지 출력 함수
def ShowImage(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
cv2.destroyWindow(name)
# 결과 이미지 출력 함수
def showResult():
for i in range(1, 9):
file_name = "result_" + str(2 ** i) + ".bmp"
img = cv2.imread(file_name, cv2.IMREAD_GRAYSCALE)
cv2.imshow(file_name, img)
cv2.waitKey(0)
cv2.destroyWindow(file_name)
if __name__ == '__main__':
# 이미지 읽기
original_image = cv2.imread('image_lena_24bit.bmp', cv2.IMREAD_GRAYSCALE)
height, width = original_image.shape
print(f"height : {height}, width : {width}", end='\n')
cv2.imshow("original", original_image)
cv2.waitKey(0)
cv2.destroyWindow("original")
# 사진 크기 추출
n = height
# Numpy Array 로 변환
original_array = np.array(original_image)
print(f"Original Photo Array : \n{original_array}")
# N by N 크기의 Haar Matrix 생성
H_n = MakeNHaarMatrix(n)
print(f"N Haar Matrix (H_n) : \n{H_n}")
# Normalization
normalized_H_n = np.zeros((n, n))
for i in range(n):
s = 0
for j in range(n):
if H_n[j][i] != 0:
s += 1
for j in range(n):
normalized_H_n[j][i] = H_n[j][i] / (s ** 0.5)
# DHWT : B = H^TAH
B = (normalized_H_n.T.dot(original_array)).dot(normalized_H_n)
print(f"B (DHWT) : \n{B}")
# 1/2 ~ 1/256 크롭 이미지 복원 및 저장
for i in range(1, 9):
MakeCroppedImage(B, normalized_H_n, 2 ** i, n)
# 사진 순서대로 출력
showResult()
|
def check(a,b,c):
if (a+b==c or a-b == c or b-a==c or b*a== c):
print("Possible")
return
elif a == 0 and c == 0:
print("Possible")
return
elif b == 0 and c == 0:
print("Possible")
return
elif a/b == c or b/a ==c:
print("Possible")
return
else:
print("Impossible")
n = int(input())
for i in range(n):
x,y,z = map(int, input().split(" "))
check(x,y,z) |
from math import cos, sin, radians
def check_safe(v0, theta, x1, h1, h2):
t = x1/(v0*cos(radians(theta)))
center = v0*t*sin(radians(theta))-.5*9.81*(t**2)
if center-1 > h1 and center+1 < h2:
print("Safe")
else:
print("Not safe")
cases = int(input())
for i in range(cases):
v0, theta, x1, h1, h2 = map(float, input().split())
check_safe(v0, theta, x1, h1, h2)
|
steps = list(map(int, input().split(" ")))
min_side = min(steps)
max_side = -1
max_steps = max(steps)
second_biggest = -1
idx = -1
found_max = False
for i in range(4):
if (steps[i] == max_steps and found_max is False):
found_max = True
elif steps[i] == max_steps:
max_side = max_steps
break
elif steps[i] > max_side:
max_side = steps[i]
print(min_side*max_side)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from random import randint
class Food(object):
def __init__(self, game):
self.position = None
self.color = (255, 0, 0)
self.game = game
def draw(self):
if self.position:
self.game.draw_rect(self.position, self.color)
def generate(self, forbidden_positions = None):
forbidden = [] if not forbidden_positions else forbidden_positions
new_position = None
while not new_position or new_position in forbidden:
new_position = [randint(0, self.game.grid[0]-1), randint(0, self.game.grid[1]-1)]
self.position = new_position |
# NOTE: This problem is a significantly more challenging version of Problem 81.
#
# In the 5 by 5 matrix below, the minimal path sum from the top left to the
# bottom right, by moving left, right, up, and down, is indicated in bold
# red and is equal to 2297.
#
# 131 673 234 103 18
# 201 96 342 965 150
# 630 803 746 422 111
# 537 699 497 121 956
# 805 732 524 37 331
#
# 131 -> 201 -> 96 -> 342 -> 234 -> 103 -> 18 -> 150 -> 111 -> 422 -> 121 -> 37 -> 331
#
# Find the minimal path sum, in matrix.txt (right click and "Save Link/Target As..."),
# a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right
# by moving left, right, up, and down.
#
# Algorithmic approach thoughts: I don't think I can use recursion/dynamic programmming.
# I think Djikstra's should work for this though.
import math
class Graph:
def __init__(self):
self.nodes = []
self.head = None
self.end = None
class Node:
def __init__(self, value, start=False, end=False):
self.value = value
self.start = start
self.end = False
self.neighbors = []
self.visited = False
self.previous = None
# For Dijkstra's, start all non-head nodes at infinity.
# Normally start source at 0, but here the value of the node
# is the cost.
self.distance = math.inf if not start else value
def __str__(self):
return str(self.value)
# map x,y to Node
already_built = {}
def build_graph(matrix):
g = Graph()
g.head = build_node(matrix, 0, 0, g)
return g
def build_node(matrix, row, col, graph):
if (row, col) in already_built:
return already_built[(row, col)]
end_row = len(matrix) - 1
end_col = len(matrix[0]) - 1
start = row == 0 and col == 0
end = row == end_row and col == end_col
new_node = Node(matrix[row][col], start=start, end=end)
already_built[(row, col)] = new_node
graph.nodes.append(new_node)
if end:
graph.end = new_node
neighbors = []
if row > 0:
neighbors.append(build_node(matrix, row-1, col, graph))
if row < end_row:
neighbors.append(build_node(matrix, row+1, col, graph))
if col > 0:
neighbors.append(build_node(matrix, row, col-1, graph))
if col < end_col:
neighbors.append(build_node(matrix, row, col+1, graph))
new_node.neighbors.extend(neighbors)
return new_node
def read_input(file):
matrix = []
for line in file:
matrix.append([int(entry) for entry in line.strip().split(",")])
width = len(matrix[0])
for row in matrix:
assert len(row) == width
return matrix
def pop_shortest(verts):
# This could be faster (using a min_heap possibly)?
m = min(verts, key=lambda vert: vert.distance)
verts.remove(m)
return m
def min_path_sum(graph):
# Huge speed up by only tracking nodes as we encounter them
# rather than starting with all nodes as unvisited.
unvisited_verts = [graph.head]
while unvisited_verts:
node = pop_shortest(unvisited_verts)
node.visited = True
for n in node.neighbors:
new_dist = node.distance + n.value
if new_dist < n.distance:
n.distance = new_dist
n.previous = node
# This could add a duplicate node to the list.
# It doesn't cause a problem here, but it could be avoided
# if needed.
unvisited_verts.append(n)
path_values = []
n = graph.end
while n:
path_values.append(str(n.value))
n = n.previous
print(" -> ".join(reversed(path_values)))
return graph.end.distance
def solve_matrix(matrix):
graph = build_graph(matrix)
print(f"Graph built with {len(graph.nodes)} nodex.")
return min_path_sum(graph)
def solve(filename):
with open(filename) as in_file:
mat = read_input(in_file)
return solve_matrix(mat)
if __name__ == '__main__':
# The recursion used to build the graph exceeds the default limit.
import sys
sys.setrecursionlimit(7000)
print(solve("matrix.txt"))
|
# In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the right and down, is indicated in bold red and is equal to 2427.
#
# 131 673 234 103 18
# 201 96 342 965 150
# 630 803 746 422 111
# 537 699 497 121 956
# 805 732 524 37 331
#
# Find the minimal path sum, in matrix.txt (right click and "Save Link/Target As..."), a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right by only moving right and down.
#
# Algorithmic approach thoughts: Recursive, dynamic programming most likely will be a good fit.
# (row, col) -> answer
cache ={}
def read_input(file):
matrix = []
for line in file:
matrix.append([int(entry) for entry in line.strip().split(",")])
width = len(matrix[0])
for row in matrix:
assert len(row) == width
return matrix
def min_path_sum(matrix, row, col):
if (row, col) in cache:
return cache[(row, col)]
max_row = len(matrix) - 1
max_col = len(matrix[0]) - 1
answer = None
if row == max_row and col == max_col:
answer = matrix[row][col]
elif col == max_col:
answer = matrix[row][col] + min_path_sum(matrix, row+1, col)
elif row == max_row:
answer = matrix[row][col] + min_path_sum(matrix, row, col+1)
else:
answer = matrix[row][col] + min(min_path_sum(matrix, row, col+1), min_path_sum(matrix, row+1, col))
cache[(row, col)] = answer
return answer
def solve(filename):
with open(filename) as in_file:
mat = read_input(in_file)
return min_path_sum(mat, 0, 0)
if __name__ == '__main__':
print(solve("matrix.txt"))
|
#
#
# A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
#
# 012 021 102 120 201 210
#
# What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?
#
from itertools import permutations
def solve(digits):
perms = permutations(digits)
return "".join(map(str, list(perms)[999999]))
if __name__ == '__main__':
print(solve([0,1,2,3,4,5,6,7,8,9]))
|
#
#
# If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
#
# Not all numbers produce palindromes so quickly. For example,
#
# 349 + 943 = 1292,
# 1292 + 2921 = 4213
# 4213 + 3124 = 7337
#
# That is, 349 took three iterations to arrive at a palindrome.
#
# Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits).
#
# Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.
#
# How many Lychrel numbers are there below ten-thousand?
#
# NOTE: Wording was modified slightly on 24 April 2007 to emphasise the theoretical nature of Lychrel numbers.
#
LIMIT = 10000
def is_pal(num):
s = str(num)
return list(reversed(s)) == list(s)
# This could be optimized by caching values that eventually lead to palindromes,
# but this solution completes instantly for this problem space.
def leads_to_pal(num, attempts):
for i in range(attempts):
num = num + int("".join(list(reversed(str(num)))))
if is_pal(num):
return True
def solve(limit):
num_lyc = 0
for i in range(1, limit):
if not leads_to_pal(i, 50):
num_lyc += 1
return num_lyc
if __name__ == '__main__':
print(solve(LIMIT))
|
from microbit import *
pin1.write_analog(90) # reset to straight on start
MAX_ANGLE = 15
MID_ANGLE = 90
def norm(n):
"""
Normalise an accelerometer reading across an angle.
Returns an offset angle to apply to the base (90) in
whichever direction it is steering.
"""
n = abs(n)
if n < 100:
a = 0 # don't want too much jitter
else:
p = n / 1024 # percentage of total angle
a = int(MAX_ANGLE * p)
return a
while True:
x = accelerometer.get_x()
off = norm(x)
angle = MID_ANGLE + (off if x < 0 else (-1 * off))
pin1.write_analog(angle)
#print(angle)
sleep(50) |
#!/usr/bin/python3
def fizzbuzz():
for fb in range(1, 101):
if fb % 3 == 0 and fb % 5 == 0:
print("FizzBuzz ", end='')
elif fb % 3 == 0:
print("Fizz ", end='')
elif fb % 5 == 0:
print("Buzz ", end='')
else:
print("{} ".format(fb), end='')
|
#!/usr/bin/python3
"""
function that reads a text file (UTF8) and prints it to stdout
"""
import json
def to_json_string(my_obj):
"""defining to_json_string function"""
return json.dumps(my_obj)
|
#!/usr/bin/python3
for alpha in range(9):
for alpha2 in range(alpha + 1, 10):
if alpha != alpha2:
if alpha == 8 and alpha2 == 9:
print("{}{}".format(alpha, alpha2))
else:
print("{}{}, ".format(alpha, alpha2), end='')
else:
continue
|
count = 10
while count > 0:
if count % 2 == 0:
print(count)
count = count - 1
print("Happy New Year!")
|
from turtle import *
# count = 4
#
# while count > 0 :
# print(forward(300))
# right(90)
# count = count -1
# steve = 1
# limit = 300
#
# speed(30)
# pencolor('cyan')
#
# while steve < limit :
# forward(steve)
# left(89)
# steve = steve + 1
print ( bgcolor("orange") )
colors = ['red', 'purple', 'blue', 'green', 'yellow', 'orange']
for x in range(360):
pencolor(colors[x % 6])
width(x / 100 + 1)
forward(x)
left(59)
done()
# https://github.com/asweigart/simple-turtle-tutorial-for-python/blob/master/simple_turtle_tutorial.md
|
class RingBuffer:
# This class starts out empty (not full yet)
def __init__(self, capacity):
# Give the class a max size
self.capacity = capacity
self.data = []
# Appends an element at the end of the buffer
def append(self, item):
self.data.append(item)
# If the length reaches max...
if len(self.data) == self.capacity:
self.cur = 0
# Change class from non-full to full
self.__class__ = self.RingBufferFull
# Returns a list of elements from oldest to newest
def get(self):
return self.data
class RingBufferFull:
def __init__(self, n):
raise "string"
# Appends an element overwriting the oldest one
def append(self, item):
self.data[self.cur] = item
self.cur = (self.cur + 1) % self.capacity
# Returns the list of elements in correct order
def get(self):
return self.data
|
参考文献:https://www.cnblogs.com/ajaxa/p/9049518.html
多态的理解:
一 多态
多态指的是一类事物有多种形态
动物有多种形态:人,狗,猪
复制代码
import abc
class Animal(metaclass=abc.ABCMeta): #同一类事物:动物
@abc.abstractmethod
def talk(self):
pass
class People(Animal): #动物的形态之一:人
def talk(self):
print('say hello')
class Dog(Animal): #动物的形态之二:狗
def talk(self):
print('say wangwang')
class Pig(Animal): #动物的形态之三:猪
def talk(self):
print('say aoao')
复制代码
文件有多种形态:文本文件,可执行文件
复制代码
import abc
class File(metaclass=abc.ABCMeta): #同一类事物:文件
@abc.abstractmethod
def click(self):
pass
class Text(File): #文件的形态之一:文本文件
def click(self):
print('open file')
class ExeFile(File): #文件的形态之二:可执行文件
def click(self):
print('execute file')
复制代码
二 多态性
一 什么是多态动态绑定(在继承的背景下使用时,有时也称为多态性)
多态性是指在不考虑实例类型的情况下使用实例
在面向对象方法中一般是这样表述多态性:向不同的对象发送同一条消息(!!!obj.func():是调用了obj的方法func,又称为向obj发送了一条消息func),不同的对象在接收时会产生不同的行为(即方法)。也就是说,每个对象可以用自己的方式去响应共同的消息。所谓消息,就是调用函数,不同的行为就是指不同的实现,即执行不同的函数。比如:老师.下课铃响了(),学生.下课铃响了(),老师执行的是下班操作,学生执行的是放学操作,虽然二者消息一样,但是执行的效果不同
多态性分为静态多态性和动态多态性
静态多态性:如任何类型都可以用运算符+进行运算
动态多态性:如下
复制代码
peo=People()
dog=Dog()
pig=Pig()
#peo、dog、pig都是动物,只要是动物肯定有talk方法
#于是我们可以不用考虑它们三者的具体是什么类型,而直接使用
peo.talk()
dog.talk()
pig.talk()
#更进一步,我们可以定义一个统一的接口来使用
def func(obj):
obj.talk()
复制代码
二 为什么要用多态性(多态性的好处)
其实大家从上面多态性的例子可以看出,我们并没有增加什么新的知识,也就是说python本身就是支持多态性的,这么做的好处是什么呢?
1.增加了程序的灵活性
以不变应万变,不论对象千变万化,使用者都是同一种形式去调用,如func(animal)
2.增加了程序额可扩展性
通过继承animal类创建了一个新的类,使用者无需更改自己的代码,还是用func(animal)去调用
复制代码
>>> class Cat(Animal): #属于动物的另外一种形态:猫
... def talk(self):
... print('say miao')
...
>>> def func(animal): #对于使用者来说,自己的代码根本无需改动
... animal.talk()
...
>>> cat1=Cat() #实例出一只猫
>>> func(cat1) #甚至连调用方式也无需改变,就能调用猫的talk功能
say miao
'''
这样我们新增了一个形态Cat,由Cat类产生的实例cat1,使用者可以在完全不需要修改自己代码的情况下。使用和人、狗、猪一样的方式调用cat1的talk方法,即func(cat1)
'''
复制代码
三 鸭子类型
逗比时刻:
Python崇尚鸭子类型,即‘如果看起来像、叫声像而且走起路来像鸭子,那么它就是鸭子’
python程序员通常根据这种行为来编写程序。例如,如果想编写现有对象的自定义版本,可以继承该对象
也可以创建一个外观和行为像,但与它无任何关系的全新对象,后者通常用于保存程序组件的松耦合度。
例1:利用标准库中定义的各种‘与文件类似’的对象,尽管这些对象的工作方式像文件,但他们没有继承内置文件对象的方法
#二者都像鸭子,二者看起来都像文件,因而就可以当文件一样去用
class TxtFile:
def read(self):
pass
def write(self):
pass
class DiskFile:
def read(self):
pass
def write(self):
pass
例2:其实大家一直在享受着多态性带来的好处,比如Python的序列类型有多种形态:字符串,列表,元组,多态性体现如下
#str,list,tuple都是序列类型
s=str('hello')
l=list([1,2,3])
t=tuple((4,5,6))
#我们可以在不考虑三者类型的前提下使用s,l,t
s.__len__()
l.__len__()
t.__len__()
len(s)
len(l)
len(t)
|
import pandas as pd
# 再pandas中一行一列都是一个序列,类似于字典一样,可以将字典转成序列,索引index就是键
dat = {"a": 10, "b": 20, "c": 30}
s1 = pd.Series(dat, index=dat.keys(), name="A")
print(s1.index)
# 还可以使用指定索引的创建方法
l1 = ['a', 'b', 'c', 'd']
l2 = [100, 200, 300, 400]
s2 = pd.Series(l2, index=l1, name="B")
print(s2.index)
# 将序列加入到dataFrame中,才能算一行或一列, 以字典形式加的话,就是列
data = pd.DataFrame({s1.name: s1, s2.name: s2})
print(data)
# 会把序列的名字当做行号,把索引当做列号
data2 = pd.DataFrame([s1, s2])
print(data2)
# 如果两个序列中,有的格有交集,有的没有交集,那就将有交集的填上,没有交接的就赋值NaN,也就是没有一个值
|
import asyncio
import time
import functools
"""
参考文章:https://segmentfault.com/a/1190000008814676
"""
async def first():
print("nihao shijie")
await asyncio.sleep(3)
return "first"
async def second():
print("woshi d")
await asyncio.sleep(1)
return "second"
async def three():
print("woshi disange")
await asyncio.sleep(1)
return "three"
def call_back(loop, futu):
print("调用回调函数")
# 在回调函数中,同样会将future对象传进来,因此获取到一步函数的返回值
print(futu.result(), 111111111)
loop.stop()
if __name__ == '__main__':
start = time.time()
# 获得时间循环对象
loop = asyncio.get_event_loop()
# 创建异步协成列表
geater = [first(), second(), three()]
# 可以创建一个future对象,将多个异步任务合并成一个future
futu = asyncio.gather(*geater)
# 使用future添加异步任务都完成后的回调函数
# functools.partial会先将函数的部分参数传递进去,等所有参数都传递完了,再开始调用
futu.add_done_callback(functools.partial(call_back, loop))
# 使用ayncio.gather将事件添加进时间循环
# loop.run_until_complete(asyncio.gather(*geater))
loop.run_forever()
# 循环完成后,关闭事件循环
# loop.close()
ends = time.time()
print(ends-start)
|
1 #利用集合,直接将列表转化为集合,自动去重后转回列表。有一个问题,转换为集合的同时,数据无序了。
2 # li = [11,22,22,33,44,44]
3 # set = set(li)
4 # li = list(set)
5 # print(li)
6 #
7 #
8 # 第二种运用新建字典的方式,去除重复的键
9 # list = [11,22,33,22,44,33]
10 # dic = {}
11 # list = dic.fromkeys(list).keys()#字典在创建新的字典时,有重复key则覆盖
12 # print(list)
13 #
14 #
15 #
16 #第三种是用列表的推导
17 # list = [11,22,33,22,44,33]
18 # lis = [] #创建一个新列表
19 # for i in list: #循环list里的每一个元素
20 # if i not in lis: #判断元素是否存在新列表中,不存在则添加,存在则跳过,以此去重
21 # lis.append(i)
22 # print(lis)
23 #
24 #
25 #
26 #第四种仅仅只是将for循环变为while循环
27 # list = [11,22,33,22,44,33]
28 # result_list=[]
29 # temp_list=list
30 # i=0
31 # while i<len(temp_list):
32 # if temp_list[i] not in result_list:
33 # result_list.append(temp_list[i])
34 # else:
35 # i+=1
36 # print(result_list)
|
import pandas as pd
data = pd.read_excel("pd操作.xlsx", index_col="ID")
# 计算列相乘,运算符重载,前面行和后面每一行一一对应相乘
# data["Price"] = data['Lprice'] * data['Cate']
# 只对指定行的数据做运算
for i in range(1, 6):
data["Price"].at[i] = data["Lprice"].at[i] * data["Cate"].at[i]
def add_2(x):
return x + 2
# 可以对每一项做函数调用计算操作
# data["Lprice"] = data["Lprice"].apply(lambda x: x + 2)
data["Lprice"] = data["Lprice"].apply(add_2)
print(data)
|
# TASK 1
# Importing the necessary classes and methods
from flask import Flask,jsonify,request,render_template,make_response,send_file,redirect
import requests
# Creating an instance of Flask class
app = Flask(__name__)
# Displaying a Hello World string
# The decorator (@app.route('/')) followed by the method to invoke
@app.route('/')
def index():
return 'Hello World - Priyadarshini J R'
# Displaying the list of authors with the count of posts
@app.route('/authors')
def authors():
# Initialising a dictionary
detail = dict()
# Fetching data from the given URLs in the json format
author_data = requests.get('https://jsonplaceholder.typicode.com/users').json()
post_data = requests.get('https://jsonplaceholder.typicode.com/posts').json()
# For every author, initially setting count to 0
for author in author_data:
detail[author['name']] = 0
userid = author['id']
# Comparing the id of an author with the userId of every post
for post in post_data:
if userid == post['userId']:
detail[author['name']] += 1
# Dictionary cannot be returned as such, use jsonify
return jsonify(detail)
# To set cookies containing age and name
@app.route('/setcookie')
def setcookie():
# Response to be displayed
resp = make_response('Cookies set with name and age.')
resp.set_cookie('Name','Priyadarshini')
resp.set_cookie('Age','21')
return resp
# Viewing the cookies set
@app.route('/getcookies')
def getcookie():
ck = request.cookies
# Dictionary of cookies (name value pair) must be jsonified
return jsonify(ck)
# Denying requests to a page
@app.route('/robots.txt')
def deny():
return 'You should not be here.'
# Rendering an HTML document
@app.route('/html')
def render_html():
# profile.html must be placed within the templates folder
# to be used by render_template
return render_template('profile.html')
# Rendering an image
@app.route('/image')
def render_image():
return send_file('sunset.jpg', mimetype='image/gif')
# Displaying a textbox, sending the data as POST to another endpoint
# Log the data to stdout
# This endpoint accepts both GET and POST requests
@app.route('/input',methods = ["GET","POST"])
def input_func():
# If the method is POST, getting the data from the form
# Redirect to a different endpoint while passing the data
if request.method == "POST":
name = request.form['input']
return redirect('/output/' + name)
# Displaying the form
return render_template('input.html')
# The data entered is passed in the URL
@app.route('/output/<name>')
def output(name):
# Output it to stdout
print("You entered : " + name)
return 'Welcome. Check your stdout for the name entered.'
# Run the file
if __name__ == '__main__':
app.run() |
# for item in ["mash","john","sera"]:
# print(item)
# for item in range(5,10,2):
# print(item)
# for x in range(4):
# for y in range(3):
# print(f"({x}, {y})")
numbers = [5, 2 , 5 ,2 ,2]
for item in numbers:
output = ""
for count in range(item):
output += "X"
print(output) |
def is_even (x):
if ( x % 2 ) == 0 :
return('TRUE')
else:
return('FALSE')
is_even(7) |
# Importing libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Importing data
dataset = pd.read_csv('Salary_Data.csv')
X = dataset.iloc[:,0:1].values
y = dataset.iloc[:,1].values
# Splitting into train and test sets
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=1/3)
# Applying simple linear regression
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train,y_train)
sample_output = regressor.predict([[3.5]])
y_pred = regressor.predict(X_test)
#Visualizing the training data
plt.scatter(X_train,y_train, color = 'red')
plt.plot(X_train,regressor.predict(X_train),color = 'blue')
plt.title('Sal vs Years')
plt.xlabel('Salary')
plt.ylabel('Years of Experience')
plt.show()
#Visualizing the test data
plt.scatter(X_test,y_test, color = 'red')
plt.scatter(X_test,y_pred, color = 'green')
plt.plot(X_train,regressor.predict(X_train),color = 'blue')
plt.title('Sal vs Years')
plt.xlabel('Salary')
plt.ylabel('Years of Experience')
plt.show()
|
num1 = int(input("Palun sisestage esimene arv:"))
num2 = int(input("Palun sisestage teine arv:"))
print ('Paarisarvud on:')
for x in range (num1, num2):
if (x % 2) == 0:
print(x)
|
"""
Extract the primary colors from each frame of a video file
"""
__author__ = "prOttonicFusion"
__version__ = "0.1.0"
__license__ = "MIT"
import sys
import cv2
import argparse
import numpy as np
from PIL import Image
def analyze_movie(
video_path, aspect_ratio=0, palette_size=32, frames=-1, step=1, show_frames=False, show_last_frame=False, color_format='hex'
):
"""Parses and prints out the primary color of every STEPth video frame
Parameters
----------
video_path : str
The path to the video file
aspect_ratio : float, optional
The aspect ratio used for cropping a video with vertical borders
palette_size: int, optional
Number of distinct colors in color space (Default: 32)
frames: int, optional
Number of frames to parse, with -1 meaning all frames (Default: -1)
step: int, optional
The step size between frames (Default: 1)
show_frames: bool, optional
Show each processed frame for debugging purposes (Default: False)
show_last_frame: bool, optional
Show last frame for debugging purposes (Default: False)
color_format: 'hex' or 'rgb'
Specify the output color format (Default: hex)
"""
# Parse video frame-by-frame
vidcap = cv2.VideoCapture(video_path)
success, image = vidcap.read()
pil_img = None
count = 0
while success and frames == -1 or count < frames:
if count % step == 0:
# Convert to PIL image
img = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
pil_img = Image.fromarray(img)
# Crop frame to remove border
if aspect_ratio != 0:
width, height = pil_img.size
left = 0
right = width
content_height = 1/aspect_ratio * width
border = (height - content_height) * 0.5
top = border
bottom = border + content_height
pil_img = pil_img.crop((left, top, right, bottom))
# Get primary color
main_color = get_primary_color(
pil_img, palette_size, show_img=show_frames)
if color_format == 'hex':
main_color = rgbToHex(main_color)
print(main_color)
# Attempt to read next frame
success, image = vidcap.read()
count += 1
if show_last_frame:
pil_img.show()
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('video_path', help='path to the video file')
parser.add_argument('--aspect_ratio', '-a',
help='specify the aspect ratio using the format 4:3 to crop out border, default: 0', default=0)
parser.add_argument('--palette_size', '-p',
help='number of distinct colors in color space, default 32', type=int, default=32)
parser.add_argument('--frames', '-f',
help='number of video frames to parse, with -1 being all, default: -1', type=int, default=-1)
parser.add_argument('--step', '-s',
help='step size, i.e. parse every STEPth frames, default: 1', type=int, default=1)
parser.add_argument('--show_frames',
help='show each processed frame for debugging purposes', action='store_true', default=False)
parser.add_argument('--show_last_frame',
help='show last frame for debugging purposes', action='store_true', default=False)
parser.add_argument('--color_format',
help='specify the color format as hex or rgb, default: hex', default='hex')
args = parser.parse_args()
if isinstance(args.aspect_ratio, str):
splitted = args.aspect_ratio.split(':')
try:
args.aspect_ratio = float(splitted[0])/float(splitted[1])
except:
raise(Exception('Unable to parse aspect ratio'))
if args.show_frames and args.frames == -1:
input("Warning: This will open each video frame in a new window. To continue, press enter")
return [args.video_path,
args.aspect_ratio,
args.palette_size,
args.frames,
args.step,
args.show_frames,
args.show_last_frame,
args.color_format]
def get_primary_color(source_img, palette_size, show_img=False):
"""Get the primary color of an image by scaling it down and reducing
the color palette
Parameters
----------
source_img : Image
The PIL image to use as source
palette_size: int
The number of distinct colors to reduce the image color palette to
show_img: bool, optional
Sets whether the modified image should be displayed
Returns
----------
primary_color : tuple
A RGB tuple describing the frame's most common color
"""
# Scale down image to conserve resources
img = source_img.copy()
img.thumbnail((100, 100))
# Reduce color palette (using k-means)
img_reduced = img.convert('P', palette=Image.ADAPTIVE, colors=palette_size)
if show_img:
img_reduced.show()
# Get list of colors in image
palette = img_reduced.getpalette()
# Find most common color
color_counts = sorted(img_reduced.getcolors(), reverse=True)
primary_index = color_counts[0][1]
primary_color = palette[primary_index*3:primary_index*3+3]
return primary_color
def rgbToHex(rgb_color):
"""Converts a RGB tuple to a hex color string"""
r, g, b = rgb_color
return '#{:02x}{:02x}{:02x}'.format(r, g, b)
if __name__ == "__main__":
args = parse_arguments()
analyze_movie(*args)
|
#----------------------------------------------------------------------------------------
# Description: This Python script uses the file newfile.txt and prints it's record such
# that the python interpretor counts "line two" but doesn't print it,
# and it stops after printing "line four".
#
#
# Parameters: None
#
# History:
# Date Author Description
# 2018-02-24 A.Patel Initial creation
#----------------------------------------------------------------------------------------
#assigning initial 0 value to the counter
count = 0
#open the file
Newfile = open('newfile.txt', 'r')
#print and count the specified lines in the file
for line in Newfile:
#Incrementing the counter in the for loop
count += 1
#command which skips line two
if line == "Line two\n" : continue
#command which stops after printing line four or breaks at line five
if line == "Line five\n" : break
#prints all the results which come true from the if statements
print(line, end='')
#print the number of lines in the file
print("There are " + str(count) + " lines in the file")
#close the file
Newfile.close()
|
#selection sort program
def selectionSort(a):
for i in range(len(a)):
minpos=i
for j in range(i+1,len(a)):
if a[j]<a[minpos]:
minpos=j
swap(a,i,minpos)
def swap(a,i,j):
a[i],a[j]=a[j],a[i]
print ("Enter array Elements")
arr=[int(x) for x in input().split(" ")]
selectionSort(arr)
print ("Sorted array ->",arr)
|
#Q1. Please provide a class in Python 3 that will include 3 different functions for rectangular prisms. The
#first function will calculate the surface area of a rectangular prism, the second one will calculate the
#volume of this prism, and the third one should properly print these two calculated values on the console.
class rectangular():
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
def area(self):
return 2*(self.a*self.b + self.b*self.c + self.a*self.c)
def volume(self):
return self.a*self.b*self.c
def print_info(self):
print ('Area: ', self.area())
print ('Volume: ',self.volume())
NewRect = rectangular(2,3,4)
NewRect.print_info()
#Q2. You are expected to understand the following class and provide the necessary comments to the given places (annotated with “# ….”).
class ComplexNumber():
def __init__(self,r = 0,i = 0): # we create an instance, default value of r and i will be zero.
self.real = r #if there is an r value of instance, it will be self.real now. If not, it will be zero.
self.imag = i #if there is an i value of instance, it will be self.imag now. If not, it will be zero.
def getData(self): # defining a function for ComplexNumber class
print("{0}+{1}j".format(self.real,self.imag)) #generate complex number with values of self paremeters of class.
c1 = ComplexNumber(2,3) #create an instance of ComplexNumber class with two parameters (r and i )
# No output because we did not call any function of created instance.
c1.getData() # Output: 2+3j
c2 = ComplexNumber(5) # #create an instance of ComplexNumber class with one parameters (r)
# No output because we did not call any function of created instance.
c2.attr = 10 # create a inclusive variable (attr) for c2 instance and assign 10 to it.
#Q3. Please make use of the following Customer class with providing Sarah and Hakeem two different
#accounts and a series of deposits. Please try to cover all the functions and attributes.
class Customer(object):
def __init__(self, name, balance=0.0):
self.name = name
self.balance = balance
def withdraw(self, amount):
if amount > self.balance:
raise RuntimeError('Amount greater than available balance.')
self.balance -= amount
return self.balance
def deposit(self, amount):
self.balance += amount
return self.balance
c1 = Customer("Sarah",1000.0)
c2=Customer("Hakeem",121.6)
#print ("remained balance of ",c1.name,c1.withdraw(5))
#print ("remained balance of ",c2.name,c2.deposit(15))
#Q4. You are expected to provide the descriptive statistics for the Boston dataset. You can make use of
#the following piece of codes to have a gentle start for this question:
#http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_boston.html
#http://www.neural.cz/dataset-exploration-boston-house-pricing.html
import pandas as pd
from sklearn.datasets import load_boston
dataset = load_boston()
#print(dataset['data'])
print(dataset['feature_names'])
#['CRIM' 'ZN' 'INDUS' 'CHAS' 'NOX' 'RM' 'AGE' 'DIS' 'RAD' 'TAX' 'PTRATIO' 'B' 'LSTAT']
#print(dataset.DESCR)
#dataset['target']
print("Properties: ", dataset.data.shape)
print("Desc of each column: ", dataset.DESCR)
df = pd.DataFrame(dataset.data, columns=dataset.feature_names)
#df['target'] = dataset.target
print(df)
print("Description of columns: ")
df.describe()
#Describe yerine tek tek bu fonksiyonları da çalıştırabilirsin.
#df.count()
#df.min()
#df.max()
#df.median()
print("Nullity Check:\n",pd.isnull(df).any())
print("Sum of null values for each column:\n",pd.isnull(df).sum()) #node null value at all !
print("Correlation:\n ", df.corr(method='pearson'))
print("Max TAX per each ZN\n",df.groupby(["ZN"],sort=False)['TAX'].max())
print("Min TAX per each ZN\n",df.groupby(["ZN"],sort=False)['TAX'].min())
#Q5. You are expected to provide a series of plots that you find logical for describing the Boston dataset
#as we did in the class for the Iris dataset. You do not have to provide all the different kind of figures
#but try to be precise while trying to illustrate the dataset. You can make use of the following link for the seaborn library:
#http://seaborn.pydata.org/examples/
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
import scipy
warnings.filterwarnings('ignore')
from sklearn.datasets import load_boston
dataset = load_boston()
df = pd.DataFrame(dataset.data, columns=dataset.feature_names)
#['CRIM' 'ZN' 'INDUS' 'CHAS' 'NOX' 'RM' 'AGE' 'DIS' 'RAD' 'TAX' 'PTRATIO' 'B' 'LSTAT']
#1
plt.hist(df['ZN'])
plt.hist(df['AGE'],bins=20)
plt.hist(df['CRIM'])
plt.hist(df['INDUS'],bins=20)
plt.hist(df['RAD'],bins=20)
#2.1
sns.distplot(df['ZN'])
#2.2.
#sns.kdeplot(df['ZN'], df['CRIM'], shade=True)
sns.jointplot(df['ZN'], df['CRIM'], kind='kde')
#3
cat_attr = df['RAD']
h = cat_attr.value_counts()
values, counts = h.index, h
plt.bar(values, counts)
plt.bar(*list(zip(*cat_attr.value_counts().items())))
#4
plt.scatter(df['RAD'], df['LSTAT'])
#5
plt.scatter(df['AGE'], df['RM'])
|
sen = "the quick brown fox jumps over the lazy dog"
dt = list(sorted(set(sen)))
for k,v in enumerate(dt):
print ('{} {}'.format(k,v))
|
def time_converter(time_str):
time_str = time_str.rjust(4,'0')
if time_str[-2:] == 'PM':
return str(int(time_str[0:2]) + 12) + time_str[2:len(time_str) - 2]
else:
return time_str.replace('PM', '').replace('AM', '')
# if __name__ == "__main__":
# print time_converter('1AM')
|
class MyDate(object):
def __init__(self, d, m, y):
self.day = int(d)
self.month = int(m)
self.year = int(y)
def __lt__(self, obj):
ret_val = False
if self.year < obj.year:
ret_val = True
else:
if self.month < obj.month:
ret_val = True
elif self.month == obj.month:
if self.day < obj.day:
ret_val = True
else:
if self.day < obj.day:
ret_val = True
return ret_val
def __eq__(self, obj):
return self.year == obj.year and self.month == obj.month and self.day == obj.day
def same_calender_month(self, obj):
return self.year == obj.year and self.month == obj.month
def diff_days(self, obj):
return obj.day - self.day
def same_calender_year(self, obj):
return self.year == obj.year
def diff_years(self, obj):
return obj.year - self.year
def diff_months(self, obj):
return obj.month - self.month
actual_date = MyDate(2,7,2015)
expected_date = MyDate(1,2,2014)
if actual_date < expected_date or actual_date == expected_date:
print 'The fine is : INR 0'
elif expected_date.same_calender_month(actual_date):
print 'The fine is : INR ' + str(expected_date.diff_days(actual_date) * 15)
elif expected_date.same_calender_year(actual_date):
print 'The fine is : INR ' + str(expected_date.diff_months(actual_date) * 500)
else:
print 'The fine is : INR 1000'
|
import Queue
class IterableQueue():
def __init__(self,source_queue):
self.source_queue = source_queue
def __iter__(self):
while True:
try:
yield self.source_queue.get_nowait()
except Queue.Empty:
return
q = Queue.Queue()
q.put(1)
q.put(2)
q.put(3)
for n in IterableQueue(q):
print n
|
import re
def add(num_list):
total=0
numbers= re.findall(r'-?\d+', num_list)
negatives= []
for number in numbers:
number= int(number)
if number>=1000:
pass
elif number>=0:
total+=number
else:
negatives.append(number)
if negatives:
raise ValueError(f'Negative numbers not allowed. found {negatives}')
return total
print('----------------------------------------------------------------')
print(' Welcome to the ultimate string calculator')
print(' no numbers above 1000')
print(' (letters and special characters will be ignored)')
print('----------------------------------------------------------------')
list_sum= input('enter numbers to add. : ')
print(add(list_sum)) |
def fizzbuzz():
for i in range(1, 101):
if (i % 3):
print 'fizz',
if (i % 5):
print 'buzz',
print ''
fizzbuzz()
|
# Lab 07 - Problem 01
def calc_bmi():
height = float(input("Enter height (in inches):"))
weight = float(input("Enter weight (in pounds):"))
bmi = (703 * weight) / (height*height)
print("Your BMI is:", bmi,"\n")
def hypertension():
systolic_p = float(input("Enter your systolic pressure:"))
diastolic_p = float(input("Enter your diastolic pressure:"))
if systolic_p >= 140 or diastolic_p >=90:
print("You have high blood pressure.")
else:
print("You do not have high blood pressure.")
def main():
print("Health and Fitness Program\n")
calc_bmi()
hypertension()
main()
|
#lists
mylist=[1,2,3]
mylist=[1,'two',3,False]
print(mylist)
#lenght of the list
print(len(mylist))
#pick an item
print(mylist[0])
#add new item
mylist.append("New Item")
print(mylist)
mylist.append(['x','y','z'])
print(mylist)
mylist.extend(['x','y','z'])
print(mylist)
item=mylist.pop()
print(item)
print(mylist)
item=mylist.pop(0) #adding indexes
print(item)
print(mylist)
mylist.reverse()
print(mylist)
mylist=[1,3,5,2]
mylist.sort()
print(mylist)
#nested lists
matrix=[[1,2,3],[4,5,6],[7,8,9]]
print(matrix[0][0])
print(matrix[1][2])
first_col = [row[0] for row in matrix]
print(first_col) |
def int_input(num):
l = []
for i in range(num):
l.append(int(input(f"Enter number {i + 1} :")))
return l
def str_input(num):
l = []
for i in range(num):
l.append(input(f"Enter string {i + 1} :"))
return l
print(int_input(4))
print("\n")
print(str_input(3)) |
#Triangle is valid if sum of its any two sides is greater than the third side
a= int(input("Enter value of a:"))
b= int(input("Enter value of b:"))
c= int(input("Enter value of c:"))
#
# if (a+b > c) or (a+c > b) or (b+c > a):
# print("Triangle is valid")
# else:
# print("not valid")
def triangle(a,b,c):
if (a + b > c) or (a + c > b) or (b + c > a):
x = "Valid triangle"
return x
else:
x= "not valid"
return x
# print(tirangle(2,7,3))
print(triangle(a,b,c)) |
# try:
# print(2/0)
# except ZeroDivisionError:
# print("No se puede dividir por cero")
#
# print("Fin del script")
try:
lista = [1,2]
print(lista[1])
except ZeroDivisionError:
print("No se puede dividir por cero")
except IndexError:
print("No es posible obtener ese valor")
finally:
print("Fin del try-except")
print("Fin del script")
|
from tkinter import *
tk=Tk()
tk.title("Tic Tac Toe")
#for changing alternet X and O
change = True
#for draw condition
check =0
#for winner at last button click
abc = True
#for printing X winner
def winner():
messageVar = Message(tk, text='x is winner')
messageVar.grid(row=5, column=2)
#for printing O is winner
def winner_1():
messageVar = Message(tk, text='O is winner')
messageVar.grid(row=5, column=2)
#for checking winner
def tictactoe(buttons):
global change
global check
global abc
if buttons["text"] == " " and change == True:
buttons["text"] = "X"
change = False
check=check+1
elif buttons["text"] == " " and change == False:
buttons["text"] = "O"
change = True
check=check+1
if(button1['text'] == 'X' and button2['text'] == 'X' and button3['text'] == 'X'):
winner()
abc = False
elif(button4['text'] == 'X' and button5['text'] == 'X' and button6['text'] == 'X'):
winner()
abc = False
elif(button7['text'] =='X' and button8['text'] == 'X' and button9['text'] == 'X'):
winner()
abc = False
elif(button1['text'] =='X' and button5['text'] == 'X' and button9['text'] == 'X'):
winner()
abc = False
elif(button3['text'] == 'X' and button5['text'] == 'X' and button7['text'] == 'X'):
winner()
abc = False
elif(button1['text'] == 'X' and button2['text'] == 'X' and button3['text'] == 'X'):
winner()
abc = False
elif(button1['text'] == 'X' and button4['text'] == 'X' and button7['text'] == 'X'):
winner()
abc = False
elif(button2['text'] == 'X' and button5['text'] == 'X' and button8['text'] == 'X'):
winner()
abc = False
elif(button3['text'] == 'X' and button6['text'] == 'X' and button9['text'] == 'X'):
winner()
abc = False
elif(button1['text'] == 'O' and button2['text'] == 'O' and button3['text'] == 'O'or
button4['text'] == 'O' and button5['text'] == 'O' and button6['text'] == 'O'or
button7['text'] == 'O' and button8['text'] == 'O' and button9['text'] == 'O'or
button1['text'] == 'O' and button5['text'] == 'O' and button9['text'] == 'O'or
button3['text'] == 'O' and button5['text'] == 'O' and button7['text'] == 'O'or
button1['text'] == 'O' and button2['text'] == 'O' and button3['text'] == 'O'or
button1['text'] == 'O' and button4['text'] == 'O' and button7['text'] == 'O'or
button2['text'] == 'O' and button5['text'] == 'O' and button8['text'] == 'O'or
button3['text'] == 'O' and button6['text'] == 'O' and button9['text'] == 'O'):
winner_1()
abc = False
if (check == 9 and abc):
messageVar = Message(tk, text='TIE')
messageVar.grid(row=5, column=2)
if __name__ == "__main__":
buttons=StringVar()
button1 = Button(tk,text=" ", fg='black', height=5, width=8,command= lambda:tictactoe(button1))
button1.grid(row=1, column=0)
button2 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button2))
button2.grid(row=1, column=1)
button3 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button3))
button3.grid(row=1, column=2)
button4 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button4))
button4.grid(row=2,column=0)
button5 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button5))
button5.grid(row=2,column=1)
button6 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button6))
button6.grid(row=2,column=2)
button7 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button7))
button7.grid(row=3,column=0)
button8 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button8))
button8.grid(row=3,column=1)
button9 = Button(tk, text=' ', fg='black', height=5, width=8, command=lambda:tictactoe(button9))
button9.grid(row=3,column=2)
tk.mainloop() |
""" Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a
list of words. For each word on each line check to see if the word is already in the list and if not append it to the list.
When the program completes, sort and print the resulting words in alphabetical order. """
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.split()
for l in line:
if l not in lst:
lst.append(l)
print(sorted(lst))
fname = input("Enter file name: ") # append text file into a list
fh = open(fname, "r")
lst = list()
for line in fh:
lst.append(line)
print(lst)
fname = input("Enter file name: ") # Append text file into a list and split
fh = open(fname)
lst = list()
for line in fh:
line = line.split()
for l in line:
lst.append(l)
print(lst)
|
def soma(v1, v2, v3):
return v1 + v2 + v3
v1 = int(input("Digite o primeiro valor: "))
v2 = int(input("Digite o segundo valor: "))
v3 = int(input("Digite o terceiro valor: "))
print(soma(v1, v2, v3)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.