text
stringlengths 37
1.41M
|
---|
import time
def convert_timestamp(time_string):
"""
Convert a string timestamp to a python time object.
:param time_string: Timestamp from 'time' column in data_raw sheet.
:return: Time object representing provided timestamp.
"""
return time.strptime(time_string, '%H:%M:%S.%f')
def compose_timestamp(min, sec, millis):
"""
Create a timestamp from the minute, second, and millisecond columns of a csv.
:param min: Minute to add to the timestamp.
:param sec: Second to add to the timestamp
:param millis: Millisecond to add to the timestamp.
:return: Timestamp formatted to reflect the 'time' column of provided CSV files.
"""
stamp = ('00:0%s:' % min) if int(min) <= 9 else ('00:%s:' % min) # Add minute
stamp += ('0%s' % sec) if int(sec) <=9 else str(sec) # Add second
stamp += '.'
for s in range(3-len(str(millis).strip())):
stamp += '0'
stamp += str(millis).strip() # Add millisecond
return stamp
|
# !/bin/python3
import os
import sys
# Problem taken from hackerrank
# Link: https://www.hackerrank.com/challenges/drawing-book/problem
#
# Complete the pageCount function below.
#
def pageCount(n, p):
page_turns = 0
if n in [2, 3]:
return page_turns
page_turns = n // 2 + 1
pt_from_start_untill_p = 1 + p // 2
percentage_of_p_from_page_turns = p / n
if percentage_of_p_from_page_turns > 0.5:
return page_turns - pt_from_start_untill_p
else:
return pt_from_start_untill_p - 1
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
p = int(input())
result = pageCount(n, p)
fptr.write(str(result) + '\n')
fptr.close()
|
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the countingValleys function below.
def countingValleys(n, s):
sea_level = 0
valleys_crossed = 0
is_in_valley = False
for char in s:
if char == 'D':
sea_level -= 1
else:
sea_level += 1
if sea_level < 0:
is_in_valley = True
if sea_level == 0 and is_in_valley:
valleys_crossed += 1
is_in_valley = False
return valleys_crossed
if __name__ == '__main__':
n = 12
s = "DDUUDDUDUUUD"
result = countingValleys(n, s)
print(result)
|
# input
n = 10
x = "3 7 8 5 12 14 21 13 50 18".split(" ")
# Step 1: get the input
# n = int(input())
# x = input().split(" ")
# Step 2: transform and sort values
xlist = [int(i) for i in x]
xlist.sort()
# Step 3: find the median
def findm(lval):
if lval:
if len(lval) % 2 == 1:
return lval[len(lval) // 2]
elif len(lval) % 2 == 0:
return sum(lval[len(lval) // 2 - 1: len(lval) // 2 + 1]) // 2
else:
return None
# Step 4: calculate the quartiles
def calcq(nval, lval):
if nval > 0 and nval == len(lval):
if len(lval) % 2 == 1:
q1 = findm(lval[:lval.index(findm(lval))])
q2 = findm(lval)
q3 = findm(lval[lval.index(findm(lval) + 1):])
print(q1, q2, q3, sep='\n')
else:
first_half = lval[:len(lval) // 2]
second_half = lval[len(lval) // 2:]
q1 = findm(first_half)
q2 = findm(lval)
q3 = findm(second_half)
print(q1, q2, q3, sep='\n')
# Step 4: output
calcq(n, xlist)
|
def swap_case(s):
output = []
if 0 < len(s) <= 1000:
for c in s:
if c.isalpha() and c.isupper():
output.append(c.lower())
elif c.isalpha and c.islower():
output.append(c.upper())
else:
output.append(c)
return ''.join(output)
if __name__ == '__main__':
s = input()
result = swap_case(s)
print(result)
|
if __name__ == '__main__':
N = int(input())
data = []
commands = ['insert', 'print', 'remove', 'append', 'sort', 'pop', 'reverse',]
for _ in range(N):
com = input().split()
if com[0] in commands and len(com) == 3:
eval("data."+ com[0] + "(" + com[1] + "," + com[2] +")" )
elif com[0] in commands and len(com) == 2:
eval("data."+ com[0] + "(" + com[1] + ")")
elif com[0] == "print":
print(data)
else:
eval("data."+ com[0] + "(" + ")")
|
def first_not_repeating_character(s):
d = {}
for char in s:
if char not in d:
d[char] = 0
d[char] += 1
for key in d:
if d[key] == 1:
return key
return "_"
|
import math
def distance(a=(0, 0), b=(0, 0)):
"""Returns the distance between two points"""
return math.sqrt((a[0] - b[0]) ** 2 +
(a[1] - b[1]) ** 2)
|
import numpy as np
import matplotlib.pyplot as plt
def plotMeanVsN():
"""
For different values of N, sample N uniformly random numbers in [0, 1) and
plot their mean. Demonstrates the central limit theorem, which says that
as N gets larger, the distribution of the sum (or mean) of the variables
approach a normal distribution
"""
NumTrials = 1000
# Vary the sample size
for N in [1, 2, 10]:
# Sample N random numbers and then find their mean
samples = [sum(np.random.random_sample(N)) / N for i in xrange(NumTrials)]
plt.hist(samples, label="N = {0}".format(N), alpha=0.8)
plt.legend()
plt.show()
if __name__ == "__main__":
plotMeanVsN()
|
import sys
def add(a, b):
try:
a = int(a)
b = int(b)
return a + b
except ValueError:
return "Invalid arguments"
try:
print(add(sys.argv[1], sys.argv[2]))
except IndexError:
print("Not enough arguments")
|
# avery cunningham
# Scrooge McDuck's Bank
class Bank:
def __init__(self, name, accounts, owner):
self.name = name
self.accounts = accounts
self.owner = owner
def withdraw(self, account, amount):
print(f"{account.name} is withdrawing ${amount}")
if amount > 0.1 * account.balance:
print("transaction unsuccessful, insufficient account balance")
account.withdraw(5)
account.penalties += 1
else:
account.withdraw(amount)
for a in self.accounts:
if a is not account and a is not self.owner:
self.owner.withdraw(amount)
a.deposit(amount)
print(self)
def __str__(self):
s = f"Here are the current account balances in {self.name}:\n"
for a in self.accounts:
s += a.__str__() + "\n"
return s
class Account:
def __init__(self, accountNumber, name, balance=0):
self.accountNumber = accountNumber
self.name = name
self.balance = balance
self.deposits = 0
self.withdrawls = 0
self.penalties = 0
def deposit(self, amount):
self.balance += amount
self.deposits += 1
def withdraw(self, amount):
self.balance -= amount
self.withdrawls += 1
def __str__(self):
s = f"{self.name}'s account #{self.accountNumber} has a balance of ${self.balance}, {self.penalties} penalties, {self.deposits} deposits, and {self.withdrawls} withdrawls"
return s
huey = Account(accountNumber=700007, name="Huey Duck", balance=150)
dewey = Account(accountNumber=800008, name="Dewey Duck", balance=350)
louie = Account(accountNumber=900009, name="Louie Duck", balance=25)
scrooge = Account(accountNumber=100001, name="Scrooge McDuck", balance=1000000)
bank = Bank(name="Scrooge's bank",
accounts=[huey, dewey, louie, scrooge],
owner=scrooge)
print("Initial values:\n")
print(bank)
bank.withdraw(account=louie, amount=2)
bank.withdraw(account=dewey, amount=20)
bank.withdraw(account=huey, amount=20)
bank.withdraw(account=louie, amount=10)
bank.withdraw(account=dewey, amount=20)
bank.withdraw(account=huey, amount=30)
bank.withdraw(account=louie, amount=40)
|
"""
Description:
- A class to define its structure
- A class to define its functionality
"""
from builtins import len
class Node:
def __init__(self, data=None, prev=None, next=None):
self.prev = prev
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def print(self):
if self.head is None:
print("LinkedList is empty")
return
itr = self.head
lout = ''
while itr:
lout += str(itr.data) + " <=> " if itr.next else str(itr.data)
itr = itr.next
print(lout)
def print_forward(self):
print("Welcome!")
if self.head is None:
print("Linked list is empty")
return
itr = self.head
llstr = ''
while itr:
llstr += str(itr.data) + ' -> '
itr = itr.next
print(llstr)
def get_last_node(self):
itr = self.head
while itr.next:
itr = itr.next
return itr
def print_backward(self):
last_node = self.get_last_node()
itr = last_node
lout = ''
while itr:
lout += str(itr.data) + '->' if itr.prev else str(itr.data)
itr = itr.prev
print(lout)
def get_length(self):
count = 0
itr = self.head
while itr:
count += 1
itr = itr.next
return count
def insert_at_begin(self, data):
node = Node(data, None, None)
self.head = node
def insert_at(self, data, index):
if index < 0 or index > self.get_length():
raise Exception("Invalid index")
if index == 0:
self.insert_at_begin(data)
itr = self.head
count = 0
while itr:
if count == index - 1:
node = Node(data, itr, itr.next)
if itr.next:
itr.next.next.prev = node
itr.next = node
break
count += 1
itr = itr.next
def append(self, data):
if self.head is None:
self.head = Node(data, None, None)
return
itr = self.head
while itr.next:
itr = itr.next
node = Node(data, itr, None)
itr.next = node
def insert_values(self, values):
self.head = None
if len(values) < 1:
print("Empty values were passed")
return
for item in values:
self.append(item)
def remove(self, index):
if index < 0 or index > self.get_length():
raise Exception("Invalid index")
count = 0
itr = self.head
while itr:
if count == index - 1:
itr.next = itr.next.next
itr.next.next.prev = itr
count += 1
itr = itr.next
if __name__ == "__main__":
ll = LinkedList()
ll.insert_values(["banana", "mango", "grapes", "orange"])
ll.print()
ll.print_forward()
ll.print_backward()
|
N = int(input())
S = input()
count = 0
ans = 0
for n in S:
if n == "A":
count = 1
elif count == 1 and n == "B":
count += 1
elif count == 2 and n == "C":
ans += 1
count = 0
else:
count = 0
print(ans)
|
print("hello world good good study day day up")
# 注释:int整数类型:不带引号的阿拉伯数字的整数 作用:可以做数学运算
# num1=10
# num2=22
# print(num1+num2+12)
# float字符数
|
def product(par1, par2):
a = 1
b = 2
# print("-" * a)
c = par1(a, b)
d = par2(a, b)
result = c * d
print(result)
# print("-" * b)
product(lambda a, b: a + b, lambda a, b: a ** b)
product(lambda a, b: a - b, lambda a, b: a / b)
product(lambda a, b: a ^ b, lambda a, b: a % b)
|
# i = 0
# while i <= 3:
# print(i)
# i += 1
# i = 0
# result = 0
# while i <= 10:
# result = result + 2
# i += 1
# print(result)
# i = 1
# result = 0
# while i <= 10:
# result = result + 2
# i += 2
# print(result)
|
def bubbleSort(array):
"""冒泡排序"""
for i in range(len(array) - 1, -1, -1):
for j in range(i):
if array[j] > array[j + 1]:
array[j], array[j + 1] = array[j + 1], array[j]
return[array]
array1 = [2, 1, 5, 3, 8, 1, 2, 3, 9, 4, 2]
print(bubbleSort(array1))
def FindSmall(list):
"""找到最小元素"""
min = list[0]
for i in range(len(list)):
if list[i] < min:
min = list[i]
return min
def Select_Sort(list):
"""选择排序"""
newArr = []
for i in range(len(list)):
minValue = FindSmall(list)
newArr.append(minValue)
list.remove(minValue)
return newArr
testArr = [2, 5, 7, 1, 8, 3, 6, 9, 2]
print(Select_Sort(testArr))
def Quick_Sort(list):
"""快速排序"""
if len(list) < 2:
return list
else:
temp = list[0]
less = [i for i in list[1:] if i <= temp]
more = [i for i in list[1:] if i > temp]
return Quick_Sort(less) + [temp] + Quick_Sort(more)
testArr = [13, 14, 12, 21, 5, 31, 11]
print(Quick_Sort(testArr))
# def Item_Search(list, item):
# low = 0
# high = len(list - 1)
# while low <= high:
# middle = (low + high) // 2
# print(list[middle])
# if list[middle] > item:
# high = middle - 1
# elif list[middle] < item:
# low = middle + 1
# else:
# return middle
# return None
#
# test_list = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21]
# Item_Search(test_list, 11)
# 广度优先搜索
# graph = {}
# graph["you"] = ["Alice", "Bob", "Claire"]
# graph["Bob"] = ["Anuj", "peggy"]
# graph["Alice"] = ["Peggy"]
# graph["Claire"] = ["Tom", "Jonny"]
# graph["Anuj"] = []
# graph["Peggy"] = []
# graph["Tom"] = []
# graph["Jonny"] = []
# from collections import deque
# def person_is_seller(name):
# return name == "Tom"
# def Search(name):
# Searched = []
# search_queue = deque()
# search_queue += graph[name]
# while search_queue:
# person = search_queue.popleft()
# if not person in Searched:
# if person_is_seller(person):
# print("ther seller is {0} ".format(person))
# return True
# else:
# search_queue += graph[person]
# Searched.append(person)
# return False
#
#
# print(Search("you"))
|
class Dog:
name = "旺财"
def __init__(self):
self.name = "来福"
@staticmethod
def eat():
print("牛来福在吃东西") # 无法调用类属性
@staticmethod
def eat():
print("牛来福在吃旺财!")
@classmethod
def eat(cls):
print(f"{cls.name}在吃东西")
dog1 = Dog
print(dog1.name)
dog1.eat()
dog1 = Dog()
print(dog1.name)
dog1.eat()
|
"""
1、青蛙跳台阶问题
一只青蛙要跳上 n 层高的台阶,一次能跳一级,也可以跳两级,请问这只青蛙有多少种跳上这个 n
层高台阶的方法?
思路分析:
方法 1:递归
设青蛙跳上 n 级台阶有 f(n)种方法,把这 n 种方法分为两大类,第一种最后一次跳了一级台阶,这
类方法共有 f(n-1)种,第二种最后一次跳了两级台阶,这种方法共有 f(n-2)种,则得出递推公式
f(n)=f(n-1)+f(n-2),显然,f(1)=1,f(2)=2,递推公式如下:
* 这种方法虽然代码简单,但效率低,会超出时间上限*
代码实现如下:
"""
class Solution(object):
# @param:{integer} n
# @return:{integer}
def climbStairs(self, n):
if n == 1 or n == 2:
return n
else:
return self.climbStairs(n - 1) + self.climbStairs(n - 2)
class Solution2(object):
# @param:{integer} n
# @return:{integer}
def climbStairs(self, n):
if n == 1 or n == 2:
return n
a, b, c = 1, 2, 3
for i in range(3, n + 1):
c = a + b
a = b
b = c
return c
class Solution3(object):
def climbStairs(self, n):
def fact(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
total = 0
for i in range(int(n / 2 + 1)):
total += int(fact(i + n - 2 * i) / fact(i) / fact(n - 2 * i))
return total
class Solution4(object):
# @param n, an integer
# @return an integer
def climbStairs(self, n):
if n <= 1:
return 1
arr = [1, 1, 0] # look here, arr[0] = 1, arr[1] = 2
for i in range(2, n + 1):
arr[2] = arr[0] + arr[1]
arr[0], arr[1] = arr[1], arr[2]
return arr[2]
if __name__ == "__main__":
# a = Solution()
# b = a.climbStairs(10)
# print(b)
# a = Solution2()
# c = a.climbStairs(10)
# print(c)
a = Solution3()
c = a.climbStairs(10)
print(c)
|
# .定义一个Person类
#
# 1)属性:姓名name,体重weight
#
# 2)方法:init方法
#
# 2.创建四个对象("牛一",60 ; "陈二",55 ; "张三",70 ; "王五",65 ),将这四个对象添加到列表。
#
# 3.获取60-70之间的随机数作为体重标准线(包含60和70),遍历列表将体重大于等于体重标准线的元素写入健康体重名单health.txt。格式如下:
#
# 姓名:牛一 体重:60 状态:健康
# 姓名:张三 体重:70 状态:健康
#
# 姓名:王五 体重:65 状态:健康
import random
class Person:
def __init__(self, name, weight):
self.name = name
self.weight = weight
def information(self):
return f"'姓名':{self.name},'体重':{self.weight}"
class Health:
def __init__(self):
self.health_weight = random.randint(60, 70)
self.person_list = []
def add_person(self, person):
self.person_list.append(person.information)
print(self.person_list)
def remove_person(self):
for value in self.person_list:
if value['weight'] < self.health_weight:
self.person_list.remove(value)
else:
return
# def save_person(self):
# with open("")
# def copration(self):
# while True:
# self.add_person(self, person)
#
# class Health:
# def __init__(self):
# self.health_weight = random.randint(60, 70)
# self.person_list = []
#
# def add_person(self, person):
# self.person_list.append(person)
# print(self.person_list)
# for value in self.people_list:
# if value['weight'] >= self.health_weight:
# with open("health.txt", "a") as w:
# w.write(value)
#
# def __str__(self):
# return f"{'、'.join(self.person_list)}, 状态:健康"
#
#
# person1 = Person("牛一", 60)
# person2 = Person("陈二", 55)
# person3 = Person("张三", 70)
# person4 = Person("王五", 65)
# health = Health()
# health.add_people(person1)
# print(health)
|
# [[0~10] * 10]
print([x * 11 for x in range(10)])
"""Python一行代码实现九九乘法表"""
print('\n'.join(' '.join(['%sX%s=%-2s' % (y, x, x * y) for y in range(1, x + 1)]) for x in range(1, 10)))
"""[0~10]以索引分别打印奇偶数列表"""
a = [i for i in range(10)]
print(f"原数列:{a}\n偶数列:{a[::2]}\n奇数列:{a[1::2]}")
"""一行打印[[1, 2, 3]...[100, 101, 102]]"""
print([[x for x in range(1, 103)][i:i + 3] for i in range(0, 102, 3)])
# 二维列表转置
"""[[1, 2, 3], [4, 5, 6], [7, 8, 9]] >> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]"""
a_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
t = [i for i in a_list]
print([[i[j] for i in a_list] for j in range(len(a_list[0]))])
"""[1, 7, 19...28519, 29107, 29701]"""
list3 = [x**3 - (x-1)**3 for x in range(1, 101)]
print(list3)
import random
import cProfile
def f1(lIn):
l1 = sorted(lIn)
l2 = [i for i in l1 if i< 0.5]
return [i * i for i in l2]
def f2(lIn):
l1 = [i for i in lIn if i < 0.5]
l2 = sorted(l1)
return [i * i for i in l2]
def f3(lIn):
l1 = [i * i for i in lIn]
l2 = sorted(l1)
return [i for i in l1 if i < (0.5 * 0.5)]
lIn = [random.random() for i in range(100000)]
cProfile.run('f1(lIn)')
cProfile.run('f2(lIn)')
cProfile.run('f3(lIn)')
def a():
alist = []
for i in range(1, 100):
if i % 6 == 0:
alist.append(i)
last_num = alist[-3:]
return last_num
result = a()
print(result)
|
# 生成器
# <class 'generator'>
x = (x for x in range(10))
print(f"{x}\n{type(x)}")
# # create a generator
def createGenerator():
mylist = range(4)
for i in mylist:
yield i * i
mygenerator = createGenerator() # create a generator
print(mygenerator) # mygenerator is an generator object
for i in mygenerator:
print(i)
# >> [0, 2, 4, 6]
def multipliers():
# return [lambda x: i * x for i in range(4)]
# return [lambda x, i=i: i * x for i in range(4)]
for i in range(4):
yield lambda x: i * x
print([m(2) for m in multipliers()])
def func(values):
for value in values:
print(f"func:{value}")
yield value
import sys
def fibonacci(n):
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield
a, b = b, a + b
counter += 1
f = fibonacci(10)
while True:
try:
print(next(f), end=" ")
except StopIteration:
sys.exit()
# def triangle():
# _list, new_list = [], []
# while True:
# length = len(_list)
# if length == 0:
# new_list.append(1)
# else:
# for times in range(length + 1):
# if times == 0:
# new_list.append(1)
# elif times == length:
# new_list.append(1)
# else:
# times = _list[times - 1] + _list[times]
# new_list.append(times)
# yield new_list
# _list = new_list.copy()
# new_list.clear()
|
"""
输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
"""
sort = input("input a string:\n")
letters = 0
space = 0
digit = 0
others = 0
for c in sort:
if c.isalpha():
letters += 1
elif c.isspace():
space += 1
elif c.isdigit():
digit += 1
else:
others += 1
print(f"char:{letters}\nspace:{space}\ndigit:{digit}\nothers{others}")
|
# encoding:utf-8
def my_function(func):
a = 100
b = 200
# 把 cucalate_rule 当做函数来调用
result = func(a, b)
print('result:', result)
my_function(lambda a, b: a / b)
my_function(lambda a, b: a // b)
my_function(lambda a, b: a % b)
# ---
import functools
list2 = []
list2.append(functools.reduce(lambda i, j: j**3 - i**3, range(2)))
print(list2)
|
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# read csv file
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2]
y = dataset.iloc[:, 2]
# linear regression classifier
from sklearn.linear_model import LinearRegression
linear_reg = LinearRegression()
linear_reg.fit(X, y)
# plot
plt.scatter(X, y, color='r')
plt.plot(X, linear_reg.predict(X), color='g')
plt.title('Linear Regression')
plt.xlabel('Position level')
plt.ylabel('Slary')
plt.show()
|
d={'name': 'ahsan', 'job': 'pythonista', 'level': 'intermediate'}
if 'name' in d:
print("Name exists in dictionary with value : ", d.get('name', ''))
|
d={'english':0, 'urdu': 0, 'computer science': 0, 'geography': 0, 'history': 0}
for k in d:
marks=int(input(f"Enter marks for {k}: "))
d[k]= marks
print("Results")
for k in d:
print(f"{k} : {d[k]}")
print("Total :", sum(d.values(1)) )
|
from functions import square
for i in range(10):
print("The square of", i, "is", square(i))
|
class Game:
player_choice = int(input("Enter your choice "))
def __init__(self,name,health,attack,heal):
self.name = name
self.health = health
self.attack = attack
self.heal = heal
def player_action(self):
print("Rock...")
print("Paper...")
print("Scissors")
return ("--" * 7)
def player_info(self):
return f"{self.name} {self.health} {self.attack} {self.heal}"
def attack(self):
if player_choice == 1:
self.health -= 10
return f"{health}"
player1 = Game("Ajayi",100,12,10)
player2 = Game("Max", 100,12,10)
print(player1.player_action())
print(player1.player_info())
print(player2.attack())
|
import math
def is_prime(number):
#small_number = int(math.ceil(number**.5))
small_number = number
i=2
while i<small_number:
if (number%i==0):
return False
i = i + 1
return True
def next_prime(number):
it = number+1
while not(is_prime(it)):
it = it + 1
return it
def primes_before(number):
cont = 3
while cont < number:
if is_prime(cont):
print cont
cont = cont + 2
def mark(number, crivo):
len_crivo = len(crivo)
i=number
while i < len_crivo-number:
i = i + number
if crivo[i]:
crivo[i] = False
return crivo
def exec_crivo(number):
crivo = [True for x in xrange (number+1)] #testar xrange e range
crivo[0]=False
crivo[1]=False
len_crivo = len(crivo)+1
#print ':' +
i=2
while i <= int(math.ceil(number**.5)):
crivo_ = mark(i,crivo)
i = i + 1
return crivo
def print_crivo(crivo):
i=0
while i<len(crivo):
if crivo[i] == True:
print i
i = i + 1
def sum_crivo(crivo):
i=0
soma=0
while i<len(crivo):
if crivo[i] == True:
soma = soma + i
i = i + 1
return soma
crivo = exec_crivo(100000000)
#mark(2, crivo)
#mark(3, crivo)
#print crivo
print_crivo(crivo)
print sum_crivo(crivo)
|
"""import pyxel
import random
pyxel.cls(0)
HEIGHT = 256
WIDTH = 256
lemmings = [] #ver si dejar o no
timer = 8 #ver si dejar o no
interval = 10
# The first thing to do is to create the screen, see API for more parameters
pyxel.init(HEIGHT, WIDTH, caption="Lemmings Game",scale=2)
pyxel.load("assets/my_resource.pyxres")
grid = [[], []]
# To start the game we invoke the run method with the update and draw functions
pyxel.run(update, draw)"""
#from classes.Board import Board
#import pyxel
#from classes.Lemmin import Lemming
#if __name__== "__main__":
# WIDTH = 256
# HEIGHT = 256
# timer = 10
# interval = 10
# CAPTION = "Lemmings Project"
# pyxel.init(WIDTH,HEIGHT, caption=CAPTION, scale=2)
# pyxel.load("my_resource.pyxres")
# Board()
# Lemming(10)
import pyxel
import random
import time
from classes.Ladder import Ladder
from classes.Lemmin import Lemming
from classes.platform import Platform
class App:
def __init__(self):
pyxel.init(256, 256,fps=6)
pyxel.load("assets/my_resource.pyxres")
#random.randint(0, 3)
self.grid = [[0 for y in range(0, 256, 14)] for x in range(0, 256, 16)]
#aqui abajo podria ir el lemming
self.cursor_x = 0
self.cursor_y= 0
self.door_x=0
self.door_y=0
self.lemmings = []
self.max_lemming = 10
self.count = 0
# ground, ceiling and walls
for x in range(16):
self.grid[x][15] = 1
self.grid[x][0] = 1
for y in range(16):
self.grid[15][y] = 1
self.grid[0][y] = 1
#making an opening at the top where the lemming will start
#self.grid[0][0] = 0
#self.grid[1][0] = 0
#self.grid[0][1] = 0
#self.grid[1][1] = 0
self.base_time = time.time()
pl = Platform(self.grid)
pl.create()
self.door(pl.x_start,pl.x_end,pl.y, pl.n)
#El run tiene que ir despues para coger los cambios del grid
pyxel.run(self.update, self.draw)
#CREAR HUECO ALEATORIA
#plataformas tienen valor 2
# def platform(self):
# count = 0
# x_index = []
# y_index = []
# platforms_sizes = []
# while count <7:
# # 14 espacios libres (contando paredes) y max blockques de 11
# j = random.randint(1, 14)
# platform_size = random.randint(5, 11)
# i = random.randint(1, 14-platform_size)
#
# #to avoid repeated places. The grid i j == 0 is to avoid blocking the entrace
# if i not in x_index and j not in y_index and self.grid[i][j]==0:
# x_index.append(i)
# y_index.append(j)
# platforms_sizes.append(platform_size)
# count+=1
# for x in range(16):
# #To place the platform. starts at i and ends at the i+random length
# if x >=i and x <=i+platform_size:
# self.grid[x][j] = 2
#
#
# return list(zip(x_index,y_index,platforms_sizes))
def door(self, pl_start,pl_end, y,n_platforms):
count = 0
while count < 2:
#random platform
platform_index = random.randint(0,n_platforms-1)#number platforms
door_coord_x = random.randint(pl_start[platform_index], pl_end[platform_index])
door_coord_y = y[platform_index]
#We only save the coords of the main door
if count ==0:
self.door_x = door_coord_x
self.door_y = door_coord_y
if self.grid[door_coord_x][door_coord_y-1] == 0:
if count==0:
self.grid[door_coord_x][door_coord_y - 1] = 3
else:
self.grid[door_coord_x][door_coord_y-1] = 4
count+=1
def update(self):
#first lemming
if self.count == 0:
self.lemmings.append(Lemming(self.door_x, self.door_y - 1, self.grid))
self.count +=1
#Lemming created in intervals
if int(time.time())-int(self.base_time) == 3 and len(self.lemmings)<self.max_lemming:
self.lemmings.append(Lemming(self.door_x, self.door_y - 1, self.grid))
self.base_time= time.time()
for n in range(len(self.lemmings)):
if self.lemmings[n].is_dead == True:
self.lemmings.pop(n)
elif self.lemmings[n].is_saved == True:
self.lemmings.pop(n)
else:
self.lemmings[n].update()
def draw_cursor(self,direction):
#if self.cursor_x + right < 16 and self.cursor_y + down <= 16 and self.cursor_x - left > 0 and self.cursor_y - up > 0:
up = self.cursor_y - 1
down = self.cursor_y + 1
left = self.cursor_x - 1
right = self.cursor_x + 1
if direction == "up" and up >= 0:
self.cursor_y = up
elif direction == "down" and down < 16:
self.cursor_y = down
elif direction == "left" and left >= 0:
self.cursor_x = left
elif direction == "right" and right < 16:
self.cursor_x = right
pyxel.blt(16 * self.cursor_x, 16 * self.cursor_y, 0, 16, 16, 16, 16)
def move_cursor(self):
if pyxel.btn(pyxel.KEY_UP):
App.draw_cursor(self,"up")
elif pyxel.btn(pyxel.KEY_DOWN):
App.draw_cursor(self, "down")
elif pyxel.btn(pyxel.KEY_LEFT):
App.draw_cursor(self, "left")
elif pyxel.btn(pyxel.KEY_RIGHT):
App.draw_cursor(self, "right")
def place_tool(self):
if self.grid[self.cursor_x][self.cursor_y] == 0:
#left to right Ladder
if pyxel.btn(pyxel.KEY_X):
Ladder(self.cursor_x, self.cursor_y, self.grid).draw_first_ladder()
#right to left ladder
elif pyxel.btn(pyxel.KEY_C):
Ladder(self.cursor_x, self.cursor_y,self.grid).draw_second_ladder()
#Umbrella
elif pyxel.btn(pyxel.KEY_V):
print("Umbrella")
#blocker
elif pyxel.btn(pyxel.KEY_B):
print("blocker")
def draw(self):
pyxel.cls(0)
for x in range(16):
for y in range(16):
if self.grid[x][y]==1:
#*16 because 1 square is 16 cells
pyxel.blt(16*x, 16*y,0,0,0,16,16)
#platform
elif self.grid[x][y]==2:
pyxel.blt(16 * x, 16 * y, 0, 16, 0, 16, 16)
#main door
elif self.grid[x][y]==3:
pyxel.blt(16 * x, 16 * y, 0, 32, 0, 16, 16)
# exit door
elif self.grid[x][y] == 4:
pyxel.blt(16 * x, 16 * y, 0, 0, 16, 16, 16)
#ladder
elif self.grid[x][y] == 5:
pyxel.blt(16 * x, 16 * y, 0, 32, 16, 16, 16)
elif self.grid[x][y] == 6:
pyxel.blt(16 * x, 16 * y, 0, 48, 16, 16, 16)
App.move_cursor(self)
App.place_tool(self)
for n in range(len(self.lemmings)):
self.lemmings[n].draw_lemming()
#for i in self.platform():
#if self.grid[x][y] == 0 and x + len(i) <y:
#pyxel.rect(self.x, 0, 6, 6, 9)
App()
|
"""
To run this script:
python shoppingCost.py
If you run the above script, a correct calculateShoppingCost function should return:
The final cost for our shopping cart is 35.58
"""
import csv
def calculateShoppingCost(productPrices, shoppingCart):
finalCost = 0
"*** Add your code in here ***"
for item in shoppingCart:
finalCost = finalCost + (float(shoppingCart[item]) * float(productPrices[item]))
return finalCost
def createPricesDict(filename):
productPrice = {}
"*** Add your code in here ***"
inputFile = csv.reader(open(filename, 'r'))
for row in inputFile:
i,j = row
productPrice[i] = j
return productPrice
if __name__ == '__main__':
prices = createPricesDict("Grocery.csv")
myCart = {"Bacon": 2,
"Homogenized milk": 1,
"Eggs": 5}
print("The final cost for our shopping cart is {}".format(calculateShoppingCost(prices, myCart)))
|
game_chosen=0
begin_game=0
running=0
while True:
while begin_game!=1:
print("play (1) motorman(one player) (2) Dungeon(one player) (3) Shop'n'Stab(one player) (4)Duel(two player)")
game_chosen=input("what to play... ")
if game_chosen==1 or 2:
begin_game=1
running=1
if game_chosen==1:
import sys, pygame, pygame.mixer
from pygame.locals import *
import random
import time
print("'You must hunt down the beast that has plauged this land, do so using arrow keys or A and D to accelerate or decellerate, use space to fire, take cation in doing so as it will prevent you from speeding up'")
print("(1)easy,(2)medium,(3)hard,(4)NIGHTMARE")
difficulty=input()
pygame.init()
pygame.key.set_repeat(25,25)
person = pygame.image.load("motorman.png")
deamon=pygame.image.load("deamon.png")
bullet=pygame.image.load("bullet.png")
ex=pygame.image.load("caution.png")
doom=pygame.image.load("doom.png")
go=0
dx=670
dy=100
posx=200
posy=460
bx=800
if difficulty==1 and go<1:
bh=random.randrange(10,20)
r1=12
r2=29
if difficulty==2 and go<1:
bh=random.randrange(20,30)
r1=11
r2=27
if difficulty==3 and go<1:
bh=random.randrange(30,40)
r1=10
r2=25
if difficulty==4 and go<1:
bh=random.randrange(40,50)
r1=10
r2=23
ticks=900/bh
go=0
print(bh)
screen=pygame.display.set_mode((900,700))
x=0
back=pygame.image.load("1.png")
while running==1:
if difficulty==1:
firepiller=random.randrange(0,26)
if difficulty==2:
firepiller=random.randrange(0,23)
if difficulty==3:
firepiller=random.randrange(0,18)
if difficulty==4:
firepiller=random.randrange(0,13)
pygame.draw.rect(screen,(225,0,0),(0,0,900,100))
pygame.draw.rect(screen,(0,225,0),(0,0,bh*ticks,100))
screen.blit(doom,(0,400))
if posx<=0:
print('" __ __ _______ __ __ ______ ___ _______ ______ "')
print('"| | | || || | | | | \ | | | || \ "')
print('"| | | || _ || | | | | __ || | | ___|| __ |"')
print('"| |_| || | | || | | | | | \ || | | |___ | | \ |"')
print('" \ / | |_| || | | | | |__/ || | | ___|| |__/ |"')
print('" | | | || |_| | | || | | |___ | |"')
print('" |___| |_______||_______| |______/ |___| |_______||______/ "')
running=0
if bh<=0:
print("' ____ ______ _____ _______ _____ _ _____ _ _ '")
print("'| _ \ | ____| /\ / ____|__ __| / ____| | /\ |_ _| \ | |'")
print("'| |_) | | |__ / \ | (___ | | | (___ | | / \ | | | \| |'")
print("'| _ < | __| / /\ \ \___ \ | | \___ \| | / /\ \ | | | . ` |'")
print("'| |_) | | |____ / ____ \ ____) | | | ____) | |____ / ____ \ _| |_| |\ |'")
print("'|____/ |______/_/ \_\_____/ |_| |_____/|______/_/ \_\_____|_| \_|'")
running=0
if firepiller==1 and go<1:
dy=350
fx=random.randrange(100,670)
go=1
if go > 0:
go+=1
if go < r1:
screen.blit(ex,(fx,500))
if r1<go<r2:
screen.blit(doom,(fx,400))
if posx-70<fx<posx+200:
print("' __ __ _______ __ __ ______ ___ _______ ______ '")
print("'| | | || || | | | | \ | | | || \ '")
print("'| | | || _ || | | | | __ || | | ___|| __ |'")
print("'| |_| || | | || | | | | | \ || | | |___ | | \ |'")
print("' \ / | |_| || | | | | |__/ || | | ___|| |__/ |'")
print("' | | | || |_| | | || | | |___ | |'")
print("' |___| |_______||_______| |______/ |___| |_______||______/ '")
running=0
if go >r2:
go=0
dy=100
if x>450:
no+=1
if no < 12:
screen.blit(ex,(600,400))
if 12<no<25:
screen.blit(doom,(600,400))
bx+=100
screen.blit(bullet,(bx,400))
screen.blit(deamon,(dx,dy))
pygame.display.flip()
screen.blit(back,(0,0))
pygame.draw.rect(screen,(0,0,0),(0,0,900,100))
screen.blit(person,(posx,posy))
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == KEYDOWN:
if event.key==K_a or event.key==K_LEFT:
posx=posx-40
if event.key==K_d or event.key==K_RIGHT:
posx=posx+40
if event.key==K_SPACE and bx>700:
bx=posx
if dx<bx<dx+125 and dy<400<dy+100:
bh-=1
x+=1
time.sleep(1/7)
back=pygame.image.load(str(x)+".png")
if x==54:
x=1
if running==0:
pygame.display.quit()
if game_chosen==2:
import sys, pygame, pygame.mixer
from pygame.locals import *
import random
import time
ground=pygame.image.load("begin.png")
grave=pygame.image.load("grave.png")
hero=pygame.image.load("hero.png")
menu=pygame.image.load("menuNEXT.png")
monster=pygame.image.load("monster.png")
knife=pygame.image.load("knifew.png")
ones=pygame.image.load("1n.png")
tens=pygame.image.load("0n.png")
pygame.init()
hx=225
hy=100
fire=0
di=1
men=0
coinneeded=10
enemies=0
level=1
begin=0
r=1
coin=0
mx=300
my=300
screen=pygame.display.set_mode((500,500))
pygame.key.set_repeat(25,25)
while running==1:
ten=int(level/10)
pygame.display.flip()
screen.blit(ground,(0,0))
tens=pygame.image.load(str(ten)+"n.png")
one=level-(ten*10+1)
ones=pygame.image.load(str(one)+"n.png")
screen.blit(ones,(110,0))
screen.blit(tens,(0,0))
if begin==1 and enemies>=0:
screen.blit(monster,(mx,my))
if hx-mx>0:
mx+=coinneeded/20
if hx-mx<0:
mx-=coinneeded/20
if hy-my>0:
my+=coinneeded/20
if hy-my<0:
my-=coinneeded/20
if my<hy<my+75 and mx<hx<mx+50:
print("you died at level " + str(level))
running=0
if fire==1:
if di==1:
ky-=25
if di==2:
kx-=25
if di==3:
ky+=25
if di==4:
kx+=25
if mx-10<kx<mx+50 and my-10<ky<my+75:
coin+=10
print("coins:" + str(coin))
mx=8000
my=8000
enemies-=1
screen.blit(knife,(kx,ky))
if kx<0 or kx>500 or ky<0 or ky>500:
fire=0
if enemies <=0:
screen.blit(grave,(225,225))
screen.blit(hero,(hx,hy))
if men==1 and enemies<=0:
screen.blit(menu,(0,400))
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == KEYDOWN:
if event.key==K_a:
knife=pygame.image.load("knifea.png")
hx-=25
if fire!=1:
di=2
if event.key==K_f:
enemies-=1
if event.key==K_d:
knife=pygame.image.load("knifed.png")
hx+=25
if fire!=1:
di=4
if event.key==K_w:
knife=pygame.image.load("knifew.png")
hy-=25
if fire!=1:
di=1
if event.key==K_s:
knife=pygame.image.load("knifes.png")
hy+=25
if fire!=1:
di=3
if event.key==K_LEFT:
menu=pygame.image.load("menuNEXT.png")
r=1
if event.key==K_RIGHT:
menu=pygame.image.load("menuUP.png")
r=0
if event.key==K_SPACE and fire==0 and enemies>0:
kx=hx
ky=hy
screen.blit(knife,(kx,ky))
fire=1
if enemies <=0:
if hx==225 and hy==225 and event.key==K_SPACE:
men=1
if hx!=225 or hy!=225:
men=0
if men==1 and event.key==K_RETURN and r==0 and coin>=coinneeded:
level+=1
print("current level:" + str(level))
coin-=coinneeded
coinneeded+=10
print("untill next level:" + str(coinneeded))
print("coins:" + str(coin))
if men==1 and event.key==K_RETURN and r==1:
x=random.randint(1,5)
ground=pygame.image.load(str(x)+"b.png")
enemies=1
screen.blit(ground,(0,0))
begin=1
mx=random.randint(0,100) or random.randint(400,500)
my=random.randint(0,100) or random.randint(400,500)
if running==0:
pygame.display.quit()
if game_chosen==3:
from random import randint as ri
inv=[]
st=1
sa=0
money=120
weapon="your an idiot"
item="your an idiot"
magic="your an idiot"
print (money)
print ("I better get some weapons items and magic")
Inventory_Blacksmith=["wooden sword","Axe","longsword","knife","hammer","torch"]
r = ri(0,5)
print (Inventory_Blacksmith[r:r+3])
buy = raw_input("what to buy?")
if buy == "wooden sword":
inv.append("wooden sword")
money=money-25
weapon="wooden sword"
if buy == "Axe":
inv.append("Axe")
money=money-60
weapon="Axe"
if buy == "longsword":
inv.append("longsword")
money=money-60
weapon="longsword"
if buy == "knife":
inv.append("knife")
money=money-30
weapon="knife"
if buy == "hammer":
inv.append("hammer")
money=money-60
weapon="hammer"
if buy == "torch":
inv.append("torch")
money=money-30
weapon="torch"
if len(inv) < 1:
inv.append("FOOL")
print(money)
print(inv)
Inventory_Shopkeep=["Potion","attack potion","defence potion"]
print (Inventory_Shopkeep)
buy = raw_input("what to buy?")
if buy == "firebomb":
inv.append("firebomb")
money=money-30
item="firebomb"
if buy == "Potion":
inv.append("Potion")
money=money-30
item="Potion"
if buy == "attack potion":
inv.append("attack potion")
money=money-30
item="attack potion"
if buy == "defence potion":
inv.append("defence potion")
money=money-30
item="defence potion"
if len(inv) < 2:
inv.append("FOOL")
print(money)
print(inv)
Inventory_wizard=["energy","magic weapon","heal","stoneflesh"
]
r = ri(0,5)
print (Inventory_wizard[r:r+3])
buy = raw_input("what to buy?")
if buy == "energy":
magic="energy"
inv.append("energy")
money=money-25
if buy == "magic weapon":
inv.append("magic weapon")
money=money-30
magic="magic weapon"
if buy == "heal":
inv.append("heal")
money=money-60
magic="heal"
if buy == "stoneflesh":
inv.append("stoneflesh")
money=money-60
magic="stoneflesh"
if buy == "thorns":
inv.append("thorns")
money=money-30
magic="thorns"
if len(inv) < 3:
inv.append("FOOL")
print(inv)
from random import randint as ri
mg=0
eh = ri(150, 280)
mh = 200
de=1
if weapon == "Axe":
st = 1.8
if weapon == "longsword":
st = 1.6
if weapon == "knife":
st = 1.1
if weapon == "hammer":
st = 1.7
if weapon == "wooden sword":
st = 1
if weapon == "torch":
st = 1.4
if item == "potion":
mh=mh+30
if item == "potion":
mh=mh+30
if item == "attack potion":
st=st+.6
if item == "defence potion":
de=de+.4
if magic == "energy":
mg=5
if magic == "magic weapon":
st=st+.6
if magic == "heal":
mh=mh+30
if magic == "magic weapon":
st=st+.6
if magic == "stoneflesh":
de=de+.2
if magic == "thorns":
cd=.5
while eh>0 and mh>0:
counter = 0
ed=ri(9,30)
print (" I can attack counter or use skill")
if sa < 40:
print ("I am too tired to use a skill")
move = raw_input("move ")
if move == "attack":
at=ri(9,15)
eh=eh-st*at+mg
print ("enemy")
print (eh)
print ("the attack was successful")
if move == ("inventory"):
print ("I have") (inv)
if move == ("skill") and sa > 40:
if weapon == "Axe":
eh = eh-st*2*at+mg
mh = mh-20
sa=0
print("the attack was powerful but left your wrist injujred")
if weapon == "longsword":
ed = 0
sa=0
print("You were too far for the enemy to attack")
if weapon == "knife":
slash = ri(1,5)
if slash == 1:
eh = eh-40
sa=0
print("you slash at the enemy dealing heavy dammage")
else:
print("you miss the enemy")
if weapon == "hammer":
de = + .5
sa=0
print("you feel far more fortified")
if weapon == "wooden sword":
st = st-.75
mh = mh + .1*mh
sa=0
print("somehow snaping your flimsy sword makes you feel better")
if weapon == "torch":
mg = 10
sa=0
print("you light the enemy ablaze")
if move == "counter":
counter = 1
ea = ri(0,4)
if ea > 0:
mh=mh-ed/de
print ("me")
print (mh)
if counter == 1:
eh=eh-st*ed*1.25+mg
print ("enemy")
print (eh)
if ea == 0:
if counter ==1:
print("the counter fails")
mh=mh-ri(10,20)
print(mh)
print ("enemy")
print (eh)
sa = sa +10
if game_chosen==4:
p1h=5
p2h=5
p1p=4
p2p=2
moves1=3
moves2=3
space=1
p1w=raw_input("P1 Weapon: ")
if p1w == "axe":
p1min=-1
p1max=1
if p1w == "longsword":
p1min=0
p1max=2
if p1w == "spear":
p1min=1
p1max=3
p2w=raw_input("P2 Weapon: ")
if p2w == "axe":
p2min=-1
p2max=1
if p2w == "longsword":
p2min=0
p2max=2
if p2w == "spear":
p2min=1
p2max=3
while p1h>=0 or p2h>=0:
moves1=3
moves2=3
while moves1>0:
if p2p==1:
if p1p==2:
print("X O_ _ _")
if p1p==3:
print("X _ O _ _")
if p1p==4:
print("X _ _ O _")
if p1p==5:
print("X _ _ _ O")
if p2p==2:
if p1p==3:
print("_ X O _ _")
if p1p==4:
print("_ X _ O _")
if p1p==5:
print("_ X _ _ O")
if p2p==3:
if p1p==4:
print("_ _ X O _")
if p1p==5:
print("_ _ X _ O")
if p2p==4:
if p1p==5:
print("_ _ _ X O")
print ("moves:"+ str(moves1))
print("health1:"+str(p1h ))
action1=raw_input("action P1")
if action1 == "back":
if p1p == 5:
print("my back is against the wall")
if p1p<5:
moves1=moves1-1
p1p=p1p+1
space=space+1
if action1 == "forwards":
if space == 0:
print("cant move past the enemy")
if space>0:
space=space-1
p1p=p1p-1
print("I moved forwards")
moves1=moves1-1
if action1 == "attack":
if space>p1min and space<p1max:
p2h=p2h-1
moves1=moves1-1
print("Hit")
if space<=p1min or space>=p1max:
print("out of my range")
if action1 == "shove":
if space==0:
moves1=moves1-1
print("I shoved him back")
p2p=p2p-1
space=space+1
while moves2>0:
if p2h>0:
if p2p==1:
if p1p==2:
print("X O_ _ _")
if p1p==3:
print("X _ O _ _")
if p1p==4:
print("X _ _ O _")
if p1p==5:
print("X _ _ _ O")
if p2p==2:
if p1p==3:
print("_ X O _ _")
if p1p==4:
print("_ X _ O _")
if p1p==5:
print("_ X _ _ O")
if p2p==3:
if p1p==4:
print("_ _ X O _")
if p1p==5:
print("_ _ X _ O")
if p2p==4:
if p1p==5:
print("_ _ _ X O")
print ("moves:"+ str(moves2))
print("health2:"+str(p2h) )
action2=raw_input("action P2")
if action2 == "back":
if p2p == 1:
print("my back is against the wall")
if p1p>1:
moves2=moves2-1
p2p=p2p-1
space=space+1
if action2 == "forwards":
if space == 0:
print("cant move past the enemy")
if space>0:
space=space-1
p2p=p2p+1
print("I moved forwards")
moves2=moves2-1
if action2 == "attack":
if space>p2min and space<p2max:
p1h=p1h-1
moves2=moves2-1
print("Hit")
if space<=p2min or space>=p2max:
print("out of my range")
if action2 == "shove":
if space==0:
moves2=moves2-1
print("I shoved him back")
p1p=p1p+1
space=space+1
begin_game=0
|
### Two Sum ###
# Given an array of integers nums and an integer target,
# return indices of the two numbers such that they add up to target.
def findTwoSum(nums, target):
# Create hashmap
hashmap = {}
for i in range(len(nums)):
# Create a complement
complement = target - nums[i]
# If complement exists in hashmap return the two indices
if complement in hashmap:
return [i, hashmap[complement]]
hashmap[nums[i]] = i
|
# #1
# def biggie(x):
# newArr=[]
# for i in range(len(x)):
# if x[i]>= 0:
# newArr.append("Big")
# else:
# newArr.append(x[i])
# return newArr
# print(biggie([-1,-4,5,-3,2,1,-1,0]))
# 2
# def count_pos(x):
# counter = 0
# for i in range(len(x)):
# if x[i]>0:
# counter += 1
# x[len(x)-1]=counter
# print(x)
# count_pos([-1,2,3,-1,2,-1])
# #3
# def su_num(x):
# sum=0
# for i in range (len(x)):
# sum += x[i]
# return sum
# print(su_num([2,2,3,4,5,6,7]))
# 4
# def average (x):
# ave= 0
# sum= 0
# for i in range (len(x)):
# sum += x[i]
# ave= sum / len(x)
# print(ave)
# average([1,2,3,4,5])
# #5
# def length (x):
# leng = 0
# for i in range (len(x)):
# leng += 1
# return leng
# print(length([12,24,5,23]))
# #6
# def minimum (x):
# min=x[0]
# for i in x:
# if i < min:
# min=i
# return min
# print(minimum([5,23,-12,0,15]))
# #7
# def maximum (x):
# max=x[0]
# for i in x:
# if i > max:
# max=i
# return max
# print(maximum([5,23,-12,0,15]))
# #8
# def ultimate (x):
# min= x[0]
# max= x[0]
# sum= 0
# for i in range(len(x)):
# if i > max:
# max=i
# elif i < min:
# min=i
# sum += x[i]
# ave= sum / len(x)
# dict = {"minimum": min, "maximum": max, "sumTotal": sum, "average": ave, "length": len(x)}
# print (dict)
# ultimate([5,23,-12,0,15])
# 9
# def reverse (x):
# newArr=[]
# for i in range(len(x)-1, -1, -1):
# newArr.append(x[i])
# return newArr
# print(reverse([1,2,3,4,5]))
def removeDubs(x):
for i in range(len(x)):
# temp = x[i]
for j in range(len(x)-1, i, -1):
if x[i] == x[j]:
x.pop(j)
else:
continue
return x
print(removeDubs([1,1,3,5,2,3,1]))
|
items1 = dict({"key1" : 1,"key2" : 2,"key3" : "three","key4" : 4,})
print(items1)
items2 = {}
items2["key1"] = 1
items2["key2"] = 2
items2["key3"] = 3
print(items2)
# print(items1["key6"])
items2["key2"] = "two"
print(items2)
for key, value in items2.items():
print("Key: ", key, " value:", value)
|
def generate_concept_HTML(concept_title, concept_description):
html_text_1 = '''
<div class="concept">
<div class="concept-title">
''' + concept_title
html_text_2 = '''
</div>
<div class="concept-description">
''' + concept_description
html_text_3 = '''
</div>
</div>'''
full_html_text = html_text_1 + html_text_2 + html_text_3
return full_html_text
def make_HTML(concept):
title = concept[0]
description = concept[1]
return generate_concept_HTML(title, description)
EXAMPLE_LIST_OF_CONCEPTS = [['Python', 'Python is a Programming Languate'],
['For Loop', 'For Loops allow you to iterate over lists'],
['Lists', 'Lists are sequences of data']]
def make_HTML_for_many_concepts(list_of_concepts):
HTML = ""
for concept in list_of_concepts:
concept_HTML = make_HTML(concept)
HTML = HTML + concept_HTML
return HTML
print make_HTML_for_many_concepts(EXAMPLE_LIST_OF_CONCEPTS)
|
# import turtle
# t = turtle.Turtle()
# shapeInput = input('circle and square or triangle, what is your favorite shape?:')
# colorInput = input('What color will it be? :')
# t.fillcolor(colorInput)
# t.begin_fill()
# if shapeInput == 'circle':
# r=float(input("radius :"))
# t.circle(r)
# elif shapeInput == 'square':
# a = float(input("side length :"))
# for x in range(4):
# t.fd(a)
# t.rt(90)
# elif shapeInput == 'triangle' :
# l = float(input("side length :"))
# for x in range(3):
# t.fd(l)
# t.lt(120)
# else:
# print("Sorry, I don't have this shape :(")
# t.end_fill()
# wn = turtle.Screen()
# wn.bgcolor("black")
# wn.title("Your shape")
# turtle.done()
|
################################################
# CS 21B Intermediate Python Programming Lab #1
# Topics: Arithmetic, Data Types, User Input,
# Formatting Output, Importing Modules
# Description: To evaluate arithmetic expressions
# using Python.
# User Input: student ID, name, various other vars
# Output: evaluates expressions
# Version: 3.6.5
# Development Environment: Windows 10
# Developer: Anirudhan Badrinath
# Date: 10/02/18
################################################
import datetime as dt
########## FUNCTIONS ###########################
def get_student_id():
""" gets valid student ID input """
REQUIRED_LENGTH = 8
while (True):
# make sure it is an integer
try:
student_id = int(input("Enter your Student ID: "))
except ValueError:
print("Try again, ID should contain 8 digits & be numeric")
continue
# make sure it has the right length
if (len(str(student_id)) != REQUIRED_LENGTH):
print("Try again, ID should contain 8 digits & be numeric")
# return if conditions are met
else:
return student_id
def get_family_name():
""" gets a valid family name input """
MIN_LENGTH = 2
MAX_LENGTH = 15
while (True):
family_name = input("Enter your family name: ")
# check alpha and length
if (not family_name.isalpha() or
not MIN_LENGTH <= len(family_name) <= MAX_LENGTH):
print("Try again, family name should be only " +
"characters and between 2 and 15 chars long")
else:
return len(family_name)
def sum_of_digits(num):
""" gets sum of all the digits in the number passed in """
sum = 0
while (num != 0):
# sum last digit and divide by 10
sum += num % 10
num //= 10
return sum
def print_output(arr):
""" prints output in the requested format using array structure """
for i in range(0, len(arr)):
print("expression ", i + 1, ": ", arr[i])
def calculate_exprs(my_id, n_let):
""" calculate each of the 10 expressions """
expressions = []
# evaluate the 9 expressions and store in array
expressions.append(format(my_id / 2, '.2f'))
expressions.append(my_id % 2)
expressions.append(sum(range(2, n_let + 1)))
expressions.append(my_id + n_let)
expressions.append(abs(n_let - my_id))
expressions.append(format(my_id / (n_let + 1100), '.2f'))
expressions.append((n_let % n_let) and (my_id * my_id))
expressions.append(1 or (my_id / 0))
expressions.append(format(round(3.15, 1), '.2f'))
return expressions
########### MAIN PROGRAM #######################
# get the family name letters and sum of digits of stut ID
n_let = get_family_name()
my_id = sum_of_digits(get_student_id())
print(" my_id is: ", my_id, "\n" +
" n_let is: ", n_let)
# calculate the 9 expressions and store in array
expressions = calculate_exprs(my_id, n_let)
# iterate through printing all expressions
print_output(expressions)
# print date and time as timestamp
print("Today's date is ", dt.datetime.now().strftime("%Y-%m-%d"))
################################################
"""
Output:
Enter your Student ID: 20346732
Enter your family name: Badrinath
my_id is: 27
n_let is: 9
expression 1 : 13.50
expression 2 : 1
expression 3 : 44
expression 4 : 36
expression 5 : 18
expression 6 : 0.02
expression 7 : 0
expression 8 : 1
expression 9 : 3.10
Today's date is 2018-10-02
"""
|
"""
Binary search trees are a data structure that enforce an ordering over
the data they store. That ordering in turn makes it a lot more efficient
at searching for a particular piece of data in the tree.
This part of the project comprises two days:
1. Implement the methods `insert`, `contains`, `get_max`, and `for_each`
on the BSTNode class.
2. Implement the `in_order_print`, `bft_print`, and `dft_print` methods
on the BSTNode class.
"""
class Node:
def __init__(self, value=None, next_node=None):
# the value at this linked list node
self.value = value
# refference to the next node in the list
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, new_next):
# set this node's next node reference to the passed in node
self.next_node = new_next
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def get_length(self):
return self.length
def add_to_head(self, value):
new_node = Node(value, self.head)
self.head = new_node
if self.length == 0:
self.tail = new_node
self.length += 1
def add_to_tail(self, value):
new_node = Node(value)
if self.head is None and self.tail is None:
self.head = new_node
else:
self.tail.set_next(new_node)
self.tail = new_node
self.length += 1
def get_max(self):
if self.head is None:
return None
maxValue = self.head.get_value()
currNode = self.head
while(currNode != None):
if(currNode.get_value() > maxValue):
maxValue = currNode.get_value()
currNode = currNode.get_next()
return maxValue
def contains(self, value):
if self.head is None:
return False
currNode = self.head
while currNode is not None:
if currNode.get_value() == value:
return True
currNode = currNode.get_next()
return False
# def contains(self, value):
# while(self.tail != None):
# pass
def remove_head(self):
if self.head is None:
return None
elif self.head == self.tail:
value = self.head.get_value()
self.head = None
self.tail = None
self.length -= 1
return value
else:
value = self.head.get_value()
self.head = self.head.get_next()
self.length -= 1
return value
def remove_tail(self):
if(self.length == 0):
return None
elif(self.head == self.tail):
self.head = None
self.tail = None
length -= 1
else:
currNode = self.head
prevNode = self.head
while currNode is not None:
prevNode = currNode
currNode = currNode.get_next()
self.tail = prevNode
return self.tail.get_value()
class Queue:
def __init__(self):
self.size = 0
self.storage = LinkedList()
def __len__(self):
return self.size
def enqueue(self, value):
self.storage.add_to_tail(value)
self.size += 1
def dequeue(self):
if self.size == 0:
return None
else:
self.size -= 1
return self.storage.remove_head()
class Stack:
def __init__(self):
self.size = 0
self.storage = list()
def __len__(self):
return self.size
def push(self, value):
self.storage.append(value)
self.size += 1
def pop(self):
if self.size == 0:
return
else:
self.size -= 1
return self.storage.pop()
class BSTNode:
def __init__(self, value=None):
self.value = value
self.left = None
self.right = None
# Insert the given value into the tree
def insert(self, value):
if self is None:
return None
if value < self.value:
if self.left is None:
self.left = BSTNode(value)
else:
self.left.insert(value)
if value >= self.value:
if self.right is None:
self.right = BSTNode(value)
else:
self.right.insert(value)
# Return True if the tree contains the value
# False if it does not
pass
def contains(self, target):
if self is None:
return False
while self is not None:
if self.value < target:
self = self.right
elif self.value > target:
self = self.left
else:
return True
# # compare target_value to cur_value
# # 1. == we return True
# if self.value == target:
# return True
# # 2. < we go left
# if self.left is not None:
# return contains(target)
# # 3 > we go right
# elif self.right is not None:
# contains(target)
# # 4. if can't go left/right (not found) return False
# else:
# return False
# Return the maximum value found in the tree
def get_max(self):
# handle empty list
# keep track of current max
# loop through
# compare current max with each value
# return max
if self is None:
return None
curr_node = self
while curr_node.right:
curr_node = curr_node.right
return curr_node.value
# Call the function `fn` on the value of each node
def for_each(self, fn):
# 1 Base case - no more nodes in our subtree
# 2 Recursive case
fn(self.value)
if self.left is not None: # if self.left:
self.left.for_each(fn)
if self.right is not None: # if self.right
self.right.for_each(fn)
# Stretch
def delete(self, value):
# Search like we did in contains()
# different cases
# If node at bottom level
# update parent left/right = None
#If node has only one child
# parent.left/right = node.left right
# if node has two children
# "larger" child becomes the parent of its sibling
pass
# Part 2 -----------------------
# Print all the values in order from low to high
# Hint: Use a recursive, depth first traversal
def in_order_print(self):
if self.left:
# go left with recursion
self.left.in_order_print()
print(self.value)
# print
if self.right:
# go right with recursion
self.right.in_order_print()
# Print the value of every node, starting with the given node,
# in an iterative breadth first traversal
def bft_print(self):
if self is None:
return None
# use a queue!
queue = Queue()
queue.enqueue(self)
while queue.size > 0:
curr_node = queue.dequeue()
print(curr_node.value)
if curr_node.left:
queue.enqueue(curr_node.left)
if curr_node.right:
queue.enqueue(curr_node.right)
# print current node, add left_child to queue, add right_ child to queue
# (if not None)
# done when queue is empty
# Print the value of every node, starting with the given node,
# in an iterative depth first traversal
def dft_print(self):
# create a stack
# push some initial values? onto the stack
# stack = Stack()
stack = Stack()
stack.push(self)
# while stack is not empty
while(len(stack) > 0):
curr_node = stack.pop()
print(curr_node.value)
if curr_node.right:
stack.push(curr_node.right)
if curr_node.left:
stack.push(curr_node.left)
# done when stack is empty
# Stretch Goals -------------------------
# Note: Research may be required
# Print Pre-order recursive DFT
def pre_order_dft(self):
pass
# Print Post-order recursive DFT
def post_order_dft(self):
pass
def in_order_dft(self):
pass
"""
This code is necessary for testing the `print` methods
"""
class Node:
def __init__(self, value=None, next_node=None):
# the value at this linked list node
self.value = value
# refference to the next node in the list
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, new_next):
# set this node's next node reference to the passed in node
self.next_node = new_next
|
def menu(conn):
option = ""
while option != "return":
print("")
print("Please select from one of the following options:")
print("view users")
print("add admin")
print("remove user")
print("return")
option = input("> ")
if(option == "view users"):
view_users(conn)
elif(option == "add admin"):
add_admin(conn)
elif(option == "remove user"):
remove_user(conn)
def view_users(conn):
cur = conn.cursor()
cur.execute("SELECT * FROM users")
rows = cur.fetchall()
for row in rows:
print("=================================================")
print("user id:", row[0])
print("username:", row[1])
print("password:", row[2])
print("name:", row[3])
print("phone:", row[4])
print("billing address:", row[5])
print("shipping address:", row[6])
print("account type:", row[7])
print("cart id:", row[8])
def add_admin(conn):
cur = conn.cursor()
print("Admin registration page")
print("Please enter the following details")
username = input("username > ")
passwd = input("password > ")
name = input("name > ")
phone = int(input("phone > "))
billing_address = input("billing address > ")
shipping_address = input("shipping address > ")
acc_type = "admin"
cur.execute("INSERT INTO carts VALUES (NULL)")
cart_id = cur.lastrowid
cur.execute("INSERT INTO users VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)", (username, passwd, name, phone, billing_address, shipping_address, acc_type, cart_id))
conn.commit()
|
"""
http://practice.geeksforgeeks.org/problems/minimum-platforms/0
Author : Salman Ahmad
"""
def min_platforms(arrival,exits):
time_adds = {}
for i in range(len(arrival)):
if exits[i] <= arrival[i]:
exits[i]+=2400
for t in arrival:
time_adds[t] = time_adds.get(t,0)+1
for t in exits:
time_adds[t] = time_adds.get(t,0)-1
full_list = arrival+exits
sorted_list = sorted(full_list)
min_pltforms = 0
count = 0
for t in sorted_list:
count+=time_adds[t]
if count>min_pltforms:
min_pltforms = count
return min_pltforms
if __name__ == '__main__':
test_cases = int(input())
for i in range(test_cases):
n=input()
arrivals = [int(x) for x in input().strip().split(' ') if x!='']
exits = [int(x) for x in input().strip().split(' ') if x!='']
print (min_platforms(arrivals,exits))
|
'''
Created on 2018年8月4日
https://www.geeksforgeeks.org/level-order-tree-traversal/
@author: Viking
'''
# python3 orgram to print level order traversal using queue
class Node:
def __init__(self, data):
self.data = data
self.left = self.right = None
def printLevelOrder(root):
if root is None:
return
# create an empty queue for level order traversal
queue = []
queue.append(root)
while(len(queue) > 0):
tmp = queue.pop(0)
print(tmp.data, end=" ")
if tmp.left is not None:
queue.append(tmp.left)
if tmp.right is not None:
queue.append(tmp.right)
# Driver code to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("Level Order Traversal of binary tree is -")
printLevelOrder(root)
'''
Level Order Traversal of binary tree is -
1 2 3 4 5
'''
|
import turtle
def POSICIONAR():
"""Cambia el onscreenclick para que lea donde posicionar a Karel"""
global kl
wn.title("HAGA CLICK DONDE QUIERA INICIAR A KAREL")
bep.ht()
kl.ht()
wn.onscreenclick(FACING)
def FACING(x,y):
"""Recibe unas coordenadas y posiciona a karel en el centro del cuadrante donde estan ubicadas,
luego activa comandos onkey para determinar su orientacion"""
x=((25+x)//50)*50
y=((25+y)//50)*50
kl.goto(x,y)
karel.x=x
karel.y=y
kl.st()
kl.speed(1)
wn.title("PRESIONE UNA TECLA DE DIRECCION PARA ORIENTAR A KAREL")
wn.onkey(EJECUTARNORTE,"Up")
wn.onkey(EJECUTARSUR,"Down")
wn.onkey(EJECUTAROESTE,"Left")
wn.onkey(EJECUTARESTE,"Right")
def EJECUTARNORTE():
"""Comienza a ejecutar la programacion compilada con karel orientandose al norte"""
karel.facing=1
kl.seth(karel.facing*90)
karel.execute(ejecucion)
def EJECUTARSUR():
"""Comienza a ejecutar la programacion compilada con karel orientandose al sur"""
karel.facing=3
kl.seth(karel.facing*90)
karel.execute(ejecucion)
def EJECUTAROESTE():
"""Comienza a ejecutar la programacion compilada con karel orientandose al oeste"""
karel.facing=2
kl.seth(karel.facing*90)
karel.execute(ejecucion)
def EJECUTARESTE():
"""Comienza a ejecutar la programacion compilada con karel orientandose al este"""
karel.facing=0
kl.seth(karel.facing*90)
karel.execute(ejecucion)
def exitf():
"""Cambia el onscreenclick para que lea donde posicionar los beepers"""
global bep
wn.title("SITUE LOS BEEPERS Y LUEGO PRESIONE ENTER")
visualk.penup()
visualk.ht()
visualk.onclick(None)
bep.penup()
bep.color("red")
bep.shape("circle")
bep.speed(0)
wn.onclick(situarbeeper)
def situarmuros(x,y):
"""Recibe unas coordenadas y situa muros hasta estas coordenadas, ubicandolos en el centro
de los cuadrantes, guarda la ubicacion de los muros en una lista"""
primero=visualk.position()
visualk.pendown()
visualk.pencolor("Black")
visualk.pensize("10")
x=(x//50)*50+25
y=(y//50)*50+25
if (x!=primero[0] or y!=primero[1]) and (x==primero[0] or y==primero[1]):
visualk.goto(x,y)
if x!=primero[0]:
a=(x+primero[0])/2
muros.append([a, y])
else:
a=(y+primero[1])/2
muros.append([x,a])
visualk.penup()
def iracentro(x,y):
"""Recibe unas coordenadas y situa la tortuga en el centro del cuadrante"""
x=(x//50)*50+25
y=(y//50)*50+25
visualk.goto(x,y)
visualk.st()
def situarbeeper(x,y):
"""Recibe unas coordenadas y situa un beeper en la esquina del cuadrante, guarda los beepers
en un diccionario. Si hay mas de un beeper en la esquina, dibuja el numero de beepers que hay"""
x=((25+x)//50)*50
y=((25+y)//50)*50
bep.goto(x,y)
bep.st()
if (x,y) not in list(beepers.keys()):
beepers[x,y]=[bep.clone()]
else:
beepers[x,y].append(bep.clone())
beepers[x,y][0].pencolor("black")
beepers[x,y][0].write(len(beepers[x,y]), move=False, align="center", font=("Arial", 7, "bold"))
def tolist(contador,listraw):
"""Recibe una lista de lineas y las almacena en una nueva lista, quitando las cadenas vacias,
limpiando de espacios y tabulaciones el final de la cadena, almacenando en una sublista los cuerpos
de los comandos de tipo ITERATE, WHILE, IF, DEFINE (identificados por no tener ; al final y no ser
turnoff ni END ni ELSE ni BEGIN)"""
newlist=[]
i=0
while (i)<len(listraw):
listraw[i]=listraw[i][contador:]
if len(listraw[i])!=0:
if listraw[i]=="turnoff":
for x in reversed(range(len(listraw)-i)):
newlist.append(listraw[len(listraw)-1-x])
return newlist
else:
if listraw[i][len(listraw[i])-1]!=";":
block=[]
while listraw[i][contador:]!="END" and listraw[i][contador:]!="END;":
block.append(listraw.pop(i))
block.pop(1)
block[len(block)-1]+=";"
newblock=[block[0]]+tolist(contador+1,block[1:])
newlist.append(newblock)
else:
newlist.append(listraw[i])
i+=1
return newlist
class Karel:
def __init__(self,facing=0,x=0,y=0,beepers=0):
"""x, y son las coordenadas. facing: 0 es este, 1 es norte, 2 es oeste, 3 es sur."""
self.facing=facing
self.x=x
self.y=y
self.beepers=beepers
def __str__(self):
"""Este metodo permite imprimir en la consola a lo que hace karel"""
return "Facing: {0}, pos:({1},{2}), beepers:{3}".format(self.facing,self.x,self.y,self.beepers)
# ********FUNCIONES BASICAS**********
def move(self):
"""Mueve a karel 50 unidades, guarda las nuevas coordenadas en self.x, self.y.
Es util dado que a veces al pedir las coordenadas de turtle hay problemas con los decimales"""
if self.facing==0:
if [self.x+25,self.y] in muros:
kl.forward(20)
self.executionerror()
self.x+=50
elif self.facing==1:
if [self.x,25+self.y] in muros:
kl.forward(20)
self.executionerror()
self.y+=50
elif self.facing==2:
if [self.x-25,self.y] in muros:
kl.forward(20)
self.executionerror()
self.x-=50
else:
if [self.x,self.y-25] in muros:
kl.forward(20)
self.executionerror()
self.y-=50
kl.forward(50)
def turnleft(self):
"""Cambia el facing a la izquierda, mueve a karel a la izquierda"""
if self.facing==3:
self.facing=0
kl.seth(self.facing*90)
else:
self.facing+=1
kl.seth(self.facing*90)
def pickbeeper(self):
"""Si no hay beepers devuelve un error, si hay beepers suma 1 a self.beepers. Borra el numero
de beepers que estaba escrito antes y si queda mas de un beeper en el lugar escribe el numero
que queda"""
if (self.x,self.y) not in list(beepers.keys()):
self.executionerror()
elif len(beepers[self.x,self.y])==0:
self.executionerror()
beepers[self.x,self.y][0].pencolor("white")
beepers[self.x,self.y][0].write(len(beepers[self.x,self.y]),move=False, align="center", font=("Arial", 7, "bold"))
beepers[self.x,self.y][0].ht()
beepers[self.x,self.y].pop(0)
if len(beepers[self.x,self.y])!=0:
beepers[self.x,self.y][0].pencolor("black")
beepers[self.x,self.y][0].write(len(beepers[self.x,self.y]),move=False, align="center", font=("Arial", 7, "bold"))
self.beepers+=1
def putbeeper(self):
"""Si no tiene beepers karel, devuelve un error. Situa un beeper en la posicion de karel,
disminuye 1 a self.beepers"""
if self.beepers<=0:
self.executionerror()
situarbeeper(self.x,self.y)
self.beepers-=1
# ********EJECUCION**********
def execute(self,listaejecu):
"""Lee cada funcion en una lista y la ejecuta debidamente, busca en un diccionario las
funciones que no entiende, si no esta en el diccionario levanta error de lexico.
Imprime en consola el comando ejecutado y el nuevo estado de karel"""
for i in range(len(listaejecu)):
print(listaejecu[i])
if listaejecu[i]!="":
if listaejecu[i]=="move;":
self.move()
elif listaejecu[i]=="turnleft;":
self.turnleft()
elif listaejecu[i]=="pickbeeper;":
self.pickbeeper()
elif listaejecu[i]=="putbeeper;":
self.putbeeper()
elif listaejecu[i]=="turnoff" or listaejecu[i]=="turnoff":
self.turnoff()
if listaejecu[i+1]=="\tEND-OF-EXECUTION" and listaejecu[i+2]=="END-OF-PROGRAM":
break
else:
self.lexicerror()
elif type(listaejecu[i]) is list:
if listaejecu[i][0][:7]=="ITERATE":
x=listaejecu[i][0].find(" TIMES")
a=(listaejecu[i][0][8:x])
for q in range(int(a)):
self.execute(listaejecu[i][1:])
if listaejecu[i][0][:3]=="IF " and listaejecu[i][0][len(listaejecu[i][0])-5:]==" THEN":
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="facing-north":
if self.facingnorth():
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="not-facing-north":
if not self.facingnorth():
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="facing-south":
if self.facingsouth():
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="not-facing-south":
if not self.facingsouth():
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="facing-west":
if self.facingwest():
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="not-facing-west":
if not self.facingwest():
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="facing-east":
if self.facingeast():
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="not-facing-east":
if not self.facingeast():
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="next-to-a-beeper":
if self.nexttoabeeper():
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="not-next-to-a-beeper":
if not self.nexttoabeeper():
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="front-is-clear":
if self.isclear(0):
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="front-is-blocked":
if not self.isclear(0):
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="left-is-clear":
if self.isclear(1):
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="left-is-blocked":
if not self.isclear(1):
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="right-is-clear":
if self.isclear(-1):
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][3:len(listaejecu[i][0])-5]=="right-is-blocked":
if not self.isclear(-1):
self.execute(listaejecu[i][1:])
else:
if len(listaejecu)>(i+1):
if listaejecu[i+1][0]=="ELSE":
self.execute(listaejecu[i+1][1:])
if listaejecu[i][0][:6]=="WHILE " and listaejecu[i][0][len(listaejecu[i][0])-3:]==" DO":
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="facing-north":
while self.facingnorth():
self.execute(listaejecu[i][1:])
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="not-facing-north":
while not self.facingnorth():
self.execute(listaejecu[i][1:])
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="facing-south":
while self.facingsouth():
self.execute(listaejecu[i][1:])
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="not-facing-south":
while not self.facingsouth():
self.execute(listaejecu[i][1:])
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="facing-west":
while self.facingwest():
self.execute(listaejecu[i][1:])
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="not-facing-west":
while not self.facingwest():
self.execute(listaejecu[i][1:])
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="facing-east":
while self.facingeast():
self.execute(listaejecu[i][1:])
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="not-facing-east":
while not self.facingeast():
self.execute(listaejecu[i][1:])
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="next-to-a-beeper":
while self.nexttoabeeper():
self.execute(listaejecu[i][1:])
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="not-next-to-a-beeper":
while not self.nexttoabeeper():
self.execute(listaejecu[i][1:])
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="front-is-clear":
while self.isclear(0):
self.execute(listaejecu[i][1:])
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="front-is-blocked":
while not self.isclear(0):
self.execute(listaejecu[i][1:])
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="left-is-clear":
while self.isclear(1):
self.execute(listaejecu[i][1:])
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="left-is-blocked":
while not self.isclear(1):
self.execute(listaejecu[i][1:])
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="right-is-clear":
while self.isclear(-1):
self.execute(listaejecu[i][1:])
if listaejecu[i][0][6:len(listaejecu[i][0])-3]=="right-is-blocked":
while not self.isclear(-1):
self.execute(listaejecu[i][1:])
elif listaejecu[i][0][:4]=="ELSE":
None
else:
try:
self.execute(diccionario[listaejecu[i]])
except:
self.lexicerror()
wn.ontimer(None,100)
print(self)
# ********ERRORES**********
def lexicerror(self):
"""Levanta error de lexico"""
raise ValueError("Error de lexico")
def executionerror(self):
"""levanta error de ejecucion"""
raise ValueError("Error de ejecucion")
# ********PRUEBAS LOGICAS**********
def facingeast(self):
"""Evalua si karel esta orientada al este"""
if self.facing==0:
return True
else:
return False
def facingnorth(self):
"""Evalua si karel esta orientada al norte"""
if self.facing==1:
return True
else:
return False
def facingwest(self):
"""Evalua si karel esta orientada al oeste"""
if self.facing==2:
return True
else:
return False
def facingsouth(self):
"""Evalua si karel esta orientada al sur"""
if self.facing==3:
return True
else:
return False
def nexttoabeeper(self):
"""Evalua si karel esta sobre un beeper"""
if (self.x,self.y) in list(beepers.keys()):
if len(beepers[self.x,self.y])!=0:
return True
else:
return False
else:
return False
def isclear(self,direc):
"""Evalua si la direccion indicada esta bloqueada.
CERO ES PARA FRONT, 1 PARA LEFT, -1 PARA RIGHT"""
m=self.facing+direc
if m not in range(4):
if m>=4:
m=0
else:
m=3
if m==0:
if [self.x+25,self.y] in muros:
return False
elif m==1:
if [self.x,25+self.y] in muros:
return False
elif m==2:
if [self.x-25,self.y] in muros:
return False
else:
if [self.x,self.y-25] in muros:
return False
return True
def turnoff(self):
"""Cambia el titulo a -karel se ha apagado-"""
wn.title("Karel se ha apagado")
# ***************COMPILACION***********************
# ****************************************************
# ****************************************************
# ***********CAMBIAR EL ARCHIVO AQUI******************
# ****************************************************
# ****************************************************
miArchivo=open("AndresIsazaQuiz2 (2).txt","r")
macrobloques=miArchivo.read().split("BEGINNING-OF-EXECUTION") #Divide entre definiciones y ejecucion
numbep=9999
karel=Karel(0,0,0,numbep)
ejecucionraw=macrobloques[1].split("\n") #Divide la ejecucion entre lineas
definicionesraw=macrobloques[0].split("\n")
for i in range(len(definicionesraw)):
while definicionesraw[i][len(definicionesraw[i])-1:]==" " or definicionesraw[i][len(definicionesraw[i])-1:]=="\t":
definicionesraw[i]=definicionesraw[i][:-1]
linea=0
while linea<len(definicionesraw):
while definicionesraw[linea]=="":
definicionesraw.pop(linea)
if linea+1>len(definicionesraw):
break
linea+=1
if definicionesraw[0]=="BEGINNING-OF-PROGRAM":
definiciones=tolist(1,definicionesraw[1:])
else: karel.lexicerror()
diccionario={}
for i in definiciones: #AGREGA LAS DEFINICIONES A UN DICCIONARIO CUYA CLAVE ES LA NUEVA FUNCION
if i[0][:22]=="DEFINE-NEW-INSTRUCTION":
x=i[0].find(" AS")
a=(i[0][23:x])
diccionario[a+";"]=i[1:]
for i in range(len(ejecucionraw)):
while ejecucionraw[i][len(ejecucionraw[i])-1:]==" " or ejecucionraw[i][len(ejecucionraw[i])-1:]=="\t":
ejecucionraw[i]=ejecucionraw[i][:-1]
linea=0
while linea<len(ejecucionraw):
while ejecucionraw[linea]=="":
ejecucionraw.pop(linea)
if linea+1>len(ejecucionraw):
break
linea+=1
ejecucion=tolist(2,ejecucionraw)
# ******************************INTERFAZ****************************
kl=turtle.Turtle()
kl.ht()
kl.penup()
wn=turtle.Screen()
bep=turtle.Turtle()
bep.ht()
wn.screensize(150,150)
wn.title("El mundo de Karel")
wn.bgcolor("White")
visualk=turtle.Turtle()
visualk.ht()
visualk.pencolor("Blue")
visualk.pensize(3)
visualk.penup()
visualk.goto(-250,-250)
visualk.pendown()
visualk.speed(0)
visualk.pensize(2)
for i in range(2):
for i in range(5):
visualk.forward(500)
visualk.left(90)
visualk.forward(100)
visualk.back(50)
visualk.left(90)
visualk.forward(500)
visualk.right(90)
visualk.forward(50)
visualk.right(90)
visualk.right(90)
visualk.forward(500)
visualk.goto(-250,-250)
wn.title("SITUE LOS MUROS (CLICK, LUEGO ARRASTRAR LENTAMENTE). AL TERMINAR PRESIONE ESPACIO")
visualk.shape("square")
visualk.color("black")
visualk.penup()
muros=[]
beepers={}
wn.onclick(iracentro)
visualk.ondrag(situarmuros)
wn.onkey(exitf,"space")
wn.onkey(POSICIONAR,"Return")
wn.listen()
wn.mainloop()
|
from tkinter import *
import sqlite3 as db
from tkcalendar import DateEntry
def submit():
# connect to a database
conn = db.connect('expense.db')
#Create cursor for db
c = conn.cursor()
# Insert into Table
c.execute("INSERT INTO expenses VALUES (:date, :amount, :name, :paid_by)",
{
'date': date_entry.get_date(),
'amount': amount_entry.get(),
'name': name_entry.get(),
'paid_by': paid_by_entry.get()
}
)
conn.commit()
conn.close()
# Clearing the fields
name_entry.delete(0, END)
amount_entry.delete(0,END)
paid_by_entry.delete(0,END)
total_label.config(text = "Expense Total: $" + str(total_expenses()))
# updating record display
view_records()
return
def view_records():
# connect to a database
conn = db.connect('expense.db')
#Create cursor for db
c = conn.cursor()
# Query the database
c.execute("SELECT *, oid FROM expenses")
records = c.fetchall()
# Delete list before repopulating
rec_list.delete(0, END)
for rec in records:
# print(rec)
rec_list.insert(END, str(rec[4]) + "________________" + str(rec[0]) + "______________" + str(rec[1]) + "_____________________" + str(rec[2]) + "_____________" + str(rec[3]))
# print("_______________________________________")
# # for each in rec_list:
# # print(each)
# for i, listbox_entry in enumerate(rec_list.get(0, END)):
# print(listbox_entry)
rec_list.pack(side=LEFT, fill=None, expand=False)
scrollbar.config(command = rec_list.yview)
conn.commit()
conn.close()
return
"""
Calculates Total Expenses
"""
def total_expenses():
# connect to a database
conn = db.connect('expense.db')
#Create cursor for db
c = conn.cursor()
# Query the database
total_expense = 0
for row in c.execute('SELECT * FROM expenses'):
try:
total_expense += float(row[1])
except:
pass
# total_label.config(text = "Expense Total: $" + str(total_expense))
conn.commit()
conn.close()
return round(total_expense,2)
"""
Delete Records
"""
def delete():
# connect to a database
conn = db.connect('expense.db')
#Create cursor for db
c = conn.cursor()
# Delete a record
c.execute("DELETE FROM expenses WHERE oid=" + delete_entry.get())
delete_entry.delete(0, END)
conn.commit()
conn.close()
# refresh records
view_records()
return
"""Initializing Program"""
conn = db.connect("expense.db")
curr = conn.cursor()
query = '''
create table if not exists expenses (
name string,
amount number,
paid_by string,
date string
)
'''
curr.execute(query)
conn.commit()
# Creating GUI
root = Tk()
root.title("Rent Tracker")
root.geometry('600x800')
# Creating Frames
f1 = Frame(root, width=600, height=300)
f1.pack()
f2 = Frame(root, width=600, height=300)
f2.pack(fill=None, expand=False)
# Initializing List of Records and Scrollbar
scrollbar = Scrollbar(f2)
scrollbar.pack(side=RIGHT, fill=Y)
rec_list = Listbox(f2, yscrollcommand = scrollbar.set)
rec_list.config(width=250, height=200)
# Creating Labels and Entries
date_label=Label(f1,text="Date")
date_label.grid(row=1,column=0,padx=7,pady=7)
date_entry=DateEntry(f1, width=30)
date_entry.grid(row=1,column=1,padx=7,pady=7)
amount_label = Label(f1, text = "Amount")
amount_label.grid(row=2, column=0, padx=7, pady=7)
amount_entry=Entry(f1, width=30)
amount_entry.grid(row=2,column=1,padx=7,pady=7)
name_label=Label(f1, text="Expense")
name_label.grid(row=3,column=0,padx=7,pady=7)
name_entry=Entry(f1, width=30)
name_entry.grid(row=3,column=1,padx=7,pady=7)
paid_by_label = Label(f1, text = "Paid By")
paid_by_label.grid(row=4, column=0, padx=7, pady=7)
paid_by_entry=Entry(f1, width=30)
paid_by_entry.grid(row=4,column=1,padx=7,pady=7)
# Submit Button
submit_btn = Button(f1, text="Submit Expense", command=submit)
submit_btn.grid(row=5, column=0, columnspan=2, padx=10, pady=10, ipadx=100)
# Total Expenses
total_label = Label(f1, text = "Expense Total: $" + str(total_expenses()))
total_label.grid(row=6, column=0, columnspan=2)
# View Expenses
query_btn = Button(f1, text="Show Records", command=view_records)
query_btn.grid(row=10, column=0, columnspan=2, padx=10, pady=10, ipadx=105)
l=Label(f1,text="Date\t\t Amount\t\t Name\t\t Paid By", justify=CENTER)
l.grid(row=11,column=0, columnspan= 2)
# Delete Records
delete_btn = Button(f1, text="Delete Record (Enter ID)", command=delete)
delete_btn.grid(row=8, column=0, padx=10, pady=20, ipadx=50)
delete_entry = Entry(f1, width=30)
delete_entry.grid(row=8,column=1)
root.mainloop()
|
from datetime import date
todays_date = date.today()
birth_year = input("what is your birth year : ",)
your_age = int(todays_date.year) - int(birth_year)
print(your_age)
|
collageCode="333"
collageName ="Global Collage of Engineering"
# it works on index values
print("my collage cosde is {0} ,and name is {1}".format(collageCode,collageName))
print("my collage cosde is {0} ,and name is {0}".format(collageCode,collageName))
print("my collage cosde is {1} ,and name is {0}".format(collageCode,collageName))
print("my collage cosde is {1} ,and name is {1}".format(collageCode,collageName))
|
import sys
def is_int(s):
try:
int(s)
return True
except ValueError:
return False
def eval(exp, stack):
# print(exp, stack)
if len(exp) == 0:
return
if exp[-1] in ['+', "*", "-"]:
symbol = exp.pop()
ex1 = stack.pop()
ex2 = stack.pop()
if is_int(ex1) and is_int(ex2):
res = None
if symbol == "*":
res = int(ex1) * int(ex2)
elif symbol == "-":
res = int(ex1) - int(ex2)
else:
res = int(ex1) + int(ex2)
stack.append(res)
else:
stack.append("{} {} {}".format(symbol, ex1, ex2))
else:
stack.append(exp.pop())
eval(exp, stack)
count = 1
for line in sys.stdin:
exp = line.strip().split(" ")
stack = []
eval(exp, stack)
# print(exp, stack)
print("Case {}: {}".format(count, stack[-1]))
count +=1
# * - + - - *
# 6 x -6 9 6 0 c
|
cases = int(input())
def check(path):
bag = []
for c in path:
if c == ".":
pass
elif c == "$":
bag.append("$")
pass
elif c == "|":
bag.append("|")
pass
elif c == "*":
bag.append("*")
pass
elif c == "t":
if len(bag) == 0 or bag.pop() != "|":
return False
pass
elif c == "j":
if len(bag) == 0 or bag.pop() != "*":
return False
pass
elif c == "b":
if len(bag) == 0 or bag.pop() != "$":
return False
pass
return len(bag) == 0
for _ in range(cases):
if check(input().strip()):
print("YES")
else:
print("NO")
|
from Classify import Classify
from Fetch import Fetch
import json, requests
# Main class to fetch one tweet and classify
class Main():
url = None
tweets = None
fetch = None
parse = None
classifier = Classify("trainSet.json", "dictionary.json", "./liveTrain.json", "./pastTrain.json", "./liveTrainDic.json", "./pastTrainDic.json")
fetch = Fetch ()
print(classifier.classifyOne(fetch.tweets[0],1,1))
# Load parsed tweets
def loadTweets(self):
json_data = open("parsedTweets.json")
data = json.load(json_data)
return data
# Function to check tweet exists
def getTweet(self, tweet_id):
for line in self.tweets:
if int(line['id']) == tweet_id:
return line
# Save a tweet in json file
def save(self):
with open('./parsedTweets.json', 'w+') as outfile:
outfile.write(json.dumps(self.tweets, indent=4))
|
from typing import List
import numpy as np
from collections import Counter
class IntroGates:
# 8 problems
def __init__(self):
self.mintTwoDigits = self.addTwoDigits(n=15)
self.mintMaxMultiple=self.maxMultiple(divisor=3,bound=10)
self.miLateRide=self.lateRide(n=1439)
def addTwoDigits(self, n: int) -> int:
a = n % 10
b = int(n // 10)
return a + b
def largestNumber(self) -> int:
pass
def candies(self) -> int:
pass
def seatsInTheater(self) -> int:
pass
def maxMultiple(self, divisor, bound) -> int:#does not work
i = 1
while i <= bound:
N = i * divisor
if N % divisor == 0 and N <= bound:
i += 1
else:
return N
def circleOfNumbers(self) -> int: #i have seen the result but i don't understand
pass
def lateRide(self,n) -> int:
entireHours=n//60
minutes=n-entireHours*60
a=entireHours//10
b=entireHours%10
c=minutes//10
d=minutes%10
return a+b+c+d
def phoneCall(self,min1, min2_10, min11, s) -> int:#duration of the longest call
centsLeftAfter1Taryf=s-min1
if centsLeftAfter1Taryf<0:
return 0# there is not enough money for 1 min
minutesBetween1and10=1
if minutesBetween1and10*min2_10>centsLeftAfter1Taryf:
minutesBetween1and10+=1
centsLeftAfter2Taryf=centsLeftAfter1Taryf-min2_10
if centsLeftAfter1Taryf<0:
return minutesBetween1and10
minutesMoreThan10=1
if minutesMoreThan10 * min11>centsLeftAfter2Taryf:
minutesMoreThan10+=1
centsLeftAfter3Taryf=centsLeftAfter2Taryf-min11
if centsLeftAfter3Taryf<0:
return minutesMoreThan10
class atTheCrossroads:
def __init__(self):
self.mbRpgNextLevel = self.reachNextLevel(experience=10, threshold=15, reward=5)
self.mintknapsackLight = self.knapsackLight(value1=15, weight1=2, value2=20, weight2=3, maxW=2)
# self.mbIsInfinite=self.isInfiniteProcess(a=2,b=3)#does not work
self.btenis = self.tenisSet(score1=7, score2=7)
def reachNextLevel(self, experience, threshold, reward):
if experience + reward >= threshold:
return True
else:
return False
def knapsackLight(self, value1: int, weight1: int, value2: int, weight2: int, maxW: int) -> int:
if weight1 + weight2 <= maxW:
return value1 + value2
elif min(weight2, weight1) > maxW:
return 0
elif weight1 <= maxW and weight2 > maxW:
return value1
elif weight2 <= maxW and weight1 > maxW:
return value2
elif weight1 <= maxW and weight2 <= maxW and weight1 + weight2 > maxW:
return max(value1, value2)
def extraNumber(self, a: int, b: int, c: int) -> int:
if (a == b):
return c
if (a == c):
return b
if (b == c):
return a
def isInfiniteProcess(self, a: int, b: int) -> bool: # does not work
while a != b:
a += 1
b -= 1
if a == b:
return False
else:
return True
def arithmeticExpression(self, a: float, b: float, c: float) -> bool:
if a + b == c or a - b == c or a * b == c or a / b == c:
return True
else:
return False
def tenisSet(self, score1, score2): # does not work hiden 17/20 test passed
if (score1 == 6 and score2 < 5) or (score2 == 6 and score1 < 5):
return True
elif ((score1 == 7 and score1 - score2 <= 2) or (score1 == 5 and score2 - score1 <= 2)) and (score1 != score2):
return True
else:
return False
def willYou(self):
pass
def metroCard(self):
pass
class CornerOf0sAnd1s:
def __init__(self):
pass
class LoopTunnel:
def __init__(self):
self.miLeastFactorial = self.leastFactorial(n=17)
self.miRepresentationSum=self.countSumOfTwoRepresentations2(n=6,l=2,r=4)
def leastFactorial(self, n):
pass
def countSumOfTwoRepresentations2(self, n, l, r):
counter=0
a=0
b=0
while a>=l and b<=r:
if n==a+b:
counter+=1
if n<a+b
a += 1
b += 1
return counter
def magicalWell(self, a, b, n):
pass
def lineUp(self, commands):
pass
def additionWithoutCarrying(self, param1, param2):
pass
class ListForestEdge:
def __init__(self):
self.mlArray = self.createArray(size=5)
self.mlReplaicement = self.arrayReplace(inputArray=[1, 2, 1], elemToReplace=1, substitutionElem=3)
self.mlFirstReverse = self.firstReverseTry(arr=[1, 2, 3, 4, 5])
self.mlRemovePart = self.removeArrayPart(inputArray=[2, 3, 2, 3, 4, 5], l=2, r=4)
self.mbMiddle = self.isSmooth(arr=[4, 5, 6, 7, 10, 3])
self.mlReplaceMiddle = self.replaceMiddle(arr=[7, 2, 2, 5, 10, 7])
def createArray(self, size):
return [1] * size
def arrayReplace(self, inputArray, elemToReplace, substitutionElem):
for i in range(len(inputArray)):
if inputArray[i] == elemToReplace:
inputArray[i] = substitutionElem
return inputArray
def firstReverseTry(self, arr: List[int]) -> List[int]:
if len(arr) == 0:
return []
else:
f = arr[0]
l = arr[-1]
arr[0] = l
arr[-1] = f
return arr
def removeArrayPart(self, inputArray: List[int], l: int, r: int) -> List[int]:
left = inputArray[:l]
right = inputArray[r + 1:]
return left + right
def isSmooth(self, arr):
l = len(arr)
if l % 2 == 0:
rightMiddlIndex = len(arr) // 2
leftMiddleIndex = rightMiddlIndex - 1
u = arr[rightMiddlIndex] + arr[leftMiddleIndex]
if (arr[0] == arr[l - 1] == u):
return True
else:
return False
else:
middleIndex = (0 + l - 1) // 2
u = arr[middleIndex]
if arr[0] == arr[l - 1] == u:
return True
else:
return False
def replaceMiddle(self, arr):
l = len(arr)
if l % 2 == 0:
rightMiddlIndex = len(arr) // 2
leftMiddleIndex = rightMiddlIndex - 1
u = arr[rightMiddlIndex] + arr[leftMiddleIndex]
arr.pop(rightMiddlIndex)
arr.pop(leftMiddleIndex)
arr.insert(leftMiddleIndex, u)
return arr
else:
return arr
def makeArrayConsecutive2(self, statues: List[int]) -> int:
statues.sort()
missingStatues = []
for i in range(len(statues) - 1):
if statues[i + 1] - statues[i] > 1:
dif = statues[i + 1] - statues[i]
lGaps = list(range(1, dif))
for j in range(len(lGaps)):
temp = statues[i] + lGaps[j]
missingStatues.append(temp)
i += 1
return len(missingStatues)
class LabyrinthOfNestedLoops:
def __init__(self):
pass
class BookMarket:
def __init__(self):
self.msBrackets = self.encloseInBrackets(inputString="lala")
self.msNoun = self.properNounCorrection(noun='mercedes')
self.mbTandem = self.isTandemRepeat(inputString='tandemtandem')
def encloseInBrackets(self, inputString: str) -> str:
return "(" + inputString + ")"
def properNounCorrection(self, noun: str) -> str:
firstLetter = noun[0].upper()
theRest = noun[1:].lower()
return firstLetter + theRest
def isTandemRepeat(self,
inputString): # nope check len of the first half of the string is equal to the second half of the string.
d1 = {}
for ch in inputString:
d1[ch] = d1.get(ch, 0) + 1
return d1
class MirrorLake:
def __init__(self):
pass
class WellOfIntegration:
def __init__(self):
pass
if __name__ == "__main__":
introGates = IntroGates()
crossRoads = atTheCrossroads()
corner0sAnd1s = CornerOf0sAnd1s()
tunel = LoopTunnel()
forestedge = ListForestEdge()
nestedLoops = LabyrinthOfNestedLoops()
bookMarket = BookMarket()
mirrorLake = MirrorLake()
integration = WellOfIntegration()
print('the end')
|
"""CSP (Constraint Satisfaction Problems) problems and solver."""
from filecmp import cmp
from search import Problem
from utils import DefaultDict, product, argmin_list, update, count_if, argmin_random_tie, every
import itertools
class CSP(Problem):
"""This class describes finite-domain Constraint Satisfaction Problems.
A CSP is specified by the following three inputs:
vars A list of variables; each is atomic (e.g. int or string).
domains A dict of {var:[possible_value, ...]} entries.
neighbors A dict of {var:[var,...]} that for each variable lists
the other variables that participate in constraints.
constraints A function f(A, a, B, b) that returns true if neighbors
A, B satisfy the constraint when they have values A=a, B=b
In the textbook and in most mathematical definitions, the
constraints are specified as explicit pairs of allowable values,
but the formulation here is easier to express and more compact for
most cases. (For example, the n-Queens problem can be represented
in O(n) space using this notation, instead of O(N^4) for the
explicit representation.) In terms of describing the CSP as a
problem, that's all there is.
However, the class also supports data structures and methods that help you
solve CSPs by calling a search function on the CSP. Methods and slots are
as follows, where the argument 'a' represents an assignment, which is a
dict of {var:val} entries:
assign(var, val, a) Assign a[var] = val; do other bookkeeping
unassign(var, a) Do del a[var], plus other bookkeeping
nconflicts(var, val, a) Return the number of other variables that
conflict with var=val
curr_domains[var] Slot: remaining consistent values for var
Used by constraint propagation routines.
"""
def __init__(self, vars, domains, neighbors, constraints):
"Construct a CSP problem. If vars is empty, it becomes domains.keys()."
vars = vars or domains.keys()
update(self, vars=vars, domains=domains,
neighbors=neighbors, constraints=constraints,
initial={}, curr_domains=None, pruned=None, nassigns=0)
def assign(self, var, val, assignment):
"""Add {var: val} to assignment; Discard the old value if any.
Do bookkeeping for curr_domains and nassigns."""
self.nassigns += 1
assignment[var] = val
if self.curr_domains:
if self.fc:
self.forward_check(var, val, assignment)
def unassign(self, var, assignment):
"""Remove {var: val} from assignment; that is backtrack.
DO NOT call this if you are changing a variable to a new value;
just call assign for that."""
if var in assignment:
# Reset the curr_domain to be the full original domain
if self.curr_domains:
self.curr_domains[var] = self.domains[var]
del assignment[var]
def nconflicts(self, var, val, assignment):
"Return the number of conflicts var=val has with other variables."
# Subclasses may implement this more efficiently
def conflict(var2):
val2 = assignment.get(var2, None)
return val2 is not None and not self.constraints(var, val, var2, val2)
return count_if(conflict, self.neighbors[var])
def nconflictsss(self, var, val, assignment): ####
"""The number of conflicts, as recorded with each assignment.
Count conflicts in row and in up, down diagonals. If there
is a queen there, it can't conflict with itself, so subtract 3."""
n = len(self.vars)
c = self.rows[val] + self.downs[var + val] + self.ups[var - val + n - 1]
if assignment.get(var, None) == val:
c -= 3
return c
def forward_check(self, var, val, assignment):
"Do forward checking (current domain reduction) for this assignment."
if self.curr_domains:
# Restore prunings from previous value of var
for (B, b) in self.pruned[var]:
self.curr_domains[B].append(b)
self.pruned[var] = []
# Prune any other B=b assignment that conflict with var=val
for B in self.neighbors[var]:
if B not in assignment:
for b in self.curr_domains[B][:]:
if not self.constraints(var, val, B, b):
self.curr_domains[B].remove(b)
self.pruned[var].append((B, b))
def backtracking_search(csp, mcv=False, lcv=False, fc=False, mac=False, mrv=False):
"""Set up to do recursive backtracking search. Allow the following options:
mrv - If true, use Minimum Remaining Value Heuristic
fc - If true, use Forward Checking
"""
if fc or mac:
csp.curr_domains, csp.pruned = {}, {}
for v in csp.vars:
csp.curr_domains[v] = csp.domains[v][:]
csp.pruned[v] = []
update(csp, mcv=mcv, lcv=lcv, fc=fc, mac=mac, mrv=mrv)
return recursive_backtracking({}, csp)
def recursive_backtracking(assignment, csp):
"""Search for a consistent assignment for the csp.
Each recursive call chooses a variable, and considers values for it."""
if len(assignment) == len(csp.vars):
return assignment
# print('domain', ' , '.join(str(v) + ' ' + str(len(d)) for v, d in csp.curr_domains.items()))
var = select_unassigned_variable(assignment, csp)
# print('selected var', var)
for val in csp.curr_domains[var]:
# print('selected value', val)
if csp.fc or csp.nconflicts(var, val, assignment) == 0:
csp.assign(var, val, assignment)
# print(assignment)
result = recursive_backtracking(assignment, csp)
if result is not None:
return result
csp.unassign(var, assignment)
# print('back track from', var)
if csp.fc: # undo pruned values
for pruned_var in csp.pruned[var]:
csp.curr_domains[pruned_var[0]].append(pruned_var[1])
csp.pruned[var].clear()
return None
def select_unassigned_variable(assignment, csp):
"Select the variable to work on next. Find"
if csp.mcv: # Most Constrained Variable
unassigned = [v for v in csp.vars if v not in assignment]
return argmin_random_tie(unassigned,
lambda var: -num_legal_values(csp, var, assignment))
if csp.mrv: # Minimum Remaining Values
unassigned = [v for v in csp.vars if v not in assignment]
mins = argmin_list(unassigned, lambda var: len(csp.curr_domains[var]))
return mins[0]
else: # First unassigned variable
for v in csp.vars:
if v not in assignment:
return v
def order_domain_values(var, assignment, csp):
"Decide what order to consider the domain variables."
if csp.curr_domains:
domain = csp.curr_domains[var]
else:
domain = csp.domains[var][:]
if csp.lcv:
# If LCV is specified, consider values with fewer conflicts first
key = lambda val: csp.nconflicts(var, val, assignment)
#domain.sort(lambda(x,y): cmp(key(x), key(y)))
while domain:
yield domain.pop()
def num_legal_values(csp, var, assignment):
if csp.curr_domains:
return len(csp.curr_domains[var])
else:
return count_if(lambda val: csp.nconflicts(var, val, assignment) == 0,
csp.domains[var])
# Map-Coloring Problems
class UniversalDict:
"""A universal dict maps any key to the same value. We use it here
as the domains dict for CSPs in which all vars have the same domain.
>>> d = UniversalDict(42)
>>> d['life']
42
"""
def __init__(self, value): self.value = value
def __getitem__(self, key): return self.value
def __repr__(self): return '{Any: %r}' % self.value
def different_values_constraint(A, a, B, b):
"A constraint saying two neighboring variables must differ in value."
global zVariables
if 'Z' in A:
return a[zVariables[A][0].index(B)] == b
else:
return b[zVariables[B][0].index(A)] == a
def graphLabelingCSP(numbers, node_shapes):
"""Make a CSP for the problem of coloring a map with different colors
for any two adjacent regions. Arguments are a list of colors, and a
dict of {region: [neighbor,...]} entries. This dict may also be
specified as a string of the form defined by parse_neighbors"""
if isinstance(node_shapes, str):
node_shapes = parse_neighbors(node_shapes)
return CSP(node_shapes.keys(), numbers, node_shapes,
different_values_constraint)
def parse_neighbors(neighbors, vars=[]):
"""Convert a string of the form 'X: Y Z; Y: Z' into a dict mapping
regions to neighbors. The syntax is a region name followed by a ':'
followed by zero or more region names, followed by ';', repeated for
each region name. If you say 'X: Y' you don't need 'Y: X'.
>>> parse_neighbors('X: Y Z; Y: Z')
{'Y': ['X', 'Z'], 'X': ['Y', 'Z'], 'Z': ['X', 'Y']}
"""
dict = DefaultDict([])
for var in vars:
dict[var] = []
specs = [spec.split(':') for spec in neighbors.split(';')]
for (x, xneighbors) in specs:
x = x.strip()
dict.setdefault(x, [])
for B in xneighbors.split():
dict[x].append(B)
dict[B].append(x)
return dict
def AC3(csp, queue=None): ####
"""[Fig. 5.7]"""
if queue == None:
queue = [(Xi, Xk) for Xi in csp.vars for Xk in csp.neighbors[Xi]]
while queue:
(Xi, Xj) = queue.pop()
if remove_inconsistent_values(csp, Xi, Xj):
for Xk in csp.neighbors[Xi]:
queue.append((Xk, Xi))
def remove_inconsistent_values(csp, Xi, Xj):
"Return true if we remove a value."
removed = False
for x in csp.curr_domains[Xi][:]:
# If Xi=x conflicts with Xj=y for every possible y, eliminate Xi=x
if every(lambda y: not csp.constraints(Xi, x, Xj, y),
csp.curr_domains[Xj]):
csp.curr_domains[Xi].remove(x)
removed = True
return removed
zVariables = {}
if __name__ == '__main__':
print('Input:')
V = int(input())
E = int(input())
node_shapes = input().split()
# create input graph
neighborss = ''
for _ in range(E):
i, j = map(int, input().split())
# print("i",i)
# print("j",j)
neighborss += node_shapes[i] + str(i) + ':' + node_shapes[j] + str(j) + ';'
# print("neighbor_string",neighbor_string)
neighborss = neighborss[:-1]
for node, adjacents in parse_neighbors(neighborss).items():
if 'C' not in node: # circle
# binary constraints
zVariables['Z' + str(len(zVariables))] = [node] + adjacents, [
x for x in list(itertools.product(*[list(range(1, 10)) for _ in range(1 + len(adjacents))]))
if str(x[0]) == str(product(x[1:]))[0]]if 'T' in node else [ # left
x for x in list(itertools.product(*[list(range(1, 10)) for _ in range(1 + len(adjacents))]))
if str(x[0]) == str(sum(x[1:]))[0]] if 'P' in node else [ # right
x for x in list(itertools.product(*[list(range(1, 10)) for _ in range(1 + len(adjacents))]))
if str(x[0]) == str(product(x[1:]))[-1]] if 'S' in node else [ # left sum
x for x in list(itertools.product(*[list(range(1, 10)) for _ in range(1 + len(adjacents))]))
if str(x[0]) == str(sum(x[1:]))[-1]] if 'H' in node else [] # right sum
neighborss = ''
for z in zVariables:
neighborss += z + ':' + ' '.join(zVariables[z][0]) + ';'
neighborss = neighborss[:-1]
node_domain = {n: list(range(1, 10)) if 'Z' not in n else zVariables[n][1].copy()
for n in parse_neighbors(neighborss)}
problem = graphLabelingCSP(node_domain, neighborss)
solutions = backtracking_search(problem, mcv=False, lcv=False, fc=True, mac=False, mrv=True)
solutions = {k[1:]: v for k, v in solutions.items() if 'Z' not in k}
print('Output:')
print('...'.join(str(solutions[str(i)]) for i in range(V)))
#print(type(adjacents))
|
list1 = [int(x) for x in input().split()]
list2 = [int(x) for x in input().split()]
common =list(set(list1).intersection(list2))
print(common)
l1ntl2 = []
for i in list1:
if i not in(common):
l1ntl2.append(i)
print(l1ntl2)
|
def modInverse(a, m) :
a = a % m;
for x in range(1, m) :
if ((a * x) % m == 1) :
# print(f"({a} * {x}) % {m}")
return x
return 1
# Driver Program
for a in range(0,90):
k = modInverse(a, 91)
if k != 0 and k != 1:
print(a)
print("____________________________________________________________")
for a in range(0,90):
k = modInverse(a, 91)
if k != 0 and k != 1:
print(k)
|
'''
# 4195 : 친구 네트워크
# Union-find
'''
# 부모 찾기
def find(x):
if x == parent[x]:
return x
else:
# 재귀적으로 최상위 부모 찾기
p = find(parent[x])
parent[x] = p
return parent[x] # 부모값 반환
# 합집합
def union(x, y):
x = find(x)
y = find(y)
if x != y:
parent[y] = x # 최상위 부모끼리 연결
number[x] += number[y] # 다른 네트워크간 개수 합치기
n = int(input())
for _ in range(n):
parent = {} # {자식 : 부모}
number = {}
for _ in range(int(input())):
x, y = input().split(' ')
if x not in parent:
parent[x] = x # 처음 값은 자기 자신으로 초기화
number[x] = 1
if y not in parent:
parent[y] = y
number[y] = 1
union(x, y)
print(number[find(x)])
|
from nltk.corpus import stopwords
stops = set(stopwords.words("english"))
fin = open('out_posts_20000.txt', 'r')
import re
from nltk.stem.wordnet import WordNetLemmatizer
lmtzr = WordNetLemmatizer()
def fix_line(line):
line = line.lower()
line = re.sub(r"[^ a-zA-Z\n]"," ",line)
line = line.replace("\n"," ")
words = line.split(" ")
words = [w for w in words if not w in stops]
line = ""
for word in words:
if(len(word)>0):
noun_lmtzr = lmtzr.lemmatize(word,'n')
verb_lmtzr = lmtzr.lemmatize(word,'v')
if(len(word)!= len(noun_lmtzr)):
line = line + " "+ noun_lmtzr
else:
line = line + " "+ verb_lmtzr
return line
from gensim.models.doc2vec import LabeledSentence
label = 0
min_len = 3
sentences = []
for line in fin:
# line = fix_line(line)
label = label + 1
sentences = sentences + [LabeledSentence(words=line.split(" "), tags = [u"SENT_"+str(label)])]
# tokens = line.split(' ')
# temp_tokens = []
# for t in tokens:
# if(len(t)>=min_len):
# temp_tokens = temp_tokens + [t]
# temp_tokens = [w for w in temp_tokens if not w in stops]
# sentences = sentences + [temp_tokens]
# fin.close()
answer = "Encapsulation is a strategy used as part of abstraction. Encapsulation refers to the state of objects - objects encapsulate their state and hide it from the outside; outside users of the class interact with it through its methods, but cannot access the classes state directly. So the class abstracts away the implementation details related to its state. Abstraction is a more generic term, it can also be achieved by (amongst others) subclassing. For example, the interface List in the standard library is an abstraction for a sequence of items, indexed by their position, concrete examples of a List are an ArrayList or a LinkedList. Code that interacts with a List abstracts over the detail of which kind of a list it is using. Abstraction is often not possible without hiding underlying state by encapsulation - if a class exposes its internal state, it can't change its inner workings, and thus cannot be abstracted."
# sentences = sentences + [LabeledSentence(words=fix_line(answer).split(" "), tags = [u"ANSWER"])]
sentences = sentences + [LabeledSentence(words=answer.split(" "), tags = [u"ANSWER"])]
# Import the built-in logging module and configure it so that Word2Vec
# creates nice output messages
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',\
level=logging.INFO)
# Set values for various parameters
num_features = 500 # Word vector dimensionality
min_word_count = 100 # Minimum word count
num_workers = 4 # Number of threads to run in parallel
context = 15 # Context window size
downsampling = 1e-3 # Downsample setting for frequent words
# Initialize and train the model (this will take some time)
from gensim.models import doc2vec
print "Training model..."
model = doc2vec.Doc2Vec(workers=num_workers, \
size=num_features, min_count = min_word_count, \
window = context, sample = downsampling) #, alpha = 0.025, min_alpha = 0.025
model.build_vocab(sentences)
for epoch in range(3):
model.train(sentences)
model.alpha -= 0.002 # decrease the learning rate
model.min_alpha = model.alpha # fix the learning rate, no decay
model.docvecs.most_similar("ANSWER");
# If you don't plan to train the model any further, calling
# init_sims will make the model much more memory-efficient.
model.init_sims(replace=True)
# It can be helpful to create a meaningful model name and
# save the model for later use. You can load it later using Word2Vec.load()
model_name = "SO20000QDoc2Vecmodel"
model.save(model_name)
|
import cv2 as cv
#haar cascade are not used in advanced levels becuase they are not that accurate they are very senstive
img = cv.imread('C:/Users/karim.salim/Desktop/car/group2.jpg')
#shows the image
cv.imshow("Image", img)
gray= cv.cvtColor(img,cv.COLOR_BGR2GRAY)
cv.imshow('Gray person',gray)
#pass in the path of the harr_face XMl
#will read teh code and store it in the variable
# haar_cascade are very senstive against the noise of the face so anything that looks like a face will be detected as
#per ex lady gaga had many faces (nick , hiar and shirt ) that is expected from haar_cascade
#in order to solve the porblem, we have to minimize the senstivtie in scalefactgor and neighbors
haar_cascade = cv.CascadeClassifier('haar_face.xml')
#detect faces change from 3 to 6 inorder to minimze the senstivetive of haar_cascade
faces_rect = haar_cascade.detectMultiScale(gray, scaleFactor = 1.1 , minNeighbors = 1)
#number of faces detected wwill be equal to 1 because theres only one person there
print( f'number of faces found = {len(faces_rect)}')
#this draws the green rectangle around the persons face and loops
for(x,y,w,h) in faces_rect:
cv.rectangle(img, (x,y),(x+w,y+h),(0,255,0),thickness=2)
cv.imshow('Dected faces',img)
cv.waitKey(0)
|
def digits(n) :
if abs(n) < 10 :
return 1
else :
num = 0
while abs(n) >= 10:
num = num + 1
n = n // 10
return num+1
print(digits(12345))
|
import numpy as np
import matplotlib.pyplot as plt
x= np.arange(-10,11,1)
y = x*x
plt.plot(x,y)
# 加入注释
plt.annotate("this is the bottom",xy = (0,1),xytext=(0,20),
arrowprops = dict(facecolor = 'r',headlength=20,headwidth =20,width=30))
plt.show()
|
def quick_sort(arr):
_quick_sort(arr, 0, len(arr) - 1)
def _quick_sort(arr, first, last):
if first < last:
split_point = partition(arr, first, last)
_quick_sort(arr, first, split_point - 1)
_quick_sort(arr, split_point + 1, last)
def partition(arr, first, last):
pivot_value = arr[first]
left_mark = first + 1
right_mark = last
done = False
while not done:
while left_mark <= right_mark and arr[left_mark] <= pivot_value:
left_mark += 1
while arr[right_mark] >= pivot_value and right_mark >= left_mark:
right_mark -= 1
if right_mark < left_mark:
done = True
else:
temp = arr[left_mark]
arr[left_mark] = arr[right_mark]
arr[right_mark] = temp
temp = arr[first]
arr[first] = arr[right_mark]
arr[right_mark] = temp
return right_mark
array = [15, 22, 13, 27, 12, 10, 20, 25]
quick_sort(array)
print(array)
# [10, 12, 13, 15, 20, 22, 25, 27]
|
def insertion_sort(arr):
for i in range(1, len(arr)):
cur_val = arr[i]
pos = i
while pos > 0 and arr[pos - 1] > cur_val:
arr[pos] = arr[pos - 1]
pos = pos - 1
arr[pos] = cur_val
array = [20, 10, 40, 30, 60, 50, 70]
insertion_sort(array)
print(array)
# [10, 20, 30, 40, 50, 60, 70]
|
def coin_change(target, coins, known_results):
min_coins = target
if target in coins:
known_results[target] = 1
return 1
elif known_results[target] > 0:
return known_results[target]
else:
for i in [c for c in coins if c <= target]:
num_coins = 1 + coin_change(target - i, coins, known_results)
if num_coins < min_coins:
min_coins = num_coins
known_results[target] = min_coins
return min_coins
target = 74
coins = [1, 5, 10, 25]
known_results = [0] * (target + 1)
print(coin_change(target, coins, known_results))
|
import math
import os
def get_square_root(items):
square = [math.sqrt(x) for x in items]
return square
def get_square_root_loop(items):
square = []
for x in items:
square.append(math.sqrt(x))
return square
external_items = [1, 4, 9]
def get_square_root_external_variable():
square = [math.sqrt(x) for x in external_items]
return square
def get_square_root_loop_external_variable():
square = []
for x in external_items:
square.append(math.sqrt(x))
return square
def summarize_environ_values():
return {k: len(v) for k, v in os.environ.items()}
def summarize_environ_values_loop():
summary = {}
for k, v in os.environ.items():
summary[k] = len(v)
return summary
def trimmed_strings(items):
return {x.strip(): len(x) for x in items}
def trimmed_strings_loop(items):
trimmed = {}
for x in items:
trimmed[x.strip()] = len(x)
return trimmed
|
#DataFrame is a 2-dimensional labeled data structure.
import numpy as np
import pandas as pd
#From dict of Series or dicts
a = {'data' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'Scientist' : pd.Series([11., 12., 13., 14.], index=['a', 'b', 'c', 'd'])}
type(a)
b = pd.DataFrame(a)
type(b)
b
a
#To get only data column values.
ab=pd.DataFrame(a, index=['c', 'a', 'b'], columns=['Scientist'])
ab
b.index
#From dict of ndarrays / lists
d = {'one' : [1, 2, 3, 4], 'two' : [4, 3, 2, 1]}
pd.DataFrame(d)
#From a list of dicts
data = [{'a': 1, 'b': 2}, {'a': 5, 'b': 10, 'c': 20}]
pd.DataFrame(data)
#Operations using dataframe
a
a['data']
a['data'] * a['Scientist']
del a['data']
#Indexing / Selection
#Operation Syntax Result
#Select column a[col] Series
#Select row by label a.loc[label] Series
#Select row by integer location a.iloc[loc] Series
#Slice rows a[1:4] DataFrame
#Select rows by boolean vector a[bool_vec] DataFrame
b['data']
b['Scientist']
a['data']
a['Scientist']
a
b
b.loc['b']
b.iloc[2]
b.columns
#Some example of creating dataframes
ab = np.random.randint(10,20)
ab
df = pd.DataFrame(np.random.randn(10,5), columns=['A', 'B', 'C', 'D','E'])
df
index = pd.date_range('1/1/2000', periods=4)
index
|
"""
Functions as Variables
You can assign functions to variables in python. We can use this to leverage some "shell" organization in your main program of the shell assignment.
You could obviously use a huge `if then else` statement to achieve the same thing, but this will look cleaner.
Each function below is fake with crap filler just for this example.
"""
def ls(**kwargs):
params = kwargs.get('params',None)
flags = kwargs.get('flags',None)
print(f"Function: ls, params: {params}, flags: {flags}")
def rm(**kwargs):
params = kwargs.get('params',None)
flags = kwargs.get('flags',None)
print(f"Function: rm, params: {params}, flags: {flags}")
def mv(**kwargs):
params = kwargs.get('params',None)
flags = kwargs.get('flags',None)
print(f"Function: mv, params: {params}, flags: {flags}")
def wc(**kwargs):
params = kwargs.get('params',None)
flags = kwargs.get('flags',None)
print(f"Function: wc, params: {params}, flags: {flags}")
def driver(**kwargs):
fname = kwargs.get('fname',None)
params = kwargs.get('params',None)
flags = kwargs.get('flags',None)
function_lookup = {
'ls':ls,
'mv':mv,
'rm':rm,
'wc':wc
}
if fname:
function_lookup[fname](params=params,flags=flags)
if __name__=='__main__':
driver(fname='wc',flags='-l',params=['file1.txt','file2.csv'])
driver(fname='mv',flags='-l',params=['from.txt','to.txt'])
driver(fname='rm',flags='-rf',params=['dir_name'])
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
#The Class is the building block of Object oriented programming.
#A class is like a blueprint for an object
#An obejct is an instance of a class.
#When a class is defined it takes up no memory until it is instantiated.
class BrickHouse:
material = 'brick'
def __init__(self, floors, rooms, chairs, stairs, shelves, location):
self.floors = floors
self.rooms = rooms
self.chairs = chairs
self.stairs = stairs
self.shelves = shelves
self.location = location
def describe(self):
return 'The {} House has {} floors, {} rooms, {} chairs and {} shelves'\
.format(self.location, self.floors, self.rooms, self.chairs, self.shelves)
def inventory(self):
cost = 0
price_dict = {self.rooms: 1000,
self.chairs: 30,
self.floors: 3000,
self.stairs: 200,
self.shelves : 5}
for i in price_dict:
cost += i * price_dict[i]
return cost
class Shape:
def __init__(self, color, size):
self.color = color
self.size = size
class Cube(Shape):
shape_type = 'Cube'
faces = 6
edges = 12
vertices = 8
interior_angle = 90
def grow(self, factor):
self.size = self.size * factor
return print('{} grew by {} to {}'.format(self.shape_type, factor, self.size))
class Dog:
species = 'mammal'
def __init__(self, name, color, strength,mental_state):
self.name = name
self.color = color
self.strength = strength
self.mental_state = mental_state
def scream(self, words):
word_upper = str.upper(words)
return '{}!!! shouted {} the {}'.format(word_upper, self.name,
self.mental_state)
#Inheriting parent classes
class GermanShepard(Dog):
def sprint(self):
return '{} the German Shepard starts sprinting...'.format(self.name)
def guard(self):
self.strength = 75
self.aggresive = True
north_house = BrickHouse(2,5,6,1,20, 'North')
south_house = BrickHouse(1,3,2,0,1, 'South')
bilo = Dog('bilO', 'blue', 99, 'retard')
gali = GermanShepard('Gali', 'Brown', 30, 'attentive')
green_cube = Cube('green', 1)
green_cube.grow(2)
green_cube.grow(4)
green_cube.grow(6)
green_cube.grow(9)
|
# from string import ascii_lowercase
# lettermap = {c: k for k, c in enumerate(ascii_lowercase, 1)}
# print(lettermap)
""" lettermap = dict((c, k) for k, c in enumerate(ascii_lowercase, 1))
print(lettermap)
"""
""" word = 'Hello'
swaps = {c: c.swapcase() for c in word}
print(swaps)
positions = {c: k for k, c in enumerate(word)}
print(positions) """
word = 'Hello'
letters1 = set(c for c in word)
letters2 = {c for c in word}
print(letters1)
print(letters1 == letters2)
|
# late = True
# if late:
# print('Vou ligar para o meu gerente!')
# else:
# print('Não preciso ligar para meu gerente')
# chovendo = False
# if chovendo:
# print('Vou pegar o guarda-chuva!')
# else:
# print('Vou deixa-lo em casa!')
# dependents = 0
# dependent_value = 189.59
# if dependents == 1:
# print(dependent_value)
# elif dependents >= 2:
# print(dependents * dependent_value)
# else:
# print(0.0)
""" salary = 3700.00
if salary <= 1903.00:
print("Você está isento de pagar a tributação!")
elif salary >= 1903.99:
if salary <= 2826.66:
print("Sua aliquota é de 7.5% e a parcela a deduzir é de R$ 142.80")
elif salary <= 3751.05:
print("Sua aliquota é de 15% e a parcela a deduzir é de R$ 354.80")
elif salary <= 4664.05:
print("Sua aliquota é de 22% e a parcela a deduzir é de R$ 636.13")
else:
print("Sua aliquota é de 27% e a parcela a deduzir é de R$ 869.36") """
# order_total = 200
# if order_total > 100:
# discount = '10%'
# else:
# discount = 0
# print(order_total, discount)
# discount = '10%' if order_total > 100 else 0
# print(order_total, discount)
order_total = 500
discount = order_total * 0.10 if order_total > 100 else order_total
print(order_total, discount)
|
# loop enquanto
# n = 42
# remainders = []
# while n > 0:
# remainder = n % 2 # restos da divisão por 2
# remainders.insert(0, remainder) # mantemos registro dos restos
# n //= 2 # dividimos n por 2
# print(remainders)
# n = 42
# remainders = []
# while n > 0: # condição
# n, remainder = divmod(n, 2)
# remainders.insert(0, remainder)
# print(remainders)
people = ['Helena', 'Débora', 'Julio', 'André']
ages = [36, 2, 42, 6]
position = 0 # inicialização
while position < len(people): # condição
person = people[position]
age = ages[position]
print(person, age)
position += 1 # atualização
|
from typing import List, NamedTuple
from os import path
class Node(NamedTuple):
id: int
name: str
is_dir: bool
children: dict[str, NamedTuple]
size: int
parent: NamedTuple
def id_gen():
id = 0
while True:
yield id
id += 1
def build_tree(i: List[str]) -> dict:
id = id_gen()
root = Node(next(id), "", True, {}, 0, None)
current = root
for l in i:
if l.startswith("$ cd"):
d = l.split()[2]
if d == "..":
current = current.parent
elif d == "/":
current = root
else:
current = current.children[d]
elif l == "$ ls":
pass
else:
s, item = l.split()
this_id = next(id)
if s == "dir":
current.children[item] = Node(this_id, item, True, {}, 0, current)
else:
current.children[item] = Node(this_id, item, False, {}, int(s), current)
return root
def print_tree(r: Node, ind: int, sizes: dict):
s = (ind * " ") + r.name
if r.is_dir:
s += f"/ ({sizes[r.id]})"
if sizes[r.id] <= 100000:
s += " ***"
else:
s += f" ({r.size})"
print(s)
for c in r.children.values():
print_tree(c, ind+1, sizes)
def calc_sizes(r: Node, nodes: dict) -> int:
if not r.is_dir:
return r.size
s = sum(calc_sizes(n, nodes) for n in r.children.values())
nodes[r.id] = s
return s
def part1(i: List[str]) -> int:
r = build_tree(i)
sums = {}
calc_sizes(r, sums)
return sum(v for _, v in sums.items() if v <= 100000)
def part2(i: List[str]) -> int:
r = build_tree(i)
sums = {}
used = calc_sizes(r, sums)
need = 30000000 - (70000000 - used)
return min(v for _, v in sums.items() if v > need)
def default_input() -> str:
fn = path.join(path.dirname(__file__), "input.txt")
with open(fn) as i:
return parse(i.read())
def parse(i: str) -> List[str]:
return i.splitlines()
def run():
i = default_input()
print(part1(i))
print(part2(i))
def test():
i = parse("""$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k""")
print(part1(i))
print(part2(i))
if __name__ == "__main__":
test()
|
from itertools import chain
from typing import List, Tuple
from os import path
def find_start(i: List[str]) -> Tuple[int, int]:
for y, row in enumerate(i):
for x, c in enumerate(row):
if c == "S":
return (x, y)
raise ValueError("no start node")
def neighbours(p: Tuple[int, int]) -> List[Tuple[int, int]]:
yield p[0], p[1]-1
yield p[0], p[1]+1
yield p[0]-1, p[1]
yield p[0]+1, p[1]
def in_bounds(a, bounds: Tuple[int, int]) -> bool:
return a[0] >= 0 and a[0] < bounds[0] and a[1] >= 0 and a[1] < bounds[1]
def fetch(i: List[str], p: Tuple[int, int]) -> str:
return i[p[1]][p[0]]
def height_of(i: List[str], p: Tuple[int, int]) -> int:
c = fetch(i, p)
if c == "S":
return "a"
elif c == "E":
return "z"
else:
return c
def height_diff(i: List[str], p1, p2: Tuple[int, int]) -> int:
pc1 = height_of(i, p1)
pc2 = height_of(i, p2)
return ord(pc2) - ord(pc1)
def shortest_route(i: List[str], start: List[Tuple[int, int]]) -> Tuple:
bounds = len(i[0]), len(i)
routes = start
visited = set()
while len(routes) > 0:
nxt = []
for r in routes:
p = r[-1]
if fetch(i, p) == "E":
return r
for n in neighbours(p):
if n in visited:
continue
if in_bounds(n, bounds) and height_diff(i, p, n) <= 1:
visited.add(n)
nxt.append((r + (n,)))
routes = nxt
raise Exception("no route found")
def part1(i: List[str]) -> int:
return len(shortest_route(i, [(find_start(i),)])) - 1
def part2(i: List[str]) -> int:
all_as = [
[(x, y) for x, v in enumerate(row) if v == "a"]
for y, row in enumerate(i)
]
start = [(p,) for p in chain(*all_as)]
return len(shortest_route(i, start)) - 1
def default_input() -> str:
fn = path.join(path.dirname(__file__), "input.txt")
with open(fn) as i:
return parse(i.read())
def parse(i: str) -> List[str]:
return i.splitlines()
def run():
i = default_input()
print(part1(i))
print(part2(i))
def test():
i = parse("""Sabqponm
abcryxxl
accszExk
acctuvwj
abdefghi""")
print(part1(i))
print(part2(i))
if __name__ == "__main__":
test()
|
from collections import namedtuple
from itertools import product
from typing import Dict, Iterable, List, Set, Tuple
from os import path
from re import split
Point = namedtuple("Point", "x y")
Left = Point(-1, 0)
Right = Point(1, 0)
Up = Point(0, -1)
Down = Point(0, 1)
Directions = [Right, Down, Left, Up]
def add(p1: Point, p2: Point) -> Point:
return Point(p1.x + p2.x, p1.y + p2.y)
def sub(p1: Point, p2: Point) -> Point:
return Point(p1.x - p2.x, p1.y - p2.y)
def neg(p: Point) -> Point:
return Point(-p.x, -p.y)
def turn(p: Point, clockwise: bool):
idx = Directions.index(p)
if clockwise:
idx += 1
else:
idx -= 1
return Directions[idx % len(Directions)]
def wrap(frm: Point, d: Point, mapper: Dict[Point, str]) -> Point:
if d == Left:
return Point(max(p.x for p in mapper if p.y == frm.y), frm.y)
elif d == Right:
return Point(min(p.x for p in mapper if p.y == frm.y), frm.y)
elif d == Up:
return Point(frm.x, max(p.y for p in mapper if p.x == frm.x))
elif d == Down:
return Point(frm.x, min(p.y for p in mapper if p.x == frm.x))
raise ValueError("invalid direction", d)
def travel(p: Point, d: Point, i: int, mapper: Dict[Point, str]) -> Point:
for _ in range(i):
nxt = add(p, d)
if nxt not in mapper:
nxt = wrap(nxt, d, mapper)
if mapper[nxt] == "#":
return p
p = nxt
return p
def part1(i: Tuple[Dict[Point,str], List]) -> int:
mapper, ins = i
loc = Point(min(p.x for p in mapper if p.y == 0), 0)
dir = Point(1, 0)
for instruct in ins:
if instruct in ("L", "R"):
dir = turn(dir, instruct == "R")
else:
loc = travel(loc, dir, instruct, mapper)
px = loc.x + 1
py = loc.y + 1
pd = Directions.index(dir)
return 1000*py + 4*px + pd
def neighbours(p: Point) -> Iterable[Point]:
return (
add(p, Point(*m))
for m in product(*((-1, 0, 1),) * 2)
)
def get_inward(p: Point, dir: Point, mapper: Set[Point]) -> Point:
right = turn(dir, True)
left = turn(dir, False)
r_in = add(p, right) in mapper
l_in = add(p, left) in mapper
if r_in and not l_in:
return right
elif l_in and not r_in:
return left
else:
return None
def find_next(p: Point, dir: Point, mapper: Set[Point]) -> Tuple[Point, Point, Point]:
nxt = add(p, dir)
inward = get_inward(nxt, dir, mapper)
if inward is not None:
return nxt, dir, inward
right = turn(dir, True)
r_in = get_inward(p, right, mapper)
if r_in is not None and add(p, right) in mapper:
return p, right, r_in
left = turn(dir, False)
l_in = get_inward(p, left, mapper)
if l_in is not None and add(p, left) in mapper:
return p, left, l_in
inw = get_inward(p, dir, mapper)
d = neg(inw)
i = dir
nxt = add(add(p, i), d)
return nxt, d, i
def walk(start: Point, dir: Point, mapper: Set[Point]) -> Iterable[Tuple[Point, Point, Point]]:
p = start
inward = get_inward(p, dir, mapper)
while True:
yield p, dir, inward
p, dir, inward = find_next(p, dir, mapper)
Walker = namedtuple("Walker", "position direction inward")
def until_separate(w: Iterable[Tuple[Walker, Walker]]) -> Iterable[Tuple[Walker, Walker]]:
d1, d2 = None, None
for w1, w2 in w:
nd1, nd2 = w1[1], w2[1]
if d1 is not None and d2 is not None:
if d1 != nd1 and d2 != nd2:
break
d1, d2 = nd1, nd2
yield w1, w2
def perimeter(mapper: Dict[Point, str]) -> Iterable[Iterable[Tuple[Point, Point]]]:
points = set(mapper)
inner_corners = [
p for p in mapper
if len(points & set(neighbours(p))) == 8
]
for c in inner_corners:
missing = next(p for p in neighbours(c) if p not in mapper)
a, b = Point(c.x, missing.y), Point(missing.x, c.y)
ad, bd = sub(a, c), sub(b, c)
yield until_separate(zip(walk(a, ad, mapper), walk(b, bd, mapper)))
def travel2(
p: Point, d: Point, i: int,
mapper: Dict[Point, str],
move: Dict[Tuple[Point, Point], Tuple[Point, Point]],
) -> Point:
for _ in range(i):
if (p, d) in move:
nxt, nd = move[(p, d)]
else:
nxt = add(p, d)
nd = d
if mapper[nxt] == "#":
return p, d
p = nxt
d = nd
return p, d
def part2(i: Tuple[Dict[Point,str], List]) -> int:
mapper, ins = i
move = dict()
for z in perimeter(mapper):
for a, b in z:
a_p, _, a_in = a
a_out = neg(a_in)
b_p, _, b_in = b
b_out = neg(b_in)
move[(a_p, a_out)] = (b_p, b_in)
move[(b_p, b_out)] = (a_p, a_in)
loc = Point(min(p.x for p in mapper if p.y == 0), 0)
dir = Point(1, 0)
for instruct in ins:
if instruct in ("L", "R"):
dir = turn(dir, instruct == "R")
else:
loc, dir = travel2(loc, dir, instruct, mapper, move)
px = loc.x + 1
py = loc.y + 1
pd = Directions.index(dir)
return 1000*py + 4*px + pd
def default_input() -> str:
fn = path.join(path.dirname(__file__), "input.txt")
with open(fn) as i:
return parse(i.read())
def parse(i: str) -> Tuple[Dict[Point,str], List]:
mapper, instruct = i.split("\n\n")
m = dict()
for y, row in enumerate(mapper.splitlines()):
for x, c in enumerate(row):
if c != " ":
m[Point(x, y)] = c
ins = [v if v in ("L", "R") else int(v) for v in split(r"([LR])", instruct)]
return m, ins
def run():
i = default_input()
print(part1(i))
print(part2(i))
def test():
i = parse(""" ...#
.#..
#...
....
...#.......#
........#...
..#....#....
..........#.
...#....
.....#..
.#......
......#.
10R5L5R10L4R5L5""")
print(part1(i))
print(part2(i))
if __name__ == "__main__":
test()
|
"""
this module takes care of all the task that has to with delivering the lessons to the user
The format of the lesson should be as shown below when it is to be configured with a sound control object
[
{
"caption":"Name of file to speak the caption of the lesson to be delivered",
"lesson":{
"A key to be used in identifying the part on the map that was clicked":"Name of the file that contains the lesson to be delivered to the user based on the part of the map that was touched",
"A key to be used in identifying the part on the map that was clicked":"Name of the file that contains the lesson to be delivered to the user based on the part of the map that was touched"
}
}
]
And below when it is to be configured with a Text to speech converter object
[
{
"caption":"Text to be spoken as the caption of the lesson",
"lesson":{
"A key to be used in identifying the part on the map that was clicked":"A text format of the lesson to be delivered (spoken) to the user based on the part of the map that was touched",
"A key to be used in identifying the part on the map that was clicked":"A text format of the lesson to be delivered (spoken) to the user based on the part of the map that was touched"
}
}
]
"""
from speech_control import SoundControl as sc #importing the module that have been programmed to take care of sound
from text_converter import Converter as ct #importing the module that have been programmed to convert text to speech
import json
class Lesson(object):
"""
This class creates the instance for the quiz, a file is to be provided which has the record of all the audio files for each of the questions in the quiz
and also the they correct option.
"""
def __init__(self, file):
with open(file, 'r') as f:
data = f.read()
self.lessons = json.loads(data)
def configure_with_sound_control(self):
"""
The method configures the lesson with a sound control object
"""
for le in self.lessons:
le["caption"] = sc(le["caption"]) #reconfiguring the caption to a sound control object
for key in le["lesson"].keys():
le["lesson"][key] = sc(le["lesson"][key])#reconfiguring the lesson to a sound control object
self.result_sayer = sc("audio_files/LESSON MODE.wav")# specifying the result sayer
def configure_with_tts_converter(self):
"""
This method configures the lesson with a text to speech converter
"""
for le in self.lessons:
le["caption"] = ct(le["caption"]) #reconfiguring the caption to a text to speech converter object
for key in le["lesson"].keys():
le["lesson"][key] = ct(le["lesson"][key])#reconfiguring the lesson to a text to speech converter object
self.result_sayer = ct("LESSON MODE")# specifying the result sayer
def get_lesson(self, id):
"""
This gets a particular lesson dict in the lessons and returns none if there is no lesson with the index of id
"""
if id < len(self.questions) and id >= 0:
return self.questions[id]
else:
return None
def next_lesson(self, id):
"""
This returns the next lesson dict in the lessons array
"""
if id < (len(self.lessons) - 1):
return self.lessons[id+1]
else:
return None
def previous_lesson(self, id):
"""
This returns the previous lesson and returns non if they is no previous lesson
"""
if id > 0:
return self.lessons[id-1]
else:
return None
def play_lesson(self, le):
"""
This plays the lesson
Note: the quiz property of the object has to be set before this method is called else an error could be raised
"""
le["caption"].play(True) #playing the lesson
choice = self.get_user_choice() #getting the user's choice
while not (choice == "LESSON MODE" or choice == "QUIZ MODE"):#looping until the user wants to change the lesson or the mode
"""
This means that tapping the lesson button while the mode is already on lesson simply means the user wants to go to the next lesson
"""
if le["lesson"].get(choice): #checking if the user's choice of lesson is part of the lesson to be delivered
le['lesson'][choice].play(True)#playing the lesson tied to that choice
choice = self.get_user_choice() #getting the user's choice and also passing the mode so the hardware knows the current mode of operation
next_lesson = self.next_lesson(self.lessons.index(le))
if choice == "LESSON MODE":
if next_lesson is not None:#checking if there is a next lesson
return self.play_lesson(next_lesson)#playing the next lesson for the user
else:
return self.quiz.take_quiz()#taking quiz in a scenario where the user has selected quiz mode
def get_user_choice(self):
"""
This method is meant to communicate to the hardware package and get the users response
Note: the board has to be set before the method is called else it will raise an error
"""
result = self.board.get_touched()
print(self.board.touched_pins)
print(result)
self.result_sayer.say(result)# saying the received result
return result
def take_lesson(self):
"""
This takes care of the lesson
"""
if len(self.lessons) > 0:#checking if there is a lesson at all to be played
self.play_lesson(self.lessons[0])#playing the lesson
|
from math import sqrt
l = []
def lagrange(n):
i = 0
while not i == 4:
rad = sqrt(n)//1
n = n - (rad * rad)
l.append(rad*rad)
i=i+1
return l
n = input('Introduceti N: ')
print(lagrange(n))
|
'''resolvi comentar o codigo em ingles para treinar
'''
import pygame
pygame.init()
window = pygame.display.set_mode((500,480))
pygame.display.set_caption("First game project")
clock = pygame.time.Clock()
class player(object):
def __init__(self,x,y,width,height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 5
self.isJump = False
self.jumpCount = 7.5
self.left = False
self.right = False
self.walkCount = 0
self.standing = True
self.hitbox = (self.x + 17, self.y+11,29,52) #one hit box for each class (top left x, top left y,width,height)
self.visible = True
self.health = 10
self.able_to_shot =True
def draw(self,window):
if self.visible:
if self.walkCount + 1 >= 27:
self.walkCount = 0
if self.left:
window.blit(walkLeft[self.walkCount // 3], (self.x, self.y)) # image three coordinates for one image and his coordinate
self.walkCount += 1
elif self.right:
window.blit(walkRight[self.walkCount // 3], (self.x, self.y))
self.walkCount += 1
else: # if the character stops we shoot the bullet in the last direction
if self.right:
window.blit(walkRight[0],(self.x,self.y))
else:
window.blit(walkLeft[0],(self.x,self.y))
pygame.draw.rect(window, (0, 128, 0), (self.hitbox[0], self.hitbox[1] - 20, 50, 10))
pygame.draw.rect(window, (255, 0, 0), (self.hitbox[0], self.hitbox[1] - 20, 50 - (5 * (10 - self.health)),10)) # drawing two rectangles (red and green) to represent the health
self.hitbox = (self.x + 17, self.y + 11, 29, 52)
#pygame.draw.rect(window,(255,0,0),self.hitbox,2) #to draw the hitbox around the character
def hit(self):
if self.health > 0:
self.health -=1
else:
self.able_to_shot = False
self.visible = False
self.hitbox = (0,0, 31, 57)
#self.win()
class projectile(object):
def __init__(self,x,y,radius,color,facing):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.facing = facing
self.vel = 18*facing
def draw(self,window):
pygame.draw.circle(window,self.color,(self.x,self.y),self.radius)
class enemy:
walkRight = [pygame.image.load('images/R1E.png'), pygame.image.load('images/R2E.png'), pygame.image.load('images/R3E.png'), pygame.image.load('images/R4E.png'), pygame.image.load('images/R5E.png'), pygame.image.load('images/R6E.png'), pygame.image.load('images/R7E.png'), pygame.image.load('images/R8E.png'), pygame.image.load('images/R9E.png'),pygame.image.load('images/R10E.png'),pygame.image.load('images/R11E.png')]
walkLeft = [pygame.image.load('images/L1E.png'), pygame.image.load('images/L2E.png'),
pygame.image.load('images/L3E.png'), pygame.image.load('images/L4E.png'),
pygame.image.load('images/L5E.png'), pygame.image.load('images/L6E.png'),
pygame.image.load('images/L7E.png'), pygame.image.load('images/L8E.png'),
pygame.image.load('images/L9E.png'),pygame.image.load('images/L10E.png'),pygame.image.load('images/L11E.png')]
def __init__(self,x,y,width,height,end):
self.x = x
self.y = y
self.width = width
self.height = height
self.path = [x,end]
self.end = end
self.walkCount = 0
self.vel = 3
self.hitbox = (self.x+17,self.y+2,31,57)
self.health = 10
self.visible = True
def draw(self,window):
self.move()
if self.visible:
if self.walkCount + 1 >= 33: #because we have 11 images
self.walkCount = 0
if self.vel > 0: #walking to the right
window.blit(self.walkRight[self.walkCount//3],(self.x,self.y))
self.walkCount+=1
else:
window.blit(self.walkLeft[self.walkCount//3],(self.x,self.y))
self.walkCount+=1
pygame.draw.rect(window, (0, 128, 0), (self.hitbox[0], self.hitbox[1] - 20, 50, 10))
pygame.draw.rect(window, (255,0, 0), (self.hitbox[0], self.hitbox[1] - 20, 50 - (5 * (10 - self.health)), 10)) #drawing two rectangles (red and green) to represent the health
self.hitbox = (self.x+16,self.y+2,31,57)
#pygame.draw.rect(window,(255,0,0),self.hitbox,2) #to draw the hitbox around the characte
def move(self):
if self.vel>0: #moving to the right
if self.x < self.path[1]+self.vel:
self.x+=self.vel
else:
self.vel = self.vel*-1
self.x+=self.vel
self.walkCount = 0
else:
if self.x > self.path[0] - self.vel:
self.x += self.vel
else:
self.vel = self.vel*-1
self.x += self.vel
self.walkCount = 0
def hit(self):
if self.health > 0:
self.health -=1
else:
self.visible = False
self.hitbox = (0,0, 31, 57)
self.x ,self.y = 0,0
score = 0 #1 point for every bullet that hits the enemy,
font = pygame.font.SysFont("comicsans",30,True)
#font, size, bold?
pygame.mixer.music.load("balada.mp3")
pygame.mixer.music.play(-1, start = 280)
#pygame.mixer.music.play()
pygame.mixer.music.set_volume(0.30)
#this determine which way the character will walk and then we output the correct image
bullet_sound = pygame.mixer.Sound("laser.wav")
#let use lists to store the images
walkRight = [pygame.image.load('images/R1.png'), pygame.image.load('images/R2.png'), pygame.image.load('images/R3.png'), pygame.image.load('images/R4.png'), pygame.image.load('images/R5.png'), pygame.image.load('images/R6.png'), pygame.image.load('images/R7.png'), pygame.image.load('images/R8.png'), pygame.image.load('images/R9.png')]
walkLeft = [pygame.image.load('images/L1.png'), pygame.image.load('images/L2.png'), pygame.image.load('images/L3.png'), pygame.image.load('images/L4.png'), pygame.image.load('images/L5.png'), pygame.image.load('images/L6.png'), pygame.image.load('images/L7.png'), pygame.image.load('images/L8.png'), pygame.image.load('images/L9.png')]
background = pygame.image.load('images/bg.jpg')
char = pygame.image.load('images/standing.png')
x = 50
y = 400
width = 40
height = 60
bullets = [] #list for put and remove them if they have left the window
bullet_cdr = 0 #cooldown for bullets
#let's do a function for loop and draw the scene
def redrawGameWindow():
window.blit(background,(0,0))
main_character.draw(window)
goblin.draw(window)
if goblin.visible and main_character.visible:
text = font.render("Score: "+str(score),1,(0,0,0))
window.blit(text,(390,10))
for bullet in bullets:
bullet.draw(window)
if not goblin.visible:
text = font.render("YOU WON ", 1, (0, 0, 0))
window.blit(text, (180, 180))
if not main_character.visible:
font2 = pygame.font.SysFont("comicsans",60,True)
text = font2.render("SEU BOT, PERDEU! ", 1, (0, 0, 0))
window.blit(text, (30, 180))
pygame.display.update()
goblin = enemy(100,410,64,64,300)
main_character = player(x,y,width,height)
run = True
while run:
clock.tick(27)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
for bullet in bullets:
if bullet.y - bullet.radius < goblin.hitbox[1] + goblin.hitbox[3] and bullet.y - bullet.radius > goblin.hitbox[1]:
if bullet.x - bullet.radius < goblin.hitbox[0] + goblin.hitbox[2] and bullet.x - bullet.radius > goblin.hitbox[0]:
goblin.hit()
score+=1
bullets.pop(bullets.index(bullet))
if bullet.x<500 and bullet.x > 0:
bullet.x += bullet.vel
else:
bullets.pop(bullets.index(bullet)) #remove from the list
if main_character.x > goblin.x - 30 and main_character.x < goblin.x +30:
if main_character.y > goblin.y - 30 and main_character.y <goblin.y +30:
main_character.hit()
print("ai")
keys = pygame.key.get_pressed() #this will give us a dictionary where each key has a value of 0 or 1. Where 1 is pressed and 0 is not
if keys[pygame.K_q]:
int(input("entre"))
if main_character.able_to_shot:
if keys[pygame.K_SPACE]:
if main_character.left:
facing = -1
else:
facing = 1
if bullet_cdr <= 0: #limit of 5 bullets on the screen
bullets.append(projectile(round(main_character.x+main_character.width//2), #the bullet starts from the middle of the character
round(main_character.y + main_character.height//2),6,(0,0,0),facing))
bullet_cdr = 15
bullet_sound.play()
if keys[pygame.K_LEFT] and main_character.x > main_character.vel: #We can check if a key is pressed like this and making sure that the object will never get out of the screen
main_character.x-= main_character.vel
main_character.left = True
main_character.right = False
main_character.standing = False
elif keys[pygame.K_RIGHT] and main_character.x < 500 - main_character.width - main_character.vel:
main_character.x+=main_character.vel
main_character.left = False
main_character.right = True
main_character.standing = False
else: #reset the walkcounter if the character is not moving
main_character.standing = True
main_character.walkCount = 0
if not main_character.isJump:
if keys[pygame.K_UP]:
main_character.isJump = True
main_character.right = False
main_character.left = False
main_character.walkCount = 0
else:
if main_character.jumpCount >= -7.5: #jumping and falling
main_character.y -= (main_character.jumpCount * abs(main_character.jumpCount)) * 0.5
main_character.jumpCount -=1
else: #ending and reset values of the jump
main_character.jumpCount = 7.5
main_character.isJump = False
bullet_cdr -=1
redrawGameWindow()
pygame.quit()
|
class Point(object):
def __init__(self, x, y)
self.x, self.y = x, y
@staticmethod
def from_point(other):
return Point(other.x, other.y)
class Rect(object):
def __init__(self, x1, y1, x2, y2):
xl, xh = (x1,x2) if x1 < x2 else (x2,x1)
yl, yh = (y1,y2) if y1 < y2 else (y2,y1)
self.min, self.max = Point(xl, yl), Point(xh, yh)
@staticmethod
def from_points(p1,p2)
return Rect(p1.xl, p1.yl, p2.xl, p2.yl)
|
# -*- coding: utf-8 -*-
data = (2, 45, 55, 200, -100, 99, 37, 10284)
for i in data:
if i % 3 == 0:
print i
|
arr=[2,42,13,67,34,255,7,1,13,55]
def merge(arr,start,mid,end):
temp=[]
left=start
center=mid
right=end
while left<mid and center<end:
if arr[left]<=arr[center]:
temp.append(arr[left])
left+=1
else:
temp.append(arr[center])
center += 1
while left<mid:
temp.append(arr[left])
left += 1
while center<end:
temp.append(arr[center])
center += 1
c=0
for i in range(start,end):
arr[i]=temp[c]
c=c+1
def mergeSort(arr,start,end):
if start==end-1:
return [arr[start]]
else:
mid=int((start+end)/2)
left=mergeSort(arr,start,mid)
right=mergeSort(arr,mid,end)
return merge(arr,start,mid,end)
mergeSort(arr,0,len(arr))
print(arr)
|
import sys
import getpass
print ("Welcome to the game of Rock Paper Scissors")
def PlayerNames():
global player1
global player2
player1 = input("Please enter your name:")
player2 = input("Please enter your name:")
menu()
def menu():
choice = input("\nwhat do you want to do? \n"
" 1. Start a new game \n"
" 2. Change Player name \n"
" 3. Quit game \n"
"choose(1, 2, 3)")
if choice == "1":
NewGame()
elif choice == "2":
PlayerNames()
elif choice == "3":
sys.exit("3 chosen")
else:
print("invalid option")
def NewGame():
print ("starting a new game of Rock Paper Scissors")
print ("Instructions: Use r(ock), p(aper), s(cissors) as input")
allowed = ['r', 'p', 's']
#using getpass module here to hide the input.
play1choice = getpass.getpass(prompt = "player1, enter your choice:")
if play1choice not in allowed:
print("invalid input")
#continue
play2choice = getpass.getpass(prompt = "player2, enter your choice:")
if play2choice not in allowed:
print("invalid input")
#continue
else:
if play1choice == play2choice:
print ("its a tie")
menu()
elif play1choice == 'r' and play2choice == 's':
print("the winner is " + player1)
elif play1choice == 's' and play2choice == 'p':
print("the winner is " + player1)
elif play1choice == 'p' and play2choice == 'r':
print("the winner is " + player1)
else:
print(player2 + " is the winner")
menu()
PlayerNames()
|
import re
import urllib.request
import json
API_conversion = "https://api.exchangerate-api.com/v4/latest/"
def page_exists(page):
try:
urllib.request.urlopen(page)
return True
except:
return False
def currenct_conversion( convert_from, convert_to):
try:
if(page_exists(API_conversion+convert_from)):
page = urllib.request.urlopen(API_conversion+convert_from)
content = page.read().decode("utf-8")
data = json.loads(content)
from_cur = data["rates"]
rate = from_cur[convert_to]
return rate
else:
print("ERROR:invalid API endpoint")
except:
print("one or more currency codes not found")
def isValidCurrency(currency):
if currency.isupper() and len(currency)==3:
return True
return False
while True:
amount = input("Enter amount to be converted(q to quit):")
if(amount == 'q' or amount == 'Q'):
print('Input is "q",Aborting!')
break
try:
val = int(amount)
except ValueError:
try:
val = float(amount)
except ValueError:
print("No.. input is not a valid amount")
continue
from_country = input("Enter FROM currency 3 letter code: ")
if isValidCurrency(from_country) == False:
print("Invalid input...please enter 3 letters in uppler case")
continue
to_country = input("Enter TO currency 3 letter code: ")
if isValidCurrency(from_country) == False:
print("Invalid input...please enter 3 letters in uppler case")
continue
conversion_rate = currenct_conversion(from_country, to_country)
if(conversion_rate):
final_amount = float(conversion_rate) * float(amount)
print(amount+ " in "+ from_country + " = " + str(final_amount) + " in "+ to_country)
|
import pyautogui
import time
print("Welcome to autoType!\n")
message = input("Enter the text you want to type:-\n")
number = int(input("Enter how many times you would like the program to type and send the message:-\n"))
timeDelay = int(input("Enter how long you would like the program to wait before typing in seconds:-\n"))
confirm = input("WARNING: PLEASE MAKE SURE YOU ARE IN THE CORRECT TEXTFIELD BEFORE CONTINUING, WOULD YOU LIKE TO CONTINUE? (y / n):-\n")
def start(number, message, timeDelay):
print("Starting...")
time.sleep(timeDelay)
for n in range(0, number):
pyautogui.typewrite(message)
pyautogui.press("enter")
if (confirm == "y"):
start(number, message, timeDelay)
else:
print("Aborting program!...")
exit(0)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Введите с клавиатуры 5 положительных целых чисел.
# Вычислите сумму тех из них, которые делятся на 4
# и при этом заканчиваются на 6. Программа должна
# вывести одно число: сумму чисел, введенных с
# клавиатуры, кратных 4 и оканчивающихся на 6.
# Указываем длину массива
listLength = 5
# Создаём пустой массив
list = []
# Создаём пустые переменные
y = 0
a = 0
# Создаём цикл
for l in range(listLength):
# Спрашиваем числа для массива
print "vvedite chislo"
y = input()
list.append(y)
# Проверяем, подходят ли введённые числа под условия задачи
if y % 4 == 0 and y % 10 == 6:
a += y
# Выводим ответ(otvet)
print "Otvet:", a
|
# A starter program for Python with Tkinter
from tkinter import * # import Tkinter library
from tkinter.ttk import *
from tkinter import Menu
from tkinter.ttk import Progressbar
from tkinter import ttk
window = Tk() # Create the application window
# Add a label with the text "Hello"
lbl = Label(window, text="How is it going", font=("Arial Bold",50))
# Place the label in the window at 0, 0
lbl.grid(column=1, row=2)
txt = Entry(window,width=10)
txt.grid(column=1, row=0)
chk_state = BooleanVar()
chk_state.set(True)
chk = Checkbutton(window, text='Choose', var=chk_state)
chk.grid(column=1, row=3)
menu = Menu(window)
new_item = Menu(menu)
new_item.add_command(label='New')
menu.add_cascade(label='File', menu=new_item)
window.config(menu=menu)
style = ttk.Style()
style.theme_use('default')
style.configure("black.Horizontal.TProgressbar", background='yellow')
bar = Progressbar(window, length=100, style='black.Horizontal.TProgressbar')
bar.grid(column=0, row=0)
spin = Spinbox(window, from_=-100, to=100, width=10)
spin.grid(column=3,row=0)
progress = Progressbar(window, orient = HORIZONTAL,
length = 100, mode = 'determinate')
def bar():
import time
progress['value'] = 20
window.update_idletasks()
time.sleep(1)
progress['value'] = 30
window.update_idletasks()
time.sleep(1)
progress['value'] = 60
window.update_idletasks()
time.sleep(1)
progress['value'] = 80
window.update_idletasks()
time.sleep(1)
progress['value'] = 100
progress.pack(pady=10)
Button(window, text="Click Me" command=bar).pack(pady=10)
window.mainloop() # Keep the window open
|
#计算for break 语句
print('----------------------')
print('1.for语句程序正常循环')
for i in range(10):
print('当前执行:',i)
print('----------------------')
print('2.for语句程序break中断')
for i in range(10):
if(i>=5): break
print('当前执行:',i)
print('----------------------')
print('3.for语句程序continue跳过')
for i in range(10):
if( i%2 == 0 ): continue
print('当前执行:',i)
|
# Towers of Hanoi
'''
You have three disks of varying sizes (large, medium, small) - these disks are stacked on top
of one another on a single tower/rod.
Problem Rules:
1. Only one disk can be moved at a time
2. Each move consists of taking the upper disk from one of the stacks and placing it atop another stacks
3. No disk may be placed on top of a smaller disks
'''
def printMove(fr, to):
print('move from' + str(fr) + 'to' + str(to))
def Towers(n, fr, to, spare): # three towers, one named 'from', one named 'to', and one named 'spare'
if n == 1:
printMove(fr, to)
else:
Towers(n - 1, fr, spare, to)
Towers(1, fr, to, spare)
Towers(n - 1, spare, to, fr)
Towers(3, 1, 2, 3)
|
import turtle
wn = turtle.Screen()
wn.bgcolor("lightgreen")
tess = turtle.Turtle()
tess.pensize(3)
def drawBar(t, height):
for i in height:
t.begin_fill()
if i >= 200:
t.fillcolor("red")
elif i >= 100 and i < 200:
t.fillcolor("yellow")
elif i < 100:
t.fillcolor("green")
t.left(90)
t.forward(i)
if i > 0:
t.penup()
t.forward(5)
t.pendown()
t.write(str(i))
t.penup()
t.backward(5)
t.pendown()
elif i < 0:
t.penup()
t.backward(i)
t.pendown()
t.write(str(i))
t.penup()
t.forward(i)
t.pendown()
t.right(90)
t.forward(40)
t.right(90)
t.forward(i)
t.left(90)
t.end_fill()
def main():
xs = [48, -117, 200, -240, 160, 260, 220]
drawBar(tess, xs)
wn.exitonclick()
main()
|
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 12 16:54:08 2021
Q asked in Microsft interview
@author: Ashish
"""
def removeZeros(ip):
# splits the ip by "."
# converts the words to integeres to remove leading removeZeros
# convert back the integer to string and join them back to a string
new_ip = ".".join([str(int(i)) for i in ip.split(".")])
return new_ip
# driver code
# example1
ip ="100.020.003.400"
print(removeZeros(ip))
# example2
ip ="001.200.001.004"
print(removeZeros(ip))
|
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 21 09:02:51 2021
Objective: To generate a random list of email addresses and write to file
Reference: https://codereview.stackexchange.com/questions/58269/generating-random-email-addresses
@author: Ashish
"""
import random, string
domains = ["hotmail.com", "gmail.com", "aol.com", "mail.com", "mail.kz", "yahoo.com"]
letters = string.ascii_lowercase[:12]
def get_random_domain(domains):
return random.choice(domains)
def get_random_name(letters, length):
return "".join(random.choice(letters) for i in range(length))
def generate_random_emails(nb, length):
return [
get_random_name(letters, length) + "@" + get_random_domain(domains)
for i in range(nb)
]
def main():
# 7 refers to the number of chars in username part of the email id
# 100 referes to the number of email address required
print(generate_random_emails(100, 7))
if __name__ == "__main__":
main()
|
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 21 10:11:18 2020
The given program will transform a single column containing categorical vars into boolean values
@author: Ashish
"""
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
df = pd.DataFrame({'EDUCATION':['high school','high school','high school',
'university','university','university',
'graduate school', 'graduate school','graduate school',
'others','others','others']})
print(df)
onehot_encoder = OneHotEncoder(sparse=False)
# print(onehot_encoder)
df1=onehot_encoder.fit_transform(df['EDUCATION'].to_numpy().reshape(-1,1))
print(df1)
|
def som(getal1, getal2, getal3):
return getal1 + getal2 + getal3
getal1 = float(input('voer een getal in: '))
getal2 = float(input('voer een tweede getal in: '))
getal3 = float(input('voer een derde getal in: '))
print(som(getal1, getal2, getal3))
|
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np
rng = np.random.RandomState(1)
x = 10 * rng.rand(50)
y = 2 * x - 5 + rng.randn(50)
plt.scatter(x, y);
plt.show()
from sklearn.linear_model import LinearRegression
model = LinearRegression(fit_intercept=True)
model.fit(x[:, np.newaxis], y)
xfit = np.linspace(0, 10, 1000)
yfit = model.predict(xfit[:, np.newaxis])
plt.scatter(x, y)
plt.plot(xfit, yfit);
print("Model slope: ", model.coef_[0])
print("Model intercept:", model.intercept_)
plt.show()
rng = np.random.RandomState(1)
X = 10 * rng.rand(100, 3)
y = 0.5 + np.dot(X, [1.5, -2., 1.])
model.fit(X, y)
print(model.intercept_)
print(model.coef_)
from sklearn.preprocessing import PolynomialFeatures
x = np.array([2, 3, 4])
poly = PolynomialFeatures(3, include_bias=False)
poly.fit_transform(x[:, None])
from sklearn.pipeline import make_pipeline
poly_model = make_pipeline(PolynomialFeatures(7),
LinearRegression())
rng = np.random.RandomState(1)
x = 10 * rng.rand(50)
y = np.sin(x) + 0.1 * rng.randn(50)
poly_model.fit(x[:, np.newaxis], y)
yfit = poly_model.predict(xfit[:, np.newaxis])
plt.scatter(x, y)
plt.plot(xfit, yfit);
plt.show()
|
def dependencia(input):
dicionario = {}
for classe in input:
c = classe.pop(0)
deps = classe
dicionario[c].append(deps)
result = set()
for k, v in dicionario:
recurseDependency(set, dicionario, k, v)
return result
def recurseDependency(set, dicionario, classe, dependencias):
if !dicionario[classe]:
return
set.add(dependencias)
recurseDependency(set, dicionario, dicionario[dependencias[0]])
|
class Alphabet:
def getCharCode(self, letter):
return ord(letter.lower())
def isInRange(self, letter):
beginIndex = self.getCharCode('a')
endIndex = self.getCharCode('z')
charIndex = self.getCharCode(letter)
return 1 if charIndex >= beginIndex and charIndex <= endIndex else 0
def isInOrder(self, firstLetter, secondLetter):
if not self.isInRange(firstLetter) or not self.isInRange(secondLetter):
return False
if (self.getCharCode(secondLetter) - self.getCharCode(firstLetter) > 0):
return True
return False
def getLettersInRange(self, firstLetter, secondLetter):
if not self.isInOrder(firstLetter, secondLetter):
return -1
firstCharCode = self.getCharCode(firstLetter)
secondCharCode = self.getCharCode(secondLetter)
return secondCharCode - firstCharCode - 1
if __name__ == "__main__":
alf = Alphabet()
a = input('First letter: ')
b = input('Second letter: ')
distance = alf.getLettersInRange(a, b)
if distance >= 0:
print("All right! The distance between letter {0} and {1} is {2}. :D".format(a,b,distance))
else:
print("Oh no! The letters must be in order! D:")
|
# ---------------------------
# Sogol Moshtaghi
# Oscar chavarria
# PFD
# ---------------------------
import Queue
# ------------
# PFD_read
# ------------
def PFD_read (r, a) :
"""
reads one line of the input and populates the list of predecessors
r is a reader
a is a list of predecessors
return true if the read was successful, false otherwise
"""
s = r.readline()
if s == "" :
return False
l = s.split()
size = len(l)
l_idx = 1
while l_idx < size :
assert int(l[l_idx]) > 0
assert int(l[l_idx]) < 101
assert int(l[0]) != 0
a[int(l[0])][l_idx-1] = int(l[l_idx])
l_idx += 1
return True
# ------------
# PFD_eval
# ------------
def PFD_eval(i,j,w):
"""
populating the list of successors and creating a PriorityQueue
i is the list of predecessors
j is the list of successors
w is a reader
returns the result of calling PFD_romoval
"""
i_size = len(i[0]) #populating the list of successors created in PFD_solve
idx = 1
while i_size > idx :
jdx = 1
while i_size > jdx :
if i[idx][jdx] != 0 :
j[i[idx][jdx]].append(idx)
jdx += 1
idx += 1
pq = Queue.PriorityQueue()
i_size = len(i)
idx = 1
while i_size > idx :
if i[idx][0] == 0:
pq.put(idx) #populating the PriorityQueue
idx += 1
return PFD_removal(i,pq,j,w)
# ------------
# PFD_removal
# ------------
def PFD_removal(i,pq,j,w):
"""
looping in the priority queue and marking the visited vertex in predecessor list, updating the successors count, creating the result
i is the predecessor list
pq is the priority queue
j is the successors list
w is a writer
"""
result = ""
while not pq.empty():
removal = pq.get()
removal_list = []
removal_list.append(removal)
removal_size = len(removal_list)
idx = 0
while idx < removal_size :
i[removal][0] = -1
list_idx = [k for k, e in enumerate(j[removal]) if e != 0] #getting the list of indeces of non-zero elements in the successors list
size_list_idx = len(list_idx)
index = 0
list_successors = []
while index < size_list_idx:
list_successors.append(j[removal][list_idx[index]]) #creating a list of actual successors using the index list
index += 1
size_list_successors = len(list_successors)
index = 0
while index < size_list_successors:
i[list_successors[index]][0] -= 1
if i[list_successors[index]][0] == 0:
pq.put(list_successors[index])
index += 1
idx += 1
result += str(removal) + " "
return PFD_print(w, result)
# ------------
# PFD_print
# ------------
def PFD_print(w,v):
"""
prints the result
w is a writer
v is the result to be printed
return the printed result on the
"""
w.write(v)
# ------------
# PFD_solve
# ------------
def PFD_solve (r, w) :
"""
read, eval, removal, print result, creates lists of successors and predecessors
r is a reader
w is a writer
"""
counter = 0
s = r.readline()
if s == "" :
return false
l = s.split()
vertex_count = int(l[0])
rule_count = int(l[1])
a = [[0]*(vertex_count+1) for _ in range(vertex_count+1)] #Creates 2D list that has individual references to each cell
successors = [[0]*(1) for _ in range(vertex_count+1)]
while PFD_read(r, a) :
counter += 1
v = PFD_eval(a, successors,w)
|
#x,y and z representing the dimensions of a cuboid along with an integer n.
#print a list of all possible coordinates given by (i,j,k) on a 3D grid
#where the sum of i+j+k is not equal to n.
#print the list in lexicographic increasing order.
x,y,z,n = (int(input()) for _ in range(4))
coordinates = [[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if i+j+k != n]
print(coordinates)
|
"""Create files and symbolic links in a way that appears to be an atomic file-system operation.
It is sometimes useful that files and symbolic links are created with the intermediate write operations hidden.
Temporary files and symbolic links are used and the final update operation is atomic.
"""
import errno
import logging
import os
import tempfile
__author__ = 'Steve Marple'
__version__ = '0.3.0'
__license__ = 'MIT'
class smart_open:
"""A smarter way to open files for writing.
This class mimics the behaviour of::
with open(filename) as handle:
but with two additional benefits:
1. When opening a file for write access (including appending) the
parent directory will be created automatically if it does not
already exist.
2. When opening a file for write access it is created with a temporary
name (with a .tmp extension) and if there are no errors it is renamed automatically
when closed. In the case of errors the default is to delete the temporary file,
to keep the temporary file call :py:func:`smart_open` with ``delete_temp_on_error=False``.
The temporary extension can be overridden with the ``temp_ext`` parameter.
The use of a temporary file is automatically disabled when the mode
includes ``'r'``, ``'x'``, ``'a'``, or ``'+'``. It can be prevented manually by calling :py:func:`smart_open`
with ``use_temp=False``. When a temporary file is used it will be
deleted automatically if an exception occurs; this behaviour can be prevented by calling
with ``delete_temp_on_error=False``.
For security reasons the temporary files are created with restricted read and write permissions.
To maintain the atomic behaviour do not call :py:func:`os.chmod` after :py:func:`smart_open`, instead pass
the appropriate file mode permissions with ``chmod=perms``.
Example use::
with smart_open('/tmp/dir/file.txt', 'w') as f:
f.write('some text')
"""
def __init__(self,
filename,
mode='r',
use_temp=None,
delete_temp_on_error=True,
chmod=None,
temp_ext='.tmp'):
# Modes which rely on an existing file should not change the name
cannot_use_temp = 'r' in mode or 'x' in mode or 'a' in mode or '+' in mode
self.filename = filename
self.mode = mode
self.delete_temp_on_error = delete_temp_on_error
if chmod is None:
# Must set umask to find current umask
current_umask = os.umask(0)
os.umask(current_umask)
self.chmod = (~current_umask & 0o666) # No execute, read and write as umask allows
else:
self.chmod = chmod
self.file = None
self.temp_ext = temp_ext
if use_temp and cannot_use_temp:
raise ValueError('cannot use temporary file with mode "%s"' % mode)
elif use_temp is None:
self.use_temp = not cannot_use_temp
else:
self.use_temp = use_temp
def __enter__(self):
d = os.path.dirname(self.filename)
if (d and not os.path.exists(d) and
('w' in self.mode or 'x' in self.mode
or 'a' in self.mode or '+' in self.mode)):
logger.debug('creating directory %s', d)
os.makedirs(d)
if self.use_temp:
d = os.path.dirname(self.filename)
self.file = tempfile.NamedTemporaryFile(self.mode, suffix=self.temp_ext, dir=d, delete=False)
else:
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, traceback):
if self.file is not None:
if not self.file.closed:
self.file.close()
if exc_type is None:
if self.chmod: # Deliberately not applied when chmod == 0
os.chmod(self.file.name, self.chmod)
if self.file.name != self.filename:
logger.debug('renaming %s to %s',
self.file.name, self.filename)
# For better compatibility with Microsoft Windows use os.replace() if available,
# otherwise use os.rename()
getattr(os, 'replace', os.rename)(self.file.name, self.filename)
elif self.delete_temp_on_error:
os.remove(self.file.name)
def atomic_symlink(src, dst):
"""Create or update a symbolic link atomically.
This function is similar to :py:func:`os.symlink` but will update a symlink atomically."""
dst_dir = os.path.dirname(dst)
tmp = None
max_tries = getattr(os, 'TMP_MAX', 10000)
try:
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
for n in range(max_tries):
try:
# mktemp is described as being unsafe. That is not true in this case since symlink is an
# atomic operation at the file system level; if some other processes creates a file with
# 'our' name then symlink will fail.
tmp = tempfile.mktemp(dir=dst_dir)
os.symlink(src, tmp)
logger.debug('created symlink %s', tmp)
except OSError as e:
if e.errno == errno.EEXIST:
continue # Someone else grabbed the temporary name first
else:
raise
logger.debug('renaming %s to %s', tmp, dst)
os.rename(tmp, dst)
return
except:
if tmp and os.path.exists(tmp):
os.remove(tmp)
raise
raise IOError(errno.EEXIST, 'No usable temporary file name found')
logger = logging.getLogger(__name__)
|
__author__ = "Sylvain Dangin"
__licence__ = "Apache 2.0"
__version__ = "1.0"
__maintainer__ = "Sylvain Dangin"
__email__ = "[email protected]"
__status__ = "Development"
from datetime import datetime
class date_format():
def action(input_data, params, current_row, current_index):
"""Convert date from a specified format to another format
:param input_data: String of the date to convert
:param params: dict with 2 keys:
- input: Format of the input date (Example: %Y-%m-%d)
- output: Format of the output date (Example: %Y/%m/%d)
:param current_row: Not used
:param current_index: Not used
:return: Input date converted
:rtype: str
"""
if isinstance(input_data, str) and isinstance(params, dict) and input_data is not "":
if 'input' in params and 'output' in params:
try:
d = datetime.strptime(input_data, params['input'])
return d.strftime(params['output'])
except ValueError:
return input_data
return input_data
|
# -*- coding: utf-8 -*-
import datetime
def calcular_tiempo_recorrido(distancias, velocidad):
"""
Definicion de la funcion calcular_tiempo_recorrido:
Funcion de calculo del tiempo de recorrido
Parametros
----------
distancias: Pandas Dataframe
Dataframe que contiene las distancias entre nodos
velocidad: float
float con velocidad media del coche
Returns
------
tiempos_recorrido: Pandas Dataframe
Pandas Dataframe que el tiempo de recorrido para cada arista
Ejemplo
-------
>>> df_distancias_reduced["Time_h"] = Tiempos.calcular_tiempo_recorrido(df_distancias_reduced["Distance_km"],velocidad_coche)
"""
tiempos_recorrido = (1.2*distancias)/velocidad
return tiempos_recorrido
def calcular_tiempo_parada(capacidad_bateria, potencia_pc, punto_recarga, num_electricPump, timestamp, lista_definitiva, rendimiento_carga):
"""
Definicion de la funcion calcular_tiempo_parada:
Funcion de calculo del tiempo de parada
Parametros
----------
distancias: Pandas Dataframe
Dataframe que contiene las distancias entre nodos
capacidad_bateria: float
float con capacidad de bateria para el coche
potencia_pc: float
float con potencia para el punto de carga
numero_conectores_pc: float
float con numero de conectores para el punto de carga
Returns
------
tiempo_parada: float
Tiempo de parada para ese punto y coche
Ejemplo
-------
>>> tiempos_puntos_parada.append((punto_carga["id"],
Tiempos.calcular_tiempo_parada(capacidad_coche,potencia_pc,numero_conectores_pc)))
"""
tiempo_recarga = calcular_tiempo_recarga(potencia_pc, capacidad_bateria, rendimiento_carga)
tiempo_espera = calcular_tiempo_espera_cola(punto_recarga, num_electricPump, timestamp, lista_definitiva)
tiempo_parada = tiempo_recarga + tiempo_espera
return tiempo_parada
# ANOTACIONES TIEMPO DE RECARGA:
# Va a depender de:
# 1)Como de cargado este el coche --> vamos a suponer una cte de 10% de bateria
# 2)Tipo de carga que ofrezca el punto de carga --> una potencia concreta
def calcular_tiempo_recarga(potencia_pc, capacidad_bateria, rendimiento_carga):
"""
Definicion de la funcion calcular_tiempo_recarga:
Funcion de calculo del tiempo de recarga para un coche
y punto de recarga especifico
Parametros
----------
potencia_pc: float
Float con la potencia del punto de carga
capacidad_bateria: float
Float con capacidad de bateria para el coche
rendimiento_carga: float
Float con el rendimiento del proceso de carga
Returns
------
tiempo_recarga: float
Tiempo de recarga para ese punto y coche
Ejemplo
-------
>>> tiempo_recarga = calcular_tiempo_recarga(potencia_pc,
capacidad_bateria,
rendimiento_carga)
"""
tiempo_recarga = capacidad_bateria / (potencia_pc * rendimiento_carga)
return tiempo_recarga
def calcular_tiempo_espera_cola(punto_recarga, num_electricPump, timestamp, lista_definitiva):
"""
Definicion de la funcion calcular_tiempo_espera_cola:
Funcion de calculo del tiempo de espera segun la
teoria de colas en un punto de recarga especifico
Parametros
----------
punto_recarga: string
String con el id del punto de recarga
num_electricPump: int
Int con el número de surtidores del punto de recarga
timestamp: datetime
Datetime de la hora de la consulta
lista_definitiva: list[string]
Lista de ids de los puntos de recarga/gasolineras a
menos de 50 km de una ciudad importante
Returns
------
tiempo_espera_cola: float
Tiempo de espera de cola para ese punto y coche
Ejemplo
-------
>>> tiempo_espera = calcular_tiempo_espera_cola(punto_recarga,
num_electricPump,
timestamp,
lista_definitiva)
"""
landa1 = valor_lambda(punto_recarga, timestamp, lista_definitiva)
mu = 3
factor_congestion = landa1 / (num_electricPump * mu)
inicio = 0
final = num_electricPump - 1
def sumatorio(inicio,final):
control = 0
n = range(0, final + 1)
for x in n:
control += pow((landa1/mu),x) / factorial(x) + (1/factorial(num_electricPump)) * pow((landa1/mu),num_electricPump) * (1/(1-factor_congestion))
return control
probab_no_cola = 1 / sumatorio(inicio,final)
num_usuarios_cola = pow((landa1/mu),num_electricPump) * landa1 * mu / (factorial(final) * pow((num_electricPump*mu-landa1),2)) * probab_no_cola
tiempo_espera_cola = num_usuarios_cola / landa1
return tiempo_espera_cola
def valor_lambda(punto_recarga, timestamp, lista_definitiva):
"""
Definicion de la funcion valor_lambda:
Funcion de calculo del parámetro lambda de la teoría
de colas
Parametros
----------
punto_recarga: string
String con el id del punto de recarga
timestamp: datetime
Datetime de la hora de la consulta
lista_definitiva: list[string]
Lista de ids de los puntos de recarga/gasolineras a
menos de 50 km de una ciudad importante
Returns
------
landa: int
Parámetro lambda de la teoría de colas para cálculo
de tiempo de espera
Ejemplo
-------
>>> landa1 = valor_lambda(punto_recarga, timestamp, lista_definitiva)
"""
# Obtenemos hora y mes actuales (instante en que usuario realiza su consulta)
hora = timestamp.hour
mes = timestamp.month
horario_diurno = list(range(7,23))
periodo_vacacional = list(range(5,10))
if punto_recarga in lista_definitiva:
if hora in horario_diurno:
if mes in periodo_vacacional:
landa = 8
else:
landa = 4
elif mes in periodo_vacacional:
landa = 4
else:
landa = 2
elif hora in horario_diurno:
if mes in periodo_vacacional:
landa = 2
else:
landa = 1
elif mes in periodo_vacacional:
landa = 1
else:
landa = 1
return landa
# Funcion para calcular el factorial de un numero entero
def factorial(entero):
"""
Definicion de la funcion factorial:
Funcion de calculo del factorial de un numero entero
Parametros
----------
entero: int
Entero del que calcular el factorial para cálculo de
tiempo de espera
Returns
------
resultado: int
Entero con el factorial de entero
Ejemplo
-------
>>> num_usuarios_cola = pow((landa1/mu),num_electricPump) * landa1 * mu
/ (factorial(final) * pow((num_electricPump*mu-landa1),2)) * probab_no_cola
"""
resultado = 1
i = 1
while i <= entero:
resultado = resultado * i
i = i + 1
return resultado
|
# I understood the task as creating a dictionary and then getting a user to enter a sentence to count the amount of
# times that it occured in your dictionary. Taking a look at the solution I noticed it was different.
dictionary = {"a": 0, "be": 0, "car": 0, "drive": 0, "cat": 0, "fun": 0, "dog": 0, "alpha": 0,
"kitty": 0, "love": 0, "meme": 0, "review": 0, "subscribe": 0, "youtube": 0}
# user_string = input("Please enter a sentence: ")
user_string = " a be car drive a be car drive a be car drive a be car drive a be car drive a be car drive subscribe"
# split the string so each word is it only value in the list.
words = user_string.split()
for words in words:
if words in dictionary:
dictionary[words] += 1
else:
pass
# I noticed in the solution that if I created the dictionary by storing the user values then the below code would work.
# Since I made the dictionary and compared it to the sentence I can set a max value for it to line up.
# max_length = max(len(words) for user_string in words)
for word, value in dictionary.items():
print("{:{}} = {}".format(word, 9, value))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
######### library ##########
import time
import datetime
################################## Fonction Gestion ################################
def find_list(l1,l2): # cherche si un argument de "l1" et dans "l2" et retourne sont n'indice
i = 0
while i < len(l1):
j = 0
while j < len(l2):
if l1[i] == l2[j]:
return j
else :
j = j + 1
i = i + 1
return "false"
def find_word(w,li): # cherche un mot "w" dans une liste "li" et retourne "ok" si oui
k = 0
while k < len(li):
if w == li[k]:
return "ok"
break
else:
k=k+1
return "false"
def supp_balise(t_char): # supprime les balise HTML dans un tableau de charactere
new_t_char = [" "]*(len(t_char))
length = len(t_char)
balise = 0
i = 0
j = 0
while j <= (length-1):
if t_char[j] == '<' and balise == 0:
j = j + 1
balise = 1
elif t_char[j] == '>' and balise == 1:
j = j + 1
balise = 0
elif balise == 1:
j = j + 1
else:
new_t_char[i] = t_char[j]
j = j + 1
i = i + 1
return "".join(new_t_char)
def supp_spec(t_char):
new_t_char = [" "]*(len(t_char))
length = len(t_char)
i = 0
j = 0
while j <= (length-1):
if t_char[j] == '[':
j = j + 1
elif t_char[j] == ']':
j = j + 1
elif t_char[j] == '{':
j = j + 1
elif t_char[j] == '}':
j = j + 1
elif t_char[j] == ':':
j = j + 1
elif t_char[j] == ',':
j = j + 1
elif t_char[j] == 'u':
j = j + 1
if t_char[j] == "'":
j = j + 1
else:
j + j - 1
elif t_char[j] == "'":
j = j + 1
if t_char[j] == " ":
j = j - 1
else:
j + j - 1
else:
new_t_char[i] = t_char[j]
j = j + 1
i = i + 1
return "".join(new_t_char)
def make_str(ordre,index,length): # decoupe un tableau de string a partir de l'argument "index" a "length"
request = [0]*(((length - index) * 2) - 1)
j = 0
while index <= (length-1):
request[j] = ordre[index]
index = index + 1
j = j + 1
if j < len(request):
request[j] = " "
j = j + 1
return "".join(request)
def make_ordre(ordre): # construit un tableau de string a partir du tableau de char
space_count = 0
count_char = 0
length = 0
space = 0
i = 0
j = 0
k = 0
z = 0
while i < len(ordre):
if ordre[i] == " " and space == 0:
space_count = space_count + 1
space = 1
i = i + 1
else:
space = 0
i = i + 1
length = space_count + 1
new_ordre = [" "]*length
i = 0
while i < length:
count_char = 0
while ordre[z] != " ":
count_char = count_char + 1
z = z + 1
if z == len(ordre):
break
temp = [" "]*count_char
while ordre[j] != " ":
temp[k] = ordre[j]
j = j + 1
k = k + 1
if k == count_char:
break
new_ordre[i] = "".join(temp)
i = i + 1
if j < len(ordre) and i < length:
if ordre[j] == " ":
j = j + 1
if z < len(ordre) and i < length:
if ordre[z] == " ":
z = z + 1
k = 0
return new_ordre
def make_date(index,index2):
now = datetime.datetime.now()
from_day = 0
to_day = 0
from_month = 0
to_month = 0
date = [0]*2
if index == 0 and index2 == "false": # aujourd'hui
from_day = 0
to_day = 0
elif index == 1 and index2 == "false": # demain
from_day = 1
to_day = 1
elif index == 1 and index2 == 4: # apres demain
from_day = 2
to_day = 2
elif index == 2 and index2 == 2 or index == 2 and index2 == "false": # ce weekend
day = time.strftime('%A',time.localtime())
if day == "Sunday":
from_day = -1
to_day = 0
elif day == "Monday":
from_day = 5
to_day = 6
elif day == "Tuesday":
from_day = 4
to_day = 5
elif day == "Wednesday":
from_day = 3
to_day = 4
elif day == "Thursday":
from_day = 2
to_day = 3
elif day == "Friday":
from_day = 1
to_day = 2
elif day == "Saturday":
from_day = 0
to_day = 1
elif index == 2 and index2 == 0: # le weekend prochain
day = time.strftime('%A',time.localtime())
if day == "Sunday":
from_day = 6
to_day = 7
elif day == "Monday":
from_day = 12
to_day = 13
elif day == "Tuesday":
from_day = 11
to_day = 12
elif day == "Wednesday":
from_day = 10
to_day = 11
elif day == "Thursday":
from_day = 9
to_day = 10
elif day == "Friday":
from_day = 8
to_day = 9
elif day == "Saturday":
from_day = 7
to_day = 8
elif index == 3 and index2 == 3 or index == 3 and index2 == "false": # cette semaine
day = time.strftime('%A',time.localtime())
if day == "Sunday":
from_day = 0
to_day = 0
elif day == "Monday":
from_day = 0
to_day = 6
elif day == "Tuesday":
from_day = -1
to_day = 5
elif day == "Wednesday":
from_day = -2
to_day = 4
elif day == "Thursday":
from_day = -3
to_day = 3
elif day == "Friday":
from_day = -4
to_day = 2
elif day == "Saturday":
from_day = -5
to_day = 1
elif index == 3 and index2 == 1: # la semaine prochaine
day = time.strftime('%A',time.localtime())
if day == "Sunday":
from_day = 1
to_day = 7
elif day == "Monday":
from_day = 7
to_day = 13
elif day == "Tuesday":
from_day = 6
to_day = 12
elif day == "Wednesday":
from_day = 5
to_day = 11
elif day == "Thursday":
from_day = 4
to_day = 10
elif day == "Friday":
from_day = 3
to_day = 9
elif day == "Saturday":
from_day = 2
to_day = 8
elif index == 4 and index2 == 2 or index == 4 and index2 == "false": # ce mois
from_day = -now.day + 1
to_day = -now.day + 1
from_month = 0
to_month = 1
elif index == 4 and index2 == 0: # mois prochain
from_day = -now.day + 1
to_day = -now.day + 1
from_month = 1
to_month = 2
date[0] = datetime.datetime(now.year, now.month + from_month, now.day + from_day)
date[1] = datetime.datetime(now.year, now.month + to_month, now.day + to_day)
#print date
return date
def make_cal(event):
i = 0
count_event = 0
while i < len(event):
if event[i] == "startDate":
count_event = count_event + 1
i = i + 1
else:
i = i + 1
i = 0
j = 0
k = 0
l = 0
t_event = [[" "]*3 for _ in range(count_event)]
t_cut = [""]*11
while j < count_event:
while k < len(event):
if event[k] == "startDate":
i = 0
t_cut[i] = "de "
i = i + 1
k = k + 5
t_cut[i] = event[k]
k = k + 1
i = i + 1
t_cut[i] = " heures "
i = i + 1
t_cut[i] = event[k]
k = k - 2
i = i + 1
t_cut[i] = ", le "
i = i + 1
t_cut[i] = event[k]
k = k - 1
i = i + 1
t_cut[i] = "/"
i = i + 1
t_cut[i] = event[k]
k = k - 1
i = i + 1
t_cut[i] = "/"
i = i + 1
t_cut[i] = event[k]
t_event[j][l] = "".join(t_cut)
l = l + 1
k = k + 6
elif event[k] == "endDate":
i = 0
t_cut[i] = "a "
i = i + 1
k = k + 5
t_cut[i] = event[k]
k = k + 1
i = i + 1
t_cut[i] = " heures "
i = i + 1
t_cut[i] = event[k]
k = k - 2
i = i + 1
t_cut[i] = ", le "
i = i + 1
t_cut[i] = event[k]
k = k - 1
i = i + 1
t_cut[i] = "/"
i = i + 1
t_cut[i] = event[k]
k = k - 1
i = i + 1
t_cut[i] = "/"
i = i + 1
t_cut[i] = event[k]
t_event[j][l] = "".join(t_cut)
l = l + 1
k = k + 6
elif event[k] == "title":
k = k + 1
i = 0
for i in range(len(t_cut)):
t_cut[i] = " "
i = 0
while event[k] != "localEndDate":
t_cut[i] = event[k]
i = i + 1
t_cut[i] = " "
i = i + 1
k = k + 1
if event[k] == " ":
k = k + 1
if event[k] == "localEndDate":
break
else:
k = k - 1
encode = "".join(t_cut)
t_event[j][l] = encode
l = 0
break
else:
k = k + 1
j = j + 1
return t_event
def make_find(ordre):
i = 0
space_count = 0
while i < len(ordre):
if ordre[i] == " ":
space_count = space_count + 1
i = i + 1
else:
i = i + 1
length = space_count + len(ordre)
new_ordre = [" "]*length
i = 0
j = 0
while i < len(ordre):
if ordre[i] == " ":
new_ordre[j] = "\\"
j = j + 1
new_ordre[j] = ordre[i]
i = i + 1
j = j + 1
else:
new_ordre[j] = ordre[i]
i = i + 1
j = j + 1
#print new_ordre
return "".join(new_ordre)
def make_say(string):
new_string = [" "]*(len(string))
length = len(string)
i = 0
j = 0
while j < length:
if string[j] == '\n':
new_string[i] = "; "
j = j + 1
i = i + 1
else:
new_string[i] = string[j]
j = j + 1
i = i + 1
return "".join(new_string)
def sub_menu(): # affiche un sous-menu pour choisir une action dans une fonction
ordre = 0
while ordre == 0:
choix = raw_input("choix par < text > ou < speech > : ")
if choix == "text":
ordre = raw_input("tape ta selection : ")
elif choix == "speech":
print("parle maintenant")
ordre = listen()
elif choix == "exit":
say_fr("retour au menu principale")
ordre = "exit"
else:
say_fr("je n'est pas compris")
ordre = 0
return str(ordre)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.