text
stringlengths 37
1.41M
|
---|
def friendCircles(friendships):
count = 0
visited = set()
for person in range(len(friendships)):
if person not in visited:
count += 1
dfs(person, friendships, visited)
return count
def dfs(node, friendships, visited):
for person, is_friend in enumerate(friendships[node]):
if is_friend and person not in visited:
visited.add(person)
dfs(person, friendships, visited)
friendships =[
[1,1,0],
[1,1,0],
[0,0,1]
]
# friendships = [
# [1,1,0],
# [1,1,1],
# [0,1,1]
# ]
print(friendCircles(friendships))
# depth first search recursive solution
# time complexity is O(n squared) every node visited
# space complexity is O(n) visited array of size n. |
import sys
sys.path.append('../queue2')
sys.path.append('../stack')
from queue2 import Queue
from stack import Stack
"""
Binary search trees are a data structure that enforce an ordering over
the data they store. That ordering in turn makes it a lot more efficient
at searching for a particular piece of data in the tree.
This part of the project comprises two days:
1. Implement the methods `insert`, `contains`, `get_max`, and `for_each`
on the BSTNode class.
2. Implement the `in_order_print`, `bft_print`, and `dft_print` methods
on the BSTNode class.
"""
class BSTNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
def insert(self, value):
if self.value is None:
return None
# RECURSIVE
if value < self.value: # if value is less than self.value
if self.left is None: # if left child is None
self.left = BSTNode(value) # insert here - create new BSTnode
else:
self.left.insert(value) # recursive call
elif value >= self.value: # - duplicate values go right
if self.right is None: # if right child is None
self.right = BSTNode(value) # insert here
else:
self.right.insert(value) # recursive call
# ************************************************************
# ITERATIVE
# while not at bottom level of tree
# is it less than or equal to the root - duplicate values go right
# if left child is None
# add here
# exit loop
# is it greater than or equal to the root - duplicate values go right
# if right child is None
# add node here
# exit loop
# Return True if the tree contains the value
# False if it does not
def contains(self, target):
if self.value is None:
return None
if self.value == target: # check if self.value is target
return True # if yes, return True
# if no,
elif target < self.value: # go left
if self.left:
return self.left.contains(target)
else:
return False
elif target >= self.value: # go right
if self.right:
return self.right.contains(target)
else:
return False
# Return the maximum value found in the tree
def get_max(self):
if self.value is None:
return None
# Go right until you can't go right anymore - you get back the biggest value
# while loop - while self.value is not next right node
while not self.right:
return self.value
return self.right.get_max()
# Call the function `fn` on the value of each node
def for_each(self, fn):
# RECURSIVE
# check one side and then check the other
fn(self.value) # call function fn on each node
if self.right: # go right
self.right.for_each(fn) # call function when it's the right side
if self.left: # go left
self.left.for_each(fn) # call function when it's the left side
# Part 2 -----------------------
# Print all the values in order from low to high
# Hint: Use a recursive, depth first traversal
def in_order_print(self):
if self.left:
self.left.in_order_print()
print(self.value)
if self.right:
self.right.in_order_print()
# Print the value of every node, starting with the given node,
# in an iterative breadth first traversal
def bft_print(self):
my_queue = Queue() # Create a new Queue
my_queue.enqueue(self) # add passed node to the new Queue
while len(my_queue) > 0: # check if the queue is not empty
current_node = my_queue.dequeue() # set node_value to next item in the list
print(current_node.value) # print the node_value
if current_node.left:
my_queue.enqueue(current_node.left)
if current_node.right:
my_queue.enqueue(current_node.right)
# Print the value of every node, starting with the given node,
# in an iterative depth first traversal
def dft_print(self):
my_stack = Stack() # create a stack to keep track of nodes we are processing
my_stack.push(self) # push `self` into the stack
# while something still in the stack(not done processing all nodes)
while len(my_stack) > 0:
# push when we START, pop when a node is DONE
current_node = my_stack.pop()
print(current_node.value) # call `print()`
if current_node.left:
my_stack.push(current_node.left)
if current_node.right:
my_stack.push(current_node.right)
# use existing `for_each()` as a reference for the traversal logic
# Stretch Goals -------------------------
# Note: Research may be required
# Print Pre-order recursive DFT
def pre_order_dft(self):
pass
# Print Post-order recursive DFT
def post_order_dft(self):
pass
"""
This code is necessary for testing the `print` methods
"""
bst = BSTNode(1)
bst.insert(8)
bst.insert(5)
bst.insert(7)
bst.insert(6)
bst.insert(3)
bst.insert(4)
bst.insert(2)
bst.bft_print()
bst.dft_print()
print("elegant methods")
# print("pre order")
# bst.pre_order_dft()
print("in order")
bst.in_order_print()
# print("post order")
# bst.post_order_dft()
|
from Calculators import division
from Calculators import multiplication
from Calculators import summation
from Calculators import subtraction
class Calculator():
def summa(a,b):
print (summation.Summation.summa(a, b))
def devis (a,b):
print(division.Divisions.divis(a,b))
def multiplicat (a,b):
print (multiplication.Multiplication.multiplicat(a,b))
def substract (a,b):
print (subtraction.Subtraction.subtract(a,b))
# print (division.Divisions.divis(10, 2))
# print (multiplication.Multiplication.multiplicat(10, 2))
# print (summation.Summation.summa(10, 2, 3, 20, 17))
# print (subtraction.Subtraction.subtract(10, 2)) |
def word_count(str):
counts = dict()
words = str.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
text = input("Herhangi bir metin giriniz: ")
sayac = ""
for harf in text:
if harf not in sayac:
sayac += harf
for harf in sayac:
print("{} harfi {} kelimesinde {} kez geçiyor!".
format(harf,text,text.count(harf)))
result=word_count(text)
print("{} metni {} kelimeden oluşuyor.".format(text,result)) |
class Ogrenci:
def __init__(self,numara,ad,soyad,sinif):
self.ad=ad
self.soyad=soyad
self.numara=numara
self.sinif=sinif
self.derslistesi=[]
def dersEkle(self,ders):
self.derslistesi.append(ders)
class Hoca:
def __init__(self,ad,soyad):
self.ad=ad
self.soyad=soyad
self.verdigiDersler=[]
def dersEkle(self,ders):
self.verdigiDersler.append(ders)
class Ders:
def __init__(self,kod,ad,hoca=None):
self.kod=kod
self.ad=ad
self.hoca=hoca
self.ogrenciListesi=[]
def hocayiBelirle(self,hoca):
self.hoca=hoca
def ogrenciEkle(self,ogrenci):
self.ogrenciListesi.append(ogrenci)
def dersBilgisiYazdir(self):
print("Ders kodu:",self.kod)
print("Ders Adı:",self.ad)
print("Ders Hocası:",self.hoca.ad,self.hoca.soyad)
print(self.ad,"Öğrenci Listesi")
for ogrenci in self.ogrenciListesi:
print(ogrenci.ad+" "+ogrenci.soyad)
print("---------------------------------------------------")
furkan=Ogrenci(1234,"Furkan","AKKUŞ",4)
aysenur=Ogrenci(12345,"Ayşenur","AKKUŞ",3)
kerem=Ogrenci(23456,"Kerem","AKKUŞ",1)
yusuf=Ogrenci(34567,"Yusuf","AKKUŞ",4)
ademHoca=Hoca("Adem","AKKUŞ")
gultenHoca=Hoca("Gülten","AKKUŞ")
programlama=Ders("PRG102","Programlama Temelleri")
edebiyat=Ders("EDB203","Türk Dili ve Edebiyatı")
yazilim=Ders("YZM400","Yazılım Mühendisliği Giriş")
programlama.hocayiBelirle(ademHoca)
edebiyat.hocayiBelirle(gultenHoca)
yazilim.hocayiBelirle(ademHoca)
furkan.dersEkle(programlama)
furkan.dersEkle(edebiyat)
furkan.dersEkle(yazilim)
kerem.dersEkle(programlama)
kerem.dersEkle(edebiyat)
aysenur.dersEkle(yazilim)
aysenur.dersEkle(edebiyat)
programlama.ogrenciEkle(furkan)
programlama.ogrenciEkle(kerem)
edebiyat.ogrenciEkle(furkan)
edebiyat.ogrenciEkle(kerem)
edebiyat.ogrenciEkle(aysenur)
yazilim.ogrenciEkle(kerem)
print("***Ders Bilgilerini Yazdırma***")
programlama.dersBilgisiYazdir()
edebiyat.dersBilgisiYazdir()
yazilim.dersBilgisiYazdir()
|
sentence = input("Enter a sentence :")
numberOfWovels = 0
numberOfConsonants = 0
for i in range(len(sentence)):
if sentence[i] == "a" or sentence[i] == "e" or sentence[i] == "i" or sentence[i]=="ı" or sentence[i]=="u" or sentence[i]=="ü" or sentence[i] == "o" or sentence[i]=="ö":
numberOfWovels = numberOfWovels + 1
else:
numberOfConsonants = numberOfConsonants + 1
print(sentence, "number of vowels in a sentence =", numberOfWovels)
print(sentence, "number of consonants in a sentence =", numberOfConsonants) |
#Descobrindo os números primos em um range
a = int(input('Digite o primeiro bimestre: '))
while a > 10:
a = int(input('Nota inválida! Digite o primeiro bimestre: '))
b = int(input('Digite o segundo bimestre: '))
while b > 10:
b = int(input('Nota inválida! Digite o segundo bimestre: '))
c = int(input('Digite o terceiro bimestre: '))
while c > 10:
c = int(input('Nota inválida! Digite o terceiro bimestre: '))
d = int(input('Digite o quarto bimestre: '))
while d > 10:
d = int(input('Nota inválida! Digite o terceiro bimestre: '))
media = print((a + b + c + d) / 4) |
conjunto = {1, 2, 3, 4}
print(type(conjunto))
print(conjunto)
#Não se repete. São elementos únicos
conjunto2 = {1, 2, 3, 4, 4, 2}
print(conjunto2)
# Adicionando
conjunto.add(5)
print(conjunto)
# Eliminando
conjunto.discard(2)
print(conjunto)
|
#Descobrindo os números primos em um range
a = int(input('Digite um número para ver os números primos: '))
for num in range(a):
div = 0
for x in range(1, num + 1):
resto = num % x
if resto == 0:
div += 1
if div == 2:
print(num) |
def make_bread(arg1, arg2, arg3):
if arg1 == 'water' and arg2 == 'flour' and arg3 == 'eggs':
return 'dough'
else:
return 'not dough'
# Test for bake
def bake(arg1):
if arg1 == 'dough':
return 'brioche'
else:
return 'not brioche'
def run_factory(arg1, arg2, arg3):
result_dough = make_bread(arg1, arg2, arg3)
result_bake = bake(result_dough)
return result_bake
# Tests for make bread
# print('Testing make dough() with water, flour and eggs. Expected dough')
# # # print(make_bread('water', 'flour', 'eggs') == 'dough')
#simple unit test
print('Testing make dough() with water, cement and gravel. dough')
print(make_bread('water', 'cement', 'gravel') == 'dough')
print(('testing bake() concrete. expected brioche'))
print(bake('concrete') == 'brioche')
## simple integration test
print('testing run_factory() with water flour and eggs. Expected brioche')
print(run_factory('cement', 'flour', 'eggs') == 'not brioche') |
import math
def print_hi(message):
print(f'Hi, {message}')
def factorial(number):
return math.factorial(number)
def log(number):
return math.log(number)
def sqrt(number):
return math.sqrt(number)
if __name__ == '__main__':
print_hi('Hi, Welcome to simple math helper')
print('What would you like to calculate?')
print("1. Square root \n2. log \n3. Factorial")
try:
option = int(input("Enter a number: "))
user_selection = ("Square root", "log", "factorial")
if 1 <= option <= 3:
user_option = option - 1
number_to_calculate = float(input(f"\nEnter the number to find the {user_selection[user_option]}: "))
if option == 1:
result = sqrt(number_to_calculate)
print(f"\n\nThe {user_selection[user_option]} of {number_to_calculate} is : {int(result)}")
elif option == 2:
result = log(number_to_calculate)
print(f"\n\nThe {user_selection[user_option]} of {number_to_calculate} is : {result}")
else:
result = factorial(number_to_calculate)
print(f"\nThe {user_selection[user_option]} of {number_to_calculate} is : {int(result)}")
else:
print('wrong selection. Please re run the program')
except ValueError:
print('Not a number! Please re run the program')
|
# -*- coding: utf-8 -*-
import csv
import os
import networkx as nx
import time
import zipfile
import shutil
# Function that read a csv file and return a list with a dict for each row
def csvToDictList(filename):
with open(filename, 'r') as csvfile:
csvdata = csv.DictReader(csvfile, delimiter=';')
data = []
for row in csvdata:
data.append(row)
# Transform strings into numbers (floatables only)
for row in data:
for key in row.keys():
try:
row[key] = float(row[key].replace(',', '.'))
except ValueError:
continue
return data, csvdata.fieldnames
def is_number(x): # Check if an element is a number
try:
float(x)
return True
except ValueError:
return False
def saveGraph(graph, name='noname'):
filename = "Results/"
if graph.is_multigraph():
filename += name + "-multigraph"
else:
filename += name + "-graph"
filename += time.strftime("_%Y-%m-%d_%Hh%Mm%Ss")
nx.write_gml(graph, filename)
print('Graph saved as: ' + filename)
def saveGraphList(graphList, names, location='', timestamp=True):
# Removing end slash if needed
if location[-1] == '/':
path = location[:-1]
else:
path = location
# Adding timestamp
if timestamp:
ts = time.strftime("-%Y-%m-%d_%Hh%M")
path += ts
dirname = path + '/'
os.makedirs(dirname, exist_ok=True)
# Creating files
if len(names) == len(graphList):
for index in range(len(names) - 1):
filename = dirname + names[index] + '.gml'
nx.write_gml(graphList[index], filename)
return {'dirname': dirname, 'path': path}
else:
print("Error when saving graphs : graphList's size and names's size don't match")
return {}
def compressFolder(folder_path, clean=True, algo=zipfile.ZIP_LZMA):
# Compressing files
zf = zipfile.ZipFile(folder_path + '.zip', mode='w', compression=algo)
folder_path += '/'
for dirname, subdirs, files in os.walk(folder_path):
# zf.write(dirname) # Uncomment to create the folder in the zip
for filename in files:
zf.write(os.path.join(dirname, filename), filename)
zf.close()
print('Folder \'' + folder_path + '\' compressed')
# Cleaning files
if clean:
shutil.rmtree(dirname)
print('Original files cleaned')
else:
print('Original files kept')
def showTime(start):
print("--- %s seconds ---" % (time.time() - start))
def normalizeWeights(graph):
maxW = 0
minW = math.inf
for edge in graph.edges():
[u, v] = edge
if graph[u][v]['weight'] > maxW:
maxW = graph[u][v]['weight']
if graph[u][v]['weight'] < minW:
minW = graph[u][v]['weight']
for edge in graph.edges():
[u, v] = edge
a = maxW - minW
graph[u][v]['weight'] = (graph[u][v]['weight'] - minW) / a + 1
|
#!/usr/bin/python
import sys
from datetime import datetime
arguments=sys.argv[1:]
if "-f" in arguments:
format=sys.argv[2]
else:
format="%d/%m/%Y"
arg2=sys.argv[len(sys.argv)-1]
if len(sys.argv) in [3,5]:
arg1=sys.argv[len(sys.argv)-2]
else:
currentt=datetime.now()
arg1=currentt.strftime(format)
def countDays(formatd=format,date1=arg1,date2=arg2):
myFormat=formatd
d1=datetime.strptime(date1, myFormat)
d2=datetime.strptime(date2, myFormat)
nrDays=abs(d2-d1)
print 'Between %s and %s are: %d days'%(date1,date2,nrDays.days)
countDays()
|
import pandas as pd
# Catch raw song data as music variable
music = pd.read_csv("featuresdf.csv")
# Get Ed Sheeran songs by looping over list comprehension
for track in (song for artist, song in zip(music.artists, music.name) if 'Sheeran' in artist):
print(track)
# High energy tracks (>0.8)
def get_energy(cuttoff):
def over_cuttoff(energy):
return energy > cuttoff
return over_cuttoff
# Set cutt off
cuttoff = get_energy(0.8)
# Get list of high energy song in list comprehension
print([(x, y, z) for (x, y, z) in zip(music.artists, music.name, music.energy) if get_energy(z)]) |
class Heap:
def __init__(self):
self.storage = []
def insert(self, value):
# pass
self.storage.append(value)
self._bubble_up(len(self.storage) - 1)
def delete(self):
pass
def get_max(self):
# pass
print('self.storage:', self.storage)
return self.storage[0]
def get_size(self):
return len(self.storage)
def _bubble_up(self, index):
# pass
# print('value of index passed in:', index)
# import math
# import time
# p = math.floor((index - 1)/ 2) if index > 1 else 0
p = (index - 1) // 2
current_value = self.storage[index]
parent_value = self.storage[p]
while index > 0:
print('index:', index, 'p:', p)
print('self.storage at buble up:', self.storage)
if current_value > parent_value and p <= 0:
self.storage[index] = parent_value
parent_value = current_value
index = p
p = ((index - 1) // 2)
else:
break
# print("walked through")
# time.sleep(0.25)
# p = math.floor((index - 1)/ 2) if index > 0 else 0
# print('index:', index, 'p:', p)
# print('self.storage at buble up:', self.storage)
# current_value = self.storage[index]
# parent_value = self.storage[p]
# if current_value > parent_value:
# self.storage[index] = parent_value
# self.storage[p] = current_value
# self._bubble_up(p)
def _sift_down(self, index):
pass
# first_child = self.storage[2 * index + 1 ]
# second_child = self.storage[2 * index + 2 ]
# while self.storage[index] < first_child or second_child:
# better_child = first_child >
|
"""
Project Euler Problem 5: https://projecteuler.net/problem=5
Smallest multiple
What is the smallest positive number that is _evenly divisible_ by all
of the numbers from 1 to 20?
"""
def solution(n: int = 7) -> int:
try:
n = int(n)
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or castable to int.")
if n <= 0:
raise ValueError("Parameter n must be greater than or equal to one.")
i = 0
while 1:
print("i = " , i )
i += n * (n - 1)
print("i == " , i )
nfound = 0
for j in range(2, n):
if i % j != 0:
nfound = 1
break
if nfound == 0:
if i == 0:
i = 1
return i
if __name__ == "__main__":
print(f"{solution() = }")
|
import unittest
from app.models import Pitch
class PitchModelTest(unittest.TestCase):
def setUp(self):
self.new_pitch = Pitch(id = 1, title = 'hilarious', pitch_content = 'I saw you in my dreams and i dint wanna wake up', category = 'Pickup Line', upvote = 1, downvote = 1, author = 'james')
def test_instance(self):
self.assertTrue(isinstance(self.new_pitch, Pitch))
|
# You are required to write a program to sort the (name, age, score) tuples by ascending order where name is string,
# age and height are numbers. The tuples are input by console. The sort criteria is:
# 1: Sort based on name; 2: Then sort based on age; 3: Then sort by score.
# The priority is the same as name > age > score.
# If the following tuples are given as input to the program:
# Tom,19,80
# John,20,90
# Jony,17,91
# Jony,17,93
# Json,21,85
# Then, the output of the program should be:
# [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]
output_list = []
while True:
data = input('Enter a comma-separated data input here : ')
if not data:
break
else:
data_split_tuple = tuple(data.split(','))
output_list.append(data_split_tuple)
# or just print(sorted(output_list))
print(sorted(output_list, key=itemgetter(0, 1, 2)))
|
# ###############################################
# Question 1
# A program which will find all such numbers which are divisible by 7 but are not a multiple of 5,
# between 2000 and 3200 (both included).
from random import shuffle
import random
import math
import re
from math import pi
from functools import lru_cache
from operator import itemgetter
from math import sqrt
finalList = []
for num in range(2000, 3200+1):
if num % 7 == 0 and num % 5 != 0:
finalList.append(num)
for i in finalList:
print(i, end=',')
# ################################################
# Question 2
# A program which can compute the factorial of a given numbers.
number = int(input('Enter an integer'))
multiplier = 1
for num in range(1, number+1):
multiplier *= num
print(multiplier)
# ###############################################
# Question 3
# With a given integral number n, a program to generate a dictionary that contains (i, i*i) such that i,
# is an integral number between 1 and n (both included). and then the program should print the dictionary.
int_num = int(input('Enter an integer'))
int_dico = {}
for num in range(1, int_num+1):
key = num
value = num*num
int_dico[key] = value
print(int_dico)
# ###############################################
# Question 4
# A program which accepts a sequence of comma-separated numbers from console
# and generate a list and a tuple which contains every number.
list = []
print('input "stop" to end')
while True:
number = input('Enter number here: ')
if number == 'stop':
break
else:
list.append(number)
print(list, tuple(list))
# ##############################################
# Question 5
# Define a class which has at least two methods: getString: to get a string from console input
# printString: to print the string in upper case.
# Also include simple test function to test the class methods.
class String:
def __init__(self):
self.string = ''
def get_string(self):
self.string = input('Enter a string here: ')
def print_string(self):
print(self.string.upper())
x = String()
x.getString()
x.printString()
# ##############################################
# Question 6
# A program that calculates and prints the value according to the given formula:
# Q = Square root of [(2 * C * D)/H]
# Following are the fixed values of C and H: C is 50. H is 30.
# D is the variable whose values should be input to your program in a comma-separated sequence.
C, H, D = 50, 30, input('enter a comma-separated value here : ')
D = D.split(',')
print(D)
for num in D:
Q = sqrt((2*C*int(num))//H)
print(round(Q))
# ##############################################
# Question 7
# A program that takes two digits ixj and generates a two-dimensional array
array_str = input('Enter a two dimension of array here: ')
array_dim = [int(x) for x in array_str.split('x')]
rowNum = array_dim[0]
colNum = array_dim[1]
multiList = [[0 for col in range(colNum)] for row in range(rowNum)]
multiList[1][2] = 4
print(multiList)
# ###############################################
# Question 8
# A program that accepts a comma separated sequence of names as input and
# print the names in a comma-separated sequence after sorting them alphabetically
name_string = input('Enter sequence of names here ')
names = name_string.split(', ')
print(sorted(names))
# ###############################################
# Question 9
# A program that accepts a sequence of lines as input and prints the lines after
# making all characters in the sentence capitalized.
word_str = ''
while True:
prompt = input('Enter sentences here : ')
if prompt != '':
word_str += prompt
else:
break
print(word_str.upper())
# ###############################################
# Question 10
# A program that accepts a sequence of whitespace separated words as input and
# prints the words after removing all duplicate words and sorting them alphanumerically.
# ###############################################
# Question 11
# A program which accepts a sequence of comma separated 4 digit binary numbers as its input and then check whether
# they are divisible by 5 or not. The numbers that are divisible by 5 are to be printed in a comma separated sequence.
# ###############################################
# Question 12
# Write a program, which will find all such numbers between 1000 and 3000 (both included) such that each digit of
# the number is an even number. The numbers obtained should be printed in a comma-separated sequence on a single line.
# ##############################################
# Question 13
# A program that accepts a sentence and calculate the number of letters and digits.
# ##############################################
# Question 14
# A program that computes the value of b+bb+bbb+bbbb with a given digit as the value of b.
# ##############################################
# Question 15
# A program which uses list comprehension to square each odd number in a list.
# The list is input by a sequence of comma-separated numbers.
# ##############################################
# Question 16
# Write a program that computes the net amount of a bank account based a transaction log from console input.
# The transaction log format is shown as following:
# D 100
# W 200
# D means deposit while W means withdrawal. Suppose the following input is supplied to the program:
# D 300
# D 300
# W 200
# D 100
# Then, the output should be: 500
# ##################################################
"""
QUESTION 17
A website requires the users to input username and password to register. Write a program to
check the validity of password input by users.
Following are the criteria for checking the password:
1. At least 1 letter between [a-z]
2. At least 1 number between [0-9]
1. At least 1 letter between [A-Z]
3. At least 1 character from [$#@]
4. Minimum length of transaction password: 6
5. Maximum length of transaction password: 12
Your program should accept a sequence of comma separated passwords and will check them according to the
above criteria. Passwords that match the criteria are to be printed, each separated by a comma.
Example
If the following passwords are given as input to the program:
ABd1234@1,a F1#,2w3E*,2We3345
Then, the output of the program should be:
ABd1234@1
"""
# ##################################################
# QUESTION 18
# You are required to write a program to sort the (name, age, score) tuples by ascending order where name is string,
# age and height are numbers. The tuples are input by console. The sort criteria is:
# 1: Sort based on name; 2: Then sort based on age; 3: Then sort by score.
# The priority is the same as name > age > score.
# If the following tuples are given as input to the program:
# Tom,19,80
# John,20,90
# Jony,17,91
# Jony,17,93
# Json,21,85
# Then, the output of the program should be:
# [('John', '20', '90'), ('Jony', '17', '91'), ('Jony', '17', '93'), ('Json', '21', '85'), ('Tom', '19', '80')]
# ###############################################
# QUESTION 19
# Write a function to reverse a given string
# ##############################################
# QUESTION 20
# Define a class with a generator which can iterate the numbers,
# which are divisible by 7, between a given range 0 and n.
# #############################################
# QUESTION 21
# A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT
# with a given steps. The trace of robot movement is shown as the following: UP 5 DOWN 3 LEFT 3 RIGHT 2
# The numbers after the direction are steps. Write a program to compute the distance from current position after a
# sequence of movement and original point. If the distance is a float, then just print the nearest integer.
# Example:
# If the following tuples are given as input to the program:
# UP 5
# DOWN 3
# LEFT 3
# RIGHT 2
# Then, the output of the program should be: 2
# ###################################################
# QUESTION 22
# Write a program to compute the frequency of the words from the input.
# The output should output after sorting the key alphanumerically.
# Suppose the following input is supplied to the program:
# New to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.
# Then, the output should be:
# 2:2 3.:1 3?:1 New:1 Python:5 Read:1 and:1 between:1 choosing:1 or:2 to:1
# ####################################################
# QUESTION 23
# Write a method which can calculate square value of number
# ###################################################
# QUESTION 24
# Write a valid HTML + Python Page that will count numbers from 1 to 1,000,000?
# i. Display every 10th number in the series in Bold
# ii. Display every 3rd number in the series in Italics.
# iii. Bonus: Underline every Prime Number in this series.
# ####################################################
# QUESTION 25
# Define a function that can convert an integer into a string and print it in console.
# ####################################################
# QUESTION 26
# Define a function that can receive two integral numbers in string form and
# compute their sum and then print it in console.
# ####################################################
# QUESTION 27
# Define a function that can accept two strings as input and concatenate them and
# then print it in console.
# ####################################################
# QUESTION 28
# Define a function that can accept two strings as input and print the string with
# maximum length in console. If two strings have the same length, then the function
# should print all strings line by line.
# ####################################################
# QUESTION 29
# Define a function which can print a dictionary where the keys are numbers
# between 1 and 3 (both included) and the values are square of keys.
# #####################################################
# QUESTION 30
# With a given tuple(1,2,3,4,5,6,7,8,9,10), write a program to print the first half
# values in one line and the last half values in one line.
# ######################################################
# QUESTION 31
# Create a function to print the nth term of a fibonacci sequence using recursion, and
# also use memoization to cache the result.
# ##################################################
# QUESTION 32
# Create a function to print the nth term of a fibonacci sequence using recursion, and
# also use lru_cache to cache the result.
# ######################################################
# QUESTION 33
# Write a program which can filter even numbers in a list by using filter function.
# The list is: [1,2,3,4,5,6,7,8,9,10].
# ###################################################
# QUESTION 34
# Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10].
# ####################################################
# QUESTION 35
# Write a program which can map() and filter() to make a list whose elements are square of
# even number in [1,2,3,4,5,6,7,8,9,10].
# ####################################################
# QUESTION 36
# Define a class named American which has a static method called printNationality.
# ####################################################
# QUESTION 37
# Define a class named American and its subclass NewYorker.
# ####################################################
# QUESTION 38
# Define a class named Circle which can be constructed by a radius. The Circle class
# has a method which can compute the area.
# ####################################################
# QUESTION 39
# Define a class named Rectangle which can be constructed by a length and width.
# The Rectangle class has a method which can compute the area.
# ####################################################
# QUESTION 40
# Define a class named Shape and its subclass Square.
# The Square class has an init function which takes a length as argument.
# Both classes have a area function which can print the area of the shape where Shape's area is 0 by default.
####################################################
# QUESTION 41
# Pleas raise a RuntimeError exception.
####################################################
# QUESTION 42
# Write a function to compute 5/0 and use try/except to catch the exceptions.
####################################################
# QUESTION 43
# Define a custom exception class which takes a string message as attribute.
####################################################
# QUESTION 44
# Assuming that we have some email addresses in the "[email protected]" format,
# please write program to print the user name of a given email address.
# Both user names and company names are composed of letters only.
# Example: If the following email address is given as input to the program:
# [email protected]
# Then, the output of the program should be: john
# In case of input data being supplied to the question, it should be assumed to be a console input.
####################################################
# QUESTION 45
# Write a program which accepts a sequence of words separated by whitespace as input to
# print the words composed of digits only.
# Example: If the following words is given as input to the program: 2 cats and 3 dogs.
# Then, the output of the program should be: ['2', '3']
# In case of input data being supplied to the question, it should be assumed to be a console input.
# ###########################################################
# QUESTION 46
# Listen to this story, a boy and his father, a programmer are playing with wooden blocks.
# They a're building a pyramid, their pyramid is a bit weird, as it's actually a pyramid-shaped
# wall - it's flat. The pyramid is stacked according to one simple principle, each lower layer
# contains one block more than the layer above.
# Your task is to write a program which reads the number of blocks the builders have, and outputs
# the height of the pyramid that can be built using these blocks.
# NOTE: The height is measured by the number of fully completed layers - if the builders doesn't
# have a sufficient number of blocks and cannot complete the next layer, they finish their work immediately.
# ###########################################################
# QUESTION 47
# Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).
# Example: If the following n is given as input to the program: 5
# Then, the output of the program should be: 3.55
# ###########################################################
# QUESTION 48
# Write a program to compute: f(n)=f(n-1)+100 when n>0 and f(0)=1 with a given n input by console (n>0).
# Example: If the following n is given as input to the program: 5 Then, the output of the program should be: 500
# ###########################################################
# QUESTION 49
# The Fibonacci Sequence is completed based on the following formula:
# f(n) = 0 if n=0
# f(n) = 1 if n=1
# f(n) = f(n-1) + f(n-2) if n>1
# Please write a program to compute the value of f(n) with a given n input by console.
# If n=7 is given as input to the program: Then, the output should be: 13
# ###########################################################
# QUESTION 50
# Given array {2,4,6,10}
# target say (16)
# Find the number of possible subsets that will sum up to the target.
# Assumptions: i. all elements inside the array is non-negative.
# ii. You cannot repeat number.
# iii. if 0 is given as the target, the possible subset is 1 i.e {}.
# ###########################################################
# QUESTION 51
# The Fibonacci Sequence is computed based on the following formula:
# f(n)=0 if n=0, f(n)=1 if n=1, f(n)=f(n-1)+f(n-2) if n>1
# Please write a program using list comprehension to print the Fibonacci
# Sequence in comma separated form with a given n input by console.
# Example: If the following n is given as input to the program:7
# Then, the output of the program should be: 0,1,1,2,3,5,8,13
# ###########################################################
# QUESTION 52
# Please write a program using generator to print the even numbers between 0 and n
# in comma separated form while n is input by console.
# Example: If the following n is given as input to the program: 10
# Then, the output of the program should be: 0,2,4,6,8,10
# ###########################################################
# QUESTION 53
# Please write a program using generator to print the numbers which can be divisible by 5 and 7
# between 0 and n in comma separated form while n is input by console.
# Example: If the following n is given as input to the program: 100
# Then, the output of the program should be: 0,35,70
# ##########################################################
# QUESTION 54
# Please write assert statements to verify that every number in the list [2,4,6,8] is even.
# ##########################################################
# QUESTION 55
# Please write a program which accepts basic mathematics expression from console and print the evaluation result.
# Example: If the following string is given as input to the program: 35+3
# Then, the output of the program should be: 38
# ##########################################################
# QUESTION 56
# Please write a binary search function which searches an item in a sorted list. The function should return
# the index of element to be searched in the list.
# ##########################################################
# QUESTION 57
# Please generate a random float where the value is between 10 and 100 using Python math module.
# ##########################################################
# QUESTION 58
# Please write a program to output a random even number between 0 and 10 inclusive using random module
# and list comprehension.
# ##########################################################
# QUESTION 59
# Please write a program to generate a list with 5 random numbers between 100 and 200 inclusive.
# ##########################################################
# QUESTION 60
# Write a program to shuffle and print a list.
# ########################################################################
# QUESTION 61
# Have the function StringChallenge(str) read str which will contain two strings separated by a space.
# The first string will consist of the following sets of characters: +, *, $, and {N} which is optional.
# The plus (+) character represents a single alphabetic character, the ($) character represents a number between 1-9,
# and the asterisk (*) represents a sequence of the same character of length 3 unless it is followed by {N}
# which represents how many characters should appear in the sequence where N will be at least 1.
# Your goal is to determine if the second string exactly matches the pattern of the first string in the input.
# For example: if str is "++*{5} jtggggg" then the second string in this case does match the pattern,
# so your program should return the string true. If the second string does not match the pattern
# your program should return the string false.
# Examples
# Input: "+++++* abcdehhhhhh"
# Output: false
# Input: "$**+*{2} 9mmmrrrkbb"
# Output: true
# ##########################################################
|
# Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
# The overall run time complexity should be O(log (m+n)).
# Using binary search algorithm
def findMedianSortedArrays(nums1, nums2):
# Ensure that nums1 is the shorter array
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1
m, n = len(nums1), len(nums2)
lo, hi = 0, m
while lo <= hi:
i = (lo + hi) // 2
j = (m + n + 1) // 2 - i
if i < m and nums2[j-1] > nums1[i]:
# i is too small, increase it
lo = i + 1
elif i > 0 and nums1[i-1] > nums2[j]:
# i is too big, decrease it
hi = i - 1
else:
# i is the perfect size
if i == 0:
max_of_left = nums2[j-1]
elif j == 0:
max_of_left = nums1[i-1]
else:
max_of_left = max(nums1[i-1], nums2[j-1])
if (m + n) % 2 == 1:
return max_of_left
if i == m:
min_of_right = nums2[j]
elif j == n:
min_of_right = nums1[i]
else:
min_of_right = min(nums1[i], nums2[j])
return (max_of_left + min_of_right) / 2
# using merge sort algorithm
# To find the median of two sorted arrays, you can use the following approach:
# Merge the two arrays into a single sorted array using a merge sort algorithm.
# Find the length of the merged array.
# If the length of the merged array is odd, return the middle element.
def findMedianSortedArrays(nums1, nums2):
# Merge the two arrays into a single sorted array
merged = []
i, j = 0, 0
while i < len(nums1) and j < len(nums2):
if nums1[i] < nums2[j]:
merged.append(nums1[i])
i += 1
else:
merged.append(nums2[j])
j += 1
merged.extend(nums1[i:])
merged.extend(nums2[j:])
# Find the median of the merged array
if len(merged) % 2 == 1:
median = merged[len(merged) // 2]
else:
median = (merged[len(merged) // 2] + merged[len(merged) // 2 - 1]) / 2
return median
# TEST
print(findMedianSortedArrays([1, 3], [2])) # Output: 2
print(findMedianSortedArrays([1, 2], [3, 4])) # Output: 2.5
|
# With a given tuple(1,2,3,4,5,6,7,8,9,10), write a program to print the first half
# values in one line and the last half values in one line.
tup = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
tup1 = tup[:5]
tup2 = tup[5:]
print(f"First half = {tup1} \n Second half = {tup2}")
|
# QUESTION
# Have you heard of the fibonacci sequence? It is defined by f0=0, f1=1 and fn=fn-1 + fn-2 for n>=2.
# This question is about a similar sequence, called gibonacci sequence. It is defined by g0 = x, g1 = y and gn = gn-1 - gn-2 for n >= 2.
# Different possible starting values of the gibonacci sequence may lead to different gibonacci sequences.
# You are given three arguments: n, x, y. Your task is to find gn using the above definition of a gibonacci sequence starting with g0 = x, g1 = y.
# Write a function gibonacci(n,x,y) that takes in 3 arguments.
# Inputs
# It is guaranteed that n,x,y are integers and 0 <= n, x, y <= 1000000000
# Outputs
# gibonacci(n,x,y) should return gn given that g0 = x, g1 = y.
# SOLUTION
def gibonacci(n, x, y):
# Check if n is 0, if it is return x
if n == 0:
return x
# Check if n is 1, if it is return y
elif n == 1:
return y
# If n is greater than 1
else:
# Initialize g_n_2 as x and g_n_1 as y
# g_n_2 = x
# g_n_1 = y
prev1 = y
prev2 = x
# Iterate from 2 to n+1 (inclusive)
for i in range(2, n+1):
# calculate the next term gn = gn-1 - gn-2
nth = prev1 - prev2
# update the value of g_n_2 as g_n_1
prev2 = prev1
# update the value of g_n_1 as g_n
prev1 = nth
# return the nth term g_n
return nth
print(gibonacci(1, 0, 1))
# SOLUTION
# This function takes in 3 arguments: n, x, and y. It first checks if n is equal to 0, in which case it returns x. If n is equal to 1, it returns y.
# Otherwise, it initializes two variables g_n_2 and g_n_1 to x and y respectively, representing the 2 previous terms in the sequence.
# Then it uses a for loop to iterate from 2 to n+1 (inclusive), on each iteration it calculates the next term g_n using the definition provided by subtracting the previous term g_n_2 from the current term g_n_1. Then it updates the value of g_n_2 and g_n_1 to g_n_1 and g_n respectively.
# Finally, it returns the value of g_n which is the nth term of the gibonacci sequence given the initial values of x and y.
|
# Write a program which can map() and filter() to make a list whose elements are square of
# even number in [1,2,3,4,5,6,7,8,9,10].
even_filtered = [even for even in filter(
lambda u: u % 2 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])]
squared_even = [square for square in map(lambda m: m**2, even_filtered)]
|
# Given a signed 32-bit integer x, return x with its digits reversed.
# If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.
# Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
def reverse_integer(x):
# Check if x is within the signed 32-bit integer range
if x < -2147483648 or x > 2147483647:
return 0
# Convert x to a string and reverse it
x_str = str(x)
reversed_str = x_str[::-1]
# If the first character is a "-", remove it and negate the result
if reversed_str[0] == "-":
reversed_int = -1 * int(reversed_str[1:])
else:
reversed_int = int(reversed_str)
# Check if the result is within the signed 32-bit integer range
if reversed_int < -2147483648 or reversed_int > 2147483647:
return 0
else:
return reversed_int
print(reverse_integer(123))
print(reverse_integer(-123))
# This solution first checks if the input is within the signed 32-bit integer range. If it is, it converts the input to a string and reverses it. It then checks if the first character of the reversed string is a "-", and if it is, it removes the "-" and negates the result. Finally, it checks if the result is within the signed 32-bit integer range and returns it, or returns 0 if it is not.
# REVISED SOLUTION
def reverse_integer(x):
# Check if x is within the signed 32-bit integer range
if x < -2147483648 or x > 2147483647:
return 0
# Convert x to a string and reverse it
x_str = str(x)
if x < 0:
# If x is negative, remove the "-" before reversing
x_str = x_str[1:]
reversed_str = "-" + x_str[::-1]
else:
reversed_str = x_str[::-1]
reversed_int = int(reversed_str)
# Check if the result is within the signed 32-bit integer range
if reversed_int < -2147483648 or reversed_int > 2147483647:
return 0
else:
return reversed_int
# This solution first checks if x is within the signed 32-bit integer range. If it is, it converts x to a string and reverses it. If x is negative, it removes the "-" before reversing the string and adds it back after reversing. Finally, it converts the reversed string back to an integer and checks if the result is within the signed 32-bit integer range, returning it or 0 if it is not.
|
# Write a program to compute 1/2+2/3+3/4+...+n/n+1 with a given n input by console (n>0).
# Example: If the following n is given as input to the program: 5
# Then, the output of the program should be: 3.55
def formula(n):
result = 0
if n > 0:
list_n = [i for i in range(1, n+2)]
for num in list_n[:-1]:
result += num/list_n[list_n.index(num)+1]
print(f"{result:.2f}")
else:
print("Value must be greater than 0")
# *******************OR*******************
def formula(n):
result = 0
for i in range(1, n+1):
result += i/(i+1)
print(f"{result:.2f}")
formula(5)
|
# Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
# You must implement a solution with a linear runtime complexity and use only constant extra space.
# SOLUTION
def singleNumber(nums):
result = 0
for num in nums:
result ^= num
return result
# The XOR operation (^) has the property that a ^ a = 0 for any a, which means that if we XOR all the elements in the array together, all the elements that appear twice will cancel each other out, leaving only the element that appears once.
# This solution has a linear runtime complexity, since it iterates through the array once and performs a constant number of operations on each element.
# It also uses only constant extra space, since it only stores a single integer (the result variable).
|
"""
ZADANIE 4.2
Rozwiązania zadań 3.5 i 3.6 z poprzedniego zestawu zapisać w postaci funkcji,
które zwracają pełny string przez return.
"""
print("---Zadanie 4.2---")
#3.5
def make_linijka(length):
pattern = "|...."
linear = ['', '0']
linijka = ''
for i in range(length):
linear[0] += pattern
linear[1] += "%5s" % (i + 1)
linear[0] += "|"
linijka = linear[0] + '\n' + linear[1]
return linijka
print(make_linijka(12))
#3.6
def make_siatka(x,y):
row = "+---"
column = "| "
SIZE = [x, y] #dlugosc wiersza x dlugosc kolumny y
board = ''
def generate_el(pattern, end_cap):
result = ''
for j in range(SIZE[0]):
result += pattern
if j == SIZE[0] - 1:
result += end_cap + '\n'
return result
for _ in range(SIZE[1]):
board += generate_el(row, '+')
board += generate_el(column, '|')
board += generate_el(row, '+')
return board
print(make_siatka(3,4))
"""
ZADANIE 4.3
Napisać iteracyjną wersję funkcji factorial(n) obliczającej silnię.
"""
print("---Zadanie 4.3---")
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
assert factorial(5) == 120
"""
ZADANIE 4.4
Napisać iteracyjną wersję funkcji fibonacci(n)
obliczającej n-ty wyraz ciągu Fibonacciego.
"""
print("---Zadanie 4.4---")
def fibonacci(n):
a, b = 1, 1
for i in range(0, n-1):
a, b = b, a + b
return a
assert fibonacci(8) == 21
"""
ZADANIE 4.5
Napisać funkcję odwracanie(L, left, right) odwracającą kolejność elementów
na liście od numeru left do right włącznie.
Lista jest modyfikowana w miejscu (in place). Rozważyć wersję iteracyjną i rekurencyjną.
"""
print("---Zadanie 4.5---")
def iter_odwracanie(L, left, right):
assert left in range(len(L)) and right in range(len(L))
if right < left:
left, right = right, left
if ((right - left) % 2) != 0:
zakres = (right - left + 1) // 2
else:
zakres = (right - left) // 2
for i in range(zakres):
L[left], L[right] = L[right], L[left]
left += 1
right -= 1
def rek_odwracanie(L, left, right):
L[left], L[right] = L[right], L[left]
left, right = left + 1, right - 1
if left < right:
return rek_odwracanie(L, left, right)
else:
return True
L = [1, 2, 3, 4, 5, 6, 7, 8]
left = 1
right = 7
print(L)
iter_odwracanie(L, left, right)
print(L)
rek_odwracanie(L, left, right)
print(L)
"""
ZADANIE 4.6
Napisać funkcję sum_seq(sequence) obliczającą sumę liczb zawartych w sekwencji,
która może zawierać zagnieżdżone podsekwencje.
Wskazówka: rozważyć wersję rekurencyjną,
a sprawdzanie, czy element jest sekwencją, wykonać przez isinstance(item, (list, tuple)).
"""
print("---Zadanie 4.6---")
sequence = [(1, 2), 3, (4, [5, 6], (7, 8, (9, 10, 11)))]
def sum_seq(sequence):
sum = 0
for item in sequence:
if isinstance(item, (list, tuple)):
sum += sum_seq(item)
else:
sum += item
return sum
assert sum_seq(sequence) == 66
"""
ZADANIE 4.7
Mamy daną sekwencję, w której niektóre z elementów mogą okazać się podsekwencjami,
a takie zagnieżdżenia mogą się nakładać do nieograniczonej głębokości.
Napisać funkcję flatten(sequence), która zwróci spłaszczoną listę wszystkich elementów sekwencji.
Wskazówka: rozważyć wersję rekurencyjną, a sprawdzanie czy element jest sekwencją,
wykonać przez isinstance(item, (list, tuple)).
seq = [1,(2,3),[],[4,(5,6,7)],8,[9]]
print flatten(seq) # [1,2,3,4,5,6,7,8,9]
"""
print("---Zadanie 4.7---")
def flatten(sequence):
L = []
for item in sequence:
if isinstance(item, (list, tuple)):
L.extend(flatten(item))
else:
L.append(item)
return L
sequence = [1,(2,3),[],[4,(5,6,7)],8,[9]]
print(flatten(sequence))
|
"""
ZADANIE 2.10
Mamy dany napis wielowierszowy line. Podać sposób obliczenia liczby wyrazów w napisie.
Przez wyraz rozumiemy ciąg "czarnych" znaków,
oddzielony od innych wyrazów białymi znakami (spacja, tabulacja, newline).
"""
print("---Zad 2.10---")
line = """jeden dwa trzy
cztery piec szesc siedem
osiem
dziewiec GvR"""
word_num = len(line.split())
print("Number of words in line file: ", word_num)
"""
ZADANIE 2.11
Podać sposób wyświetlania napisu word tak, aby jego znaki były rozdzielone znakiem podkreślenia.
"""
print("---Zad 2.11---")
word = "slowobezpodkreslnikow"
new_word = ""
for char in word:
if len(new_word) == 2*len(word)-2:
new_word += char
break
new_word += char + "_"
print(new_word)
"""
ZADANIE 2.12
Zbudować napis stworzony z pierwszych znaków wyrazów z wiersza line.
Zbudować napis stworzony z ostatnich znaków wyrazów z wiersza line.
"""
print("---Zad 2.12---")
def get_words_from_sights_starting_with(from_which_digit):
word_from_single_line = ''
for single_line in line.splitlines():
for single_word in single_line.split():
word_from_single_line += single_word[from_which_digit]
print(word_from_single_line)
word_from_single_line = ''
get_words_from_sights_starting_with(0)
print("\n")
get_words_from_sights_starting_with(-1)
"""
ZADANIE 2.13
Znaleźć łączną długość wyrazów w napisie line. Wskazówka: można skorzystać z funkcji sum().
"""
print("---Zad 2.13---")
words = line.split()
all_words = "".join(words)
char_num = len(all_words)
print("Number of chars in line file: ", char_num)
"""
ZADANIE 2.14
Znaleźć: (a) najdłuższy wyraz, (b) długość najdłuższego wyrazu w napisie line.
"""
print("---Zad 2.14---")
the_longest_word_in_file = ''
for single_line in line.splitlines():
for single_word in single_line.split():
if len(single_word) > len(the_longest_word_in_file):
the_longest_word_in_file = single_word
print("the longest word in file is:", the_longest_word_in_file)
print("Length = ", len(the_longest_word_in_file))
"""
ZADANIE 2.15
Na liście L znajdują się liczby całkowite dodatnie.
Stworzyć napis będący ciągiem cyfr kolejnych liczb z listy L.
"""
print("---Zad 2.15---")
L = [203, 12, 7, 442, 23, 683, 25, 50, 8436, 1, 44, 73, 2, 43, 25, 6, 199, 2, 47, 381]
word_from_list = "".join(str(x) for x in L)
print(word_from_list)
"""
ZADANIE 2.16
W tekście znajdującym się w zmiennej line zamienić ciąg znaków "GvR" na "Guido van Rossum".
"""
print("---Zad 2.16---")
line2 = "George V (GvR) was King of the United Kingdom and the British Dominions,GvR and Emperor of India, from 6 May 1910 until GvR death in 1936."
line2 = line2.replace("GvR", "Guido van Rossum")
print(line2)
"""
ZADANIE 2.17
Posortować wyrazy z napisu line raz alfabetycznie, a raz pod względem długości.
Wskazówka: funkcja wbudowana sorted().
"""
print("---Zad 2.17---")
words_list = []
with open("line.txt", 'r') as file:
for single_line in file:
for single_word in single_line.split():
words_list.append(single_word)
print(len(words_list))
words_list.sort(key=str.casefold)
print("sorted_list: ", words_list)
words_list.sort(key=len)
print("sorted list when key is length: ", words_list)
"""
ZADANIE 2.18
Znaleźć liczbę cyfr zero w dużej liczbie całkowitej. Wskazówka: zamienić liczbę na napis.
"""
print("---Zad 2.18---")
L = [203, 12, 7, 442, 23, 683, 25, 50, 8436, 1, 44, 73, 2, 43, 25, 6, 199, 2, 47, 381]
big_number = "".join(str(x) for x in L)
print("Number of zeros in the number: ", big_number.count('0'))
"""
ZADANIE 2.19
Na liście L mamy liczby jedno-, dwu- i trzycyfrowe dodatnie.
Chcemy zbudować napis z trzycyfrowych bloków, gdzie liczby jedno-
i dwucyfrowe będą miały blok dopełniony zerami, np. 007, 024. Wskazówka: str.zfill().
"""
print("---Zad 2.19---")
L = [203, 12, 7, 442, 23, 683, 25, 50, 8436, 1, 44, 73, 2, 43, 25, 6, 199, 2, 47, 381]
big_number = ", ".join(str(x).zfill(3) for x in L)
print(big_number)
|
import requests, time
print("\n---> This is a Site Connectivity Checker <---\n")
print("Input your URL in the following format 'http://www.google.com'")
url = "http://google.com"
diff = 1
count = 1
flag = 1
def initialize():
url = input("Enter a URL to check: ")
diff = input(f"Ping {url} on an interval of (seconds): ")
count = input(f"Ping {url} for how many times (number of times): ")
return url, diff, count
url, diff, count = initialize()
print("")
while True:
try:
if flag % (int(count) + 1) == 0:
print(f"\n{url} was pinged for {count} times")
print("")
url, diff, count = initialize()
print("")
response = requests.get(url)
status_code = response.status_code
# print("Enter 'Q' to stop")
if status_code == 200:
print(f"{url} is LIVE, the site responded with a status code {status_code}")
if status_code == 301:
print(f"{url} is UNAVAILABLE, the site Moved Permanently and responded with a status code {status_code}")
if status_code == 302:
print(f"{url} is UNAVAILABLE, the site Moved TEMPORARILY and responded with a status code {status_code}")
if status_code == 404:
print(f"{url} is UNAVAILABLE, the site was NOT FOUND and responded with a status code {status_code}")
if status_code == 500:
print(
f"{url} is UNAVAILABLE, the site is having an INTERNAL SERVER ERROR and responded with a status code {status_code}")
if status_code == 503:
print(
f"{url} is UNAVAILABLE, the site's SERVICE is UNAVAILABLE and responded with a status code {status_code}")
except Exception as e:
print(e)
url = input("\nEnter another URL to check: ")
diff = input(f"Ping {url} on an interval of (seconds): ")
count = input(f"Ping {url} for how many times (number of times): ")
time.sleep(int(diff))
flag = flag + 1
|
from algorithms.AbstractGenetic import AbstractGeneticAlgorithm
import numpy as np
import copy
from solution.Solution import Solution
import pandas as pd
import math
class FireflyAlgorithm(AbstractGeneticAlgorithm):
def __init__(
self, absorption_coefficient=1, attractivness_coefficient=1, alpha=1, **kwds
):
self.absorption_coefficient = absorption_coefficient
self.attractivness_coefficient = attractivness_coefficient
self.alpha = alpha
super().__init__(**kwds)
def generate_population(self, Function):
"""Generates population according to Function with help of method generate_individual.
Args:
Function (Function): One of the cost function. (Sphere, Ackley..)
Returns:
[Solution[]]: Returns whole population with particles.
"""
return [
self.generate_individual(Function) for i in range(self.size_of_population)
]
def generate_random_distribution_vector(self):
"""Generates random movement according to gaussian distribution. (Hill Climb)
Returns:
[float[]]: Vector with filled values according to gaussian distribution with u0,sigma1.
"""
return np.random.normal(0, 1, size=self.dimension)
def generate_random_movement(self):
"""Generates part of calculation for new position of firefly.
Returns:
[float[]]: Vector filled with gaussian distribution numbers multiplied by constant.
"""
return self.alpha * self.generate_random_distribution_vector()
def generate_individual(self, Function):
"""Function (Function): One of the cost function. (Sphere, Ackley..)
Returns:
[Solution]: Returns individual from population. In PSO it is called particle.
"""
solution = self.generate_random_solution(Function.left, Function.right, self.D)
return solution
def calculate_light_intensity(self, individual, distance=1):
"""Calculates light intenstity according to formula.
Args:
individual (Solution): Current individual (firefly).
distance (int, optional): Eucladian. Defaults to 1.
Returns:
[float]: Light intensity of firefly.
"""
new_light_intensity = individual.fitness_value * math.exp(
-self.absorption_coefficient * distance
)
return new_light_intensity
def calculate_attractivness(self, a, b, distance):
"""Calculates attractivnes for firefly a and b. Uses formula without absoption.
Args:
a (Solution): Firefly 1.
b (Solution): Firefly 2.
distance (float): Distance between f1 and f2, calculated according to ed.
Returns:
[float]: Attractivnes.
"""
return self.attractivness_coefficient / (1 + distance)
def calculate_new_random_position(self, individual, Function):
"""Calcualted new position for best firefly in pop.
If new position is not better, then position of best firefly is not changed.
Args:
individual (Solution): Current best value.
Function (Function): One of the cost function. (Sphere, Ackley..)
"""
new_position = individual.vector + self.generate_random_movement()
new_position = np.clip(new_position, Function.left, Function.right)
possible_fitness = Function.run(new_position)
self.current_OFE += 1
if individual.fitness_value > possible_fitness:
individual.vector = new_position
individual.fitness_value = possible_fitness
def calculate_new_position(
self, individual, towards_individual, distance, Function
):
"""Calculates new position for fireflies which are not best.
Args:
individual (Solution): Firefly which will be moved.
towards_individual (Solution): Parametr individual will be moved towards this one.
distance (float): Distance between f1 and f2, calculated according to ed.
Function (Function): One of the cost function. (Sphere, Ackley..)
"""
new_position = (
individual.vector
+ self.calculate_attractivness(individual, towards_individual, distance)
* (towards_individual.vector - individual.vector)
+ self.generate_random_movement()
)
new_position = np.clip(new_position, Function.left, Function.right)
individual.vector = new_position
def start(self, Function):
"""Runs ______ Algorithm on specified Function, with specified args.
Args:
Function (class Function): specific Function (Sphere || Ackley..)
"""
super().start()
self.reset_alg()
fireflies = self.generate_population(Function)
self.dimension = self.D
self.evalute_population(fireflies, Function)
self.best_solution = self.select_best_solution(fireflies)
while self.index_of_generation < self.max_generation and self.ofe_check():
for i in range(self.size_of_population):
fireflyI = fireflies[i]
if fireflyI.key == self.best_solution.key:
self.calculate_new_random_position(fireflyI, Function)
if self.graph:
beforeMoveSolution = copy.deepcopy(fireflyI)
self.graph.draw_with_vector(
fireflyI, beforeMoveSolution, None, False
)
self.graph.draw(self.best_solution, fireflies)
continue
if self.graph:
savedfireflyI = copy.deepcopy(fireflyI)
self.graph.refresh_path()
self.graph.draw_extra_population(
savedfireflyI, None, "black", "start_position"
)
for j in range(self.size_of_population):
fireflyJ = fireflies[j]
distance = np.linalg.norm(fireflyI.vector - fireflyJ.vector)
if self.calculate_light_intensity(
fireflyI, distance
) > self.calculate_light_intensity(fireflyJ, distance):
if self.graph:
beforeMoveSolution = copy.deepcopy(fireflyI)
self.calculate_new_position(
fireflyI, fireflyJ, distance, Function
)
self.best_solution = self.select_best_solution(fireflies)
if self.graph:
self.graph.draw_with_vector(
fireflyI, beforeMoveSolution, fireflyJ, True
)
self.graph.draw(self.best_solution, fireflies)
self.evaluate(fireflyI, Function)
self.index_of_generation += 1
self.print_best_solution()
self.close_plot()
return self.return_after_at_the_end(fireflies)
|
import psycopg2
import pandas as pd
import tabulate as tb
import csv
import os
fileName = 'test.csv'
hostName = input('Enter host name :')
portNumber = input('Enter port number :')
databaseName = input('Enter database Name :')
userName = input('Enter user name :')
passwordOfDb = input('Enter password :')
tableName = input('Enter table name: ')
connect = None
if os.path.exists(fileName):
connect = psycopg2.connect(host=hostName, port=portNumber, database=databaseName, user=userName, password=passwordOfDb)
cursor = connect.cursor()
sqlSelect = "SELECT * FROM "+tableName
try:
cursor.execute(sqlSelect)
results = cursor.fetchall()
headers = [i[0] for i in cursor.description]
print(pd.read_sql(sqlSelect, connect))
csvFile = csv.writer(open(fileName, 'w', newline=''),
delimiter=',', lineterminator='\r\n',
quoting=csv.QUOTE_ALL, escapechar='\\')
csvFile.writerow(headers)
for row in results:
csvFile.writerow(row)
print("Data export successful.")
except psycopg2.DatabaseError as e:
print("Data export unsuccessful.")
quit()
finally:
cursor.close()
connect.close()
else:
print("File path does not exist.")
cursor.close()
connect.close()
|
file = input("")
tokenCount = 0
types = set([])
#f = open(file, "r")
#for line in f:
with open(file, 'rb') as f:
contents = f.read()
content = contents.split()
for tokens in content:
tokens.lower()
if tokens.isalpha:
tokenCount += 1
types.add(tokens)
ratio = tokenCount/len(types)
print("File: " + file + "\n")
print("Tokens: " + str(tokenCount) + "\n")
print("Types: " + str(len(types)) + "\n")
print("Token / Type Ratio: " + str(ratio)) |
#!/usr/bin/env python3
"""Count the number of times each anchor in the given YAML file is used."""
import argparse
import re
from pathlib import Path
def main(file: str):
contents = Path(file).read_text()
counter = {}
for anchor in re.findall(r'(?<=&)[\w-]+', contents):
if anchor in counter:
raise Exception(f'Found repeated anchor: {anchor}')
counter[anchor] = 0
for ref in re.findall(r'(?<=\*)[\w-]+', contents):
if ref not in counter:
print(f'WARNING: Found unknown reference: {ref}')
continue
# raise Exception(f'Found unknown reference: {ref}')
counter[ref] += 1
for anchor, count in sorted(counter.items(), key=lambda x: x[1], reverse=True):
print(f'{anchor}: {count}')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('file', help='The YAML file to check')
args = parser.parse_args()
main(args.file)
|
from random import randrange
from collections import deque
class Game(object):
def __init__(self):
self.rows = 9
self.columns = 9
self.density = 20
def initialize(self):
self.board = Board(self.rows, self.columns, self.density)
self.game_status = 'RUNNING'
def start(self):
while self.game_status == 'RUNNING':
self.print_user_board()
coord_y = input('Enter X:\n')
try:
coord_y = int(coord_y)
except ValueError:
print('X must be between 0 and {}'.format(self.columns))
continue
if not 0 < coord_y <= self.columns:
print('X must be between 0 and {}'.format(self.columns))
continue
coord_x = input('Enter Y:\n')
try:
coord_x = int(coord_x)
except ValueError:
print('Y must be between 0 and {}'.format(self.rows))
continue
if not 0 < coord_x <= self.rows:
print('Y must be between 0 and {}'.format(self.rows))
continue
flag = input('Flag it? (y or f for yes):\n')
flag = True if flag == 'y' or flag == 'f' else False
if flag:
self.flag_cell(coord_x - 1, coord_y - 1)
else:
self.flip_cell(coord_x - 1, coord_y - 1)
self.check_win()
if self.game_status == 'LOST':
self.print_user_board()
print('--------------------------------')
print('-------- YOU LOST! :\'( --------')
print('--------------------------------')
elif self.game_status == 'WON':
self.print_user_board()
self.print_full_board()
print('--------------------------------')
print('-- YOU WON!! Congratulations! --')
print('--------------------------------')
else:
print('Unexpected state')
self.ask_play_again()
def ask_play_again(self):
onemore = input('Play again? (y/n):\n')
if onemore == 'y':
self.initialize()
self.start()
else:
quit()
def check_win(self):
#print('Remaining number of cells to reveal:', self.board.n_cells_toreveal)
if self.board.n_cells_toreveal == 0:
self.game_status = 'WON'
def flip_cell(self, x, y):
cell = self.board.cells[x][y]
# Only decrease n_cells_toreveal if the cell has not been revealed yet
cell.is_flagged = False # Remove the flag if any
if not cell.revealed:
cell.revealed = True
self.board.n_cells_toreveal -= 1
if cell.is_bomb:
self.game_status = 'LOST'
elif cell.value == 0:
self.board.expand_blank(cell)
def flag_cell(self, x, y):
cell = self.board.cells[x][y]
if not cell.revealed:
cell.is_flagged = True
def print_user_board(self):
print('--------- GAME BOARD --------')
print(' ' + ' '.join([str(index + 1) for index in range(len(game.board.cells[0]))]))
print(' ' + ''.join(['___' for index in range(len(game.board.cells[0]))]))
print ('\n'.join([str(index + 1) + ' | ' + ' '.join([cell.display() for cell in row]) for index, row in enumerate(game.board.cells)]))
def print_full_board(self):
print('--------- DEV BOARD ---------')
print(' ' + ' '.join([str(index + 1) for index in range(len(game.board.cells[0]))]))
print(' ' + ''.join(['___' for index in range(len(game.board.cells[0]))]))
print ('\n'.join([str(index + 1) + ' | ' + ' '.join([cell.display(True) for cell in row]) for index, row in enumerate(game.board.cells)]))
class Board(object):
def __init__(self, rows, columns, density):
"""
Args:
rows (int): number of rows
columns (int): number of columns
density (int): mine density of the board (in percentage)
"""
self.rows = rows
self.columns = columns
self.density = density
self.n_bombs = int((rows * columns) * (self.density / 100))
self.n_cells_toreveal = self.rows * self.columns - self.n_bombs
self.cells = [ [Cell(i,j) for j in range(columns)] for i in range(rows) ]
self.bombs = []
self.place_mines()
self.shuffle_board()
self.set_numbered_cells()
#print('nb of bombs:', self.n_bombs)
#print('nb of other cells:', self.n_cells_toreveal)
def place_mines(self):
local_n_bombs = self.n_bombs
for i in range(len(self.cells)): # Iterates on rows
for j in range(len(self.cells[0])): # Iterates on columns
self.cells[i][j].is_bomb = True
self.bombs.append(self.cells[i][j]) # Add the cell to the list of bombs
local_n_bombs -= 1
if local_n_bombs == 0: # All mines are placed
return
def shuffle_board(self):
for i in range(len(self.cells)): # Iterates on rows
for j in range(len(self.cells[0])): # Iterates on columns
rand_i = randrange(self.rows)
rand_j = randrange(self.columns)
#print('rand_i, rand_j: {}, {}'.format(rand_i, rand_j))
if i != rand_i and j != rand_j:
temp_cell = self.cells[rand_i][rand_j]
self.cells[rand_i][rand_j] = self.cells[i][j]
self.cells[rand_i][rand_j].row = rand_i
self.cells[rand_i][rand_j].column = rand_j
self.cells[i][j] = temp_cell
self.cells[i][j].row = i
self.cells[i][j].column = j
def set_numbered_cells(self):
deltas = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)] # Offsets of 8 surrounding cells
for bomb in self.bombs:
#print('bomb:{},{}'.format(bomb.row,bomb.column))
for delta in deltas:
current_row = bomb.row + delta[0]
current_column = bomb.column + delta[1]
if current_row > -1 and current_column > -1:
try:
self.cells[current_row][current_column].value += 1
#print('cell:{},{}'.format(bomb.row + delta[0],bomb.column + delta[1]))
except IndexError:
pass
def expand_blank(self, cell):
deltas = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)] # Offsets of 8 surrounding cells
queue = deque() # Queue holding the current blank cell and all surrounding blank cells
visited_cells = [] # List holding the visited cells
queue.append(cell) # Add the current blank cell to the empty queue
while queue:
current_blank = queue.popleft()
for delta in deltas:
surround_row = current_blank.row + delta[0]
surrounding_col = current_blank.column + delta[1]
if surround_row > -1 and surrounding_col > -1:
try:
surrounding_cell = self.cells[surround_row][surrounding_col]
if not surrounding_cell.revealed: # Prevents from decreasing the counter more than once for the same cell
surrounding_cell.revealed = True
self.n_cells_toreveal -= 1
if surrounding_cell.value == 0 and surrounding_cell not in visited_cells:
queue.append(surrounding_cell)
visited_cells.append(surrounding_cell)
except IndexError:
pass
class Cell(object):
def __init__(self, row, column):
self.row = row
self.column = column
self.is_bomb = False
self.is_flagged = False
self.value = 0
self.revealed = False
def display(self, reveal_all=False):
if self.is_flagged and self.is_bomb and reveal_all:
return 'X'
elif self.is_flagged and not reveal_all:
return 'F'
elif self.is_bomb and (reveal_all or self.revealed):
return '@'
elif self.revealed or reveal_all:
return str(self.value)
else:
return '_'
def __repr__(self):
return '{}(value:{}, is_bomb:{}, is_flagged:{})'.format(self.__class__.__name__, self.value, self.is_bomb, self.is_flagged)
if __name__ == '__main__':
game = Game()
game.initialize()
game.start()
|
##python code to clean and tokenize a file
from __future__ import print_function
import string
import re,sys,os,codecs
from unicodedata import normalize
from mosestokenizer import *
# load document into memory
def load_doc(filename):
# open the file as read only
file = codecs.open(filename, 'r', encoding='utf-8')
# read all text
text = file.read()
# close the file
file.close()
return text
# split a loaded document into sentences
def to_sentences(doc):
return doc.strip().split('\n')
# clean a list of lines
def clean_lines(lines,lang):
cleaned = list()
tokenize=MosesTokenizer(lang)
for line in lines:
# tokenize usig moses tokenizer
line=tokenize(line)
# convert to lower case
line = [word.lower() for word in line]
# store it as a string
line = ' '.join(line)
cleaned.append(line)
return cleaned
# save a list of clean sentences to file
def save_clean_sentences(sentences, filename):
fout=open(filename,'a')
for line in sentences:
print(line, file=fout)
fout.close()
print('Saved: %s' % filename)
if __name__=="__main__":
# load data for cleaning
filename = sys.argv[1]
lang=sys.argv[2]
doc = load_doc(filename)
sentences = to_sentences(doc)
print(sentences[-1])
sentences = clean_lines(sentences,lang)
print(sentences[-1])
save_clean_sentences(sentences, filename+'.processed')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ANFIS in torch: the ANFIS layers
@author: James Power <[email protected]> Apr 12 18:13:10 2019
Acknowledgement: twmeggs' implementation of ANFIS in Python was very
useful in understanding how the ANFIS structures could be interpreted:
https://github.com/twmeggs/anfis
"""
import itertools
from collections import OrderedDict
import numpy as np
import torch
import torch.nn.functional as F
dtype = torch.float
class FuzzifyVariable(torch.nn.Module):
"""
Represents a single fuzzy variable, holds a list of its MFs.
Forward pass will then fuzzify the input (value for each MF).
"""
def __init__(self, mfdefs):
super(FuzzifyVariable, self).__init__()
if isinstance(mfdefs, list): # No MF names supplied
mfnames = ['mf{}'.format(i) for i in range(len(mfdefs))]
mfdefs = OrderedDict(zip(mfnames, mfdefs))
self.mfdefs = torch.nn.ModuleDict(mfdefs)
self.padding = 0
@property
def num_mfs(self):
"""Return the actual number of MFs (ignoring any padding)"""
return len(self.mfdefs)
def members(self):
"""
Return an iterator over this variables's membership functions.
Yields tuples of the form (mf-name, MembFunc-object)
"""
return self.mfdefs.items()
def pad_to(self, new_size):
"""
Will pad result of forward-pass (with zeros) so it has new_size,
i.e. as if it had new_size MFs.
"""
self.padding = new_size - len(self.mfdefs)
def fuzzify(self, x):
"""
Yield a list of (mf-name, fuzzy values) for these input values.
"""
for mfname, mfdef in self.mfdefs.items():
yvals = mfdef(x)
yield mfname, yvals
def forward(self, x):
"""
Return a tensor giving the membership value for each MF.
x.shape: n_cases
y.shape: n_cases * n_mfs
"""
y_pred = torch.cat([mf(x) for mf in self.mfdefs.values()], dim=1)
if self.padding > 0:
y_pred = torch.cat([y_pred,
torch.zeros(x.shape[0], self.padding)], dim=1)
return y_pred
class FuzzifyLayer(torch.nn.Module):
"""
A list of fuzzy variables, representing the inputs to the FIS.
Forward pass will fuzzify each variable individually.
We pad the variables so they all seem to have the same number of MFs,
as this allows us to put all results in the same tensor.
"""
def __init__(self, varmfs, varnames=None):
super(FuzzifyLayer, self).__init__()
if not varnames:
self.varnames = ['x{}'.format(i) for i in range(len(varmfs))]
else:
self.varnames = list(varnames)
maxmfs = max([var.num_mfs for var in varmfs])
for var in varmfs:
var.pad_to(maxmfs)
self.varmfs = torch.nn.ModuleDict(zip(self.varnames, varmfs))
@property
def num_in(self):
"""Return the number of input variables"""
return len(self.varmfs)
@property
def max_mfs(self):
""" Return the max number of MFs in any variable"""
return max([var.num_mfs for var in self.varmfs.values()])
def __repr__(self):
"""
Print the variables, MFS and their parameters (for info only)
"""
r = ['Input variables']
for varname, members in self.varmfs.items():
r.append('Variable {}'.format(varname))
for mfname, mfdef in members.mfdefs.items():
r.append('- {}: {}({})'.format(mfname,
mfdef.__class__.__name__,
', '.join(['{}={}'.format(n, p.item())
for n, p in mfdef.named_parameters()])))
return '\n'.join(r)
def forward(self, x):
""" Fuzzyify each variable's value using each of its corresponding mfs.
x.shape = n_cases * n_in
y.shape = n_cases * n_in * n_mfs
"""
assert x.shape[1] == self.num_in, \
'{} is wrong no. of input values'.format(self.num_in)
y_pred = torch.stack([var(x[:, i:i + 1])
for i, var in enumerate(self.varmfs.values())],
dim=1)
return y_pred
class AntecedentLayer(torch.nn.Module):
"""
Form the 'rules' by taking all possible combinations of the MFs
for each variable. Forward pass then calculates the fire-strengths.
"""
def __init__(self, varlist):
super(AntecedentLayer, self).__init__()
# Count the (actual) mfs for each variable:
mf_count = [var.num_mfs for var in varlist]
# Now make the MF indices for each rule:
#######full combinations of rule bases
mf_indices = [(0, 0, 5), (0, 1, 5), (0, 2, 5), (0, 3, 5), (0, 4, 5),
(1, 5, 0), (1, 5, 1), (1, 5, 2), (1, 5, 3), (1, 5, 4),
(2, 5, 0), (2, 5, 1), (2, 5, 2), (2, 5, 3), (2, 5, 4),
(3, 5, 0), (3, 5, 1), (3, 5, 2), (3, 5, 3), (0, 5, 4),
(4, 0, 5), (4, 1, 5), (4, 2, 5), (4, 3, 5), (4, 4, 5), ]
########popping one rule base
##We can pick our rule bases manually where
##For example , (0, 0 ,1) , (1, 2, 2), (2,1,0) .....etc
# 0 = 'far_left'
# 1 = 'near_left'
# 2 = 'zero'
# 3 = 'near_right'
# 4 = 'far_right'
# 5 = 'none'
mf_out = [-3, -2, 0, 2, 3,
-3, -2, -1, 0, 1,
-2, -1, 0, 1, 2,
-1, 0, 1, 2, 3,
3, 2, 0, -2, -3]
self.mf_indices = torch.tensor(list(mf_indices))
self.mf_out = mf_out
# mf_indices.shape is n_rules * n_in
print(mf_count)
print(len(self.mf_indices))
def num_rules(self):
return len(self.mf_indices)
def extra_repr(self, varlist=None):
if not varlist:
return None
row_ants = []
mf_count = [len(fv.mfdefs) for fv in varlist.values()]
for rule_idx in itertools.product(*[range(n) for n in mf_count]):
thisrule = []
for (varname, fv), i in zip(varlist.items(), rule_idx):
thisrule.append('{} is {}'
.format(varname, list(fv.mfdefs.keys())[i]))
row_ants.append(' and '.join(thisrule))
return '\n'.join(row_ants)
def forward(self, x):
""" Calculate the fire-strength for (the antecedent of) each rule
x.shape = n_cases * n_in * n_mfs
y.shape = n_cases * n_rules
"""
# Expand (repeat) the rule indices to equal the batch size:
batch_indices = self.mf_indices.expand((x.shape[0], -1, -1))
# Then use these indices to populate the rule-antecedents
ants = torch.gather(x.transpose(1, 2), 1, batch_indices)
# ants.shape is n_cases * n_rules * n_in
# Last, take the AND (= product) for each rule-antecedent
rules = torch.prod(ants, dim=2)
return rules
class ConsequentLayer(torch.nn.Module):
"""
A simple linear layer to represent the TSK consequents.
Hybrid learning, so use MSE (not BP) to adjust coefficients.
Hence, coeffs are no longer parameters for backprop.
"""
def __init__(self, d_in, d_rule, d_out):
super(ConsequentLayer, self).__init__()
c_shape = torch.Size([d_rule, d_out, d_in + 1])
self._coeff = torch.zeros(c_shape, dtype=dtype, requires_grad=True)
@property
def coeff(self):
"""
Record the (current) coefficients for all the rules
coeff.shape: n_rules * n_out * (n_in+1)
"""
return self._coeff
@coeff.setter
def coeff(self, new_coeff):
"""
Record new coefficients for all the rules
coeff: for each rule, for each output variable:
a coefficient for each input variable, plus a constant
"""
assert new_coeff.shape == self.coeff.shape, \
'Coeff shape should be {}, but is actually {}' \
.format(self.coeff.shape, new_coeff.shape)
self._coeff = new_coeff
def fit_coeff(self, x, weights, y_actual):
"""
Use LSE to solve for coeff: y_actual = coeff * (weighted)x
x.shape: n_cases * n_in
weights.shape: n_cases * n_rules
[ coeff.shape: n_rules * n_out * (n_in+1) ]
y.shape: n_cases * n_out
"""
# Append 1 to each list of input vals, for the constant term:
x_plus = torch.cat([x, torch.ones(x.shape[0], 1)], dim=1)
# Shape of weighted_x is n_cases * n_rules * (n_in+1)
weighted_x = torch.einsum('bp, bq -> bpq', weights, x_plus)
# Can't have value 0 for weights, or LSE won't work:
weighted_x[weighted_x == 0] = 1e-12
# Squash x and y down to 2D matrices for lstsq:
weighted_x_2d = weighted_x.view(weighted_x.shape[0], -1)
y_actual_2d = y_actual.view(y_actual.shape[0], -1)
# Use to do LSE, then pick out the solution rows:
try:
coeff_2d, _ = torch.lstsq(y_actual_2d, weighted_x_2d)
except RuntimeError as e:
print('Internal error in lstsq', e)
print('Weights are:', weighted_x)
raise e
coeff_2d = coeff_2d[0:weighted_x_2d.shape[1]]
# Reshape to 3D tensor: divide by rules, n_in+1, then swap last 2 dims
self.coeff = coeff_2d.view(weights.shape[1], x.shape[1] + 1, -1) \
.transpose(1, 2)
# coeff dim is thus: n_rules * n_out * (n_in+1)
def forward(self, x):
"""
Calculate: y = coeff * x + const [NB: no weights yet]
x.shape: n_cases * n_in
coeff.shape: n_rules * n_out * (n_in+1)
y.shape: n_cases * n_out * n_rules
"""
# Append 1 to each list of input vals, for the constant term:
x_plus = torch.cat([x, torch.ones(x.shape[0], 1)], dim=1)
# Need to switch dimansion for the multipy, then switch back:
y_pred = torch.matmul(self.coeff, x_plus.t())
return y_pred.transpose(0, 2) # swaps cases and rules
class PlainConsequentLayer(ConsequentLayer):
"""
A linear layer to represent the TSK consequents.
Not hybrid learning, so coefficients are backprop-learnable parameters.
"""
def __init__(self, *params):
super(PlainConsequentLayer, self).__init__(*params)
@property
def coeff(self):
"""
Record the (current) coefficients for all the rules
coeff.shape: n_rules * n_out * (n_in+1)
"""
return self.coefficients
def fit_coeff(self, x, weights, y_actual):
"""
"""
assert False, \
'Not hybrid learning: I\'m using BP to learn coefficients'
class WeightedSumLayer(torch.nn.Module):
"""
Sum the TSK for each outvar over rules, weighted by fire strengths.
This could/should be layer 5 of the Anfis net.
I don't actually use this class, since it's just one line of code.
"""
def __init__(self):
super(WeightedSumLayer, self).__init__()
def forward(self, weights, tsk):
"""
weights.shape: n_cases * n_rules
tsk.shape: n_cases * n_out * n_rules
y_pred.shape: n_cases * n_out
"""
# Add a dimension to weights to get the bmm to work:
y_pred = torch.bmm(tsk, weights.unsqueeze(2))
return y_pred.squeeze(2)
class AnfisNet(torch.nn.Module):
"""
This is a container for the 5 layers of the ANFIS net.
The forward pass maps inputs to outputs based on current settings,
and then fit_coeff will adjust the TSK coeff using LSE.
"""
def __init__(self, description, invardefs, outvarnames, mamdani_out, input_keywords, number_of_mfs, hybrid=True):
super(AnfisNet, self).__init__()
self.description = description
self.outvarnames = outvarnames
self.hybrid = hybrid
varnames = [v for v, _ in invardefs]
mfdefs = [FuzzifyVariable(mfs) for _, mfs in invardefs]
self.num_in = len(invardefs)
self.input_keywords = input_keywords
self.number_of_mfs = number_of_mfs
#######setting number of rule base for anfis structure
self.num_rules = np.prod([len(mfs) for _, mfs in invardefs]) ##full comb
self.num_rules = 25
###############################################################
print(self.num_rules)
self.mam_varnames = [mam_v for mam_v, _ in mamdani_out]
self.mam_mfdefs = [FuzzifyVariable(mam_mfs) for _, mam_mfs in mamdani_out]
if self.hybrid:
cl = ConsequentLayer(self.num_in, self.num_rules, self.num_out)
else:
cl = PlainConsequentLayer(self.num_in, self.num_rules, self.num_out)
self.layer = torch.nn.ModuleDict(OrderedDict([
('fuzzify', FuzzifyLayer(mfdefs, varnames)),
('rules', AntecedentLayer(mfdefs)),
# normalisation layer is just implemented as a function.
('consequent', cl),
# weighted-sum layer is just implemented as a function.
]))
@property
def num_out(self):
return len(self.outvarnames)
@property
def coeff(self):
return self.layer['consequent'].coeff
@coeff.setter
def coeff(self, new_coeff):
self.layer['consequent'].coeff = new_coeff
def fit_coeff(self, x, y_actual):
"""
Do a forward pass (to get weights), then fit to y_actual.
Does nothing for a non-hybrid ANFIS, so we have same interface.
"""
if self.hybrid:
self(x)
self.layer['consequent'].fit_coeff(x, self.weights, y_actual)
def input_variables(self):
"""
Return an iterator over this system's input variables.
Yields tuples of the form (var-name, FuzzifyVariable-object)
"""
return self.layer['fuzzify'].varmfs.items()
def output_variables(self):
"""
Return an list of the names of the system's output variables.
"""
return self.outvarnames
def extra_repr(self):
rstr = []
vardefs = self.layer['fuzzify'].varmfs
rule_ants = self.layer['rules'].extra_repr(vardefs).split('\n')
for i, crow in enumerate(self.layer['consequent'].coeff):
rstr.append('Rule {:2d}: IF {}'.format(i, rule_ants[i]))
rstr.append(' ' * 9 + 'THEN {}'.format(crow.tolist()))
return '\n'.join(rstr)
def forward(self, x):
"""
Forward pass: run x thru the five layers and return the y values.
I save the outputs from each layer to an instance variable,
as this might be useful for comprehension/debugging.
"""
self.fuzzified = self.layer['fuzzify'](x)
self.raw_weights = self.layer['rules'](self.fuzzified)
self.weights = F.normalize(self.raw_weights, p=1, dim=1)
c_shape = torch.Size([25, 1, 1])
self._coeff2 = torch.zeros(c_shape, dtype=dtype, requires_grad=True)
with torch.no_grad():
for i in range(25):
self._coeff2[i][0][0].copy_(self.mam_mfdefs[self.layer['rules'].mf_out[i] + 3].mfdefs['mf0'].b)
self._coeff2 = self._coeff2.transpose(0, 2)
c_shape = torch.Size([25, 1, len(self.weights.unsqueeze(2))])
self._coeff = torch.zeros(c_shape, dtype=dtype, requires_grad=True)
self._coeff = self._coeff.transpose(0, 2)
with torch.no_grad():
for j in range(len(self.weights.unsqueeze(2))):
self._coeff[j].copy_(self._coeff2[0][0])
y_pred = torch.bmm(self._coeff, self.weights.unsqueeze(2))
self.y_pred = y_pred.squeeze(2)
return self.y_pred
|
"""
ConfigFile.py
Created on: Feb 8, 2016
Author: Lee
"""
def basic_parse(file_name):
"""
Parses a config file with format:
<Field Name 0>: <Value 0>
<Field Name 1>: <Value 1>
.
.
.
<Field Name n>: <Value n>
Inputs: config file name
Outputs: a dictionary consisting of Field Name Value pairs
"""
with open(file_name) as config_file:
file_list = config_file.read().replace(': ', '\n').strip('\n').split('\n')
file_list = [(file_list[2 * i], file_list[2 * i + 1]) for i in range(len(file_list)//2)]
fields, values = map(list, zip(*file_list))
fields = [field.replace(" ", "_") for field in fields]
for i in range(len(values)):
try:
values[i] = int(values[i])
except ValueError:
continue
return dict(zip(fields, values))
class ConfigFile:
"""
Note that any config file parser will do, as long as it returns a dictionary
which can be used as the config file's __dict__.
"""
def __init__(self, file_name, parser=basic_parse):
self.__dict__ = parser(file_name)
|
# use input para guardar o nome digitado pelo usuário
# coloque a variável que você criou antes no local correto abaixo:
print("Olá", ,"!")
# use input para perguntar a idade do usuario
# use int para converter a idade digitada em número
idade = int(idade)
# coloque a variável com a idade no local correto abaixo:
print("Então você tem", ,"anos...")
# crie a expressão para que a mensagem seguinte seja mostrada
# apenas e o usuário tiver menos de 18 anos
if ( ): print("Você ainda é menor de idade.")
# crie uma expressão para que a mensagem seguinte seja mostrada
# se o usuário tiver mais ou igual a 18 anos
if ( ): print("Voce é maior de idade.")
# use input para perguntar qual a comida favorita do usuário
# e guarde em uma variável
# compare a resposta do usuário com 2 comidas favoritas suas
# e mostre uma mensagem diferente para cada uma delas
if ( ): print( )
if ( ): print( )
# crie uma expressão que verifique se a comida do usuário
# é diferente da sua primeira E da sua segunda favoritas.
# guarde na variável abaixo:
desconhecida =
# se a expressão anterior estiver correta, esta mensagem só vai
# ser mostrada se a comida do usuário for diferente das
# 2 comidas que você comparou antes
if (desconhecida): print("Não conheço essa comida...")
# Usando a variavel abaixo 'comidaboa', pergunte se a comida
# do usuário é boa se ela for desconhecida.
# Diga para o usuário responder com 's' ou 'n'
comidaboa = "n"
if ( ): comidaboa =
# mostre uma mensagem com print para caso o usuário responder 's'
# mostre uma mensagem com print para caso o usuário responder 'n'
# salve e execute o programa com F5!
|
## 1 - Criar expressões para as seguintes operações:
# a) Somar sua idade e 10:
# b) Calcular o dobro de 35:
# c) Diferença da sua idade com a de um(a) colega:
# d) Somar o dobro da sua idade com a metade da idade de um(a) colega:
## 2 - Usar parênteses, se necessário, para que as expressões abaixo façam o resultado certo:
# a) = 12
4 + 4 * 2
# b) = 3
10 - 4 / 2
# c) = 60
2 * 4 + 6 * 3
# d) = 17
2 * 4 + 6 - 3
## 3 - Vamos criar um pequeno programa:
# a) Crie 2 variáveis: uma para guardar o ano que você nasceu, e outra para guardar
# sua idade.
# b) Agora calcule a diferença entre um ano qualquer e o ano que você nasceu
# usando as variáveis que você criou antes, e coloque o resultado em uma nova
# variável. Este valor é quantos anos você terá no ano que você usar na expressão!
# c) Crie uma variável para guardar uma idade maior que a sua
# d) Agora subtraia a idade maior da sua idade, e some ao ano que você nasceu.
# Use apenas as variáveis que você criou antes, e coloque o resultado em uma nova
# variável!
# e) Agora copie o valor das variáveis que você criou para as variáveis abaixo, de
# acordo com o nome delas, no lugar dos '0':
copia_sua_idade = 0
copia_ano_nascimento = 0
copia_idade_maior = 0
copia_ano_da_idade_no_futuro = 0
##### Agora EXECUTE O PROGRAMA COM F5 #####
print("Você nasceu em {}, e hoje tem {} anos.".format(copia_ano_nascimento,copia_sua_idade))
print("No ano de {}, você terá {} anos de idade!".format(copia_ano_da_idade_no_futuro,copia_idade_maior - copia_sua_idade))
|
##Practical 5
##Question 1
##try:
## dataFile = open('Data/precipitations-europe.txt')
##except IOError as err:
## print ('The following error occurred:',err)
##else:
## data = dataFile.readlines()
## dataFile.close() # we have read the full content of the file so we can close it
## minPrecipitation = []
## maxPrecipitation = []
## averagePrecipitation = 0.0
## row = 1 # first line should be omitted
##
## while row < len(data):
##
## cells = data[row].split(',')
## cells[0] = int(cells[0])
## cells[1] = float(cells[1])
## if (len(minPrecipitation) == 0 or
## cells[1] < minPrecipitation[1]):
## minPrecipitation = [cells[0], cells[1]]
##
## if (len(maxPrecipitation) == 0 or
## cells[1] > maxPrecipitation[1]):
## maxPrecipitation = [cells[0], cells[1]]
##
## averagePrecipitation += cells[1]
##
## row += 1
##
## print ("min precipitation was", minPrecipitation[1], end='')
## print (" and it occurred in",minPrecipitation[0],)
##
## print ("max precipitation was", maxPrecipitation[1], end='')
## print (" and it occurred in",maxPrecipitation[0])
##
## print ("the average precipitation in last century was",
## averagePrecipitation/(len(data)-1))
##Question 2.1
##dataRecords = {} # keys are years, value are list of three floats:
## # precipitation for Europe, NAmerica, World
##listOfFiles = ['precipitations-europe.txt',
## 'precipitations-NAmerica.txt',
## 'precipitations-world.txt']
##validListOfFiles = []
##
##for fileName in listOfFiles:
## try:
## dataFile = open(fileName)
## except IOError as err:
## print ('The following error occurred:',err)
## else:
## validListOfFiles.append(fileName)
## data = dataFile.readlines()
## dataFile.close()
## row = 1 # first line should be ommitted
## while row < len(data):
##
## cells = data[row].split(',')
##
## # convert each cell to its appropriate type rather than keeping
## # all cells as string
## cells[0] = int(cells[0])
## cells[1] = float(cells[1])
## if cells[0] in dataRecords:
## dataRecords[cells[0]].append(cells[1])
## else:
## # must create a list containing a single element
## dataRecords[cells[0]] = [cells[1]]
##
## row += 1
##
##
#### This section of the code deals with writing the collated data to
#### a text file (.CSV)
##try:
## outputFile = open('collatedFiles.txt','w')
##except IOError as err:
## print ('The following error occurred:',err)
##else:
## # write the header of the file, e.g. column names
## outputFile.write('Years,')
## outputFile.write(','.join(validListOfFiles))
## outputFile.write('\n')
## outputFile.flush()
##
## # write the data. item is a tuple containing item[0]: the key (e.g. year)
## # and item[1] the list of values (three in this case) corresponding the
## # precipitation for that particular year.
## for item in sorted(dataRecords.items()):
## outputFile.write(str(item[0]))
## for value in item[1]:
## outputFile.write(',')
## outputFile.write(str(value))
## outputFile.write('\n')
## outputFile.flush()
##
## outputFile.close()
##Question 2.2
##def readDataFile(fileName):
## try:
## dataFile = open(fileName)
## except IOError as err:
## print ('The following error occurred:',err)
## raise # We don't want to deal with the error here
## # We let the calling function deal with it.
## else:
## data = dataFile.readlines()
## dataRecords = {}
## dataFile.close()
## row = 1 # first line should be ommitted
## while row < len(data):
##
## cells = data[row].split(',')
## if cells[0] in dataRecords:
## raise ValueError() # there should not be duplicate year in the file
## else:
## dataRecords[int(cells[0])] = float(cells[1])
##
## row += 1
## return dataRecords
##
##
##
##def collatePrecipitationFile(fileNames,outputFile):
## '''
## Collate the data of all the files where the name is in the list of string
## fileNames and store the collated data in the file whose name is given by
## the parameter outputfile (a string). files that cannot be opened are simply
## ignored. It is assumed that the data in each file is correct and complete,
## e.g. all contains the same years. Note no checking is done regarding the
## validity of the data.
## The data is written as a CSV file.
##
## '''
## listDataRecords = {} # keys are years, value are list of three floats:
## # precipitation for Europe, NAmerica, World or whatever the
## # files past in parameters
## validListOfFiles = []
## for name in fileNames:
## try:
## dataRecords = readDataFile(name)
## except IOError as err:
## print ('The following error occurred:',err)
## except ValueError as err:
## print ("duplicate year in file", name)
## else:
## validListOfFiles.append(name)
## for item in dataRecords.items():
## if item[0] in listDataRecords:
## listDataRecords[item[0]].append(item[1])
## else:
## listDataRecords[item[0]] = [item[1]]
##
## ## This section of the code deals with writing the collated data to
## ## a text file (.CSV)
## outputF = open(outputFile,'w')
## # write the header of the file, e.g. column names
## outputF.write('Years,')
## outputF.write(','.join(validListOfFiles))
## outputF.write('\n')
## outputF.flush()
##
## # write the data. item is a tuple containing item[0]: the key (e.g. year)
## # and item[1] the list of values (three in this case) corresponding the
## # precipitation for that particular year.
## for item in sorted(listDataRecords.items()):
## outputF.write(str(item[0]))
## for value in item[1]:
## outputF.write(',')
## outputF.write(str(value))
## outputF.write('\n')
## outputF.flush()
##
## outputF.close()
##
##
##
############################################
#### TESTS
###########################################
##
##
##listOfFiles = ['Data/precipitations-europe.txt',
## 'Data/precipitations-NAmerica.txt',
## 'Data/precipitations-world.txt']
##
##collatePrecipitationFile(listOfFiles, 'Data/collated.txt')
##Question 3
### IN THIS MODEL ANSWER, WE ARE USING A SCRIPT, TRY TO TRANSFORM THE SCRIPT
### INTO ONE OR MORE FUNCTION. DISCUSS WITH ONE OF YOUR PEER YOUR SOLUTION,
### ESPECIALLY HOW MANY FUNCTIONS WOULD YOU USE, WHAT EACH FUNCTION SHOULD DO,
### WHAT ARE THE PARAMETERS AND RETURNED VALUES IF ANY.
###
### ANOTHER IMPROVEMENT IS TO WRITE THE DATA LIKE 971.4000000000001 AS 971.4.
### SEARCH HOW TO FORMAT A STRING BEFORE WRITING THE STRING INTO A FILE.
##
############ READING THE DATA FROM FILE ###########
##
##dataFile = open('Data/aberporth_meteorological_data.txt')
##data = dataFile.readlines()
##dataFile.close()
##
##row = 2 # data starts at row 2 (third row)
##yearRecord = {} #keys are years, values are the list of attribute [frost, rain, sunshine]
##
##while row < len(data):
##
## cells = data[row].split(',')
## if cells[0] in yearRecord:
## record = yearRecord.get(cells[0])
## for index in range(4, len(cells)): # 4 as the data we are interested in is in the 5th-7th columns
## record[index - 4] += float(cells[index]) # -4 is the offset for the indices
## else:
## record = []
## for index in range(4, len(cells)):
## record.append(float(cells[index]))
##
## yearRecord[cells[0]] = record
##
## row += 1
##
##
######## WRITING THE SUMMARY FILE ########
##summaryDataFile = open('Data/aberporth_meteorological_data_summary.txt','w')
##
##summaryDataFile.write(data[0])
##cells = data[1].split(',')
##cells = [cells[0]] + cells[4:] # append the header of each column
##summaryDataFile.write(','.join(cells))
##summaryDataFile.flush()
##
##for item in sorted(yearRecord.items()):
## line = item[0]
## for value in item[1]:
## line += ',' +str(value)
##
## summaryDataFile.write(line)
## summaryDataFile.write('\n')
## summaryDataFile.flush()
##
##
##summaryDataFile.close()
##
|
# Each order is represented by an "order id" (an integer).
# We have our lists of orders sorted numerically already, in lists. Write a function to merge our lists of orders into one sorted list.
# def merge_list(my_list, alice_list):
# len_merged_list = len(my_list)+len(alice_list)
# index_my_list = 0
# index_alice_list=0
# index_merged_list = 0
# merged_list = len_merged_list*[None]
# while index_merged_list < len_merged_list:
# exhausted_my_list = index_my_list>=len(my_list)
# exhausted_alice_list = index_alice_list>=len(alice_list)
# if not exhausted_my_list and ((my_list[index_my_list]<alice_list[index_alice_list]) or exhausted_alice_list):
# merged_list[index_merged_list]=my_list[index_my_list]
# index_my_list+=1
# else:
# merged_list[index_my_list]=my_list[index_alice_list]
# index_alice_list+=1
# index_merged_list+=1
# return merged_list
def merge_lists(my_list, alices_list):
# set up our merged_list
merged_list_size = len(my_list) + len(alices_list)
merged_list = [None] * merged_list_size
current_index_alices = 0
current_index_mine = 0
current_index_merged = 0
while current_index_merged < merged_list_size:
is_my_list_exhausted = current_index_mine >= len(my_list)
is_alices_list_exhausted = current_index_alices >= len(alices_list)
# case: next comes from my list
# my list must not be exhausted, and EITHER:
# 1) Alice's list IS exhausted, or
# 2) the current element in my list is less
# than the current element in Alice's list
if not is_my_list_exhausted and (is_alices_list_exhausted or \
(my_list[current_index_mine] < alices_list[current_index_alices])):
merged_list[current_index_merged] = my_list[current_index_mine]
current_index_mine += 1
# case: next comes from Alice's list
else:
merged_list[current_index_merged] = alices_list[current_index_alices]
current_index_alices += 1
current_index_merged += 1
return merged_list
print (merge_lists([2,4,7],[1,3,5]))
|
#!usr/bin/env python
# Created by: Cameron Teed
# Created On: September 2019
# This program adds two numbers together
def main():
# This program adds two numbers together
# Input
first_number = int(input("enter the first number: "))
second_number = int(input("enter the second number: "))
# Procces
sum_ = first_number + second_number
# Output
print("")
print("The sum of {} + {} = {}".format(first_number, second_number, sum_))
if __name__ == "__main__":
main()
|
class Solution:
def isRectangleOverlap(self, rec1, rec2) -> bool:
"""
矩形以列表 [x1, y1, x2, y2] 的形式表示,其中 (x1, y1) 为左下角的坐标,(x2, y2) 是右上角的坐标。
如果相交的面积为正,则称两矩形重叠。需要明确的是,只在角或边接触的两个矩形不构成重叠。
给出两个矩形,判断它们是否重叠并返回结果。
"""
# 长和宽的坐标都分别相交
x1,y1,x2,y2=rec1
x3,y3,x4,y4=rec2
return (x3-x2)*(x4-x1)<0 and (y3-y2)*(y4-y1)<0
sol = Solution()
print(sol.isRectangleOverlap([0,0,1,1],[1,0,2,1])) |
class ListNode():
def __init__(self, node=None):
self.val = node
self.next = None
class Solution(object):
def hasCycle(self, head):
"""
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。
如果 pos 是 -1,则在该链表中没有环。
"""
if not head:
return False
walker = head
runner = head.next
try:
while walker != runner:
walker = walker.next
print(walker.val)
runner = runner.next.next
print(runner.val)
return True
except:
return False
node0 = ListNode(3)
node1 = ListNode(2)
node2 = ListNode(0)
node3 = ListNode(-4)
node0.next = node1
node1.next = node2
node2.next = node3
node3.next = None
res = Solution().hasCycle(node0)
print(res) |
class Solution:
def containsNearbyDuplicate(self, nums, k):
"""
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。
"""
dic = dict()
for i,num in enumerate(nums):
if num in dic:
if (i - dic[num]) <= k:
return True
dic[num] = i
return False
sol = Solution()
print(sol.containsNearbyDuplicate([1,2,3,1,2,3],2))
|
class Solution(object):
def findComplement(self, num):
"""
给定一个正整数,输出它的补数。补数是对该数的二进制表示取反。
注意:
给定的整数保证在32位带符号整数的范围内。
你可以假定二进制数不包含前导零位。
:type num: int
:rtype: int
"""
i = 1
while i <= num:
i = i << 1
return (i-1) ^ num
sol = Solution()
print(sol.findComplement(5)) |
class TreeNode:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def add(self,item):
node = TreeNode(item)
if self.root is None:
self.root = node
return
queue = [self.root]
while queue:
cur_node = queue.pop(0)
if cur_node.left is None:
cur_node.left = node
return
else:
queue.append(cur_node.left)
if cur_node.right is None:
cur_node.right = node
return
else:
queue.append(cur_node.right)
def traval(self, node):
if node is None:
return
print(node.val, end=" ")
self.traval(node.left)
self.traval(node.right)
class Solution(object):
def mergeTrees(self, t1, t2):
"""
:type t1: TreeNode
:type t2: TreeNode
:rtype: TreeNode
"""
if t1 is None and t2 is None:
return None
if t1 and t2 is None:
return t1
if t2 and t1 is None:
return t2
t1.val = t1.val + t2.val
print(t1.val)
self.mergeTrees(t1.left,t2.left)
self.mergeTrees(t1.right,t2.right)
return t1
if __name__ == "__main__":
p = [1,3]
q = [1,3]
pp = Tree()
qq = Tree()
for i in range(len(p)):
pp.add(p[i])
for i in range(len(q)):
qq.add(q[i])
sol = Solution()
print(sol.mergeTrees(pp.root,qq.root)) |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.res = []
def leafSimilar(self, root1, root2):
"""
请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。
:type root1: TreeNode
:type root2: TreeNode
:rtype: bool
"""
def leaf(root):
if root is None:
return None
if root.left is None and root.right is None:
self.res.append(root.val)
return self.res
leaf(root.left)
leaf(root.right)
if leaf(root1) == leaf(root2):
return True
else:
return False
class Solution2:
def leafSimilar(self, root1, root2):
def dfs(node):
if node:
if not node.left and not node.right:
yield node.val
yield from dfs(node.left)
yield from dfs(node.right)
return list(dfs(root1)) == list(dfs(root2)) |
class TreeNode:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def add(self,item):
node = TreeNode(item)
if self.root is None:
self.root = node
return
queue = [self.root]
while queue:
cur_node = queue.pop(0)
if cur_node.left is None:
cur_node.left = node
return
else:
queue.append(cur_node.left)
if cur_node.right is None:
cur_node.right = node
return
else:
queue.append(cur_node.right)
class Solution(object):
def levelOrderBottom(self, root):
"""
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
:type root: TreeNode
:rtype: List[List[int]]
"""
queue = [root]
res = list()
while queue:
next_queue = list()
layer = list()
for node in queue:
if node is not None:
if node.left is not None:
next_queue.append(node.left)
if node.right is not None:
next_queue.append(node.right)
layer.append(node.val)
queue = next_queue
res.append(layer)
res.reverse()
return res
class Solution2(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
stack = [(root,0)]
res = []
while stack!=[]:
node,level = stack.pop()
if node:
if len(res) < (level+1):
res.insert(0,[])
res[-(level+1)].append(node.val)
stack.append((node.right,level+1))
stack.append((node.left,level+1))
return res
if __name__ == "__main__":
t = [1,2,2,3,None,None,3]
tt = Tree()
for i in range(len(t)):
tt.add(t[i])
sol = Solution()
print(sol.levelOrderBottom(tt.root))
|
class Solution(object):
def hasAlternatingBits(self, n):
"""
给定一个正整数,检查他是否为交替位二进制数:
换句话说,就是他的二进制数相邻的两个位数永不相等。
:type n: int
:rtype: bool
"""
t = n ^ (n>>1)
return (t&(t+1))==0
class Solution2(object):
def hasAlternatingBits(self, n):
return not ('11' in str(bin(n)) or '00' in str(bin(n)))
sol = Solution()
print(sol.hasAlternatingBits(5))
|
class TreeNode:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def add(self,item):
node = TreeNode(item)
if self.root is None:
self.root = node
return
queue = [self.root]
while queue:
cur_node = queue.pop(0)
if cur_node.left is None:
cur_node.left = node
return
else:
queue.append(cur_node.left)
if cur_node.right is None:
cur_node.right = node
return
else:
queue.append(cur_node.right)
class Solution(object):
def hasPathSum(self, root, sum):
"""
给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root is None:
return False
if root.left is None and root.right is None and root.val == sum:
return True
return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right,sum-root.val)
|
class Solution:
def findPairs(self, nums, k):
"""
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.
给定一个整数数组和一个整数 k, 你需要在数组里找到不同的 k-diff 数对。这里将 k-diff 数对定义为一个整数对 (i, j), 其中 i 和 j 都是数组中的数字,且两数之差的绝对值是 k.
"""
import collections
class Solution2(object):
def findPairs(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
如果k大于0,则返回两个set的交集
如果k=0,则计数,找出出现1次以上的元素的个数
如果k小于0,返回0
"""
if k>0:
return len(set(nums) & set(n+k for n in nums))
elif k==0:
return sum(v>1 for v in collections.Counter(nums).values())
else:
return 0
sol = Solution2()
print(sol.findPairs([3, 1, 4, 1, 5],0)) |
class Solution:
def largestPerimeter(self, A) -> int:
"""
给定由一些正数(代表长度)组成的数组 A,返回由其中三个长度组成的、面积不为零的三角形的最大周长。
如果不能形成任何面积不为零的三角形,返回 0。
"""
A = sorted(A)
while len(A)>=3:
if A[-3]+A[-2] > A[-1]:
return A[-1]+A[-2]+A[-3]
else:
A.pop()
return 0
sol = Solution()
print(sol.largestPerimeter([3,6,2,3]))
|
# class Room:
# def __init__(self, name, description, exits):
# self.name = name
# self.description = description
# self.exits = exits
# def get_description(self):
# return f"Name: {self.name}\nDescription: {self.description}\nExits: {self.exits}\n"
# room_1 = Room("Main Hall", "dusty", 3)
# room_2 = Room("Fire Room", "burnt", 1)
# print(room_1.get_description())
# print(room_2.get_description())
# class Monster:
# def __init__(self, name, total_health):
# self.name = name
# self.health = total_health
# def get_info(self):
# return f"{self.health"
# monster_1 = Monster("Goblin", 10)
# monster_2 = Monster("King Goblin", 50)
# print(monster_1.get_info())
counter = 0
while counter < 5:
print(counter)
counter += 1
|
def main():
contacts = []
continue_ = True
while continue_:
choice = int(input("\nContacts\
\n========\
\n1. View Contacts\
\n2. Add new contact\
\n3. Search\
\n4. Update contact\
\n5. Delete Contact\
\n6. Quit\
\nEnter choice number\
\n>>"))
if choice == 1:
view(contacts)
continue_ = get_menu_choice()
elif choice == 2:
add(contacts)
continue_ = get_menu_choice()
elif choice == 3:
search(contacts)
continue_ = get_menu_choice()
elif choice == 4:
update(contacts)
continue_ = get_menu_choice()
elif choice == 5:
delete(contacts)
continue_ = get_menu_choice()
elif choice == 6:
break
def add(contacts):
contact = {}
contact["name"] = input("\nEnter a name\
\n>>")
contact["number"] = input("\nEnter a number\
\n>>")
contacts.append(contact)
def get_menu_choice():
choice2 = int(input("\n1. Return to menu\
\n2. Quit\
\n>>"))
return choice2 == 1
def delete(contacts):
choice = input("enter a name\n>>")
if len(contacts) == 0:
print("name not found")
return
for contact in contacts:
if choice == contact['name']:
contacts.remove(contact)
break
def search(contacts):
name = input("Enter a name\n>>")
if len(contacts) == 0:
print("name not found")
return
for contact in contacts:
if name == contact['name']:
print(f"{contact['name']} {contact['number']}\n")
elif name != contact['name']:
print("no names")
return
def update(contacts):
name = input("Enter a name\n>>")
if len(contacts) == 0:
print("name not found")
return
for contact in contacts:
if name == contact['name']:
number = input("Enter a new number\n>>")
contact['number'] = number
break
elif name != contact['name']:
print("name is not found")
continue
#add contact, update bob which doesnt exist, add bob, update bob again, something wrong
def view(contacts):
if len(contacts) == 0:
print("There are no contacts")
return
for contact in contacts:
print(f"\n{contact['name']} {contact['number']}\n")
main() |
#coding utf-8
def backtracking(word):
if(len(word) < 3):
return
for i in xrange(len(word)):
new_word = word[:i] + word[i+1:]
if(new_word not in set_words):
set_words.add(new_word)
backtracking(new_word)
while True:
try:
global set_words
set_words = set()
word = raw_input()
set_words.add(word)
for i in xrange(len(word)):
set_words.add(word[i])
backtracking(word)
list_words = list(set_words)
list_words.sort()
for iword in list_words:
print iword
print
except EOFError:
break
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
只要当前序列中的'('多于')'即合法
def duang(left_n, right_n, max_n, base=''):
if left_n == max_n:
base += ')'*(max_n-right_n)
return(base)
if left_n > right_n:
duang(left_n+1, right_n, max_n, base+'(')
duang(left_n, right_n+1, max_n, base+')')
elif left_n == right_n:
duang(left_n+1, right_n, max_n, base+'(')
'''
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
self.result = []
self.duang(0,0,n)
return (self.result)
'''
只要当前序列中的'('多于')'即合法
'''
def duang(self, left_n, right_n, max_n, base=''):
if left_n == max_n:
base += ')'*(max_n-right_n)
self.result.append(base)
return
if left_n > right_n:
self.duang(left_n+1, right_n, max_n, base+'(')
self.duang(left_n, right_n+1, max_n, base+')')
elif left_n == right_n:
self.duang(left_n+1, right_n, max_n, base+'(')
s = Solution()
s.generateParenthesis(3)
|
from tkinter import *
import time
class GameUI:
# Variables
rotationsAfterBoss = 0
# Initializing Object
def __init__(self, bot):
self.window = Tk()
self.window.geometry("700x350")
self.game_bot = bot
self.run = False
def startMenu(self):
win = self.window
# Create buttons to trigger the starting and ending of the loop
start = Button(win, text="Start Game", command=self.start)
start.pack(padx=10)
stop = Button(win, text="Stop Game", command=self.stop)
stop.pack(padx=15)
# Call the print_hello() function after 1 sec.
win.after(1000, self.game_loop)
win.mainloop()
def game_loop(self):
win = self.window
if self.run:
Label(win, text="Running Game", font=('Helvetica 10 bold')).pack()
self.game_bot.startQueue()
print("Pausing for 20 seconds")
time.sleep(20)
if not self.run:
Label(win, text="Not Running Game",
font=('Helvetica 10 bold')).pack()
# After 1 sec call the print_hello() again
win.after(1000, self.game_loop)
def start(self):
self.run = True
def stop(self):
self.run = False
|
# method that sums up all integers in any array; basically involves flattening a nested list
def _flattenNestedList(inputlist):
for item in inputlist:
if not isinstance(item,(list,tuple)):
yield item
else:
for subitem in _flattenNestedList(item):
yield subitem
def _extractIntList(list):
integer_list = [item for item in list if isinstance(item, (int,long))]
return integer_list
if __name__ == "__main__":
test_list = ['1', 3, ['the'], 'quick', [3, [['lazy'], [4, [-6]]]], 'fox', [1, '%'], '-5', [-5]]
flatlist = _flattenNestedList(test_list)
flatted_list = list(flatlist)
print "flat list:", flatted_list
integerlist = _extractIntList(flatted_list)
print "integer list:", integerlist
print "sum of integer list:", sum(integerlist) |
""" Solution for exercise 8.12 from Think Python.
Author: Aliesha Garrett
"""
def rotate_word(s,i):
""" 'Rotates' each letter in a word 'i' places. (Rotating a letter is shifting through the alphabet, wrapping around to the beginning again if necessary.)
i: integer
s: string
"""
word=''
if abs(i) > 26:
i=i%26
for char in s:
old=ord(char)
new=old+i
if old < 65:
fixed=old
elif old > 122:
fixed=old
elif 90 < old < 97:
fixed=old
elif 65 < old < 90:
if new > 90:
fixed=new-26
elif new < 65:
fixed=new+26
else:
fixed=new
elif 97 < old < 122:
if new > 122:
fixed=new-26
elif new < 97:
fixed=new+26
else:
fixed=new
rotated=chr(fixed)
word=word+rotated
return word
print rotate_word('cheer',7)
print rotate_word('melon',-10)
print rotate_word('sleep',9)
|
"""This code creates a dragon curve.
Author: Aliesha Garrett
"""
import math
from swampy.TurtleWorld import *
def dragon(t, length, n):
"""
dragon draws a dragon curve.
t: A turtle.
length: Length of the steps- should be a positive integer.
n: The number of recursions to go through. Should be a positive integer.
"""
fd(t,length)
dragonx(t,length,n)
def dragonx(t,length,n):
if n==0:
return
dragonx(t,length,n-1)
rt(t)
dragony(t,length,n-1)
fd(t,length)
def dragony(t,length,n):
if n==0:
return
fd(t,length)
dragonx(t,length,n-1)
lt(t)
dragony(t,length,n-1)
def dragons(n):
"""
Builds a string with the steps process_string should take to draw a dragon curve.
n: The number of recursions to go through. Should be a positive integer.
"""
if n == 0: return ""
return "F"+dragonxs(n-1)
def dragonxs(n):
if n==0:
return ""
return dragonxs(n-1)+"+"+dragonys(n-1)+"F"
def dragonys(n):
if n==0:
return ""
return "F"+dragonxs(n-1)+"-"+dragonys(n-1)
def process_string(string,length,t):
"""
draws a dragon curve using the string built by dragons.
t: A turtle.
length: Length of the steps- should be a positive integer.
string: the string returned by dragons.
"""
for char in string:
if char == 'F':
fd(t,length)
elif char == '+':
rt(t)
elif char == '-':
lt(t)
def hilbert(t, length, n):
"""
hilbert draws a hilbert curve.
t: A turtle.
length: Length of the steps- should be a positive integer.
n: The number of recursions to go through. Should be a positive integer.
"""
fd(t,length)
hilbertx(t,length,n)
def hilbertx(t,length,n):
if n==0:
return
lt(t)
hilberty(t,length,n-1)
fd(t,length)
rt(t)
hilbertx(t,length,n-1)
fd(t,length)
hilbertx(t,length,n-1)
rt(t)
fd(t,length)
hilberty(t,length,n-1)
lt(t)
def hilberty(t,length,n):
if n==0:
return
rt(t)
hilbertx(t,length,n-1)
fd(t,length)
lt(t)
hilberty(t,length,n-1)
fd(t,length)
hilberty(t,length,n-1)
lt(t)
fd(t,length)
hilbertx(t,length,n-1)
rt(t)
world=TurtleWorld()
t=Turtle()
length=5
t.delay=.01
n=100
gosper(t,length,n)
wait_for_user()
|
import sqlite3
from sqlite3 import Error
class UserDeviceDB:
create_user_table = """
CREATE TABLE IF NOT EXISTS users (
email TEXT PRIMARY KEY,
device_id INTEGER,
topic_arn TEXT
);
"""
create_device_table = """
CREATE TABLE IF NOT EXISTS devices (
device_id INTEGER PRIMARY KEY,
status TEXT
);
"""
def __init__(self, path):
self.connection = self.create_connection(path)
self.execute_query(self.create_user_table)
self.execute_query(self.create_device_table)
def create_connection(self, path):
connection = None
try:
connection = sqlite3.connect(path)
print("Connected to DB successfully")
except Error as e:
print(f"During connection to {path} DB error '{e}' occurred")
return connection
def execute_query(self, query):
cursor = self.connection.cursor()
try:
cursor.execute(query)
self.connection.commit()
print("Executed query successfully")
except Error as e:
print(f"During query execution error '{e}' occurred")
def execute_read_query(self, query):
cursor = self.connection.cursor()
result = None
try:
cursor.execute(query)
result = cursor.fetchall()
return result
except Error as e:
print(f"During read query execution error '{e}' occurred")
def add_user(self, email, device_id, topic_arn):
query = """
INSERT INTO
users (email, device_id, topic_arn)
VALUES
('{0}', {1}, '{2}')
""".format(email, device_id, topic_arn)
self.execute_query(query)
def add_device(self, device_id, status):
query = """
INSERT INTO
devices (device_id, status)
VALUES
({0}, '{1}')
""".format(device_id, status)
self.execute_query(query)
def update_device_status(self, device_id, status):
query = """
UPDATE
devices
SET
status = '{0}'
WHERE
device_id = {1}
""".format(status, device_id)
self.execute_query(query)
def get_device_status(self, device_id):
query = """
SELECT
status
FROM
devices
WHERE
devices.device_id = {0}
""".format(device_id)
return self.execute_read_query(query)
def get_topic_from_id(self, device_id):
query = """
SELECT
topic_arn
FROM
users
WHERE
users.device_id = {0}
""".format(device_id)
return self.execute_read_query(query)
def update(self, flag, list):
# for adding users
if (flag[0] == "u"):
self.add_user(list[0], int(list[1]), list[2])
# for adding devices
elif (flag[0] == "d"):
self.add_device(int(list[0]), list[1])
# for updating device status
elif (flag[0] == "s"):
self.update_device_status(int(list[0]), list[1])
# for getting device status
elif (flag[0] == "g"):
return self.get_device_status(int(list[0]))
# for getting topic from id
elif (flag[0] == "t"):
return self.get_topic_from_id(int(list[0]))
return None
def main():
db = UserDeviceDB("test.db")
db.update("u", ["[email protected]", "2554", "http:www.google.com"])
db.update("d", ["2554", "not full"])
print(db.update("t", ["2554"]))
print(db.update("g", ["2554"]))
db.update("s", ["2554", "full"])
print(db.update("t", ["2554"]))
print(db.update("g", ["2554"]))
if __name__ == "__main__":
main()
|
class programs:
def __init__(self,ai,ml,course,i,desig):
self.ai = ai
self.ml = ml
print("course 1.) ml or 2.) ai")
course = input()
print(course)
if (course == 'ml' ):
print("mentor or student")
desig = input()
print(desig)
if (desig == 'mentor'):
ai = []
ai = input("name , time").split()
else:
print(ai)
|
'''
#! coding=utf-8
@Author: zmFeng
@Created at: 2019-06-12
@Last Modified: 2019-06-12 8:26:56 am
@Modified by: zmFeng
expression builder
'''
from utilz import triml
class AbsResolver(object):
''' a class to resolve argument passed to it, this default one return
any argument passed to it
'''
def resolve(self, arg):
''' resolve the given arg to value
'''
return arg
_df_rsv = AbsResolver()
class Exp(object):
'''
an expression that should be able to evaluate itself
'''
def __init__(self, lopr, op, ropr=None):
'''
Args:
lopr: the left operator
op: the operation, can be one of +,-,*,/,and,or,not,==,>,>=,<,<=,!=
ropr: the right operator
'''
self._op, self._lopr, self._ropr = op, lopr, ropr
def chain(self, op, *oprs):
''' return a chain expression, an often used example is
a.chain('and', expb, expc, expf)
'''
e = self
for opr in oprs:
e = Exp(e, op, opr)
return e
def and_(self, exp):
''' convenient "and" operation
'''
return Exp(self, 'and', exp)
def or_(self, exp):
''' convenient "or" operation
'''
return Exp(self, 'or', exp)
def eval(self, resolver=None):
'''
evaluate myself
Args:
resolver: an instance that sub-class AbsResolver, who can solve the operators
'''
if not resolver:
resolver = _df_rsv
l = self._lopr.eval(resolver) if isinstance(self._lopr, Exp) else resolver.resolve(self._lopr)
r = self._ropr.eval(resolver) if isinstance(self._ropr, Exp) else resolver.resolve(self._ropr)
op, rc = self._op, None
if isinstance(op, str):
op = triml(op)
if op == 'and':
rc = l and r
elif op == 'or':
rc = l or r
elif op == 'not':
rc = not l
elif op == '==':
rc = l == r
elif op == '!=':
rc = l != r
elif op == '>':
rc = l > r
elif op == '>=':
rc = l >= r
elif op == '<':
rc = l < r
elif op == '<=':
rc = l <= r
elif op in ('+', 'add'):
rc = l + r
elif op == '-':
rc = l - r
elif op == '*':
rc = l * r
elif op == '/':
rc = l / r
else:
rc = self._eval_ext(op, l, r)
else:
rc = op(l)
return rc
def __str__(self):
return '(%s %s %s)' % (self._lopr, self._op, self._ropr)
def _eval_ext(self, op, l, r):
''' when the basic function eval can not process, this will be called,
extend this in the sub-class to do more op
'''
return None
|
'''
The solution follows the following approach:
->Pour from first bucket to second
1.Fill the first bucket and empty it into the second bucket.
2.If first bucket is empty fill it.
3.If the second bucket is full empty it.
4.Repeat steps 1,2,3 till either the first or second bucket contains the
desired amount.
->Pour from first bucket to second
1.Fill the second bucket and empty it into the first bucket.
2.If second bucket is empty fill it.
3.If the firts bucket is full empty it.
4.Repeat steps 1,2,3 till either the first or second bucket contains the
desired amount.
'''
def two_bucket(bucket_one_cap, bucket_two_cap, desired_liters, first):
if first == "one":
moves = 0
bucket_one, bucket_two = 0, 0
while(True):
if bucket_one == 0:
moves += 1
bucket_one = bucket_one_cap
elif bucket_two == bucket_two_cap:
moves += 1
bucket_two = 0
else:
moves += 1
measure = min(bucket_one, bucket_two_cap - bucket_two)
bucket_one -= measure
bucket_two += measure
if bucket_one == desired_liters:
return (moves, "one", bucket_two)
elif bucket_two == desired_liters:
return (moves, "two", bucket_one)
elif first == "two":
moves = 0
bucket_one, bucket_two = 0, 0
while(True):
if bucket_two == 0:
moves += 1
bucket_two = bucket_two_cap
elif bucket_one == bucket_one_cap:
moves += 1
bucket_one = 0
else:
moves += 1
measure = min(bucket_two, bucket_one_cap - bucket_one)
bucket_two -= measure
bucket_one += measure
if bucket_one == desired_liters:
return (moves, "one", bucket_two)
elif bucket_two == desired_liters:
return (moves, "two", bucket_one)
|
import math
def fuel_double_checker(file):
f = open(file, "r")
fuel_total = 0
for line in f:
fuel_module = math.floor(int(line)/3) - 2
fuel_total = fuel_total + fuel_module
while (math.floor(fuel_module/3) > 0):
fuel_module = math.floor(fuel_module/3) - 2
if (fuel_module > 0):
fuel_total = fuel_total + fuel_module
print(fuel_total)
if __name__ == "__main__":
fuel_double_checker("input_day1.txt") |
'''
Created on 17 ene. 2019
* Contruir un objeto Fraccion pasándole al constructor el numerador y el denominador.
* Obtener la fracciónn.
* Obtener y modificar numerador y denominador. No se puede dividir por cero.
* Obtener resultado de la fracción(número real).
* Multiplicar la fracción por un número.
* Multiplicar, sumar y restar fracciones.
* Simplificar la fracción.
@author: Rafael Miguel Cruz Álvarez
'''
class Fraccion:
def __init__(self,numerador,denominador):
self.__numerador=numerador
self.setDenominador(denominador)
def getNumerador(self):
return self.__numerador
def setNumerador(self,numerador):
self.__numerador=numerador
def getDenominador(self):
return self.__denominador
def setDenominador(self,denominador):
self.__denominador=denominador
if (denominador==0):
print("El denominador no puede ser 0, se le asigna 1.")
self.__denominador=1
def obtenerReal(self):
return self.__numerador/self.__denominador
def multiplicarPorEntero(self,num):
self.__numerador*=num
self.__denominador*=1
resultado= print(self.__numerador,"/",self.__denominador)
return resultado
def multiplicarFracciones(self,fraccion1,fraccion2):
n=fraccion1.getNumerador()*fraccion2.getNumerador()
d=fraccion1.getDenominador()*fraccion2.getDenominador()
resultado = print(n,"/",d)
return resultado
def sumarFracciones(self,fraccion1,fraccion2):
auxNum=fraccion1.getNumerador()*fraccion2.getDenominador()
auxDen=fraccion2.getNumerador()*fraccion1.getDenominador()
auxDivisor = fraccion1.getDenominador() * fraccion2.getDenominador();
resultado = print(auxNum+auxDen,"/",auxDivisor)
return resultado
def restarFracciones(self,fraccion1,fraccion2):
auxNum= fraccion1.getNumerador()*fraccion2.getDenominador()
auxDen=fraccion2.getNumerador()*fraccion1.getDenominador()
auxDivisor = fraccion1.getDenominador() * fraccion2.getDenominador();
resultado = print(auxNum-auxDen,"/",auxDivisor)
return resultado
def hallarMcd(self):
dividendo= self.__numerador
divisor=self.__denominador
while(dividendo%divisor!=0) :
resto = dividendo%divisor
dividendo=divisor
divisor=resto
return divisor
def simplificarFraccion(self):
mcd=self.hallarMcd()
self.__numerador/=mcd
self.__denominador/=mcd
return f"{self.__numerador}/{self.__denominador}"
def __str__(self):
return f"{self.__numerador}/{self.__denominador}"
if __name__=="__main__":
fraccion1 = Fraccion(1,0)
fraccion2 = Fraccion(3,2)
fraccion3 = Fraccion(4,5)
fraccion4 = Fraccion(3,6)
print(fraccion1)
print(fraccion1.obtenerReal())
fraccion1.multiplicarPorEntero(5)
fraccion2.sumarFracciones(fraccion1,fraccion2)
fraccion3.restarFracciones(fraccion1,fraccion2)
fraccion1.multiplicarFracciones(fraccion1, fraccion2)
print(fraccion4.simplificarFraccion()) |
"""Doc string."""
from clean_up import clean_text_in
from pprint import pprint
from sys import argv
import histogram
import random
def random_words(word_count, histogram):
"""Returns dict containing random words & number of times it was chosen."""
# Dict will hold random word and number of times that word was chosen.
chosen_words = dict()
weights = get_word_weights(histogram)
# Adds number(WORD_COUNT) of random words to the CHOSEN_WORDS dict.
for i in range(0, word_count):
random_float = random.random()
cumulative_probability = 0.0
for (word, word_weight) in weights.items():
# computing the increasing cumulative probability
cumulative_probability += word_weight
# until the cumulative_probability becomes greater than random_int
if random_float < cumulative_probability:
if word not in chosen_words:
chosen_words[word] = 1
else:
chosen_words[word] += 1
break
# pprint(chosen_words)
return chosen_words
def get_word_weights(histogram):
"""Returns dict with words in histogram and their corresponding weight."""
weights = dict()
total_values = sum(histogram.values())
for key, value in histogram.items():
weight = float(value) / total_values
weights[key] = weight
# print(key, value, weights[key])
# print("sumtype", type(sum(histogram.values())))
return weights
# testpy
if __name__ == '__main__':
filename = argv[1:]
text = clean_text_in(filename[0])
fish = {"one": 1, "fish": 4, "two": 1, "red": 1, "blue": 1}
# histogram = histogram.make_histogram_from(sys.argv[1])
# weights = word_weights(histogram)
histo = histogram.make_histogram_from(text)
# weights = get_word_weights(histo)
print(random_words(20000, histo))
|
#!/usr/bin/python
""" Just count all the vowels and consonants """
def fun(string):
""" something is missing. I can't get correct number of consonants in output
I saw this game/trick in a video lecture in Python Bible, good series and modified
it to make it a function so that it can be called again and again."""
# string = input(" Say something ")
vowels = 0
consonants = 0
for letter in string:
if letter.lower() in "aeiou":
vowels += 1
elif letter == " ":
pass
else:
consonants += consonants
print(f"There are {vowels} vowels and {consonants} consonants in\
' {string} '")
fun(input("Say something ")) # I.C now
|
class BST :
def __init__(self, data) :
self.data = data
self.right = None
self.left = None
def set_data(self, data) :
self.data = data
def get_data(self) :
return self.data
def get_right(self) :
return self.right
def get_left(self) :
return self.left
def find_element(root, data) :
current = root
while current is not None :
if data == current :
return current
if data < current :
current = current.get_left ( )
if data > current :
current = current.get_right ( )
return current
def min_element(root) :
current = root
if root is None :
return None
else :
return current (current.get_left ( ))
def min_element_without_recursion(root) :
current = root
if current is None :
return None
else :
while current is not None :
current = current.get_left ( )
return current
def max_element(root) :
current = root
if current is None :
return None
else :
return max_element (current.get_right ( ))
def max_element_without_recursion(root) :
current = root
if current is None :
return
else :
while current is not None :
current = current.get_right ( )
return current
def in_order_predecessor(root) :
temp = None
if root.get_left ( ) :
temp = root.get_left ( )
while temp is not None :
temp = temp.get_right
return temp
def in_order_successor(root) :
temp = None
if root.get_right ( ) :
temp = root.get_right ( )
while temp is not None :
temp = temp.get_left ( )
return temp
def insertion_bst(root, node) :
if root is None :
root = node
else :
if node.data < root.data :
if root.left is None :
root.left = node
else :
return insertion_bst (root.left, node)
else :
if root.right is None :
root.right = node
else :
return insertion_bst (root.right, node)
"""def delete_node(root, data):
if root is None:
return None
else:
current = root
while current is not None:
if data > current.data:
if current.get_right() is None:
return None
else:
return delete_node(root.right, data)
else:
if current.get_left() is None:
return None
else:
return delete_node(root.left, data)
if current.get_left() is not None and current.get_right() is not None:
current.set_data(current.get_right().data)
current.right = None
elif current.get_left() is None and current.get_right() is not None:
current.set_data (current.get_right ( ).data)
current.right = None
elif current.get_left() is not None and current.get_right() is None:
"""
def lca(root, a, b) :
while root :
if (a <= root.data) and (b >= root.data) or (a <= root.data) and (b >= root.data) :
return root
elif a < root.data :
root = root.left
else :
root = root.right
def check_bst(root):
if root is None:
return
else:
current = root
if current.left.data < current.right.data:
return True
else:
return False
x = check_bst(root.left)
y = check_bst(root.right)
if x is True and y is True:
print("bst")
else:
print("not bst")
def kth_smallest_number(root, k):
count = 0
if not root:
return None
left = kth_smallest_number(root.left, k)
if left:
return left
count += 1
if count == k:
return root
return kth_smallest_number(root.right, k)
def count_tree(root, n):
if n <= 1:
return
else:
sum_1 = 0
for i in range(1, n+1):
left = count_tree(root-1)
right = count_tree(n-root)
sum_1 = left*right
return sum_1
|
from array import *
array1 = array('i', [10,20,30,40,50])
array1.insert(2,90)
array1.remove(30)
print(array1.index(40))
array1[4]=300
for x in array1:
print(x)
|
def mix_up(a, b):
x=a[1]
y=b[1]
s=list(a)
r=list(b)
s[1]=y
r[1]=x
a=''.join(s)
b=''.join(r)
c=a
a=b
b=c
return (a,b)
print(mix_up("archit","sharma")) |
# testing type modifications
car = input("Enter car price: ")
car = int(car)
car += 5
print(car)
house = int(input("Enter house price: "))
house -= 5
print(house)
input("Press Enter to exit")
|
# A module for standard card deck
class UsualCardSet:
"""Describes a standard card"""
SUITS = ["Spades", "Hearts", "Diamonds", "Clubs"]
RANKS = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
def __init__(self, suit=None, rank=None):
self.suit = suit
self.rank = rank
def __str__(self):
rep = self.suit + "-" + self.rank
return rep
@property
def value(self):
if self.rank == "Ace":
v = 1
elif self.rank in ("Jack", "Queen", "King"):
v = 10
elif not self.rank:
v = None
else:
v = int(self.rank)
return v
class Deck:
"""Describes a deck object as a set of card objects"""
def __init__(self):
self.deck = []
def __str__(self):
rep = ', '.join(map(str, self.deck))
return rep
def create_deck(self, card_set):
for rank in card_set.RANKS:
for suit in card_set.SUITS:
self.deck.append(card_set(suit, rank))
def shuffle(self):
import random
random.shuffle(self.deck)
print("\nThe deck was shuffled.")
def give_card(self, player, number=1):
if self.deck:
for i in range(number):
print("Giving some card from deck to", player.name)
player.cards.append(self.deck[0])
player.score += self.deck[0].value
del self.deck[0]
else:
print("No cards in deck.")
# debug!
card_set = UsualCardSet()
print(card_set.SUITS)
deck = Deck()
deck += card_set
#deck.create_deck(card_set)
print("\n", "New deck:\n", deck)
# debug!
# debug!
debug = False
if debug:
card = UsualCardSet("S", "2")
print("Predefined card:", card)
print("Value of predefined card:", card.value)
deck = Deck()
deck.create_deck(UsualCardSet)
print("\n", "New deck:\n", deck)
deck.shuffle()
print("\n", "Shuffled deck:\n", deck)
import test8.card_player
player1 = test8.card_player.CardPlayer("John")
player2 = test8.card_player.CardPlayer("Bill")
players = [player1, player2]
print("\nDealing deck to players:")
while deck.deck:
for player in players:
deck.give_card(player, 2)
print("\n", player1)
print("\n", player2)
print("\n", "Deck after dealing:\n", deck)
# debug! |
# A module for a simple game
class CardPlayer:
"""Describes a card player as object"""
def __init__(self, name, score=0):
self.name = name
self.cards = []
self.score = score
def __str__(self):
rep = "\tName: " + self.name + "\n\tCards: " + ', '.join(map(str, self.cards)) + "\n\tScore: " + str(self.score)
return rep
def ask_yes_no(question):
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
def ask_number(question, low, high):
response = None
while response not in range(low, high):
response = int(input(question))
return response
|
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
bit = []
flag = 1 if x > 0 else -1
x = abs(x)
result = 0
while x > 0:
result = result * 10 + x % 10
x = x / 10
# big than 32-bit singed int
max_val = 2 ** 31
return result * flag if result < max_val else 0
def main():
sol = Solution()
print sol.reverse(321)
if __name__ == '__main__':
main()
|
def comma(s1):
for f in range(len(s1)):
if s1[f] not in "0123456789,":
raise Exception("Invalid input. Your input contains characters other than numbers and commas.")
else:
if s1[f]=="," and s1[f+1]==",":
raise Exception("Invalid input. Your input contains 2 or more consecutive commas.")
else:
return "The input is valid."
while True:
comma(input("Enter a string and i will validate it:")) |
import requests
APPID = "b4534e0524a27721f663d669f5581780"
URL_BASE = "http://api.openweathermap.org/data/2.5/"
def current_weather(lat: float, lon: float,units: str = "metric", appid: str = APPID) -> dict:
print(locals(), end='\n=========\n')
res = requests.get(URL_BASE + "weather", params=locals()).json()
return res["main"]["temp"]
if __name__ == "__main__":
while True:
(latitude) = input("Enter a location:").strip()
(longitude) = input("Enter a location:").strip()
if latitude and longitude:
print("Прогноз погоды: ", current_weather(latitude, longitude))
else:
break |
import pandas as pd
FILENAME = "salary.csv"
def load_data():
"""
This function read the csv file
and looks for a place to divide the data set.
Return the tuple with <numpy.ndarray> objects:
- worked years
- salary brutto
- worked years to prediction
"""
df = pd.read_csv(FILENAME) # declared DataFrame container
try:
data_indexes_to_complete = df[df['salaryBrutto'].isnull()].index.tolist() # empty value - indexes
data_indexes_to_complete.extend(df[df['salaryBrutto']==' '].index.tolist()) # NaN value - indexes
data_indexes_to_complete = list(set(data_indexes_to_complete)) # if NaN is first sort indexes
except:
print("Error appending to list")
stop_train_data_index = data_indexes_to_complete[0] # end training data and start testing(predicting) data
try:
# training set
x = train_data_worked_years = df["workedYears"][0:stop_train_data_index].astype(float)
y = train_data_salary_brutto = df["salaryBrutto"][0:stop_train_data_index].astype(float)
# testing set
x_pred = pred_data_worked_years = df["workedYears"][stop_train_data_index:].astype(float)
except:
print("Error parse to float type")
return(x.values, y.values, x_pred.values) |
def FLOYD_WARSHALL(weight):
#Setting n to be the keys of the dictionary
n = weight.keys()
print weight
#Checks the amount of vertices
if len(n) > 100:
print 'The maximum number of vertices of the directed graph is 100 and yours is', len(n)
else:
for m in n:
print ''
#If statement signifying the start of the sequence
if m == 0:
print 'Inital:'
print 'm =', m
#If statement signifying the intermidiate parts of the sequence
if m < len(n) - 1 and m !=0:
print 'm =', m
#If statement signifying the end of the sequence
if m == len(n) - 1:
print 'Final:'
print 'm =', m
for i in n:
for j in n:
#weight[i][j] is the weight of the edge
if weight[i][m] + weight[m][j] < weight[i][j]:
weight[i][j] = weight[i][m] + weight[m][j]
#The initial start of the sequence
if m == 0:
print '%5s'% weight[i][j],
#The final conclusion of the sequence
if m == len(n)-1:
print '%5s'% weight[i][j],
#The intermidiate steps in the sequence
if m > 0 and m < len(n)-1:
print '%5s'% weight[i][j],
print ''
for m in range(2):
print ''
#If statement signifying the start of the sequence
if m == 0:
print 'Inital:'
print 'm =', m
#If statement signifying the intermidiate parts of the sequence
if m < len(n) - 1 and m !=0:
print 'm =', m
#If statement signifying the end of the sequence
if m == len(n) - 1:
print 'Final:'
print 'm =', m
for i in n:
for j in n:
#weight[i][j] is the weight of the edge
if weight[i][m] + weight[m][j] < weight[i][j]:
weight[i][j] = weight[i][m] + weight[m][j]
#The initial start of the sequence
if m == 0:
print '%5s'% weight[i][j],
#The final conclusion of the sequence
if m == len(n)-1:
print '%5s'% weight[i][j],
#The intermidiate steps in the sequence
if m > 0 and m < len(n)-1:
print '%5s'% weight[i][j],
print ''
def main():
#graph is the dictionary that I will append the list of dictionary to create a
#nested dictionary
#newD is the dictionary that I append the weights to
#l is the list that I append the dictionary weights to
#weight is a nested list that appends the weights of each row from value that is
#read from the file f
graph = {}
newD = {}
l = []
weight = []
with open('graph_file.txt', "r") as f:
for line in f:
values = line.rstrip().split(" ")
weight.append(values)
for i in range(len(weight)):
for j in range(len(weight[i])):
if weight[i][j] == 'inf':
newD[j] = float(weight[i][j])
else:
newD[j] = int(weight[i][j])
l.append(newD)
newD = {}
for i in range(len(l)):
graph[i] = l[i]
FLOYD_WARSHALL(graph)
main()
|
a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))
d = b ** 2 - (4 * a * c)
x1 = (-b - d ** 0.5) / (2 * a)
x2 = (-b + d ** 0.5) / (2 * a)
print(" 답은: ", x1, "and", x2) |
import re
import encodings
months = ('January','February','March','April','May','June',\
'July','August','September','October','November',' December')
print(months)
mystr="ddd"
cats = ['Tom', 'Snappy', 'Kitty', 'Jessie', 'Chester']
cats.append("pippo")
cats.count(4)
print(cats)
dict = {'Andrew Parson':8806336, \
'Emily Everett':6784346, 'Peter Power':7658344, \
'Lewis Lame':1122345}
dict["aaa"]="000"
print(dict.keys())
print(dict.values())
print(dict)
a = [5, 1, 4, 3]
print(sorted(a)) ## [1, 3, 4, 5]
print(a) ## [5, 1, 4, 3]
str = 'an example word:cat!!'
match = re.search(r'word:\w\w\w', str)
# If-statement after search() tests if it succeeded
if match:
print('found', match.group()) ## 'found word:cat'
else:
print('did not find')
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
class MyClass:
@staticmethod
def my_method():
return "aaa"
|
x=int(input())
y=0
while x>0:
x=x // 10
y=y+1
print (y)
|
import sqlite3
import json
import csv
from datetime import datetime
db_name = "test"
sql_transaction = []
connection = sqlite3.connect('{}.db'.format(db_name))
c = connection.cursor()
def create_table():
c.execute("""CREATE TABLE IF NOT EXISTS users
(id TEXT PRIMARY KEY,
first_name TEXT,
last_name TEXT,
email TEXT,
gender TEXT)""")
def sql_insert_user(id,first_name,last_name,email,gender):
try:
sql = """INSERT INTO users (id, first_name, last_name, email, gender) VALUES ("{}","{}","{}","{}","{}");""".format(id, first_name, last_name, email, gender)
print(sql)
try:
c.execute(sql)
connection.commit()
# print("successfully inserted", id)
except:
print("Something went wrong with entering", id)
pass
except Exception as e:
print('insertion',str(e))
if __name__ == "__main__":
create_table()
# sql = "SELECT * FROM users;"
# c.execute(sql)
# result = c.fetchall()
# print(result)
with open("./users.csv", buffering=1000) as f:
users = csv.reader(f, delimiter=',')
for row in users:
sql_insert_user(row[0], row[1], row[2], row[3], row[4]) |
# Binomial Experiment
# A binomial experiment (or Bernoulli trial) is a statistical experiment that has the following properties:
# 1. The experiment consists of n repeated trials.
# 2. The trials are independent.
# 3. The outcome of each trial is either success (s) or failure (f).
# Bernoulli Random Variable and Distribution
# The sample space of a binomial experiment only contains two points, s and f. We define a Bernoulli random variable to be the random variable defined by X(s)=1 and X(f)=0.
# Binomial Distribution
# We define a binomial process to be a binomial experiment meeting the following conditions:
# 1. The number of successes is x.
# 2. The total number of trials is n.
# 3. The probability of success of 1 trial is p.
# 4. The probability of failure of 1 trial q, where q = 1 - p.
# 5. b(x, n, p) is the binomial probability, meaning the probability of having exactly x successes out of n trials.
# The binomial random variable is the number of successes, x, out of n trials.
# map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)
boy, girl = map(float, input().split(' '))
p_boy = boy / (boy + girl)
# Recursive functions in Python
# Recursion is a way of programming or coding a problem, in which a function calls itself one or more times in its body.
# Usually, it is returning the return value of this function call.
# Termination condition:
# A recursive function has to terminate to be used in a program.
# A recursive function terminates, if with every recursive call the solution of the problem is downsized and moves towards a base case.
# A base case is a case, where the problem can be solved without further recursion. A recursion can lead to an infinite loop, if the base case is not met in the calls.
def factorial(n):
if n < 2:
return 1
else:
return n * factorial(n-1)
def combination(n, k):
return factorial(n) / (factorial(k) * factorial(n - k))
def binomial(n, k, p):
return combination(n,k)*(p**k)*((1-p)**(n-k))
p_family = [binomial(6, i, p_boy) for i in range(3, 7)]
# '{:06.2f}'.format()
# For floating points the padding value represents the length of the complete output. In the example below we want our output to have at least 6 characters with 2 after the decimal point.
print("{:.3f}".format(sum(p_family)))
|
from math import erf
cdf = lambda x: .5 + .5 * erf((x - mu)/2 ** .5/sigma)
print(round(cdf(x1), 3))
print(round(cdf(x3) - cdf(x2), 3))
# Create a function for integration
# Calculate the area underneath a curve for a finite interval
# One method to compute integrals approximately, that a computer can actually handle, is done by filling the area of interest with a user-defined amount of rectangles of equal width and variable height then summing up all of the rectangle's areas.
# The Midpoint Rule:
# Each rectangle out of "N" rectangles has to have an equal width, Δx, but each nth rectangle cannot be the exact same: the varying factor is the height which varies as the function evaluated at a certain point.
# The midpoint rule gets its name from the fact that you are evaluating the height of each rectangle as f(x_n), where "x_n" is the respective center-point of each rectangle, as apposed to the left or right of the rectangle.
# Using the midpoint is like implementing an average which will make the approximation more accurate than if you were to use the right or left.
# The cumulative distribution function for a function with normal distribution is:
# phi(x) = 0.5 * (1 + erf((x - mu) / (sigma * 2 ** .5)))
# where erf is the error function:
# erf(z) = (2 / pi ** 0.5) * integration from 0 to 2 e ** (-x**2) dx
e = 2.71828
pi = 3.14159
def normal_pdf(x, mu, sigma):
top = e**(-(x - mu)**2/(2*sigma**2))
bottom = sigma*(2*pi)**0.5
return top/bottom
def normal_cdf(a, b, n, mu, sigma):
dx = float(b - a) / n
area = 0
midpoint = a + (dx / 2)
for i in range(n):
area += normal_pdf(midpoint, mu, sigma) * dx
midpoint += dx
return area
n = 10000
print(round(normal_cdf(0, 19.5, n, mu, sigma), 3))
print(round(normal_cdf(20, 22, n, mu, sigma), 3)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 19 15:13:44 2020
@author: fiona
"""
# input() function
# x = input("Enter your name:")
# print("Hello, " + x)
# Day 0: Mean, Median, and Mode
n = int(input()) # change a string to an integer
nums = [int(i) for i in input().split(' ')]
# Mean
mean = sum(nums)/n
# Median
nums.sort()
if n % 2 == 1:
median = nums[(n - 1) / 2]
else:
median = (nums[int(n / 2)] + nums[int(n / 2 - 1)]) / 2
# Mode
# The count() method returns the number of elements with the specified value.
max_nums = max([nums.count(i) for i in set(nums)])
for i in nums:
if nums.count(i) == max_nums:
mode = i
break
print(mean)
print(median)
print(mode)
|
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the makeAnagram function below.
def makeAnagram(a, b):
# .subtract(): Elements are subtracted from an iterable or from another mapping (or counter)
dict_a = Counter(a)
dict_b = Counter(b)
dict_a.subtract(dict_b)
return sum(abs(i) for i in dict_a.values())
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
a = input()
b = input()
res = makeAnagram(a, b)
fptr.write(str(res) + '\n')
fptr.close()
import math
import os
import random
import re
import sys
from collections import Counter
# Complete the makeAnagram function below.
def makeAnagram(a, b):
# .elements(): Return an iterator over elements repeating each as many times as its count.
# Elements are returned in arbitrary order.
# If an element’s count is less than one, elements() will ignore it.
res = list((Counter(b) - Counter(a)).elements()) + list((Counter(a) - Counter(b)).elements())
return len(res)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
a = input()
b = input()
res = makeAnagram(a, b)
fptr.write(str(res) + '\n')
fptr.close()
|
# From: https://stackoverflow.com/questions/40330623/keep-on-halving-by-integer-division-until-x-1/40330685
def keep_dividing(x):
num = x # temp variable
count = 0 # number of times divided
while num > 1:
num //= 2
print(num)
count += 1
print("number of times divided = ", count)
keep_dividing(128)
# TESTS
# check divide by 0 |
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
if n == 1 or n == 2:
return True
base = 2
while base < n:
base = base * 2
if n == base:
return True
return False
|
class Solution:
def sortArrayByParity(self, A: List[int]) -> List[int]:
even_array = []
odd_array = []
for num in A:
if num % 2 == 0:
even_array.append(num)
else:
odd_array.append(num)
even_array.extend(odd_array)
return even_array
'''
NOTES
**Understad**
We are given an array of *NON NEGATIVE INTEGERS* therefore we don't have to worry about negatives in our array.
We have to return an array **NEW ARRAY?** with even elements first and then all the odd elements.
As seen from the first sample test case, the order of the even and odd elements does not appear to matter.
What happens with an empty array? [] -> [] ?
What happens when they are all odd? [1,1,1,1] - > [1,1,1,1]?
Same for even ^^
**MATCH**
We can use arrays, or lists in python, to divide the odd and even elements in the array
**PLAN**
We are going to iterate through the whole array once, we are going to check if an element is odd or even by % 2, if 0, it is even, else it is odd.
We are going to put all the even numbers into even_array and all the odds into odd_array.
At the end, we will return even_array.join(odd_array)
**IMPLEMENT**
Will be done through the code
**REVIEW**
input = [3,1,2,4]
even_array = [2, 4]
odd_array = [3, 1]
num = 4
return [2,4].extend([3,1])
**EVALUATE**
TIME COMPLEXITY: O(N) SINCE WE ARE PASSING THROUGH THE ARRAY ONCE
SPACE COMPLEXITY: O(N) SINCE, IN THE WORST CASE, WE WILL STORE ALL ELEMENTS AGAIN INTO TWO SEPERATE ARRAYS
''' |
from itertools import permutations
import enchant
d = enchant.Dict("en_US")
chars = input("Enter Space Separated Letters\n").split()
anagrams = list(permutations(chars,len(chars)))
file = open("All-Anagrams.txt","w")
mfile = open("Meaningful Anagrams.txt","w")
for i in range(len(anagrams)):
anagrams[i] = "".join(k for k in anagrams[i])
if d.check(anagrams[i]): mfile.write(anagrams[i]+"\n")
else: file.write(anagrams[i]+"\n")
file.close()
mfile.close()
ch1 = str(input(("Do You Have A First Letter? (y/n)\n")))
if ch1 == "y" or ch1 == "Y":
startletter = str(input("Enter The Letter\n"))
file = open(startletter+"-Anagrams.txt","w")
for i in anagrams:
if i[0] == startletter:
file.write(i+"\n")
file.close()
print("Files Created Successfully.") |
PreOrderS = ""
InOrderS = ""
class TreeNode:
def __init__(self,key):
self.key = key
self.left = None
self.right = None
self.p = None
def __str__(self):
return str(self.key)
def PreOrder(n):
PreOrderS = ""
PreOrderS+=n.data
def PreOrderHelper(n):
PreOrderS+=n.data
if (n.left == None):
PreOrderS+="0"
else
PreOrder(n.left)
if (n.right == None):
PreOrderS+="0"
else
PreOrder(n.right)
def InOrder(n):
if(n.left == None):
InOrderS+="0"
else
InOrder(n.left)
InOrderS+=n.data
if(n.right == None):
InOrderS+="0"
else
InOrder(n.right)
def Compare(t1,t2):
PreOrder(t1)
#Create the Trees here, call them t1, t2
def
|
"""
Working with MongoDB vs PostgreSql:
Perhaps the most obvious difference is that the commands/syntax are
slightly different between the two. SQL in general is more straight forward
and intuitive than MongoDB. I also do like how we could test out queries
in ElephantSQL and DB Browser. This is helpful especially since I'm just
getting startedand not entirely confident with the language. Another major
difference is how they operate and what they're used for. SQL is for relational
databases and MongoDB is used for unstructured databases. Structure
seems better for beginners like me. And, it was mentioned in class that
documents are easily lost with MongoDB compared to SQL's. As with everything
new, however, they both present unqiue challenges when learning.
"""
# Recreation of lecture:
import pymongo
# Connect to MongoDB:
client = pymongo.MongoClient("mongodb://admin:<password>@cluster0-shard-00-00-eb7sm.mongodb.net:27017,cluster0-shard-00-01-eb7sm.mongodb.net:27017,cluster0-shard-00-02-eb7sm.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&w=majority")
db = client.test
# First I'm going to delete all the existing documents from class:
db.test.drop()
# Insert data 1 at a time option 1(must cast as dictionary before inserting):
character1 = (2, "Optio dolorem ex a", 0, 0, 10, 1, 1, 1, 1)
db.test.insert_one({'rpg_character': character1})
# Insert RPG data 1 at a time option 2(seems better since get feature names):
db.test.insert_one({
'character_id': 3,
'name': 'Minus c',
'level': 0,
'exp': 0,
'hp': 10,
'strength': 1,
'intelligence': 1,
'dexterity': 1,
'wisdom':1
})
"""
Too add multiple characters at once. Tried to define a function to only change
the name and the character ID but couldn't get it to work. Maybe we can go over.
Tried something similar to last sprint challenge.
"""
characters = [
{
'character_id': 4,
'name': 'Sit ut repr',
'level': 0,
'exp': 0,
'hp': 10,
'strength': 1,
'intelligence': 1,
'dexterity': 1,
'wisdom':1
},
{
'character_id': 3,
'name': 'Minus c',
'level': 0,
'exp': 0,
'hp': 10,
'strength': 1,
'intelligence': 1,
'dexterity': 1,
'wisdom':1
},
{
'character_id': 4,
'name': 'Sit ut repr',
'level': 0,
'exp': 0,
'hp': 10,
'strength': 1,
'intelligence': 1,
'dexterity': 1,
'wisdom':1
}
]
# Insert multiple documents at once:
db.test.insert_many(characters)
# Can find a specific document, like where character_id is 3:
print(list(db.test.find({'character_id': 3})))
# Can update a document. Will change hp to 20 on character_id 4:
db.test.update_one({'character_id': 4}, {'$set': {'hp':20}})
# Can update many documents. Will change all the levels to increase by 2:
db.test.update_many({'level':0}, {'$inc': {'level': 2}})
# Lets look at all the documents in the db:
print(list(db.test.find()))
|
#Joseph Harrison 2020
#find prime-power factorisations
import gcdbez
def prime_pow_fact(n):
ppf = {}
#divide n by 2 until it 2 doesn't divide it anymore
while n % 2 == 0:
if 2 not in ppf:
ppf[2] = 1
else:
ppf[2] += 1
n //= 2
#now try all odd integers
k = 3
while n != 1 and k <= n:
if n % k == 0 and k not in ppf:
ppf[k] = 0
#divide n by k until k doesn't divide it anymore
while n % k == 0:
ppf[k] += 1
n //= k
k += 2
return ppf
#format the ppf in a neat table
def table(ppf):
key_len = max([len(str(p)) for p in ppf.keys()] + [5])
print(f"\nprime{' ' * (key_len - 5)} : exponent")
for p in ppf:
print(f"{p}{' ' * (key_len - len(str(p)))} {ppf[p]}")
def main():
print('find the prime-power factorisation of n > 1\n')
n = gcdbez.get_int_input('n: ', lambda x: x > 1, 'n must be greater than 1')
ppf = prime_pow_fact(n)
table(ppf)
if __name__ == '__main__':
main() |
class Point(object):
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return '(%d, %d)' % (self.x, self.y)
def __add__(self, other):
added_x = self.x + other.x
added_y = self.y + other.y
combined = Point(added_x, added_y)
return combined
p1 = Point(14, 31)
print("Your points are currently " + str(p1) + "\n")
ps = int((raw_input("What do you want to add to the first point?\n")))
pt = int((raw_input("What do you want to add to the second point?\n")))
p2 = Point(ps, pt)
print p1 + p2
print("Above are your new points")
|
#Getting the alphabet to ease things up
from string import ascii_uppercase
def __main__ ():
key = input('Enter the key: ')
key = key.replace(' ', '')
key = key.upper()
t = int(input('Enter T parameter: '))
text = input('Enter the text: ')
text = text.replace(' ', '')
text = text.upper()
while len(text) % t != 0:
text = text + 'X'
par = int(input('Enter 1 for encrypting, 0 for decrypting: '))
add = 1 if par == 1 else -1
i = 0
j = 0
while i < len(text):
less = ord('A')
a = ord(text[i])
b = ord(key[j])
print(ascii_uppercase[((a - less) + add * (b - less) + 26) % 26], end = "")
if i % t == t - 1:
print(" ", end = "")
i += 1
j = (j + 1) % len(key)
print("")
__main__()
|
# write your code here
# print("Enter letters:")
xcount = 0
ocount = 0
def printTicTacToe():
global i, j
xcount = 0
ocount = 0
print("---------")
for i in ticTacToeMatrix:
print("|", end=" ")
for j in i:
if j == "O":
ocount += 1
elif j == "X":
xcount += 1
print(j, end=" ")
print("|")
print("---------")
return ocount, xcount
letters = " "
row1 = list(letters[0:3])
row2 = list(letters[3:6])
row3 = list(letters[6:9])
ticTacToeMatrix = [row1, row2, row3]
ocount, xcount = printTicTacToe()
diff = xcount - ocount
if diff < -1 or diff > 1:
print("Impossible")
exit(0)
xwins = False
owins = False
def check_game_state():
global i, j, xwins, owins
for i in range(0, 3):
for j in range(0, 3):
if j == 1:
if ticTacToeMatrix[i][j - 1] == ticTacToeMatrix[i][j] and ticTacToeMatrix[i][j] == ticTacToeMatrix[i][
j + 1]:
if ticTacToeMatrix[i][j] == "X":
xwins = True
elif ticTacToeMatrix[i][j] == "O":
owins = True
if i == 1:
if ticTacToeMatrix[i - 1][j] == ticTacToeMatrix[i][j] and ticTacToeMatrix[i][j] == \
ticTacToeMatrix[i + 1][j]:
if ticTacToeMatrix[i][j] == "X":
xwins = True
elif ticTacToeMatrix[i][j] == "O":
owins = True
if j == 1 and ticTacToeMatrix[i - 1][j - 1] == ticTacToeMatrix[i][j] and ticTacToeMatrix[i][j] == \
ticTacToeMatrix[i + 1][j + 1]:
if ticTacToeMatrix[i][j] == "X":
xwins = True
elif ticTacToeMatrix[i][j] == "O":
owins = True
if j == 1 and ticTacToeMatrix[i - 1][j + 1] == ticTacToeMatrix[i][j] and ticTacToeMatrix[i][j] == \
ticTacToeMatrix[i + 1][j - 1]:
if ticTacToeMatrix[i][j] == "X":
xwins = True
elif ticTacToeMatrix[i][j] == "O":
owins = True
if i == 2 and j == 2 and xwins == False and owins == False:
letters2 = ''.join(row1)+''.join(row2)+''.join(row3)
if " " in letters2:
print("Game not finished")
else:
printTicTacToe()
print("Draw")
exit(0)
# check_game_state()
if xwins == True and owins == True:
print("Impossible")
elif xwins == True:
print("X wins")
elif owins == True:
print("O wins")
enterCoords = True
letter = "X"
while enterCoords:
print("Enter the coordinates: > ")
coords = input()
coords = coords.split(" ")
isDig = True
for i in coords:
if not i.isdigit():
isDig = False
if not isDig:
print("You should enter numbers!")
columnInd = int(coords[0]) - 1
rowInd = int(coords[1])
if columnInd < 0 or columnInd > 2 or rowInd < 1 or rowInd > 3:
print("Coordinates should be from 1 to 3!")
continue
row = ''
if (rowInd == 1):
row = row3
elif (rowInd == 2):
row = row2
elif (rowInd == 3):
row = row1
element = row[columnInd]
if (element == " "):
# row = row[:columnInd]+'X'+row[columnInd+
row[columnInd] = letter
check_game_state()
if letter == "X":
letter = "O"
else:
letter = "X"
if xwins == True and owins == True:
printTicTacToe()
print("Impossible")
exit(0)
elif xwins == True:
printTicTacToe()
print("X wins")
exit(0)
elif owins == True:
printTicTacToe()
print("O wins")
exit(0)
else:
printTicTacToe()
else:
print("This cell is occupied! Choose another one!")
printTicTacToe()
|
"""
String Compression: Implement a method to perform basic string compression using the counts
of repeated characters. For example, the string aabcccccaaa would become a2blc5a3, If the
"compressed" string would not become smaller than the original string, your method should return
the original string. You can assume the string has only uppercase and lowercase letters (a - z).
"""
class Solution:
def stringCompression(self, s):
if len(s) == 0:
return ''
answer = ''
tmp = s[0]
counter = 1
for letter in s[1:]:
if tmp == letter:
counter += 1
else:
answer += tmp + str(counter)
counter = 1
tmp = letter
answer += tmp + str(counter)
if len(answer) > len(s):
return s
else:
return answer
print(Solution().stringCompression('aabcccccaaa'))
print(Solution().stringCompression('abababs'))
|
"""
Stack Min: How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time.
"""
class MinStack:
def __init__(self, data=[]):
self.data = data
self.min = min(data, default=None)
def __str__(self):
return f'{self.data}'
def push(self, x):
if x < self.min:
self.min = x
self.data.append(x)
def pop(self):
if self.data == []:
return None
x = self.data[-1]
self.data = self.data[:-1]
if x == self.min:
self.min = min(self.data)
print(f'{x}')
return x
def get_min(self):
print(f'{self.min}')
return self.min
x = MinStack([1,2,3,4,5])
print(x)
x.pop()
print(x)
x.push(1000)
print(x)
x.get_min() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.