text
stringlengths 37
1.41M
|
---|
''' https://www.geeksforgeeks.org/mongodb-and-python/
'''
# importing module
from pymongo import MongoClient
# creation of MongoClient
# Connect with the portnumber and host
try:
cluster = MongoClient("mongodb://localhost:27017/")
# cluster = MongoClient("mongodb+srv://ameya:<pwd>@cluster0.csmbw.mongodb.net/<dbname>?retryWrites=true&w=majority")
# Access database
db = cluster['testDb']
# Access collection of the database
collection = db['testCollection']
# dictionary to be added in the database: called as post or document
post1 = {"name": "John", "role": "tester"}
post2 = {
"title": 'MongoDB and Python',
"description": 'MongoDB is no SQL database',
"tags": ['mongodb', 'database', 'NoSQL'],
"viewers": 104
}
post3 = {"_id": 5, "name": "Akshay", "role": "developer"}
# inserting the data in the database
# collection.insert_one(post1)
# collection.insert_many([post2, post3])
# find specific data
results = collection.find({"name": "John"})
print("\nQuried data")
for result in results:
print(result)
print(result["_id"])
record = collection.find({"_id": 5})
print(record)
for i in record:
print(i["_id"])
one_result = collection.find_one({"name": "John"})
print("\none_result")
print(one_result)
# To find() all the entries inside collection name 'footprint'
cursor = collection.find()
print("\nAll records in collection")
for record in cursor:
print(record)
# deleting data
# deleted_result = collection.delete_one({"_id": 5})
# deleted_results = collection.delete_many({})
# print(deleted_results)
# updating data using $set operator
# update_result = collection.update_one({"_id": 5}, {"$set":{"name": "Tiem"}})
# update_result = collection.update_one({"_id": 5}, {"$set":{"address": "141 B"}}) # updating post with field
# print(update_result)
# update_results = collection.update_many({"title": "MongoDB and Python"}, {"$inc": {"viewers": 10}})
# print(update_results)
# counting documents
post_counts = collection.count_documents({})
print(post_counts)
except Exception as error:
print(str(error))
print("Could not connect to MongoDB")
|
import sys
a = sys.argv[1]
dosya = open(a, "r")
liste = [i for i in dosya.read().split("\n")]
chart = [i.split(" ") for i in liste]
number_of_deleted = 0
def fibonacci(n):
if n < 2:
return n
else:
return fibonacci(n - 2) + fibonacci(n - 1)
def deleteUp(row, column):
global number_of_deleted
chart[row - 1][column] = " "
chart[row][column] = " "
number_of_deleted += 1
def deleteDown(row, column):
global number_of_deleted
chart[row + 1][column] = " "
chart[row][column] = " "
number_of_deleted += 1
def deleteLeft(row, column):
global number_of_deleted
chart[row][column - 1] = " "
chart[row][column] = " "
number_of_deleted += 1
def deleteRight(row, column):
global number_of_deleted
chart[row][column + 1] = " "
chart[row][column] = " "
number_of_deleted += 1
def delete_recursively(row, column):
if row -1 < 0:
pass
elif chart[row - 1][column] == number: # ÜST
deleteUp(row, column)
delete_recursively(row - 1, column)
if column + 2 > len(chart[row]):
pass
elif chart[row][column + 1] == number: # SAĞ
deleteRight(row, column)
delete_recursively(row, column + 1)
if column - 1 < 0:
pass
elif chart[row][column - 1] == number: # SOL
deleteLeft(row, column)
delete_recursively(row, column - 1)
if row + 2 > len(chart):
pass
elif chart[row + 1][column] == number: # ALT
deleteDown(row, column)
delete_recursively(row + 1, column)
def slideDown():
number_of_line = len(chart)
for satir in range(0, number_of_line):
for eleman in chart[satir]:
if eleman == " ":
a = chart[satir].index(eleman)
chart[satir][a] = chart[satir - 1][a]
chart[satir - 1][a] = " "
return chart
def slideDown2():
number_of_line = len(chart)
for satir in range(1, number_of_line):
a = 0
for eleman in chart[satir]:
if eleman == " ":
chart[satir][a] = chart[satir - 1][a]
chart[satir - 1][a] = " "
a += 1
def slideLeft2(sutun):
for i in range(len(chart)):
chart[i][sutun] = chart[i][sutun+1]
chart[i].remove(chart[i][sutun+1])
def slideLeft(): # TRY EXCEPT
try:
donen = [] # Sütun Sayısı
for i in chart:
donen = [j for j in range(len(i))]
for j in donen:
sayac = 0
for k in range(len(chart)):
if chart[k][j] == " ":
sayac += 1
if sayac == len(chart):
slideLeft2(j)
except IndexError:
pass
def deleteRow():
sayar = 0
for satir in chart: # Boş satır silme
for eleman in satir:
if eleman == " ":
sayar += 1
if sayar == len(satir):
chart.remove(satir)
sayar = 0
score = 0
while True:
for i in chart: # SHOW
print(" ".join(i))
entry = input("Please enter a row and column number(There should be a space between the numbers):")
row = int(entry.split(" ")[0]) - 1
column = int(entry.split(" ")[1]) -1
if row+1 > len(chart) or column+1 > len(chart[row]):
print("Please enter a correct size!")
else:
number = chart[row][column]
if number == " ":
print("Please enter a correct size!")
else:
delete_recursively(row, column)
slideDown()
slideDown2()
slideDown2()
slideDown2()
slideDown2()
slideDown2()
slideLeft()
if number_of_deleted != 0: # SCORE
score += int(number)*int((fibonacci(number_of_deleted+1)))
else:
score += 0
number_of_deleted = 0
print("Your score is: {}".format(score))
for i in chart: # Boş satırları siler.
deleteRow()
bonus = 0
for satir in range(len(chart)):
for eleman in chart[satir]:
a = chart[satir].index(eleman)
if satir - 1 < 0:
pass
elif eleman == chart[satir-1][a] and eleman != " ":
bonus += 1
if satir+2 > len(chart):
pass
elif eleman == chart[satir+1][a] and eleman != " ":
bonus += 1
if a - 1 < 0:
pass
elif eleman == chart[satir][a-1] and eleman != " ":
bonus += 1
if a+2 > len(chart[satir]):
pass
elif eleman == chart[satir][a+1] and eleman != " ":
bonus += 1
if bonus == 0:
print("Game Over")
for i in chart:
print(" ".join(i))
sys.exit()
|
import sys
def fizz_buzz(line):
X, Y, n = tuple([int(i) for i in line.split(' ')])
output_seq = ['1']
for i in range(2, n + 1, 1):
result_str = ''
if i / X == i // X:
result_str = 'F'
if i / Y == i // Y:
result_str += 'B'
if not result_str:
result_str = str(i)
output_seq.append(result_str)
print(' '.join(output_seq))
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
if not test:
continue
fizz_buzz(test.rstrip())
|
"""
Useful decorators
"""
from functools import wraps
from utils.seed import Seed
def cascade(func):
"""
class method decorator, always returns the
object that called the method
"""
@wraps(func)
def wrapper(self, *args, **kwargs):
func(self, *args, **kwargs)
return self
return wrapper
def seeded(pos):
"""
Decorator:
Looks for the positional pos(int) or keyword name(str) argument and if
the argument is a list calls the function once for each item
This changes the function to always return void
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
valid = lambda val: (
val if isinstance(val, Seed)
else (
Seed(val) if isinstance(val, int)
else Seed()
)
)
if len(args) > pos:
args = list(args)
args[pos] = valid(args[pos])
elif 'seed' in kwargs:
kwargs['seed'] = valid(kwargs['seed'])
else:
kwargs['seed'] = Seed()
return func(*args, **kwargs)
return wrapper
return decorator
def allow_list(pos, name=None):
"""
Decorator:
Looks for the positional pos(int) or keyword name(str) argument and if
the argument is a list calls the function once for each item
This changes the function to always return void
"""
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
if len(args) > pos:
# args is normally an immutable tuple
args = list(args)
source = args
key = pos
elif name is not None and name in kwargs:
source = kwargs
key = name
else:
# The argument wasn't passed in .: original call
func(*args, **kwargs)
return
# Make sure we'll loop through a list of one index
if not isinstance(source[key], list):
source[key] = [source[key]]
for item in source[key]:
source[key] = item
func(*args, **kwargs)
return wrapper
return decorator
|
# numbers = range(1,4)
# products = {}
# for num1 in numbers:
# for num2 in numbers:
# products.update({num1*num2 : [(num1, num2)]})
# products = {1: [(1, 1)], 2: [(2, 1)], 3: [(3, 1)], 4: [(2, 2)], 6: [(3, 2)], 9: [(3, 3)]}
# products[1][len(products[1])-1] = "blue"
#print(products)
# test_list = [1, 2, 3, 4, 4]
# new_list = list(set(test_list))
# print(new_list)
|
def convert(number):
conversion = {3 : "Pling", 5 : "Plang", 7 : "Plong"}
code = ''.join([value for key, value in conversion.items() if number % key == 0])
if code:
return code
return str(number)
|
from random import shuffle
from random import randint
class Robot:
names = []
def __init__(self):
self.name = self.pick_name()
def reset(self):
self.name = self.pick_name()
return self.name
def __repr__(self):
return self.name
def pick_name(self):
first = self._pick_letter()
second = self._pick_letter()
third = self._pick_number()
fourth = self._pick_number()
fifth = self._pick_number()
name = first + second + third + fourth + fifth
if name in Robot.names:
name = self.pick_name()
Robot.names.append(name)
return name
def _pick_letter(self):
letters = letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
shuffle(letters)
return letters[0]
def _pick_number(self):
num = str(randint(0,10))
return num
robbie = Robot()
print(robbie)
print(robbie.reset())
print (Robot.names)
|
class Matrix(object):
def __init__(self, matrix_string):
self.matrix_string = matrix_string
splitted = self.matrix_string.splitlines()
self.numbers = [[int(num) for num in item] for item in [item.split() for item in splitted]]
def row(self, index):
return self.numbers[index-1].copy()
def column(self, index):
return [item[index-1] for item in self.numbers]
m = Matrix("1 2 3\n4 5 6\n7 8 9")
print(m.numbers)
print(m.row(2))
print(m.column(2))
test_row = m.row(2).append(4)
print(m.row(2))
print(m.numbers)
|
"""
An Adaption of Homework 10, Problem 1, Part 1 from Numerical Analysis, Spring 2016
The general least squares method:
(1) Create a 'Z' matrix --> a matrix which can be seen as transposed and concatenated lists of each value in a list of
independent variables such that the first column is x_i^0, the second column is x_i^1 etc.
all the way up to x_i^n, where n is the degree of the polynomial being fit
(2) Calculate 'A', a vector containing the coefficients used for the polynomial fit of the form:
a0 + a1*x + a2*x**2 + ... + an*x**n
A = [a0, a1, a2, ..., an ]
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as sci
import math
# x = [1.01, 1.27, 1.85, 2.38, 2.83, 3.13, 3.96, 4.91]
# y = [0.00, 0.19, 0.58, 0.96, 1.26, 1.47, 2.07, 2.75]
def z_matrix(degree, t):
Z = np.zeros((len(t), degree + 1))
for i in range(0, degree + 1):
for j in range(0, len(t)):
Z[j, i] = t[j]**i
return Z
def find_A(x, Y, degree, W = 'none'): # Find the matrix of coefficients which give desired fit
# if A is a matrix of coefficients ([a0, a1, ..., an]), then
# A = ([Z]^T*[Z])^-1*[Z]^T*Y
# With a weight matrix:
# A = ([Z]^T*W*[Z])^-1*[Z]^T*W*Y
# The weight matrix is a square n x n matrix (where n = len(x)) where the diagonals are the inverse of the standard
# deviation of the data point squared (1/(sigma_i ** 2))
Z = z_matrix(degree, x)
ZT = np.transpose(Z) # transposed z matrix
if isinstance(W, np.ndarray):
ZTW = np.dot(ZT, W)
ZTWZ = np.dot(ZTW, Z)
ZTWZinv = np.linalg.inv(ZTWZ)
ZTWZinvZT = np.dot(ZTWZinv, ZT)
ZTWZinvZTW = np.dot(ZTWZinvZT, W)
A = np.array(np.dot(ZTWZinvZTW, Y).tolist())
else:
ZTZ = np.dot(ZT, Z) # multiply ZT and Z
ZTZinv = np.linalg.inv(ZTZ) # inverse of ZTZ
ZTZinvZT = np.dot(ZTZinv, ZT) # multiply the inverse of Z transposed * Z by Z transposed
A = np.array(np.dot(ZTZinvZT, Y).tolist())
return A
def poly_eval(degree, x, A):
y = A[0]
for i in range(1, degree + 1):
y += A[i]*x**i
Sr = (y)
return y
def poly_fit(x, y, degree, weight='none'):
if isinstance(weight, np.ndarray):
A = find_A(x, y, degree, weight)
else:
A = find_A(x, y, degree)
y_val = np.zeros((len(x)))
St = 0
Sr = 0
mean = np.mean(y)
n = len(y)
for i in range(0, len(x)):
y_val[i] = poly_eval(degree, x[i], A)
Sr += (y[i] - (y_val[i]))**2
St += (y[i] - mean)**2
s = math.sqrt(Sr/(len(y) - 2))
x_square = [i**2 for i in x]
slope_error = s * np.sqrt(n/(n*sum(x_square) - (sum(x))**2))
intercept_error = s * np.sqrt(sum(x_square)/(n*sum(x_square) - (sum(x))**2))
R_squared = 1 - (Sr/St)
return y_val, R_squared, slope_error, intercept_error, A
|
# необходимо найти остаток от деления n-го числа Фибоначчи на m.
def fib():
f = input().split()
n, m = int(f[0]), int(f[1])
a = [0, 1, 1]
while a[-1] != 1 or a[-2] != 0:
a.append((a[-1] + a[-2]) % m)
circle = len(a) - 2
print(a[n % circle] % m)
fib()
|
from unittest import TestCase
def main() -> None:
x_coordinates: list[int] = []
y_coordinates: list[int] = []
for _ in range(int(input())):
x, y = input().split()
x_coordinates.append(int(x))
y_coordinates.append(int(y))
x1, y1, x2, y2 = count_rectangle(x_coordinates, y_coordinates)
print(f"{x1} {y1} {x2} {y2}")
def count_rectangle(x_coordinates: list[int], y_coordinates: list[int]) -> tuple[int, int, int, int]:
return min(x_coordinates), min(y_coordinates), max(x_coordinates), max(y_coordinates)
if __name__ == "__main__":
main()
class Tests(TestCase):
def test_example(self):
assert count_rectangle([1, 1, 5], [1, 10, 5]) == ((1, 1), (5, 10))
|
from collections import defaultdict
from unittest import TestCase
def main() -> None:
word = input()
letters_counts = count_letters(word)
for letter, count in sorted(letters_counts.items()):
print(f"{letter}: {count}")
def count_letters(word: str) -> dict[str, int]:
result = defaultdict(int)
word_len = len(word)
for i in range(word_len):
result[word[i]] += (word_len - i) * (i + 1)
return result
if __name__ == "__main__":
main()
class Tests(TestCase):
def test_example_1(self):
assert count_letters("hello") == {"e": 8, "h": 5, "l": 17, "o": 5}
def test_example_2(self):
assert count_letters("abacaba") == {"a": 44, "b": 24, "c": 16}
|
def rotated_array_search(input_list, number):
"""
Find the index by searching in a rotated sorted array
Args:
input_list(array), number(int): Input array to search and the target
Returns:
int: Index or -1
"""
#if input_list is None:
#print("the list is empty")
lower_bound = 0
upper_bound = len(input_list)-1
while (lower_bound <= upper_bound):
mid=(lower_bound + upper_bound)//2
if input_list[mid]==number:
#print(mid)
return mid
if input_list[lower_bound] <= input_list[mid]:#left half of the list is sorted
if input_list[lower_bound] <= number and input_list[mid] > number:#searching in the left half
upper_bound = mid-1
else: #searching in the right half
lower_bound = mid+1
else:#right half of the list is sorted
if input_list[mid] <= number and input_list[upper_bound] >= number:#searching in the right half
lower_bound = mid+1
else:##searching in the left half
upper_bound = mid-1
return -1
def linear_search(input_list, number):
for index, element in enumerate(input_list):
if element == number:
return index
return -1
def test_function(test_case):
if not test_case:
print("the list is empty")
return None
else:
input_list = test_case[0]
number = test_case[1]
if linear_search(input_list, number) == rotated_array_search(input_list, number):
print("Pass")
else:
print("Fail")
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6])#pass
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])#pass
test_function([[6, 7, 8, 1, 2, 3, 4], 8])#pass
test_function([[6, 7, 8, 1, 2, 3, 4], 1])#pass
test_function([[6, 7, 8, 1, 2, 3, 4], 10])#pass
test_function([])#list is empty
test_function([[1, 2, 3, 4, 6, 7, 8 ], 4])#pass
|
print("Enter the radius of the circle: ")
radius=int(input())
units=input("units of measurement : ")
py=3.142
Area=py*(radius*radius)
Circumfrance = (2*py*radius)
print(f"Area of the circle is {Area} squared {units}")
print( f"while its circumference is {Circumfrance} {units}")
|
dictOfbirthday = {'Tilek':'11.07','Makhmud':'09.10','Jetigen':'04.07','Meka':'28.11'}
name = input("who birthday do you want to know: ")
data = dictOfbirthday[name.capitalize()]
print(f'{name} has birthday on {data} ')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/12/23 16:07
# @Author : lingxiangxiang
# @File : demonIfWhileFor.py
# python缩进
# main:
# print("hello")
# print("hello world")
# c main(param){}
# java main(param){}
# if 判断条件:
# 执行语句
# elif 判断条件:
# 执行语句
# else:
# 执行语句
# while 判断条件:
# 执行语句
a = 100
while a>1:
print(a)
a -=1
if a == 50:
break#退出循环
if a == 55:
print("555555555555555")
continue
# break 跳出循环
# continue 进入下一次循环
# for item in sequence:
# 执行语句
l = ['a', 'b', 'c', 'd', 'e']
print(l[0:5])# 大于等于0 小于5 0<=a<5
print(l[0:-1])# 大于等于0 小于5 0<=a<5
print(l[:])# 大于等于0 小于5 0<=a<5
for x, y in enumerate(l):
print(x, y)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 23 18:36:29 2021
@author: Evgeniya Vorontsova
LC Problem 168 Excel Sheet Column Title
Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: columnNumber = 1
Output: "A"
Example 2:
Input: columnNumber = 28
Output: "AB"
Example 3:
Input: columnNumber = 701
Output: "ZY"
Example 4:
Input: columnNumber = 2147483647
Output: "FXSHRXW"
Constraints:
1 <= columnNumber <= 2^31 - 1
"""
class Solution:
def convertToTitle(self, columnNumber: int) -> str:
# Let's translate the number to 26-digits number
# system. One little problem: it's not a real
# 26-digits system, because this is no 0.
# So, we need to substract 1 in that case
ost = columnNumber
if ost == 1:
return 'A'
rez = ''
l = []
base = 26
while ost > 0:
digit = ost % base
ost = ost // base
if digit == 0:
l.append('Z')
ost = ost - 1
else:
l.append(chr(digit + 64))
#print(digit, ost, l)
for i in l[::-1]:
rez = rez + i
return rez
class_instance = Solution()
rez = Solution.convertToTitle(class_instance, 51)
print(rez)
|
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 9 19:28:23 2021
@author: Evgeniya Vorontsova
LC Problem 202 Happy Number
Write an algorithm to determine if a number n is happy.
A happy number is a number defined by the following process:
Starting with any positive integer, replace the number by the sum of the
squares of its digits.
Repeat the process until the number equals 1 (where it will stay),
or it loops endlessly in a cycle which does not include 1.
Those numbers for which this process ends in 1 are happy.
Return true if n is a happy number, and false if not.
Example 1:
Input: n = 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Example 2:
Input: n = 2
Output: false
Constraints:
1 <= n <= 2^31 - 1
"""
class Solution:
def isHappy(self, n: int) -> bool:
# We need to keep all previous numbers in a hash map, because
# they could be repeated, and in that case we need to break a cycle
str_n = str(n)
hash_map = {}
sum_sq = 0
while sum_sq != 1:
sum_sq = 0
for i in str_n:
int_i = int(i)
sum_sq = sum_sq + int_i*int_i
if n in hash_map:
break
else:
hash_map[n] = sum_sq
n = sum_sq
str_n = str(sum_sq)
#print(sum_sq, str_n, hash_map)
if sum_sq == 1:
return True
else:
return False
n = 7
class_instance = Solution()
rez = Solution.isHappy(class_instance, n)
print(rez)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 6 23:30:02 2021
@author: Evgeniya Vorontsova
LC Problem 83 Remove Duplicates from Sorted List
Given the head of a sorted linked list, delete all duplicates such that
each element appears only once. Return the linked list sorted as well.
Example 1:
Input: head = [1,1,2]
Output: [1,2]
Example 2:
Input: head = [1,1,2,3,3]
Output: [1,2,3]
Constraints:
The number of nodes in the list is in the range [0, 300].
-100 <= Node.val <= 100
The list is guaranteed to be sorted in ascending order.
"""
from typing import Optional
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def print_list(self):
p = self
while True:
print(p.val, end='')
p = p.next
if not p:
break
else:
print("--> ", end='')
print()
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
p_list = head
p_l_prev = None
while p_list:
if p_l_prev:
if p_l_prev.val == p_list.val:
p_l_prev.next = p_list.next
else:
p_l_prev = p_list
else:
p_l_prev = p_list
p_list = p_list.next
#head.print_list()
return head
# Tests
a = ListNode(1)
b = ListNode(1)
c = ListNode(2)
d = ListNode(2)
a.next = b
b.next = c
c.next = d
print("List: ")
a.print_list()
class_instance = Solution()
rez = Solution.deleteDuplicates(class_instance, a)
print("After processing:")
if rez:
rez.print_list()
|
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 22 18:59:46 2021
@author: Evgeniya Vorontsova
LC Problem 125 Valid Palindrome
Given a string s, determine if it is a palindrome, considering only
alphanumeric characters and ignoring cases.
Example 1:
Input: s = "A man, a plan, a canal: Panama"
Output: true
Explanation: "amanaplanacanalpanama" is a palindrome.
Example 2:
Input: s = "race a car"
Output: false
Explanation: "raceacar" is not a palindrome.
Constraints:
1 <= s.length <= 2 * 10^5
s consists only of printable ASCII characters.
"""
import string
class Solution:
# Two-pointers approach
def isPalindrome(self, s: str) -> bool:
len_s = len(s)
if len_s == 1:
return True
p_first = 0
p_last = len_s - 1
while p_first < p_last:
s_i = s[p_first]
while not s_i.isalnum() and p_first < p_last:
p_first = p_first + 1
s_i = s[p_first]
s_j = s[p_last]
while not s_j.isalnum() and p_last > p_first:
p_last = p_last - 1
s_j = s[p_last]
if s_i.lower() != s_j.lower():
return False
p_first = p_first + 1
p_last = p_last - 1
return True
s = "A man, a plan, a canal: Panama"
class_instance = Solution()
rez = Solution.isPalindrome(class_instance, s)
print(rez)
|
import matplotlib.pyplot as plt
x1 = [1,2,3,4]
y1 = [3,6,7,8]
plt.plot(x1,y1,label = "line 1", color = "green",\
linestyle = "dashed", marker="o", \
markerfacecolor="blue", markersize=12)
plt.ylim(1,8)
plt.xlim(1,8)
plt.title("Stylised Line Graph")
plt.legend()
plt.show()
|
from random import randint
count = 0
def add_quiz(num1, num2):
answer = int(input("What is " + str(num1) + " + " + str(num2) + "? : "))
if answer == num1 + num2:
print("You guessed it right! Good Job!")
return 1
else:
print(str(num1) + " + " + str(num2) + "should be " + str(num1 + num2) + "! Wrong Answer")
return 0
def sub_quiz(num1, num2):
answer = int(input("What is " + str(num1) + " - " + str(num2) + "? : "))
if answer == num1 - num2:
print("You guessed it right! Good Job!")
return 1
else:
print(str(num1) + " - " + str(num2) + "should be " + str(num1 + num2) + "! Wrong Answer")
return 0
def mul_quiz(num1, num2):
answer = int(input("What is" + str(num1) + "*" + str(num2) + "? : "))
if answer == num1 * num2:
print("You guessed it right! Good Job!")
return 1
else:
print(str(num1) + " * " + str(num2) + " should be " + str(num1 + num2) + "! Wrong Answer")
return 0
def div_quiz(num1, num2):
answer = int(input("What is " + str(num1) + " / " + str(num2) + "? : "))
if answer == num1 / num2:
print("You guessed it right! Good Job!")
return 1
else:
print(str(num1) + " / " + str(num2) + " should be " + str(num1 / num2) + "! Wrong Answer")
return 0
for i in range(10):
num1 = randint(0,100)
num2 = randint(0,100)
op = ["+", "-", "/", "*"]
sign = op[randint(0,3)]
if sign == "+":
count = count + add_quiz(num1, num2)
elif sign == "-":
count += sub_quiz(num1, num2)
elif sign == "*":
num1 = num1//10
num2 = num2 // 10
count += mul_quiz(num1, num2)
elif sign == "/":
num2 = num2 // 10
count += div_quiz(num1, num2)
print("You got", count, "answers right out of", 10)
|
from random import randint
number = randint(0,100)
guess = 10000
while guess != number:
number = randint(0,100)
guess = int(input("Guess the number : "))
if guess > number:
print("You've guessed too high!")
elif guess < number:
print("You've guessed too low!")
else:
print("You guessed it Right!")
|
def prime(num):
count = 0
for i in range(1,num): #[1,2,3,4,5,6,7,8,.......,num-1]
if num % i == 0:
count+=1
if count == 1:
return num
for i in range(100): #"Banana"
if(prime(i)):
print(i)
|
name = input("Enter Full Name\n")
name.strip()
name = " " + name
abbr = ""
for i in range(len(name)):
if name[i] == " ":
abbr += name[i+1].upper() + ". "
print(abbr)
|
print("Enter two numbers whose greatest common divisor is to be found")
num1 = int(input())
num2 = int(input())
gcd = 1
k = 2
while(k <= min(num1, num2)):
if num1 % k == 0 and num2 % k == 0:
gcd == k
k+=1
print("The GCD of the two numbers is", gcd)
|
#!/usr/bin/python
__author__ = "Fabian Schilling"
__email__ = "[email protected]"
import sys
# conver int to str under certain base
def int2str(num, base):
(d, m) = divmod(num, base)
if d > 0:
return int2str(d, base) + str(m)
return str(m)
# convert from base 7 to (0, 1, 2, 5, 6, 8, 9) system
def convert_sys(num_str):
ls = list(num_str)
for i, dig in enumerate(ls):
if dig == '3':
ls[i] = '5'
elif dig == '4':
ls[i] = '6'
elif dig == '5':
ls[i] = '8'
elif dig == '6':
ls[i] = '9'
return ''.join(ls)
nums = [int(x) for x in sys.stdin.readlines()]
for num in nums:
num_str = list(convert_sys(int2str(num, 7))[::-1])
# turn upside down, i.e. 6 -> 9 and 9 -> 6
for i, char in enumerate(num_str):
if char == '6':
num_str[i] = '9'
elif char == '9':
num_str[i] = '6'
print(''.join(num_str))
|
# binary numbers
# 1=0b0001
# 2=0b0010
# hexadecimal
# 1=0o001
# 2=0o002
print(0o17)
print(0x11)
print(123e6)
# operatii aritmetice
# #x/y impartirea cu virgula
number1 = 3
number2 = 4
print('impartire 3/4:', number1 / number2)
print('floordiv4/3', number1 // number2) # partea intreaga din nr respectiv care rezulta la impartire
print('remander 4%3', number1 % number2) # restul impartirii
print('negative 3:', -number1)
print('zero:', number1 + number2)
print('3 to the power of 4:', number1 ** number2)
a = 3
b = 4
c = 5
result = (-b + pow((b ** 2) - 4 * a * c, 1 / 2)) / (2 * a)
print(result)
number4 = 0.75
number5 = 1.0 + 2.3j # j e pt nr complexe nu conteaza daca e j mare sau j mic
print(type(number4))
print(type(result))
print(type(number5))
# string:
# orice tip de ghilimea e suportata inclusiv seturi de 3 """
string5 = 'hello world'
string5 = "hello world"
string5 = '''hello world'''
string5 = " " "hello world"""
print(string5)
string5 = u'hello \nworld'
string5 = r'hello \n world' # caracterele nu sunt interpretate pt caractere speciale deci \n nu mai e interperetat ca si linie noua
print(string5)
string5 = f'hello : {string5}'
print(string5) # string formatabil , daca il luam si il printam nu se vede nici o diferenta
# daca pune{} in interior putem sa dam obiecte printate
# ctrl+alt +l pt aranjare a codului automata
result = string5[4]
print(string5)
result = string5[-3]
result = string5[
4:7] # interval inchis in stg si deschis in dreapta deci nu include caracterul de la index 7 nu e cuprins
# totul pana la caracter cu index 7
print('citim linia care trebuie?', result)
result = string5[4:7:1] # ultimul e stepul/hop , step de 1 inseamna fiecare caracter 2 din 2 in 2
print(result)
restult = string5[-2:-6:-2]
print(result)
# citirea se face doar in ordine de la stg la dr. deci un interval 9:4 nu exista returneaza 0
## String interpretation:
string5 = u'Hello\nWorld'
print('unicode string:', string5)
string5 = r'Hello\nWorld'
print('Row string:', string5)
string5 = f'Hello World: {string5}'
print('Formatted string:', string5)
#dot notation for strings:
print('string actions', dir(result)) # dir trebuie printat altfel nu vedem nimic
#functia de lower se acceseaza din obiect folosind .
print(result.upper()) #toate caract in litere mari
print(result.capitalize()) #primu caract litera mare, restu litere mici
#join are nevoie de o lista de obiecte sau de un ob iterabil
result= result + '{}'
print(result.format('silvia'))
print(result.format(6, 'silvia'))
#metoda -trebuie sa-i dam un argument ca sa functioneze
print(result.find('h'))
print(result.center(20, '#'))
# dot notation for ints:
print(number1.__add__(number2))
print((3).__add__(4))
print(number1.__mul__(number2)) #multiply
print(number1.__truediv__(number2)) #division
#obiectele au diverse actiuni-metode si fctii e pot fi apelate cu .dot notaions
print('power of:', number1.__pow__(number2)) #ridicare la putere
|
def crypt_decrypt(string, key):
result = []
for letter in string:
result.append(chr(ord(letter).__xor__(key)))
return ''.join(result)
def is_prime(number):
for i in range(2, number // 2 + 2):
if not number % i:
return False
return True
def generate_primes(limit):
result = []
for i in range(limit):
if is_prime(i):
result.append(i)
return result
|
'''from tkinter import *
mv=Tk()
canvas=Canvas(mv, bg="black", height=900, width=1400)
canvas.pack()
photo=PhotoImage(file="hotel12.png")
canvas.create_image(690,350, image=photo)
mainloop()'''
'''import tkinter
from tkinter import *
root=Tk()
root.geometry("600x600")
# def enterd(event):
# btn.config(bg="red")
#
# def left(event):
# btn.config(bg="white")
f=Frame(root,background='black')
f.pack(expand=True,fill="both")
f1=Frame(root,background='yellow',height=50,width=50)
f1.pack(expand=True,fill="both")
f2=Frame(root,background='red',height=50,width=50)
f2.pack(expand=True)
# btn=Button(f2,text="kkkkkkkkkkkkkkkkkkk")
# btn.pack()
# btn.bind("<Enter>",enterd)
# btn.bind("<Leave>",left)
mainloop()'''
'''try:
# Python2
import Tkinter as tk
except ImportError:
# Python3
import tkinter as tk
root = tk.Tk()
# use opacity alpha values from 0.0 to 1.0
# opacity/tranparency applies to image and frame
root.wm_attributes('-alpha', 0.7)
# use a GIF image you have in the working directory
# or give full path
photo = tk.PhotoImage(file="hotel12.png")
tk.Label(root, image=photo).pack()
root.mainloop()'''
#jpg to png
from PIL import Image
img = Image.open('order.jpg')
img = img.convert("RGBA")
datas = img.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
newData.append(item)
img.putdata(newData)
img.save("order1.png", "PNG")
# import tkinter as tk
# from tkinter import *
# root=Tk()
# def key_pressed(event):
# if event.char==" ":
# print("mjmahi")
# print(event.char)
# root.bind("<Key>",key_pressed)
# root.mainloop()
'''from tkinter import *
top = Tk()
def list(event):
Lb = Listbox(top)
Lb.insert(1, 'Python')
Lb.insert(2, 'Java')
Lb.insert(3, 'C++')
Lb.insert(4, 'Any other')
Lb.pack()
button = Button(top, text='Stop', width=25, command=list)
button.pack()
button.bind("<Enter>",list)
top.mainloop()'''
#------------------------------------------------menubar_________________________________________________________
'''from tkinter import *
from tkinter import messagebox
import tkinter
top = Tk()
global mb
mb = Menubutton(top, text="condiments", relief=RAISED)
mb.pack()
#mb.bind("<Enter>",list)
#def list(event):
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu
mayoVar = IntVar()
ketchVar = IntVar()
mb.menu.add_checkbutton ( label="mayo",
variable=mayoVar )
mb.menu.add_checkbutton ( label="ketchup",
variable=ketchVar )
mb.menu.add_checkbutton.bin
top.mainloop()'''''
#-----------------------------------------------------------------------------------------------------------------
'''from tkinter import *
root = Tk()
def callback(event):
print("clicked at", event.x, event.y)
frame = Frame(root, width=100, height=100)
frame.bind("<Button-1>", callback)
frame.pack()
root.mainloop()'''
#------------------------------------- print key----------------------
'''from tkinter import *
root = Tk()
def key(event):
print("pressed", repr(event.char))
def callback(event):
frame.focus_set()
print("clicked at", event.x, event.y)
frame = Frame(root, width=100, height=100)
frame.bind("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()
root.mainloop()'''
#-------------------------------------------------------------------------
'''from tkinter import *
root = Tk()
def callback():
print("called the callback!")
filename = PhotoImage(file="hotel12.png")
background_label = Label(root, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
# create a toolbar
toolbar = Frame(root)
toolbar.config(bg="darkblue")
b = Button(toolbar, text="new", width=6, command=callback,bg="darkblue",relief="flat",fg="white")
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback, font=("Hargus-Normal", 17))
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback)
b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)
b = Button(toolbar, text="open", width=6, command=callback)
b.pack(side=LEFT, padx=2, pady=2)
toolbar.place(x=100,y=100)
mainloop()'''
#-----------------------------------------------------------------------------------------------------------
'''import tkinter as tk
from tkinter import *
root = Tk()
frame1 = Frame(root)
frame1.config(bg="red")
l1=Label(frame1,text=" Enter Below Details- ",font=("Medusa",20),bg="red")
l1.pack(side=TOP,padx=2,pady=2)
l2=Label(frame1,text="",font=("Medusa",10),bg="red")
l2.pack(side=TOP,padx=2,pady=2)
l4=Label(frame1,text="Coustomer Name:-",font=("Times new roman",10),bg="red")
l4.place(x=20,y=50)
e4=Entry(frame1,bd=3).place(x=180,y=50)
l2=Label(frame1,text="",font=("Medusa",10),bg="red")
l2.pack(side=TOP,padx=2,pady=2)
l5=Label(frame1,text="Aadhar card No:-",font=("Times new roman",10),bg="red")
l5.place(x=20,y=100)
e5=Entry(frame1,bd=3).place(x=180,y=100)
l2=Label(frame1,text="",font=("Medusa",20),bg="red")
l2.pack(side=TOP,padx=2,pady=2)
l6=Label(frame1,text="Address:-",font=("Times new roman",10),bg="red")
l6.place(x=20,y=150)
e6=Entry(frame1,bd=3).place(x=180,y=150)
l2=Label(frame1,text="",font=("Medusa",20),bg="red")
l2.pack(side=TOP,padx=2,pady=2)
l7=Label(frame1,text="Contact:-",font=("Times new roman",10),bg="red")
l7.place(x=20,y=200)
e7=Entry(frame1).place(x=180,y=200)
l2=Label(frame1,text="",font=("Medusa",20),bg="red")
l2.pack(side=TOP,padx=2,pady=2)
Button(frame1,text="SAVE", font=("Medusa", 10), bg="red").place(x=200,y=250)
l2=Label(frame1,text="",font=("Medusa",60),bg="red")
l2.pack(side=TOP,padx=2,pady=2)
frame1.pack()
root.mainloop()'''
#
#
# code written by shubhank
# from tkinter import *
# from tkinter import ttk
# import time
# import datetime
# from PIL import ImageTk, Image
# import os
# import sqlite3
# from tkinter import messagebox
#
# root=Tk()
# root.title("mj")
# root.geometry("1028x780")
#
#
#
# def reserve():
# b_frame = Frame(root, height=420, width=1080, bg='gray89')
# path = "newbg6lf.jpg"
# img = ImageTk.PhotoImage(Image.open(path))
# label = Label(b_frame, image=img, height=420, width=1080)
# label.image = img
# label.place(x=0, y=0)
# b_frame.config(bg="black")
#
# hline = Frame(b_frame,height=10,width=960,bg='cyan4')
# hline.place(x=122,y=27)
# vline = Frame(b_frame, height=400, width=7, bg='lightsteelblue3')
# vline.place(x=700, y=0)
#
# Label(b_frame, text='Personal Information', font='msserif 15', bg='gray93').place(x=225, y=0)
#
# fnf = Frame(b_frame, height=1, width=1)
# fn = Entry(fnf)
#
# mnf = Frame(b_frame, height=1, width=1)
# mn = Entry(mnf)
#
# lnf = Frame(b_frame, height=1, width=1)
# ln = Entry(lnf)
#
# fn.insert(0, 'First Name *')
# mn.insert(0, 'Middle Name')
# ln.insert(0, 'Last Name *')
#
# def on_entry_click1(event):
# if fn.get() == 'First Name *':
# fn.delete(0, END)
# fn.insert(0, '')
#
# def on_entry_click2(event):
# if mn.get() == 'Middle Name':
# mn.delete(0, END)
# mn.insert(0, '')
#
# def on_entry_click3(event):
# if ln.get() == 'Last Name *':
# ln.delete(0, END)
# ln.insert(0, '')
#
# def on_exit1(event):
# if fn.get() == '':
# fn.insert(0, 'First Name *')
#
# def on_exit2(event):
# if mn.get() == '':
# mn.insert(0, 'Middle Name')
#
# def on_exit3(event):
# if ln.get() == '':
# ln.insert(0, 'Last Name *')
#
# fn.bind('<FocusIn>', on_entry_click1)
# mn.bind('<FocusIn>', on_entry_click2)
# ln.bind('<FocusIn>', on_entry_click3)
# fn.bind('<FocusOut>', on_exit1)
# mn.bind('<FocusOut>', on_exit2)
# ln.bind('<FocusOut>', on_exit3)
#
# fn.pack(ipady=4, ipadx=15)
# mn.pack(ipady=4, ipadx=15)
# ln.pack(ipady=4, ipadx=15)
# fnf.place(x=20, y=42)
# mnf.place(x=235, y=42)
# lnf.place(x=450, y=42)
#
# Label(b_frame, text='Contact Information', font='msserif 15', bg='gray93').place(x=225, y=90)
#
# cnf = Frame(b_frame, height=1, width=1)
# cn = Entry(cnf)
#
# emf = Frame(b_frame, height=1, width=1)
# em = Entry(emf)
#
# adf = Frame(b_frame, height=1, width=1)
# ad = Entry(adf)
#
# cn.insert(0, 'Contact Number *')
# em.insert(0, 'Email *')
# ad.insert(0, "Guest's Address *")
#
# def on_entry_click4(event):
# if cn.get() == 'Contact Number *':
# cn.delete(0, END)
# cn.insert(0, '')
#
# def on_entry_click5(event):
# if em.get() == 'Email *':
# em.delete(0, END)
# em.insert(0, '')
#
# def on_entry_click6(event):
# if ad.get() == "Guest's Address *":
# ad.delete(0, END)
# ad.insert(0, '')
#
# def on_exit4(event):
# if cn.get() == '':
# cn.insert(0, 'Contact Number *')
#
# def on_exit5(event):
# if em.get() == '':
# em.insert(0, 'Email *')
#
# def on_exit6(event):
# if ad.get() == '':
# ad.insert(0, "Guest's Address *")
#
# cn.bind('<FocusIn>', on_entry_click4)
# em.bind('<FocusIn>', on_entry_click5)
# ad.bind('<FocusIn>', on_entry_click6)
# cn.bind('<FocusOut>', on_exit4)
# em.bind('<FocusOut>', on_exit5)
# ad.bind('<FocusOut>', on_exit6)
#
# cn.pack(ipady=4, ipadx=15)
# em.pack(ipady=4, ipadx=15)
# ad.pack(ipady=4, ipadx=15)
# cnf.place(x=20, y=130)
# emf.place(x=235, y=130)
# adf.place(x=450, y=130)
# # l = Label(b_frame,text='Please Enter The Unique Payment ID',font='msserif 15',bg='cyan4',fg='white')
# # l.place(x=245,y=0)
#
# Label(b_frame, text='Reservation Information', font='msserif 15', bg='gray93').place(x=210, y=175)
#
# nocf = Frame(b_frame, height=1, width=1)
# noc = Entry(nocf)
#
# noaf = Frame(b_frame, height=1, width=1)
# noa = Entry(noaf)
#
# nodf = Frame(b_frame, height=1, width=1)
# nod = Entry(nodf)
#
# noc.insert(0, 'Number of Children *')
# noa.insert(0, 'Number of Adults *')
# nod.insert(0, 'Number of Days of Stay *')
#
# def on_entry_click7(event):
# if noc.get() == 'Number of Children *':
# noc.delete(0, END)
# noc.insert(0, '')
#
# def on_entry_click8(event):
# if noa.get() == 'Number of Adults *':
# noa.delete(0, END)
# noa.insert(0, '')
#
# def on_entry_click9(event):
# if nod.get() == 'Number of Days of Stay *':
# nod.delete(0, END)
# nod.insert(0, '')
#
# def on_exit7(event):
# if noc.get() == '':
# noc.insert(0, 'Number of Children *')
#
# def on_exit8(event):
# if noa.get() == '':
# noa.insert(0, 'Number of Adults *')
#
# def on_exit9(event):
# if nod.get() == '':
# nod.insert(0, 'Number of Days of Stay *')
#
# noc.bind('<FocusIn>', on_entry_click7)
# noa.bind('<FocusIn>', on_entry_click8)
# nod.bind('<FocusIn>', on_entry_click9)
# noc.bind('<FocusOut>', on_exit7)
# noa.bind('<FocusOut>', on_exit8)
# nod.bind('<FocusOut>', on_exit9)
#
# noc.pack(ipady=4, ipadx=15)
# noa.pack(ipady=4, ipadx=15)
# nod.pack(ipady=4, ipadx=15)
# nocf.place(x=20, y=220)
# noaf.place(x=235, y=220)
# nodf.place(x=450, y=220)
#
# roomnf = Frame(b_frame, height=1, width=1)
# roomn = Entry(roomnf)
# roomn.insert(0, 'Enter Room Number *')
#
# def on_entry_click10(event):
# if roomn.get() == 'Enter Room Number *':
# roomn.delete(0, END)
# roomn.insert(0, '')
#
# def on_exit10(event):
# if roomn.get() == '':
# roomn.insert(0, 'Enter Room Number *')
#
# roomn.bind('<FocusIn>', on_entry_click10)
# roomn.bind('<FocusOut>', on_exit10)
# roomn.pack(ipady=4, ipadx=15)
# roomnf.place(x=20, y=270)
#
# pmethod = IntVar()
#
# def booking():
# if fn.get() == 'First Name' or ln.get() == 'Last Name' or cn.get() == 'Contact Number *' or em.get() == 'Email' or ad.get() == "Guest's Address" or noc.get() == 'Number of Children' or noa.get() == 'Number of Adults' or nod.get() == 'Number of Days of Stay' or roomn.get() == 'Enter Room Number':
# messagebox.showinfo('Incomplete', 'Fill All the Fields marked by *')
# elif fn.get() == '' or ln.get() == '' or cn.get() == '' or em.get() == '' or ad.get() == "" or noc.get() == '' or noa.get() == '' or nod.get() == '' or roomn.get() == '':
# messagebox.showinfo('Incomplete', 'Fill All the Fields marked by *')
# # cur.execute("create table if not exists paymentsf(id number primary key,f_name varchar,l_name varchar,c_number varchar,email varchar , r_n number ,day varchar,month varchar,year varchar,time varchar , method varchar)")
#
# Res = Button(b_frame, text='Reserve', bg='white', fg='cyan4', font='timenewroman 11', activebackground='green',command=booking).place(x=235, y=270)
# unres = Button(b_frame, text='Unreserve', bg='white', fg='cyan4', font='timenewroman 11',activebackground='green').place(x=327, y=270)
# b_frame.place(x=0, y=120 + 6 + 20 + 60 + 11)
# b_frame.pack_propagate(False)
# b_frame.tkraise()
#
#
# Button(text="press",command=reserve).pack()
#
# mainloop()
#--HOTEL DEMO-----------------------------------------------------------------H
# code written by shubhank
|
import random
from state import *
class Searcher:
""" A class for objects that perform random state-space
search on an Eight Puzzle.
This will also be used as a superclass of classes for
other state-space search algorithms.
"""
def __init__(self, init_state, depth_limit):
'''constructs a new Searcher object'''
self.states = [init_state]
self.num_tested = 0
self.depth_limit = depth_limit
def should_add(self, state):
'''takes a State object called state and returns True if the called
Searcher should add state to its list of untested states, and False
otherwise.
'''
if (self.depth_limit != -1 and state.num_moves > self.depth_limit):
return False
if state.creates_cycle():
return False
return True
def add_state(self, new_state):
'''adds takes a single State object called new_state and adds it to the
Searcher‘s list of untested states
'''
self.states.append(new_state)
def add_states(self, new_states):
'''takes a list State objects called new_states, and that processes
the elements of new_states one at a time
'''
for s in new_states:
if self.should_add(s):
self.add_state(s)
def next_state(self):
""" chooses the next state to be tested from the list of
untested states, removing it from the list and returning it
"""
s = random.choice(self.states)
self.states.remove(s)
return s
def find_solution(self):
'''performs a full random state-space search, stopping when the
goal state is found or when the Searcher runs out of untested
states.
'''
while self.states != []:
s = self.next_state()
self.num_tested += 1
if s.is_goal():
return s
else:
self.add_states(s.generate_successors())
return None
def __repr__(self):
""" returns a string representation of the Searcher object
referred to by self.
"""
# You should *NOT* change this method.
s = str(len(self.states)) + ' untested, '
s += str(self.num_tested) + ' tested, '
if self.depth_limit == -1:
s += 'no depth limit'
else:
s += 'depth limit = ' + str(self.depth_limit)
return s
######## Searchers ######
class BFSearcher(Searcher):
'''a subclass of the Searcher, BFS performs breadth-first
search instead of random search
'''
def next_state(self):
'''overrides the next_state method that is inherited from Searcher.
this version of next_state follows FIFO ordering,
choosing the state that has been in the list the longest.
'''
s = self.states[0]
self.states.remove(s)
return s
class DFSearcher(Searcher):
'''a subclass of the Searcher, DFS performs depth-first
search instead of random search
'''
def next_state(self):
'''overrides the next_state method that is inherited from Searcher.
this version of next_state follows LIFO ordering,
choosing the state that has been in the list the shortest.
'''
s = self.states[-1]
self.states.remove(s)
return s
class GreedySearcher(Searcher):
'''a subclass of the Searcher, GreedySearcher performs greedy
search instead of random search using a heuristic
'''
def priority(self, state):
'''takes a State object called state, and that computes and
returns the priority of that state
'''
if self.heuristic == 1:
pri = -1 * (state.board.sum_dis())
elif self.heuristic == 2:
pri = -1 * (state.board.sum_dis() + state.board.find_min_dis())
else:
pri = -1 * state.board.num_misplaced()
return pri
def __init__(self, init_state, heuristic, depth_limit):
""" constructor for a GreedySearcher object
inputs:
* init_state - a State object for the initial state
* heuristic - an integer specifying which heuristic
function should be used when computing the priority
of a state
* depth_limit - the depth limit of the searcher
"""
self.heuristic = heuristic
self.states = [[self.priority(init_state), init_state]]
self.num_tested = 0
self.depth_limit = depth_limit
def add_state(self, state):
'''overrides the add_state method that is inherited from Searcher.
adds a sublist that is a [priority, state] pair
'''
self.states.append([self.priority(state), state])
def next_state(self):
'''overrides the next_state method that is inherited from Searcher.
this chooses one of the states with the highest priority.
'''
s = max(self.states)
self.states.remove(s)
s = s[1]
return s
class AStarSearcher(GreedySearcher):
'''a subclass of the GreedySearcher, AStarSearcher performs
search instead of random search using a heuristic
'''
def priority(self, state):
'''overrides priority method in GreedySearcher ,takes a State
object called state, and that computes and
returns the priority of that state
'''
if self.heuristic == 1:
pri = -1 * (state.board.sum_dis() + state.num_moves)
elif self.heuristic == 2:
pri = -1 * (state.board.sum_dis() + state.num_moves + state.board.find_min_dis())
else:
pri = -1 * (state.board.num_misplaced() + state.num_moves)
return pri
|
# Python program to print positive Numbers in a List
list1 = [12, -7, 5, 64, -14]
list2 = [12, 14, -95, 3]
for no in list1:
if no >= 0:
print(no, end = " ")
print()
for no in list2:
if no >= 0:
print(no, end = " ")
|
from shapely.geometry import Point
class Image:
"""
A Class representing an image object as given in input data
"""
def __init__(self, row):
"""
Constructor for class Image, parsing raw feature and validating fields
:param feature: feature data from geojson file
"""
img_row = row.rstrip('\n')
img_row = img_row.split(",")
if len(img_row) != 7:
raise Exception("Img row invalid")
self.name = img_row[0]
self.point = Point((float(img_row[2]), float(img_row[1])))
self.z = img_row[3]
self.yaw = img_row[4]
self.pitch = img_row[5]
self.roll = img_row[6]
self.polygon = None
def dict_repr(self):
"""
Function to return a dictionary representation of the current object
:return: Dictionary representing obj
"""
return {"name": self.name,
"point": [self.point.x, self.point.y],
"z": self.z,
"yaw": self.yaw,
"pitch": self.pitch,
"roll": self.roll,
"polygon index": self.polygon.index if self.polygon else None}
|
import sqlite3
# Database
class DatabaseLogic():
# Constructor
def __init__(self, database):
# Database
self.database = database
# Connection and cursor
self.con = sqlite3.connect(self.database)
self.cursor = self.con.cursor()
def checkUser(self, username):
"""this function checks that the username
exists in the database"""
#cur.execute("FROM ")
def addUser(self, username, password):
pass
def deleteUser(self, username):
pass
def getPassword(self, username):
pass
def updateUsername(self, username, newUsername):
pass
def updatePassword(self, username, newPassword):
pass
def addProduct(self, productName, productID, productPrice):
pass
def deleteProduct(self, productID):
pass
def getProductFromName(self, productName):
pass
def createTables(self):
"""this function creates tables """
with sqlite3.connect('database.db') as dbase:
cur = dbase.cursor()
userQuery = '''CREATE TABLE IF NOT EXISTS users(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL,
isAdmin BOOl
)'''
bikeQuery = '''CREATE TABLE IF NOT EXISTS bikes(
bikeID INTEGER PRIMARY KEY AUTOINCREMENT,
bikeName TEXT NOT NULL,
price INTEGER,
model TEXT NOT NULL
)'''
cardQuery = '''CREATE TABLE IF NOT EXISTS cards(
cardID INTEGER PRIMARY KEY AUTOINCREMENT,
type TEXT,
expireDate INTEGER
)'''
saleQuery = '''CREATE TABLE IF NOT EXISTS sales(
saleID INTEGER PRIMARY KEY AUTOINCREMENT,
userID INTEGER,
FOREIGN KEY (userID)
REFERENCES users (ID),
bikeID INTEGER,
FOREIGN KEY (bikeID)
REFERENCES bikes (bikeID),
cardID INTEGER,
FOREIGN KEY (cardID)
REFERENCES cards (cardID),
)'''
cur.execute()
|
from math import sqrt
from Vertice import *
## A street
#
# More details.
class Street:
## The constructor
# @param name name of the street
# @param vertices vertices list
# @param oneway bool
def __init__(self, name, vertices, oneway):
#street name
self.streetName = name
#vertex list
self.streetVertices = []
self.streetVertices = vertices
#oneway bool
self.streetOneway = oneway
self.streetWeight = self.WeightCalculation()
## Calulation of the street weight
def WeightCalculation(self):
difX = self.streetVertices[0].verticeX - self.streetVertices[1].verticeX
difY = self.streetVertices[0].verticeY - self.streetVertices[1].verticeY
#calculation of vertices distance
result = sqrt((difX*difX)+(difY*difY))
return result
## Return the street in a dictionary
def toDictFormat(self):
#initialise street dictionnary
street = {}
street["name"] = self.streetName
street["path"] = []
#for each vertices add vertice name
for vertexToJson in self.streetVertices:
street["path"].append(vertexToJson.verticeName)
street["oneway"] = self.streetOneway
return street
|
import sys
PYTHON_3 = sys.version_info[0] == 3
if PYTHON_3:
import builtins
else:
import __builtin__
def make_builtin(func, name=None):
"""Make a function act like a built-in function in Python.
This is intended to be used sparingly and really only for adding
built-in functions so that ccino test scripts don't need to
import ccino.
This can be used as decorator.
Args:
func: The function to make a built-in
Keyword Args:
name: The name to register the function as if needed.
Returns:
The same function unmodified.
"""
if PYTHON_3:
setattr(builtins, name or func.__name__, func)
else:
setattr(__builtin__, name or func.__name__, func)
return func
def remove_builtin(name):
"""Remove a built-in function.
Args:
name: The function to remove
"""
if PYTHON_3:
delattr(builtins, name)
else:
delattr(__builtin__, name)
|
#!/usr/bin/env python
# coding: utf-8
# Diff entries from two sqlite3 db
import os
import sqlite3
import sys
def get_entries(db_name):
db = sqlite3.connect(db_name)
cur = db.cursor()
cur.execute("SELECT name, type, path from searchIndex")
entries = cur.fetchall()
db.commit()
db.close()
return set(entries)
def diff(old, new):
add = new - old
rem = old - new
print("Added: %d" % len(add))
print_merged_entries(add)
print("Removed: %d" % len(rem))
print_merged_entries(rem)
def print_merged_entries(entries):
size = len(entries)
if size == 0:
return
entries = sorted(entries, key=lambda x: x[2])
entries_in_previous_doc = []
current_doc = entries[0][2].split('#')[0]
start = 0
for i in range(size + 1):
if i < size:
doc_name, _ = entries[i][2].split('#')
# Only print when new doc is met or the last doc is met
if doc_name == current_doc:
continue
entries_in_previous_doc = entries[start:i]
start = i
else:
entries_in_previous_doc = entries[start:]
print("%s: %d" % (os.path.splitext(current_doc)[0],
len(entries_in_previous_doc)))
max_len = [0, 0, 0]
for entry in entries_in_previous_doc:
for j, e in enumerate(entry):
max_len[j] = max(max_len[j], len(e))
format_str = '\t' + '\t'.join(('%%-%ds' % length)
for length in max_len)
for entry in entries_in_previous_doc:
print(format_str % entry)
print('')
current_doc = doc_name
if __name__ == '__main__':
argc = len(sys.argv)
if (argc == 2 or argc == 3) and sys.argv[1] not in ('-h', '--help'):
if argc == 3:
old = get_entries(sys.argv[1])
new = get_entries(sys.argv[2])
diff(old, new)
else:
entries = get_entries(sys.argv[1])
diff(set(), entries)
else:
print("Diff entries with given sqlite3 db")
print("Usage: %s [old_sqlite.db] new_sqlite.db")
|
def ceaser_cipher():
def encrypt_ceaseri( string, key ) :
k = []
print "the message sting is is " + string
for i in range(0, len(string)):
d = ord (string [i])
if ( d + key > 122 ) :
d = 97 + ((d+key) % 122)-1
else:
d = d+key
k.append ( chr(d))
s=""
for i in range ( 0 , len (k)):
s=s+k[i]
return s
def decrypt_ceaser ( string , key ):
k = []
for i in range(0, len(string)):
d = ord (string [i])
if ( d - key < 97 ) :
d = 122 - (key - (d -97)) +1
else:
d = d-key
k.append ( chr(d))
s=""
for i in range ( 0 , len (k)):
s=s+k[i]
return s
string = str(raw_input("enter the string for ceaser cipher : "))
ceaser_key = int(raw_input("enter the key for ceaser cipher : "))
ceasere = encrypt_ceaseri(string,ceaser_key)
print "the encrypted ceaser message is : "+ ceasere
ceaserd = decrypt_ceaser(ceasere , ceaser_key)
print "the encrypted ceaser message is : "+ ceaserd
print "\npress \n1. For Matrix Transposition \n2. Vigenere cipher \n3. Matrix Transposition \n 4. Exit"
return int(raw_input("Enter your choice : "))
def vegenere_cipher():
vengence_matrix =[[0 for x in range(0,26)] for y in range(0,26)]
f=0
def matrix_making():
f=0
for i in range (0,26):
for j in range (0,26):
if((j+97+f) > 122):
#print "if condition running at" + str(97 +j +f)
vengence_matrix[i][j] = chr ( (j+97+f)%122 + 96)
else:
vengence_matrix [i][j]= chr(j+97+f)
f=f+1
#### to manipulate the secret key###
def secretm (secret_key,vstring):
secret_key2=''
j=0
for i in range(0,len(vstring)):
if(j==len(secret_key)):
j=0
secret_key2=secret_key2+secret_key[j]
j=j+1
##print secret_key2
#print "above is the string" + str(len(vstring)) + str (len(vstring))
return secret_key2
### function to decrypt vegenence###
def vegee(vegemat , string ,key):
d=''
for i in range(0,len(key)):
d = d+ vegemat[(ord(string[i]))-97][(ord(key[i]))-97]
return d
def veged(vegemat , estring , key):
d=''
for i in range(0,len(key)):
### first finding the position of i ###
xval=0
for j in range(0,26):
if( key[i] == vegemat[0][j]):
xval=j
break
yval = 0
for j in range(0,26):
if ( estring[i] == vegemat[xval][j]):
yval = j
d=d + chr(yval + 97)
return d
vstring = str(raw_input("enter the string to be converted using vegenece cipher "))
secret_key =str(raw_input( "enter the secret key"))
matrix_making()
for i in range(0,26):
print vengence_matrix[i]
###manipulating the key string according to the user###
secret_keym = secretm(secret_key,vstring)
### function to get the encrypted string ###
vstringe = vegee(vengence_matrix, vstring, secret_keym)
print "the encrypted string is " + vstringe
print "now doing the decrypt function "
vstringd = veged(vengence_matrix, vstringe, secret_keym)
print " the decrypted string is " + vstringd
print "\npress \n1. For Matrix Transposition \n2. Vigenere cipher \n3. Matrix Transposition \n 4. Exit"
return int(raw_input("Enter your choice : "))
def matrix_trans():
### code for matrix transposition###
s = str( raw_input("enter the string : "))
string= ''
for i in range(0,len(s)):
if(s[i] == ' '):
string = string + '%'
else:
string = string + s[i]
print string
k= str(raw_input( "enter the key : "))
key = []
for i in range ( 0 ,len(k)):
key.append( (ord(k[i])) - 48 )
########333
## diy
if((len(string)%len(key)) != 0):
e=(len(string) / len(key))+1
else:
#print "else is running"
e = len(string) / len(key)
###########
c=0
### function for encryption###
mat =[[0 for x in range(0,len(key))] for y in range(0,e)]
for i in range(0,e):
for j in range(0,len(key)):
if(c<len(string)):
mat[i][j]=string[c]
else:
mat[i][j]='%'
c = c+1
for i in range(0,e):
print mat[i]
print key
encrypted = ''
for i in range(0,len(key)):
for j in range(0,e):
#print " the x value is " + str(j) + " the value of y is " + str(key[i])
encrypted = encrypted + mat[j][key[i]-1]
print " the encrypted message is "
print encrypted
print " the decrypted message is "
if((len(encrypted)%len(key)) != 0):
ss=(len(encrypted) / len(key))+1
else:
#print "else is running"
ss= len(encrypted) / len(key)
#print ss
print
matd =[[0 for x in range(0,len(key))] for y in range(0,ss)]
c=0
for i in range(0,len(key)):
for j in range(0,ss):
matd[j][i]=encrypted[c]
c = c+1
for i in range(0,ss):
print matd[i]
decrypted = ' '
for i in range(0,ss):
for j in range(0,len(key)):
#print " the x value is " + str(j) + " the value of y is " + str(key[i])
decrypted = decrypted + matd[i][key[j]-1]
print decrypted
decrypted2=''
for i in range(0,len(decrypted)):
if(decrypted[i] == '%'):
decrypted2 = decrypted2 + ' '
else:
decrypted2 = decrypted2 + decrypted[i]
print " the decrypted message is " +str(decrypted2)
print "\npress \n1. For Matrix Transposition \n2. Vigenere cipher \n3. Matrix Transposition \n4. Exit"
return int(raw_input("Enter your choice"))
print "press \n1. For Ceaser Cipher \n2. Vigenere cipher \n3. Matrix Transposition \n4. Exit"
j = int(raw_input("Enter your choice in numeric form : "))
while(j != 4):
if( j == 1):
j = ceaser_cipher()
elif ( j== 2):
j = vegenere_cipher()
elif ( j == 3):
j = matrix_trans()
else:
exit
### these functions are for matrix transposition ####
## naive solution ###
|
# sum_digits
def sum_digits(num):
'''Takes in a non-negative integer, and tells the sum of each of the digits.'''
if num == 0: # Making a terminating case, with an if statement
return 0 # Terminating Case always returns 0
else:
return num % 10 + sum_digits(num // 10) # Recursive Case
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
n=input()
lis=[]
a =raw_input()
lis=a.split()
newlis=list(map(int,lis))
newlis.sort()
st=set(newlis)
st=st.union()
L=list(st)
L.sort()
print L[-2]
|
#! /usr/bin/env python3
import os
import csv
import json
def create_new_csv_from_json(file_to_write_to, json_data):
with open(file_to_write_to, 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
for line in json_data:
# back_of_card = f"{line["kana"]} {line["eng"]}"
kanji = line["kanji"]
kana = line["kana"]
eng = line["eng"]
combined_kana_eng = "{} \n {}".format(kana, eng)
if kanji:
writer.writerow([ kanji , combined_kana_eng])
else:
writer.writerow([ kana , combined_kana_eng])
# writer.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
json_data = json.load(open('./jlpt_n5_all.json', 'r'))
file_to_write_to = "./csv_for_anki.csv"
create_new_csv_from_json(file_to_write_to, json_data)
# create_dic_for_new_csv('./jlpt_n5_all.json')
|
# -*- coding: utf-8 -*-
import random
arquivo = open("entrada.txt", encoding="utf-8")
palavras = arquivo.readlines()
for i in range(len(palavras)-1):
palavras[i] = palavras[i].strip().upper()
if palavras[i] == '':
del palavras[i]
palavras[i] = palavras[i].strip().upper()
pa = random.choice(palavras)
import turtle # Usa a biblioteca de turtle graphics
window = turtle.Screen() # cria uma janela
window.bgcolor("lightblue")
window.title("Jogo Da Forca")
tartaruga = turtle.Turtle() # Cria um objeto "desenhador"
tartaruga.speed(10) # define a velocidade
tartaruga.penup() # Remova e veja o que acontece
tartaruga.setpos(-250,-200)
tartaruga.pendown()
tartaruga.color("blue")
dist = 120
#funções
def cabeça():
tartaruga.penup() # cabeça
tartaruga.setpos(-80,90)
tartaruga.pendown()
tartaruga.circle(40)
tartaruga.penup()
tartaruga.setpos(-40,50)
tartaruga.penup()
def corpo():
tartaruga.penup()
tartaruga.setpos(-40,50)
tartaruga.pendown() # corpo
tartaruga.forward(150)
tartaruga.penup()
def braço1():
tartaruga.penup()
tartaruga.setpos(-40,-100)
tartaruga.pendown()
tartaruga.backward(125) # braço 1
tartaruga.left(60)
tartaruga.forward(70)
tartaruga.backward(70)
tartaruga.penup()
def braço2():
tartaruga.penup()
tartaruga.setpos(-40,25)
tartaruga.pendown()
tartaruga.right(125) # braço2
tartaruga.forward(70)
tartaruga.backward(70)
tartaruga.penup()
def perna1():
tartaruga.left(65) # perna1
tartaruga.forward(125)
tartaruga.left(35)
tartaruga.penup()
tartaruga.setpos(-40,-100)
tartaruga.pendown()
tartaruga.forward(100)
tartaruga.backward(100)
tartaruga.penup()
def perna2():
tartaruga.penup()
tartaruga.setpos(-40,-100)
tartaruga.pendown()
tartaruga.right(75) # perna2
tartaruga.forward(100)
tartaruga.forward(120)
tartaruga.backward(60)
tartaruga.left(90)
tartaruga.forward(400)
tartaruga.left(270)
tartaruga.forward(150)
tartaruga.right(90)
tartaruga.forward(70)
tartaruga.penup()
espaço = len(pa)
i=0
acertos = 0
while i<= espaço-1:
if pa[i] == (" "):
acertos+=1
else:
tartaruga.setpos(35*i-5*espaço,-200)
tartaruga.write("_ ",font=("arial",25))
i+=1
erros=0
espaço = len(pa)
lista = []
|
#!/usr/bin/env python
chars = 'abcdefghijklmnopqrstuvwxyz'
while True:
sum = 0
inputStr = raw_input()
if inputStr:
for char in inputStr:
if char.lower() in chars:
sum += chars.index(char.lower()) + 1
print sum
else:
break
|
class A:
def sayhi(self):
print("I'm in A")
class B(A):
def sayhi(self):
print("I'm in B")
objB=B()
objB.sayhi()
#Python does not support method overloading
def add(instanceOf,*args):
if instanceOf=='int':
result=0
if instanceOf=='str':
result=''
for i in args:
result+=i
return result
res=add('int',3,4,5)
print(res)
res2=add('str',"Rolando","Mota","Del Campo")
print(res2)
"""
On the other hand, we will learn Python MRO (Method Resolution Order).
At last, we will learn complications in Multiple Inheritance in Python Programming Language.
"""
class Mother:
pass
class Father:
pass
class Child(Mother,Father):
pass
print(issubclass(Child,Mother) and issubclass(Child,Father))
print(Child.__mro__)
print(Child.mro())
class A:
id=1
class B:
id=2
class C:
id=3
class M(A,C,B):
pass
M.id
class A:
def sayhi(self):
print("A")
class B:
def sayhi(self):
print("B")
class M(A,B):
pass
m=M()
m.sayhi()
|
class Car:
def __init__(self, brand,model, color, fuel):
self.brand=brand
self.model=model
self.color=color
self.fuel=fuel
def start(self):
pass
def halt(self):
pass
def drift(self):
pass
def speedup(self):
pass
def turn(self):
pass
def __str__(self):
return f"car model: {self.model}, brand: {self.brand}."
class Van(Car):
def __init__(self,*args,**kwargs):
super(Van,self).__init__(*args,**kwargs)
def __str__(self):
return f"van model: {self.model}, brand: {self.brand}."
if __name__ == '__main__':
blackverna=Car('Hyundai', "Verna", "Black", 'Oil')
ranger=Van('Ford', "Ranger", "Red", 'diesel')
print(blackverna.__str__())
print(ranger.__str__())
|
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/')
def monkey():
return '''
<html>
<head>
<title>Favorite Game</title>
</head>
<body>
<a href="/whatsup?page=2">Next</a>
<form action="/processLogin" method="get">
Enter your name: <input type="text" name="username">
Enter your fav game: <input type="password" name="favgame">
<input type="submit">
</form>
</body>
</html>
'''
@app.route('/processLogin')
def login():
user = request.args.get('username')
# user against db
is_valid_user = False
if is_valid_user:
message = "You're good <a href=/>Back</a>"
else:
message = "Wrong user <a href=/>Back</a>"
return message
@app.route('/submitgame')
def submitgame(blahblah):
#value = request.args.get('tid')
the_name_that_came_in = request.args.get('username')
return 'You sent me ' + str(the_name_that_came_in).upper()
@app.route('/calc/<somenum>')
def calc(somenum=1):
return str(int(somenum) * 10)
@app.route('/process')
def duh():
return 'Duh!!'
@app.route('/whatsup')
def bro():
request.args.get('uid')
return 'Bro!!!??'
|
def factorial(n):
if n==0:
return 1
else:
return n * factorial(n-1)
factorial_of_five = factorial(5)
print('The factorial of five is',factorial_of_five)
factorial_of_ten = factorial(10)
print('The factorial of ten is',factorial_of_ten)
print('The factorial of six is',factorial(6))
f = factorial(7)
print('The factorial of seven is',f)
f = factorial(9)
print('9! is ',f)
|
from random import randint
from time import sleep
sort = []
temp = []
print('-' * 30)
print(f'{"JOGA NA MEGA SENA":^30}')
print('-' * 30)
jog = int(input('Quantos jogos você quer que eu sorteie? '))
tot = 1
while tot <= jog:
cont = 0
while True:
num = randint(1, 60)
if num not in temp:
temp.append(num)
cont += 1
if cont == 6:
break
temp.sort()
sort.append(temp[:])
temp.clear()
tot += 1
print('-=' * 3, f'SORTEANDO {jog} JOGOS', '=-' * 3)
for i, l in enumerate(sort):
print(f'Jogo {i+1}: {l}')
sleep(1)
print('-=' * 4, '< BOA SORTE! >', '=-' * 4)
|
numeros = []
while True:
numeros.append(int(input('Digite um valor: ')))
sair = ' '
while sair not in 'SN':
sair = str(input('Quer continuar? [S/N] ')).upper().strip()[0]
if sair == 'N':
break
print('=-' * 30)
print(f'Você digitou {len(numeros)} elementos.')
numeros.sort(reverse=True)
print(f'Os valores em ordem decrescente são {numeros}')
if 5 in numeros:
print('O valor 5 faz parte da lista!')
else:
print('O valor 5 não foi encontrado na lista!')
|
lista = []
pares = []
impares = []
while True:
lista.append(int(input('Digite um número: ')))
sair = str(input('Quer continar? [S/N] '))
if sair in 'Nn':
break
for i, v in enumerate(lista):
if v % 2 == 0:
pares.append(v)
else:
impares.append(v)
print('=-' * 30)
print(f'A lista completa é {lista}')
print(f'A lista de pares é {pares}')
print(f'A lista de ímpares é {impares}')
|
#!/usr/bin/python
for letter in 'this is another test':
print('Letters: ', letter)
for number in range(0,10000):
print(number)
|
#multi level
class name:
def __init__(self,n):
self.n=intput("name")
def names(self):
print(self.n)
class roll(name):
def __init__(self,r):
name.__init__(self,n)
self.r=r
def rolls(self):
print(self.r)
class student(roll):
def __init__(self,s):
roll.__init__(self,r)
self.s=s
def display(self):
print("The name of student is",name.names(self))
print("The roll of student is",roll.rolls(self))
x=input("enter name")
y=int(input("enter roll"))
obj1=roll(x)
obj=student(y)
obj.display()
|
class Employee:
name=input("enter name")
ID=int(input("enter your eid"))
def Increment(self,bsal):
self.bsal=bsal
self.hra= (25/100)*self.bsal
self.gross=self.bsal+self.hra
print("gross",self.gross)
obj1=Employee()
obj1.Increment(1000)
print("name:",getattr(obj1,"name"))
print("eid:",getattr(obj1,"ID"))
print("gross salary",getattr(obj1.Increment,""))
#obj2=Employee()
#Increment()
#eid,obj=total sal, (basic sal,hra,da)
|
#bitwise operators are used to perform operations on one bit(binary digit) at a time.
a=10
b=20
print(a&b) #bitwise and
print(a|b) #bitwise or
print(a^b) #bitwise EX-OR
print(a<<1) #bitwise left shift
print(a>>1) #bitwise right shift
|
from abc import ABC,abstractmethod #abstract base class
class AbstractClassExample(ABC):
def __init__(self,value):
self.value=value
super().__init__()
@abstractmethod
def do_something(self):
pass
class DoAdd42(AbstractClassExample):
def do_something(self):
return self.value+42
class DoMul42(AbstractClassExample):
def do_something(self):
return self.value*42
x=DoAdd42(10)
y=DoMul42(10)
print(x.do_something())
print(y.do_something())
|
def selection_sort(array):
for i in range(len(array)):
i_min = i
for j in range(i+1, len(array)):
if array[j] < array[i_min]:
i_min = j # finding minimum value in unsorted array
if i != i_min:
array[i], array[i_min] = array[i_min], array[i] # swap if a smaller value exists
|
import Cell
class Board():
board = []
max_rows = 0
max_columns = 0
def __str__(self):
new_str = ''
for row in range(self.max_rows):
for col in range(self.max_columns):
new_str += str(self.board[col + row * self.max_columns])
new_str += "\n"
return new_str
def __init__(self, max_rows, max_columns):
self.max_rows = max_rows
self.max_columns = max_columns
# make board
for row in range(max_rows):
for col in range(max_columns):
self.board.append(Cell.Cell(row, col))
def find_neighbour(self, target):
neighbours = dict()
# north
if target.row + 1 < self.max_rows:
index = (target.row + 1)*self.max_columns + target.column
if not(self.board[index].visited):
neighbours['north'] = self.board[index]
# east
if target.column + 1 < self.max_columns:
index = (target.row * self.max_columns + (target.column + 1))
if not(self.board[index].visited):
neighbours['east'] = self.board[index]
# south
if target.row - 1 >= 0:
index = ((target.row - 1)*self.max_columns + target.column)
if not(self.board[index].visited):
neighbours['south'] = self.board[index]
# west
if target.column - 1 >= 0:
index = (target.row * self.max_columns + (target.column - 1))
if not(self.board[index].visited):
neighbours['west'] = self.board[index]
return neighbours
|
#!/usr/local/bin/python
# appends lexicographically smallest rotation at the end of the line
import sys
import os
import re
from Bio.Seq import Seq
import subprocess as sp
def RotateMe(text,mode=0,steps=1):
# function from http://www.how2code.co.uk/2014/05/how-to-rotate-the-characters-in-a-text-string/
# Takes a text string and rotates
# the characters by the number of steps.
# mode=0 rotate right
# mode=1 rotate left
length=len(text)
for step in range(steps):
# repeat for required steps
if mode==0:
# rotate right
text=text[length-1] + text[0:length-1]
else:
# rotate left
text=text[1:length] + text[0]
return text
def SmallestRotation(seq):
smallest=seq
for i in range(0,len(seq)):
actual=RotateMe(seq,0,i)
#print ("*" + actual)
if (actual<smallest):
#found new minimum
smallest=actual
return smallest
def lexicographicallySmallestRotation(seq): #Modified by Wil to remove reverse complement collapsing
my_seq=Seq(seq)
#reverse_complement=my_seq.reverse_complement()
#reverse_complement=str(reverse_complement)
smrt_seq=SmallestRotation(seq)
#smrt_rev_compl_seq=SmallestRotation(reverse_complement)
#lexicographically smallest rotation is either one of the rotations of the sequence or its reverse complement
#if (smrt_seq < smrt_rev_compl_seq):
# return smrt_seq
#else:
# return smrt_rev_compl_seq
return smrt_seq
def parseTRF(file):
number_of_sequences=0
for line in open(file):
li=line.strip()
fields=li.split("\t")
if (len(fields)==7):
#append lexicographically smallest rotation at the end of the line
repeat=fields[0] #changed from 3
#print (li + "\t" + lexicographicallySmallestRotation(repeat))
f.write(li + "\t" + lexicographicallySmallestRotation(repeat) + "\n")
trf_file = sys.argv[1]
output = trf_file + "_output.txt"
f = open(output,"w")
parseTRF(trf_file)
f.close()
print ("Output printed into file " + output)
#split into multiple files based on the repeat representatives
args = ["awk", r'{print > ""$8"n"}', output]
p = sp.Popen(args, stdin = sp.PIPE, stdout = sp.PIPE, stderr = sp.PIPE )
print(p.stdout.readline()) # will give you the first line of the awk output
print ("Splitting finished. Done.")
|
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from urllib.request import urlopen
import wget
'''
Scraping web - Python 3
'''
def scraping_web(url, patron_link):
"""
Esta funcion me pide una url y me devuelve un lista con los links
:param url: pide una url como http://www.google.com con http
:param patron_link: es un patron que aparece en el link <a href=>
:return: devuelve una lista con los links de la pagina, que son de tipo excel xls
"""
page = urlopen(url)
bs = BeautifulSoup(page.read(), 'lxml')
a = bs.find_all("a")
# crea listas vacias para guardar los links
links = []
archivos_excel = []
for link in a:
links.append(link.get('href'))
for link in links:
if patron_link in str(link):
print(link)
archivos_excel.append(link)
return archivos_excel
def descargar(links, patron_error, url_base):
"""
descarga todos los links de excel
:param links: es una lista con los links de excel
:param patron_error: es un patron que se encuentra en los links que no queremos
:return: solo descarga en la carpeta datos
"""
links_buenos = []
for link in links:
if patron_error not in link:
links_buenos.append(link)
for link in links_buenos:
if 'xls' in link:
link = link.replace(" ", "%20")
wget.download(url_base + link)
'''
Ejecucion de funciones
'''
# url de ejemplo con muchos archivos para descargar
url = 'https://www.superfinanciera.gov.co/jsp/loader.jsf?lServicio=Publicaciones&lTipo=publicaciones&lFuncion=loadContenidoPublicacion&id=10427'
# patron que aparece en los links que me interesan
patron = 'xls'
lista_links = scraping_web(url, patron)
print(lista_links, len(lista_links))
# para descargar necesitamos la url_base
url_base = 'https://www.superfinanciera.gov.co'
# la funcion descargar descarga toda la lista de links
descargar(lista_links, 'http', url_base)
#listo
print('listo...')
|
import datetime
last_id = 0
class Note:
"""
Class for representation of a single note with memo
"""
def __init__(self, memo, tags=''):
"""
Initializes a note with memo and tags (remembers creation date)
"""
self.memo = memo
self.tags = tags
self.creation_date = datetime.date.today()
global last_id
last_id += 1
self.id = last_id
def match(self, filt):
"""
Checks if in note there is matches with given tags
"""
return filt in self.memo or filt in self.tags
class Notebook:
def __init__(self):
"""
Initializes a Notebook with a empty list of notes
"""
self.notes = []
def new_note(self, memo, tags=''):
"""
Creates a new note with memo in notebook
"""
self.notes.append(Note(memo, tags))
def _find_note(self, note_id):
"""
Finds a note by note id
"""
for note in self.notes:
if note.id == note_id:
return note
def modify_memo(self, note_id, memo):
"""
Modifies a memo in notebook by id
"""
note = self._find_note(note_id)
if note:
self._find_note(note_id).memo = memo
return 1
def modify_tags(self, note_id, tags):
"""
Modifies a tegs in notebook by id
"""
note = self._find_note(note_id)
if note:
self._find_note(note_id).tags = tags
return 1
def search(self, filt):
"""
Returns a list of notes which matches a filter
"""
return [note for note in self.notes if
note.match(filt)]
|
#!/usr/bin/env python
import time
import random
import RPi.GPIO as GPIO
# led-blink.py
# From a selection of 5 LEDs, blink them alternatively by randomly
# turning each one on and off, while pausing on every loop. The
# intention of this script is to create an "alarm" system for a model
# house which will make all lights blink in rapide succession.
# Tell the GPIO to use the PIN numbering schema for the Rpi
GPIO.setmode(GPIO.BOARD)
# GPIO17, GPIO18, GPIO27, GPIO23, and GPIO21, respectively below:
PINS = [11, 12, 13, 16, 40]
# Setup the pins to use as output (lights)
# setup() takes a single value or a list
GPIO.setup(PINS, GPIO.OUT)
# This endless loop below is so the program continues to run
# indefinitely until you break out of it..
run = True
try:
while run:
# Get a random pin
led = random.choice(PINS)
# Turn the pin/led "on"
GPIO.output(led, GPIO.HIGH)
# Wait a bit..
time.sleep(0.15)
# Then tun the pin/led off, then loop back to get another
# random pin, note that the random function can return the same
# pin again, but it should be enough to give the blinking illusion.
GPIO.output(led, GPIO.LOW)
except KeyboardInterrupt:
print('Exit Requested..')
run = False
finally:
GPIO.cleanup()
|
def rekursif(angka):
if angka > 0 :
print (angka)
angka = angka - 1
rekursif(angka)
else :
print(angka)
masukan = int(input("masukkan angka : "))
rekursif(masukan)
|
def reverseItem(item):
toString = str(item)
stringLent = len(toString)
print item
# import pdb
# pdb.set_trace()
newStr = toString[::-1]
print newStr
if newStr[stringLent-1] == '-':
strToInt = 0 - int(newStr[0:stringLent-1])
else:
strToInt = int(newStr)
return strToInt
def solution(LD):
"""
Complete the function such that:
Given a list of digits LD, reverse all the digits in LD to a new list LR.
Return the LR and largest element in LR in a tuple such that:
- [123] -> ([321], 321)
- [-789, 10] -> ([-987, 1], 1)
- [11020, 3512] -> ([2011, 2153], 2153)
Constraints:
Eliminate leading zeros.
Note the position of the negative operator after the reversal.
"""
arr1 = []
for item in LD:
arr1.append(reverseItem(item))
print ((arr1, max(arr1)))
return ((arr1, max(arr1)))
solution([11020, 3512])
|
"""This module contains basic codes for the project, such as a Wave object to
save the rate and data from a .wav files and functions to read the speakers and
the utterances.
"""
import scipy.io.wavfile as wavfile
import numpy as np
import os
class Wave(object):
"""Class to describe a basic .wav file. The Wave object contains the sampling
rate and data from the .wav file.
"""
def __init__(self, filename=None):
if filename is not None:
wavf = wavfile.read(filename)
self.rate = wavf[0]
self.data = wavf[1].astype(np.int64, copy=False) # by default, numpy creates a array of int16
def __str__(self):
ret = 'rate: %d\nsample_length: %d\ndata: %s' % (self.rate, self.length(),
self.data)
return ret
def save(self, filename):
"""Saves a Wave object into a .wav file.
"""
wavfile.write(filename, self.rate, self.data)
def length(self):
"""Size of the data array.
"""
return len(self.data)
def clone(self, start, end):
cloned_wave = Wave()
cloned_wave.rate = self.rate
cloned_wave.data = self.data[start : end].astype(np.int16, copy=False)
return cloned_wave
def read_speakers(subcorpus):
"""Given a subcorpus (enroll_1, enroll_2 or imposter) it returns a tuple of
names for speakers. The first element is a list of names for female speakers
and the second is a list of names for male speakers.
"""
dirs = os.listdir(subcorpus)
females = [d for d in dirs if d[0] == 'f']
females.sort()
males = [d for d in dirs if d[0] == 'm']
males.sort()
return (females, males)
def read_utterances_from_speaker(subcorpus, speaker):
"""Given a subcorpus (enroll_1, enroll_2 or imposter) and a speaker (f00, f01,
m00...) it returns the 54 utterances names (.wav) for this speaker in this
particular base. The utterances are sorted.
"""
utterances = os.listdir('%s/%s/' % (subcorpus, speaker))
utterances = [utterance for utterance in utterances if utterance.endswith('.wav')]
utterances.sort()
return utterances
def read_utterance(subcorpus, speaker, utterance):
wave = Wave('%s/%s/%s' % (subcorpus, speaker, utterance))
return wave
# Test
if __name__ == '__main__':
import os.path
if not os.path.exists('tests'):
os.mkdir('tests')
basic = open('tests/basic.out', 'w')
corpus = ['corpus/enroll_1/', 'corpus/enroll_2/', 'corpus/imposter/']
for subcorpus in corpus:
print(subcorpus)
print(subcorpus, file=basic)
(females, males) = read_speakers(subcorpus)
speakers = females + males
for speaker in speakers:
print(speaker)
print(speaker, file=basic)
utterances = read_utterances_from_speaker(subcorpus, speaker)
for utterance in utterances:
print(utterance, file=basic)
wave = read_utterance(subcorpus, speaker, utterance)
print(wave, file=basic)
print(file=basic)
print(file=basic)
print('output to file "tests/basic.out"')
|
import cv2
from matplotlib import pyplot as plt
import numpy as np
image = cv2.imread("saggital.png")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
# convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
# create a binary thresholded image
_, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV)
# show it
plt.imshow(binary, cmap="gray")
plt.show()
# find the contours from the thresholded image
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# draw all contours
image = cv2.drawContours(image, contours, -1, (0, 255, 0), 2)
# show the image with the drawn contours
plt.imshow(image)
plt.show()
|
import robot
import sys
from time import sleep
def run_auto(r):
"""
run_auto(r) - The robot will crawl until it sees blue and then turn 180 degrees and crawl the same distance again
:param r: a robot class
:return: nothing
"""
print(" ___________________________________")
print(" / /")
print(" / AUTO MODE /")
print("/__________________________________/")
steps = 0
for i in range(0, 20):
r.crawl()
sleep(0.5)
while not r.sees_blue():
r.crawl()
sleep(0.5)
r.turn(3960)
for i in range(0,10):
r.crawl()
sleep(0.5)
while not r.sees_blue():
r.crawl()
sleep(0.5)
r.dance(10)
def run_manual(r):
"""
run_manual(r) - Gives user control of robot until they quit. Control with WASD keys
:param r: a robot class
:return: nothing
"""
#if extra time, then use arrow keys/don't press enter
print(" ___________________________________")
print(" / /")
print(" / MANUAL MODE /")
print("/__________________________________/")
sleep(1)
c = ""
while c.lower() != "q":
c = input().lower()
if c == "w":
r.crawl()
elif c == "d":
r.turn(-90)
elif c == "a":
r.turn(90)
elif c == "s":
r.suction()
elif c == "c":
r.sees_blue()
elif c == "!":
r.dance(10)
elif c != "q":
print(c + ': Command not found')
sleep(0.1)
if __name__ == "__main__":
if len(sys.argv) is 1:
auto = False
elif sys.argv[1] in ['--auto', '-a']:
auto = True
elif sys.argv[1] in ['--manual', '-m']:
auto = False
else:
print('usage: main.py [-a or --auto] or [-m --manual]')
quit()
r = robot.Robot()
if auto:
run_auto(r)
else:
run_manual(r)
|
#!/bin/python3
import math
import os
import random
import re
import sys
import collections
#
# Complete the 'collectionfunc' function below.
#
# The function accepts following parameters:
# 1. STRING text1
# 2. DICTIONARY dictionary1
# 3. LIST key1
# 4. LIST val1
# 5. DICTIONARY deduct
# 6. LIST list1
#
def collectionfunc(text1, dictionary1, key1, val1, deduct, list1):
# Section 1
dict_count = dict()
text_split = text1.split()
for word in sorted(text_split):
if word not in dict_count:
dict_count[word] = 0
dict_count[word] += 1
print(dict_count)
# Section 2
cnt = Counter(dictionary1)
cnt.subtract(deduct)
print(dict(cnt))
# Section 3
od = collections.OrderedDict(zip(key1, val1))
od.pop(key1[1])
# Section 4
od[key1[1]] = val1[1]
print(dict(od))
# Section 5
count = collections.defaultdict(int)
count_even = []
count_odd = []
for items in list1:
if items % 2 == 0:
count_even.append(items)
else:
count_odd.append(items)
if count_odd:
count['odd'] = count_odd
if count_even:
count['even'] = count_even
print(dict(count))
if __name__ == '__main__':
from collections import Counter
text1 = input()
n1 = int(input().strip())
qw1 = []
qw2 = []
for _ in range(n1):
qw1_item = (input().strip())
qw1.append(qw1_item)
qw2_item = int(input().strip())
qw2.append(qw2_item)
testdict = {}
for i in range(n1):
testdict[qw1[i]] = qw2[i]
collection1 = (testdict)
qw1 = []
n2 = int(input().strip())
for _ in range(n2):
qw1_item = (input().strip())
qw1.append(qw1_item)
key1 = qw1
qw1 = []
n3 = int(input().strip())
for _ in range(n3):
qw1_item = int(input().strip())
qw1.append(qw1_item)
val1 = qw1
n4 = int(input().strip())
qw1 = []
qw2 = []
for _ in range(n4):
qw1_item = (input().strip())
qw1.append(qw1_item)
qw2_item = int(input().strip())
qw2.append(qw2_item)
testdict = {}
for i in range(n4):
testdict[qw1[i]] = qw2[i]
deduct = testdict
qw1 = []
n5 = int(input().strip())
for _ in range(n5):
qw1_item = int(input().strip())
qw1.append(qw1_item)
list1 = qw1
collectionfunc(text1, collection1, key1, val1, deduct, list1)
|
#!/bin/python3
import math
import os
import random
import re
import sys
def Reverse(lst):
lst.reverse()
return lst
def stringmethod(para, special1, special2, list1, strfind):
# Section 1 --> Ok
word1 = ""
for character in para:
if character not in special1:
word1 = word1 + character
rword2 = word1[0:70]
print(rword2[::-1])
# Section 2 --> Ok
rword3 = rword2[::-1]
rword3 = re.sub("\s+", "", rword3)
temp = ""
for character in rword3:
temp = temp + character + special2
print(temp[:-1])
# Section 3 --> Ok
a = True
for s in list1:
if s not in para:
a = False
if a:
print("Every string in ", end=" "),
print(list1, end=" "),
print("were present")
else:
print("Every string in ", end=" "),
print(list1, end=" "),
print("were not present")
# Section 4 --> OK
print(word1.split()[:20])
# Section 5
word_list = word1.split()
temp_dict = dict()
for str1 in word_list:
if word_list.count(str1) <= 3:
if str1 not in temp_dict:
temp_dict[str1] = 0
temp_dict[str1] += 1
temp_list = []
for value in list(reversed(list(temp_dict)))[0:20]:
temp_list.append(value)
print(Reverse(temp_list))
# Section 6
print(word1.rindex(strfind))
if __name__ == '__main__':
para = input() # a string
spch1 = input()
spch2 = input()
qw1_count = int(input().strip())
qw1 = []
for _ in range(qw1_count):
qw1_item = input()
qw1.append(qw1_item)
strf = input()
stringmethod(para, spch1, spch2, qw1, strf)
|
m = bin(585).zfill(8)
m = m.lstrip('-0b')
palindrome_list = list()
def is_palindrom(number):
number = str(number)
reversed_number = reverse_it(number)
if number == reversed_number:
binary_number = bin(int(number))
binary_number = binary_number.lstrip('-0b')
binary_number = str(binary_number)
reversed_binary = reverse_it(binary_number)
if reversed_binary == binary_number:
if number not in palindrome_list:
palindrome_list.append(int(number))
def reverse_it(number):
reversed_number = number[::-1]
return reversed_number
for first_number in range(1,1000000):
is_palindrom(first_number)
print(sum(palindrome_list))
|
#Sum square difference
number = 0
sum = 0
total= 0
totalsum = 0
numbersum= 0
for x in range(1,101):
number = x*x
total = total + number
for x in range(1,101):
numbersum = numbersum + x
totalsum = numbersum * numbersum
value= totalsum - total
print(value)
|
a = input()
b = input()
list1 = b.split(' ')
score = []
for i in list1:
score.append(int(i))
mx1 = max(score)
mx2 = -100
for i in score:
if i < mx1 and i > mx2:
mx2 = i
print(mx2)
|
for cases in range(int(input())):
n = int(input())
characters = {}
for strings in range(n):
string = input()
for i in string:
characters[i] = characters.get(i, 0) + 1
status = True
for value in characters.values():
if value % n != 0:
status = False
break
if status:
print("YES")
else:
print("NO")
|
# -- coding: utf-8 --
name = 'hoohoo'
age = 35
height = 74
weight = 180
eyes = 'Blue'
teeth = "White"
hair = 'Brown'
print "Let's talk about %s." % name
print "He's %d inches tall." % height
print "He's %d pounds heavy." % weight
print "Actually that's not too heavy."
print "He's got %r eyes and %s hair." % (eyes, hair)
print "His teeth are usually %s depending on the coffee." % teeth
print "If I add %r, %r, and %d I get %d." % (
age, height, weight, age + height + weight)
lang = "python"
year = 0.5
print "I have been learning %r for %r years." % (lang, year)
pounds = 25
inches = 24
print "%d pounds is equal to %f kilograms." % (pounds, pounds * 0.4536)
print "%d inches is equal to %f centimeters." % (inches, inches * 2.54)
|
import unittest
import main
class TestMain(unittest.TestCase):
def setUp(self):
self.graph_dict = {
"a": {"b": 30, "c": 10},
"b": {"d": 40},
"c": {"a": 50},
"d": {"c": 20}
}
self.graph_matrix = [
[0, 30, 10, 0],
[0, 0, 0, 40],
[50, 0, 0, 0],
[0, 0, 20, 0]
]
self.labeled_graph = {"a": 3, "b": 1, "c": 2}
def test_create_graph_from_dict(self):
result = self.graph_dict
self.assertEqual(
main.create_graph_from_dict(self.graph_dict).get_dict(),
result)
def test_create_graph_from_matrix(self):
result = {
"0": {"1": 30, "2": 10},
"1": {"3": 40},
"2": {"0": 50},
"3": {"2": 20}
}
self.assertEqual(
main.create_graph_from_matrix(self.graph_matrix).get_dict(),
result)
def test_get_current_node(self):
visited_nodes = ["b"]
result = "c"
self.assertEqual(
main.get_current_node(self.labeled_graph, visited_nodes),
result)
def test_get_current_node_none(self):
visited_nodes = ["a", "b", "c"]
self.assertIsNone(
main.get_current_node(self.labeled_graph, visited_nodes))
def test_dijkstra(self):
graph = main.create_graph_from_dict(self.graph_dict)
initial_node = "a"
result = {"a": 0, "b": 30, "c": 10, "d": 70}
self.assertEqual(
main.dijkstra(graph, initial_node),
result)
|
#Loop exercise 4 another way
for rows in range(5):
# print("*" * 5)
star = ""
for cols in range(5):
star += "*"
print(star)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 31 11:04:14 2019
Text classification & NLP using Multinominal Naive Bayes
"""
# Step 1 : Import libraries
import nltk
from nltk.stem.lancaster import LancasterStemmer
# word stemmer
stemmer = LancasterStemmer()
# Step 2 : Provide training data
# 3 classes of training data
training_data = []
# greeting class
training_data.append({"class": "greeting", "sentence": "how are you?"})
training_data.append({"class": "greeting", "sentence": "how is your day?"})
training_data.append({"class": "greeting", "sentence": "good day"})
training_data.append({"class": "greeting", "sentence": "how is it going today?"})
# goodbye class
training_data.append({"class": "goodbye", "sentence": "have a nice day"})
training_data.append({"class": "goodbye", "sentence": "see you later"})
training_data.append({"class": "goodbye", "sentence": "see ya"})
training_data.append({"class": "goodbye", "sentence": "talk to you soon"})
# sandwich calss
training_data.append({"class": "sandwich", "sentence": "make me a sandwich"})
training_data.append({"class": "sandwich", "sentence": "can you make a sandwich?"})
training_data.append({"class": "sandwich", "sentence": "having a sandwich today?"})
training_data.append({"class": "sandwich", "sentence": "what's for lunch?"})
print("%s sentences of training data" % len(training_data))
# Step 3 : Organize data in structures
# capture unique stemmed words in the training corpus
corpus_words = {}
class_words = {}
# turn a list into a set and then a list again (this removes duplicates)
classes = list(set([a['class'] for a in training_data]))
for c in classes:
# prepare a list of words within each class
class_words[c] = []
# loop through each sentence in our training data
for data in training_data:
# tokenize each sentence into words
for word in nltk.word_tokenize(data['sentence']):
# ignore a some things
if word not in ["?", "'s"]:
# stem & lowercase each word
stemmed_word = stemmer.stem(word.lower())
# have we not seen this word already?
if stemmed_word not in corpus_words:
corpus_words[stemmed_word] = 1
else:
corpus_words[stemmed_word] += 1
# add the word to our words in class list
class_words[data['class']].extend([stemmed_word])
# we now have each stemmed word and the number of occurances of the word in our training corpus(the word's commonality)
print("Corpus words and counts: %s \n" % corpus_words)
# also we have all words in each class
print("Class words: %s" % class_words)
# Step 4 : Code algorithm
# calculate a score for a given class
def calculate_class_score(sentence, class_name, show_details=True):
score = 0
# tokenize each word in our new sentence
for word in nltk.word_tokenize(sentence):
# check to see if the stem of the word is in any of our classes
if stemmer.stem(word.lower()) in class_words[class_name]:
'''# treat each word with same weight
score += 1
'''
# treat each word with relative weight
score += (1 / corpus_words[stemmer.stem(word.lower())])
if show_details:
'''print("match: %s" % stemmer.stem(word.lower()))'''
print("match: %s (%s)" % (stemmer.stem(word.lower()), 1 / corpus_words[stemmer.stem(word.lower())]))
return score
# we can now calculate score for new sentence
sentence = "A good, good plot and great characters, but poor acting."
# now we can find the class with the highest score
for c in class_words.keys():
print("Class: %s, Score: %s\n" % (c, calculate_class_score(sentence, c)))
# Step 5 : Abstract algorithm
# return the class with highest score for sentence
def classify(sentence):
high_class = None
high_score = 0
# loop through our classes
for c in classes:
# calculate score of sentence for each class
score = calculate_class_score(sentence, c, show_details=False)
# keep track of highest sore
if score > high_score:
high_score = score
high_class = c
return high_score, high_class
|
from Exer_04 import Pessoa
def main():
nome = input("Digite seu nome: ")
idade = int(input("Digite sua idade: "))
peso = float(input("Digite seu peso: "))
altura = float(input("Digite seu altura: "))
continua = True
pessoa = Pessoa(nome, idade, peso, altura)
while(continua):
print("1.Envelhecer")
print("2.Engordar")
print("3.Emagrecer")
print("4.Crescer")
print("5.Sair")
escolha = int(input("Digite uma opção: "))
if(escolha == 1):
pessoa.envelhecer()
print("{} você envelheceu 1 ano sua idade é de {}".format(pessoa.nome, pessoa.idade))
if(pessoa.idade < 21):
print("Você cresceu 0.5 cm e sua altura é de {}m".format(round(pessoa.altura, 2)))
elif(escolha == 2):
pessoa.engordar()
print("{} você engordou 1 Kg seu peso é de {}Kg".format(pessoa.nome, pessoa.peso))
elif(escolha == 3):
pessoa.emagrecer()
print("{} você emagreceu 1 Kg seu peso é de {}Kg".format(pessoa.nome, pessoa.peso))
elif(escolha == 4):
pessoa.crescer()
print("{} você cresceu 0.5m sua altura é de {}m".format(pessoa.nome, pessoa.altura))
else:
continua = False
if __name__ == "__main__":
main()
|
from pynput import keyboard
from pynput.keyboard import Key
def on_press(key):
if isinstance(key ,Key):
if key == keyboard.Key.esc:
# Stop listener and exit
keyboard.Listener.stop
return False
elif Key.space == key:
print(" ",end="",flush=True)
elif Key.enter == key:
print("\n",end="",flush=True)
else:
print(key.char,end="",flush=True)
print("hi")
with keyboard.Listener(on_press=on_press) as listener:
listener.join()
|
li=[]
i=0
for i in range(5):
print "Enter the value"
r=raw_input()
li.append(r)
print li
|
import os
import sys
import signal
import itertools
def print_titles(file, inc=3):
"""
Print titles in a file
Keyword arguments:
real -- the real part (default 0.0)
imag -- the imaginary part (default 0.0)
"""
count = 0
with open(file) as f:
for line in f:
if count == 0 or count % 3 == 0:
print(line.strip() + '\t 0')
count += 1
def unique_everseen(iterable, key=None):
"""
List unique elements, preserving order. Remember all elements ever seen.
# unique_everseen('AAAABBBCCDAABBB') --> A B C D
# unique_everseen('ABBCcAD', str.lower) --> A B C D
"""
seen = set()
seen_add = seen.add
if key is None:
for element in itertools.ifilterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element
def remove_duplicates(file):
"""
Remove duplicate lines in file
"""
file_tmp = 'tmp'
with open(file) as f, open(file_tmp, 'w') as o:
for line in unique_everseen(f):
o.write(line)
# rename file_tmp to file
os.remove(file)
os.rename(file_tmp, file)
def annotate_titles(file, start_line=0, default_annotation=0):
"""
Print lines one by one and prompt annotation
"""
count = 0
with open(file) as f:
for line in f:
if count >= start_line:
text, annotation = line.split('\t')
print(text)
new_annotation = raw_input('Annotation: ')
if not new_annotation:
break
if count >= 10:
break
count += 1
if __name__ == '__main__':
# # print titles from dataset
# file = sys.argv[1]
# print_titles(file)
# # annotate lines
# file = sys.argv[1]
# start_line = 0
# if len(sys.argv) > 2:
# start_line = int(sys.argv[2])
# annotate_titles(file, start_line)
# # signal.signal(signal.SIGINT, save_file)
# # signal.signal(signal.SIGTERM, save_file)
remove_duplicates(sys.argv[1])
|
import json
class Player():
def __init__(self, first_name, last_name, height_cm, weight_kg):
self.first_name = first_name
self.last_name = last_name
self.height_cm = height_cm
self.weight_kg = weight_kg
class BasketballPlayer(Player):
def __init__(self, first_name, last_name, height_cm, weight_kg, points, rebounds, assists):
super().__init__(first_name=first_name, last_name=last_name, height_cm=height_cm, weight_kg=weight_kg)
self.points = points
self.rebounds = rebounds
self.assists = assists
class FootballPlayer(Player):
def __init__(self, first_name, last_name, height_cm, weight_kg, goals, yellow_cards, red_cards):
super().__init__(first_name=first_name, last_name=last_name, height_cm=height_cm, weight_kg=weight_kg)
self.goals = goals
self.yellow_cards = yellow_cards
self.red_cards = red_cards
def bb_player():
first_n = input("Enter first name: ")
last_n = input("Enter last name: ")
height = input("Enter height: ")
weight = input("Enter weight: ")
point = input("Enter the number of points: ")
rebound = input("Enter the number of rebounds: ")
assist = input("Enter the number of assists: ")
b_player = BasketballPlayer(first_name=first_n, last_name=last_n, height_cm=height, weight_kg=weight, points=point,
rebounds=rebound, assists=assist)
with open("b_players.txt", "a") as player_file:
player_file.write(json.dumps(b_player.__dict__))
print("Player successfully entered!")
print("Player's data: {0}".format(b_player.__dict__))
def fb_player():
first_n = str(input("Enter first name: "))
last_n = str(input("Enter last name: "))
height = int(input("Enter height: "))
weight = int(input("Enter weight: "))
goal = int(input("Enter the number of goals: "))
yellow_card = int(input("Enter the number of yellow cards: "))
red_card = int(input("Enter the number of red cards: "))
f_player = FootballPlayer(first_name=first_n, last_name=last_n, height_cm=height, weight_kg=weight, goals=goal,
yellow_cards=yellow_card, red_cards=red_card)
with open("f_players.txt", "a") as player_file:
player_file.write(str(f_player.__dict__))
print("Player successfully entered!")
print("Player's data: {0}".format(f_player.__dict__))
while True:
selection = input("Would you like to A) create new basketball player B) create new football player or c) quit? ")
if selection.upper() == "A":
bb_player()
elif selection.upper() == "B":
fb_player()
else:
print("Goodbye!")
break
|
import heapq
from collections import Counter, defaultdict
class Solution(object):
def __init__(self, nums, k):
self.nums = nums
self.k = k
def counter(self):
"""
Elements with equal counts are ordered in the order first encountered.
"""
return [x[0] for x in Counter(self.nums).most_common(self.k)]
def hashmap(self):
hm = defaultdict(int)
for n in self.nums:
hm[n] += 1
most_freq = [k for k, _ in sorted(hm.items(), key=lambda x: x[1], reverse=True)]
return most_freq[: self.k]
def heap(self):
"""
Solve using a min heap, sorting on count
"""
if not self.nums or self.k == 0:
return []
counter = Counter(self.nums)
return sorted(heapq.nlargest(self.k, counter.keys(), key=counter.get))
def heap_oneliner(self):
return sorted(
[
x[2]
for x in heapq.nlargest(
self.k,
[
(count, i, val)
for (i, (val, count)) in enumerate(Counter(self.nums).items())
],
)
]
)
|
class Stack(object):
def __init__(self):
self.len = 0
self.stack = []
self.max = [] # latest value reflects current maximum
def Push(self, value):
# empty
if not self.max:
self.max.append(value)
else:
self.max.append(max(value, self.max[-1]))
self.stack.append(value)
self.len += 1
def Pop(self):
# empty
if not self.stack:
return None
self.len -= 1
_ = self.max.pop() # discard current max
return self.stack.pop()
def Max(self):
# empty
if not self.max:
return None
return self.max[-1]
def Len(self):
return self.len
|
class Node(object):
def __init__(self, v, n=None):
self.next = n
self.value = v
def __eq__(self, other):
curr = self
while curr.next:
if not curr.value == other.value:
return False
curr = curr.next
other = other.next
return True
def __repr__(self):
out = ""
curr = self
while curr:
out += f"Node({curr.value}) -> "
curr = curr.next
return out + "None"
class Solution(object):
# time complexity linear, space complexity linear (creating new LinkedList)
def naive(self, ll):
if ll is None:
return ll
curr = ll
head = Node(curr.value)
while curr.next:
curr = curr.next
head = Node(curr.value, head)
return head
# time complexity linear, space complexity linear (creating new LinkedList)
def recursion(self, ll):
if ll is None:
return ll
def _helper(ll, acc):
if ll.next is None:
return Node(ll.value, acc)
else:
return _helper(ll.next, Node(ll.value, acc))
return _helper(ll, None)
# time complexity linear, space complexity none because changing pointers inplace
# use 3 pointers (mental trick: point to left)
def inplace(self, ll):
curr = ll
prev = None
while curr is not None:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
return prev
|
Name = input('What is your name?: ')
Favoritefood = input('What is your favorite food?: ')
Swimming = input('What is your favorite place to swim?: ')
print()
print(Name + ' is a small boy ')
print('he likes to eat ' + Favoritefood)
print ('and loves to swim at the', Swimming)
|
from numbers import Number
from rfrac import RationalFrac
class Monomial(dict):
"""
The product of a coefficient and several variables.
Represented as a dictionary from strings, which are
variable names, to integers, which are their degrees.
"""
coefficient: RationalFrac
def __init__(self, coefficient: (Number, RationalFrac), **kwargs: _VT):
super().__init__(**kwargs)
self.coefficient = coefficient
# TODO
def deg(self):
return sum(self.values())
def __lt__(self, other):
"""
true if self.deg() < other.deg(),
or if self.deg() is other.deg() and
self.keys() < other.keys(),
or otherwise if the corresponding items list is less.
"""
if isinstance(other, Monomial):
pass # TODO
else:
return NotImplemented
class Polynomial:
"""
A collection of polynomials
"""
terms: [Monomial, ] = []
def __init__(self):
pass # TODO;
# just testing syntax:
monomial_vars = {'x': 2, 'y': 1, 'z': 0}
for entry in monomial_vars.items():
print(entry)
|
import cv2
path="/home/shishir/study/code/openCV/resource/"
def threshold_img():
img = cv2.imread(f"{path}/crossword.jpg",0)
print(img.shape)
cv2.imshow("raw", img)
## if the pixel in greater then threshold value, it is assigned one value
## else it is assigned another value.cv2.imshow("raw", img)
#if s(x,y) > trunc the s(x,y) = max_val else 0
retVal_binary, binary_img = cv2.threshold(img, 150, 200, type=cv2.THRESH_BINARY)
print("************binary***************")
print(f"min = {binary_img.min()}")
print(f"max = {binary_img.max()}")
#if s(x,y) > trunc the s(x,y) = 0 else max_val
retVal_binary, binary_img_inv = cv2.threshold(img, 150, 200, type=cv2.THRESH_BINARY_INV)
print("************binary inverse***************")
print(f"min = {binary_img_inv.min()}")
print(f"max = {binary_img_inv.max()}")
#if s(x,y) > trunc the s(x,y) = trunc else keep it as it is
retVal_binary, trunc_img = cv2.threshold(img, 170, 255, type=cv2.THRESH_TRUNC)
print("************trunc***************")
print(f"min = {trunc_img.min()}")
print(f"max = {trunc_img.max()}")
# if s(x,y) > trunc keep it as it is else change it to zero, max_val is ignored
retVal_binary, tozero_img = cv2.threshold(img, 170, 255, type=cv2.THRESH_TOZERO)
print("************tozero***************")
print(f"min = {tozero_img.min()}")
print(f"max = {tozero_img.max()}")
# if s(x,y) > trunc change it to zero else keep it as it is, max_val is ignored
retVal_binary, tozero_img_inv = cv2.threshold(img, 170, 255, type=cv2.THRESH_TOZERO_INV)
print("************tozero inverse***************")
print(f"min = {tozero_img_inv.min()}")
print(f"max = {tozero_img_inv.max()}")
cv2.imshow("raw", img)
cv2.imshow("binary", binary_img)
cv2.imshow("binary_inv", binary_img_inv)
cv2.imshow("trunc", trunc_img)
cv2.imshow("tozero_img", tozero_img)
cv2.imshow("tozero_img_inv", tozero_img_inv)
cv2.waitKey(-1)
if __name__ == "__main__":
threshold_img()
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2016 Sumner Evans <[email protected]>
#
# Distributed under terms of the MIT license.
import sys
from matrix import Matrix
def rowreduce(matrix, start_y = 0, start_x = 0):
pivot_found = False
for (i, row) in enumerate(matrix):
if i < start_y: continue
if row[start_x] != 0:
pivot_found = True
# If this isn't the top already, move it to the top
if i != start_y:
matrix.interchange(i, start_y)
matrix.print()
print()
# Make everything under the pivot a zero
for (j, row) in enumerate(matrix):
if j <= start_y: continue
if row[start_x] != 0:
scale = - (row[start_x] / matrix[start_y][start_x])
matrix.replace(scale, start_x, j)
matrix.print()
print()
break
if not pivot_found and start_x < len(matrix[0]) - 1:
rowreduce(matrix, start_y, start_x + 1)
elif start_y < len(matrix) - 1:
rowreduce(matrix, start_y + 1)
if not pivot_found: return
# Pivot Was Found
if matrix[start_y][start_x] != 0:
matrix.scale(start_y, 1 / matrix[start_y][start_x])
for (j, row) in enumerate(matrix):
if j == start_y: return
if row[start_x]:
scale = -(row[start_x] / matrix[start_y][start_x])
matrix.replace(scale, start_x, j)
matrix.print()
print()
print('Welcome to rowreduce')
matrix = Matrix()
matrix.prompt_for_matrix('Type each row of your matrix, separating the entries with a space. ' +
'When you are finished entering your matrix, type "done".')
rowreduce(matrix)
matrix.print()
|
#Write a program split.py, that takes an integer n and a filename as command line arguments and splits the file into multiple small files with each having n lines.
import sys
def split(filename):
n=int(sys.argv[2])
new='file'
f=open(sys.argv[1]).read()
print f
x=1
for lines in range(0,len(f),n):
line=f[lines:lines+n]
new_file=open(new+str(x)+'.txt','w')
new_file.write('\n'.join(line))
new_file.close()
x+=1
split(sys.argv[1])
|
#make a sum function to work for a list of strings to concatinate.
def sum (c):
s=''
for i in c:
s = s+i
return s
c = sum(["hello","world"] )
print c
|
#write a funtionname lensort to sort a list of strings based on length.
def lensort(names):
sort =[]
for i in range(0,len(names)):
temp =""
for j in range(i+1,len(names)):
if len(names[i])>len(names[j]):
temp= names[j]
names[j] = names[i]
names[i] = temp
return names
print lensort(['fdsfjkds','sdfa','adcscd',])
|
#Write a program csv2xls.py that reads a csv file and exports it as Excel file. The prigram should take two arguments. The name of the csv file to read as first argument and the name of the Excel file to write as the second argument.
import tablib
import sys
f = open(sys.argv[1]).readlines()
data = tablib.Dataset()
for i in f:
data.append(i.split(','))
with open(sys.argv[2],'wb') as f:
f.write(data.xls)
|
#Write a function unflatten_dict to do reverse of flatten_dict.
#unflatten_dict({'a': 1, 'b.x': 2, 'b.y': 3, 'c': 4})
#{'a': 1, 'b': {'x': 2, 'y': 3}, 'c': 4}
def unflatten_dict(d):
result = {}
for k in d.keys():
if "." in k:
parent,child = k.split('.',1)
if parent in result.keys():
result[parent].update(unflatten_dict({child:d[k]}))
else:
result.update({parent:unflatten_dict({child:d[k]})})
else:
result.update({k:d[k]})
return result
print unflatten_dict({'a': 1, 'b.x': 2, 'b.y': 3, 'c': 4})
|
# Write a function mutate to compute all words generated by a single mutation on a given word. A mutation is defined as inserting a character, deleting a character, replacing a character, or swapping 2 consecutive characters in a string.
def mutate(word):
a=[]
z=word
s=word
v=word
st =[]
l= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for i in range(len(word)):
word = s[:]
for j in l:
word = s[:]
word[i]= j
a.append(word)
s =v[:]
for i in range(len(s)+1):
for j in range(len(l)):
s =v[:]
s.insert(i,l[j])
a.append(s)
s =z[:]
for i in range(len(s)):
s =z[:]
del s[i]
a.append(s)
s =v[:]
for i in xrange(len(s)):
j =i+1
for j in xrange(len(s)):
s =z[:]
temp = s[i]
s[i] = s[j]
s[j] = temp
a.append(s)
st =[''.join(i) for i in a]
return st
print mutate(['h','e','l','l','o'])
|
#The head and tail commands take a file as argument and prints its first and last 10 lines of the file respectively.
import sys
def head(filename):
temp = open(filename).readlines()
print temp[0:10]
def tail(filename):
temp = len(open(filename).readlines())
z= open(filename).readlines()
print z[temp-10:temp]
print "head is for print first 10 lines"
x =head(sys.argv[1])
print "tail is for print last 10 lines"
y =tail(sys.argv[1])
|
"""
This code is from http://www.youtube.com/watch?v=6n5vW3DhElw.
Thank you for putting this online!
"""
import os, time
seconds = 0
minutes = 0
hours = 0
while seconds <=60:
os.system("cls")
print hours, "Hours", minutes, "Minutes", seconds, "Seconds"
time.sleep(1)
seconds +=1
if seconds == 60:
minutes += 1
seconds = 0
elif minutes ==60:
hours += 1
minutes = 0
seconds = 0
|
import pandas as pd
from math import radians, cos, sin, asin, sqrt
import numpy as np
import random
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
"""
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
def make_distance_matrix(df):
"""
Extracts location from df
:param df: The given data set
:return: A matrix A, the index corresponds to the number of the location and the content is the distance
btw. the locations
"""
A = np.zeros(shape=(df.shape[0], df.shape[0]))
for i, row_i in enumerate(df.itertuples()):
for j, row_j in enumerate(df.itertuples()):
# calculate distance between i and j
A[i][j] = haversine(row_i.Long, row_i.Lat, row_j.Long, row_j.Lat)
return A
def get_visiting_time(df, index):
store_type = df.loc[index].Type
if store_type == "Jumbo":
return 1.5
else:
return 1
def calculate_travel_time(distance):
"""
Calculates the time spent travelling for a specified distance
:param distance: the distance to be travelled
:return: time spent travelling
"""
driving_speed = 80
return distance / driving_speed
def make_list_containing_lists_routes(routes):
"""
Creates a list that contains all routes as a list
:param routes:
:return:
"""
hq_counter = 0
temp_route = []
list_of_lists_of_routes = []
for city in routes:
if city == 0:
hq_counter += 1
temp_route.append(city)
if hq_counter == 2:
list_of_lists_of_routes.append(temp_route)
temp_route = []
hq_counter = 0
else:
temp_route.append(city)
return list_of_lists_of_routes
def are_edges_in_same_route(routes_of_routes, node_a, node_c):
for idx, route in enumerate(routes_of_routes):
if node_a in route and node_c in route:
return True
return False
def recalculate_route(A, route, data):
"""
Recalculates a given route to verify constraints
:param A: distance matrix
:param route: the given route
:param data: data from assignment
:return:
"""
total_travel_time = 0
total_visiting_time = 0
total_km = 0
kms = [0]
current_loc = route[0]
n = len(route)
for idx in range(1, n):
if idx == 1:
next_loc = route[idx]
travel_dist = A[current_loc, next_loc]
travel_time = calculate_travel_time(travel_dist)
visiting_time = get_visiting_time(data, next_loc)
total_travel_time += travel_time
total_travel_time += visiting_time
total_visiting_time += visiting_time
total_km += travel_dist
kms.append(kms[-1] + travel_dist)
current_loc = next_loc
elif idx == n - 1:
next_loc = route[idx]
travel_dist = A[current_loc, next_loc]
travel_time = calculate_travel_time(travel_dist)
total_travel_time += travel_time
total_visiting_time += travel_time
total_km += travel_dist
kms.append(kms[-1] + travel_dist)
current_loc = next_loc
else:
next_loc = route[idx]
travel_dist = A[current_loc, next_loc]
travel_time = calculate_travel_time(travel_dist)
visiting_time = get_visiting_time(data, next_loc)
total_travel_time += travel_time
total_travel_time += visiting_time
total_visiting_time += travel_time
total_visiting_time += visiting_time
total_km += travel_dist
kms.append(kms[-1] + travel_dist)
current_loc = next_loc
if total_visiting_time > 8 or total_travel_time > 10:
return False, -1, []
return True, total_km, kms
def get_old_routes_total_values(A, route_1, route_2, data):
if len(route_2) > 0:
is_valid, total_km_1, kms_1 = recalculate_route(A, route_1, data)
is_valid, total_km_2, kms_2 = recalculate_route(A, route_2, data)
return total_km_1 + total_km_2
else:
is_valid, total_km, kms = recalculate_route(A, route_1, data)
return total_km
def check_swap_two_routes(A, nodeA, nodeC, routes_of_routes, data):
"""
If two nodes from different routes are selected then we build both options of swapping
and then check which one is better and perform exchange if possible
:param A:
:param nodeA:
:param nodeC:
:param routes_of_routes:
:param data:
:return:
"""
route_1 = []
route_nr_a = -1
route_2 = []
route_nr_c = -1
for route in routes_of_routes:
if nodeA in route:
route_1 = route
route_nr_a = routes_of_routes.index(route)
elif nodeC in route:
route_2 = route
route_nr_c = routes_of_routes.index(route)
if len(route_1) > 0 and len(route_2) > 0:
break
idx_a = route_1.index(nodeA)
idx_b = idx_a + 1
idx_c = route_2.index(nodeC)
idx_d = idx_c + 1
# make new route: option 1
new_route_ad = route_1[:idx_a + 1] + route_2[idx_d:]
new_route_bc = route_1[:idx_b - 1:-1] + route_2[idx_c::-1]
# make new route: option 2
new_route_ac = route_1[:idx_a + 1] + route_2[idx_c::-1]
new_route_bd = route_1[:idx_b - 1:-1] + route_2[idx_d:]
# option1
total_km_opt1 = -1
is_option_1_valid = False
is_route_valid_ad, total_km_ad, kms_ad = recalculate_route(A, new_route_ad, data)
is_route_valid_bc, total_km_bc, kms_bc = recalculate_route(A, new_route_bc, data)
if is_route_valid_ad and is_route_valid_bc:
is_option_1_valid = True
total_km_opt1 = total_km_ad + total_km_bc
# option2
total_km_opt2 = -1
is_option_2_valid = False
is_route_valid_ac, total_km_ac, kms_ac = recalculate_route(A, new_route_ac, data)
is_route_valid_bd, total_km_bd, kms_bd = recalculate_route(A, new_route_bd, data)
if is_route_valid_ac and is_route_valid_bd:
is_option_2_valid = True
total_km_opt2 = total_km_ac + total_km_bd
# check if an option is better than the original route.
total_km_old = get_old_routes_total_values(A, route_1, route_2, data)
if is_option_1_valid and total_km_opt1 < total_km_old:
if not is_option_2_valid:
return True, new_route_ad, new_route_bc, route_nr_a, route_nr_c
elif is_option_2_valid and total_km_opt1 < total_km_opt2:
return True, new_route_ad, new_route_bc, route_nr_a, route_nr_c
elif is_option_2_valid and total_km_opt2 < total_km_old:
return True, new_route_ac, new_route_bd, route_nr_a, route_nr_c
else:
return False, [], [], -1, -1
def check_swap_one_route(A, node_a, node_c, routes_of_routes, data):
"""
If two nodes are selected in the same route this method verifies whether a swap can be made
:param A: distance matrix
:param node_a: city 1
:param node_c: city 2
:param routes_of_routes: list of all routes
:param data: data from assignment
:return:
"""
route_ = []
route_nr = -1
for route in routes_of_routes:
if node_a in route:
route_ = route
route_nr = routes_of_routes.index(route_)
break
idx_a = route_.index(node_a)
idx_c = route_.index(node_c)
index_diff = abs(idx_a - idx_c)
new_route = []
if index_diff >= 3:
if idx_a > idx_c:
idx_d = idx_a - 1
new_route = route_[:idx_c + 1] + route_[idx_d:idx_c:-1] + route_[idx_a:]
else:
idx_b = idx_c - 1
new_route = route_[:idx_a + 1] + route_[idx_b: idx_a:-1] + route_[idx_c:]
elif index_diff == 1:
new_route = route_
new_route[idx_a] = node_c
new_route[idx_c] = node_a
elif index_diff == 2:
if idx_a > idx_c:
new_route = route_[:idx_c] + route_[idx_a:idx_c - 1:-1] + route_[idx_a + 1:]
else:
new_route = route_[:idx_a] + route_[idx_c:idx_a - 1:-1] + route_[idx_c + 1:]
if len(new_route) > 0:
is_route_valid, total_km, kms = recalculate_route(A, new_route, data)
total_old_km = get_old_routes_total_values(A, route_, [], data)
if is_route_valid and total_km < total_old_km:
return True, new_route, route_nr
return False, [], -1
def create_data_to_append(new_route_1, route_nr_1, kms_1, new_route_2, route_nr_2, kms_2):
new_data = []
for i in range(len(new_route_1)):
new_data.append([route_nr_1, new_route_1[i], 'city_tbd', kms_1[i], -1])
if len(new_route_2) > 0:
for j in range(len(new_route_2)):
new_data.append([route_nr_2, new_route_2[j], 'city_tbd', kms_2[j], -1])
return new_data
def create_new_df(A, routes_of_routes, data):
total_distance = 0
new_data = []
print(routes_of_routes)
for route_idx in range(len(routes_of_routes)):
route_distance = 0
previous_loc = 0
for loc_idx in range(len(routes_of_routes[route_idx])):
route = routes_of_routes[route_idx]
loc = route[loc_idx]
if loc_idx == 0:
dist = 0
else:
dist = A[previous_loc, loc]
route_distance += dist
total_distance += dist
city_name = data.iat[loc, 1]
previous_loc = loc
new_data.append([route_idx, loc, city_name, route_distance, total_distance])
print('Total distance: {}'.format(total_distance))
return pd.DataFrame(new_data, columns=['Route Nr.', 'City Nr.', 'City Name', 'Total Distance in Route (km)',
'Total distance (km)'])
def two_opt_swap(data, n_iterations):
A = make_distance_matrix(data)
# tabu_matrix = make_tabu_matrix(data)
routes = df['City Nr.'].tolist()
routes_of_routes = make_list_containing_lists_routes(routes)
for i in range(n_iterations):
if i % 1000 == 0:
print('Iteration {}'.format(i))
node_a = random.randint(1, 133)
node_c = random.randint(1, 133)
# makes sure that there is no invalid index to get an index out of range exception
# or edges to swap are the same
if node_a == node_c:
continue
# Basically if the km are lower for routes in total the swap can be made
# but also the whole time needs to be still in the 8 visit and 10 john work time
if are_edges_in_same_route(routes_of_routes, node_a, node_c):
is_swap_good, new_route, route_nr = check_swap_one_route(A, node_a, node_c, routes_of_routes, data)
if is_swap_good:
routes_of_routes[route_nr] = new_route
else:
is_swap_good, new_route_1, new_route_2, route_nr_1, route_nr_2 = check_swap_two_routes(A, node_a, node_c,
routes_of_routes,
data)
if is_swap_good:
routes_of_routes[route_nr_1] = new_route_1
routes_of_routes[route_nr_2] = new_route_2
return create_new_df(A, routes_of_routes, data)
df = pd.read_excel('Ex2.1-2025115.xls')
data = pd.read_excel('Data Excercise 2 - EMTE stores - BA 2019.xlsx')
n_iterations = 50000
output_df = two_opt_swap(data, n_iterations)
output_df.to_excel('Ex2.2-2025115.xls', index=False)
|
import numpy as np
import matplotlib.pyplot as plt
def corner_squares(ax,n,p):
if n>0:
i1 = [1,2,3,0,1]
ax.plot(p[:,0],p[:,1],color='k')
q = -250 + p[i1]*.5 #coordinates for bottom left
corner_squares(ax,n-1,q)
q = 750 + p[i1]*.5 #coordinate for top right
corner_squares(ax,n-1,q)
q = [-250, 750] + p[i1]*.5 #coordinate for top left
corner_squares(ax,n-1,q)
q = [750, -250] + p[i1]*.5 #coordinate for bottom right
corner_squares(ax,n-1,q)
plt.close("all")
base = 1000 #Creates the base size of the square
p = np.array([[0,0], [0, base], [base, base], [base, 0], [0, 0]])
fig, ax = plt.subplots()
corner_squares(ax, 4, p)
ax.set_aspect(1.0)
ax.axis('off')
plt.show()
fig.savefig('squares.png')
#n = number of squares
#p = coordinates/lines to make the square
#w- percantage at which the new points are chosen
|
def encrypt(key, msg):
encryped = []
for i, c in enumerate(msg):
key_c = ord(key[i % len(key)])
msg_c = ord(c)
encryped.append(chr((msg_c + key_c) % 127))
return ''.join(encryped)
def decrypt(key, encryped):
msg = []
for i, c in enumerate(encryped):
key_c = ord(key[i % len(key)])
enc_c = ord(c)
msg.append(chr((enc_c - key_c) % 127))
return ''.join(msg)
def lerPalavraPasse(ficheiro):
file = open(ficheiro,"r")
return decrypt("Programando_com_Andre_Youtube_2.0",file.read())
def criarPalavraPasse():
file = open("password.txt","w")
palavraPasse = ""
repeticao = ""
while repeticao == "" and palavraPasse == "":
palavraPasse = input("Digite a palavra passe: ")
repeticao = input("Digite novamente a palavra passe: ")
if palavraPasse == repeticao:
encrypted = encrypt("Programando_com_Andre_Youtube_2.0",palavraPasse)
file.write(encrypted)
return palavraPasse
else:
palavraPasse = ""
repeticao = ""
password = ""
try:
password = lerPalavraPasse("password.txt")
except(FileNotFoundError):
password = criarPalavraPasse()
palavraPass = ""
while password != palavraPass:
palavraPass = input("Digite a sua palavra passe")
if palavraPass != password:
print("Palavra Passe errada")
print("Bem vindo")
|
n=input("Enter the value of 'n': ")
num=float(n)
s=((2*num+1)*num*(num+1))/6
sum=str(s)
print("The total sum is "+sum)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.