text
stringlengths
37
1.41M
tup=(1,2,3,4,5,6,7,8,9,10) def print_even(tup): for i in range(10): if tup[i] % 2 ==0: print(tup[i]) print_even(tup)
a=int(input()) class gen(): def gent(self,a): n=1 while n<=a: if n % 7 == 0: yield n n+=1 obj=gen() obj.gent(a) for i in obj.gent(a): print(i)
print("number of lines want to capilatize") t=int(input()) ls=[] # tr='' for i in range (t): a=input() # tr=a.split(" ") ls.append(a) for item in ls: print(item.upper())
def dic_val(): lis=[] for c in range (21): lis.append(c*c) # for c in range (5): # print(dic[c],end=" ") return lis print(dic_val())
S = 'chungus' def revstr(S): if len(S) == 1 : return S else : return S[-1] + revstr(S[:-1]) print(revstr(S))
iterable_here = "Andy Rulz" for variable_here in iterable_here: print(variable_here) #actions here print("Is shorthand for:") it = iter(iterable_here) while True: try: variable_here = next(it) #declare variable_here except StopIteration: break #break out of the loop if we're done print(variable_here) #actions here
f = open('filelooper.txt', 'w') f.write("Hi there. \n\ I am a competer. \n\ Are you a human or a computer?") f.close() f = open('filelooper.txt') temp = 'start' while temp != '': temp = f.read(3) print(temp) print("\n**\n") f.close() #seek(0) ---> sets the file's current position at the offset
import random, time def draw_to_screen(content): print("\n"*50) print(content) time.sleep(0.2) def noise_bars(n, w): result = "" list_of_numbers = [] for i in range(n): list_of_numbers.append(random.randint(1,w)) while len(list_of_numbers) > 0: next_number = list_of_numbers.pop() result += "*"*next_number + "\n" return result for i in range(60): draw_to_screen(noise_bars(18, 40))
total = 1 def hundredforward (n): if n < 100: global total total = total * n return hundredforward(n+3) else: return total print(hundredforward(1))
people = [{"name":"Andy", "rel_stat":"married"}, {"name":"Sara", "rel_stat":"married"}, {"name":"Simone", "rel_stat":"single"}] print("Count married people") print(list(map(lambda x: x["rel_stat"], people))) print(list(map(lambda x: 1 if x["rel_stat"] == "married" else 0, people))) print(sum(map(lambda x: 1 if x["rel_stat"] == "married" else 0, people))) print("Evaluate a polynomial at many points:") for i in map(lambda x: x**3 + 2*x -1, range(11)): print(i)
n = input("Pick a number please: ") for i in range (1, n+1): print (i*i)
""" Read file into texts and calls. It's ok if you don't understand how to read files. """ import csv import re with open('texts.csv', 'r') as f: reader = csv.reader(f) texts = list(reader) with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) """ TASK 3: (080) is the area code for fixed line telephones in Bangalore. Fixed line numbers include parentheses, so Bangalore numbers have the form (080)xxxxxxx.) Part A: Find all of the area codes and mobile prefixes called by people in Bangalore. - Fixed lines start with an area code enclosed in brackets. The area codes vary in length but always begin with 0. - Mobile numbers have no parentheses, but have a space in the middle of the number to help readability. The prefix of a mobile number is its first four digits, and they always start with 7, 8 or 9. - Telemarketers' numbers have no parentheses or space, but they start with the area code 140. Print the answer as part of a message: "The numbers called by people in Bangalore have codes:" <list of codes> The list of codes should be print out one per line in lexicographic order with no duplicates. Part B: What percentage of calls from fixed lines in Bangalore are made to fixed lines also in Bangalore? In other words, of all the calls made from a number starting with "(080)", what percentage of these calls were made to a number also starting with "(080)"? Print the answer as a part of a message:: "<percentage> percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore." The percentage should have 2 decimal digits """ def extract_bangalore_calls(calls): phonebook={} for record in calls: bangalore_match=re.match(r'\(080\)',record[0]) area_code_match=re.match(r'\(0\d+\)',record[1]) mobile_match=re.match(r'(7|9|8)\d{3}',record[1]) telemarketers_match=re.match(r'(140)',record[1]) if bangalore_match: if phonebook.get(record[0]): if area_code_match: phonebook[record[0]].add(area_code_match.group(0)) elif mobile_match: phonebook[record[0]].add(mobile_match.group(0)) elif telemarketers_match: phonebook[record[0]].add(telemarketers_match.group(0)) else: phonebook[record[0]]=set() if area_code_match: phonebook[record[0]].add(area_code_match.group(0)) elif mobile_match: phonebook[record[0]].add(mobile_match.group(0)) elif telemarketers_match: phonebook[record[0]].add(telemarketers_match.group(0)) return phonebook def part_a(calls): phonebook=extract_bangalore_calls(calls) codes=set() for key in phonebook: codes=codes.union(phonebook[key]) codes=sorted(list(codes)) for i,code in enumerate(codes): codes[i]+='\n' code_string=''.join(codes) print("The numbers called by people in Bangalore have codes:\n{}".format(code_string)) #Part B part_a(calls) def part_b(calls): phonebook={} count=0 for record in calls: pattern=re.compile(r'\(080\)') calling=pattern.match(record[0]) if calling: count+=1 recieving=pattern.match(record[1]) if calling and recieving: phonebook[record[0]]=phonebook.get(record[0],0)+1 no_calls=list(phonebook.values()) total=0. for value in no_calls: total+=value percentage=round((total/count) * 100,2) print("{} percent of calls from fixed lines in Bangalore are calls to other fixed lines in Bangalore.".format(percentage)) part_b(calls) """ calculating the time complexity for the extract_bangalore_calls algorithm: It has a single for loop that runs for n in the worst case Assume in the worst case all conditionals are checked f(n)=2 + 20(n) O(f(n))=20n + 2 approximately O(n) Time complexity for part_a there are two for loops and since they are not nested on the worst case they in the range of n which is the input size assume in the worst case, the size of the dictionary and the set are equal with combined size n f(n)=n+ 4 + 2*n =3n + 5 O(f(n))=3n + 5 O(f(n)) can be approximated to O(n) Time complexity for part_b Two for loops that run on worst case in time n f(n)=6+ 7*n + n =8n + 6 approximated as O(n) """
import math def is_leap_year(year): if year%4 !=0: return False elif year%100 !=0: return True elif year%400 !=0: return False else: return True def days_between_dates(birth_date,current_date): """Calculates the age in days based on the values provided Args: arg1: string containg the birth date in the form '10,June,1994' arg2: string containing the current date in the form '10,June,2019' return value: a string describing the age in days """ try: birthday,birth_month,birth_year=birth_date.split(',') birthday=int(birthday) birth_month=birth_month.title() birth_year=int(birth_year) current_day,current_month,current_year=current_date.split(',') current_day=int(current_day) current_month=current_month.title() current_year=int(current_year) if birth_year>current_year: raise months=['January', 'February', 'March', 'April', 'May','June', 'July', 'August', 'September', 'October','November', 'December'] days_in_month=[31,28,31,30,31,30,31,31,30,31,30,31] is_leap=is_leap_year(birth_year) birth_month_index=months.index(birth_month) current_month_index=months.index(current_month) #To calculate days lived in years inbetween the birth year and the current year if birth_year==current_year: days_lived_inbetween=0 else: days_lived_inbetween=0 for year in range(birth_year+1,current_year): if(is_leap_year(year)): days_lived_inbetween+=366 else: days_lived_inbetween+=365 #To calculate days lived in the year of birth days_passed_before_birth=0 for i in range(birth_month_index): days_passed_before_birth+=days_in_month[i] if(is_leap): days_lived_in_birth_year=366-(days_passed_before_birth+birthday) else: days_lived_in_birth_year=365-(days_passed_before_birth+birthday) #To calculate days lived in current year up to the present day days_lived_in_current_year=0 for i in range(current_month_index): days_lived_in_current_year+=days_in_month[i] if (is_leap_year(current_year)) and current_month_index>2: days_lived_in_current_year=days_lived_in_current_year+current_day+1 else: days_lived_in_current_year=days_lived_in_current_year+current_day #To calculate total age in days if birth_year==current_year: age=abs(days_lived_in_current_year-(days_passed_before_birth+birthday)) else: age=days_lived_inbetween+days_lived_in_birth_year+days_lived_in_current_year string='You have lived for {} day(s). Congratulations!'.format(age) return age except Exception as e: print('\n {}:please use the prescribed input format'.format(e)) def test(): test_cases=[(('30,september,2012','30,october,2012'),31), (('1,january,2012','1,january,2013'),366), (('1,september,2012','4,september,2012'),4), (('1,january,2013','31,december,1999'),"AssertionError")] for (args, answer) in test_cases: try: result = days_between_dates(*args) if result == answer and answer != "AssertionError": print("Test case passed!") else: print("Test with data:", args, "failed") except AssertionError: if answer == "AssertionError": print("Nice job! Test case {0} correctly raises AssertionError!\n".format(args)) else: print("Check your work! Test case {0} should not raise AssertionError!\n".format(args)) test() #print(days_between_dates('1,january,2012','1,january,2013'))
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str(self.value) class LinkedList: def __init__(self, head=None): self.head = head def append(self, value): if self.head is None: self.head = Node(value) return node = self.head while node.next is not None: node = node.next node.next = Node(value) def __iter__(self): current=self.head while current: yield current.value current=current.next def create_linked_list(arr): if len(arr)==0: return None l_list=LinkedList() for data in arr: l_list.append(data) return l_list def swap_nodes(head,left_index,right_index): """ :param: head- head of input linked list :param: left_index - indicates position :param: right_index - indicates position return: head of updated linked list with nodes swapped TODO: complete this function and swap nodes present at left_index and right_index Do not create a new linked list """ current=head count=0 left_node=None right_node=None before_left=None before_right=None if left_index>right_index or left_index==right_index: return head while current: if count==left_index: left_node=current if (left_index-count) == 1: before_left=current if (right_index-count) == 1: before_right=current if count==right_index: right_node=current break count+=1 current=current.next if before_left is None: head=right_node else: before_left.next=right_node before_right.next=left_node temp=left_node.next left_node.next=right_node.next right_node.next=temp return head arr = [3, 4, 5, 2, 6, 1, 9] solution =[3, 4, 5, 6, 2, 1, 9] l_list= create_linked_list(arr) left_index = 3 right_index = 4 updated_head=swap_nodes(l_list.head,left_index,right_index) print("Pass" if list(l_list)==solution else "Fail") l_list.head=updated_head print(list(l_list))
import math import random import scripting.py def main(): print(math.pow(2,3)) def generate_password(): try: word_list=[] with open('words_list.txt','r') as f: for line in f: word_list.append(line.strip('\n')) password_list=random.sample(word_list,3) password=''.join(password_list) return password except Exception as e: print('\n{}: check if file exists '.format(e)) print(generate_password()) if __name__=='__main__': main()
#!/usr/bin/python3 """ Given an array A of N numbers (integers), you have to write a program which prints the sum of the elements of array A with the corresponding elements of the reverse of array A. If array A has elements [1,2,3], then reverse of the array A will be [3,2,1] and the resultant array should be [4,4,4]. Input Format: The first line of the input contains a number N representing the number of elements in array A. The second line of the input contains N numbers separated by a space. (after the last elements, there is no space) Output Format: Print the resultant array elements separated by a space. (no space after the last element) Example: Input: 4 2 5 3 1 Output: 3 8 8 3 """ num = int(input()) a = list(map(int,input().split())) for i in range(num): if(i != num-1): print(a[i]+a[-i-1],end=" ") if(i == num-1): print(a[0]+a[num-1],end="")
#!/usr/bin/python3 """ Given a list of numbers (integers), find second maximum and second minimum in this list. Input Format: The first line contains numbers separated by a space. Output Format: Print second maximum and second minimum separated by a space Example: Input: 1 2 3 4 5 Output: 4 2 """ ls = list(map(int,input().split(' '))) ls.sort() print(ls[len(ls)-2],ls[1])
#!/usr/bin/python3 """ You are provided with the number of rows (R) and columns (C). Your task is to generate the matrix having R rows and C columns such that all the numbers are in increasing order starting from 1 in row wise manner. Input Format: The first line contain two numbers R and C separated by a space. Output Format: Print the elements of the matrix with each row in a new line and elements of each row are separated by a space. NOTE: There should not be any space after the last element of each row and no new line after the last row. Example: Input: 3 3 Output: 1 2 3 4 5 6 7 8 9 """ m,n = map(int,input().split()) num = 1 for i in range(m): for j in range(n-1): print(num,end=" ") num += 1 if ( num == m*n ): print(num,end="") else: print(num) num += 1
#!/usr/bin/python3 """ Write a program to convert a square matrix into a lower triangular matrix. Input Format: The first line of the input contains an integer number n which represents the number of rows and the number of columns. From the second line, take n lines input with each line containing n integer elements. Elements are separated by space. Output format: Print the elements of the matrix with each row in a new line and each element separated by a space. Example 1: Input: 3 1 2 3 4 5 6 7 8 9 Output: 1 0 0 4 5 0 7 8 9 n = int(input()) ls = [list(map(int,input().split())) for i in range(n)] for i in range(n): for j in range(n): if ( i < j ): print('0',end=" ") else: print(ls[i][j],end=" ") print() """ n=int(input()); a=[list(map(int,input().split())) for i in range(n)]; for i in range(n): for j in range(n): end = '' if j == n-1 else ' '; if(i<j): print(0, end=end); else: print(a[i][j], end=end); end = '' if i == n-1 else '\n'; print('',end=end);
import math from abc import abstractmethod from utils import Vector, Position GRAVITAIONAL_CONSTANT = .001 class Object: def __init__(self, radius, density, position, velocity=Vector(), colour=(0,0,255)): self.__radius = radius self.__density = density self.position = position self.velocity = velocity self.colour = colour @property def area(self): return 2 * math.pi * (self.__radius ** 2) @property def mass(self): return self.__density * self.area @property def radius(self): return self.__radius def update_pos(self): new_x = self.velocity.magnitude*math.sin(self.velocity.angle) new_y = self.velocity.magnitude*math.cos(self.velocity.angle) self.position = Position(self.position.x_pos + new_x, self.position.y_pos + new_y) def update_velocity(self, v2): self.velocity += v2 @abstractmethod def display(self, screen): pass @staticmethod def gravitational_force(obj1, obj2): magnitude = (GRAVITAIONAL_CONSTANT * obj1.mass * obj2.mass) / obj1.position.distance(obj2.position) dx = obj1.position.x_pos - obj2.position.x_pos dy = obj1.position.y_pos - obj2.position.y_pos angle = math.atan2(-dy, dx) return Vector(magnitude, angle)
for tc in range(1, int(input())+1): n = int(input()) list1 = list(map(int, input().split())) list1.sort() list2 = list1[::-1] result = [] for i in range(5): result.append(list2[i]) result.append(list1[i]) print('#{}'.format(tc), end = ' ') for i in result: print(i, end = ' ') print()
# -*- coding: utf-8 -*- """ Created on Wed Mar 11 20:31:08 2020 @author: 86158 """ #import n, start the loop temp=input('please input a positive integer:') n = int(temp) print(n,"-") while n>1 : #judge n even or odd, give different operations #if the number is even if n%2==0: n=n/2 print(n,"-") #if the number is odd else: n=n*3+1 print(n,"-")
# -*- coding: utf-8 -*- """ Created on Mon May 11 21:25:14 2020 @author: 86158 """ #input necessary library import pandas as pd #input 3 protein sequence human='MLSRAVCGTSRQLAPVLAYLGSRQKHSLPDLPYDYGALEPHINAQIMQLHHSKHHAAYVNNLNVTEEKYQEALAKGDVTAQIALQPALKFNGGGHINHSIFWTNLSPNGGGEPKGELLEAIKRDFGSFDKFKEKLTAASVGVQGSGWGWLGFNKERGHLQIAACPNQDPLQGTTGLIPLLGIDVWEHAYYLQYKNVRPDYLKAIWNVINWENVTERYMACKK' mouse='MLCRAACSTGRRLGPVAGAAGSRHKHSLPDLPYDYGALEPHINAQIMQLHHSKHHAAYVNNLNATEEKYHEALAKGDVTTQVALQPALKFNGGGHINHTIFWTNLSPKGGGEPKGELLEAIKRDFGSFEKFKEKLTAVSVGVQGSGWGWLGFNKEQGRLQIAACSNQDPLQGTTGLIPLLGIDVWEHAYYLQYKNVRPDYLKAIWNVINWENVTERYTACKK' random='WNGFSEWWTHEVDYNQKLTIENNQRPKIHEHEQWGLRQSPPPPKLCCPTCQMCERMRHQNRFAPLMEVGCRCMCWFHDWWVISVGTWLHTVIMYMMWPKRFHHNECPKACFRTTYTRKNHHALYWMLFEMCCYDQDVVWSKTHIFTTVRDIEVYVEQVFFIWGPLCHVAIACYEPVKTIRRRIPMYLCRHCIRGDNSYLLACCSIIYYFYHHMSYYGVLDIL' #read the "BLOSUM62 matrix.csv" as a dataframe matrix=pd.read_csv("BLOSUM62matrix.csv") #set up a function to find the amino acid(aa) in the matrix def find_row_num(aa): j=0 while True: if matrix.iloc[j,0]!=aa: j+=1#position j not the amino acid we need, then move on if matrix.iloc[j,0]==aa: break#find the amino acid return j#result of the function #comparison of two sequences that you want to compare temp1=input('please input human/mouse/random:' ) seq1=locals()[temp1] temp2=input('please input human/mouse/random:' ) seq2=locals()[temp2] #calculate the hamming distance distance=0 #set initial distance as zero for i in range(len(seq1)): #compare each amino acid one by one if seq1[i]!=seq2[i]: distance+=1 #add a score 1 if amino acids are different percent=(len(seq1)-distance)/len(seq1) score=0#variable for storing the blosum score alignment=''#variable for storing the BLAST-like visual alignment for i in range(len(seq1)): aa1=seq1[i] aa2=seq2[i] #use the function to retrieve the score according to 2 amino acids from seq1 and seq2 score_plus=matrix.loc[find_row_num(aa2),aa1] #calculate the total score score+=score_plus #calculate the BLAST-like visual alignment if aa1==aa2: alignment+=aa1 elif score_plus>=0: alignment+='+' else: alignment+=" " #print out the result print("the hamming distance of two sequence is "+str(distance)) print(str(percent*100)+"%"+" of the amino acids are identical.") print("the blosum62 score is "+str(score)) print("seq1:"+seq1) print("#vis:"+alignment) print("seq2:"+seq2)
import random import dicts class WordFactory(object): def element(self, type): if type == "SimpleWord": return SimpleWord() elif type == "Password": return Password() elif type == "Noun": return Noun() elif type == "Verb": return Verb() elif type == "Adjective": return Adjective() assert 0, "Bad word creation: " + type class SimpleWord(WordFactory): value = "Word" length = len(value) class Password(WordFactory): value = "Password1234" length = len(value) class Noun(WordFactory): value = dicts.nouns[random.randint(0, len(dicts.nouns)-1)] length = len(value) class Verb(WordFactory): value = dicts.verbs[random.randint(0, len(dicts.verbs)-1)] length = len(value) class Adjective(WordFactory): value = dicts.adjectives[random.randint(0, len(dicts.adjectives)-1)] length = len(value)
def chartoint (c): return ord(c) - ord("A") + 10 if c.isalpha() else int(c) def baseConversion(numStr,radix): result=0 for i,char in enumerate(reversed(numStr)): res = chartoint(char) if res>radix: return -1 result = result + res * radix ** i return result print baseConversion('AF',16)
valor = float(input('Qual o valor da casa? ')) sal = float(input('Qual o seu salário? ')) anos = int(input('Em quantos anos pagará a casa? ')) pres = valor / (anos * 12) if pres > (0.3 * sal): print('Empréstimo negado. A prestação seria de R${:.2f}.'.format(pres)) else: print('Empréstimo aprovado')
pro = float(input('Qual o valor do produto? ')) print('''Formas de pagamento: [ 1 ] à vista: dinheiro ou cheque [ 2 ] à vista, no cartão [ 3 ] 2x no cartão [ 4 ] 3x ou mais no cartão''') meio = int(input('Qual o meio de pagamento? ')) if meio == 1: print('O valor fica R${}.'.format(pro -(pro*0.1))) elif meio == 2: print('O valor fica R${}.'.format(pro-(pro*0.15))) elif meio == 3: print('O valor fica R${}.'.format(pro)) elif meio == 4: print('O valor fica R${}.'.format(pro+(pro*0.2))) else: print('Opção inválida.')
nome = input('Digite o nome: ').strip() print('Seu nome tem Silva? {}'.format()) # in é um operador do python, não um método. print('silva' in nome.lower())
#nome = input('Digite seu nome completo: ').strip() #n = nome.split() #print('Seu primeiro nome é {}'.format(n[0])) #print('Seu último nome é {}'.format(n[len(n)-1])) #print('{}'.format(nome[:5])) print(19 // 2) print(19 % 2)
#!/usr/bin/python3.6 # --coding:Utf- - import pymysql import pandas as pd import sys import site site.addsitedir('/home/hsaid/Bureau/scripts/python/jeu_video') from dbHelpers import * def mysql_to_csv(sql, file_path, con): ''' The function creates a csv file from the result of SQL in MySQL database. ''' try: df = pd.read_sql(sql, con) df.to_csv(file_path, encoding='utf-8', header = True,\ doublequote = True, sep=',', index=False) print('File, {}, has been created successfully'.format(file_path)) con.close() except Exception as e: print('Error: {}'.format(str(e))) sys.exit(1) def csv_to_mysql(load_sql, con): ''' This function load a csv file to MySQL table according to the load_sql statement. ''' try: cursor = con.cursor() cursor.execute(load_sql) print('successfully loaded the table from csv.') con.close() except Exception as e: print('Error: {}'.format(str(e))) sys.exit(1) def csv_integrity(InFileName, OutFileName): NumCommas = 0 numberOfLines = 0 print("Checking file") try: File = open(InFileName,'r') for line in File: if line.count(',') > NumCommas: NumCommas = line.count(',') #return to the start of the file File.seek(0) OutFile = open(OutFileName, 'w') for line in File: OutFile.write(line.rstrip() + ',' * (NumCommas - line.count(',')) + '\n') numberOfLines += 1 OutFile.close() File.close() except Exception as e: print('Error: {}'.format(str(e))) sys.exit(1) print(numberOfLines, "lines processed",)
"""节点""" class Node(object): def __init__(self, item): self.elem = item self.next = None self.prev = None """双向链表""" class DoubleLinkList(object): def __init__(self, node=None): self.__head = node """链表是否为空""" def is_empty(self): return self.__head is None """链表长度""" def length(self): # cur游标,用来移动遍历节点 cur = self.__head # counter:记录数量 counter = 0 while cur != None: counter += 1 cur = cur.next return counter """链表尾部添加节点,尾插法""" def append(self, item): node = Node(item) if self.is_empty(): self.__head = node else: cur = self.__head while cur.next != None: cur = cur.next cur.next = node node.prev = cur """链表头部添加节点,头插法""" def add(self, item): node = Node(item) node.next = self.__head self.__head = node node.next.prev = node """任意位置添加节点""" def insert(self, pos, item): # pos的初始值为0 if pos <= 0: self.add() elif pos > (self.length()-1): self.append() else: cur = self.__head counter = 0 while counter != pos: counter += 1 cur = cur.next node = Node(item) node.prev = cur.prev cur.prev.next = node node.next = cur cur.prev = node """遍历整个链表""" def travel(self): cur = self.__head while cur != None: print(cur.elem, end=" ") cur = cur.next print("") """根据元素删除节点""" def remove(self, item): cur = self.__head while cur != None: if cur.elem == item: # 先判断此结点是否是头节点 # 头节点 if cur == self.__head: self.__head = cur.next if cur.next != None: # 链表不只有一个节点 cur.next.prev = None else: cur.prev.next = cur.next if cur.next != None: cur.next.prev = cur.prev return True else: cur = cur.next return False """根据元素查找节点是否存在""" def search(self, item): cur = self.__head while cur != None: if cur.elem == item: return True else: cur = cur.next return False if __name__ == '__main__': dll = DoubleLinkList() print(dll.remove(4)) dll.travel() print("----------") dll.append(2) print(dll.search(2)) print(dll.remove(2)) print("----------") dll.append(2) dll.append(3) dll.append(5) dll.append(6) dll.append(7) dll.travel() dll.add(1) dll.travel() dll.insert(3, 4) dll.travel() dll.remove(1) dll.travel() dll.remove(7) dll.travel() dll.remove(4) dll.travel() print(dll.remove(100)) dll.travel()
class AQueue: def __init__(self): self.in_stack = [] self.out_stack = [] def enqueue(self, value): self.in_stack.append(value) def dequeue(self): if not len(self.out_stack): while self.in_stack: self.out_stack.append(self.in_stack.pop()) return self.out_stack.pop() def get_front(self): value = self.dequeue() self.out_stack.append(value) return value
from contacts.trie import TrieNode N = int(input()) trie = TrieNode() for _ in range(N): instruct, in_str = input().split() if instruct == "add": trie.add(in_str) if instruct == "find": print(trie.find(in_str))
s = input("Enter the String : ") vowels = 'AEIOUaeiou' d = {item: s.count(item) for item in s if item in vowels} print(d)
s = input("Enter string : ") print(s.swapcase())
import random import string st = '' l = [()] for i in range(0,6): if i % 2 == 0: st += random.choice(string.ascii_letters) else: j = random.randrange(0,9,1) st += str(j) print(st)
from sys import argv def bmi(): print('Name : ', argv[1]) print('Height : ', argv[2]) print('Weight : ', argv[3]) height = float(argv[2]) weight = float(argv[3]) bmivalue = round(weight / (height * height), 1) return 'Your BMI is ', bmivalue, 'which means you are underweight.' if bmivalue < 18.5 else \ 'which means you are healthy.' if bmivalue < 24.9 else \ 'which means you are overweight.' if bmivalue < 29.9 else \ 'which means you are obese.' print(bmi())
n = int(input("Enter the Value:")) if n in range(1,101): if n%2 != 0: print('Weird') else : if n in range(2, 5): print(' Not Weird') elif n in range(6,11): print('Weird') elif n > 10: print('Not Weird') else : print("Invalid Number")
s = input('Enter String: ') t = '' for i in s: if i not in t: t = t+i print(t)
# coding: utf-8 # ## Finite State Machine for Snakes and Ladders game import random class State(object): def __init__(self, ix): self.index = ix self.link = None # placeholder, not None if Snake or Ladder def process(self): """Action when landed upon""" if self.link: if self.link > self.index: # Ladder! return self.link else: # Snake! return self.link else: # link is None: "Normal" = not a snake or ladder return self.index class GameFSM(object): def __init__(self, n): self.all_states = [] self.position = 0 self.n = n for ix in range(n+1): self.all_states.append(State(ix)) def move(self, die): """die is an integer """ inter_pos = self.position + die state_obj = self.all_states[inter_pos] final_pos = state_obj.process() self.position = final_pos # all this could be written more consisely as #self.position = self.all_states[self.position+die].process() def run(self): print("Starting game!") while self.position < self.n: # roll die die = rollDie() # move based on die roll self.move(die) # record results print("Game over!") # Global constant in caps DIE_SIDES = 4 def rollDie(): return random.randint(1, DIE_SIDES) game = GameFSM(16) # Ladders game.all_states[2].link = 10 game.all_states[8].link = 14 # Snakes game.all_states[11].link = 4 game.all_states[15].links = 6 print(game.all_states)
# -*-coding:Utf-8 -* """Ce module contient la classe Labyrinthe.""" class Labyrinthe: """Classe représentant un labyrinthe.""" def __init__(self,max_largeur,max_hauteur, position_robot, position_sortie,grille): self.max_largeur = max_largeur self.max_hauteur = max_hauteur self.position_robot = position_robot self.position_sortie = position_sortie self.grille = grille def display(self): """Permet d'afficher la grille du labyrinthe""" j=1 i=1 chaine = "" while (j<=self.max_hauteur): i=1 while(i<=self.max_largeur): if self.position_robot[0] == i and self.position_robot[1] == j: chaine += 'X' else: chaine += self.grille[i,j] i += 1 chaine +="\n" j += 1 print(chaine) def move(self, commande): """Permet de déplacer votre robot sur la carte du labyrinthe et affiche la grille mise à jour""" # Récupération de la direction ainsi que du nombre de déplacement direction = commande[0].lower() # si l'utilisateur n'a pas saisie de nombre de déplacement alors il est de 1 par défaut. nb_deplacement = 1 if len(commande) > 1: nb_deplacement = int(commande[1:]) if not self.deplacementPossible(direction, nb_deplacement): print("Déplacement impossible, un mûr vous empêche d'effectuer ce déplacement") else: print("Déplacement possible") self.calculNouvellePosition( direction,nb_deplacement) self.display() def sortieTrouvee(self): """Renvoi True si le joueur a trouvé la sortie, False sinon""" return self.position_robot == self.position_sortie def calculNouvellePosition(self, direction,nb_deplacement): """Calcul la nouvelle position du robot en fonction de la direction et du nombre de déplacement saisie""" if direction=='n': self.position_robot[1] -= nb_deplacement elif direction=='s': self.position_robot[1] += nb_deplacement elif direction=='e': self.position_robot[0] += nb_deplacement elif direction=='o': self.position_robot[0] -= nb_deplacement def deplacementPossible(self,direction, nb_deplacement): """Retourne True si si le déplacement est possible, False sinon""" deplacement_possible = True if direction == "n": deplacement_possible=self.deplacementNordPossible(nb_deplacement) elif direction == 's': deplacement_possible=self.deplacementSudPossible(nb_deplacement) elif direction == 'e': deplacement_possible=self.deplacementEstPossible(nb_deplacement) elif direction == 'o': deplacement_possible=self.deplacementOuestPossible(nb_deplacement) else : raise Exception("La direction rentrée est différente des lettres autorisées ('n','s','e','o')") return deplacement_possible def deplacementNordPossible(self, nb_deplacement): """On vérifie si le déplacement vers le Nord est possible""" # si le déplacement n'est pas sur la carte on retourne false if self.position_robot[1] - nb_deplacement < 1 : return False # si il y a un mûr sur la trajectoire on retourne false i=1 while i<=nb_deplacement: if self.grille[self.position_robot[0], self.position_robot[1]-i] == 'O': return False i+=1 # si rien ne bloque la trajectoire on retourne True return True def deplacementSudPossible(self, nb_deplacement): """On vérifie si le déplacement vers le Sud est possible""" # si le déplacement n'est pas sur la carte on retourne false if self.position_robot[1] + nb_deplacement < 1 : return False # si il y a un mûr sur la trajectoire on retourne false i=1 while i<=nb_deplacement: if self.grille[self.position_robot[0], self.position_robot[1]+i] == 'O': return False i+=1 # si rien ne bloque la trajectoire on retourne True return True def deplacementOuestPossible(self, nb_deplacement): """On vérifie si le déplacement vers l'Ouest est possible""" # si le déplacement n'est pas sur la carte on retourne false if self.position_robot[0] - nb_deplacement > self.max_largeur : return False # si il y a un mûr sur la trajectoire on retourne false i=1 while i<=nb_deplacement: if self.grille[self.position_robot[0]-i, self.position_robot[1]] == 'O': return False i+=1 # si rien ne bloque la trajectoire on retourne True return True def deplacementEstPossible(self, nb_deplacement): """On vérifie si le déplacement vers l'Est est possible""" # si le déplacement n'est pas sur la carte on retourne false if self.position_robot[0] + nb_deplacement > self.max_largeur : return False # si il y a un mûr sur la trajectoire on retourne false i=1 while i<=nb_deplacement: if self.grille[self.position_robot[0]+i, self.position_robot[1]] == 'O': return False i+=1 # si rien ne bloque la trajectoire on retourne True return True
number=int(input('')) list=[] for i in range(0,number): newNo=int(input('')) a=list.append(newNo) print("Elements are",list[i],i)
list=[] number=input() for i in range(0,number): a=input() list.append(a) list.sort() print list
x=int(input("")) y=int(input("")) temp=x x=y y=temp print(format(x), format(y))
def getPrimes(n): if n % 2 == 0: nums = list(range(n-1, 3, -2)) else: nums = list(range(n-2, 3, -2)) curPrime = 3 primes = [2, 3] while(curPrime*curPrime < n): removes = set(list(range(curPrime*curPrime, n, 2*curPrime))) numSet = set(nums) numSet.difference_update(removes) nums = list(numSet) nums.sort() nums.reverse() curPrime = nums.pop() primes.append(curPrime) return sorted(primes + nums) def getProperFactorsSum(num, primes): sum = 1 curDividend = num for prime in primes: if curDividend % prime == 0: curDividend = curDividend / prime primeMult = prime * prime while curDividend % prime == 0: curDividend = curDividend / prime primeMult *= prime sum *= (primeMult - 1)/(prime - 1) if curDividend == 1: break return sum - num def findAbundantNums(numsToCheck, primes): if len(numsToCheck) < 0: return [] abundantNums = set([]) for num in numsToCheck: curSum = getProperFactorsSum(num, primes) if curSum == num: maxNum = numsToCheck[len(numsToCheck)-1] + 1 abundantNums.update(range(num+num, maxNum, num)) if num+1 < maxNum: abundantNums.update(findAbundantNums([i for i in range(num+1, maxNum+1) if i not in abundantNums and i not in primes], primes)) return abundantNums elif curSum > num: abundantNums.add(num) return abundantNums def getNonAbundantsSum(): primes = getPrimes(28124) abundantNums = list(findAbundantNums([i for i in range(2, 28124) if i not in primes], primes)) abundantNums.sort() abundantPairSums = set([]) for num1 in abundantNums: for num2 in abundantNums: pairSum = num1 + num2 if pairSum < 28124: abundantPairSums.add(pairSum) else: break return sum([i for i in range(1, 28124) if i not in abundantPairSums])
def numberWordCount(): singles = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'] singlesCount = 0 for word in singles: singlesCount += len(word) tenCount = len('ten') multTens = ['twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] multTensCount = 0 for word in multTens: multTensCount += len(word) teens = ['eleven', 'twelve', 'thir', 'four', 'fif', 'six', 'seven', 'eigh', 'nine'] teensCount = 0 for word in teens: teensCount += len(word) teensCount += len('teen') * 7 doublesCount = 10*multTensCount + tenCount + teensCount andCount = len('and') hundredCount = len('hundred') thousandCount = len('oneThousand') allCount = 190*singlesCount + 10*doublesCount + 891*andCount + 900*hundredCount + thousandCount return allCount print(numberWordCount())
from __future__ import print_function import math def findMillthPerm(): numPermsLeft = 1000000 numsLeft = range(10) numNumsLeft = 10 while numNumsLeft > 1: nextNumPerms = math.factorial(numNumsLeft-1) curNumPerms = 0 for i in numsLeft: if (nextNumPerms + curNumPerms) >= numPermsLeft: print(i, end="") numsLeft.remove(i) numPermsLeft -= curNumPerms break else: curNumPerms += nextNumPerms numNumsLeft -= 1 print(numsLeft[0], end="")
import heapq class ProductTuple: def __init__(self, _fact1, _fact2): self.product = _fact1 * _fact2 * -1 self.fact1 = _fact1 self.fact2 = _fact2 def __cmp__(self, other): return cmp(self.product, other.product) def addNextProds(heap, fact, topBound): if(fact == 0): return for i in xrange(fact, topBound+1): heapq.heappush(heap, ProductTuple(fact, i)) def isPalindrome(num): numStr = str(num) if(numStr == numStr[::-1]): return True else: return False lowerFact = 999 upperFact = 999 prodHeap = [] prodHeap.append(ProductTuple(upperFact, upperFact)) heapq.heapify(prodHeap) while(len(prodHeap) > 0): nextMax = heapq.heappop(prodHeap) nextProd = nextMax.product * -1 if(isPalindrome(nextProd)): print '{0} * {1} = {2}'.format(nextMax.fact1, nextMax.fact2, nextProd) break if(nextMax.fact1 == lowerFact): lowerFact = lowerFact - 1 addNextProds(prodHeap, lowerFact, upperFact)
''' Created on October 9, 2019 @author: Brad Bosak ''' import socket class CertificateAuthority: def createCaServer(self): #Create server socket caSocket = socket.socket() #Define port and bind port = 9501 caSocket.bind(('', port)) caSocket.listen(5) print ("CA socket is created, binded to port {0}, and listening".format(port)) serverName = "BradsServer" publicKey = "Brad is really cool!!" while True: #Find client (clientSocket, address) = caSocket.accept() print ("Connection found from ", address) dataFromClient = clientSocket.recv(1024).decode() #Logic around messages if dataFromClient == serverName: returnMessage = publicKey else: returnMessage = "Goodbye" #Print client message and send return message print ('Message from client is:', dataFromClient) clientSocket.send(returnMessage.encode()) def main(): certificateAuthority = CertificateAuthority() certificateAuthority.createCaServer() main()
from typing import List # Runtime: 48 ms, faster than 94.59% of Python3 online submissions for Find Numbers with Even Number of Digits. def findNumbers(nums: List[int]) -> int: count = 0 for i in nums: if len(str(i)) % 2 == 0: count += 1 return count print(findNumbers([12, 345, 2, 6, 7896]))
# You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water. # # Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). # # The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. from typing import List # Runtime: 520 ms, faster than 81.59% of Python3 online submissions for Island Perimeter. # Memory Usage: 13.8 MB, less than 93.19% of Python3 online submissions for Island Perimeter. def islandPerimeter(grid: List[List[int]]) -> int: count = 0 for index, val in enumerate(grid): for xindex, xval in enumerate(val): sides = 4 if xval == 1: if xindex > 0: if val[xindex - 1] == 1: sides -= 1 if xindex < len(val) - 1: if val[xindex + 1] == 1: sides -= 1 if index > 0: if grid[index - 1][xindex] == 1: sides -= 1 if index < len(grid) - 1: if grid[index + 1][xindex] == 1: sides -= 1 count += sides return count print(islandPerimeter([[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0]]))
# Description: Given a two parameters of type integer 'N', 'D', return a string of the decimal representation where N is the numerator and D is the denominator. If the decimal has a repeating sequence of digits, indicate the sequence by enclosing it in brackets. Use xxx.0 to denote an integer. def frick_fractions(N, D): new = [f'{N // D}.'] decimals = [N % D] N % D while N != 0: N *= 10 result_digit, N = divmod(N, D) new.append(str(result_digit)) if N not in decimals: decimals.append(N) else: new.insert(decimals.index(N) + 1, '(') new.append(')') break return ''.join(new) print(frick_fractions(500, 501)) print(frick_fractions(1, 7))
from typing import List # There are N children standing in a line. Each child is assigned a rating value. # # You are giving candies to these children subjected to the following requirements: # # Each child must have at least one candy. # Children with a higher rating get more candies than their neighbors. # # What is the minimum candies you must give? def candy(ratings: List[int]) -> int: res = [1] * len(ratings) lbase = rbase = 1 for i in range(1, len(ratings)): lbase = lbase + 1 if ratings[i] > ratings[i - 1] else 1 res[i] = lbase for i in range(len(ratings) - 2, -1, -1): rbase = rbase + 1 if ratings[i] > ratings[i + 1] else 1 res[i] = max(rbase, res[i]) return sum(res) print(candy([1, 0, 2]))
import types class GameBoard: def __init__(self, width=5, height=5): """Initializes a rectangular gameboard.""" self.width, self.height = width, height assert 2 <= self.width and 2 <= self.height,\ "Game can't be played on this board's dimension." self.board = {} self.squares = {} self.player = 0 def isGameOver(self): """Returns true if no more moves can be made. The maximum number of moves is equal to the number of possible lines between adjacent dots. I'm calculating this to be $2*w*h - h - w$; I think that's right. *grin* """ w, h = self.width, self.height return len(self.board.keys()) == 2*w*h - h - w def _isSquareMove(self, move): """Returns a true value if a particular move will create a square. In particular, returns a list of the the lower left corners of the squares captured by a move. (Note: I had forgotten about double crossed moves. Gregor Lingl reported the bug; I'd better fix it now! *grin*) """ b = self.board mmove = self._makeMove ## just to make typing easier ((x1, y1), (x2, y2)) = move captured_squares = [] if self._isHorizontal(move): for j in [-1, 1]: if (b.has_key(mmove((x1, y1), (x1, y1-j))) and b.has_key(mmove((x1, y1-j), (x1+1, y1-j))) and b.has_key(mmove((x1+1, y1-j), (x2, y2)))): captured_squares.append(min([(x1, y1), (x1, y1-j), (x1+1, y1-j), (x2, y2)])) else: for j in [-1, 1]: if (b.has_key(mmove((x1, y1), (x1-j, y1))) and b.has_key(mmove((x1-j, y1), (x1-j, y1+1))) and b.has_key(mmove((x1-j, y1+1), (x2, y2)))): captured_squares.append(min([(x1, y1), (x1-j, y1), (x1-j, y1+1), (x2, y2)])) return captured_squares def _isHorizontal(self, move): "Return true if the move is in horizontal orientation." return abs(move[0][0] - move[1][0]) == 1 def _isVertical(self, move): "Return true if the move is in vertical orientation." return not self.isHorizontal(self, move) def play(self, move): """Place a particular move on the board. If any wackiness occurs, raise an AssertionError. Returns a list of bottom-left corners of squares captured after a move.""" assert (self._isGoodCoord(move[0]) and self._isGoodCoord(move[1])),\ "Bad coordinates, out of bounds of the board." move = self._makeMove(move[0], move[1]) assert(not self.board.has_key(move)),\ "Bad move, line already occupied." self.board[move] = self.player ## Check if a square is completed. square_corners = self._isSquareMove(move) if square_corners: for corner in square_corners: self.squares[corner] = self.player else: self._switchPlayer() return square_corners def _switchPlayer(self): self.player = (self.player + 1) % 2 def getPlayer(self): return self.player def getSquares(self): """Returns a dictionary of squares captured. Returns a dict of lower left corner keys marked with the player who captured them.""" return self.squares def __str__(self): """Return a nice string representation of the board.""" buffer = [] ## do the top line for i in range(self.width-1): if self.board.has_key(((i, self.height-1), (i+1, self.height-1))): buffer.append("+--") else: buffer.append("+ ") buffer.append("+\n") ## and now do alternating vertical/horizontal passes for j in range(self.height-2, -1, -1): ## vertical: for i in range(self.width): if self.board.has_key(((i, j), (i, j+1))): buffer.append("|") else: buffer.append(" ") if self.squares.has_key((i, j)): buffer.append("%s " % self.squares[i,j]) else: buffer.append(" ") buffer.append("\n") ## horizontal for i in range(self.width-1): if self.board.has_key(((i, j), (i+1, j))): buffer.append("+--") else: buffer.append("+ ") buffer.append("+\n") return ''.join(buffer) def _makeMove(self, coord1, coord2): """Return a new "move", and ensure it's in canonical form. (That is, force it so that it's an ordered tuple of tuples.) """ ## TODO: do the Flyweight thing here to reduce object creation xdelta, ydelta = coord2[0] - coord1[0], coord2[1] - coord1[1] assert ((abs(xdelta) == 1 and abs(ydelta) == 0) or (abs(xdelta) == 0 and abs(ydelta) == 1)),\ "Bad coordinates, not adjacent points." if coord1 < coord2: return (coord1, coord2) else: return (tuple(coord2), tuple(coord1)) def _isGoodCoord(self, coord): """Returns true if the given coordinate is good. A coordinate is "good" if it's within the boundaries of the game board, and if the coordinates are integers.""" return (0 <= coord[0] < self.width and 0 <= coord[1] < self.height and isinstance(coord[0], types.IntType) and isinstance(coord[1], types.IntType)) def _test(width, height): """A small driver to make sure that the board works. It's not safe to use this test function in production, because it uses input().""" board = GameBoard(width, height) turn = 1 scores = [0, 0] while not board.isGameOver(): player = board.getPlayer() print "Turn %d (Player %s)" % (turn, player) print board move = input("Move? ") squares_completed = board.play(move) if squares_completed: print "Square completed." scores[player] += len(squares_completed) turn = turn + 1 print "\n" print "Game over!" print "Final board position:" print board print print "Final score:\n\tPlayer 0: %s\n\tPlayer 1: %s" % \ (scores[0], scores[1]) if __name__ == "__main__": """If we're provided arguments, try using them as the width/height of the game board.""" import sys if len(sys.argv[1:]) == 2: _test(int(sys.argv[1]), int(sys.argv[2])) elif len(sys.argv[1:]) == 1: _test(int(sys.argv[1]), int(sys.argv[1])) else: _test(4, 4) # pass one by one tuples # ((0, 0), (1, 0)) # ((2, 2), (1, 2)) # ((2, 2), (2, 1)) # ((1, 3), (0, 3)) # ((1, 0), (2, 0))
#addwithloop #sum:1 to 10 total =0 i =1 while i<=10: total =total+i i=i+1 print(total)
#ex_args def power(num,*args): if args: return[i**num for i in args] else: "no args" nums = [1,2,3] print(power(3,*nums))
#join and split #split user_info = 'anuj 18'.split() print(user_info) #if user_info1 = 'anuj,18'.split(',') print(user_info1) #name , age = input("enter ur name and age").split(',') #print(name) #print(age) #join method user_info3 = ['anuj', '18'] print(','.join(user_info3))
a = int(input("nter no")) b = int(input("enter no.")) a = a+b b = a-b a = a-b print(a,b)
#list inside list num = [[1,2,3],[4,5,6],[7,8,9]] #2d list for sublist in num: for i in sublist: print(i) print(num[1][1])
#a def twos_powers(n): for i in range(n): x=2**i yield(x) # for i in twos_powers(10): # print(i,end=", ") # print( ) #b def reverse_twos_powers(n): for i in range(n): x=.5**i yield(x) # for i in reverse_twos_powers(10): # print(i,end=", ")
def max_two_products(lst): max1=0 max2=0 for i in lst: if (max1<i): max1=i for j in lst: if (max2<j and max1!=j): max2=j return (max1*max2) print(max_two_products([11, 3, 4, 9, 2, 7, 8, 10, 5]))
def is_BST(BST): return is_BST_helper(BST.root)[2] def is_BST_helper(root): ''' Returns a tuple (min, max, bool)''' if not root.left and not root.right: return(True,root.item.key,root.item.key) if root.left and root.right
#a def print_triangle(n): if n==0: return 1 else: print_triangle(n-1) return("*"*n) #b def print_opposite_triangles(n): if n==0: return 1 else: return("*"*n) print_opposite_triangles(n-1) return("*"*n) #c def print_ruler(n): if n==0: return 1 else: print_ruler(n-1) return("-"*n) print_ruler(n-1)
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: if not head: return curLeft = curRight = last = head while True: # Discover i = k-1 history = [] while i: if not curRight.next: return head history.append(curRight) curRight = curRight.next i -= 1 print(curRight.val, i) last = curRight # Swap while curLeft != curRight and curRight.next != curLeft: curLeft.val, curRight.val = curRight.val, curLeft.val curLeft, curRight = curLeft.next, history.pop(-1) # Recovery if not last.next: break curLeft = curRight = last.next return head
input("What is your favorite basketball team?") if answer == "the warriors": input("Good, who is your favorite player?") if answer == "stephen curry": elif answer == "the spurs": input("Okay, who is your favorite player?") elif answer == "the thunder": input("Okay, who is your favorite player?")
# subtract two numbers answer = int(input("What do you want a to be?")) answer2 = int(input("What do you want b to be?")) if answer > answer2: answer3 = answer-answer2 if answer2 > answer: answer3 = answer2-answer print answer3
#determine which is least out of three numbers you give. a = int(input("What do you want a to be?")) b = int(input("What do you want b to be?")) c = int(input("What do you want c to be?")) if a < b < c: print a if a < c < b: print a if b < a < c: print b if b < c < a: print b if c < a < b: print c if c < b < a: print c
# pig latin strings words = input("HI ZOMBIE.") words = words.lower() words = words.split(" ") output = "" vowels = [ "a", "e", "i", "o", "u"] for word in words: if word[0] in vowels: output = output+ word + "yay " else: start = 0 for letter in list(word): if letter in vowels: break else: if letter is "y": break else: start += 1 output += word[start:] + word[:start] + "ay " print output
class bankAccount: def __init__(self, int_rate=0.03, balance=0): self.int_rate = int_rate self.balance = balance def deposit(self, amount): self.balance += amount return self def withdrew(self, amount): self.balance -= amount if self.balance < 0: print("Insufficient funds: Charging $5.00 fee") self.balance -= 5 return self def account_information(self): print(f"Balance: ${self.balance}") return self def interest(self): self.balance *= 1 + self.int_rate return self melissa= bankAccount(0.08, 1000) melissa.deposit(500).deposit(90).deposit(5).withdrew(752).interest().account_information() richard= bankAccount(0.05, 10) richard.deposit(500).deposit(200).withdrew(88).withdrew(286).withdrew(80).withdrew(100).interest().account_information()
def updateFreq(d, prev, curr): # if prev is a zero if prev == 0: # increment curr in d if it exists if curr in d: d[curr] += 1 # add curr to d and set to 1 else: d[curr] = 1 # return return # if value at prev of d is greater than zero if d[prev] > 0: # decrement value at prev of d d[prev] -= 1 # if curr in d if curr in d: # increment value at curr of d d[curr] += 1 # otherwise, else: # add curr to d and set to one d[curr] = 1 def freqQuery(queries): """ performs a set of operations based on input operations are insertion, deletion and frequency read use a dict to keep track of insertion and deletion use another dict to store frequency to make lookup O(n) store the result of frequency lookup in an array to be returned at the tail of the program """ # initialize op to empty dict op = {} # initialize freq to empty dict freq = {} # initialize lookup to empty arr lookup = [] # loop through queries as command/value pair for command, value in queries: # if command is a 1 if command == 1: # check if value is in op if value in op: # call updateFreq with prev value and current value updateFreq(freq, op[value], op[value] + 1) # increment the value of value in op op[value] += 1 # otherwise else: # call updateFreq with zero and one updateFreq(freq, 0, 1) # add value in op and set to 1 op[value] = 1 # if command is a 2 elif command == 2: # check if value is in op if value in op: # if value of value in op greater than zero if op[value] > 0: # call updateFreq with prev value and current value updateFreq(freq, op[value], op[value] - 1) # decrement the value of value in op op[value] -= 1 # otherwise else: # check if value is in freq dict if value in freq: # if value of value in freq dict is greater than zero if freq[value] > 0: # append 1 to lookup lookup.append(1) # otherwise else: # append zero to lookup lookup.append(0) # otherwise else: # append zero to lookup lookup.append(0) # return lookup return lookup print(freqQuery([[1, 5], [1, 6], [3, 2], [ 1, 10], [1, 10], [1, 6], [2, 5], [3, 2]])) print(freqQuery([[3, 4], [2, 1003], [1, 16], [3, 1]]))
def longestVowelSubsequence(s): # create vowel with aeiou vowel = "aeiou" # set pos to zero pos = 0 # set length to zero length = 0 # loop through s for char in s: # if pos equals four if pos == 4: # if char is char at pos of vowel if char == vowel[pos]: # increment length length += 1 # continue continue # if char is char at pos of vowel if char == vowel[pos]: # increment length length += 1 # otherwise if char is char at pos + 1 of vowel elif char == vowel[pos + 1]: # increment length length += 1 # increment pos pos += 1 # if pos equals four if pos == 4: # return length return length # otherwise else: # return 0 return 0 print(longestVowelSubsequence("aeiaaioooaauuaeiu")) print(longestVowelSubsequence("aeiaaiooaa"))
from time import time """ Find XOR of numbers from the range [L, R] Naive Approach: Initialize answer as zero, Traverse all numbers from L to R and perform XOR of the numbers one by one with the answer. This would take O(N) time. Efficient Approach: By following the approach discussed here, we can find the XOR of elements from the range [1, N] in O(1) time. Using this approach, we have to find xor of elements from the range [1, L – 1] and from the range [1, R] and then xor the respective answers again to get the xor of the elements from the range [L, R]. This is because every element from the range [1, L – 1] will get XORed twice in the result resulting in a 0 which when XORed with the elements of the range [L, R] will give the result. Calculate XOR from 1 to n Method 1 (Naive Approach): 1- Initialize result as 0. 1- Traverse all numbers from 1 to n. 2- Do XOR of numbers one by one with result. 3- At the end, return result. Method 2 (Efficient method) : 1- Find the remainder of n by moduling it with 4. 2- If rem = 0, then xor will be same as n. 3- If rem = 1, then xor will be 1. 4- If rem = 2, then xor will be n+1. 5- If rem = 3 ,then xor will be 0. # from the range [1, n] def findXOR(n): mod = n % 4; # If n is a multiple of 4 if (mod == 0): return n; # If n % 4 gives remainder 1 elif (mod == 1): return 1; # If n % 4 gives remainder 2 elif (mod == 2): return n + 1; # If n % 4 gives remainder 3 elif (mod == 3): return 0; # Function to return the XOR of elements # from the range [l, r] # Python3 implementation of the approach from operator import xor def findXORFun(l, r): return (xor(findXOR(l - 1) , findXOR(r))); """ def solution(start, length): """Generates the checksum of a matrix of size length X length by first dropping every number after column (row number - 1) from the end of each row and XORing the remaining numbers. Arguments: start {int} -- the number to begin with length {int} -- the size of the row and column Returns: int -- The generated checksum """ # WHAT! # Starts from the number start # begins to leave out one number from the end # from the second row onward # returns the XOR of the remaining number # HOW! # initialize checksum to zero checksum = 0 # set cutoff to zero cutoff = 0 # set index to length minus one index = length - 1 # max to the sum of start and square of length max = start + (length * length) # while start is less than max while start < max: # if index is equivalent to cutoff if index == cutoff: # set checksum to the XOR of start checksum ^= start # increment start by cutoff start += cutoff # increment cutoff cutoff += 1 # reset index to length minus one index = length - 1 # otherwise else: # set checksum to the XOR of start checksum ^= start # decrement index index -= 1 # increment start start += 1 # return checksum return checksum def findXOR(n): """ Calculate XOR from 1 to n from the range [1, n] """ mod = n % 4 # If n is a multiple of 4 if (mod == 0): return n # If n % 4 gives remainder 1 elif (mod == 1): return 1 # If n % 4 gives remainder 2 elif (mod == 2): return n + 1 # If n % 4 gives remainder 3 elif (mod == 3): return 0 def solution2(start, length): """Generates the checksum of a matrix of size length X length by first dropping every number after column (row number - 1) from the end of each row and XORing the remaining numbers. Arguments: start {int} -- the number to begin with length {int} -- the size of the row and column Returns: int -- The generated checksum """ # WHAT! # Starts from the number start # begins to leave out one number from the end # from the second row onward # returns the XOR of the remaining number # HOW! # initialize checksum to zero checksum = 0 # set size to length minus one size = length - 1 # while size is greater than or equal zero # we just need to perform the operation for the number of rows we have while size >= 0: # Find xor of elements from the range [1, start – 1] and from the range [1, start + size] # and then xor the respective answers again # to get the xor of the elements from the range [L, R] checksum ^= findXOR(start - 1) ^ findXOR(start + size) # reduce the size to knock off another number from the end size -= 1 # increment number to the start of the next row start += length # return checksum return checksum t = time() print(solution(0, 500)) print(solution(17, 1000)) print("First solution took", time() - t) t = time() print(solution2(0, 500)) print(solution2(17, 1000)) print("Second solution took", time() - t)
def jumpingOnClouds(c): """ should start jump at 0 can only jump 1 or 2 index forward will run in O(n) time must avoid list items that are 0's should jump 2 steps forward if there are two consecutive 1's """ # initialize jump to zero jump = 0 # initialize index to zero index = 0 # while index is less than length of c while index < len(c) - 1: # if the next item is 1 or the next two items are 0's # if at second to the last item if index == len(c) - 2: index += 1 elif c[index + 1] == 1 or (c[index + 1] == 0 and c[index + 2] == 0): # increment index by 2 index += 2 # otherwise else: # increment index by 1 index += 1 # increment jump by 1 jump += 1 # return the number of jumps return jump print(jumpingOnClouds([0, 0, 1, 0, 0, 1, 0])) print(jumpingOnClouds([0, 0, 0, 1, 0, 0]))
def find_combinations(n): # initialize a combo to empty dict combo = {} # loop from a range of one to n for i in range(1, n): # add the number to dict and set the value to empty set combo[i] = set() # loop from current number plus one to n for j in range(i + 1, n + 1): # add this number to set at index i of combo combo[i].add(j) # return combo return combo def bit_and(n, k): # call find_combinations to get combo combo = find_combinations(n) # initialize ands to empty set ands = set() # loop through combo for A in combo: # loop through items in set at current index for B in combo[A]: # find the bitwise and of both values bit_and = A & B # add it to ands if less than k if bit_and < k: ands.add(bit_and) # return max of combo return max(ands) print(bit_and(5, 2)) print(bit_and(8, 5)) print(bit_and(2, 2)) """ Let me try to explain. Consider the following Given the task "A&B is the maximum possible and also less than a given integer, K", the highest possible value to achieve is K-1 So, let's try to achieve that highest value. Also consider that, when using the AND-operation with a pair of values you can never get a value higher than the lowest value of that pair. Because to get a value higher than the lowest value, you would have to turn a zero-bit out of the lowest value into a one-bit, and it's impossible to turn zero-bits into one-bits by using AND. So to achieve that highest value K-1, you need to find an even higher value, that in an AND-operation with K-1 results in K-1. You want that higher value to be as close to K-1 as possible, so that you have the biggest chance of that higher value being within the limits of N. (remember, both values of A and B had to be from the set {1,2,3,...,N}) So, let's start with K-1 and turn that into a bits. The lowest, higher number that gives K-1 in an AND operation is K-1 with the least-significant zero turned into a one. This is the key to this elegant solution. Let's explain it with a few examples. 1001001 1001011 -------AND 1001001 1011111 1111111 -------AND 1011111 1011000 1011001 -------AND 1011000 So in cases where K-1 is even this leaves us with a very simple answer. Because K-1 is even, the last bit of K-1 is zero. Turning the least-significant zero turned into a one, is the same as adding one, and K-1+1 = K. So K-1 & K = K-1 in cases where K-1 is even. K is <= N by definition so you have an answer. But when K-1 is odd, things start to get more complicated. Now you don't know at which position a zero will turn into a 1, so you don't know how big the lowest, higher number (that gives K-1 in an AND operation) will be. It can be 2 higher (with 0 at the 2nd place from the right) or 4 higher (with 0 at the 3nd place from the right) or 8, or 16, etc. So you need to check if this lowest, higher number is still smaller or as big as N. If it is than K-1 is your answer, if it isn't than K-2 is your answer. Why K-2? Well if K-1 is odd, than K-2 is even. Because K-2 is even, the last bit of K-2 is zero. Turning the least-significant zero turned into a one, is the same as adding one, and K-2+1 = K-1. So K-2 & K-1 = K-2 in cases where K-1 is odd K-1 is <= N by definition so you have an answer. But how to get the lowest higher number? Well, as said, by turning least-significant zero into a one. And how do you do that? By using the OR-operation on K and K-1 Let's take the above examples and show that OR-ing the first value (K-1) with K, results in the second value, the value with the least significant zero turned into a one, being the lowest higher number that gives K-1 in and AND-operation 1001001 (K-1) 1001010 (K) -------OR 1001011 1011111 (K-1) 1100000 (K) -------OR 1111111 1011000 (K-1) 1011001 (K) -------OR 1011001 (K) Note, that in the case where K-1 is even K-1 OR K = K Because K <= N the condition (K-1 OR K <= N) is always true in cases where K-1 is even. In cases where K-1 is odd, the condition (K-1 OR K <= N) sometimes evaluates to false (the lowest higher number is bigger than N), in which case the answer is K-2. When it evaluates to true, the answer is K-1. """
r1 = float(input('Informe o tamanho do primeiro lado: ')) r2 = float(input('Informe o tamanho do segundo lado: ')) r3 = float(input('Informe o tamanho do terceiro lado: ')) if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2: print('É possível montar um triângulo', end=' ') if r1 == r2 and r2 == r3: print('equilátero') elif r1 == r2 or r2 == r3 or r1 == r3: print('isósceles') else: print('escaleno') else: print('Não é possível montar um triângulo')
def fatorial(num, show=False): """ Calcula o fatorial de um número :param num: número cujo fatorial será calculado :param show: mostrar cálculos :return: resultado do cálculo do fatorial """ f = 1 for c in range(num, f-1, -1): f *= c if show: if c > 1: print(f'{c} x', end=' ') else: print(f'{c} = ', end='') return f help(fatorial) print(fatorial(5, True))
frase = str(input('Informe sua frase: ')).strip().lower() aux = "".join(frase.split()) cont = 0 for c in range(0, len(aux)): if aux[c] == aux[len(aux) - 1 - c]: cont += 1 if cont == len(aux): print('A frase informada é um palíndromo') else: print('A frase informada não é um palíndromo')
from datetime import date ano = int(input('Informe seu ano de nascimento: ')) hoje = date.today().year idade = hoje - ano sexo = str(input('Informe seu sexo [M ou F]: ')).lower() if sexo == 'f' or sexo == 'fem' or sexo == 'feminino': print('Seu alistamento não é obrigatório.', end=' ') if idade < 18: print('Caso queira se alistar, ainda faltam {} ano(s)'.format(18 - idade)) tempo = hoje + 18 - idade print('Seu alistamento será no ano {}'.format(tempo)) elif idade > 18: print('Como você já tem {} anos, já deveria ter se alistado há {} ano(s)'.format(idade, idade - 18)) tempo = hoje - (idade - 18) print('Seu alistamento foi no ano {}'.format(tempo)) else: print('Você já pode se alistar') elif sexo == 'm' or 'masc' or 'masculino': if idade < 18: print('Você tem {} anos e ainda faltam {} ano(s) para seu alistamento'.format(idade, 18 - idade)) tempo = hoje + 18 - idade print('Seu alistamento será no ano {}'.format(tempo)) elif idade > 18: print('Você tem {} anos e já deveria ter se alistado há {} ano(s)'.format(idade, idade - 18)) tempo = hoje - (idade - 18) print('Seu alistamento foi no ano {}'.format(tempo)) else: print('Você tem que se alistar IMEDIATAMENTE')
salario = float(input('Informe o salário atual do funcionário: R$')) print('O salário reajustado com 15% de aumento é R${:.2f}'.format(salario*1.15))
n = float(input('Informe o preço: R$')) print('O produto com 5% de desconto custa R${:.2f}'.format(n*0.95))
valor = float(input('Informe o valor da casa: R$')) salario = float(input('Informe seu salário: R$')) tempo = int(input('Informe em quantos anos você pretende pagar a casa: ')) parcela = valor / (tempo * 12) print('Para pagar uma casa de R${:.2f} em {} anos a prestação será de R${:.2f}'.format(valor, tempo, parcela)) if (parcela > salario * 0.3): print('Empréstimo NEGADO! Salário insuficiente.') else: print('Empréstimo concedido!')
def ficha(nome='<desconhecido>', gols=0): print(f'O jogador {nome} marcou {gols} gol(s) no campeonato') nome = str(input('Nome do jogador: ')).strip().title() try: gols = int(input('Número de gols: ')) if not nome.isalpha(): ficha(gols=gols) else: ficha(nome, gols) except ValueError: if not nome.isalpha(): ficha() else: ficha(nome)
# Crie um programa onde o usuário possa digitar vários valores numéricos e cadastre-os em uma lista. # Caso o número já existe lá dentro, ele não será adicionado. No final serão exibidos todos os valores únicos # digitados, em ordem crescente. numero = list() while True: n = int(input('Informe um número: ')) if n in numero: print('O número já existe na lista!') else: numero.append(n) menu = str(input('Deseja continuar [S/N]? ')) if menu.lower() in 'nãonao': break numero.sort() print(f'Os valores digitados foram {numero}')
velocidade = int(input('Informe a velocidade do carro (em km/h): ')) if velocidade > 80: multa = (velocidade - 80) * 7 print('Limite de velocidade excedido!!! Você foi multado em R${:.2f}'.format(multa)) print('Tenha um bom dia e dirija com segurança!')
from random import randint from time import sleep palpites = list() numeros = list() print('-'*60) print(f'{"Gerador de Palpites":^60}') print('-'*60) qtd = int(input('Informe quantos palpites você deseja: ')) for q in range(0, qtd): while True: num = randint(1, 60) if num not in numeros: numeros.append(num) if len(numeros) == 6: break numeros.sort() palpites.append(numeros[:]) numeros.clear() print(f'Gerando {qtd} palpites...\n') sleep(1) print('-='*30) print(f'{"Lista de palpites":^60}') print('-='*30) for p in range(0, qtd): sleep(0.5) print(f'Palpite {p+1}: {palpites[p]}') print('-=' * 30) print(f'{"Boa sorte!!!":^60}') print('-='*30)
frase = input('Insira uma frase: ').strip().lower() print('A letra A aparece {} vez(es) na frase informada'.format(frase.count('a'))) print('A primeira vez ocorre na posição {}'.format(frase.find('a')+1)) print('A última vez ocorre na posição {}'.format(frase.rfind('a')+1))
import pandas as pd import PySimpleGUI as sg class Import(): """ This class handles importing of HRM data. Upon initilization it creates a link to the HRM parent object that stores the HRM data. """ def __init__(self, hrm): self.hrm = hrm def from_text(self, file_path): """ This function imports HRM data from a txt file. The path to the txt file can be provided by the file_path arugment. If not it will be prompted by Windows file dialogue. Arguments: ---------- file_path {string} -- string that points to the txt file to be imported Returns: -------- df_HRM {pandas dataframe} -- dataframe containing all the HRM pressure data. The index of the dataframe is the time stamp. Each row is considered 1 time step. Each column is 1 pressure sensor (total of 36). df_ann {pandas.dataframe} -- dataframe containing all the annotations from the text file. The index of the dataframe is the time stamp. Each row is considered 1 time step. Single column contains the text of the annotation. """ # Check if the file_path was given. If not, use a dialogue window to ask # the user for one. if not file_path: file_path = sg.PopupGetFile("Choose a text file to open", title="Open", default_extension=".txt") # Create the dtype input argument. The first two # columns must be objects as they contain text appended below the # pressure data in the form of the annotations. Sets all rest of the # columns to floats. Note the column names must be strings. data_dict = {"TIME": "object", "1": "object"} data_dict2 = {str(i): "float" for i in range(2, 37)} data_dict.update(data_dict2) # Read the entire csv file into a dataframe. try: df_full = pd.read_csv(file_path, delimiter="\t", dtype=data_dict) except Exception as e: print(f"{type(e)} The file was not able to be opened.") return # Rename the time column df_full = df_full.rename(columns={"TIME:": "Time"}) # Determine the index of the row in which Annotations: appears. idx_of_ann = df_full[df_full["Time"] == "Annotations:"].index[0] # Copy out the rows that include Annotation data. Only need TIME and 1 # columns. df_ann = df_full.loc[df_full.index > idx_of_ann, ("Time", "1")].copy() # Rename the second column df_ann = df_ann.rename(columns={"1": "Text"}) # Convert Time column to float df_ann["Time"] = df_ann["Time"].astype("float") # Convert the Time column to the index for df_ann df_ann = df_ann.set_index("Time", drop=True) # Copy out the pressure data from df_full. Copy all rows greater than # the row starting Annotations. df_HRM = df_full.loc[df_full.index < idx_of_ann].copy() # Convert the Time and 1st sensor columns to float df_HRM[["Time", "1"]] = df_HRM[["Time", "1"]].astype("float") # Convert the Time column to the index for df_HRM df_HRM = df_HRM.set_index("Time", drop=True) # Convert the column names from strings to integers df_HRM.columns = range(1, 37) # Set the parent properties to the imported dataframes self.hrm.data.pressures = df_HRM self.hrm.data.annotations = df_ann def from_xml(self, file_path): """ Function for future use to be able to import from xml files. Currently, only the annotations may be located within an xml file and not the HRM pressure data. Therefore, this is not used often and has not been completed as of yet. """ pass
#!/usr/bin/env python # coding: utf-8 # In[ ]: myList = [8, 10, 6, 2, 4] # list to sort swapped = True # it's a little fake - we need it to enter the while loop step=0 while swapped: swapped = False # no swaps so far for i in range(len(myList) - 1): if myList[i] > myList[i + 1]: step+=1 swapped = True # swap occured! myList[i], myList[i + 1] = myList[i + 1], myList[i] print('step:',step,end="") print(myList) print(myList)
# the first formula print ("change the value of n in the code to change precesion") # pi will be the fial value of pi pi = long long float(0) # n is the precision n = 1000000 # this value is changebale for i in range(n): # even index elements are positive if i % 2 == 0: pi += 4 / (2 * i + 1) else: # odd index elements are negetive pi -= 4 / (2 * i + 1) print("the first formula:\n pi= ", pi) pi = 0.0 for i in range(n - 1, -1, -1): if i % 2 == 0: pi += 4 / (2 * i + 1) else: pi -= 4 / (2 * i + 1) print("the first formula:\n pi= ", pi)
def transpose_matrix(a): # calculate the transpose of the matrix t = [[a[j][i] for j in range(len(a))] for i in range(len(a[0]))] # print transpose of the matrix for row in t: print(row) # uncomment the following lines to test # a = [[1.2, 1.1, 1.5], # [2.1, 2.2, 2.3], # [3.1, 3.2, 3.3]] # transpose_matrix(a)
from Adresse import Adresse from Personne import Personne from ListePersonnes import ListePersonnes # test of Adresse class # creation of three addresses a1 = Adresse("rue 1", "ville 1", "41000") a2 = Adresse("rue 2", "ville 2", "42000") a3 = Adresse("rue 3", "ville 3", "43000") a4 = Adresse("rue 3", "ville 7", "43000") # preparation of a list of addresses adresses = [] adresses.append(a1) adresses.append(a2) adresses.append(a3) adresses2 = [] adresses2.append(a4) # test of Personne class # creation of a list of type personne p1 = Personne("name 1", "F", adresses) p2 = Personne("name 2", "M", adresses) p3 = Personne("name 3", "F", adresses) p4 = Personne("name 4", "M", adresses) p5 = Personne("name 5", "F", adresses2) personnes = [] personnes.append(p1) personnes.append(p2) personnes.append(p3) personnes.append(p4) personnes3 = [] personnes3.append(p5) personnes3.append(p5) personnes3.append(p5) personnes4 = [] personnes4.append(p4) personnes4.append(p5) # test of ListePersonnes class # test the constructor lp = ListePersonnes(personnes) lp3 = ListePersonnes(personnes3) # test find_by_nom function print("---- test find_by_nom ----") print("name exist: ", lp.find_by_nom("name 1")) print("name doesn't exist: ", lp.find_by_nom("Mourad")) #test exists_code_postal function print("---- test exists_code_postal ----") print("pc exist: ", lp.exists_code_postal("43000")) print("pc doesn't exist: ", lp.exists_code_postal("555")) # test count_Personne_ville print("ville exist: ", lp.count_personne_ville("ville 1")) print("ville doesn't exist: ", lp.count_personne_ville("ville 8")) print("ville exist once: ", lp3.count_personne_ville("ville 7")) # test edit personne nom # check before the change print("------ before -----------") for p in lp.personnes: print(p.nom) # make a change lp.edit_personne_nom("name 1", "name 111") # check after the change print("------- after -------") for p in lp.personnes: print(p.nom) # test edit_personne_ville lp4 = ListePersonnes(personnes4) print("-------- befor ------------") for p in lp4.personnes: print(p.nom + "---") for a in p.adresses: print(a.ville) lp4.edit_personne_ville("name 4", "ville 111") print("----------- after ------------") for p in lp4.personnes: print(p.nom + "----") for a in p.adresses: print(a.ville)
# dict 辞書 イミュータブル型の一意なキーを与える # empty_dict # empty_dict = {} # print(empty_dict) # {} # dict1 = { # "ichigo" : "red and sweet", # "human" : "ambrose", # "mike" : "human and cool" # } # print(dict1) # dict() # lol = [['nissan','skyline'],['mitsubishi','evo']] # dict_lol = dict(lol) # print(dict_lol) # #dict() list of tuple # lot = [('nissan','skyline'),('mitsubishi','evo')] # dict_lot = dict(lot) # print(dict_lot) # #dict() tuple of list # tol = (['nissan','skyline'],['mitsubishi','evo']) # dict_tol = dict(tol) # print(dict_tol) # #dict() list of s # los = ['ab','cd'] # dict_los = dict(los) # print(dict_los) # #dict() tuple of s # tos = ('ab','cd') # dict_tos = dict(tos) # print(dict_tos) # [key] # dict1 = { # "ichigo" : "red and sweet", # "human" : "ambrose", # "mike" : "human and cool" # } # print(dict1) # dict1['human'] = 'God' # print(dict1) # update # dict1 = { # "ichigo" : "red and sweet", # "human" : "ambrose", # "mike" : "human and cool", # } # print(dict1) # other = { # "john" : "genius", # "human" : "monkey", #同じキーがある場合上書きされる # } # dict1.update(other) # print(dict1) # del # dict1 = { # "ichigo" : "red and sweet", # "human" : "ambrose", # "mike" : "human and cool", # } # print(dict1) # other = { # "john" : "genius", # "human" : "monkey", #同じキーがある場合上書きされる # } # dict1.update(other) # print(dict1) # del dict1['john'] # print(dict1) # clear # dict1 = { # "ichigo" : "red and sweet", # "human" : "ambrose", # "mike" : "human and cool", # } # print(dict1) # dict1.clear() # print(dict1) # in キーの有無 # dict1 = { # "ichigo" : "red and sweet", # "human" : "ambrose", # "mike" : "human and cool", # } # print(dict1) # human_dict = 'human' in dict1 # print(human_dict) # ambrose_dict = 'ambrose' in dict1 # print(ambrose_dict) # john_dict = 'john' in dict1 # print(john_dict) # [key]による要素の取得#1 # dict1 = { # "ichigo" : "red and sweet", # "human" : "ambrose", # "mike" : "human and cool", # } # tmp = dict1['human'] # print(tmp) # [key]による要素の取得#2 # dict1 = { # "ichigo" : "red and sweet", # "human" : "ambrose", # "mike" : "human and cool", # } # tmp = dict1.get('human') # print(tmp) # [key]による要素の取得#3 # dict1 = { # "ichigo" : "red and sweet", # "human" : "ambrose", # "mike" : "human and cool", # } # tmp = dict1.get('boy','No data') # print(tmp) # keys()によるすべてのキーの取得 # dict1 = { # "ichigo" : "red and sweet", # "human" : "ambrose", # "mike" : "human and cool", # } # tmp = dict1.keys() # print(tmp) # tmp2 = list(dict1.keys()) # print(tmp2) # values()によるすべての値の取得 # dict1 = { # "ichigo" : "red and sweet", # "human" : "ambrose", # "mike" : "human and cool", # } # tmp = dict1.values() # print(tmp) # items()によるすべてのキー/値ペアの取得 # dict1 = { # "ichigo" : "red and sweet", # "human" : "ambrose", # "mike" : "human and cool", # } # tmp = dict1.items() # print(tmp) # = and copy()#1 # dict1 = { # "ichigo" : "red and sweet", # "human" : "ambrose", # "mike" : "human and cool", # } # dict2 = dict1 # dict1['human'] = 'trush' # print(dict1) # print(dict2) # = and copy()#2 dict1 = { "ichigo": "red and sweet", "human": "ambrose", "mike": "human and cool", } dict2 = dict1.copy() dict1["human"] = "trush" print(dict1) print(dict2)
""" Code Challenge: dataset: BreadBasket_DMS.csv Q1. In this code challenge, you are given a dataset which has data and time wise transaction on a bakery retail store. 1. Draw the pie chart of top 15 selling items. 2. Find the associations of items where min support should be 0.0025, min_confidence=0.2, min_lift=3. 3. Out of given results sets, show only names of the associated item from given result row wise. """ import pandas as pd import numpy as np from apyori import apriori import matplotlib.pyplot as plt df=pd.read_csv("BreadBasket_DMS.csv") a=df["Item"].value_counts() a=a.head(15) plt.pie(a.values,labels=a.index) transactions=[] y=[] with open("BreadBasket_DMS.csv") as fp: for item in fp: x=item.split(",") y.append(x[2]) y.append(x[3]) transactions.append(y) y=[] #transactions.remove(transactions[0]) list1=[] list2=[] count=1 for item in transactions: if( not item): continue if(item[0] == str(count)): list1.append(item[1]) else: count=item[0] list2.append(list1) list1=[] list1.append(item[1]) list2.remove(list2[0]) rules = apriori(list2, min_support = 0.0025, min_confidence = 0.2, min_lift = 3) # Visualising the results results = list(rules) for item in results: # first index of the inner list # Contains base item and add item pair = item[0] items = [x for x in pair] print("Rule: " + items[0] + " -> " + items[1]) #second index of the inner list print("Support: " + str(item[1])) #third index of the list located at 0th #of the third index of the inner list print("Confidence: " + str(item[2][0][2])) print("Lift: " + str(item[2][0][3])) print("=====================================")
""" Code Challenges 02: (House Data) This is kings house society data. In particular, we will: • Use Linear Regression and see the results • Use Lasso (L1) and see the resuls • Use Ridge and see the score """ #importing import pandas as pd import numpy as np dataset=pd.read_csv("kc_house_data.csv") dataset.isnull().any(axis=0) dataset["sqft_above"]=dataset["sqft_above"].fillna(dataset["sqft_above"].mean()) features=dataset.drop(["id","date","price"],axis=1).values labels=dataset.iloc[:,2].values from sklearn.model_selection import train_test_split features_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size=0.25, random_state=0) #train the algo from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(features_train, labels_train) #To see the value of the intercept and slop calculated by the linear regression algorithm for our dataset, execute the following code. print(regressor.intercept_) print (regressor.coef_) """ This means that for every one unit of change in hours studied, the change in the score is about 9.91%. """ #making predictions #To make pre-dictions on the test data, execute the following script: labels_pred = regressor.predict(features_test) #To compare the actual output values for features_test with the predicted values, execute the following script df = pd.DataFrame({'Actual': labels_test, 'Predicted': labels_pred}) print ( df ) from sklearn import metrics print('Mean Absolute Error:', metrics.mean_absolute_error(labels_test, labels_pred)) print('Mean Squared Error:', metrics.mean_squared_error(labels_test, labels_pred)) print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(labels_test, labels_pred))) print (np.mean(dataset.values[:,2])) Score=regressor.score(features_train,labels_train) Score1=regressor.score(features_test,labels_test) #importing other models from sklearn.linear_model import LinearRegression from sklearn.linear_model import Lasso from sklearn.linear_model import Ridge from sklearn.linear_model import ElasticNet lm = LinearRegression () lm_lasso = Lasso() lm_ridge = Ridge() lm.fit(features_train, labels_train) lm_lasso.fit(features_train, labels_train) lm_ridge.fit(features_train, labels_train) #R2 Value print ("RSquare Value for Sim0ple Regresssion TEST data is-") print (np.round (lm .score(features_test,labels_test)*100,2)) print ("RSquare Value for Lasso Regresssion TEST data is-") print (np.round (lm_lasso.score(features_test,labels_test)*100,2)) print ("RSquare Value for Ridge Regresssion TEST data is-") print (np.round (lm_ridge.score(features_test,labels_test)*100,2)) #Predict on test and training data predict_test_lm = lm.predict(features_test ) predict_test_lasso = lm_lasso.predict (features_test) predict_test_ridge = lm_ridge.predict (features_test) #Print the Loss Funtion - MSE & MAE import numpy as np from sklearn import metrics print ("Simple Regression Mean Square Error (MSE) for TEST data is") print (np.round (metrics .mean_squared_error(labels_test, predict_test_lm),2) ) print ("Lasso Regression Mean Square Error (MSE) for TEST data is") print (np.round (metrics .mean_squared_error(labels_test, predict_test_lasso),2)) print ("Ridge Regression Mean Square Error (MSE) for TEST data is") print (np.round (metrics .mean_squared_error(labels_test, predict_test_ridge),2))
""" Q1. (Create a program that fulfills the following specification.) deliveryfleet.csv Import deliveryfleet.csv file Here we need Two driver features: mean distance driven per day (Distance_feature) and the mean percentage of time a driver was >5 mph over the speed limit (speeding_feature). Perform K-means clustering to distinguish urban drivers and rural drivers. Perform K-means clustering again to further distinguish speeding drivers from those who follow speed limits, in addition to the rural vs. urban division. Label accordingly for the 4 groups. """ import pandas as pd import numpy as np import matplotlib.pyplot as plt dataset=pd.read_csv("deliveryfleet.csv") dataset.isnull().any(0) features=dataset.iloc[:,1:].values plt.scatter(features[:,0],features[:,1]) from sklearn.cluster import KMeans kmean=KMeans(n_clusters=2,init='k-means++',random_state=0) pred_cluster=kmean.fit_predict(features) plt.scatter(features[pred_cluster == 0, 0], features[pred_cluster == 0, 1], c = 'blue', label = 'Rural') plt.scatter(features[pred_cluster == 1, 0], features[pred_cluster == 1, 1], c = 'red', label = 'Urban') plt.scatter(kmean.cluster_centers_[:, 0], kmean.cluster_centers_[:, 1], c = 'green', label = 'Centroids') plt.title('Clusters of datapoints') plt.xlabel('distance') plt.ylabel('speed') plt.legend() plt.show() #Perform K-means clustering again to further distinguish speeding drivers from those who follow speed limits, in addition to the rural vs. urban division. # Label accordingly for the 4 groups. kmean=KMeans(n_clusters=4,init='k-means++',random_state=0) pred_cluster=kmean.fit_predict(features) plt.scatter(features[pred_cluster == 0, 0], features[pred_cluster == 0, 1], c = 'blue', label = 'Rural_limit') plt.scatter(features[pred_cluster == 1, 0], features[pred_cluster == 1, 1], c = 'red', label = 'Urban_limit') plt.scatter(features[pred_cluster == 2, 0], features[pred_cluster == 2, 1], c = 'green', label = 'urban_speedy') plt.scatter(features[pred_cluster == 3, 0], features[pred_cluster == 3, 1], c = 'brown', label = 'rural_speedy') plt.scatter(kmean.cluster_centers_[:, 0], kmean.cluster_centers_[:, 1], c = 'yellow', label = 'Centroids') plt.title('Clusters of datapoints') plt.xlabel('distance') plt.ylabel('speed') plt.legend() plt.show()
""" Q2. (Create a program that fulfills the following specification.) The iris data set consists of 50 samples from each of three species of Iris flower (Iris setosa, Iris virginica and Iris versicolor). Four features were measured from each sample: the length and the width of the sepals and petals, in centimetres (iris.data). Import the iris dataset already in sklearn module using the following command:\ """ import pandas as pd import numpy as np from sklearn import datasets data_iris=datasets.load_iris() features=pd.DataFrame(data_iris.data,columns=data_iris.feature_names).values labels=pd.DataFrame(data_iris.target,columns=["class"]).values from sklearn.decomposition import PCA pca = PCA(n_components = 2) features= pca.fit_transform(features) explained_variance = pca.explained_variance_ratio_ from sklearn.cluster import KMeans wcss = [] for i in range(1, 15): kmeans = KMeans(n_clusters = i, init = 'k-means++', random_state = 0) kmeans.fit(features) wcss.append(kmeans.inertia_) import matplotlib.pyplot as plt plt.plot(range(1, 15), wcss) plt.title('Elbow Method') plt.xlabel('Number of Clusters') plt.ylabel('WCSS') plt.show() kmeans = KMeans(n_clusters = 3, init = 'k-means++', random_state = 0) pred_cluster = kmeans.fit_predict(features) plt.scatter(features[pred_cluster == 0, 0], features[pred_cluster == 0, 1], c = 'blue', label = 'setosa') plt.scatter(features[pred_cluster == 1, 0], features[pred_cluster == 1, 1], c = 'red', label = 'verginica') plt.scatter(features[pred_cluster == 2, 0], features[pred_cluster == 2, 1], c = 'green', label = 'versicolor') plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], c = 'yellow', label = 'Centroids') plt.title('Clusters of datapoints') plt.xlabel('X Cordindates') plt.ylabel('Y Cordinates') plt.legend() plt.show()
""" Code Challenge Name: Last Line Filename: lastline.py Problem Statement: Ask the user for the name of a text file. Display the final line of that file. Think of ways in which you can solve this problem, and how it might relate to your daily work with Python. """ input1=raw_input("enter file name with .txt extension>") count=0 try: file = open(input1, "rt" ) print(file.readlines()[-1]) except IOError: print ( "File not Found") except Exception: print ( "This is a general exception") finally: #print ("this is called always") file.close()
# Interactive Guess the Number Game """ Challenge 1 The computer will think of a random number from 1 to 10 as secret number Then ask you ( Player ) to guess the number and store as guess number Compare the guess number with the secret number If the player guesses the right number he wins, so print player wins and computer lose. If the player guesses the wrong number, then he loses so print player lose and computer wins. """ """ Challenge 2 Print the secret number and guess number when Player loses using format function """ """ Challenge 3 Print too HIGH or too LOW messages for bad guesses using elif. """ """ Challenge 4 Let people play again and again until he guesses the right secret number """ """ Challenge 5 Limit the number of guesses to maximum 6 tries """ """ Challenge 6 Print the number of tries left """ """ Challenge 7 Lets give user the option to play again """ """ Challenge 8 Catch when someone submits a non integer """ import random count=0 while count <=6: count = count + 1 num2=random.randint(1,10) num=input("choose no from 0 to 9:") num1=str(num) num3=str(num2) if(num == num2): print("Congratulations You beat computer") break elif (type(num) != int): print("Your choice is not appropriate , Try again") continue elif (num > num2): print("too high") print("Your choice is {}, correct answer is {}.".format(num1,num3)) elif (num < num2): print("too Low") print("Your choice is {}, correct answer is {}.".format(num1,num3)) else: print("Invalid choice") rem =str(6 - count) print("Remaining chances are " + rem ) if(count == 6): print("Sorry you exceed the limit") break else: ch=raw_input("press Y to continue or any key to exit:") if(ch == 'y'): continue else: break
""" Code Challenge Name: Pattern Builder Filename: pattern.py Problem Statement: Write a Python program to construct the following pattern. Take input from User. Input: 5 Output: Below is the output of execution of this program. * * * * * * * * * * * * * * * * * * * * * * * * * """ inp = input("enter number:") i=1 while i!=inp+1: print("*"*i) i=i+1 i=inp while i!=0: print("*"*i) i=i-1
if __name__ == '__main__': kv = lambda x, t, i: t(x.split(":")[i]) dic = lambda a: dict([(kv(x, str, 0), kv(x, int, 1)) for x in a.split(",")]) d = dic("语文:80,数学:82,英语:90,物理:85,化学:88,美术:80") s = 0 for v in d.values(): s += v print("总分为{}, 平均分为{:.1f}".format(s, s / len(d)))