text
stringlengths
37
1.41M
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # Author: Payne Zheng <zzuai520@live.com> # Date: 2019/5/13 # Location: DongGuang # Desc: 模拟range生成器 def range2(number): count = 0 while count < number: print("before:", count) sign = yield count # 只有一个函数里面有yield,那么这个函数就是个生成器 # yield 就是返回一个值并把程序暂停在这里,等待下次next调用 # 并且可以接收send往生成器里面发的信息 print("after:", count) if sign == 'stop': print('sign:', sign) break count += 1 return 'Done' # 在生成器中的return 信息会包含在Stopinteration报错信息里面 r = range2(3) try: print(next(r), '\n----\n') # 首次next会唤醒yield print(next(r), '\n----\n') r.send('stop') # send会唤醒yield并往里面发送消息 print(next(r), '\n----\n') print(next(r), '\n----\n') except StopIteration as e: print("return value:", e.value) # 在错误信息中获取return返回值
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # Author: Payne Zheng <zzuai520@live.com> # Date: 2019/10/30 # Location: DongGuang # Desc: do the right thing """ 顺序查找: 也叫线性查找,从列表第一个元素开始,顺序进行搜索, 直到找到元素或搜索到列表最后一个元素为止 时间复杂度: 将列表从头到尾只走了一遍,为 n,时间复杂度为:O(n) """ def linear_search(li, val): for idx, v in enumerate(li): if v == val: return idx else: return None l = [1, 3, 5, 7, 9, 8, 6, 4, 2] print(linear_search(l, 8))
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # # Author: Payne Zheng <zzuai520@live.com> # Date: 2019/6/3 # Location: DongGuang # Desc: do the right thing """ 练习1: 编写一个学生类,产生一堆学生对象 要求: 有一个计数器(属性), 统计总共实例了多少个对象 """ class Student: school = 'Luffycity' # 类的数据属性,所有对象都能访问(通过各对象来访问可以发现,各对象访问数据属性的内存地址是一样的) count = 0 # 计数器 def __init__(self, name, age, sex): # __init__方法用于接收生成对象的私有属性 self.name = name self.age = age self.sex = sex Student.count += 1 # 因为每创建对象对会自动执行__init__函数,所以直接在__init__函数中对类的变量操作,累加实例次数 def learn(self): # 类的函数属性,绑定到对象后,对象使用(通过各对象来访问可以发现,各对象调用的函数属性是独立的) print('{} is learning'.format(self.name)) def eat(self): print('{} is eating'.format(self.name)) stu1 = Student('jack', 52, 'male') # 创建对象(实例化) stu2 = Student('pony', 45, 'male') stu3 = Student('robin', 47, 'male') print('{}共实例了{}个对象'.format(Student.__name__, Student.count))
"""Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order.""" class Solution: def twoSum(self, nums: [int], target: int) -> [int]: for i in range(len(nums)): for j in range(len(nums)): if i != j: value = nums[i] + nums[j] if value == target: return [i, j] else: print('no sum')
cashvalue = 0 taxpayment = 0 cashvalue = int(input('Welcome to Lottery Daydream! Enter the Cash Option value of the upcoming lottery:')) def bracketone(): global taxpayment taxpayment = (cashvalue) * .1 def brackettwo(): global taxpayment taxpayment = (995 + ((cashvalue-9950)*.12)) def bracketthree(): global taxpayment taxpayment = (4664 + ((cashvalue - 40525)*.22)) def bracketfour(): global taxpayment taxpayment = (14751 + ((cashvalue - 86275) * .24)) def bracketfive(): global taxpayment taxpayment = (33603 + ((cashvalue - 164925) * .32)) def bracketsix(): global taxpayment taxpayment = (47843 + ((cashvalue - 209425) * .35)) def bracketseven(): global taxpayment taxpayment = (157804 + ((cashvalue - 523600) * .37)) def bracketcrunch(): if cashvalue <= 9950: bracketone() if cashvalue > 9950 and cashvalue <= 40525: brackettwo() if cashvalue > 40525 and cashvalue <= 86375: bracketthree() if cashvalue > 86375 and cashvalue <= 164925: bracketfour() if cashvalue > 164925 and cashvalue <= 209425: bracketfive() if cashvalue > 209425 and cashvalue <= 523600: bracketsix() if cashvalue > 523600: bracketseven() bracketcrunch() effectiverate = taxpayment / cashvalue print('Your 2021 federal income taxes owed will be ' + '${:,.2f}'.format(taxpayment)) print('Your take-home amount will be ' + '${:,.2f}'.format(cashvalue-taxpayment)) print('Your effective tax rate will be ' + '{:.2%}'.format(effectiverate))
#!/usr/bin/env python3 x = 4 #this is a comment, python automatically adds a line and a space print('x =', x, sep = '', end = '') print('Hello World') print("3 / 4 = ", int(3/4)) ''' this is another comment ** is exponenet % is still modulus casting is done backwards ''' print("enter a number:") x = input("enter here: ") print(x)
class Node(object): def __init__(self, val): self.left = None self.right = None self.parent = None self.value = val class Tree(object): def __init__(self): self.root = None def add(self, node): if self.root is None: self.root = node else: current_node = self.root while True: if node.value < current_node.value: if current_node.left is None: current_node.left = node node.parent = current_node return else: current_node = current_node.left else: if current_node.right is None: current_node.right = node node.parent = current_node return else: current_node = current_node.right def _visit(self, node): return node.value def _traverse(self, node): if node.left: for elem in self._traverse(node.left): yield elem yield self._visit(node) if node.right: for elem in self._traverse(node.right): yield elem def traverse(self): if self.root: return self._traverse(self.root) else: return None def _traverse_range(self, node, lower_bound, upper_bound): if node.left: for elem in self._traverse_range(node.left, lower_bound, upper_bound): yield elem value = self._visit(node) if lower_bound is None and upper_bound is None: yield value elif lower_bound is None and value < upper_bound: yield value elif lower_bound < value and upper_bound is None: yield value elif lower_bound < value and value < upper_bound: yield value if node.right: for elem in self._traverse_range(node.right, lower_bound, upper_bound): yield elem def traverse_range(self, lower_bound, upper_bound): if self.root: return self._traverse_range(self.root, lower_bound, upper_bound) else: return None def find_lesser_and_greater(self, value): if self.root is None: return None else: lesser = self._find_lesser_node(value) greater = self._find_greater_node(value) if lesser: lesser = lesser.value else: lesser = None if greater: greater = greater.value else: greater = None return lesser, greater def _find_lesser_node(self, value): """ 4 / \ 2 6 / \ / \ 1 3 5 7 """ current_node = self.root while True: if current_node is None: return None elif current_node.value < value: if current_node.right: if current_node.right.value < value: current_node = current_node.right elif current_node.right.left and current_node.right.left.value < value: current_node = current_node.right.left else: return current_node else: return current_node else: current_node = current_node.left def _find_greater_node(self, value): current_node = self.root while True: if current_node is None: return None elif current_node.value > value: if current_node.left: if current_node.left.value > value: current_node = current_node.left elif current_node.left.right and current_node.left.right.value > value: current_node = current_node.left.right else: return current_node else: return current_node else: current_node = current_node.right if __name__ == "__main__": tree = Tree() values = [21, 1, 26, 45, 29, 28, 2, 9, 16, 49, 39, 27, 43, 34, 46, 40] # values = [4, 2, 1, 3, 6, 5, 7] for value in values: tree.add(Node(value)) l = [None] + list(tree.traverse()) print l target = 100 for i in range(1, len(l)): if target <= l[i]: print l[i - 1], l[i] break else: print l[-1], None
# This programme returns the numbers that # first number is greater than last number count = 0 for i in range(1000,10000): if (int(str(i)[0])) > (int(str(i)[-1])): # First we convert 2 str print(i) # 2 reach first digit count += 1 # then, reconvert that number as int print(f"There're {count} numbers.")
# did u just click a file called lasagna.py? Lmao anyway... enjoy lasagna # SRC: https://exercism.org/tracks/python/exercises/guidos-gorgeous-lasagna EXPECTED_BAKE_TIME = 40 PREPARATION_TIME = 40 def bake_time_remaining(elapsed_bake_time): """ Returns remaining bake time This function takes one argument representing the number elapsed baking time and subtracts it from the total expected baking time of a lasagna. """ return EXPECTED_BAKE_TIME - elapsed_bake_time def preparation_time_in_minutes(number_of_layers): """ Returns the number of minutes it would take to prepare a layer of lasagna assuming that each layer takes two minutes to prepare. """ return number_of_layers * 2 def elapsed_time_in_minutes(number_of_layers, elapsed_bake_time): """ Returns the total number of elapsed time in minutes to cook a full lasagna This function adds the elapsed baking time to the number of minutes it takes to cook and add 'n' number of layers to the lasagna being prepared. """ return elapsed_bake_time + (number_of_layers * 2)
import math def merge_sort(arr): if len(arr) >= 2: hlen = math.floor(len(arr) / 2) sarr_l = merge_sort(arr[:hlen]) sarr_r = merge_sort(arr[hlen:]) marr = merge(sarr_l[0], sarr_r[0]) return marr[0], sarr_l[1] + sarr_r[1] + marr[1] else: return arr, 0 def merge(arr_l, arr_r): i = 0 j = 0 arr = [] split_count = 0 for _ in range(0, len(arr_l) + len(arr_r)): if arr_l[i] < arr_r[j]: arr.append([arr_l[i]]) i += 1 if i == len(arr_l): arr.append(arr_r[j:]) return sum(arr, []), split_count else: arr.append([arr_r[j]]) split_count += len(arr_l) - i j += 1 if j == len(arr_r): arr.append(arr_l[i:]) return sum(arr, []), split_count fh = open('IntegerArray.txt', 'r') numbers = fh.readlines() num = [int(x) for x in numbers] res = merge_sort(num) print(res[1])
def status_bmi(bmi): if bmi < 18.5: print("Estas Bajo Peso") elif bmi > 18.5 and bmi < 25: print("Tienes Peso Normal") elif bmi > 25 and bmi < 30: print("Estas Sobre Peso") else: print("Tienes Obesidad") def calculate_bmi(height, weight): result = weight / (height ** 2) status_bmi(result) result = int(result) return result def run(): height = input("enter your height in m: ") weight = input("enter your weight in kg: ") bmi = calculate_bmi(float(height), int(weight)) print(bmi) if __name__ == '__main__': run()
def calculate(num1, num2): return num1 + num2 def run(): two_digit_number = input("Type a two digit number: ") first_digit = int(two_digit_number[0]) second_digit = int(two_digit_number[1]) result = calculate(first_digit, second_digit) print(f"{first_digit} + {second_digit} = {result}") if __name__ == "__main__": run()
import math def run(): student_heights = [156, 178, 165, 171, 187] total_heights = 0 for height_student in student_heights: total_heights += height_student total_heights /= len(student_heights) total_heights = round(total_heights) print(total_heights) if __name__ == "__main__": run()
def run(): bill = 0 pizzas_bill = { "S": 15, "M":20, "L":25 } pepperoni_bill = { "S": 2, "M": 3, "L": 3 } extra_cheese_bill = 1 print("Welcome to Python Pizza Deliveries!") size = input("What size pizza do you want? S, M, or L : ") add_pepperoni = input("Do you want pepperoni? Y or N : ") extra_cheese = input("Do you want extra cheese? Y or N : ") if size == "S" or size == "M" or size == "L" and add_pepperoni == "Y" and extra_cheese == "Y": bill = pizzas_bill[size] + pepperoni_bill[size] + extra_cheese_bill elif size == "S" or size == "M" or size == "L" and add_pepperoni == "Y" and extra_cheese == "N": bill = pizzas_bill[size] + pepperoni_bill[size] elif size == "S" or size == "M" or size == "L" and add_pepperoni == "N" and extra_cheese == "Y": bill = pizzas_bill[size] + extra_cheese_bill else: bill = pizzas_bill[size] print(f"Your final bill is {bill}") if __name__ == "__main__": run()
import time def binary_search(list, item): low = 0 high = len(list) while low <= high: mid = (low + high) // 2 guess = list[mid] if guess == item: return mid if guess > item: high = mid - 1 else: low = mid + 1 return None tic = time.perf_counter() my_list = list(range(100000)) item = 99999 print (binary_search(my_list, item)) # => 1 toc = time.perf_counter() print(f"runtime: {toc - tic:0.7f} seconds")
# -*- coding: utf-8 -*- import random as rng """ Program simulating walking home in one dimention """ __author__ = 'Marius Kristiansen' __email__ = 'mariukri@nmbu.no' class Walk(object): def __init__(self, home, start=0): """ Constructor - The "start" parameter can be altered, but will essestially be same as altering home with the same amount. :param home: :param start: :return: """ self._home = home self._position = start self._steps = 0 self._steplist = [] def direction(self): """ Determines the direction the program will take the next step in. :return: """ way = rng.randint(1, 2) if way == 1: self._position -= 1 else: self._position += 1 self._steps += 1 @property def am_i_home(self): """ Tests if the current position in the same as the "home"-coordinate :return: """ if self._position == self._home: self._steplist.append(self._steps) return True def position(self): """ Query the program for the current position :return: """ return self._position def walking_home(self): """ Runs the step method (direction()) n times and checks if the program is "home" Also resets _steps and _position to prepare for next program execution :return: """ while True: self.direction() if self.am_i_home is True: self._steps = 0 self._position = 0 break def simulate(self, n): """ Runs the simulation the number of times specified. - Distance to home is the same - Only number of times the single simulation is run can be altered here :param n: :return: """ for _ in range(n): self.walking_home() print "Distance: {:4} -> Path Length: {}".\ format(self._home, self._steplist) if __name__ == '__main__': distances = [Walk(dist) for dist in [1, 2, 5, 10, 20, 50, 100]] # rng.seed(265) for d in distances: d.simulate(5)
# -*- coding: utf-8 -*- """ source: INF200_H15_L04 lecture. H.E.Plesser """ __author__ = 'Marius Kristiansen' __email__ = 'mariukri@nmbu.no' def median(data): """ Returns median of data. :param data: An iterable of containing numbers :return: Median of data """ if data == []: raise ValueError('Given list is empty') else: sdata = sorted(data) n = len(sdata) return (sdata[n / 2] if n % 2 == 1 else 0.5 * (sdata[n / 2 - 1] + sdata[n / 2]))
# -*- coding: utf-8 -*- """ Expanding list comprehension into a conventional "for loop" -form """ __author__ = 'Marius Kristiansen' __email__ = 'mariukri@nmbu.no' def squares_by_comp(number): return [k**2 for k in range(number) if k % 3 == 1] def squares_by_loop(n): squares = [] for number in range(n): if number % 3 == 1: squares.append(number**2) return squares if __name__ == '__main__': number_in = int(raw_input('Number: ')) if squares_by_comp(number_in) != squares_by_loop(number_in): print 'ERROR!'
def add(x, y): return x + y def main(): x = 5 y = 2 print(add(5, 2)) if __name__ == '__main__': main()
class Car: def __init__(self, make, year, model): self.make = make self.year = year self.model = model def display_features(self): print("Make:" + self.make) print("Year:" + str(self.year)) print("Model:" + self.model) class ElectricCar(Car): def __init__(self, make, year, model, range): super().__init__(make, year, model) self.range = range def display_Efeatures(self): self.display_features() print("Range: " + self.range) # c = Car("Hyundia", 2003, "Santro") # c.display_features() # c = ElectricCar("Tesla", 2017, "Model3", "406 miles") # c.display_Efeatures() class Circle: pi = 3.14 def __init__(self, radius): self.radius = radius def area(self): return self.radius * self.radius * Circle.pi c = Circle(3) print(c.area()) #Special Methods class Book: def __init__(self, title, author, pages): self.title = title self.author = author self.pages = pages def __str__(self): return f"Title: {self.title}, Author: {self.author}, Pages: {self.pages}" def __len__(self): return self.pages b = Book("Python", "Jose", 203) print(b) print(len(b))
# ===> Pet class # Task #1 class Pet(object): def __init__(self,name,species,food_cost,noise): self.name=name self.species=species self.food_cost=food_cost self.noise=noise # Task #2 def Speak(self): print(self.noise) # Task #3 def sumFoodCost(self): sum=0 for pet in petsList: sum+=pet.food_cost print(sum) petsList=[ Pet(name='Spot', species='dog', food_cost=5.00, noise='woof'), Pet(name='Fido', species='dog', food_cost=7.00, noise='woof'), Pet(name='Jorge', species='dog', food_cost=2.00, noise='yip') ] petsListNew=[] # Task #4 for i in petsList: petsListNew.append('The dog says ' + i.noise) for k in petsListNew: "".join(k) print(petsListNew) print("======== END Tasks =========") # Rinning the 'Speak()' and 'sumFoodCost()' methods with the 'pet1' class instance print("===== Running sample test bellow! =======") pet1=Pet("aaa","dog","11","baaaaaaaab..") pet1.Speak() pet1.sumFoodCost()
x1=[1,2,1,2,] x2=[1,2,2,1] x3=[1,2,1,2] def List_prop(q): i=0 temp=0 max1=0 max2=0 min1=0 flag='' for n in q: if i==0: temp=n i=i+1 else : if temp<n: temp=n i=i+1 if flag[-3:]!="max": flag=flag+"max" if flag.find("maxmin"): max1=n else: max2=n if temp>n: temp=n min1=n i=i+i if flag[-3:]!="min": flag=flag+"min" ret={"Flag":flag,"max1":max1,"max2":max2,"min1":min1} return ret l=[x1,x2,x3] i=0 t='' t1=List_prop(l[i]) print t1 while i<3: t1=List_prop(l[i]) t2=List_prop(l[i+2]) if t1["Flag"]==t2["Flag"] and t2["Flag"]=="maxminmax": t3=List_prop(l[i+1]) if t3["max1"]>3 and t3['Flag']=="maxminmax": print "bus" elif t3["max1"]<3 and t3['Flag']=="maxmin": print "car" i=i+3 else: j=i while j<i+2: tmp=List_prop(l[j]) if tmp["Flag"]=="maxmin": if tmp["max1"]>2: print "scotter" elif tmp["max1"]<2: print "bike" elif tmp['Flag']=="maxminmax": print "bicycle" j=j+1 i=i+1
class Slide: """ Combination of images represented as a slide List of attributes: - photos:list = list of photos the second being None if is a horizontal pic - is_vertical:bool = True if the slide is composed by two vertical images - tags:set = set being the union of both set of images """ def __init__(self, photo1, photo2 = None): """ photo1: Photo photo2: Photo (only if we have two vertical photos) """ # Check that the photo is vertical if photo2: assert(photo2.is_vertical) # List of the photos self.photos = [photo1, photo2] self.is_vertical = all(self.photos) @property def tags(self): result = set() for photo in self.photos: if photo: result.union(photo.tags) return result def pk(self): pk1 = photo1.pk pk2 = 0 if photo2: pk2 = photo2.pk*1e6 return pk1+pk2
""" Definition for a multi tree node. class MultiTreeNode(object): def __init__(self, x): self.val = x children = [] # children is a list of MultiTreeNode """ class Solution: # @param {MultiTreeNode} root the root of k-ary tree # @return {int} the length of the longest consecutive sequence path def longestConsecutive3(self, root): up, down, max_len = self.helper(root) return max_len def helper(self, root): if root is None: return 0, 0, 0 up_lst, down_lst, max_len_lst = [], [], [] for c in root.children: c_up, c_down, c_max_len = self.helper(c) up_lst.append(c_up) down_lst.append(c_down) max_len_lst.append(c_max_len) up, down = 0, 0 for i in range(len(root.children)): if root.val + 1 == root.children[i].val: down = max(down, down_lst[i] + 1) if root.val - 1 == root.children[i].val: up = max(up, up_lst[i] + 1) max_len = max(max_len_lst, default=0) max_len = max(down + up + 1, max_len) return up, down, max_len
# https://www.lintcode.com/problem/sort-colors/description?_from=ladder&&fromId=1 # 1. partition x 2: partition 0 + partition 1 class Solution: """ @param nums: A list of integer which is 0, 1 or 2 @return: nothing """ def sortColors(self, nums): index = self.partition(nums, 0, 0, len(nums) - 1) self.partition(nums, 1, index, len(nums) - 1) def partition(self, nums, pivot, start, end): if start >= end: return start l, r = start, end while l <= r: while l <= r and nums[l] <= pivot: l += 1 while l <= r and nums[r] > pivot: r -= 1 if l <= r: nums[l], nums[r] = nums[r], nums[l] l += 1 r -= 1 return start # 2. 3 Pointers class Solution: """ @param nums: A list of integer which is 0, 1 or 2 @return: nothing """ def sortColors(self, nums): if nums is None or len(nums) < 3: return l, i, r = 0, 0, len(nums) - 1 while i <= r: if nums[i] == 1: i += 1 elif nums[i] == 0: nums[i], nums[l] = nums[l], nums[i] i += 1 l += 1 else: nums[i], nums[r] = nums[r], nums[i] r -= 1
from collections import Counter class Solution(object): def numJewelsInStones(self, J, S): """ :type J: str :type S: str :rtype: int """ jewelRef = set(J) jewelCount = 0 # option A # for stone in S: # if stone in jewelRef: # jewelCount += 1 # option B uses Counter and faster according to leetcode stoneCounter = Counter(S) for stone in stoneCounter.most_common(): if stone[0] in jewelRef: jewelCount += stone[1] return jewelCount
import re import time def main(): operation = "" while operation != "q": operation = input("Please insert your calculation or q to exit: ") values = process(operation) if operation == "q": break if len(values) < 2 or len(values) > 3: print("ERROR!!!!! Please insert a correct calculation. You have inserted: " + operation) time.sleep(2) elif values[1] == "+": print(sumall(values)) elif values[1] == "-": print(subtract(values)) elif values[1] == "*": print(multiply(values)) elif values[1] == "/": print(divide(values)) else: print("Please insert a correct calculation. You have inserted: " + operation) def process(string): value = re.split('(\D)', string, maxsplit=0) return value def sumall(array): return float(array[0]) + float(array[2]) def subtract(array): return float(array[0]) - float(array[2]) def multiply(array): return float(array[0]) * float(array[2]) def divide(array): return float(array[0]) / float(array[2]) main()
import sys def fac(a): fact=1 for i in range (1,a+1): fact=fact*i return fact t=int(input()) for i in range(0,t): n=int(input()) print(fac(n))
class Node: def __init__(self, val=None): self.val = val self.next = None class LinkedList: def __init__(self): self.head = Node() self.length = 0 def append_to_tail_node(self, data): curr = self.head new = Node(data) while curr.next is not None: curr = curr.next curr.next = new return self def append_to_head_node(self, data): curr = self.head new = Node(data) if self.head.next is None: self.head.next = new return self temp = self.head.next self.head.next = new new.next = temp return self def reverse(self): head = self.head prev = None while curr is not None: next = curr.next curr.next = prev prev = curr curr = next self.head = prev def delete_first_node(self): curr = self.head if curr.next is None: return self self.head.next = curr.next.next return self def delete_last_node(self): curr = self.head if curr.next is Node: return self prev = curr while curr.next is not None: prev = curr curr = curr.next prev.next = None return curr.val def move_last_node_to_first(self): last_node = self.delete_last_node() return self.append_to_head_node(last_node) def delete_at_index(self, index): curr = self.head if curr.next is Node: return self count = 1 while curr.next is not None: prev = curr curr = curr.next if count == index: prev.next = curr.next return self count += 1 return self def delete_duplicate(self): curr = self.head if curr.next is None or curr is None: return self lst = [] curr = curr.next while curr.next is not None: if curr.next.val in lst: curr.next = curr.next.next else: lst.append(curr.next.val) curr = curr.next return self def delete_duplicate_in_sorted(self): curr = self.head if curr.next is None: return self curr = curr.next while curr.next is not None: if curr.val == curr.next.val: curr.next = curr.next.next else: curr = curr.next return self def data_at_index(self, index): cur_node = self.head count = 1 while cur_node.next is not None: cur_node = cur_node.next if count == index: return cur_node.val count += 1 return -1 def display(self): elems = [] cur_node = self.head while cur_node.next is not None: cur_node = cur_node.next elems.append(cur_node.val) return elems def check_palindrome(self): lst = self.display() num = 0 num = int("".join(map(str, lst))) rev = int("".join(map(str, reversed(lst)))) if num == rev: return True else: return False node = LinkedList() # node.append_to_tail_node(10) # node.append_to_tail_node(10) # node.append_to_tail_node(10) # node.append_to_tail_node(11) # node.append_to_tail_node(12) # node.append_to_tail_node(12) # node.append_to_tail_node(12) node.append_to_head_node(9) node.append_to_head_node(9) node.append_to_head_node(9) node.append_to_head_node(8) node.append_to_head_node(9) node.append_to_head_node(9) node.append_to_head_node(9) # node.delete_first_node() # node.delete_first_node() # node.delete_last_node() # node.delete_last_node() # node.delete_last_node() # print(node.display()) # node.delete_at_index(6) # node.reverse() # print(node.delete_duplicate_in_sorted()) # print(node.delete_duplicate()) # print(node.display()) # print(node.move_last_node_to_first()) print(node.display()) print(node.check_palindrome()) # print(node.data_at_index(2))
""" Given an array of integers nums, half of the integers in nums are odd, and the other half are even. Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even. Return any answer array that satisfies this condition. Example 1: Input: nums = [4,2,5,7] Output: [4,5,2,7] Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted. Example 2: Input: nums = [2,3] Output: [2,3] Constraints: 2 <= nums.length <= 2 * 104 nums.length is even. Half of the integers in nums are even. 0 <= nums[i] <= 1000 """ from typing import List class Solution: def sortArrayByParityII(self, nums: List[int]) -> List[int]: ev = [] odd = [] lst = [] for val in nums: if val % 2 == 0: ev.append(val) else: odd.append(val) odd.sort() ev.sort() for i in range(len(nums) // 2): lst.append(ev[i]) lst.append(odd[i]) return lst
# Definition for a binary tree node. """ Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high]. Example 1: Input: root = [10,5,15,3,7,null,18], low = 7, high = 15 Output: 32 Example 2: Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10 Output: 23 Constraints: The number of nodes in the tree is in the range [1, 2 * 104]. 1 <= Node.val <= 105 1 <= low <= high <= 105 All Node.val are unique. """ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def rangeSumBST(self, root: TreeNode, low: int, high: int) -> int: def findSum(root): nonlocal total if not root: return 0 if low <= root.val <= high: total += root.val if root.left: findSum(root.left) if root.right: findSum(root.right) total = 0 findSum(root) return total
# 1, 1, 2, 3, 5, 8, 13, 21, ... def fibo_iterativo(n): if n <= 2: return 1 else: t1 = 1 t2 = 1 contador = 3 while contador <= n: t1, t2 = t2, t1 + t2 contador += 1 return t2 def fibo_recursivo(n): if n <= 2: return 1 else: return fibo_recursivo(n - 1) + fibo_recursivo(n - 2) print(fibo_iterativo(9)) print(fibo_recursivo(9))
class Node: def __init__(self, data): self.data = data self.next = None self.previous = None # Everythong else is the same as singly linked lists. # Doubly linked lists are used as to implement the Collections.deque (pronounced: deck) which helps it insert or delete an elements from both ends of the queue with # constant O(1) performance.
from Tkinter import * #from PIL import Image, ImageTk import ttk import random import time window = Tk() canvas = Canvas(window, width=854, height=480, bg="#3796da") canvas.pack() intPlay = 0 #Creates window and centers to any screen window.geometry('{}x{}'. format(1060, 670)) #Setting size of window window.withdraw() #Hide window to stop showing in wrong position window.update_idletasks() #Request screen size from system x = (window.winfo_screenwidth() - window.winfo_reqwidth()) / 2 #Calculate screen width y = ((window.winfo_screenheight() - window.winfo_reqheight()) / 2) - 70 #Calculate screen height window.geometry("+%d+%d" % (x, y)) #Change position of window window.title('Sloths - Virtual Robot Treasure Hunt') #Adds name to window window.resizable(width=FALSE, height=FALSE) #Disabled resizable function of window window.deiconify() #Redraw window in correct position #Importing images to use through out program coinImage = PhotoImage(file="assets/coin.gif") greenImage = PhotoImage(file="assets/greenjewel.gif") redImage = PhotoImage(file="assets/redjewel.gif") chestImage = PhotoImage(file="assets/chest.gif") pirateImage = PhotoImage(file="assets/pirate.gif") coinGImage = PhotoImage(file="assets/coin-grey.gif") jewelGImage = PhotoImage(file="assets/jewel-grey.gif") chestGImage = PhotoImage(file="assets/chest-grey.gif") ClockG = PhotoImage(file="assets/clock-grey.gif") Clock1 = PhotoImage(file="assets/1.gif") Clock15 = PhotoImage(file="assets/1.5.gif") Clock2 = PhotoImage(file="assets/2.gif") Clock25 = PhotoImage(file="assets/2.5.gif") Clock3 = PhotoImage(file="assets/3.gif") Clock35 = PhotoImage(file="assets/3.5.gif") Clock4 = PhotoImage(file="assets/4.gif") Clock45 = PhotoImage(file="assets/4.5.gif") #Importing png using PIL #flash = Image.open("flash.png") #flashImage = ImageTk.PhotoImage(flash) class landmark: # Landmark class being created def __init__(self, x1, y1, x2, y2): # this sets out the layout of how all future objects will be set in order to be created self.x1 = x1 # whatever the objects name.x1 or x2 or y1 or y2, store the value in x1, which then places it in the user interface self.x2 = x2 self.y1 = y1 self.y2 = y2 self.colour = "#e7df63" # the background colour for all landmarks is set here to green in the user interface self.outline = "black" # the outline colour of all landmarks is set to black in the user interface self.treasure = False # setting the variable with the value of 'false' self.treasureID = "" # creating treasure ID for robot self.lndmrk = canvas.create_rectangle(self.x1,self.y1,self.x2,self.y2, fill=self.colour, outline = self.outline, tag="Landmark") # creates the landmark with the given coordinates and colours, but they're pre-set. def MapOneLandMarks(): #creating a new function which will store all the landmarks in the first map global obstacles obstacles = [ # this code within the array creates the first landmark landmark(30,50,180,120), landmark(670,50,825,120), landmark(30,460,180,330), landmark(670,460,825,330), landmark(270,370,590,430), landmark(160,160,690,230)] class Robot: def __init__(self): self.vx = 10.0 self.vy = 0.0 self.rXPos = 0 self.rYPos = 0 self.status = "" #String to display status of robot self.points = 0 #Integer to display points of robot self.run = False #Used for when robot should run self.done = False #Used for when robot is done i.e. got all treasures self.shipSprite = PhotoImage(file = "assets/ship.gif") def setSpawn(self, xpos, ypos): #Function to set spawn variables self.rXPos = xpos #Setting xpos self.rYPos= ypos #Setting ypos def robotLoad(self): for o in obstacles: ox1, oy1, ox2, oy2 = canvas.coords(o.lndmrk) if (self.rXPos > ox1 - 10.0 and self.rXPos < ox2 + 10.0) and (self.rYPos > oy1 - 10.0 and self.rYPos < oy2 + 10.0): self.robotLoad() else: self.robot = canvas.create_rectangle(self.rXPos, self.rYPos, self.rXPos + 10.0, self.rYPos + 10.0, fill = "blue") self.run = True self.treasureTrack(self.vx, self.vy) def treasureTrack(self, vx, vy): c = -1 if self.run == True: if self.done == False: for l in locationlist: while l.treasure == True: lookingLabel.config(image=l.treasureID) #Update currently looking for x1, y1, x2, y2 = canvas.coords(self.robot) lx1, ly1, lx2, ly2 = canvas.coords(l.lndmrk) self.bypassLandmark(x1, y1, x2, y2, lx1, ly1, lx2, ly2) self.trapCollision(x1, y1, x2, y2, traps[0]) self.trapCollision(x1, y1, x2, y2, traps[1]) if (x2 < lx1 - 20.0) and (y2 < ly1 - 20.0): # Approaching from top left. vx = self.lightResponse(x1, y1, x2, y2, 10.0) #Running lightReponse with 10 volocity vy = self.lightResponse(x1, y1, x2, y2, 5.0) #Running lightReponse with 5 volocity if (x2 < lx1 - 20.0) and (y1 > ly2 + 20.0): # Approaching from bottom left. vx = self.lightResponse(x1, y1, x2, y2, 10.0) #Running lightReponse with 10 volocity vy = self.lightResponse(x1, y1, x2, y2, -5.0) #Running lightReponse with -5 volocity if (x1 > lx2 + 20.0) and (y2 < ly1 - 20.0): # Approaching from top right. vx = self.lightResponse(x1, y1, x2, y2, -10.0) #Running lightReponse with -10 volocity vy = self.lightResponse(x1, y1, x2, y2, 5.0) #Running lightReponse with 5 volocity if (x1 > lx2 + 20.0) and (y1 > ly2 + 20.0): # Approaching from bottom right. vx = self.lightResponse(x1, y1, x2, y2, -10.0) #Running lightReponse with -10 volocity vy = self.lightResponse(x1, y1, x2, y2, -5.0) #Running lightReponse with -5 volocity if (x2 < lx1 - 20.0) and ((y2 > ly1 - 20.0) and (y1 < ly2 + 20.0)): vx = self.lightResponse(x1, y1, x2, y2, 10.0) #Running lightReponse with 10 volocity vy = self.lightResponse(x1, y1, x2, y2, 0.0) #Running lightReponse with 0 volocity if (x1 > lx2 + 20.0) and ((y2 > ly1 - 20.0) and (y1 < ly2 + 20.0)): vx = self.lightResponse(x1, y1, x2, y2, -10.0) #Running lightReponse with -10 volocity vy = self.lightResponse(x1, y1, x2, y2, 0.0) #Running lightReponse with 0 volocity if (y2 < ly1 - 20.0) and ((x2 > lx1 - 20.0) and (x1 < lx2 + 20.0)): vx = self.lightResponse(x1, y1, x2, y2, 0.0) #Running lightReponse with 0 volocity vy = self.lightResponse(x1, y1, x2, y2, 5.0) #Running lightReponse with 5 volocity if (y1 > ly2 + 20.0) and ((x2 > lx1 - 20.0) and (x1 < lx2 + 20.0)): vx = self.lightResponse(x1, y1, x2, y2, 0.0) #Running lightReponse with 0 volocity vy = self.lightResponse(x1, y1, x2, y2, -5.0) #Running lightReponse with -5 volocity if ((x2 > lx1 - 20.0) and (x1 < lx2 + 20.0)) and ((y2 > ly1 - 20.0) and (y1 < ly2 + 20.0)): ChangeThought(5) l.treasure = False #Changing landmark to not have treasure c = c + 1 #Increment counter canvas.delete(treasurelist[c].location) #Delete treasure image CollectedList.append(Label(image=l.treasureID)) #Add treasure to collected list CollectedList[c].place(x=CollectedImagex[c], y=CollectedImagey[c]) #Place image in collected treasure self.points = self.points + treasurelist[c].points #Add points to robots total for n in range (0,2): #Add points to trap items so it can be removed traps[n].points = treasurelist[c].points #Get points traps[n].previous = l.treasureID #Get previous id traps[n].colpos = c #Get position InfoLabels[2].config(text=self.points) #Display updated points self.rXPos += vx self.rYPos += vy canvas.coords(self.robot, x1 + vx, y1 + vy, x2 + vx, y2 + vy) InfoLabels[0].config(text="x:" + str(int(x1)) + " y:" + str(int(y1))) canvas.update() time.sleep(0.1) main.Finished() #Stop timer lookingLabel.place_forget() #Removed looking for image def trapCollision(self, x1, y1, x2, y2, trap): if (x2 > trap.xpos and x1 < trap.xpos + 30.0) and (y2 > trap.ypos and y1 < trap.ypos + 30.0): if trap.hit == False: trap.collision() def bypassLandmark(self, x1, y1, x2, y2, lx1, ly1, lx2, ly2): if (x2 > lx1 - 10.0 and x2 < lx1 + 10.0) and y2 > ly1 and y1 < ly2: # APPROACH FROM LEFT if self.vy == -5.0 or self.vy == 0.0: self.vx = 0.0 self.vy = -5.0 elif self.vy == 5.0: self.vx = 0.0 self.vy = 5.0 if (x1 < lx2 + 10.0 and x1 > lx2 - 10.0) and y2 > ly1 and y1 < ly2: # APPROACH FROM RIGHT if self.vy == -5.0 or self.vy == 0.0: self.vx = 0.0 self.vy = -5.0 elif self.vy == -5.0: self.vx = 0.0 self.vy = 5.0 if (y2 > ly1 - 10.0 and y2 < ly1 + 10.0) and x2 > lx1 and x1 < lx2: # APPROACH FROM TOP if self.vx == -10.0 or self.vx == 0.0: self.vx = -10.0 self.vy = 0.0 elif self.vx == 10.0: self.vx = 10.0 self.vy = 0.0 if (y1 < ly2 + 10.0 and y1 > ly2 - 10.0) and x1 > lx1 and x2 < lx2: # APPROACH FROM BOTTOM if self.vx == -10.0 or self.vx == 0.0: self.vx = -10.0 self.vy = 0.0 elif self.vx == 10.0: self.vx = 10.0 self.vy = 0.0 def lightResponse(self, x1, y1, x2, y2, vol): if (x1 > 0.0) and (x2 < 213.5): self.tagFormat(section1) if tag == "Red": vol = 0.0 InfoLabels[1].config(text=tag) ChangeThought(3) elif tag == "Amber": vol = vol / 2 InfoLabels[1].config(text=tag) ChangeThought(4) elif tag == "Green": vol = vol InfoLabels[1].config(text=tag) ChangeThought(6) if (x1 > 213.5) and (x2 < 427.0): self.tagFormat(section2) if tag == "Red": vol = 0.0 InfoLabels[1].config(text=tag) ChangeThought(3) elif tag == "Amber": vol = vol / 2 InfoLabels[1].config(text=tag) ChangeThought(4) elif tag == "Green": vol = vol InfoLabels[1].config(text=tag) ChangeThought(6) if (x1 > 427.0) and (x2 < 640.5): self.tagFormat(section3) if tag == "Red": vol = 0 InfoLabels[1].config(text=tag) ChangeThought(3) elif tag == "Amber": vol = vol / 2 InfoLabels[1].config(text=tag) ChangeThought(4) elif tag == "Green": vol = vol InfoLabels[1].config(text=tag) ChangeThought(6) if (x1 > 640.5) and (x2 < 854.0): self.tagFormat(section4) if tag == "Red": vol = 0 InfoLabels[1].config(text=tag) ChangeThought(3) elif tag == "Amber": vol = vol / 2 InfoLabels[1].config(text=tag) ChangeThought(4) elif tag == "Green": vol = vol InfoLabels[1].config(text=tag) ChangeThought(6) return vol def tagFormat(self, section): # Function for removing parenteses, commas and quotation marks from light tags. global tag tag = str(canvas.gettags(section)) tag = tag.replace("('", "") tag = tag.replace("',)", "") class Countdown: def __init__(self, label): self.second = 0 self.minute = 0 self.time = "" self.totalTime = 0 self.ticks = 0 self.done = False self.label = label def getTime(self): time = E.get() #split the time string input #set the minutes as an int self.minute = int(time[0:2]) #set the seconds as an int self.second = int(time[3:5]) self.second = self.second + 1 # for the clock countdown calculations self.ticks = (self.second + (self.minute * 60)) - 1 self.totalTime = (self.second + (self.minute * 60)) - 1 def Finished(self): #Change to done if robot is done #used so that the countdown still displays time self.done = True ChangeThought(9) InfoLabels[1].config(text="Done") def Count(self): # when the countdown has seven eighths of the totalTime to go sevenEighths = self.totalTime * 0.875 # when the countdown has three quarters of the totalTime left to go threeq = self.totalTime * 0.75 # when the countdown has five eighths of the totalTime to go fiveEighths = self.totalTime * 0.625 # when the countdown is halfway half = self.totalTime * 0.5 # when the countdown has three eighths of the totalTime to go threeEighths = self.totalTime * 0.375 # when the countdown has one quarter of the totalTime left to go oneq = self.totalTime * 0.25 # when the countdown has one eighths of the totalTime to go oneEighth = self.totalTime * 0.125 global intPlay if intPlay == 0: self.done = True # condition - if the program is running elif self.done == False: self.ticks = self.ticks - 1 # seconds decrease by 1 self.second = self.second - 1 if self.second == 0: # once the countdown reaches 60 seconds, the minutes decreases and the seconds are set back to 0 to repeat process self.minute = self.minute - 1 self.second = 59 if self.minute < 0: self.done = True self.second = 0 self.minute = 0 ChangeThought(7) #Displays text from thoughts R1.run = False R1.done = False #Generate 4 random numbers between 1 - 3 for lights # lights change every 5 seconds if self.second % 5 == 0: lightlist[0].ChangeLight() lightlist[1].ChangeLight() lightlist[2].ChangeLight() lightlist[3].ChangeLight() # formatting of timer display mm:ss if self.minute >= 10: if self.second >= 10: # e.g. 12:34 self.time = str(self.minute) + ":" + str(self.second) else: # e.g. 12:03 self.time = str(self.minute) + ":0" + str(self.second) else: if self.minute < 10: if self.second >= 10: # e.g. 01:23 self.time = "0" + str(self.minute) + ":" + str(self.second) else: # e.g. 01:02 self.time = "0" + str(self.minute) + ":0" + str(self.second) # executing the timer display as a string so it can display as a label exec str(self.label.config(text=(self.time))) # 1000 ticks == 1 second delay and continues the Count function self.label.after(1000, self.Count) # when the robot has found the treasures the timer is stopped, and the time the robot found the treasures in is displayed if self.done == True: exec str(self.label.config(text=(self.time))) #countdown image change if (float(sevenEighths) < self.ticks <= self.totalTime): # display first clock image clock.config(image=Clock1) elif (float(threeq) < self.ticks <= float(sevenEighths)): # display second clock image clock.config(image=Clock45) elif (float(fiveEighths) < self.ticks <= float(threeq)): # display third clock image clock.config(image=Clock4) elif (float(half) < self.ticks <= float(fiveEighths)): # display fourth clock image clock.config(image=Clock35) elif (float(threeEighths) < self.ticks <= float(half)): # display fifth clock image clock.config(image=Clock3) elif (float(oneq) < self.ticks <= float(threeEighths)): # display sixth clock image clock.config(image=Clock25) elif (float(oneEighth) < self.ticks <= float(oneq)): # display seventh clock image clock.config(image=Clock2) elif (0 < self.ticks <= int(oneEighth)): # display eighth clock image clock.config(image=Clock15) else: # display greyed out clock clock.config(image=ClockG) #Class for lights class Light(): def __init__(self, number): self.width = 854 #width of canvas self.height = 480 #height of canvas self.sectionWidth = 213.5 #width of one section (1/4 of whole width) self.number = number #number of section self.colour = "" #string to hold colour of section def CreateLight(self): #Function to create the lights for GUI global lightcolour1 global lightcolour2 global lightcolour3 global lightcolour4 global section1 global section2 global section3 global section4 global light1Text global light2Text global light3Text global light4Text if self.number == 1: #if section 1, place in left most position lightcolour1=canvas.create_rectangle(2, 2, self.sectionWidth, 23, fill="#2ecc71", tag="1") #Create light block and tag number section1=canvas.create_rectangle(0, self.height + 1, self.sectionWidth, 23, dash=(10,10), tag="Green") #Create dashed section and tag colour light1Text=Label(font=('Helvetica', 8), text='Green', bg="#2ecc71") #Create label to match colour of section light1Text.place(x=100, y=13) #Place label in correct position self.colour = "Green" #Change string to hold value of light elif self.number == 2: #If section 2, place in left mid position lightcolour2=canvas.create_rectangle(self.sectionWidth, 2, self.sectionWidth * self.number, 23, fill="#f39c12", tag="2") #Create light block and tag number section2=canvas.create_rectangle(self.sectionWidth, self.height + 1, self.sectionWidth * 2, 23, dash=(10,10), tag="Amber") #Create dashed section and tag colour light2Text=Label(font=('Helvetica', 8), text='Amber', bg="#f39c12") #Create label to match colour of section light2Text.place(x=310, y=13) #Place label in correct position self.colour = "Amber" #Change string to hold value of light elif self.number == 3: #If section 3, place in right mid position lightcolour3=canvas.create_rectangle(self.sectionWidth * (self.number - 1), 2, self.sectionWidth * self.number, 23, fill="#e74c3c", tag="3") #Create light block and tag number section3=canvas.create_rectangle(self.sectionWidth * 2, self.height + 1, self.sectionWidth * 3, 23, dash=(10,10), tag="Red") #Create dashed section and tag colour light3Text=Label(font=('Helvetica', 8), text='Red', bg="#e74c3c") #Create label to match colour of section light3Text.place(x=530, y=13) #Place label in correct position self.colour = "Red" #Change string to hold value of light elif self.number == 4: #If section 4, place in right most position lightcolour4=canvas.create_rectangle(self.sectionWidth * (self.number - 1), 2, ((self.sectionWidth * self.number) + 1), 23, fill="#2ecc71", tag="4") #Create light block and tag number section4=canvas.create_rectangle(self.sectionWidth * 3, self.height + 1, ((self.sectionWidth * 4) + 1), 23, dash=(10,10), tag="Green") #Create dashed section and tag colour light4Text=Label(font=('Helvetica', 8), text='Green', bg="#2ecc71") #Create label to match colour of section light4Text.place(x=740, y=13) #Place label in correct position self.colour = "Green" #Change string to hold value of light def ChangeLight(self): #Function to change lights, called in timer class count function intColour = random.randrange(1,4) # Random selection of traffic lights ranging from 1 - 3 if intColour == 1: #If random number = 1 (Green) self.colour = "Green" #Change value of colour string if self.number == 1: #Check for section to change light1Text.config(text='Green', bg="#2ecc71") #Change label text to correct value canvas.itemconfig(lightcolour1, fill="#2ecc71") #Change light to correct colour canvas.itemconfig(section1, tag="Green") #Change section tag to correct value elif self.number == 2: light2Text.config(text='Green', bg="#2ecc71") #Change label text to correct value canvas.itemconfig(lightcolour2, fill="#2ecc71") #Change light to correct colour canvas.itemconfig(section2, tag="Green") #Change section tag to correct value elif self.number == 3: light3Text.config(text='Green', bg="#2ecc71") #Change label text to correct value canvas.itemconfig(lightcolour3, fill="#2ecc71") #Change light to correct colour canvas.itemconfig(section3, tag="Green") #Change section tag to correct value elif self.number == 4: light4Text.config(text='Green', bg="#2ecc71") #Change label text to correct value canvas.itemconfig(lightcolour4, fill="#2ecc71") #Change light to correct colour canvas.itemconfig(section4, tag="Green") elif intColour == 2: #If random number = 2 (Amber) self.colour = "Amber" #Change value of colour string if self.number == 1: #Check for section to change light1Text.config(text='Amber', bg="#f39c12") #Change label text to correct value canvas.itemconfig(lightcolour1, fill="#f39c12") #Change light to correct colour canvas.itemconfig(section1, tag="Amber") #Change section tag to correct value elif self.number == 2: light2Text.config(text='Amber', bg="#f39c12") #Change label text to correct value canvas.itemconfig(lightcolour2, fill="#f39c12") #Change light to correct colour canvas.itemconfig(section2, tag="Amber") #Change section tag to correct value elif self.number == 3: light3Text.config(text='Amber', bg="#f39c12") #Change label text to correct value canvas.itemconfig(lightcolour3, fill="#f39c12") #Change light to correct colour canvas.itemconfig(section3, tag="Amber") #Change section tag to correct value elif self.number == 4: light4Text.config(text='Amber', bg="#f39c12") #Change label text to correct value canvas.itemconfig(lightcolour4, fill="#f39c12") #Change light to correct colour canvas.itemconfig(section4, tag="Amber") elif intColour == 3: #If random number = 3 (Red) self.colour = "Red" #Change value of colour string if self.number == 1: #Check for section to change light1Text.config(text='Red', bg="#e74c3c") #Change label text to correct value canvas.itemconfig(lightcolour1, fill="#e74c3c") #Change light to correct colour canvas.itemconfig(section1, tag="Red") #Change section tag to correct value elif self.number == 2: light2Text.config(text='Red', bg="#e74c3c") #Change label text to correct value canvas.itemconfig(lightcolour2, fill="#e74c3c") #Change light to correct colour canvas.itemconfig(section2, tag="Red") #Change section tag to correct value elif self.number == 3: light3Text.config(text='Red', bg="#e74c3c") #Change label text to correct value canvas.itemconfig(lightcolour3, fill="#e74c3c") #Change light to correct colour canvas.itemconfig(section3, tag="Red") #Change section tag to correct value elif self.number == 4: light4Text.config(text='Red', bg="#e74c3c") #Change label text to correct value canvas.itemconfig(lightcolour4, fill="#e74c3c") #Change light to correct colour canvas.itemconfig(section4, tag="Red") #Change section tag to correct value class image(object): # base class def __init__(self): self.x = 0 # coords used for both treasure & trap once classed is called self.y = 0 self.location = "" # location set as empty string for trap to use self.draw = canvas self.draw.pack() # pack draw anywhere on canvas as coords will decide where to put it self.widgets() # call mouse click and drag instantly def down(self, event): self.xLast = event.x # coords of where the mouse went down self.yLast = event.y # event of each coords allows mouse to interact def move(self, event): # CURRENT use to tag any object under the mouse, and only move one object at a time self.draw.move(CURRENT, event.x - self.xLast, event.y - self.yLast) # use event of x and y on what object is present to keep it under the mouse once dragged self.xLast = event.x # recall event coords when moving object with mouse self.yLast = event.y def widgets(self): #tag will be binded with movement of mouse and click of mouse, so it is looking for 'treasure' tags and no other self.draw.tag_bind('treasure',"<1>", self.down) # 1 indicates the left click on the mouse, 2 is middle and 3 is right self.draw.tag_bind('treasure',"<B1-Motion>", self.move) # movement of mouse when click is held down def spawn(self, x, y, image, tag): self.image = PhotoImage(file=image) # allows images to be added once file given self.x = x # coords for image once uploaded, both x & y self.y = y self.tag= tag # tag in place to separate the treasure from trap when using mouse self.location = self.draw.create_image(self.x, self.y,image = self.image,tag =self.tag) # able to create an image given the correct arugments wishlist = [] #Creating empty wishlist to be filled when selecting treasure wishlistx = [885, 925, 965, 1005] #X position of images to be placed wishlisty = [346, 346, 346, 346] #Y position of images to be placed treasurelist = [] #Creating empty treasure list to be filled with sorted treasure items locationlist = [] #Creating emtpy location list of landmarks that contain treasure in sorted order def SortTreasure(treasurelist): #Function to sort treasure list (using bubble sort) for i in range(len(treasurelist)-1, 0, -1): #Loop counting down from last item in list for n in range(i): #Nested loop if treasurelist[n].points < treasurelist[n+1].points: #If current item is less then next item temp = treasurelist[n] #Put current item in temp treasurelist[n] = treasurelist[n+1] #Swap next item with current item treasurelist[n+1] = temp #Put current item at place of next item class treasure(image): def __init__(self): image.__init__(self) # use the init from image class to create images, inheritance self.points = 0 # set points to default '0', it will change once each treasure is populated in wishlist def wishList(self, image): if image == "assets/coin.gif": TreasureButtons[0].config(state="disabled") # disbale each treasure button once pressed, index indicates fist item'coin' i = coinImage # used to iterate thrhough list so it can be sorted in order, highest to lowest, once collected self.points = 10 # giving treasure a point value elif image == "assets/greenjewel.gif": TreasureButtons[1].config(state="disabled")# disbale each treasure button once pressed, index indicates fist item'green jewel' i = greenImage# used to iterate thrhough list so it can be sorted in order, highest to lowest, once collected self.points = 20 # giving treasure a point value elif image == "assets/redjewel.gif": TreasureButtons[2].config(state="disabled")# disbale each treasure button once pressed, index indicates fist item'red jewel' i = redImage# used to iterate thrhough list so it can be sorted in order, highest to lowest, once collected self.points = 30 # giving treasure a point value elif image == "assets/chest.gif": TreasureButtons[3].config(state="disabled")# disbale each treasure button once pressed, index indicates fist item'chest' i = chestImage# used to iterate thrhough list so it can be sorted in order, highest to lowest, once collected self.points = 50 # giving treasure a point value image.replace(".gif", "") # replace treasure in wishlist with correct sorted treasure, highest to lowest wishlist.append(image) # append the wishlist with images of treasures, using the base class attributes placement = wishlist.index(image) #Get index of wishlist item if placement == 0: #Check for placement of wishlist item lbl1 = Label(image=i) #Create image label lbl1.place(x=wishlistx[0], y=wishlisty[0]) #Place image label in position 1 elif placement == 1: #Check for placement of wishlist item lbl2 = Label(image=i) #Create image label lbl2.place(x=wishlistx[1], y=wishlisty[1]) #Place image label in position 2 elif placement == 2: #Check for placement of wishlist item lbl3 = Label(image=i) #Create image label lbl3.place(x=wishlistx[2], y=wishlisty[2]) #Place image label in position 3 elif placement == 3: #Check for placement of wishlist item lbl4 = Label(image=i) #Create image label lbl4.place(x=wishlistx[3], y=wishlisty[3]) #Place image label in position 4 treasurelist.append(self) #Add treasure object to list def create(self,x,y,image,tag): # call the base class to use its attributes self.spawn(x,y,image,tag) # using spawn function from image class self.wishList(image) # the wishlist will use the image class for its functions def locate(self): #Function to get landmark treasure is in pos = canvas.coords(self.location) #Get coords of treasure object xpos = pos[0] #Seperate x coords ypos = pos[1] #Seperate y coords i = 0 #Start i at 0 for o in obstacles: #Loop through landmark objects i = i + 1 #Increment i ox1, oy1, ox2, oy2 = canvas.coords(o.lndmrk) #Get coords of landmark object if (xpos > ox1 and xpos < ox2) and (ypos > oy1 and ypos < oy2): #Check if treasure object is within landmark object lnd = obstacles[i-1] #Get landmark object locationlist.append(lnd) #Add landmark object to list locationlist[-1].treasure = True #Landmakr has treasure item if self.points == 10: #Check what treasure the landmark has in it locationlist[-1].treasureID = coinImage #Change treasureID to coin elif self.points == 20: #Check what treasure the landmark has in it locationlist[-1].treasureID = greenImage #Change treasureID to green jewel elif self.points == 30: #Check what treasure the landmark has in it locationlist[-1].treasureID = redImage #Change treasureID to red jewel elif self.points == 50: #Check what treasure the landmark has in it locationlist[-1].treasureID = chestImage #Change treasureID to chest class Trap(image): def __init__(self): image.__init__(self) #Use the init from image class to create images, inheritance self.xpos = 0 #Initilise xpos self.ypos = 0 #Initilise ypos self.hit = False #Initilise hit as false till trap has been hit self.points = 0 #Set points as zero self.previous = "" #Holds previous treasure collected self.colpos = 0 #Holds position of collected image picture def create(self): #Creates the x,y position of trap to check in self.xpos = random.randint(25,829) #Random xpos within canvas self.ypos = random.randint(25,455) #Random ypos within canvas for o in obstacles: #Loop through landmarks ox1, oy1, ox2, oy2 = canvas.coords(o.lndmrk) #Get landmark coords if (self.xpos > ox1 - 35.0 and self.xpos < ox2 + 35.0) and (self.ypos > oy1 - 35.0 and self.ypos < oy2 + 35.0): #Check if within landmark self.create() #Recurrsive function to retry spawn else: self.spawn(self.xpos, self.ypos, "assets/trap.gif",'trap') #Create trap, will not be in final program def collision(self): #Function called when robot within xpos and ypos of trap ChangeThought(4) #Displays text from thoughts nr.4 R1.points = R1.points - self.points #Deducts points of last collected treasure InfoLabels[2].config(text=R1.points) #Displays updated points to user if self.previous == coinImage: #Check what previous treasure collected was coinGreyImage = (Label(image=coinGImage)) #Create image label with coin greyed out coinGreyImage.place(x=CollectedImagex[self.colpos], y=CollectedImagey[self.colpos]) #Place image in correct position elif self.previous == chestImage: #Check what previous treasure collected was chestGreyImage = (Label(image=chestGImage)) #Create image label with chest greyed out chestGreyImage.place(x=CollectedImagex[self.colpos], y=CollectedImagey[self.colpos]) #Place image in correct position elif self.previous == greenImage: #Check what previous treasure collected was greenGreyImage =(Label(image=jewelGImage)) #Create image label with jewel greyed out greenGreyImage.place(x=CollectedImagex[self.colpos], y=CollectedImagey[self.colpos]) #Place image in correct position elif self.previous == redImage: #Check what previous treasure collected was redGreyImage = (Label(image=jewelGImage)) #Create image label with jewel greyed out redGreyImage.place(x=CollectedImagex[self.colpos], y=CollectedImagey[self.colpos]) #Place image in correct position self.spawn(self.xpos, self.ypos, "assets/trap.gif",'trap') #Creates trap image (unhides) #f=canvas.create_image(429,263,image=flashImage, tag="flash") self.hit = True #Changes hit to true so robot will not hit again ChangeThought(8) #Display thought 8 def Start(): Disable() #Runs function to disable settings ChangeThought(2) #Displays text from thoughts nr.2 global intPlay intPlay += 1 if intPlay <= 1: global main main = Countdown(countdown) main.getTime() main.Count() SortTreasure(treasurelist) for n in range (0, len(treasurelist)): treasurelist[n].locate() R1.robotLoad() # Draw R1 onto screen def Disable(): E.config(state=DISABLED) #Disables text entry box for n in range (0,7): #For loop through buttons to disable all ButtonList[n].config(state=DISABLED) for n in range (0,4): #For loop through buttons to disable all TreasureButtons[n].config(state=DISABLED) #These functions below are linked to the buttons for starting position on the GUI, they load up different positions # for the robot to spawn in. def FirstButton(): R1.setSpawn(300, 50) ChangeThought(1) #Displays text from thoughts nr.1 def SecondButton(): R1.setSpawn(60, 130) ChangeThought(1) #Displays text from thoughts nr.1 def ThirdButton(): R1.setSpawn(450, 130) ChangeThought(1) #Displays text from thoughts nr.1 def FourthButton(): R1.setSpawn(200, 350) ChangeThought(1) #Displays text from thoughts nr.1 def FithButton(): R1.setSpawn(700, 150) ChangeThought(1) #Displays text from thoughts nr.1 def SixthButton(): R1.setSpawn(600, 410) ChangeThought(1) #Displays text from thoughts nr.1 MapOneLandMarks() #Function to load the landmarks traps = [] #Empty list to store trap objects for n in range(0,2): #For loop to create trap objects traps.append(Trap()) #Add trap object to list traps[n].create() #Create trap object treasureitems = [] # empty list to populate with treasure treasurex = [840,835] # create a fixed x position for treasure treasurey = [138, 178, 217, 254] # give different y position for treasure #iterate through loop and use treasure class to populate for n in range(0,4): treasureitems.append(treasure()) frames = [] #Empty list to store frames used in GUI FrameHeight = [158, 85, 85, 480, 165, 140, 158] #List containing frame heights FrameWidth = [854, 180, 220, 175, 160, 160, 175] #List containing frame widths FramePlacementx = [11, 275, 476, 872, 880, 880, 872] #List containing frame x pos FramePlacementy = [500, 565, 565, 11, 128, 344, 500] #List containing frame y pos for n in range(0,7): #For loop to create frame GUI elements frames.append(Frame(bd=1, relief=SUNKEN, height=FrameHeight[n], width=FrameWidth[n])) #Creating frames in list frames[n].place(x=FramePlacementx[n], y=FramePlacementy[n]) #Placing frames in correct positions TreasureButtons = [] # creating empty list to be popualted by treasure image for buttons TreasureButtonImage = [coinImage, greenImage, redImage, chestImage] # # images for each treasure button in a list #lambda is an an anonymous function without defining specific attributes # it will call the treasure index first [0] and then create it with the index for each treasure x and & y coords, #once down, the image is loaded and tag is placed TreasureButtonCommand = [lambda: treasureitems[0].create(treasurex[0], treasurey[0], "assets/coin.gif",'treasure'), lambda: treasureitems[1].create(treasurex[0], treasurey[1], "assets/greenjewel.gif",'treasure'), lambda: treasureitems[2].create(treasurex[0], treasurey[2], "assets/redjewel.gif",'treasure'), lambda: treasureitems[3].create(treasurex[1], treasurey[3], "assets/chest.gif",'treasure')] TreasureButtonPlacementy = [130, 168, 208, 247] # placement for each buttons on window for n in range(0,4): # iterates through each treasure item 0-3 (4 objects) # update treasure button list with button function, called the window to place it, the image of the treasure, and the command to execute the button, #and then placement coords for each button TreasureButtons.append(Button(window, image =TreasureButtonImage[n], command=TreasureButtonCommand[n])) TreasureButtons[n].place(x=884, y=TreasureButtonPlacementy[n]) ButtonList = [] #Empty list used to hold buttons ButtonString = ["Start", "1", "2", "3", "4", "5", "6"] #List containing button strings ButtonPlacementx = [878, 877, 902, 927, 952, 977, 1002] #List containing button x pos ButtonPlacementy = [505, 77, 77, 77, 77, 77, 77] #List containing button y pos ButtonWidth = [22, 2, 2, 2, 2, 2, 2] #List containing button width ButtonCommand = [Start, FirstButton, SecondButton, ThirdButton, FourthButton, FithButton, SixthButton] #List containing commands for buttons for n in range (0,7): #For loop used to create buttons ButtonList.append(Button(window, text=ButtonString[n], height=1, width=ButtonWidth[n], command=ButtonCommand[n])) #Creating buttons ButtonList[n].place(x=ButtonPlacementx[n], y=ButtonPlacementy[n]) #Placement of buttons in correct place LabelList = [] #Empty list used to hold labels LabelStrings = ["Position:", "Status:", "Points:", "Currently Looking For:", "Collected Treasure:", "Thoughts:", "Time Limit:", "Starting Point:", "Treasure Selection:", "Coin - 10 Points", "Jewel - 20 Points", "Ruby - 30 Points", "Chest - 50 Points", "Drag And Drop On Landmarks", "Wishlist:"] #List containing label strings LabelPlacementx = [15, 15, 15, 15, 270, 470, 877, 877, 877, 930, 925, 927, 927, 876, 877] #List containing label x pos LabelPlacementy = [540, 570, 600, 630, 540, 540, 35, 55, 106, 137, 175, 215, 255, 293, 320] #List containing label y pos LabelSize = [12, 12, 12, 12, 12, 12, 10, 10, 10, 10, 10, 10, 10, 10, 10] #List containing label size for n in range (0,15): #For loop used to create labels LabelList.append(Label(font=('Helvetica', LabelSize[n]), text=LabelStrings[n])) #Creating labels LabelList[n].place(x=LabelPlacementx[n], y=LabelPlacementy[n]) #Placement of labels InfoLabels = [] #Empty list used to hold info labels InfoLabelString = ["", "", "0"] #List containing label strings InfoPlacementx = [80, 66, 66] #List containing label x pos InfoPlacementy = [540, 570, 600] #List containing label y pos for n in range (0, 3): #For loop used to create labels InfoLabels.append(Label(font=('Helvetica', 12), text=InfoLabelString[n])) #Creating labels InfoLabels[n].place(x=InfoPlacementx[n], y=InfoPlacementy[n]) #Placement of labels pirateLabel = Label(image=pirateImage) #Creating pirate image pirateLabel.place(x=720, y=530) #Placement of pirate images clock=Label(image=ClockG) #Creating clock image clock.place(x=916, y=534) #Placement of clock images lookingLabel = Label() #Label for currently looking for images lookingLabel.place (x=180, y=615) #Placement of label CollectedList = [] #Empty list used to hold collected treasure CollectedImage = [coinImage, greenImage, redImage, chestImage] #List containing collected images CollectedImagex = [280, 315, 345, 375] #Collected images x placement CollectedImagey = [575, 575, 575, 575] #Collected images y placement rbName=Label(font=('Helvetica', 18, 'underline'), text='Virtual Robot Pirate') #Creating heading label settings=Label(font=('Helvetica', 12, 'underline'), text='Settings') #Creating heading label rbName.place(x=15, y=505) #Placement of heading label settings.place(x=877, y=13) #Placement of heading label #Creates countdown label countdown=Label(font=('Helvetica', 20), text='00:00') countdown.place(x=922, y=620) #create entry for countdown E = Entry(font=('Helvetica', 10), width = 12) E.insert(0, "01:00") #placement of entry E.place(x= 947,y= 37) lightlist = [] #Empty list used to store light objects for n in range(1,5): #For loop to create lights lightlist.append(Light(n)) #Add light object to list lightlist[n-1].CreateLight() #Create light #create thoughts label thoughts = ("Change settings to start!", "Click Start!", "Ahoy, Matey!", "Batten down the hatches!", "Aaaarrrrgggghhhh", "Me Booty!", "Heave Ho!", "Avast ye, time up!", "Shiver me timbers!", "Blimey! Done!") thoughtLabel = Label(font=("Helvetica", 12), text=thoughts[0]) #Displays text from thoughts nr.0 thoughtLabel.place(x=480, y=567) def ChangeThought(number): thoughtLabel.config(text=thoughts[number]) #Placement of canvas canvas.place(x=10, y=10) #Drawing line around canvas whole=canvas.create_rectangle(2, 481, 855, 2) R1 = Robot() # Create instance of robot class (R1) R1.setSpawn(300, 50) window.mainloop()
#Aim : Program to find the hypotenuse of a right angled triangle, when the base and height are entered by the user. #Developer: Rakesh yadav h = float (input("Enter height of triangle : ")) b = float (input("Enter base of triangle : ")) # calculation hypotenuse = ((h**2) + (b**2))**0.5 print("Hypotenuse of a right angled triangle = %.2f" %(hypotenuse))
# author: Rakesh yadav # aim: Print even numbers upto 100, without using any arithmetic or comparison operator. l = list(map(int,range(100+1))) num_list = l[0::2] print(num_list)
''' Author : Rakesh Yadav Aim: Use of Zip function in pyhton. ''' a = int(input("Number of students")) marks_in_bme = [] name = [] for i in range(a): h = input("Enter name of students") name.append(h) i = int(input("Enter marks")) marks_in_bme.append(i) print(name) print(marks_in_bme) result=zip(name,marks_in_bme) result_set=set(result) print(result_set)
#Aim : Program to find the area and perimeter of a rectangle, when the required input (Length and Breadth) are entered by the user. #Developer: Rakesh yadav x = float (input("Enter length of rectangle : ")) y = float (input("Enter width of rectangle : ")) # calculation area = (x * y) perimeter = 2*(x + y) print(" Perimeter of rectangle = %.2f" %(perimeter)) print(" Area of rectangle = %.2f" %(area))
''' Author : Rakesh Yadav Task: To kame a program in which 1. take an input as string from user 2. check the string if it contains all vowels or not 3. print if it satisfy above conditions. ''' STR = input() if ('a' or 'A' and 'i' or 'I' and 'u' or 'U' and 'o' or 'O' and 'e' or 'E') in STR : print(STR)
class Rational: ''' Rational class ''' def __init__(self, a, b = 1): ''' :param a: numerator :param b: denominator ''' assert b !=0 assert isinstance(a, int) assert isinstance(b, int) self._a = a self._b = b div = self.gcd(self._a,self._b) self._a = self._a // div self._b = self._b // div def gcd(self,a, b): # note no self parameter for static method '''Return the greatest common divisor of the pair''' while b != 0: a, b = b, a % b return a def __repr__(self): ''' :return: str. represent the Rational class ''' if(self._b == 1): return str(self._a) # return "\'"+ str(self._a)+"/"+str(self._b)+"\'" return str(self._a) + '/' + str(self._b) def __str__(self): ''' :return: ''' if (self._b == 1): return str(self._a) return str(self._a) + '/' + str(self._b) def __add__(self, num): ''' :param num: :return: ''' # self.add(num) <- self + num num + self num.add(self) if isinstance(num,float): return float(self) + num if isinstance(num, int): num = Rational(num) return Rational(self._a * num._b + self._b * num._a,(self._b*num._b)) def __sub__(self,num): ''' :param num: :return: ''' return self + -num def __mul__(self,num): ''' :param num: :return: ''' if isinstance(num, float): return float(self) * num if isinstance(num, int): num = Rational(num) return Rational((self._a * num._a ) , (self._b * num._b)) # def __div__(self,num): # ''' # :param num: # :return: # ''' # if not isinstance(num, Rational): # num = Rational(num) # return Rational((self._a * num._b) , (self._b * num._a)) def __truediv__(self, num): ''' :param num: :return: ''' if isinstance(num,float): return float(self) / num if isinstance(num, int): num = Rational(num) return Rational((self._a * num._b) , (self._b * num._a)) def __radd__(self, num): ''' :param num: :return: ''' # return self + num def __rsub__(self, num): ''' :param frac2: :return: ''' return -self + num def __rmul__(self, num): ''' :param num: :return: ''' return self * num def __rtruediv__(self, num): ''' :param num: :return: ''' return Rational(self._b, self._a) * num def __neg__(self): ''' :return: ''' return Rational(-self._a, self._b) def __float__(self): ''' :return: ''' return self._a / self._b def __int__(self): ''' :return: ''' return int(self._a / self._b) def __lt__(self, num): ''' :param num: :return: ''' if not isinstance(num, Rational): num = Rational(num) return self._a * num._b < self._b * num._a def __eq__(self, num): ''' :param num: :return: ''' if isinstance(num, int): num = Rational(num) if isinstance(num, float): return float(self) == num return self._a == num._a and self._b == num._b # r = Rational(3,4) # print(repr(r)) # print(-1/r) # print(float(-1/r)) # print(int(r)) # print(int(Rational(10,3))) # print(Rational(10,3) * Rational(101,8) - Rational(11,8)) # print([Rational(10,3),Rational(9,8), Rational(10,1), Rational(1,100)]) # print(sorted([Rational(10,3),Rational(9,8), Rational(10,1), Rational(1,100)])) # print(Rational(100,10)) # print(-Rational(12345,128191) + Rational(101,103) * 30 /44) # print(r == Rational(3,4))
def get_trapped_water(seq): ''' :param seq: input list :return: how many units of water remain trapped between the walls in the map ''' assert isinstance(seq, list) assert len(seq) != 0 for i in seq: assert isinstance(i,int) assert i >=0 n = len(seq) left, right = 0, n - 1 max_left, max_right = seq[0], seq[-1] res = 0 while left <= right: max_left = max(seq[left], max_left) max_right = max(seq[right],max_right) if max_left < max_right: res += max_left - seq[left] left += 1 else: res += max_right - seq[right] right -= 1 return res # print(get_trapped_water([3, 0, 1, 3, 0, 5])) # print(get_trapped_water([]))
def slide_window(x,width,increment): ''' Implement a sliding window for an arbitrary input list :param x: input list :param width: window width :param increment: window increment :return: res ''' assert isinstance(x, list) assert isinstance(width, int) assert isinstance(increment, int) assert width > 0 and width <= len(x) assert increment>0 res = [] for i in range(0,len(x),increment): if i <= len(x)-width: res.append(x[i:i+width]) return res print(slide_window(list(range(18)),5,2))
#This is the program for a brute force approach to solving the closest points problem, and will run in O(n^2) time. import sys import math import time def writefile(points, distance): f1 = "output_bruteforce.txt" with open(f1, "a+") as f: f.write(str(distance) + '\n') for i in points: f.write(i[0] + " " + i[1] + '\n') def brute_sort(coords): #we will append all closest points to some array distances = [] points = [] closest_points = [] current = math.sqrt(pow((float(coords[1][0])-float(coords[0][0])), 2) + pow((float(coords[1][1])-float(coords[0][1])), 2)) for i in range(len(coords)): for j in range(i): points.append((coords[i][0] + " " + coords[i][1], coords[j][0] + " " + coords[j][1])) distance = math.sqrt(pow((float(coords[j][0])-float(coords[i][0])), 2) + pow((float(coords[j][1])-float(coords[i][1])), 2)) distances.append(distance) if current > distance: current = distance #point = coords[j][0] + " " + coords[i][0] + " " + coords[j][1] + " " + coords[i][1] for i in range(len(distances)): if distances[i] == current: closest_points.append(sorted(points[i])) #handles other points of same distance closest_points = sorted(closest_points) writefile(closest_points, current) def readfile(fn): coords = [] pairs = [] with open(fn) as f: coords = f.read().splitlines() for i in range(len(coords)): pairs.append(coords[i].split()) start = time.time() brute_sort(pairs) print "ELAPSED:",time.time()-start def main(filename): if len(filename) == 1: fn = filename[0] readfile(fn) else: print "Error reading command line. Format: program <filename>" if __name__ == "__main__": main(sys.argv[1:])
def num_tests(): return int(input("Enter number of assignments you've had: ")) return int(input("Enter number of tests: ")) def get_score(): score = [] test = num_tests() for i in range(0, test): score.append(float(input("Enter assignment grade: "))) return score def main(): score = get_score() total = sum(score) #test = num_tests() print(score) print(total) main()
i = 0 l = [1,2,3,4,5,6] for ll in l: print(ll, i) i += 1 l.insert(1, 9) print(l)
class Queue: def __init__(self): self.queue = [] # Add an element def enqueue(self, item): self.queue.append(item) # Remove an element def dequeue(self): if len(self.queue) < 1: return None return self.queue.pop(0) # Display the queue def display(self): #tempQ = Queue() for i in range(self.size()): #temp = self.dequeue() #tempQ.enqueue(temp) print(self.queue[i]) #self.queue=tempQ.queue def size(self): return len(self.queue) def front(self): return self.queue[0]
wh =raw_input() if(wh=='a' or wh=='e' or wh=='i' or wh=='o'or wh=='u'): print "vowels" else: print "consonant"
from random import randint n = 3 arr = [] for i in range(n): sign = randint(0, 1) if sign == 1: arr += [['+', randint(1, 5)]] else: arr += [['-']] print(n) for x in arr: print(*x)
#!/python3 # -*- coding: utf-8 -*- def gcd(a, b): return a if b == 0 else gcd(b, a % b) class Fraction: def __init__(self, numerator, denominator): g = gcd(numerator, denominator) self.top = int(numerator / g) self.bottom = int(denominator / g) def __eq__(self, other): first_num = self.top * other.bottom second_num = other.top * self.bottom return first_num == second_num def __add__(self, other): return Fraction( self.top * other.bottom + other.top * self.bottom, self.bottom * other.bottom ) def __str__(self): return "{}/{}".format(self.top, self.bottom) if __name__ == "__main__": fraction1 = Fraction(4, 5) print(fraction1 + Fraction(1, 8)) # => 37/40 print(Fraction(40, 70)) # => 4/7 print(Fraction(1, 6) + Fraction(1, 3)) # => 1/2
# Q5 Write a Python program to create and display all combinations of letters, # selecting each letter from a different key in a dictionary # Sample data : {'1':['a','b'], '2':['c','d']} # Expected Output: ac ad bc bd from itertools import product data ={'1':['a','b'], '2':['c','d']} print (data) for x in data['1']: for y in data['2']: print(x + y)
def decorator(cls): print(">>>AAA 这里可以写被装饰类新增的功能") return cls @decorator class A(object): def __init__(self): pass def test(self): print("test") def decoratorB(cls): print(">>>BBB 这里可以写被装饰类新增的功能") class B_new(cls): def __init__(self): print("B_new") super().__init__() return B_new @decoratorB class B(object): def __init__(self): pass def test(self): print("test") """ >>>这里可以写被装饰类新增的功能 """ a = A() b = B()
#!/usr/bin/env python # -*- coding: UTF-8 -*- dict1 = {} dict1["a"] = [] dict1["a"].append(1) dict1["a"].append(2) dict1["n"]=2 list1 = dict1["a"] n = dict1["n"] dict1["a"].pop(0) dict1["n"] -= 1 print(dict1.keys()) print(dict1["a"],list1,dict1["n"],n) list1[0] = 10 print(dict1["a"],list1) def getdict(): dict1 = {} dict1["a"] = 1 return dict1 dict11 = getdict() dict12 = getdict() dict11["a"] = 2 dict13 = getdict() print(dict11, dict12, dict13) aa = 3 for i in range(aa): if aa < 5: aa += 1 print(i)
# 创建一个多线程编程的例子 import threading def print_numbers(num): for i in range(1, num): print(i) def print_letters(str): for letter in str*10: print(letter) # 创建两个线程 t1 = threading.Thread(target=print_numbers,args=(100,)) t2 = threading.Thread(target=print_letters, args=("abcdefghij",)) # 启动线程 t1.start() t2.start() # 等待线程结束 t1.join() t2.join()
from PIL import Image, ImageFilter import cv2 def crop_edges_PIL(): # Open the image img = Image.open("image.bmp") # Convert the image to grayscale img_gray = img.convert("L") # Get the edges of the image edges = img_gray.filter(ImageFilter.FIND_EDGES) # Crop the image to remove the black border cropped = img.crop(edges.getbbox()) # Save the cropped image cropped.save("cropped_image.bmp") def crop_edges_CV(): # Read the image img = cv2.imread("image.bmp") # Convert the image to grayscale img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Get the edges of the image edges = cv2.Canny(img_gray, 10, 10) cv2.imwrite("edges.bmp", edges) # Crop the image to remove the black border x, y, w, h = cv2.boundingRect(edges) print(x, y, w, h) cropped = img[y:y + h, x:x + w] # Save the cropped image cv2.imwrite("cropped_image.bmp", cropped) if __name__ == '__main__': crop_edges_CV()
import torch from torch.utils.data import Dataset class MyDataset(Dataset): def __init__(self, data): self.data = data def __getitem__(self, index): x = self.data[index][0] y = self.data[index][1] return x, y def __len__(self): return len(self.data) # 数据 data = [(1, 2), (3, 4), (5, 6)] # Then you can create an instance of the dataset: my_dataset = MyDataset(data) # You can then use a DataLoader to load the data in batches: my_dataloader = torch.utils.data.DataLoader(my_dataset, batch_size=2, shuffle=True) # Now you can iterate over the dataloader to get batches of data: for batch in my_dataloader: x, y = batch print(x, y)
Username = input("What is your Username? ") if Username == "Homer": password = input("password: ") if password == "8166": print("Successful") else: print("try again") else: print("try again")
def show_activity(): print() print("1. Praca siedząca, brak dodatkowej aktywności fizycznej.") print("2. Praca niefizyczna, mało aktywny tryb życia") print("3. Lekka praca fizyczna, regularne ćwiczenia 3-4 razy (ok. 5h) w tygodniu") print("4. Praca fizyczna, regularne ćwiczenia od 5razy (ok. 7h) w tygodniu") print("5. Praca fizyczna ciężka, regularne ćwiczenia 7 razy w tygodniu") print() def check_activity(activity): if activity == 1: factor_a = 1.2 if activity == 2: factor_a = 1.4 if activity == 3: factor_a = 1.6 if activity == 4: factor_a = 1.8 if activity == 5: factor_a = 2.0 return factor_a def check_sex(sex): if sex == "K" or sex == "k": factor_s = -161 if sex == "M" or sex == "m": factor_s = 5 return factor_s def base_calculation(weight, height, age, factor_s, factor_a): return ((10 * weight) + (6.25 * height) - (5 * age) + factor_s) * factor_a sex = input("Podaj swoją płeć wpisując K jeśli kobieta lub M jeśli mężczyzna: ") age = int(input("Podaj swój wiek: ")) weight = int(input("Podaj swoją wagę w kilogramach: ")) height = int(input("Podaj swój wzrost w centymetrach: ")) show_activity() activity = int(input("Patrząc na powyższą listę określ swoją aktywność i podaj jej numer: ")) print("Twoje dzienne zapotrzebowanie kaloryczne wynosi:") print(base_calculation(weight, height, age, check_sex(sex), check_activity(activity)))
import sqlite3 conn = sqlite3.connect('blog.db') cur = conn.cursor() query_del = '''delete from blogpost where id=4;''' cur.execute(query_del) query = '''select * from blogpost;''' cur.execute(query) rows = cur.fetchall() for row in rows: print(row)
import math import graphics import controller import art_int """ letters = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9} inv_letters = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I', 9: 'J'} allowed_letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] allowed_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] """ def main(): # Create graphical board board_p1 = graphics.init_board() board_p2 = graphics.init_board() # Create allowed_coords list for both users allowed_coords_p1 = controller.create_allowed_coords() allowed_coords_p2 = controller.create_allowed_coords() # Start Game - Intro Screen graphics.print_intro() while True: try: turns = input('How many turns do you want to play: ') if turns == 'exit' or turns == 'quit': break turns = int(turns) * 2 if turns > 10000: print('Maximum number of turns: 1000') raise ValueError elif turns < 1: print('Minimum number of turns: 1') raise ValueError break except ValueError: print('Please specify a number between 1-10000! (Enter exit or quit if you want to finish the game') except: print('\nAn error occured.') finally: if turns == 'exit' or turns == 'quit': exit() # Players place ships - example for coords: 11 print('\n') print('Player 1 place your ships: ') ships_p1 = controller.create_ships(1, allowed_coords_p1) print('\n') print('Player 2 place your ships: ') ships_p2 = controller.create_ships(2, allowed_coords_p2) print('\n') # Begin Turns for turn in range(turns): if turn % 2 == 0: # player1 print("value of board_p1 from main", board_p1) graphics.print_board(board_p1) print('Turn', math.ceil((turn + 1) / 2)) print('Hello Player 1!') # Ask user for a guess shootTo = [] shootTo = controller.user_guess() # Evaluate user guess if controller.evaluate_guess(shootTo, board_p1, ships_p2): break else: # player2 graphics.print_board(board_p2) print('Turn', math.ceil((turn + 1) / 2)) print('Hello Player 2!') # Ask user for a guess shootTo = [] shootTo = controller.user_guess() # Evaluate user guess if controller.evaluate_guess(shootTo, board_p2, ships_p1): break if __name__ == '__main__': main()
# coding=utf-8 ''' 冒泡排序(升序)【稳定排序】 原理: 1、从第一个元素开始,开始依次对相邻的两个元素进行比较,当后面的元素大于前面的元素时,交换二者位置; 2、进行一轮比较之后,最大的元素将在序列尾部(最后一位); 3、然后对(n-1)个元素再进行第二轮比较,最大元素将在序列倒数第二位; 4、重复该过程,直至只剩下最后一个元素为止,最后的元素就是最小值,排在序列首位 以 list = [5, 4, 2, 1, 3] 为例: 第一轮排序: [4, 2, 1, 3, 5] 第二轮排序: [2, 1, 3, 4, 5] 第三轮排序: [1, 2, 3, 4, 5] 时间复杂度: O(n) ~ O(n**2) 平均:O(n**2) 空间复杂度: O(1) :param lists: :return lists: ''' def get_maopaosort(l): for i in range(len(l)-1): for j in range(len(l)-i-1): if l[j] > l[j+1]: l[j], l[j+1] = l[j+1], l[j] return l if __name__ == '__main__': l = [5, 4, 2, 1, 3] print(get_maopaosort(l))
# coding=utf-8 ''' 插入排序(升序)【稳定排序】 原理: 1、假设初始时假设第一个记录,自成一个有序序列,其余的记录为无序序列; 2、从第二个记录开始,按记录大小,依次插入之前的有序序列中; 3、直到最后一个记录插入到有序序列中为止 以 list = [5, 4, 2, 1, 3] 为例: 第一步,插入5之后: [5], 4, 2, 1, 3 第二步,插入4之后: [4, 5], 2, 1, 3 第三步,插入2之后: [2, 4, 5], 1, 3 第四步,插入1之后: [1, 2, 4, 5], 3 第五步,插入3之后: [1, 2, 3, 4, 5] 时间复杂度: O(n) ~ O(n**2) 平均: O(n**2) 空间复杂度: O(1) :param lists: :return: lists ''' def get_insertsort1(l): for i in range(len(l)): ans = i j = i-1 while j >= 0: if l[ans] < l[j]: l[ans], l[j] = l[j], l[ans] ans = j j -= 1 else: break return l def get_insertsort2(lists): for i in range(len(lists)): key = lists[i] j = i-1 while j >= 0: if key > lists[j]: lists[j+1] = key key = lists[j] j -= 1 return lists if __name__ == '__main__': l = [5, 4, 2, 1, 3] print(get_insertsort1(l)) print(get_insertsort2(l))
def readInput( file, type ): input_file = open(file, "r") # row delimitered list of strings if ( type == "text_list" ): output = [] for row in input_file : output.append(str(row)) # Return Output return output if __name__ == "__main__": # Read input string_list = readInput("2.txt", "text_list") # Part one, find checksum total_amount_list = [0] * 10 for string in string_list : # Check string for uccurances amount_set = set([]) for c in string: amount_set.add(string.count(c)) # Add string to total for amount in amount_set : if amount > 1 : total_amount_list[amount] += 1 # Calc checksum checksum = 1 for amount in total_amount_list[:4] : if (amount > 0) : checksum = checksum * amount print("Checksum (part 1):" + str(checksum)) # Part two, prototype fabric string_lenth = len(string_list[0]) - 1 for string_idx in range(0, (len(string_list))): for compare_idx in range(string_idx + 1, len(string_list)): # compare strings matches = 0 for char_idx in range(0, string_lenth): if string_list[string_idx][char_idx] == string_list[compare_idx][char_idx]: matches += 1 if matches == (string_lenth-1): #print ("idx " + str(string_idx) + " and idx " + str(compare_idx) + " match") # build prototype prototype = "" for char_idx in range(0, string_lenth): if string_list[string_idx][char_idx] == string_list[compare_idx][char_idx]: prototype += string_list[string_idx][char_idx] print ("Prototype (part 2): " + prototype)
# look at basic_01.py. if you want to print a schedule of 30 days, you should think of for loop on days members = ['Mom', 'Dad', 'Hanhan', 'Menmen'] tasks = ['Washes Dish', 'Cleans Floor', 'Cleans Table', 'Others Stuff'] for day in range (0, 30): print 'Day', day+1, ':' print '\t', members[0], tasks[0] # \t for tab print '\t', members[1], tasks[1] print '\t', members[2], tasks[2] print '\t', members[3], tasks[3] print '\n' # \n for new line # however, the job is fixed to each person! How to deal with that. # Observe teh basic_01.py. the order of tasks should be # 0,1,2,3 # 1,2,3,0 # 2,3,0,1 # 3,0,1,2 # 0,1,2,3 # 1,2,3,0 # 2,3,0,1 # 3,0,1,2 # ...... # how to generate a pattern like this?
# plus a = 3.2 b = 5.8 c = a+b print c # minus a = 3.2 b = 5.8 c = a-b print c # times a = 3.2 b = 5.8 c = a*b print c # divide a = 3.2 b = 5.8 c = a/b print c #remainder (integer only) a=187 b=13 print a%b #power a=2.0 b=3 print a**b #task, write some math expression on paper, translate them to python.
class Solution: # @param s, a string # @param dict, a set of string # @return a list of strings def wordBreak(self, s, dict): n = len(s) A = [None] * n i = n-1 while i >= 0: if s[i:n] in dict: A[i] = [n] # A[i] contains "n" means s[i..n-1] is a word else: A[i] = [] # Check al possible j break for j in range(i+1, n): if A[j] and s[i:j] in dict: A[i].append(j) i -= 1 print A res = [] # possible sentences with break path_list = [[0]] # initially, there is only one path containing the source node while path_list: new_list = [] # For each path, # 1) If the path ends with break "n", then segment the string with breaks of the path # 2) otherwise, expand it with all possible breaks for path in path_list: #print path if path[-1] == n: # segment! # Get words according to the breaks temp = [ s[path[i]:path[i+1]] for i in range(len(path)-1) ] # join words together res.append(" ".join(temp)) else: # expand the path for j in A[path[-1]]: print path+[j] new_list.append(path+[j]) print new_list path_list = new_list #print path_list return res s = Solution() a = s.wordBreak("catsanddog",["cat","cats","and","sand","dog"]) print a
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of integers def preorderTraversal(self, root): list = [] stack = [] if root: stack.append(root) while stack: node = stack.pop() list.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return list class Solution: # @param root, a tree node # @return a list of integers def preorderTraversal(self, root): list = [] stack = [] while root or stack: if root: stack.append(root) list.append(root.val) root = root.left else: root = stack.pop() root = root.right return list # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def preorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ stack = [root] res = [] while stack: node = stack.pop() if node: res.append(node.val) stack.append(node.right) stack.append(node.left) return res # recursively def preorderTraversal1(self, root): res = [] self.dfs(root, res) return res def dfs(self, root, res): if root: res.append(root.val) self.dfs(root.left, res) self.dfs(root.right, res)
class Solution(object): def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ # table = {} # for i in s: # if i in table: # table[i] += 1 # else: # table[i] = 1 # for i in t: # if i in table: # table[i] -= 1 # else: # return False # for k in table: # if table[k] != 0: # return False # return True alphabet = [0] * 26 for i in s: alphabet[ord(i) - ord('a')] += 1 for i in t: alphabet[ord(i) - ord('a')] -= 1 for i in alphabet: if i != 0: return False return True ss = Solution() s = 'ansagram' t = 'nagaram' print(ss.isAnagram(s,t))
#Bubble Sort def bubbleSort(items): for i in range(len(items)): for j in range(len(items) - i - 1): if items[j] > items[j+1]: items[j], items[j+1] = items[j+1], items[j] #Insertion Sort def insertionSort(items): for i in range(1, len(items)): j = i while j > 0 and items[j-1] > items[j]: items[j], items[j-1] = items[j-1], items[j] j -= 1 #Selection Sort def selectionSort(items): for i in range(len(items)): minimum = i for j in range(i+1, len(items)): if items[j] < items[minimum]: minimum = j items[minimum], items[i] = items[i], items[minimum] #Merge Sort # def merge(left, right): # result = [0] * (len(left) + len(right)) # l = r = 0 # for i in range(len(result)): # lval = left[l] if l < len(left) else None # rval = right[r] if r < len(right) else None # if (lval and rval and lval < rval) or rval is None: # result[i] = lval # l += 1 # elif (lval and rval and lval >= rval) or lval is None: # result[i] = rval # r += 1 # return result # def mergeSort(items): # if len(items) < 2: # return items # mid = len(items) // 2 # return merge(mergeSort(items[:mid]), mergeSort(items[mid:])) def mergesort( aList ): _mergesort( aList, 0, len( aList ) - 1 ) def _mergesort( aList, first, last ): # break problem into smaller structurally identical pieces mid = ( first + last ) // 2 if first < last: _mergesort( aList, first, mid ) _mergesort( aList, mid + 1, last ) # merge solved pieces to get solution to original problem a, f, l = 0, first, mid + 1 tmp = [None] * ( last - first + 1 ) while f <= mid and l <= last: if aList[f] < aList[l] : tmp[a] = aList[f] f += 1 else: tmp[a] = aList[l] l += 1 a += 1 if f <= mid : tmp[a:] = aList[f:mid + 1] if l <= last: tmp[a:] = aList[l:last + 1] a = 0 while first <= last: aList[first] = tmp[a] first += 1 a += 1 # #Quicksort # def quicksort(items): # if len(items) <= 1: # return items # left = [] # right = [] # pivotList = [] # pivot = items[len(items)//2] # for i in items: # if i < pivot: # left.append(i) # elif i > pivot: # right.append(i) # else: # pivotList.append(i) # left = quicksort(left) # right = quicksort(right) # return left + pivotList + right def quicksort(items): quicksortHelper(items, 0, len(items) - 1 ) def quicksortHelper(array, start, end): if(start < end): split = partition(array, start, end) quicksortHelper(array, start, split - 1) quicksortHelper(array, split + 1, end) def partition( aList, first, last ) : for i in range(first, last): if aList[i] <= aList[last]: swap(aList, i, first) first += 1 swap(aList, first, last) return first def swap( A, x, y ): A[x],A[y]=A[y],A[x] items = [43, 2,2,4 , 54, 23, 12, 4, 56, 44, 21, 7] mergesort(items) print(items)
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ heap = [] for node in lists: if node is not None: heap.append((node.val, node)) heapq.heapify(heap) head = ListNode(0) curr = head while heap: top = heapq.heappop(heap) curr.next = ListNode(top[0]) curr = curr.next if top[1].next: heapq.heappush(heap, (top[1].next.val, top[1].next)) return head.next
# https://www.codewars.com/kata/does-my-number-look-big-in-this/ def narcissistic(n): # return value == sum(int(x) ** len(str(value)) for x in str(value)) """ A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number of digits. For example, take 153 (3 digits): 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 :param n: Digit :return: True if Digit is Narcissistic Number """ sum = 0 for x in str(n): sum += int(x) ** len(str(n)) return sum == n assert narcissistic(7) is True assert narcissistic(371) is True assert narcissistic(122) is False assert narcissistic(4887) is False assert narcissistic(92727) is True
# https://www.codewars.com/kata/snail # Не уложился по времени :) def snail(a): """ Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise. array = [[1,2,3], [4,5,6], [ 7,8,9]] snail(array) #=> [1,2,3,6,9,8,7,4,5] :param a: array :return: array elements arranged from outermost elements to the middle element """ res = [] n = len(a[0]) # количество строк или столбцов full = n # количество заполнений в одном направлении for k in range(n): # обход первой строки res.append(a[0][k]) # [1, 2, 3] a[0][k] = -1 countfull = 1 # счётчик заполнений x = n i, j = 0, n - 1 while x < n * n - 1: # go down if a[i][j] == -1 and a[i+1][j] != -1: countfull += 1 if countfull == 2: full -= 1 countfull = 0 for down in range(i + 1, i + full + 1): res.append(a[down][j]) a[down][j] = -1 i += 1 x += 1 # go left if a[i][j] == -1 and a[i][j - 1] != -1: countfull += 1 if countfull == 2: full -= 1 countfull = 0 for left in range(i - 1, j - full - 1, -1): res.append(a[i][left]) a[i][left] = -1 j -= 1 x += 1 # go up if a[i][j] == -1 and a[i - 1][j] != -1: countfull += 1 if countfull == 2: full -= 1 countfull = 0 for up in range(i - 1, i - full - 1, -1): res.append(a[up][j]) a[up][j] = -1 i -= 1 x += 1 # go right if a[i][j] == -1 and a[i][j + 1] != -1: countfull += 1 if countfull == 2: full -= 1 countfull = 0 for right in range(j + 1, j + full + 1): res.append(a[i][right]) a[i][right] = -1 j += 1 x += 1 return res or [] array = [[1,2,3,4], [12,13,14,5], [11,16,15,6], [10,9,8,7]] array2 = [[1,2,3], [4,5,6], [7,8,9]] array3 = [[]] print(snail(array))
# https://www.codewars.com/kata/which-are-in/ # Не прошёл тесты. Не могу понять почему def in_array(a1, a2): d = {} for x in sorted(a1): d[x] = 0 for y in a2: if x in y: d[x] += 1 res = [] for x in d: if d[x] > 0: res.append(x) return res a1 = ["arp", "strong", "live"] a2 = ["lively", "alive", "harp", "sharp", "armstrong"] r = ['arp', 'live', 'strong'] assert in_array(a1, a2) == r
from data import * def solve(): floor = 0 position = 1 final_position = 0 for paren in parens: if paren == "(": floor = floor + 1 else: floor = floor - 1 if floor == -1 and final_position == 0: final_position = position position = position + 1 return floor,final_position if __name__=="__main__": floor, position = solve() print("The solution is:\n %d floor \n%d position" % (floor, position))
class Node: def __init__(self, data): self.data = data self.next = None self.prev = None class CircularDoublyLinkedList: def __init__(self): self.first = None def get_node(self, index): current = self.first for i in range(index): current = current.next #if current == self.first: # return None return current def insert_after(self, ref_node, new_node): new_node.prev = ref_node new_node.next = ref_node.next new_node.next.prev = new_node ref_node.next = new_node def insert_before(self, ref_node, new_node): self.insert_after(ref_node.prev, new_node) def insert_at_end(self, new_node): if self.first is None: self.first = new_node new_node.next = new_node new_node.prev = new_node else: self.insert_after(self.first.prev, new_node) def insert_at_beg(self, new_node): self.insert_at_end(new_node) self.first = new_node def remove(self, node): if self.first.next == self.first: self.first = None else: node.prev.next = node.next node.next.prev = node.prev if self.first == node: self.first = node.next def display(self): if self.first is None: return current = self.first while True: print(current.data, end = ' ') current = current.next if current == self.first: break fp = open('test_input.txt', 'r') inp_list = fp.read().strip().split() fp.close() player_num = int(inp_list[0]) last_marble_value = int(inp_list[6]) marble_circle = CircularDoublyLinkedList() marble_circle.insert_at_beg(Node(0)) player_score_array = [] current_marble_index = 0 current_marble = marble_circle.first node1 = Node(1) marble_circle.insert_after(marble_circle.get_node(0), node1) current_marble = node1 for i in range(player_num): player_score_array.append(0) #print(player_score_array) for i in range(2, last_marble_value + 1): if (i % 23 != 0): marble_circle.insert_after(current_marble.next, Node(i)) #print(current_marble_index + 2) current_marble = current_marble.next.next #print(marble_circle) else: #print("current index: ", current_marble_index) current_marble = current_marble.prev.prev.prev.prev.prev.prev.prev player_score_array[(i%player_num)] += current_marble.data player_score_array[(i%player_num)] += i temp_marb = current_marble.next marble_circle.remove(current_marble) current_marble = temp_marb #current_marble_index = current_marble_index - 7 current_marble player_score_array.sort() print(player_score_array) #PART 2 VERY VERY VERY SLOW, NEED 0(1) INSERTION, DOUBLY LINKED LIST WOULD BE IDEAL
a=[1,2,4,5] print a b=[1,2,3,4] c=a+b print c for i in c: print i print 3 in a #search a=[2,3,1,4] a.append[5] print a
n= input('Enter a number:') sum = 0 i=n temp=n while(i>0): Factorial = 1 i = 1 Reminder = Temp % 10 while(i <= Reminder): Factorial = Factorial * i i = i + 1 print("\n Factorial of %d = %d" %(Reminder, Factorial)) Sum = Sum + Factorial Temp = Temp%10 print("\n Sum of Factorials of a Given Number %d = %d" %(Number, Sum)) if (sum == n): print(" %d is a Strong Number" %Numb) else: print(" %d is not a Strong Number" %Number)
import re x='virat is good boy' if(re.search('Good',x,re.I)): #I:Ignore case print "Found" else: print "Not Found"
def fun(x,y): z=x+y return z a=fun(10,20) print a def factorial(num): f=1 for i in range(1,num+1): f=f*i return f n=input('Enter a number') result=factorial(n) print result
add = lambda x,y:x+y print add(20,30) cube = lambda x: x ** 3 print cube(4) joinStr = lambda *args: "-".join(args) print joinStr("Hi", "Hello") print "Passing a function name as a parameter in a function" def doOperations(operation,a,b): print operation(a,b) def subtract(a,b): print a-b doOperations(subtract, 10,5) print "Calling lambda as a function parameter" doOperations(lambda x,y:x-y,40,20) # lambda , express and the parameters which have to be evaluated
adharDB = {} #input from user # His adhar number, Name of the person, mobile number and city # save it in your dict # Enter for three records # Key adar num # value is dictionary containing : key personName, key mobile value = number and Key city and value # value {'name': , 'mobile':, 'city':} for _ in range(3): name = raw_input("Enter Name :") mobile = raw_input("Enter mobile :") city = raw_input("Enter city :") while True: adharNum = raw_input("Enter adhar number :") if adharNum.isdigit() and len(adharNum) ==5: break adharDB[adharNum] = {'name': name, 'mobile':mobile, 'city':city} print "******\n" print adharDB
import re str1 = "john 1234 12/12/2000 , merry 893 01-02-1994 2333 1/1/98" #DOB print "Get on DOB =",re.findall(r'\d+[/-]\d{1,2}[/-]\d{2,4}',str1) #only year of birth print "Get on Year Of birth =",re.findall(r'\d+[/-]\d{1,2}[/-](\d{2,4})',str1) str2 = "12.23.10.1 127.0.0.1 23.34 100.1.11" print "Valid Ip =",re.findall(r'\b\d+\.\d+\.\d+\.\d+',str2) str3 = "test@oracle1.com, abc@test.com, xyz@gmail.com" print "Only domain names " ,re.findall(r'@(\w+\.\w+)',str3) logs = """ Err log #1 debug log #10 msg error log #100 err""" #log id print "Only log id ",re.findall(r'#(\d+)',logs) str4 = "ant bat orange umbrella mango" print "Words starting with vowels: ",re.findall(r'\b[aeiou]\w+',str4) print "Words NOT starting with vowels: ",re.sub(r'\b[aeiou]\w+','',str4) # '' is used to replace
""" ---------------- Client Server ---------------- Create a TCP/IP side using socket() function Connect the socket with the host name and port of the server using connect method Send /receive the message to the client using send() and recv() Disconn by closing the socket using close() """ # Here we are creating our own server # Where ever you want to run the server we will use this script import socket # create , connect, send/recv, close clientListeningSocket = socket.socket() # TCP/IP socket serverHostnameIP = 'localhost' serverPort = 5500 clientListeningSocket.connect((serverHostnameIP, serverPort)) print "Connection to the Server has been established ...." dataRecivedFromServ = clientListeningSocket.recv(1024) while dataRecivedFromServ: print "Data received from server = " , dataRecivedFromServ dataRecivedFromServ = clientListeningSocket.recv(1024) clientListeningSocket.close() print "Connection to the Server has been closed" # we need to first run Server prog # then run client prog
# Required arguments : These are mandatory. The user must provide them when calling the function else error. Order of calling the argument should be followed as the func definition # Keyword arguments : Here we provide the parameter name and the value, the order of the parameter can be anything # Default arguments : Here if the user does not provide the value the default value specified in the definition is used. The default rgs should be in the end # Variable length arguments: * is used to identify the rgument which is variable. It must be a tuple # Required arguments def displayInfo(name): print name displayInfo("Suparna") # Keyword arguments def printInfo(name, age, gender): print "Name = ", name print "Age = ", age print "gender = ", gender printInfo(age = 30, name = 'Oracle', gender ='F') # Order of calling does not match as we are providing it with parameterName and value printInfo("Hello", gender='M', age=5) # here first we have given the value for name , other two we have used keyword which is fine, since in the def name is a string so order is followed #Default arguments-optional arguments #Rules - placed after the required arguments, can be multiple def calculateEMI(amount, rate = 10, duration = 12): emi = amount * rate/100 print "Amount =", amount print "Rate =", rate print "duration =", duration print "EMI = ", emi calculateEMI(1000) #takes default value of rate = 10 calculateEMI(1000,20) #takes default value of rate = 20 user defined and default of duration as 12 calculateEMI(1000, duration=24) #Rules- placed after required args, can have only one variable arg # Cannot have default and variable paramters together def joinStr(delimeter, *args): print " No of arguments passed = ", len(args) print "Args = ", args return delimeter.join(args) joinStr("-","a", "b", "c") # tuple passed contains 3 arguments joinStr("*","oracle", "GE") def add(*args): result = 0 for i in args: result = result + i return result print "10+20+30 = ", add(10,20,30) print "20+30 = ", add(20,30)
class Parent1(object): def displayInfo(self): print "Parent 1" # end of Paren1 class class Parent2(object): def displayInfo(self): print "Parent 2" # end of Paren2 class class Child(Parent1, Parent2): def displayInfo(self): super(Child, self).displayInfo() # end of Child class class Child2(Parent2, Parent1): # Different order of Parent def displayInfo(self): super(Child2, self).displayInfo() # end of Child class c = Child() c.displayInfo() print " -------------" c2 = Child2() c2.displayInfo()
"""Lists Example Append, extend, insert, remove del """ data = ['c', 'c++', 'Java', 100, 200] #Operations print "Number of elements in my list = ", len(data) print "First element: ", data[0] print "Last element: ", data[-1] #Member ship print "Is python in mylist = ", 'python' in data print "Is Java in mylist = ", 'Java' in data if 'Python' in data: print "Available in the list" else: print "Not present in the list" print "-- Enumerate through a list ---" for indx, item in enumerate(data): print "Index = {}, Value = {}".format(indx, item) print "-- Iterations through a list ---" for item in data: print "Item = ", item print "-- Index of an element ---" print "Index of C++ = ", data.index('c++') print "-- Adding elements to the list = etxend, append, insert" data.extend(['Python', 'Ruby']) print " Extending the list data = ", data data.append('Java') print " Appending to the list data = ", data print " Adding a tuple to the list data " data.append(('R', 'Go')) # data = ['c', 'c++', 'Java', 100, 200, 'Python', 'Ruby', 'Java', ('R', 'Go')] print " data = ", data # See the output the whole tuple is added as one element to the list print " data = ", data data.insert(0, 'Java') print " data = ", data print " Updating at a specific index " print " data[0] = ", data[0] data[0] = 'javaScript' print " After updating data [0] = ", data[0]
# Brute force solution import time import math start = time.time() def largest_prime_factor(num): highest_prime = 2 for i in range(2, num + 1): while num % i == 0: # print(num, 'num') highest_prime = i num /= i # print(num, 'num') return highest_prime print(largest_prime_factor(144544)) print(" %s seconds " % (time.time() - start)) # Takes 0.0107049942017 seconds # 2 # import time # import math start = time.time() def largest_prime_factor(num): div = 2 while div <= math.floor(math.sqrt(num)): if div > num: return int(num) if num % div == 0: num /= div else: div += 1 return int(num) print(largest_prime_factor(144544)) print(" %s seconds " % (time.time() - start)) # Takes 2.19345092773e-05 seconds
# sorted.py # More on the sorted function # Sort the words from a sentence sentence = "I like turtles, especially purple ones" # Notice words aren't sorted correctly! print(sorted(sentence.split())) # Now they are # Note the key= at the end print(sorted(sentence.split(), key=str.upper))
# demo of creating a list of grades # getting lowest and highest scores from it # create list to hold grades grades = [] # add 5 grades to the list for i in range(5): # get input as string grade = input("Grade? ") # append to list and force to float grades.append(float(grade)) # sort the grades grades.sort() # get lowest one print(grades[0]) # get highest one print(grades[-1])
theSentence = 'Bruce prefers teaching in a classroom rather than online' # break apart the words in the sentence into a list using .split() theSentence = theSentence.split() print('Here are the words in the sentence:',theSentence) # example data in the form of a string where each name is separated by a comma someData = "Bruce,Gayle,Tucker,Bella" # use split to break apart the data using the comma as a delimiter someData = someData.split(',') print('Here is the data:',someData)
''' Author: M. Canesche Date: 01/12/18 About: Speech Recognition for text just in english. ''' # libraries import speech_recognition as sr def main(): r = sr.Recognizer() # initialize recognizer with sr.Microphone(device_index=0) as src: print("Speak Anything: ") audio = r.listen(src) # listen to the source try: text = r.recognize_google(audio) print("You said: {}".format(text)) except: print("Sorry could`nt reconize your voice! Please speak in english.") if __name__ == "__main__" : main()
#GC26 import random import string def randomString(stringLength): letters = string.ascii_letters return ''.join(random.choice(letters) for x in range(stringLength)) newword = randomString(8) print("Please type in",newword) typeword = input(":") if newword == typeword: print("Success") else: print("Failed")
# -*- coding:utf-8 -*- import random # 元组推导式 快速生成一个元组 # 与列表推导式不同 元组推导式生成的结果是一个生成器对象 需要强制转换(tuple()和list())来生成元组或列表 # 生成器对象在执行tuple()或者list()函数后就会被清空 random_number = (random.randint(10, 20) for x in range(10)) print("生成的生成器对象为:", random_number) random_number1 = (random.randint(10, 20) for i in range(10)) # 强制转型 tuple1 = tuple(random_number) list1 = list(random_number1) print(tuple1, " ", "类型为:", type(tuple1)) print(list1, " ", "类型为:", type(list1)) # 利用_next()_方法遍历生成器对象 number1 = (random.randint(10, 20) for i in range(10)) print(number1.__next__())
# -*- coding:utf-8 -*- from Shape import Shape class Square(Shape): def __init__(self, side): Shape.__init__(self, side, side) self.side = side def area(self): print("矩形的面积为:", self.side**2) def girth(self): print("矩形的周长为:", self.side*4)
# -*- coding: utf-8 -*- # 序列的定义和下标的读取 list = ["哇哈哈哈哈哈","ohohohohh00","nnnnnnnnnnnnnnnnn"] # python中允许下标为副,下标-1为数组最后一个元素 print(list[2]) print(list[-1]) # 序列的切片操作 # sname(start:end:step)i # sname : 名字 start: 切片操作开始的位置 end:切片操作结束的位置 print("将数组切片输出的结果是:") print(list[1:2]) # 序列相加,生成新的序列 list1 = ["我日"] list2 = list + list1 print(list2) # 使用乘法 print(list1*2) # 检查某元素是否在序列内,使用in关键字 print("我日"in list2) # 输出序列的长度,最大值,最小值 print("序列list的长度为", len(list)) num = [1, 2, 3, 4, 5, 6, 7, 9, 5, 8] print("序列num的最大值为", max(num)) print("序列num的最小值为", min(num))
import os list1=[] list2=[] for (a,b,c) in os.walk('D:\\'): if c!=[]: list1.append(c) if b!=[]: list2.append(b) print(list1) print(list2)
#board = [[3, 0, 6, 5, 0, 8, 4, 0, 0], # [5, 2, 0, 0, 0, 0, 0, 0, 0], # [0, 8, 7, 0, 0, 0, 0, 3, 1], # [0, 0, 3, 0, 1, 0, 0, 8, 0], # [9, 0, 0, 8, 6, 3, 0, 0, 5], # [0, 5, 0, 0, 9, 0, 6, 0, 0], # [1, 3, 0, 0, 0, 0, 2, 5, 0], # [0, 0, 0, 0, 0, 0, 0, 7, 4], # [0, 0, 5, 2, 0, 6, 3, 0, 0]] # Método que resuelve el sudoku: def sudoku_solver(matrix): if not initial_valid(matrix): return False find = find_empty_place(matrix) if not find: # Caso base cuando no hay casillas vacías. return True else: # Caso en que si se encontró una casilla vacía. row, col = find for num in range(1, 10): # Verificar si es valido colocar el número si # es asi lo coloca, asumimos que es el correcto. if valid(matrix, row, col, num): matrix[row][col] = num # Llamada recursiva para la siguiente # casilla vacía. if sudoku_solver(matrix): return True # Colocamos como vacía la casilla pues no # se llegó a la respuesta buscada. matrix[row][col] = 0 return False # Método que revisa si es posible resolver el sudoku o no: def initial_valid(matrix): for row in range(0, 8): for col in range(0, 8): if matrix[row][col] != 0: if not is_valid_2(matrix, row, col, matrix[row][col]): return False return True # Verificar si "num" ya esta presente en otra columna # de manera inicial: def verify_column_init(matrix, column, num): cont = 0 for row in range(0, 8): if matrix[row][column] == num: cont = cont + 1 if cont > 1: return True return False # Verificar si "num" ya esta presente en otra fila # de manera inicial: def verify_row_init(matrix, row, num): cont = 0 for column in range(0, 8): if matrix[row][column] == num: cont = cont + 1 if cont > 1: return True return False # Verificar si "num" ya esta presente en otra de # las cuadrículas 3x3, de manera inicial def verify_3_x_3_box_init(matrix, start_row, start_col, num): cont = 0 for row in range(0, 3): for column in range(0, 3): if matrix[row + start_row][column + start_col] == num: cont = cont + 1 if cont > 1: return True return False # Llamamos a los métodos que verifican existe algún # número que cause conflicto: def is_valid_2(matrix, row, col, num): valid_pro1 = not verify_column_init(matrix, col, num) valid_pro2 = not verify_row_init(matrix, row, num) valid_pro3 = not verify_3_x_3_box_init(matrix, row - row % 3, col - col % 3, num) valid_pro = valid_pro1 + valid_pro2 + valid_pro3 return valid_pro # Encuentra una casilla "vacia" y actualiza row # y column: def find_empty_place(matrix): for i in range(len(matrix)): for j in range(len(matrix[0])): if matrix[i][j] == 0: return i, j # row, col return None # Verificar si "num" ya esta presente en una columna: def verify_column(matrix, column, num): for row in range(0, 8): if matrix[row][column] == num: return True return False # Verificar si "num" ya esta presente en una fila: def verify_row(matrix, row, num): for column in range(0, 8): if matrix[row][column] == num: return True return False # Verificar si "num" ya esta presente en una de # las cuadrículas 3x3 def verify_3_x_3_box(matrix, start_row, start_col, num): for row in range(0, 3): for column in range(0, 3): if matrix[row + start_row][column + start_col] == num: return True return False # Llamamos a los métodos que verifican si colocar # un número es valido o no def valid(matrix, row, col, num): valid_pro = not verify_column(matrix, col, num) and not verify_row(matrix, row, num) and \ not verify_3_x_3_box(matrix, row - row % 3, col - col % 3, num) return valid_pro # Imprimimos el sudoku en pantallla def print_board(matrix): for i in range(len(matrix)): if i % 3 == 0 and i != 0: print("- - - - - - - - - - - - - - - - -") for j in range(len(matrix[0])): if j % 3 == 0 and j != 0: print(" | ", end="") if j == 8: print("[" + str(matrix[i][j]) + "]") else: print("[" + str(matrix[i][j]) + "]", end="") #print_board(board) #sudoku_solver(board) #print("_________________________") #print_board(board)
from menu import Menu, MenuItem from coffee_maker import CoffeeMaker from money_machine import MoneyMachine menu = Menu() coffee_machine = CoffeeMaker() register = MoneyMachine() machine_is_on = True # put everything in a while loop while machine_is_on: # Get user's choice choice = input(f"What would you like? {menu.get_items()[:-1]}: ").lower() if choice == 'off': # exit machine_is_on = False elif choice == 'report': coffee_machine.report() register.report() else: # check if item exists drink = menu.find_drink(choice) # if drink is valid # check if resources are available for this item if coffee_machine.is_resource_sufficient(drink) and register.make_payment(drink.cost): coffee_machine.make_coffee(drink)
# 리스트list odd=[1,2,3,4,5,6] print(type(odd)) odd1=[1,3,"문자",[3,4,5]] print(odd1[3][0]) #리스트 인덱싱, 슬라이싱 # a= [1,2,3] #list의 a의 첫번쨰 값 #a[0] #b = a[0] + a[2] #print(b) #print(a[-2]) a = "HEELO" print(a[0:3]) a= [1,2,3,4,[1,2,3]] print(a[-1][1:]) #리스트 연산(더하기, 곱하기, 길이구하기) b=[1,2,12,13,14,15] print(a+b) print(b*3) b1 = b * 3 #print(len(b1)) #리스트 수정, 삭제 k= [1,2,3] k[1]=5 print(k) del k[2] print(k) #List 추가 add1=3,4,5 k.append(add1) print(k) c= [5,3,18,20,1] c.reverse() print(c) #리스트 안에 20이 위치하는 값 print(c.index(20)) #두번째자리에 4를 넣는다 c.insert(2,4) c.append(2) print(c) #첫번째 값 지우기 c.remove(3) print(c) c.pop() print(c) c.pop(2) print(c) d=[1,2,3,3,3,3,2,5] print(d.count(3)) d.extend(["사과","바나나"]) print(d) # extend사용시, 대괄호 잊지 말것 #tuple a=(1,2,3) b=3,4,5 print(type(a),type(b)) #tuple의 값을 하나만 수정, 빼고, extend #하지만 tuple끼리 더하고 빼고 연산은 가능 c=a+b print(c) print(c*4) print(len(c)) #Dictionary #사과와 바나나는 키 1000,5000은 밸류값 과일 = {"사과" : 1000, "바나나" : 5000} print(과일) person = {"name" : "김말이", "age" : 4} person["birth"] = 123193 print(person) del person["age"] print(person) grade = {"pey":10, "juliet": 99,"pey":20} print(grade['pey']) # 중복된 값을 입력하면 앞의 값이 무시됨 #리스트 넣으면 오류남 person = {"name":"김말이","age":4} print(person.keys()) print(person.values()) print(person.items()) print(person.get("name")) #"age"값이 person안에 있는지 없는지 확인하는 법 print("dog"in person) person.clear() print(person) print(person)
import pandas as pd import numpy as np df1 = pd.DataFrame(np.random.randint(0,10, (4,2)), index = ["A", "B", "C", "D"], columns=["a", "b"]) print(df1) print() df2 = pd.DataFrame({"a":[1,2,3,4], "b":[5,6,7,8]}, index = ["A", "B", "C", "D"]) print(df2) arr = np.array([("item1", 1), ("item2", 2), ("item3", 3), ("item3", 4)], dtype=[("name", "10S"), ("count", int)]) df3 = pd.DataFrame(arr) print(df3)
# coding=utf-8 # author:MagiRui import matplotlib.pyplot as plt import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(10,4),index=pd.date_range('2018/12/18', periods=10), columns=list('ABCD')) # 数据 索引 列 print(df) ds = df.plot() # 折线图 plt.show()