text
stringlengths
37
1.41M
#!C:\Python34 # Bubble sort def sorted(x): for i in range(len(x)-1): for j in range (i+1, len(x)): print (x[i] , x[j]) if (x[i] > x[j]): temp = x[i] x[i] = x[j] x[j] = temp def main(): x= eval(input("enter list")) sorted(x) print (x) if __name__=="__main__": main()
#!C:\Python34 def dictionary_of_char(sentence, cwd= "str"): if (cwd= "paragra result ={} for ch in sentence: if result.get(ch) != None: result[ch] +=1 else: result[ch] =1 return result def main(): sentence = input("Enter your sentence") result = dictionary_of_char(sentence) print(result) #for ch in result: #print(result) if __name__=="__main__": main()
def highestSum(arr, k): highest_sum = float('-inf') n = len(arr) # n must not be smaller than k if n < k: return -1 # subarray starts at i for i in range(n - k + 1): # calculate sum of the subarray current_sum = 0 for j in range(k): print("Value fo i and j are :", i, j, "#####") current_sum += arr[i + j] # compare the sum highest_sum = max(highest_sum, current_sum) return highest_sum arr= [1,5,2,3,6,3,8,2] print (highestSum(arr,3))
def add(a,b,c=0,d=0,e=0): return a+b+c+d+e print(add(10,20)) print(add(10,20,30)) print(add(10,20,30,40)) print(add(10,20,30,40,50))
#!C:\Python34 class stack: def __init__(self, size): print ("Stack constractured of size", size) self.stack = [] self.__size =size #print self.stack def push(self,data): status ="Failed" if not self.isFull(): self.stack.append(data) print (data, "Pushed to stack") status = "Passsed" return status def pop(self): status ="Failed" data = -1 if not self.isEmpty(): self.stack.pop() print ("Data is poped from stack") status = "Passsed" return data, status def isFull(self): return len(self.stack) == self.__size def isEmpty(self): return (self.stack == []) def stacksize(self): print (len(self.stack)) def printintersting(self): try: print ("Inersting" , self.intserting) except: print (" not inerting") def __del__(self): print ("Stack distructor") del self.stack def main(): st =stack(10) print (st._stack__size) '''' st =stack(10) st.push(1) st.push(2) print (st.__dict__) st.intserting =True st.printintersting() st1= stack(10) st1.push(3) print (st1._stack__size) print (st._stack__size) print (st.__dict__) print (stack.__dict__) st1.printintersting() st.stacksize() st.pop() st.stacksize() ''' if __name__=="__main__": main()
#!C:\Python34 a= int(input("Enter the first integer")) b= int(input("Enter the Second integer")) print (a + b) print (a - b) print (a * b ) print (a // b) print (a ** b)
#!C:\Python34 def reverselist(x): if len(x)== 0: return x # for list [] , for string "" reverselist (x[1:]) print (x[0],end=" ") #y= (x[0]) #return y # return x.appendx[0] def main(): x= eval(input("Enter elements of the list")) print ("Original List is", x) reverselist(x) if __name__=="__main__": main()
#!C:\Python34 def balance_check(s): #print(s) if len(s) %2 != 0: return False opening = set('([{') matches = set([( '(', ')' ), ( '[' , ']' ), ( '{', '}')]) # List of tuples of all pairs # implementing list as stack . Usebuilt in funstions of list stack =[] for param in s: #scaning string from left t right if param in opening: # If we see any opening parenthesis we put that in stack stack.append(param) print("After append",stack) else: if len(stack) == 0: # return False last_open = stack.pop() print("Last open", last_open) print ("After poping out", stack) #Check if there is closing match print ("#####3",last_open, param) if (last_open, param) not in matches: return False return len(stack) == 0 #print(balance_check('[]')) print(balance_check('[]({}}'))
def patt(n,c): i=str(c)+"\t" j="\t" for x in range(n,0,-1): print(str(j*(n-x))+str(i*x)) ''' for i in range(n,0,-1): for _ in range(n-i): print("\t",end="") for _ in range(i): print("*\t",end="") print() ''' def main(): x=eval(input("Enter number of rows")) y=input("Enter charater\t") patt(x+1,y) if __name__=="__main__": main()
#!C:\Python34 def reversecontainer(x): if len(x)== 0: #print ("Inside string length zero") if type(x) == str: # print ("When type is string") return x return list() y=reversecontainer(x[1:]) if type(x) == str: #print ("Build recursion") return y+ x[0] y.append(x[0]) return y def main(): x= [1,2,3,4,5] print ("before recursion", x) print (reversecontainer(x)) x="India" print(reversecontainer(x)) if __name__=="__main__": main()
def variableargs(a,b,c,*d,**e): print(a) print(b) print(c) print(d) print(e) if __name__=='__main__': a,b,c=eval(input("Enter three numbers")) d=input("Enter a number or string") e='"name":"siddharth"'#not working, it is creates dictionary inside a dictionary variableargs(a,b+1,c,a,d,b,d=c,n=e)# d=c is also considered in **e dictionary print("2nd try") variableargs(a,b+1,c,d=c,n=e)# tuple is empty print("3rd try") variableargs(a,b+1,c<<1,d,e)# key value cant be expression error
def highestSum(arr, k): highest_sum = float('-inf') n = len(arr) # n must not be smaller than k if n < k: return -1 # Compute sum of first window of size k window_sum = sum([arr[i] for i in range(k)]) # Compute sums of remaining windows by # removing first element of previous # window and adding last element of # current window. print(window_sum) for i in range(n - k): print("Elements involved are ", arr[i] , arr[i + k], "And value of i ", i) window_sum = window_sum - arr[i] + arr[i + k] print ("Latest calculated sum is ", window_sum) highest_sum = max(highest_sum, window_sum) return highest_sum arr= [1,5,2,3,6,3,8,2] print (highestSum(arr,3))
def digit(n): s=0 while(n!=0): s=s*10+n%10 n=int(n/10) return s def main(): n=eval(input("Enter Digit\t")) print(digit(n)) if __name__=='__main__': main()
#s: string , k is steps class solution: def sumofdigit(self, s:str, k:int)->int: num = "" for x in s: #print (ord("a")) num += str(ord(x) - ord("a") +1 ) for _ in range(k): s = 0 for x in num: s+=int(x) num =str(s) return int(num) s= solution() print(s.sumofdigit("leeth" ,1))
#!C:\Python34 import math def prime(no): mat.sqrt(no) def getPrimes(inputlist): for number in inputlist: if ISPrime(number): yield number def main(): x =GetPrimes(range(1,10)) print (type(x)) print (next(x))
#!C:\Python34 def patterndouble(n): for i in range (1, n+1): k = i for _ in range (1, i+2): print(k, end=' ') k *=2 print ( " " , end= "\n") def main(): no= eval(input ("enter the number")) print (patterndouble(no)) if __name__=="__main__": main() ''' Pattern output 1 2 2 4 8 3 6 12 24 4 8 16 32 64 '''
def third(x,y): z=[] i,j=0,0 while True: if i == len(x): z.extend(y[j:]) break elif j == len(y): z.extend(x[i:]) break elif x[i] < y[j]: z.append(x[i]) i+=1 elif x[i] > y[j]: z.append(y[j]) j+=1 return z def main(): print("Enter 1st list Elements") x=[int(a) for a in input().split()] print("Enter 2nd list Elements") y=[int(a) for a in input().split()] x.sort() y.sort() print(third(x,y)) if __name__=='__main__': main()
#!C:\Python34 st = str(input("Enter string : ")) print ("After replacing occurrences in string : ", st[0]+st[1:].replace(st[0],"*"))
#!C:\Python34 def pattern1(num): n = 0 for i in range(1, num +1): for _ in range(1, num-i+1 ): print (" ", end = "" ) # loop to print star while n != (2 * i - 1): print("*", end = "") n = n + 1 n=0 print ("" , end= "\n") n = 0 num= num-1 for i in range (1, num +1): for _ in range(1, i+1): print (" " , end= "") while n !=(2 * num -i*2 +1): print ("*", end ="") n = n + 1 n=0 print ("", end="\n") def main(): num= eval(input ("Enter your number of raws you want to print" )) pattern1(num) if __name__=="__main__": main() ''' Output C:\>python C:\1.Class\Class_Program_Excercises\Class8_Excercise\Pattern4_diamond.py Enter your number of raws you want to print3 * *** ***** '''
import re import os def RemoveComments(x): #multiLine = re.compile("'''.*?'''") #singleLine = re.compile("#.*.") commentsRE = re.compile(r"(#.*.)|('''.*?''')") f=open(x,"r") Data = f.read() Data = re.sub(commentsRE,"",Data) f.close() x+='_comments_removed.txt' f=open(x,'w') f.write(Data) f.close() print("Done\nCheck File:",x) def main(): x=input("Enter File Name:\t") Exists=os.path.isfile(x) if Exists: RemoveComments(x) else: print("File does not exist") if __name__=="__main__": main()
#!C:\Python34 def divisibleby8(no): return (no & 7) == 0 def main(): no= eval(input ("enter the number")) print (divisibleby8(no)) if __name__=="__main__": main()
#!C:\Python34 import functools def Multiply(x,y): print (x,y) return x*y print(functools.reduce(Multiply, range(1,10)))
''' Given the head of a singly linked list, return true if it is a palindrome. Example 1: Input: head = [1,2,2,1] Output: true Example 2: Input: head = [1,2] Output: false ''' def isPalindrome(self, head: ListNode) -> bool: vals = [] current_node = head while current_node is not None: vals.append(current_node.val) current_node = current_node.next return vals == vals[::-1] ''' Approach 1: Copy into Array List and then Use Two Pointer Technique Intuition If you're not too familiar with Linked Lists yet, here's a quick recap on Lists. There are two commonly used List implementations, the Array List and the Linked List. If we have some values we want to store in a list, how would each List implementation hold them? An Array List uses an underlying Array to store the values. We can access the value at any position in the list in O(1)O(1)O(1) time, as long as we know the index. This is based on the underlying memory addressing. A Linked List uses Objects commonly called Nodes. Each Node holds a value and a next pointer to the next node. Accessing a node at a particular index would take O(n)O(n)O(n) time because we have to go down the list using the next pointers. Determining whether or not an Array List is a palindrome is straightforward. We can simply use the two-pointer technique to compare indexes at either end, moving in towards the middle. One pointer starts at the start and goes up, and the other starts at the end and goes down. This would take O(n)O(n)O(n) because each index access is O(1)O(1)O(1) and there are nnn index accesses in total. However, it's not so straightforward for a Linked List. Accessing the values in any order other than forward, sequentially, is not O(1)O(1)O(1). Unfortunately, this includes (iteratively) accessing the values in reverse. We will need a completely different approach. On the plus side, making a copy of the Linked List values into an Array List is O(n)O(n)O(n). Therefore, the simplest solution is to copy the values of the Linked List into an Array List (or Vector, or plain Array). Then, we can solve the problem using the two-pointer technique. Algorithm We can split this approach into 2 steps: Copying the Linked List into an Array. Checking whether or not the Array is a palindrome. To do the first step, we need to iterate through the Linked List, adding each value to an Array. We do this by using a variable currentNode to point at the current Node we're looking at, and at each iteration adding currentNode.val to the array and updating currentNode to point to currentNode.next. We should stop looping once currentNode points to a null node. The best way of doing the second step depends on the programming language you're using. In Python, it's straightforward to make a reversed copy of a list and also straightforward to compare two lists. In other languages, this is not so straightforward and so it's probably best to use the two-pointer technique to check for a palindrome. In the two-pointer technique, we put a pointer at the start and a pointer at the end, and at each step check the values are equal and then move the pointers inwards until they meet at the center. When writing your own solution, remember that we need to compare values in the nodes, not the nodes themselves. node_1.val == node_2.val is the correct way of comparing the nodes. node_1 == node_2 will not work the way you expect. '''
"""Пользователь вводит целое положительное число. Найдите самую большую цифру в числе. Для решения используйте цикл while и арифметические операции.""" user_input = int(input("Введите целое положительное число: ")) a = user_input max_number = a%10 a = a//10 while a > 0: if a%10 > max_number: max_number = a%10 a = a//10 print("Самая большая цифра в числе: ",max_number)
import random import pyperclip symbol = 0 lower = 0 upper = 0 number = 0 count = 0 password = [] length = input("Hey, Welcome. Just say me how many characters do you want in your password? (default 128)\n") length = 128 if length == '' else int(length) while count < length: rand = random.randint(0, 3) if rand == 0: lower += 1 b = int(random.randint(97, 123)) password.append(b) elif rand == 1: upper += 1 b = random.randint(65, 91) password.append(b) elif rand == 2: number += 1 b = random.randint(48, 58) password.append(b) elif rand == 3: r = random.randint(0, 2) symbol += 1 if r == 0: b = random.randint(33, 48) password.append(b) elif r == 1: b = random.randint(91, 97) password.append(b) elif r == 2: b = random.randint(123, 126) password.append(b) count += 1 word = "".join([chr(c) for c in password]) pyperclip.copy(word) print("Random password of length %s is: \n" % length) print("Password: " + word) input('Password copied to clipboard, push a button to exit...')
#!/usr/bin/env python import sys import csv # input comes from STDIN data = sys.stdin.readlines() # parse the input we got from csv reader = csv.reader(data) # remove header header = next(reader) if header != None: for line in reader: # write result to STDOUT print '%s\t%s' % (line[9].capitalize(), 1)
n=int(input("Enter a number:")) if n>0: print("The number is +ve") else: print("The number is -ve")
# coding= utf-8 class Foo(object): def __init__(self, name): self.name = name def __setattr__(self, key, value): print("call __setattr__") # self.key = value # 这一句会造成无穷递归,因为这一句等效:self.name = name # 正是self.name = name 触发了__setattr__(self,key,value)的执行 self.__dict__[key] = value # setattr(self, key, value) 也是造成无穷递归,等效self.key = value def __delattr__(self, item): # del f1.age会触发__delattr__执行, item是字符串 print("call __delattr__") self.__dict__.pop(item) def __getattr__(self, item): print("call __getattr__") # 当找不到属性,会触发 # 当属性存在__dict__时,不会触发 value = 5 setattr(self, item, value) return value # 测试getattr # f = Foo('egon') # print('before %s'% f.__dict__) # print(f.data) # print('after %s'% f.__dict__) # print(f.data) # 此时调用的不是__getattr__,而是直接从dict获取 #测试setattr f = Foo('egon') # 初始化有一个self.name = name就会调用__setattr__ print('before %s'% f.__dict__) f.name = 'lzp' # 会调用__setattr__ print('after %s'% f.__dict__) print(f.data) # 从f.__dict__查找属性,而且从父类也找不到;触发__getattr__
# -*- coding: utf-8 -*- class Fib(object): def __init__(self): print('__init__') self.a, self.b = 0, 1 # 初始化两个计数器a,b def __iter__(self): print('exec __iter__') return self # 实例本身就是迭代对象,故返回自己 def __next__(self): print('exec next') self.a, self.b = self.b, self.a + self.b # 计算下一个值 if self.a > 10: # 退出循环的条件 raise StopIteration() return self.a # 返回下一个值 f = Fib() for i in f: print(i) # 输出结果如下: # __init__ # exec __iter__ # exec next # 1 # exec next # 1 # exec next # 2 # exec next # 3 # exec next # 5 # exec next # 8 # exec next
# -*- coding: utf-8 -*- import threading import time # mutexA = threading.Lock() # Lock是一个类 # mutexB = threading.Lock() recur_lock = threading.RLock() class MyThread(threading.Thread): def __init__(self): # threading.Thread.__init__(self) super().__init__() # 这里不要self参数,只要除去self外的参数 def run(self): # 当调用实例化对象的start()函数时,会调用run函数 self.fun1() self.fun2() def fun1(self): recur_lock.acquire() print("I am {name}, get res:{res}->{time}".format(name=self.name, res="ResA", time=time.ctime())) recur_lock.acquire() print("I am {name}, get res:{res}->{time}".format(name=self.name, res="ResB", time=time.ctime())) recur_lock.release() recur_lock.release() def fun2(self): recur_lock.acquire() print("I am {name}, get res:{res}->{time}".format(name=self.name, res="ResB", time=time.ctime())) time.sleep(0.1) # 加上这一行,会产生死锁 recur_lock.acquire() print("I am {name}, get res:{res}->{time}".format(name=self.name, res="ResA", time=time.ctime())) recur_lock.release() recur_lock.release() if __name__ == "__main__": for _ in range(10): t = MyThread() t.start() # 递归锁threading.RLock(),每当acquire()一次,计数器+1,每当release一次,计数器-1 # 当一个线程获取到递归锁后,其他线程是无法再获取递归锁(这和普通锁是一样的) # 但是递归锁可以被同一个线程多次acquire()(这是和普通锁不一样的地方) # 只有当计数器为0的时候,其他线程才能acquire这把锁
# -*- coding: utf-8 -*- # 有两种情况: # 一种情况: =后面跟的另外一段内存地址的话,不会更改 # 另外一种情况:在原来内存地址直接修改append, 会更改 test_list = [1, 2, 3] # 全局空间的test_list def change(t): # t也是内置空间的名字t t.append(4) print "before change test_list= %s" % test_list # 全局空间的test_list change(test_list) # t = test_list, t和test_list都是对同一内存地址的引用 # t = [1,6] 更改t为对另外一个内存的引用 print "after change test_list= %s" % test_list # 全局空间的test_list # before change test_list= [1, 2, 3] # after change test_list= [1, 2, 3, 4]
# -*- coding: utf-8 -*- import datetime now = datetime.datetime.now() last = datetime.datetime(year=2016, month=9, day=3, hour=12) delta = now - last print(delta) # 366 days, 0:07:38.303065 # delta表示一段时间,有days,时,分,秒,微秒属性 # 也可以将其初始化 import datetime now = datetime.datetime.now() print(now) delta = datetime.timedelta(days=1, seconds=10, milliseconds=100, hours=2,) future = now + delta print(future) # future表示1天2小时10.1秒后
# -*- coding: utf-8 -*- # 继承的好处: # 继承可以把父类的所有功能都直接拿过来,这样就不必重零做起, # 子类只需要新增自己特有的方法,也可以把父类不适合的方法覆盖重写; class Animal(object): def __init__(self, name, age): self.name = name self.age = age def walk(self): print('%s is walking' % self.name) def say(self): print('%s is saying' % self.name) class People(Animal): pass class Pig(Animal): pass class Dog(Animal): pass p1 = People('obama', 50) print(p1.name) print(p1.age) p1.walk() # 继承的作用: 代码的重用性(复用性) # 派生:在子类定义新的属性: 1 父类没有;2:和父类同名的属性
# -*- coding: utf-8 -*- test_list = [1,2,3] # 全局空间的test_list def change(): # 这样相当于在内部定义了名字(内置空间的test_list) test_list = [1,6] print "before change test_list= %s" % test_list #全局空间的test_list change() print "after change test_list= %s" % test_list #全局空间的test_list # before change test_list= [1, 2, 3] # after change test_list= [1, 2, 3] # 如果不是作为参数传递,test_list不会改变 # 如果作为参数传递,有哪些变化呢?
import time def A(): print("第一次由B调到A") while True: print('------A-----') time.sleep(0.1) yield print("由B返回A") def B(a): for i in range(3): print("此时B i = %d" % i) time.sleep(0.1) next(a) # 生成器一遇到next就会执行a函数的代码,A函数在yield处保存,从A函数并返回到此次 # 从A函数返回B,接着往下执行 # 在B函数循环里面再次遇到next(a),又从B调到A上次保存的地方,接着执行 print('由A返回B') a = A() B(a) # 结果应该是: # ------B----- # # yield的缺点:不能监听到什么时候出现IO操作 # greenlet,可以检测到io操作(sleep),执行.switch会切换线程(需要手工切换)
# -*- coding: utf-8 -*- #strftime是将struct time转化成字符串time(人能读时间) import time time_format = '%x' # 小写的x表示年月日date日期 local_tuple = time.localtime() print(time.strftime(time_format, local_tuple)) time_format = '%X' # 大写的X表示时分秒time local_tuple = time.localtime() print(time.strftime(time_format, local_tuple)) time_format = '%Y' #大写的Y表示年,包含世纪(1989),小写的y不包含世纪(89) time_format = '%m' #小写的m表示月(01-12),大写的M表示分00-59 time_format = "%d" # 小写d 表示日(01-31) time_format = "%H" #大写的H表示时(00-23) time_format = "%S" #大写S表示秒 time_format = "%Y-%m-%d %H:%M:%S" time_tuple = time.localtime() time_str = time.strftime(time_format, time_tuple) print(time_str)
#!/usr/bin/python # The Mayan Long Count[2] calendar is a counting of days with these units: "* # The Maya name for a day was k'in. Twenty of these k'ins are known as a winal # or uinal. Eighteen winals make one tun. Twenty tuns are known as a k'atun. # Twenty k'atuns make a b'ak'tun.*". Essentially, we have this pattern: # 1 kin = 1 day # 1 uinal = 20 kin # 1 tun = 18 uinal # 1 katun = 20 tun # 1 baktun = 20 katun # The long count date format follows the number of each type, from longest-to-shortest time # measurement, separated by dots. As an example, '12.17.16.7.5' means 12 baktun # , 17 katun, 16 tun, 7 uinal, and 5 kin. This is also the date that # corresponds to January 1st, 1970. Another example would be December 21st, 2012 # : '13.0.0.0.0'. This date is completely valid, though shown here as an # example of a "roll-over" date. # Write a function that accepts a year, month, and day and returns the Mayan # Long Count corresponding to that date. You must remember to take into account # leap-year logic, but only have to convert dates after the 1st of January, 1970 # . # Author: skeeto # import datetime utc = datetime.date(1970,1,1) kin = 1 uinal = 20 * kin tun = 18 * uinal katun = 20 * tun baktun = 20 * katun days_utc = 12 * baktun + 17 *katun + 16*tun + 7*uinal + 5* kin def convert_to_myan(date): delta = date - utc days = delta.days + days_utc mayan_long_count = [] for m in [baktun,katun,tun,uinal,kin]: (l,days) = divmod(days,m) mayan_long_count.append(str(l)) return ".".join(mayan_long_count) def mayan_to_date(mayan): mayan_long_count = mayan.split(".") days = 0 for (m,b) in zip(mayan_long_count,[baktun,katun,tun,uinal,kin]): days += (int(m) * b) days -= days_utc return str(datetime.timedelta(days=days) + utc) def main(): num_dates = int(raw_input()) dates = [] for d in range(num_dates): inp = raw_input().split() (day,month,year) = (int(x) for x in inp) dates.append(datetime.date(year,month,day)) for date in dates: print convert_to_myan(date) print mayan_to_date("14.0.0.0.0") if __name__ == "__main__": main()
''' File: Assignment1_Task1.py Author: Steven Phung Class: CS 2520.01 - Python for Programmers Assignment: Assignment #1_Task #1 Purpose: Practicing if statements. BMI can be calculated using Imperial (American) or Metric (English) system. Note that we'd like the user to choose whether to use Imperial or Metric system. A BMI scale can be used to determine an individual's fitness status. Normally the scale is related to age, sex, etc. For simplicity, we will use 18-25 as normal range, higher than that will be considered as overweight and lower than that will be considered as underweight. Please provide the user some feedback based on the calculated BMI. BMI Formula Imperial: BMI = 703 * (weight (lb) / height^2 (in^2)) Metric: BMI = (weight (kg) / height^2 (m^2)) ''' imperialOrMetricSystem = int(input("1. Imperial (lb)\n2. Metric (kg)\nChoose Option: ")) #Ask again until valid option is provided while not imperialOrMetricSystem == 1 and not imperialOrMetricSystem == 2 : print("Not a valid choice, please try again.") imperialOrMetricSystem = int(input("1. Imperial (lb)\n2. Metric (kg)\nChoose Option: ")) #Imperial formula if imperialOrMetricSystem == 1 : weight = float(input("Please enter your weight (lb): ")) #Weight must be between a small baby's weight (5lbs) #and the heaviest person ever recorded (1,400lbs) while not 5 <= weight <= 1400 : weight = float(input("Please enter a reasonable weight (lb): ")) height = float(input("Please enter your height (in): ")) #Height must be between a small baby's height (18in) #and tallest person ever recorded (107in) while not 18 <= height <= 108 : height = float(input("Please enter a reasonable height (in): ")) #BMI formula bmi = 703 * (weight / height**2) #Metric formula elif imperialOrMetricSystem == 2 : weight = float(input("Please enter your weight (kg): ")) #Weight must be between a small baby's weight (2.2kg) #and the heaviest person ever recorded (635kg) while not 2.2 <= weight <= 635 : weight = float(input("Please enter a reasonable weight (kg): ")) height = float(input("Please enter your height (m): ")) #Height must be between a small baby's height (0.457m) #and tallest person ever recorded (2.73m) while not 0.457 <= height <= 2.73 : height = float(input("Please enter a reasonable height (m): ")) #BMI formula bmi = (weight / height**2) #Print BMI result and range print("Your BMI is: " + str(round(bmi, 2))) if bmi >= 18 and bmi <= 25 : print("This is considered normal.") elif bmi < 18 : print("This is considered underweight.") elif bmi > 25 : print("This is considered overweight.") ''' Tests Underweight test 1. Imperial (lb) 2. Metric (kg) Choose Option: 1 Please enter your weight (lb): 82 Please enter your height (in): 60 Your BMI is: 16.01 This is considered underweight. Normal weight test Choose Option: 1. Imperial (lb) 2. Metric (kg) Choose Option: 2 Please enter your weight (kg): 69 Please enter your height (m): 1.76 Your BMI is: 22.28 This is considered normal. Overweight test Choose Option: 1. Imperial (lb) 2. Metric (kg) Choose Option: 1 Please enter your weight (lb): 236 Please enter your height (in): 67 Your BMI is: 36.96 This is considered overweight. Abnormal input #1 1. Imperial (lb) 2. Metric (kg) Choose Option: 1 Please enter your weight (lb): 0 Please enter a reasonable weight (lb): -1 Please enter a reasonable weight (lb): 100000000 Please enter a reasonable weight (lb): 99 Please enter your height (in): 0 Please enter a reasonable height (in): -1 Please enter a reasonable height (in): 222222222 Please enter a reasonable height (in): 60 Your BMI is: 19.33 This is considered normal. Abnormal input #2 1. Imperial (lb) 2. Metric (kg) Choose Option: 2 Please enter your weight (kg): 0 Please enter a reasonable weight (kg): -1 Please enter a reasonable weight (kg): 999999999 Please enter a reasonable weight (kg): 58 Please enter your height (m): 0 Please enter a reasonable height (m): -1 Please enter a reasonable height (m): 8888888888 Please enter a reasonable height (m): 1.645 Your BMI is: 21.43 This is considered normal. '''
# leetcode 491 class Solution(object): def findSubsequences(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] def dfs(nums, start, tmp): # 使用dict去重,常规append + pop TLE。 dic = {} if len(tmp) > 1: res.append(tmp[::]) for i in range(start, len(nums)): if dic.get(nums[i], 0): continue if not tmp or nums[i] >= tmp[-1]: dic[nums[i]] = 1 dfs(nums, i + 1, tmp + [nums[i]]) dfs(nums, 0, []) return res print(Solution().findSubsequences([4, 6, 7, 7]))
# leetcode 212 单词搜索 # 基本性质 # 1,根节点不包含字符,除根节点以外每个节点只包含一个字符。 # 2,从根节点到某一个节点,路径上经过的字符连接起来,为该节点对应的字符串。 # 3,每个节点的所有子节点包含的字符串不相同。 class Solution: def findWords(self, board, words): # build trie begin ### trie = {} for word in words: t = trie for w in word: # 有key=w 就返回其value or 添加key = w , value ={} t = t.setdefault(w, {}) t["end"] = 1 print(trie) # build trie end ### res = [] row = len(board) col = len(board[0]) def dfs(i, j, trie, s): # print(i, j, trie, s) c = board[i][j] if c not in trie: return trie = trie[c] if "end" in trie and trie["end"] != 0: res.append(s + c) trie["end"] -= 1 board[i][j] = "#" for x, y in [[-1, 0], [1, 0], [0, 1], [0, -1]]: tmp_i = x + i tmp_j = y + j if 0 <= tmp_i < row and 0 <= tmp_j < col and board[tmp_i][tmp_j] != "#": dfs(tmp_i, tmp_j, trie, s + c) board[i][j] = c for i in range(row): for j in range(col): dfs(i, j, trie, "") return res print(Solution().findWords([ ['o', 'a', 'a', 'n'], ['e', 't', 'a', 'e'], ['i', 'h', 'k', 'r'], ['i', 'f', 'l', 'v'] ], ["oath", 'aa', 'oatt', "pea", "eat", "rain"])) # leetcode 472 连接词 class Solution: def findAllConcatenatedWordsInADict(self, words): def is_res(w, trie): if len(w) == 0: return True t = trie for i, v in enumerate(w): t = t.get(v) if not t: return False elif t.get('end') and is_res(w[i + 1:], trie): return True return False words.sort(key = lambda x: len(x)) res = [] trie = {} for w in words: if len(w) == 0: continue if is_res(w, trie): res.append(w) else: t = trie for k in w: t = t.setdefault(k, {}) t['end'] = True return res print(Solution().findAllConcatenatedWordsInADict( ["cat", "cats", "catsdogcats", "dog", "dogcatsdog", "hippopotamuses", "rat", "ratcatdogcat"]))
import sys import pygame import random from sprite import * from pygame.sprite import Group def date_read(): fd_1 = open("data.txt","r") best_score = fd_1.read() fd_1.close() return best_score def update_screen(screen,swk,arrows,energy): # swk.update() swk.blitme(screen,energy) for arrow in arrows.sprites(): arrow.blitme() arrows.update() # print(len(arrows)) for arrow in arrows.copy(): if arrow.rect.left > 954: arrows.remove(arrow) # print(len(arrows)) # def update_screen(swk,fruit): # swk.blitme() # for fruit in fruit.sprites(): # fruit.draw_fruit() # def demo(): def add_dragon(screen,dragons): e1=Dragon(screen) dragons.add(e1) # print(len(dragons)) def add_fruit(screen,fruits): for i in range(random.randint(1,5)): f1=Fruit(screen) fruits.add(f1) def update_f1(screen,fruits): for fruit in fruits.sprites(): fruit.blitme() # print(fruit.rect.height) # print(len(fruits)) fruits.update() for fruit in fruits.copy(): if fruit.rect.right<0: fruits.remove(fruit) def update_e1(screen,dragons): for dragon in dragons.sprites(): dragon.blitme() dragons.update() for dragon in dragons.copy(): if dragon.rect.right<0: dragons.remove(dragon) # print(len(dragons)) # print("dingshangqul") def collide(swk,arrows,dragons,fruits,score,energy): pygame.sprite.groupcollide(arrows, dragons, True, True) sprite_list=pygame.sprite.spritecollide(swk,fruits,True) score+=len(sprite_list) if pygame.sprite.spritecollide(swk,dragons,True): print ('碰上了') swk.rect.centerx-=10 energy-=0.25 return energy,score # distroy.image.position=swk.rect.centerx,swk.rect.centery # if len(crushs)>0: # die=die+1 # def power(): def v(v0): v0-=0.6 def show_score(screen): pass def set_time_passed(screen,clock): # 控制画的帧,越大越快 # 得到上一次画图到现在的时间,ms time_pass=clock.tick() def draw_background(screen): pass def create_stones(screen): pass # def draw_stones(screen,stones): # # 绘制石头到屏幕,清理跑出去的石头 # while True: # t=random.randint(1,3) # sum = random.randint(1, 6) # # if len(stones) < sum: # new_stone = Stone(screen) # stones.add(new_stone) # for stone in stones.copy(): # stones.update() # if stone.rect.right <= 0: # stone.blitme() # time.sleep(t) def update_stones(stones): stones.update() for stone in stones: if stone.rect.right<=0: stones.remove(stone) print(len(stones)) def create_fruits(screen,fruits): # fruits.update() while True: t = random.randint(1, 6) sum=random.randint(1,5) if len(fruits)<sum: new_fruit=Fruit(screen) fruits.add(new_fruit) for fruit in fruits.copy(): fruits.update() if fruit.rect.right <= 0: fruit.blitme() time.sleep(t) def swk_and_stone_crush(swk,dragon): # 检测孙悟空是否撞到石头 pass # def swk_eat_fruit(swk,fruits): # if # 检测孙悟空是否吃到水果 pass def draw_swk(screen,swk): pass def game_over(score,screen,font): score_text = font.render("Score: " + str(score), 1, (0, 0, 0)) screen.blit(score_text, [10, 10]) # while True: # 绘制背景图 pass
""" Base class for the different user model classes """ from .abs_user import AbsUser class BaseUser(AbsUser): def __init__(self, username="", password="", role=None): # todo: raise exception if username, password and role is not set at object creation self._username = username self._password = password self._comments = [] # stores ids of the user's comments for quick reference self._role = role # todo: role has to be one of accepted types def __str__(self): return self._username def __repr__(self): return "{} - {} - {}".format(self._username, self._role.role, self._role.permissions) @property def username(self): """ This method returns the username of the user """ return self._username @username.setter def username(self, username): """ This method sets the username of the user """ # todo: validate username self._username = username @property def password(self): """ This method returns the password of the user """ return self._password @password.setter def password(self, password): """ This method sets the password of the user """ # todo: validate password self._password = password @property def role(self): """ This method returns the role of the user as a string """ return self._role.role @role.setter def role(self, role): """ This method sets the role of the user """ # todo: validate role self._role = role @property def permissions(self): """ This method returns the permissions of the user """ return self._role.permissions @property def comments(self): """ This method returns list containing ids of comments that belong to the user """ return self._comments @comments.setter def comments(self, comment_id): """ This method adds a comment id to the user's comments list """ # todo: validate id self._comments.append(comment_id)
import numpy as np friend=["Kevin","Allen","Jim","Jim","Zelle",'Bill'] re =friend.pop() print(friend) print(re) lucky_number=[4,8,3,1,0] friend.extend(lucky_number) print(friend) #insert Kelly friend.insert(1,'Kelly') print("insert Kelly",friend) #remove Kelly friend.remove('Kelly') print("#remove Kelly",friend) #remove the last element friend.pop() print("remove the last element:", friend) #get the index of certain element print("Index of Zelle is ",friend.index("Zelle")) #count the amount of certain elements of list print("Jim has show up",friend.count("Jim"),"times in the list") #sort the list print("Sort list in ascending: ",lucky_number.sort()) #reverse the list print("list has been reverse: ",lucky_number.reverse()) #copy list and become independent object friend2 = friend.copy() friend2.insert(1,"Tester") print("Copy and modify list ",friend2) print("original list: ",friend) #clear List friend.clear() print("List has been clear ",friend) #2D list number = [[1,2,3],[4,5,6],[7,8,9]] for x in number: for y in x: print("number ",y) #3D list n=3 #distance= [[[0 for k in range(n)] for j in range(n)] for i in range(n)] distance=[[[0, 1, 2], [3, 0, 0], [6, 0, 0]], [[9, 0, 0], [12, 0, 0], [15, 0, 0]], [[18, 0, 0], [21, 0, 0], [24, 0, 0]]] print("distance is : ",distance) #print("distance[:,:,0] :",distance[:,:,0]) #Can not be accessing multi-dimension slicing #Solution: use nump array distance=np.array(distance) print("distance[:,:,0] :",distance[1:,1:,0])
# 使用format()函数进行格式化 # print("尊敬的 {0} 用户,您好! 您当月已用话费 {1} 元, 可用话费为 {2} 元,可用积分 {3} 分." format('颛孙鹏程',12.12,23.43,1234)) # 报错,format()是一个函数,需要调用的, 用 . 调用 # print("尊敬的 {0} 用户,您好! 您当月已用话费 {1} 元, 可用话费为 {2} 元,可用积分 {3} 分.".format('颛孙鹏程',12.12,23.43,1234)) # ---OK # 小明的成绩从去年的72分提升到了今年的85分,请计算小明成绩提升的百分点, # 并用字符串格式化显示出'xx.x%',只保留小数点后1位: last = 72 now = 85 print("成绩提升了 %.1f%% " % ((85-72)/72*100)) print("成绩提升了 {0:.1f}%".format((85-72)/72*100)); #print('小明比去年成绩提升了{0:.1f}%'.format(r))
from collections import namedtuple,deque Point = namedtuple('Point',['x','y']) p = Point(1,2) print(p.x) q = deque(['a','b','c']) q.append('x') q.appendleft('y') print(q)
# 日志捕获 import logging def foo(s): return 10 / int(s) def bar(s): return foo(s) * 2 def main(): try: bar('0') except Exception as e: logging.exception(e) # print("哈哈哈") finally: print("我去你吗的") # main() # print('END') # 异常抛出 # 我把我的错误信息,返回到上层 def foo1(s): try: return 10 / int(s) except Exception as e: raise # 我是上层,我把错误信息给吃了 def bar1(s): try: return foo1(s) * 2 except Exception as e: print("异常被我吃了") bar1("0") print('END')
# type()用于判断对象的类型 ''' class Student(object): pass student = Student() print(type(student)) print(type(123)) ''' # types用于判断方法的类型 ''' import types def fun1(): print("hello world") return if type(fun1) == types.FunctionType: print(True) ''' # isinstance() 就很高级了 ''' - 判断对象类型 - 判断方法类型 - 判断某一个变量是否属于某一类 print("1-->",isinstance(123,int)) print("2-->",isinstance(123,str)) print("3-->",isinstance([1,2,3],(list,tuple))) print("4-->",isinstance([1,2,3],(list,tuple))) class Student(object): pass student = Student() print("5-->",isinstance(student,Student)) import types def funq(): pass print("6-->",isinstance(funq,types.FunctionType ''' # dir() 获取一个对象的所有属性和方法 ''' class Student(object): """docstring for Student""" def __init__(self, __name,__score): self.__name = __name; self.__score = __score; def sayHello(): print("hello world") return def readBook(): print("read book") return def readSomething(self,str): print("%s what to say: %s" % (self.__name,str)) return def __len__(self): return 2 student = Student("张三","98") print(dir(student)) print(len(student)) print() # 不能获取隐藏属性 print("有属性__name吗?",hasattr(student,'__name')) print("设置属性name!",setattr(student,'name',"王五")) fn = getattr(student,'readSomething') fn("fuck you") ''' # 实例属性和雷属性 ''' >>> class Student(object): ... name = 'Student' ... >>> s = Student() # 创建实例s >>> print(s.name) # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性 Student >>> print(Student.name) # 打印类的name属性 Student >>> s.name = 'Michael' # 给实例绑定name属性 >>> print(s.name) # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性 Michael >>> print(Student.name) # 但是类属性并未消失,用Student.name仍然可以访问 Student >>> del s.name # 如果删除实例的name属性 >>> print(s.name) # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了 Student '''
from datetime import datetime,timedelta # 获取当前时间 print(datetime.now()) # 获取指定时间 print(datetime(2015,4,19,12,20)) # 获取时间戳 print(datetime(2015,4,19,12,20).timestamp()) # 时间戳转时间 t = datetime.now().timestamp() print(datetime.fromtimestamp(t)) # 时间戳转UTC时间 print(datetime.utcfromtimestamp(t)) # string转时间 print(datetime.strptime('2019-03-11 15:20:09','%Y-%m-%d %H:%M:%S')) # 时间转string print(datetime.now().strftime('%H:%M:%S')) # 加减时间 print(datetime.now() + timedelta(hours=3)) print(datetime.now() - timedelta(days=3))
class Student(object): def getName(self): return self.name def setName(self,name): self.name = name return student = Student() student.setName("lisi") print(student.getName()) # @property 是把一个方法变成属性,可以直接通过属性直接调用 class Teacher(object): @property def name(self): return self._name @name.setter def name(self,name): self._name = name return t = Teacher() t.name='zs' print(t.name) # 必须要加上_ ,要不然会报错 class Teacher1(object): @property def name(self): return self.name @name.setter def name(self,name): self.name = name return t = Teacher1() t.name='zs' print(t.name)
stanciya = { "A": '1 час.', "B": '2 часа.', "C": '3 часа.', "D": '4 часа.', "E": '5 часа.' } st = input("Введи станцию: ") st = st.upper() if st in stanciya: print(stanciya[st])
def gcd(x, y): a = x b = y if (b == 0): return a else: while b != 0: c = a % b print(f'{a} {b} {c}') a = b b = c return a print(gcd(1970, 1066))
class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def createListNode(self, target: list, index = 0): if (index != len(target)): return ListNode(val=target[index], next=self.createListNode(target, index + 1)) def addTwoNumbers(self, l1: ListNode, l2: ListNode): str_l1 = "" str_l2 = "" while (l1.next): str_l1 += str(l1.val) l1 = l1.next str_l1 += str(l1.val) str_l1 = int(str_l1[::-1]) while (l2.next): str_l2 += str(l2.val) l2 = l2.next str_l2 += str(l2.val) str_l2 = int(str_l2[::-1]) num = str_l1+str_l2 return self.createListNode(target=[int(x) for x in str(num)][::-1]) # nodes = ListNode(val=1, next= ListNode(val=0, next = ListNode(val=3))) # print(nodes.val) s = Solution() l1 = s.createListNode([2, 4, 3]) l2 = s.createListNode([5, 6, 4]) print(s.addTwoNumbers(l1, l2).val) print(s.addTwoNumbers(l1, l2).next.val) print(s.addTwoNumbers(l1, l2).next.next.val)
# An Arithmetic Progression is defined as one in which there is a constant difference between the consecutive terms of a given series of numbers. You are provided with consecutive elements of an Arithmetic Progression. There is however one hitch: exactly one term from the original series is missing from the set of numbers which have been given to you. The rest of the given series is the same as the original AP. Find the missing term. # You have to write the function findMissing(list), list will always be at least 3 numbers. The missing term will never be the first or last one. # Example # find_missing([1, 3, 5, 9, 11]) == 7 # ``` # PS: This is a sample question of the facebook engineer challenge on interviewstreet. I found it quite fun to solve on paper using math, derive the algo that way. Have fun! def find_missing(sequence): mean_diff = [] num = 0 for n in range(0, len(sequence) - 1): mean_diff.append(sequence[n + 1] - sequence[n]) for n in range(0, len(sequence) - 1): if (sequence[n + 1] - sequence[n]) != mean_diff[0]: num = sequence[n] break return num + mean_diff[0] print(find_missing([1, 3, 5, 9, 11])) print(find_missing([1, 3, 4, 5, 6, 7, 8, 9])) print(find_missing([1, 3, 5, 7, 11, 13]))
""" Define a function that takes in two numbers a and b and returns the last decimal digit of a^b. Note that a and b may be very large! For example, the last decimal digit of 9^7 is 9, since 9^7 = 4782969. The last decimal digit of (2^200)^(2^300), which has over 10^92 decimal digits, is 6. The inputs to your function will always be non-negative integers. Examples last_digit(4, 1) # returns 4 last_digit(4, 2) # returns 6 last_digit(9, 7) # returns 9 last_digit(10, 10 ** 10) # returns 0 last_digit(2 ** 200, 2 ** 300) # returns 6 """ def last_digit(n1, n2): result = pow(n1, n2, 10) result_str = str(result) return int(result_str[-1]) def last_Digit(n1, n2): return pow( n1, n2, 10 ) rules = { 0: [0,0,0,0], 1: [1,1,1,1], 2: [2,4,8,6], 3: [3,9,7,1], 4: [4,6,4,6], 5: [5,5,5,5], 6: [6,6,6,6], 7: [7,9,3,1], 8: [8,4,2,6], 9: [9,1,9,1], } def Last_digit(n1, n2): ruler = rules[int(str(n1)[-1])] return 1 if n2 == 0 else ruler[(n2 % 4) - 1] # import math # # Function to find b % a # def Modulo(a, b) : # # Initialize result # mod = 0 # # calculating mod of b with a to make # # b like 0 <= b < a # for i in range(0, len(b)) : # mod = (mod * 10 + (int)(b[i])) % a # return mod # return modulo # function to find last digit of a ^ b # def LastDigit(a, b) : # len_a = len(a) # len_b = len(b) # # if a and b both are 0 # if (len_a == 1 and len_b == 1 and b[0] == '0' and a[0] == '0') : # return 1 # # if exponent is 0 # if (len_b == 1 and b[0]=='0') : # return 1 # # if base is 0 # if (len_a == 1 and a[0] == '0') : # return 0 # # if exponent is divisible by 4 that means last # # digit will be pow(a, 4) % 10. # # if exponent is not divisible by 4 that means last # # digit will be pow(a, b % 4) % 10 # if((Modulo(4, b) == 0)) : # exp = 4 # else : # exp = Modulo(4, b) # # Find last digit in 'a' and compute its exponent # res = math.pow((int)(a[len_a - 1]), exp) # # Return last digit of result # return res % 10 print(last_digit(9, 7)) print(last_digit(2 ** 200, 2 ** 300))
# -*- coding: utf-8 -*- """ Created on Sun Mar 17 10:46:21 2019 @author: 16327143仲逊 """ annual_salary=float(input('Enter your starting annual salary:' )) total_cost=1000000 portion_down_payment=0.25 need_pay=portion_down_payment*total_cost def calculate_36month_after(portion_saved,monthly_salary): """ 计算36个月后的存款 """ r=0.04 month=1 current_savings=0.0 semi_annual_raise=0.07 for month in range(1,37): current_savings+=(current_savings*r/12) current_savings+=(monthly_salary*portion_saved) if(month%6==0): monthly_salary*=(1+semi_annual_raise) return current_savings def calculate_saving_rate(annual_salary): """ 计算最佳存款率 """ monthly_salary=annual_salary/12 left,right=0,10000 steps=0 #若每个月剩下100%都无法满足题意,返回非法值 if(calculate_36month_after(1,monthly_salary)<need_pay): return -1,-1 #二分查找 while left<right: steps+=1 mid=left+(right-left)//2 if(calculate_36month_after(mid/10000,monthly_salary)<need_pay): left=mid+1 else: right=mid #返回存款率和二分查找次数 return left/10000,steps Best_savings_rate,steps=calculate_saving_rate(annual_salary) if(steps==-1): print("It is not possible to pay the down payment in three years.") else: print('Best_savings_rate:',Best_savings_rate) print('Steps in bisection search:',steps)
# Picodisplay demo Make Magazin 2021 (caw) import time, random # Boilerplate code which will be needed for any program using the Pimoroni Display Pack # Import the module containing the display code import picodisplay as display def makemagazin(): display.set_pen(makeRed) display.text("Make:", 10, 10, 64, 6) display.set_pen(makeBlue) #display.rectangle(20, 20, 40, 20) display.text("Deutschlands gefaehrlichstes DIY-Magazin", 10, 5, 240, 1) display.set_pen(makeGray) display.rectangle(5, 50, width-10, height-55) # update/push changes to display (to avoid flicker) # 240x135 # Get the width of the display, in pixels width = display.get_width() # Get the height of the display, in pixels height = display.get_height() # Use the above to create a buffer for the screen. It needs to be 2 bytes for every pixel. display_buffer = bytearray(width * height * 2) # Start the display! display.init(display_buffer) # Boilerplate end # setting the backlight intensity display.set_backlight(1.0) # set drawing color display.set_pen(255,255,255) # define pens/colors makeRed = display.create_pen(255, 0, 0) makeBlue = display.create_pen(0, 0, 200) makeGray = display.create_pen(220,220,220) # "clear" (just fills display with color= display.clear() # update/push changes to display (to avoid flicker) display.update() makemagazin() display.set_pen(makeRed) while not(display.is_pressed(display.BUTTON_A)): display.pixel(random.randint(5, 234), random.randint(50, 129)) if display.is_pressed(display.BUTTON_Y): display.set_pen(makeBlue) display.text("Pico", random.randint(5, 234), random.randint(50, 129), 100, 2) display.set_pen(makeRed) display.update() # wait a second time.sleep(1)
"""Useful miscellaneous functions.""" from typing import Callable def get_linear_anneal_func( start_value: float, end_value: float, end_steps: int ) -> Callable: """Create a linear annealing function. Parameters ---------- start_value : float Initial value for linear annealing. end_value : float Terminal value for linear annealing. end_steps : int Number of steps to anneal value. Returns ------- linear_anneal_func : Callable A function that returns annealed value given a step index. """ def linear_anneal_func(x): assert x >= 0 return (end_value - start_value) * min(x, end_steps) / end_steps + start_value return linear_anneal_func
""" LeetCode Problem: 445. Add Two Numbers II Link: https://leetcode.com/problems/add-two-numbers-ii/ Language: Python Written by: Mostofa Adib Shakib Time Complexity: O(n) Space Complexity: O(n) """ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: FirstNumber = "" SecondNumber = "" FirstPointer = l1 SecondPointer = l2 while FirstPointer: FirstNumber += str(FirstPointer.val) FirstPointer = FirstPointer.next while SecondPointer: SecondNumber += str(SecondPointer.val) SecondPointer = SecondPointer.next amount = int(FirstNumber) + int(SecondNumber) Pointer = ListNode() head = Pointer for i in str(amount): new_node = ListNode() new_node.val = int(i) Pointer.next = new_node Pointer = Pointer.next return head.next
def tripleTheChances(chances): quantidade = chances[0] chances = chances[1:] chances.sort() for i in range(quantidade): chances[i] = chances[i] * 3 return chances d = tripleTheChances([5, 2, 3, 5, 8, 10]) print(d)
def action(input_char, replace_with, move, new_state): global tapehead, state if tape[tapehead] == input_char: tape[tapehead] = replace_with state = new_state if move == 'L': tapehead -= 1 else: tapehead += 1 return True return False string = input("Enter String: ") length = len(string) + 2 tape = ['B']*length i = 1 tapehead = 1 for s in string: #loop to place string in tape tape[i] = s i += 1 state = 0 #assigning characters to variable so that don't have to use characters each time zero, one, X, R, Y, B = '0', '1', 'X', 'R', 'Y', 'B' oldtapehead = -1 accept = False while(oldtapehead != tapehead): #if tapehead not moving that means terminate Turing machine oldtapehead = tapehead print(tape , "with tapehead at index", tapehead, "on state" , state) if state == 0: if action(zero, X, R, 1): pass elif action(one,one,R,0) or action(B,B,R,0): break elif state == 1: if action(one, Y, R, 1) or action(zero, X, R, 2): pass elif action(B,B,R,1): break elif state == 2: if action(B,B,R,"ACCEPT"): pass elif action(one,one,R,2) or action(zero,zero,R,2): break else: accept = True if accept: print("String accepted on state = ", state) else: print("String not accepted on state = ", state)
""" An Elf just remembered one more important detail: the two adjacent matching digits are not part of a larger group of matching digits. Given this additional criterion, but still ignoring the range rule, the following are now true: 112233 meets these criteria because the digits never decrease and all repeated digits are exactly two digits long. 123444 no longer meets the criteria (the repeated 44 is part of a larger group of 444). 111122 meets the criteria (even though 1 is repeated more than twice, it still contains a double 22). How many different passwords within the range given in your puzzle input meet all of the criteria? """ MIN = 372037 MAX = 905157 def _has_double(digits): prev = None occurrences = 0 for digit in digits: if prev is None: prev = digit occurrences = 1 continue if digit == prev: occurrences += 1 continue else: if occurrences == 2: return True else: prev = digit occurrences = 1 # the last two digits form a double (not triple) if occurrences == 2: return True return False def _increasing_only(digits): return digits == sorted(digits) def main(): found = [] for number in range(MIN, MAX + 1): digits = [int(digit) for digit in str(number)] if not _has_double(digits) or not _increasing_only(digits): continue found.append(number) print('The number of passwords: {}'.format(len(found))) if __name__ == '__main__': main()
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Apr 9 16:39:26 2017 @author: neelabhpant """ from __future__ import division # want 3 / 2 == 1.5 import re, math, random # regexes, math functions, random numbers import matplotlib.pyplot as plt # pyplot from collections import defaultdict, Counter from functools import partial def vector_add(v, w): return [v_i + w_i for v_i, w_i in zip(v, w)] def vector_subtract(v, w): return [v_i - w_i for v_i, w_i in zip(v, w)] def vector_sum(vectors): return reduce(vector_add, vectors) def scalar_multiply(c, v): return [c * v_i for v_i in v] def vector_mean(vectors): length = len(vectors) sum_of_vectors = vector_sum(vectors) return scalar_multiply(1/length, sum_of_vectors) def dot(v,w): prod = [v_i * w_i for v_i, w_i in zip(v, w)] return sum(prod) def sum_of_squares(v): return dot(v,v) def magnitude(v): return(math.sqrt(sum_of_squares(v))) def squared_distance(v,w): return sum_of_squares(vector_subtract(v,w)) def distance(v,w): return math.sqrt(squared_distance(v,w)) def shape(A): nr = len(A) nc = len(A[0]) return nr, nc def get_row(A, i): return A[i] def get_column(A, j): return [A_i[j] for A_i in A] def make_matrix(num_rows, num_cols, entry_fn): return [[entry_fn(i, j) for j in range(num_cols)] for i in range(num_rows)] def is_diagonal(i, j): return 1 if i==j else 0 def matrix_add(v, w): if shape(v) != shape(w): raise ArithemeticError("cannot add matrrices of different shapes") num_row, num_col = shape(v) def entry_func(i,j): return v[i][j] + w[i][j] return make_matrix(num_row, num_col, entry_func) friendships = [[0, 1, 1, 0, 0, 0, 0, 0, 0, 0], # user 0 [1, 0, 1, 1, 0, 0, 0, 0, 0, 0], # user 1 [1, 1, 0, 1, 0, 0, 0, 0, 0, 0], # user 2 [0, 1, 1, 0, 1, 0, 0, 0, 0, 0], # user 3 [0, 0, 0, 1, 0, 1, 0, 0, 0, 0], # user 4 [0, 0, 0, 0, 1, 0, 1, 1, 0, 0], # user 5 [0, 0, 0, 0, 0, 1, 0, 0, 1, 0], # user 6 [0, 0, 0, 0, 0, 1, 0, 0, 1, 0], # user 7 [0, 0, 0, 0, 0, 0, 1, 1, 0, 1], # user 8 [0, 0, 0, 0, 0, 0, 0, 0, 1, 0]] # user 9 # find who all are friends with user 5 friend_of_five = [] for i, j in enumerate(friendships[5]): if j: friend_of_five.append(i) def mean(v): return (sum(v)/len(v)) def de_mean(v): v_bar = mean(v) return [v_i - v_bar for v_i in v] def variance(v): n = len(v) dist_from_mean = de_mean(v) sum_sq_diff = sum_of_squares(dist_from_mean) return (sum_sq_diff / n - 1) def standard_deviation(v): return math.sqrt(variance(v)) def covariance(v, w): n = len(v) return dot(de_mean(v), de_mean(w)) / (n-1) def correlation(v, w): std_v = standard_deviation(v) std_w = standard_deviation(w) return covariance(v, w) / std_v / std_w def covariance_matrix(X): mean_vec = vector_mean(X) (X - mean_vec) def PCA(data): #Subtract the mean from each of the dimensions. #find Correlation matrix #find eigenvalue and eigenvector if Correlation matrix # sort the eigenvector according to the eigenvalues in descending order # Multiply the Eigenvectors chosen wiht the original data pass
# Matrix Loop # Demonstrates the use of random and loops to create a matrix looking program import random for matrix in range(1000): print(random.randrange(2)) input("\n\nPress ENTER to exit out of the program.")
# Trust Fund Buddy - Bad # Demonstrates a Logical Error print( """ Trust Fund Buddy Totals your monthly spending so that your trust fund doesn't run out (and you're forced to get a real job). Please enter the requested, monthly costs. Since you're rich, ignore pennies and only use dollar amounts. """ ) car = (int)(input("BMW Tune Ups: ")) rent = (int)(input("Tempe Apartment: ")) boat = (int)(input("New Boat Rental: ")) gifts = (int)(input("Gifts: ")) food = (int)(input("Dining Out?: ")) staff = (int)(input("Staff (butlers, chef, driver, assistant): ")) games = (int)(input("Computer Games: ")) total = car + rent + boat + gifts + food + staff + games print("\nGrand Total: ", total) print("\nFor an average of: ", total // 7, "per item") input("\n\nPress ENTER to exit the program") ## Selected Type Conversion Functions # float(x) - returns a floating-point value by converting x, float("10.0") = 10.0 # int(x) - returns an integer value by converting x, int("10") = 10 # str(x) - returns a String value by converting x, str(10) = '10'
import random def insert(list, item): tempList = list indexList = [] for i in range(0, len(list)): indexList.append(i) while(len(tempList) > 1): middle = len(tempList) // 2 if(item < tempList[middle]): tempList = tempList[:middle] indexList = indexList[:middle] elif(item > tempList[middle]): indexList = indexList[middle:] tempList = tempList[middle:] else: list.insert(indexList[middle], item) return list if(item > tempList[0]): list.insert(indexList[0] + 1, item) else: list.insert(indexList[0], item) return(list) def sort(list): sortedList = list[0:1] for i in range(1, len(list)): insert(sortedList, list[i]) return sortedList def main(): mylist = [] for i in range(0, 10000): mylist.append(random.randint(0, 10000)) mylist = sort(mylist) print(mylist) main()
# day2 assignment #delete an element from begining def delete_array_begining(arr): if len(arr)<1: print("array is empty cant delete") else: # for i in range(len(arr)): # del_element=arr1.array('i',arr) # del del_element[0] my_list=arr my_list.remove(arr[0]) print("array after deleting first element:",my_list) print() arr=[1,4,5,6,7,3] print("the elements in array are:",arr) delete_array_begining(arr) # delete an element at end def delete_element_at_end(arr): if len(arr)>1: l=arr l.remove(arr1[-1]) print("after deleting last element:",l) print() arr1=[1,3,4,5,6] print("the element in the array:",arr1) delete_element_at_end(arr1) # delete an element at particular position # import array as arr1 def del_at_position(arr,k): new_list=[] if len(arr)>1: # print("elements are greater than 1") for i in range(len(arr)): if i!=k: new_list.append(arr[i]) print("array after delete at particular position",new_list) arr=[1,4,2,6,3,8] print("the elements in the array are:",arr) k=3 del_at_position(arr,k)
import time class Timer: def __init__(self): self.start_time = time.time() self.end_time = 0 self.steps = 0 def step(self): self.steps += 1 self.end_time = time.time() def get_speed(self): speed = 1.0 * self.steps / (self.end_time - self.start_time) return speed
""" Percent Daily Return Exercise In this exercise, you are given the stock values for several consecutive days for acme corporation. Your job is to calculate the "percent daily return" for each day. The percent daily return is the percentage that the stock changes each compared to the day before. Below you are given the stock prices (there are only 4 days in this example). Use slicing a numeric operations to calculate the percent daily return (no for loops!). Refer back to the video lecture for inspiration. """ from numpy import array acme = array([10, 11.5, 11, 10, 12]) pdr = (acme[1:]-acme[:-1])/acme[:-1] print (pdr)
import numpy as np import scipy.io as sio import matplotlib.pyplot as plt from linearRegCostFunction import * from trainLearnReg import * from learningCurve import* from plotFeatures import* from featureNormalize import* from plotFit import* from validationCurve import * print('Loading and Visualizing Data ...') data=sio.loadmat('ex5data1.mat') X=data['X'] y=data['y'] Xval=data['Xval'] yval=data['yval'] Xtest=data['Xtest'] ytest=data['ytest'] plt.xlabel('Change in water level (x)') plt.ylabel('Water flowing out of the dam (y)') plt.scatter(X,y,c='red',marker='x',linewidths=10) plt.show() input('Program paused. Press enter to continue.\n') m=X.shape[0] theta=np.array([1,1]) J=linearRegCostFunction(np.c_[np.ones((X.shape[0],1)),X],y,theta,1)[0] print('Cost at theta = [1 ; 1]: %f \n(this value should be about 303.993192)'%J) input('Program paused. Press enter to continue.\n') # =========== Part 3: Regularized Linear Regression Gradient ============= # You should now implement the gradient for regularized linear # regression. # theta =np.array([1,1]) J,grad=linearRegCostFunction(np.c_[np.ones((X.shape[0],1)),X],y,theta,1) print(grad.shape) print('Gradient at theta = [1 ; 1]: [%f; %f] \ \n(this value should be about [-15.303016; 598.250744])\n') print(grad) input('Program paused. Press enter to continue.\n') # =========== Part 4: Train Linear Regression ============= # Once you have implemented the cost and gradient correctly, the # trainLinearReg function will use your cost function to train # regularized linear regression. # Write Up Note: The data is non-linear, so this will not give a great # fit. lmd=0 theta_result=trainLinearReg(np.c_[np.ones((X.shape[0],1)),X],y,lmd) print(theta_result) Xnew=np.c_[np.ones((X.shape[0],1)),X] plt.xlabel('Change in water level (x)') plt.ylabel('Water flowing out of the dam (y)') plt.scatter(X,y,c='red',marker='x',linewidths=10) plt.plot(X,Xnew.dot(theta_result.T)) plt.show() input('Program paused. Press enter to continue.\n') # =========== Part 5: Learning Curve for Linear Regression ============= # Next, you should implement the learningCurve function. # # Write Up Note: Since the model is underfitting the data, we expect to # see a graph with "high bias" -- Figure 3 in ex5.pdf lmd=0 error_train,error_val=learningCurve(np.c_[np.ones((X.shape[0],1)),X],y,np.c_[np.ones((Xval.shape[0],1)),Xval],yval,lmd) plt.figure() plt.plot(np.arange(m),error_train) plt.plot(np.arange(m), error_val) plt.title('Learning Curve for Linear Regression') plt.legend(['Train', 'Cross Validation']) plt.xlabel('Number of Training Examples') plt.ylabel('Error') plt.axis([0, 13, 0, 150]) plt.show() print('# Training Examples\tTrain Error\tCross Validation Error') for i in range(m): print(' \t%d'%i,end='') print(' \t%d'%error_train[i],end='') print(' \t%d'%error_val[i],end='') input('Program paused. Press enter to continue.\n') # =========== Part 6: Feature Mapping for Polynomial Regression ============= # One solution to this is to use polynomial regression. You should now # complete polyFeatures to map each example into its powers # p = 8 X_poly=polyFeatures(X,p) X_poly, mu, sigma = featureNormalize(X_poly) X_poly = np.c_[np.ones((m, 1)), X_poly] X_poly_test = polyFeatures(Xtest, p) X_poly_test-=mu X_poly_test/=sigma X_poly_test = np.c_[np.ones((ytest.shape[0], 1)), X_poly_test] X_poly_val = polyFeatures(Xval, p) X_poly_val-=mu X_poly_val/=sigma X_poly_val = np.c_[np.ones((yval.shape[0], 1)), X_poly_val] print('Normalized Training Example 1 : \n{}'.format(X_poly[0])) # =========== Part 7: Learning Curve for Polynomial Regression ============= # Now, you will get to experiment with polynomial regression with multiple # values of lambda. The code below runs polynomial regression with # lambda = 0. You should try running the code with different values of # lambda to see how the fit and learning curve change. lmd=1 np.set_printoptions(suppress=True) print(X_poly) theta=trainLinearReg(X_poly,y,lmd) print(theta) X_fit,y_fit=plotFit(np.min(X),np.max(X),mu,sigma,theta,p) plt.scatter(X,y,c='r',marker='x') plt.plot(X_fit,y_fit) plt.xlabel('Change in water level (x)') plt.ylabel('Water folowing out of the dam (y)') plt.ylim([-60, 60]) plt.title('Polynomial Regression Fit (lambda = {})'.format(lmd)) plt.show() error_train, error_val = learningCurve(X_poly, y, X_poly_val, yval, lmd) plt.figure(4) plt.plot(np.arange(m), error_train, np.arange(m), error_val) plt.title('Polynomial Regression Learning Curve (lambda = {})'.format(lmd)) plt.legend(['Train', 'Cross Validation']) plt.xlabel('Number of Training Examples') plt.ylabel('Error') plt.axis([0, 13, 0, 150]) plt.show() print('Polynomial Regression (lambda = {})'.format(lmd)) print('# Training Examples\tTrain Error\t\tCross Validation Error') for i in range(m): print(' \t{}\t\t{}\t{}'.format(i, error_train[i], error_val[i])) lambda_vec ,error_train,error_val=validationCurve(X_poly,y,X_poly_val,yval) plt.plot(lambda_vec,error_train) plt.plot(lambda_vec,error_val) plt.xlabel('lambda') plt.ylabel('Error') plt.show()
""" Uzrakstiet programmu Python, lai pārbaudītu, vai norādītā vērtība ir vērtību grupā. Testa dati: 3 -> [1, 5, 8, 3]: taisnība -1 -> [1, 5, 8, 3]: nepatiesa """ cipari = [1, 5, 8, 3] if 3 in cipari: print("taisnība") if -1 in cipari: print("nepatiesi")
""" glc.shapes.segment ================== (c) 2016 LeoV https://github.com/leovoel/ """ from math import atan2, hypot from .shape import Shape class Segment(Shape): """Draws a portion of a line. The drawn segment will animate from the start of the line to the end of it during the animation (and back to the start if the loop attribute on the animation is ``True``). Create it using: .. code-block:: python render_list.segment(x0=0, y0=0, x1=100, y1=100, length=50, show_points=False) Attributes ---------- x0 : float Horizontal position of the first point. y0 : float Vertical position of the first point. x1 : float Horizontal position of the second point. y1 : float Vertical position of the second point. length : float Length of the segment drawn. show_points : bool Whether to show the points used to draw the curve or not. Defaults to ``False``. """ def draw(self, context, t): x0 = self.get_number("x0", t, 0) y0 = self.get_number("y0", t, 0) x1 = self.get_number("x1", t, 100) y1 = self.get_number("y1", t, 100) segment_length = self.get_number("length", t, 50) dx = x1 - x0 dy = y1 - y0 angle = atan2(dy, dx) dist = hypot(dx, dy) start = -0.01 end = (dist + segment_length) * t if end > segment_length: start = end - segment_length if end > dist: end = dist + 0.01 context.translate(x0, y0) context.rotate(angle) context.move_to(start, 0) context.line_to(end, 0) self.draw_fill_and_stroke(context, t, False, True)
""" glc.shapes.circle ================= (c) 2016 LeoV https://github.com/leovoel/ """ from .shape import Shape from ..utils import rad class Circle(Shape): """Draws a circle. This can also draw an arc, if you use the start and end angle properties to do so. Create it using: .. code-block:: python render_list.circle(x=100, y=100, radius=50, start=0, end=360, centered=False, rotation=0, scale_x=1, scale_y=1) Attributes ---------- x : float Horizontal position of the circle. y : float Vertical position of the circle. radius : float Radius of the circle. start : float Start angle of the arc, in degrees. end : float End angle of the arc, in degrees. rotation : float Rotation of the circle, in degrees. centered : bool Whether to start drawing at the center of the circle or not. Defaults to ``False``. scale_x : float Horizontal scale factor of the circle. scale_y : float Vertical scale factor of the circle. """ def draw(self, context, t): x = self.get_number("x", t, 100) y = self.get_number("y", t, 100) radius = self.get_number("radius", t, 50) start_angle = self.get_number("start", t, 0) end_angle = self.get_number("end", t, 360) centered = self.get_bool("centered", t, False) context.translate(x, y) context.rotate(rad(self.get_number("rotation", t, 0))) context.scale(self.get_number("scale_x", t, 1), self.get_number("scale_y", t, 1)) if centered: context.move_to(0, 0) context.arc(0, 0, radius, rad(start_angle), rad(end_angle)) if centered: context.close_path() self.draw_fill_and_stroke(context, t, True, False)
import matplotlib.pyplot as plt import numpy as np def make_column_chart(): number_of_data_sets = int(input("Enter number of data sets: ")) averages = [] labels = [] title = str(input("Enter title: ")) x_label = str(input("Enter x axis title: ")) y_label = str(input("Enter y axis title: ")) for i in range(0, number_of_data_sets): data = input("Enter data set: ") label = str(input("Enter data label: ")) averages.append(_compute_average(data)) labels.append(label) y_pos = np.arange(len(averages)) plt.bar(y_pos, averages, align='center', alpha=0.5) plt.xticks(y_pos, labels) plt.title(title) plt.xlabel(x_label) plt.ylabel(y_label) plt.show() def _compute_average(data): total = 0 average = 0 for i in range(0, len(data)): total += data[i] average = total / len(data) return average
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: ahtouw """ __doc__ = """ Dependencies: pandas sklearn.preprocessing -> MinMaxScaler sklearn.decomposition -> PCA This module is for performing PCA on a dataset NOTE: DATA GETS SCALED DOWN PRIOR TO PCA This is done in the function performPCA(), which will receive the original dataframe as input and return PCA dataframe NOTE: This is before the dataset is split into test and train. PCA can be done after but this function would need to be reconfigured """ import pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn.decomposition import PCA def performPCA(df:pd.DataFrame, var = 0.95, printComponents = False) -> pd.DataFrame: """ Performing PCA on the dataset Parameters ---------- df : pd.DataFrame This should be the entire Housing Prices dataframe. var : float (OPTIONAL) This should be the desired variance to be retained after PCA is performed. If not specified, will be set to 0.95 (95% retained) printComponents : Boolean (OPTIONAL) This should be the value that specifies whether or not to print the number of components remaining after PCA If not specified, will be set to False (no print) Returns ------- pd.DataFrame This dataframe will include ONLY remaining components from PCA. """ # Data must be normalized prior to PCA, I chose to use MinMaxScaler scaler = MinMaxScaler() df = scaler.fit_transform(df) # Perfoming PCA on the dataset using the 'var' parameter pca = PCA(n_components = var) principalComponents = pca.fit_transform(df) # Converting principalComponents (numpy array) to a pd.dataframe principalDf = pd.DataFrame(data = principalComponents) # Print number of components remaining after PCA if requested if printComponents: print("PCA with variance of %.f%%"%(var*100)) print("Number of components: %d"%len(pca.components_)) return principalDf import pandas as pd from sklearn.linear_model import SGDRegressor from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler def sgd_model(df:pd.DataFrame, y:pd.Series) -> str: """SGD Regressor model that returns score.""" # Checks if Foundation is still in the columns and if it is still set to string and drops it if it is if 'Foundation' in df.columns and df.Foundation.dtype == object: df.drop(axis=1, labels='Foundation', inplace=True) # # Instantiates the MinMaxScaler and scales our dataframe before train/test split # scaler = MinMaxScaler() # df = scaler.fit_transform(df) # Train/Test data split x_train, x_test, y_train, y_test = train_test_split(df, y, test_size=0.2) # Create model with 10,000 iterations and warm_start set to true so it reuses previous iteration for initialization values model = SGDRegressor(max_iter=10000, warm_start=True) model.fit(x_train, y_train) return f'{model.score(x_test, y_test):.2f}' if __name__ == '__main__': df=pd.read_csv('fixed_No.csv') y = pd.read_csv('train.csv')['SalePrice'] # ONLY THE FIRST PARAMETER IS REQUIRED princ_df = performPCA(df,var=.95,printComponents=True) print(sgd_model(princ_df,y)) # print(princ_df.head())
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 6 10:57:22 2020 @author: staxx Brandon Jackson """ # Function we worked on that was not used def feature_extract(df): ''' Take in dataframe object and check for NaN values and handle ---------- df_train : dataframe training dataset from the Ames,Iowa housing file. Returns concatenated dataframe ------- dataframe object of extracted data and transformed variable. Looked for missing values and outliers and did not find any. ''' # Handle NaN values for col in df: if col.isnull(): # Condition1 and Condition2 unique values # Neighborhood Nominal # LandSlope Ordinal # create list of my respective values for evaluating predictor_columns = ['Neighborhood','Condition1','Condition2'] # create dummy list of relevant values for evaluation df_housing = pd.get_dummies(df[predictor_columns]) # based off EDA LandSLope can be changed to numerical based of th three types df_housing.LandSlope.replace({'Sev':3, 'Mod':2, 'Gtl':1}, inplace=True) fill = 1 return pd.concat(df_housing, df.LandSlope)
import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv("/Users/nithinkyatham/Downloads/Mall_Customers.csv") X = dataset.iloc[:,[3,4]].values # Elbow method using WCSS from sklearn.cluster import KMeans # Creating a list to hold WCSS values for different K Values wcss = [] for i in range(1,11): kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter=300, n_init=10) kmeans.fit(X) wcss.append(kmeans.inertia_) # Plot the graph of WCSS values versus number of clusters to get elbow angle """plt.plot(range(1,11),wcss,color='blue') plt.xlabel('Number of clusters') plt.ylabel('WCSS-Values') plt.title('Graph of WCSS versus number of clusters')""" # Implementing K-Means with K=5 kmeans = KMeans(n_clusters = 5, init = 'k-means++', max_iter=300, n_init=10) # Fitting and Predicting the clusters of each customer y_kmeans = kmeans.fit_predict(X) #Visual Representtion of the cluster-formation plt.scatter(X[y_kmeans==0,0], X[y_kmeans==0,1], s = 100, color = 'red', label = 'Cluster 0') plt.scatter(X[y_kmeans==1,0], X[y_kmeans==1,1], s = 100, color = 'blue', label = 'Cluster 1') plt.scatter(X[y_kmeans==2,0], X[y_kmeans==2,1], s = 100, color = 'yellow', label = 'Cluster 2') plt.scatter(X[y_kmeans==3,0], X[y_kmeans==3,1], s = 100, color = 'green', label = 'Cluster 3') plt.scatter(X[y_kmeans==4,0], X[y_kmeans==4,1], s = 100, color = 'cyan', label = 'Cluster 4') plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],s=300, c='black', label='Centroids') plt.xlabel('Annual Income') plt.ylabel('Spending Score') plt.title('Clusters of customers') plt.legend()
flag = list('flag{caesar_ciphers_are_basically_a_formality}') for m in range(len(flag)): cur = flag[m] if cur == 'z': flag[m] = 'a' elif cur == 'Z': flag[m] ='A' elif 65 <= ord(cur) <= 89 or 97 <= ord(cur) <= 121: flag[m] = chr(ord(cur) + 1) print ''.join(flag)
from Tkinter import * window = Tk() window.title("MGH App") lbl = Label(window, text="Gravitational Potential Energy Calculator") lbl.grid(column=0, row=0) window.geometry("600x600") mass_q = Label(window, text="What is the mass in kilograms?") mass_q.grid(column=0, row=1) Mass = Entry(window, width=5) Mass.grid(column=1, row=1) kg = Label(window, text = "kg") kg.grid(column = 2, row = 1) height_q = Label(window, text="What is the height in meters?") height_q.grid(column=0, row=2) Height = Entry(window, width=5) Height.grid(column=1, row=2) meters = Label(window, text = "meters") meters.grid(column = 2, row = 2) def solve_gpe(): sol = str(float(Mass.get()) * 9.8 * float(Height.get())) answer = "The GPE is " + sol + " KJ" solution.configure(text = answer) return sol solve = Button(window, text="Solve GPE", command = solve_gpe) solve.grid(column=1, row=3) solution = Label(window, text = "The GDP will show here") solution.grid(column = 0, row = 4) window.mainloop()
import collections Nucleotides = ["A","T","G","C"] def validateSeq(dna_seq): tmpseq = dna_seq.upper() for nuc in tmpseq: if nuc not in Nucleotides: return False return tmpseq def countNucFrequency(seq): tempFreqDict = {"A": 0, "T": 0, "G": 0, "C": 0} for nuc in seq: tempFreqDict[nuc] += 1 return tempFreqDict dnastring = "TAGCTACGATCGA" result = countNucFrequency(dnastring) print(result)
def division(a, b): try: result = a / b except ZeroDivisionError as e: return "divide by zero, error: %s"%e except TypeError as e: return division(int(a), int(b)) else: return result finally: print ("good, well done!")
__author__ = 'Guruguha' # Percentages num_of_students = int(input()) if num_of_students < 2 or num_of_students > 10: print("Enter valid number of students") else: count = num_of_students student_data = [] valid_input = True while count != 0: values = input() input_list = values.split() if input_list[1].isdigit() is False or float(input_list[1]) < 0 or float(input_list[1]) > 100: print("Enter valid marks for physics") valid_input = False if input_list[2].isdigit() is False or float(input_list[2]) < 0 or float(input_list[2]) > 100: print("Enter valid marks for chemistry") valid_input = False if input_list[3].isdigit() is False or float(input_list[3]) < 0 or float(input_list[3]) > 100: print("Enter valid marks for mathematics") valid_input = False dict = {'name':input_list[0], 'physics':input_list[1], 'chemistry':input_list[2], 'mathematics':input_list[3]} student_data.append(dict) count -= 1 if valid_input: search_student = input() for i in range(0, len(student_data)): if search_student == student_data[i]['name']: total_marks = float(student_data[i]['physics']) \ + float(student_data[i]['chemistry'])\ + float(student_data[i]['mathematics']) avg = total_marks / 3 print(str("{0:.2f}".format(avg))) break else: print("Invalid input")
#!/bin/python3 import sys n = int(input().strip()) fact = 1 itr = 1 while itr <= n: fact *= itr itr += 1 print(fact)
nums=int(input()) status=None for i in range(2,nums): if nums>1: if nums%i==0: status='Not Prime' break else: status='Prime' print(status)
# -*- coding:utf-8 -*- from binascii import * import sys #import passwordlist if len(sys.argv) != 3 or sys.argv[1] not in ('0','1'): sys.exit( '''Useage: python exchange.py <mode> <'exchange-string'> Examples: python exchange.py 0 'hello' python exchange.py 1 '12345' ''' ) def a2b(exc_num): src_pw = '' src_num = a2b_hex(exc_num) src_num_len = len(src_num) for m in range(0,src_num_len,2): n = m+1 if n <= src_num_len: src_pw += pwlist[int(src_num[m])][int(src_num[n])] else: break return src_pw def b2a(src_str): exc_list=[] exc_str='' for s in src_str: for i in range(len(pwlist)): if s in pwlist[i]: exc_list.append(i) #print pwlist[i].index(s) exc_list.append(pwlist[i].index(s)) exc_str += str(i)+str(pwlist[i].index(s)) return(b2a_hex(exc_str)) #pwlist = passwordlist.pwlist pwlist=[['!','@','#','$','%','^','&','*','(',')','_','+'], ['1','2','3','4','5','6','7','8','9','0','-','='], ['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']'], ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', "'"], ['z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/'], ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', '|'], ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '"'], ['Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?']] arg_list=[b2a,a2b] print('{} => {}'.format(sys.argv[2],arg_list[int(sys.argv[1])](sys.argv[2])))
""" This is your coding interview problem for today. This problem was asked by Microsoft. Suppose an arithmetic expression is given as a binary tree. Each leaf is an integer and each internal node is one of '+', '−', '∗', or '/'. Given the root to such a tree, write a function to evaluate it. For example, given the following tree: * / \ + + / \ / \ 3 2 4 5 You should return 45, as it is (3 + 2) * (4 + 5). """ class Node: """ Simple Node class to represent arithmetic tree. """ def __init__(self, data): """ Initialize with some data. """ self.data = data self.left = None self.right = None def insert_level_order(arr): """ Function to insert nodes in level order. """ def _insert_level_order(arr, root, i, n): """ Helper function for initialization. """ # Base case for recursion if i < n: temp = Node(arr[i]) root = temp # insert left child root.left = _insert_level_order(arr, root.left, 2 * i + 1, n) # insert right child root.right = _insert_level_order(arr, root.right, 2 * i + 2, n) return root return _insert_level_order(arr, None, 0, len(arr)) def arith(root): """ Gets in-order arithmetic traversal of root and returns result. Does NOT handle cases that are not well-defined: Well-defined tree: - All non-leaf nodes are operations - All leaf nodes are numbers. We can think of this function as performing a real python arithmetic function. """ # Easily grab operation op = { '+': lambda x, y: x + y, '-': lambda x, y: x - y, '*': lambda x, y: x * y, '/': lambda x, y: x / y, } # Base case if not root: return 0 # Operation Case if root.data in op: # Get's appropriate operation and performs recursively return op[root.data](arith(root.left), arith(root.right)) # Leaf case - hit a number return root.data # Test case if __name__ == "__main__": head = insert_level_order(['*', '+', '+', 3, 2, 4, 5]) print(arith(head))
""" This problem was asked by Facebook. Given a function f, and N return a debounced f of N milliseconds. That is, as long as the debounced f continues to be invoked, f itself will not be called for N milliseconds. """ import time def debounce(f, N): """ Returns a debounced function s.t. f is executed after N milliseconds. """ def debounced_f(*args, **kwargs): time.sleep(N / 1000) return f(*args, **kwargs) return debounced_f def add(x, y): """ Example function. """ return x + y if __name__ == "__main__": debounced_add = debounce(add, 1000) print(debounced_add(1, 2))
""" This is your coding interview problem for today. This problem was asked by Dropbox. What does the below code snippet print out? How can we fix the anonymous functions to behave as we'd expect? functions = [] for i in range(10): functions.append(lambda : i) for f in functions: print(f()) """ if __name__ == "__main__": functions = [] for i in range(10): functions.append(lambda: i) # Prints all 9's! for f in functions: print(f()) # Fix the problem def g(i): return lambda: i functions_0 = [g(i) for i in range(10)] for f in functions_0: print(f()) # Or functions_1 = [lambda i=i: i for i in range(10)] # Prints all 9's! for f in functions_1: print(f())
""" This question was asked by Google. Given an integer n and a list of integers l, write a function that randomly generates a number from 0 to n-1 that isn't in l (uniform). Ex: n = 7 l = {0, 1, 4} the function should return any random number { 2, 3, 5, 6 } with equal probability. """ import numpy as np class UniformGenerator: """ If we assume array is not sorted and can contain any value, we need to generate an array of valid numbers """ def __init__(self, n, data): self.data = data self.max_num = n self.usable = set(num for num in self.data) self.usable = list(set(range(self.max_num)) - self.usable) def sample(self): """ Returns a random integer from 0 to n-1 uniform s.t. n not in l. """ if not self.usable: return ValueError("No output to return") idx = np.random.randint(0, len(self.usable)) return self.usable[idx] def bin_search(arr, k, lo, hi, left_misses): """ Conducts binary search to find kth missing element in arr. """ if hi - lo == 1: val = arr[lo] + k - left_misses if val >= arr[hi]: return val + 1 return val mid = (lo + hi) // 2 rem = (arr[mid] - arr[lo]) - (mid - lo) if left_misses + rem >= k: return bin_search(arr, k, lo, mid, left_misses) else: left_misses += rem return bin_search(arr, k, mid, hi, left_misses) def random_non_arr_elt(n, l): """ Returns a random integer from 0 to n-1 uniform s.t. n not in l. note: 0 <= len(l) < n. 0 <= l[i-1] < l[i] < l[i+1] < n for all i. """ # We want the rth missing element in the array l (1 - indexed) r = np.random.randint(1, n - len(l) + 1) return bin_search(l, r, 0, len(l) - 1, 0) if __name__ == "__main__": import matplotlib.pyplot as plt ITERS = 100000 out = [0 for _ in range(ITERS)] l = [0, 2, 4] gen = UniformGenerator(7, l) for i in range(ITERS): out[i] = gen.sample() # for i in range(ITERS): # out[i] = random_non_arr_elt(7, l) print(out) plt.hist(out) plt.show()
""" Return a tuple representing the minumum index range of an array that is out of order. For example, the array [3, 7, 5, 6, 9] would return (1, 3). """ def min_arr_range(arr): """ Returns minimum index range that is out of order. Input: arr: numeric list Returns: (n, m) where n and m represent integer indeces. """ max_seen, min_seen = -float("inf"), float("inf") left, right = None, None for i, v in enumerate(arr): max_seen = max(max_seen, v) if v < max_seen: right = i for i, v in enumerate(reversed(arr)): min_seen = min(min_seen, v) if v > min_seen: # Correct reversed index left = len(arr) - 1 - i return (left, right) if __name__ == "__main__": # Test cases print(min_arr_range([3, 7, 5, 6, 9])) print(min_arr_range([-1, 4, -30, 2, 1]))
import random import math class Player: player_list = {} def __init__(self, name, money=1500): self.name = name self.money = money self.jail = False self.jail_counter = 0 self.position = 0 # Colours, Utilities, Railroads self.properties = [{}, [], []] self.jail_free = 0 Player.player_list[self.name] = self def list_all(self): for x in self.properties[0]: # Prints out all properties that are colours, with the number of houses and hotels aligned. print(x + ' ' * (32 - len(x)), end="") if self.properties[0][x].houses > 0: print(str(self.properties[0][x].houses) + " houses", end="") elif self.properties[0][x].hotel > 0: print(str(self.properties[0][x].hotel) + " hotel", end="") elif self.properties[0][x].mortgaged: print("(mortgaged)") print("") print("\n") for x in self.properties[1]: # Prints out utilities print(x.name) print("\n") for x in self.properties[2]: # Prints out railroads print(x.name) def move_action(self): self.position = (self.position + Dice.roll[0] + Dice.roll[1]) % 40 tiles[self.position].action(self) def trade(self): for x in Player.player_list: print(x) try: trade_player = Player.player_list[input("Which player to trade with?\n")] print("Owned properties:") self.list_all() print("$" + str(self.money)) print(trade_player + "\'s properties:") self.list_all() print("$" + str(self.money)) choices = input("Offering properties (P), money (M) or Jail-free card (J)? Multiple letters possible.\n") # Two arrays of offer/trade, with property names, money, get out of jail free cards. assets = [[[], 0, 0], [[], 0, 0]] players = [self, trade_player] for loop in range(2): # Colours if choices.lower().find("p") != -1: count = int(input("Number of properties?\n")) for x in range(count): property_name = input("Enter a property name.\n") if players[loop].variable_prop_owned(property_name, True) != -1: assets[loop][0].append(property_name.title()) # Money if choices.lower().find("m") != -1: money = int(input("How much money?\n")) if money <= players[loop].money: assets[loop][1] = money else: print("Not enough money.") # Jail card if choices.lower().find("j") != -1: if players[loop].jail_free > 0: assets[loop][2] += 1 else: print("Not owned.") if trade_player.accept_trade(): for prop_name in assets[0][0]: selector = self.variable_prop_owned(prop_name) if selector == 0: self.properties[0][prop_name].player = trade_player else: for x in self.properties[selector]: if x.name == prop_name: x.player = trade_player self.money -= assets[0][1] self.money += assets[1][1] trade_player.money += assets[0][1] trade_player.money -= assets[1][1] self.jail_free -= assets[0][2] self.jail_free += assets[1][2] trade_player.jail_free += assets[0][2] trade_player.jail_free -= assets[0][2] except KeyError: print("Player does not exist.") return False @staticmethod def accept_trade(initiator, offered, trade): print(initiator.name + "trades:") for x in offered[0]: print(x) print("$" + str(offered[1])) if offered[2] > 0: print(str(offered[2]) + " get out of jail free cards.") print("for:") for x in trade[0]: print(x) print("$" + str(trade[1])) if trade[2] > 0: print(str(trade[2]) + " get out of jail free cards.") return True if input("Accept trade? y/n \n").lower() == "y" else False def variable_prop_owned(self, variable_prop, house=False): if variable_prop == "Electric Company" or variable_prop == "Water Works": if len(self.properties[1]) == 1: if variable_prop == self.properties[1][0].name: self.properties[1][0].mortgage() return 1 else: print("Property not owned.") return -1 elif len(self.properties[1]) == 2: for x in range(2): if variable_prop == self.properties[1][x].name: return 1 else: print("Property not owned.") return -1 elif variable_prop.find("Railroad") != -1 or variable_prop.find("Line") != -1: found = False for x in self.properties[2]: if x.name == variable_prop: found = True if found: return 2 else: print("Property not owned.") return -1 else: if variable_prop in self.properties[0]: if house: if self.properties[0][variable_prop].houses == 0 and self.properties[0][variable_prop].hotel == 0: return 0 else: return -1 return 0 else: print("Property not owned.") return -1 def roll_dice(self, counter=0): if not self.jail: print(self.name + "rolls dice.") Dice.throw() initial_position = self.position print(self.name + " rolled a " + str(Dice.roll[0] + Dice.roll[1])) if Dice.roll[0] == Dice.roll[1]: print("Rolled doubles.") if counter == 2: # If the player has previously already rolled 2 doubles, they are sent to jail. self.jailed() print("Double three times in a row. ", end="") else: go_check(initial_position, self) self.roll_dice(counter + 1) self.move_action() else: self.move_action() if initial_position > self.position > 0 and not self.jail: Go.action(self) else: choice = input("Roll for doubles (R), pay fine (F), or use card (C).\n") if choice.lower == "r": Dice.throw() if Dice.roll[0] == Dice.roll[1]: self.move_action() else: if self.jail_counter == 2: self.transaction(-50, "the Bank", True) self.move_action() else: self.jail_counter += 1 elif choice.lower == "f": self.transaction(-50, "the Bank", True) Dice.throw() self.move_action() elif choice.lower == "c": if self.jail_free > 0: self.jail_free -= 1 Dice.throw() self.move_action() else: print("No get out of jail free cards. Try again.") self.roll_dice() return else: print("Invalid choice. Try again") self.roll_dice() return for x in Player.player_list: # Checks the money of all players if x.money < 0: x.debt() def debt(self): while self.money < 0: print("Money = " + str(self.money)) choice = input("Sell, mortgage, trade with another player, or declare bankruptcy?\n") if choice.lower() == "sell": property_selling_count = 0 for x in self.properties[0]: if x.houses > 0 or x.hotel > 0: property_selling_count += 1 print(x.name + ' ' * (32 - len(x.name)), end="") if x.houses > 0: print(str(x.houses) + " houses") elif x.hotel > 0: print(str(x.hotel) + " hotel") print("") if property_selling_count > 0: property_selling = input("Select property to sell from.\n").title() try: self.properties[0][property_selling].sell_house() except KeyError: print("Property name invalid or unowned.") elif choice.lower() == "mortgage": for x in self.properties[0]: if self.properties[0][x].houses == 0: print(x) print("\n") for x in self.properties[1]: print(x.name) print("\n") for x in self.properties[2]: print(x.name) property_mortgaging = input("Select property to mortgage.\n").title() selector = self.variable_prop_owned(property_mortgaging) if selector != -1: if selector == 0: self.properties[0][selector].mortgage() else: for x in self.properties[selector]: if x.name == property_mortgaging: x.mortgage() elif choice.lower() == "trade": self.trade() def transaction(self, value, partner, trusted=False): if not trusted: if self.money + value >= 0 and Player.player_list[partner] - value >= 0: if value >= 0: print(partner + " paid " + value + " to " + self.name) elif value < 0: print(self.name + " paid " + value + " to " + partner) else: print("Not enough money!") else: self.money += value Player.player_list[partner].money -= value if self.money < 0: self.debt() elif Player.player_list[partner].money < 0: Player.player_list[partner].debt() def jailed(self): self.position = 10 self.jail = True print("Sent to jail.") class Tile: def __init__(self, name): self.name = name class Go(Tile): def __init__(self, name="GO"): Tile.__init__(self, name) @staticmethod def action(player): print("For passing or landing on Go, ", end="") player.transaction(200, "the Bank") class GotoJail(Tile): def __init__(self, name="Go to jail"): Tile.__init__(self, name) @staticmethod def action(player): print("Go to jail.") player.jailed() class CommunityChest(Tile): cards_list = {0: "Advance to \"GO\"", 1: "Bank error in your favour.", 2: "Doctor's fees.", 3: "Sale of stock.", 4: "Get out of jail free.", 5: "Go to jail.", 6: "Holiday fund matures.", 7: "Income tax refund.", 8: "It's your birthday.", 9: "Life insurance matures.", 10: "Hospital fees.", 11: "School fees.", 12: "Consultancy fee.", 13: "Street repairs.", 14: "2nd place in a beauty contest.", 15: "Inheritance."} def __init__(self, name="Community Chest"): Tile.__init__(self, name) @staticmethod def action(player): initial_position = player.position card = random.randint(0, len(CommunityChest.cards_list)) print(CommunityChest.cards_list[card]) if card == 0: player.position = 0 tiles[player.position].action(player) elif card == 1: player.transaction(200, "the Bank", True) elif card == 2: player.transaction(-50, "the Bank", True) elif card == 3: player.transaction(50, "the Bank", True) elif card == 4: player.jail_free += 1 del CommunityChest.cards_list[4] elif card == 5: player.position = 10 player.jailed() elif card == 6: player.transaction(100, "the Bank", True) elif card == 7: player.transaction(20, "the Bank", True) elif card == 8: for payer in Player.player_list: player.transaction(10, Player.player_list[payer], True) elif card == 9: player.transaction(100, "the Bank", True) elif card == 10: player.transaction(-50, "the Bank", True) elif card == 11: player.transaction(-50, "the Bank", True) elif card == 12: player.transaction(25, "the Bank", True) elif card == 13: houses = 0 hotels = 0 for x in range(0, len(player.properties[0])): houses += player.properties[0][x].houses hotels += player.properties[0][x].hotel player.transaction(-40 * houses - 115 * hotels, "the Bank", True) elif card == 14: player.transaction(10, "the Bank", True) elif card == 15: player.transaction(100, "the Bank", True) go_check(initial_position, player) class Chance(Tile): cards_list = {0: "Advance to \"GO\"", 1: "Advance to Illinois Avenue.", 2: "Advance to St. Charles Place.", 3: "Advance to nearest utility, and roll again to decide payment", 4: "Advance to nearest railroad. If owned, pay double to the owner.", 5: "Bank pays you.", 6: "Get out of jail free.", 7: "Go back three spaces.", 8: "Go to jail.", 9: "Make general repairs on your properties.", 10: "Pay poor tax.", 11: "Take a trip to Reading Railroad.", 12: "Go to Boardwalk.", 13: "Chairman. Pay each player $50.", 14: "Building loan matures.", 15: "You won a crosswords competition."} def __init__(self, name="CHANCE"): Tile.__init__(self, name) @staticmethod def action(player): # The actions for tiles are done per card as some properties do not follow the conventional flow. initial_position = player.position card = random.randint(0, len(CommunityChest.cards_list)) print(CommunityChest.cards_list[card]) if card == 0: player.position = 0 tiles[player.position].action(player) elif card == 1: player.position = 24 tiles[player.position].action(player) elif card == 2: player.position = 11 tiles[player.position].action(player) elif card == 3: if 13 < player.position < 29: player.position = 28 tiles[player.position].action(player) Dice.throw() else: player.position = 12 tiles[player.position].action(player) Dice.throw() elif card == 4: if 15 > player.position >= 5: player.position = 15 elif 25 > player.position >= 15: player.position = 25 elif 35 > player.position >= 25: player.position = 35 else: player.position = 5 if tiles[player.position].player != banker: # If the railroad is not owned by the bank, pay double. tiles[player.position].action(player) tiles[player.position].action(player) else: tiles[player.position].action(player) elif card == 5: player.transaction(50, "the Bank", True) elif card == 6: player.jail_free += 1 del Chance.cards_list[6] elif card == 7: player.position -= 3 tiles[player.position].action(player) elif card == 8: player.position = 10 player.jailed() elif card == 9: houses = 0 hotels = 0 for x in range(0, len(player.properties[0])): houses += player.properties[0][x].houses hotels += player.properties[0][x].hotel player.transaction(-25 * houses - 100 * hotels, "the Bank", True) elif card == 10: player.transaction(-15, "the Bank", True) elif card == 11: player.position = 5 tiles[player.position].action(player) elif card == 12: player.position = 39 tiles[player.position].action(player) elif card == 13: for payee in Player.player_list: player.transaction(-50, Player.player_list[payee], True) elif card == 14: player.transaction(150, "the Bank", True) elif card == 15: player.transaction(100, "the Bank", True) go_check(initial_position, player) class Property(Tile): def __init__(self, name, position, value, rent, prop_type): self.position = position self.prop_type = prop_type Tile.__init__(self, name) self.player = banker self.value = value self.rent = rent self.sold = False self.mortgaged = False def mortgage(self): if not self.mortgaged: self.player.transaction(self.value / 2, "the Bank") print("Mortgaged " + self.name) else: if self.player.transaction(math.ceil((self.value / 2) * 1.1), "the Bank"): print("Un-mortgaged" + self.name) else: print(self.name + "remains mortgaged") self.mortgaged = not self.mortgaged # This inversion nullifies the inversion done in the next line self.mortgaged = not self.mortgaged def action(self, player): if not self.sold: self.sell(player) else: if not self.mortgaged: player.transaction(self.rent, self.player, True) def bank_transfer(self, player): if self.prop_type > 0: self.player.properties[self.prop_type].remove(self) self.player = player player.properties[self.prop_type].append(self) elif self.prop_type == 0: del banker.properties[0][self.name] self.player = player player.properties[0][self.name] = self def sell(self, player): option = input("Buy or auction property?\n") if option.lower() == "buy": if player.money < self.value: print("Not enough money. Please auction.") self.sell(player) else: player.transaction(-self.value, "the Bank") self.bank_transfer(player) elif option.lower() == "auction": bid = 1 player_list_copy = list(Player.player_list) while len(player_list_copy) != 1: for player_num in range(len(player_list_copy)): choice = input("Bid or fold. Current bid: " + str(bid) + "\n") if choice == "fold": del player_list_copy[player_num] elif choice == "bid": new_bid = input("Enter bid. Current bid: " + str(bid) + "\n") if bid < new_bid <= player_list_copy[player_num].money: bid = new_bid else: print("Invalid bid. Try again.") player_num -= 1 else: print("Invalid input. Try again.") player_num -= 1 player_list_copy[0].transaction(-bid, "the Bank") self.bank_transfer(player) else: print("Please choose to buy or auction.") self.sell(player) class Colours(Property): # order of groups is brown, light blue, pink, orange, yellow, red, green, (dark) blue groups = [[], [], [], [], [], [], [], []] def __init__(self, name, position, value, rent): Property.__init__(self, name, position, value, rent, 0) self.const_rent = self.rent self.houses = 0 self.hotel = 0 self.set = False self.change = True self.group = math.floor(self.position / 5) banker.properties[0][self.name] = self self.house_value = math.floor((self.value + 20) / 80) * 50 if self.house_value == 250: # Boardwalk is the only exception, as it yields 250 self.house_value = 200 Colours.groups[self.group].append(self) def add_house(self): if self.hotel == 0: if self.player.money >= self.house_value: self.houses += 1 self.player.transaction(-self.house_value, "the Bank") print("One house bought.") else: print("No houses bought.") return if self.houses == 5: print("Traded five houses in for a hotel.") self.hotel += 1 self.change = True else: print("Already at maximum occupancy for this property.") def sell_house(self): if self.hotel > 0: self.hotel -= 1 self.player.transaction(self.house_value / 2, "the Bank") print("One hotel sold.") self.change = True elif self.houses > 0: self.houses -= 1 self.player.transaction(self.house_value / 2, "the Bank") print("One house sold.") else: print("No houses/hotel to sell. None sold.") def mortgage(self): if self.houses == 0 and self.hotel == 0: Property.mortgage(self) self.rent = 0 else: print("You own houses or hotels on this property. You must sell those before mortgaging.") def check_set(self): player = self.player for x in Colours.groups[self.group]: if x.player != player: self.set = False return def action(self, player): if self.player != banker: self.check_set() if self.change: self.rent = self.set_rent() self.change = not self.change Property.action(self, player) def set_rent(self): if self.houses == 0: self.change = not self.change return self.const_rent * 2 if self.set else self.const_rent elif self.houses == 1: if self.value == 320: # Pennsylvania Ave is the one outlier return 150 else: return self.const_rent * 5 elif self.houses == 2: if self.value == 120: return self.const_rent * 25 / 2 elif self.value == 320: return self.value * 225 / 14 elif 180 <= self.value < 240 or self.value == 350: return math.floor(self.const_rent * 10 / 7) * 10 else: return self.value * 15 elif self.houses == 3: if self.value == 120 or self.value == 200 or self.value == 240: return self.const_rent * 37.5 elif self.value < 120 or self.value == 140: return self.const_rent * 45 elif self.value <= 280: return math.ceil(self.value * 85 / 1400) * 50 elif self.value <= 400: return math.floor(self.value * 14 / 400 - 1) * 100 elif self.houses == 4: if self.value <= 60: return self.value * 80 elif self.value <= 120: return self.value / 2 * 5 + 150 elif self.value <= 140: return 625 elif self.value <= 180: return math.floor(self.value * 35 / 400) * 50 elif self.value == 200: return self.value * 4 elif self.value <= 280: return 5 / 2 * self.value + 325 elif self.value <= 320: return 5 * self.value - 400 elif self.value <= 400: return 8 * self.value - 1500 elif self.hotel == 1: if self.name == "Mediterranean Avenue": return 250 elif self.value <= 120: return 5 / 2 * self.value + 300 elif self.value <= 160: return 7.5 * self.value - 300 elif self.value <= 280: return 5 / 2 * self.value + 500 elif self.value <= 320: return 25 / 4 * self.value - 600 elif self.value <= 400: return 10 * self.value - 2000 class Utilities(Property): def __init__(self, name, position, value): Property.__init__(self, name, position, value, 0, 1) self.set = False self.rent = 0 banker.properties[1].append(self) def action(self, player): if self.player != player: self.rent = (Dice.roll[0] + Dice.roll[1]) * (4 if self.set else 10) Property.action(self, player) class Railroad(Property): def __init__(self, name, position): Property.__init__(self, name, position, 200, 25, 2) banker.properties[2].append(self) def action(self, player): if self.player != player: self.rent = 25 * (2 ** len(self.player.properties[2])) Property.action(self, player) class Tax(Tile): def __init__(self, name, rent): Tile.__init__(self, name) self.rent = rent def action(self, player): player.transaction(-self.rent, "the Bank", True) class Dice: roll = [0, 1] @staticmethod def throw(): Dice.roll[0] = random.randint(1, 6) Dice.roll[1] = random.randint(1, 6) def go_check(initial_position, player): if player.position < initial_position and not player.jail: Go.action(player) return True banker = Player("the Bank", 1000000) tiles = [Go("GO"), Colours("Mediterranean Avenue", 1, 60, 2), Colours("Baltic Avenue", 2, 60, 4), CommunityChest("Community Chest"), Tax("Income Tax", 200), Railroad("Reading Railroad", 5), Colours("Oriental Avenue", 6, 100, 6), Chance("Chance"), Colours("Vermont Avenue", 8, 100, 6), Colours("Connecticut Avenue", 9, 120, 8), Tile("Jail"), Colours("St. Charles Place", 11, 140, 10), Utilities("Electric Company", 12, 150), Colours("States Avenue", 13, 140, 10), Colours("Virginia Avenue", 14, 160, 12), Railroad("Pennsylvania Railroad", 15), Colours("St. James Place", 16, 180, 14), CommunityChest(), Colours("Tennessee Avenue", 18, 180, 14), Colours("New York Avenue", 19, 200, 16), Tile("Free Parking"), Colours("Kentucky Avenue", 21, 220, 18), Chance(), Colours("Indiana Avenue", 23, 220, 18), Colours("Illinois Avenue", 24, 240, 20), Railroad("B. & O. Railroad", 25), Colours("Atlantic Avenue", 26, 260, 22), Colours("Ventnor Avenue", 27, 260, 22), Utilities("Water Works", 28, 150), Colours("Marvin Avenue", 29, 280, 24), GotoJail(), Colours("Pacific Avenue", 31, 300, 26), Colours("North Carolina Avenue", 32, 300, 26), CommunityChest(), Colours("Pennsylvania Avenue", 34, 320, 28), Railroad("Short Line", 35), Chance(), Colours("Park Place", 37, 350, 35), Tax("Luxury Tax", 100), Colours("Boardwalk", 39, 400, 50)] banker.list_all()
range(3) == [0, 1, 2] >>> for i in range(5): ... print(i) ... 0 1 2 3 4
""" Given an array A[ ], find maximum and minimum elements from the array. Input: The first line of input contains an integer T, denoting the number of testcases. The description of T testcases follows. The first line of each testcase contains a single integer N denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array. Output: For each testcase in a new line, print the maximum and minimum element in a single line with space in between. Example: Input: 2 4 5 4 2 1 1 8 Output: 5 1 8 8 Explanation: Testcase 1: Maximum element is: 5 Minimum element is: 1 """ def getMinimumMaximumElement(n, arr): return " ".join([str(max(arr)), str(min(arr))]) if __name__ == '__main__': t = int(input()) for i in range(t): n = int(input()) arr = list(map(int, input().split())) print(getMinimumMaximumElement(n, arr))
""" Given a array of length N, at each step it is reduced by 1 element. In the first step the maximum element would be removed, while in the second step minimum element of the remaining array would be removed, in the third step again the maximum and so on. Continue this till the array contains only 1 element. And print that final element remaining in the array. Input: The first line contains a single integer T i.e. the number of test cases. The first line of each test case consists of a single integer N. The second and last line of each test case contains the N spaced integers . Output: Fore each test case in new line print the final remaining element in the array. Example: Input: 2 7 7 8 3 4 2 9 5 8 8 1 2 9 4 3 7 5 Ouput: 5 4 Explanation: Test Case 1: In first step '9' would be removed, in 2nd step '2' will be removed, in third step '8' will be removed and so on. So the last remaining element would be '5'. """ def removeMaxandMinElement(arr, n): arr.sort() index = n//2 return arr[index] if n%2 != 0 else arr[index-1] if __name__=='__main__': t = int(input()) for i in range(t): n = int(input()) arr = list(map(int, input().split())) print(removeMaxandMinElement(arr, n))
""" Given an Array, Find the maximum sun sub-array I/P: a = [1, 2, 5, -7, 1, 2] O/P: [1, 2, 5] Explanation: sum of sub array [1, 2, 5] is 8 and it is maximum sum of all sub-array of given array. """ def get_max_sum_subarray(arr): maxi = 0 element_sum = 0 main_max = 0 temp = [] for i in arr: element_sum += i print(maxi, element_sum) if maxi < element_sum: maxi = element_sum main_max = maxi temp.append(i) elif maxi > element_sum: element_sum = 0 # maxi = 0 temp = [] # print(maxi, element_sum) return main_max, temp if __name__ == "__main__": a = [-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7] print(get_max_sum_subarray(a))
""" 1. You are given an array A of size N. You need to print elements of A in alternate order. https://practice.geeksforgeeks.org/problems/print-alternate-elements-of-an-array/1 The first line of input contains T denoting the number of testcases. T testcases follow. Each test case contains two lines of input. The first line contains N and the second line contains the elements of the array. """ def printAL(arr, n): for i in range(0, n, 2): print(arr[i]) if __name__ == "__main__": t = int(input()) for i in range(t): n = int(input()) arr = list(map(int, input().split())) printAL(arr, n)
import unittest # 1.1 - O(n) def all_unique(string): return len(set(string)) == len(string) # 1.2 O(n) def reverse_string(string): return string[::-1] # rev = "" # length = len(string) # for i in range(length)[::-1]: # rev += string[i] # return rev # 1.3 - should be O(n), two passes through both strings def is_permutation(first, second): return len(first) == len(second) and set(first) == set(second) # 1.4 - should be O(n), two passes through the string def replace_spaces(string, length): return string.replace(" ", "%20") # 1.6 - should be O(n^2), minimum you touch every element in the matrix def rotate_matrix(matrix, N): for layer in range(N/2): # indices for rows first = layer last = N - first - 1 for i in range(first, last): offset = i - first # for iterating backwards in a list temp = matrix[first][i] matrix[first][i] = matrix[i][last] matrix[i][last] = matrix[last][offset] matrix[last][offset] = matrix[offset][first] matrix[offset][first] = temp return matrix class Test_Stuff(unittest.TestCase): # 1.1 def test_all_unique(self): self.assertEquals(all_unique("hello"), False) self.assertEquals(all_unique("ll"), False) self.assertEquals(all_unique(""), True) self.assertEquals(all_unique("obligatory"), False) self.assertEquals(all_unique("sharp"), True) # 1.2 def test_reverse_string(self): self.assertEquals(reverse_string(""), "") self.assertEquals(reverse_string("a"), "a") self.assertEquals(reverse_string("ab"), "ba") self.assertEquals(reverse_string("abc"), "cba") def test_permutations(self): self.assertTrue(is_permutation("hello", "holle")) self.assertTrue(is_permutation("", "")) self.assertFalse(is_permutation("hello", "hole")) self.assertFalse(is_permutation("aaaa", "aaa")) # 1.4 def test_replace_spaces(self): string = "Hi my name is Albert " replaced = 'Hi%20my%20name%20is%20Albert%20%20%20' self.assertEquals(replace_spaces(string, len(string)), replaced) # 1.6 def test_rotate_matrix(self): matrix = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] rotated = [[0, 5, 6], [1, 4, 7], [2, 3, 8]] self.assertEquals(rotate_matrix(matrix, 3), rotated) if __name__ == "__main__": unittest.main()
from typing import Callable, Any counter_records = dict() def counter(func: Callable) -> Callable: def wrapped_func(*args, **kwargs) -> Any: func_to_call = func(*args, **kwargs) func_name = func.__name__ if func_name in counter_records: counter_records[func_name] += 1 else: counter_records[func_name] = 1 print(f'На данный момент функция {func_name} была вызвана уже {counter_records[func_name]} раз') return func_to_call return wrapped_func @counter def two_plus_two() -> int: return 4 @counter def valera_go(number) -> int: return number * 2 for x in range(10): two_plus_two() valera_go(2) for y in range(20): valera_go(2) for keys, values in counter_records.items(): print(keys, values)
from itertools import combinations, chain def powerset(iterable): ''' Generate the powerset (set of all subsets) of a given iterable. ''' initialSet = list(iterable) return chain.from_iterable(combinations(intialSet, subSetSize) for subSetSize in range(len(intialSet) + 1)) def contains_edges(graph, nodeset): ''' Check for edges between selected nodes in a graph Return true if an edge is found, otherwise false. ''' for node in nodeset: for neighbour in graph[node]: if neighbour in nodeset: return True return False def isThreeColourable(graph): ''' Determines whether a given graph is three colourable. Arguments: graph -- the adjacency list of a graph Returns: True if the graph is three colourable otherwise False ''' V = set(graph.keys()) for rnodes in powerset(V): rset = set(rnodes) if not contains_edges(graph, rset): for gnodes in powerset(V - rset): gset = set(gnodes) if not contains_edges(graph, gset): bset = set(V - rset - gset) if not contains_edges(graph, bset): return True return False if __name__ == '__main__': GRAPH1 = {0: set([1, 2]), 1: set([0, 2]), 2: set([0, 1])} GRAPH2 = {0: set([1, 2, 3]), 1: set([0, 2, 3]), 2: set([0, 1, 3]), 3: set([0, 1, 2])} GRAPH3 = {0: set([1, 2, 4, 5]), 1: set([0, 2, 3, 5]), 2: set([0, 1, 3, 4]), 3: set([1, 2, 4, 5]), 4: set([0, 2, 3, 5]), 5: set([0, 1, 3, 4])} GRAPH4 = {1: set([2, 8]), 2: set([1, 3, 4, 6, 8]), 3: set([2, 4]), 4: set([2, 3, 5, 6, 8]), 5: set([4, 6]), 6: set([2, 4, 5, 7, 8]), 7: set([6, 8]), 8: set([1, 2, 4, 6, 7])} print(isThreeColourable(GRAPH1)) print(isThreeColourable(GRAPH2)) print(isThreeColourable(GRAPH3)) print(isThreeColourable(GRAPH4))
#Task 12 #Bond and Investment calculator #Programmer: Berto Swanepoel #This program will help anyone to calculate investment as well as calculate you monthly installment when wanting to buy a house. import math #This part is where you ask the user to make decision, I have also explained to the user what the meaning of both words are. print("Choose either 'investment' or 'bond' from the menu below to proceed: ") print("investment - to calculate the amount of interest you'll earn on interest.") print("bond - to calculate the amount you'll have to pay on a home loan.") #The user's decision in stored in a variable call choice as this is he's or her's choice. It does not matter how the user enters the word as #it will automatically be changed to lowercase. choice = str(input("Please enter one of the following: (invest or bond) : ")).lower() #This is a veriable with no input or value for now, it will be used later in the program. interest_type = "" #If the user's decision is invest the ask the following information. #How much do they want to use as a starting deposit. #What is the investment rate that the bank is offering them. This must be entered without the decimal. #Then the user must enter the amount of year's they wish do have this investment. #Once we have that information we need to know how the investment will be structured, nl: simple or compound. #Lastly the investment rate is devided by 100 to get the decimal value needed for calculations. if choice == "invest": deposit = float(input("Please enter the your deposit amount: ")) i_rate = float(input("Please enter the interest rate: (Only enter the number): ")) years = float(input("Please enter the amount of years that you'll be investing: ")) interest_type = str(input("Please choose between 'simple' or 'compound' interest: (simple or compound) : ")).lower() i_r = float(i_rate /100) #If the user has chosen the bond option, we will be needing some information so we will have to ask the user. #We will need to know what is the value of the house, or what is the loan amount. #What is the interest rate that the user is getting from the bank per year. #How many months will the user be needing to pay of the house bond. #Interest rate is now devided by 12 to get a monthly interest rate value. #Once all that information has been given the calculation can be made. #Now we print our the result along with a little sentance stating the monthly installment based on user's information. elif choice == "bond": house = float(input("Please enter the current value of the house: ")) b_rate = float(input("Please enter the interest rate only enter the number: ")) months = float(input("Please enter the number of months you would to repay: ")) b_r = float(b_rate / 12) repayment = house * ((b_r * (1 + b_r) ** months )/(((1 + b_r) ** months ) - 1)) print("Your monthly installment will be R " + str(repayment)) #This to to make sure that user enters either invest or bond, in the case where user does not anything the program will stop and prompt the #that they have not entered anything. if not choice.isalpha(): print ("You haven’t entered anything, please try again.") #If user chose invest at the beginning and then also chose simple investment, the information from all the questions will then used in the #calcuations below. The result will be printed. elif interest_type == "simple": interest =(deposit * (1 + i_r * years)) print("Your total interest earned with " + interest_type + " will be, R " + str(interest)) #If user chose invest at the beginning and then also chose compound investment, the information from all the questions will then used in the #calcuations below. The result will be printed. elif interest_type == "compound": interest = (deposit * math.pow ((1+i_r),(years*1))) print("Your total interest earned with " + interest_type + " will be, R " + str(interest))
import random lista = ['PEDRA', "PAPEL", "TESOURA"] jogador = str(input("Escolha pedra, papel ou tesoura: ")).upper() computador = random.choice(lista) if jogador == "PEDRA" and computador == "TESOURA" or jogador == "TESOURA" and computador == "PAPEL" or jogador == "PAPEL" and computador == "PEDRA": print(f"O jogador venceu! Ele escolheu {jogador} e o computador {computador}") elif computador == "PEDRA" and jogador == "TESOURA" or computador == "TESOURA" and jogador == "PAPEL" or computador == "PAPEL" and jogador == "PEDRA": print(f"O computador venceu! Ele escolheu {computador} e o jogador {jogador}") else: print(f"EMPATE! Jogador escolheu {jogador} e computador escolheu {computador}")