text
stringlengths
37
1.41M
import random # minus print('minus') a = [1, 2, 3, 4, 5, 6, 7, 8, 9] b = [2, 5, 7] c = [item for item in a if item not in b] print(c) # add print('add') a = [1, 2, 3] b = [3, 4, 5, 6] c = a + b print(c) # shuffle print('shuffle') a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] slice = random.sample(a, 5) print(slice) # shuffle and minus print('shuffle and minus') a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] slice = random.sample(a, 3) minus = [item for item in a if item not in slice] print(slice) print(minus) # shuffle the units in the list print('shuffle the units in the list') a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] random.shuffle(a) print(a)
# Skyline.py by Dave Musicant # Note from Adam Canady - this code was used to test the class in building.py from building import * from graphics import * def main(): # Create a window object and make it appear windowWidth = 800 windowHeight = 500 window = GraphWin('Skyline',windowWidth,windowHeight) # Generate 50 building objects, and draw each one. # Sum up the area as you go along. totalArea = 0 for i in range(50): building = Building() building.setHeightRandom(windowHeight) building.setWidthRandom(windowWidth/5) building.setColorRandom() building.setLocationRandom(windowWidth) building.draw(window,windowHeight) totalArea = totalArea + building.area() # Display results. print "Total area =", totalArea raw_input("Press enter when done") window.close() main()
# input.py # Written by Dave Musicant # This program demonstrates how to accept input from the user. currentString = raw_input('What is the current year? ') currentyear = int(currentString) birthString = raw_input('In what year were you born? ') birthyear = int(birthString) difference = currentyear - birthyear print 'Hey! You\'re approximately', difference, 'years old!'
import math import turtle import random """ This program draws arrows randomly in a box. Author: Sanchit Monga language: python """ """ declaring global variables that will be used throughout the program """ MAX_SIZE=30 MAX_DISTANCE=30 MAX_ANGLE=30 BOUNDING_BOX=100 MAX_FIGURES=500 """ This function calculates and returns the value of area of an equilateral triangle. """ def area_of_triangle(length): area=(math.sqrt(3)*length**2)/4 return(area) """ This function checks whether the turtle draws arrows in the designated area or not and moves the turtle by 180 degrees if the turtle tries to go out of the box """ def boundary_check(): if(turtle.xcor()+MAX_SIZE>BOUNDING_BOX): turtle.setheading(180) elif(turtle.ycor()+MAX_SIZE>BOUNDING_BOX): turtle.setheading(270) elif(turtle.xcor()-MAX_SIZE<-BOUNDING_BOX): turtle.setheading(0) elif(turtle.ycor()-MAX_SIZE<-BOUNDING_BOX): turtle.setheading(90) """ This function draws an equilateral triangle using turtle This function uses the RGB values to randomly print the colors of the figures """ def triangle(length): boundary_check() r=random.randint(1,255) g=random.randint(1,255) b=random.randint(1,255) turtle.colormode(255) turtle.pencolor((r,g,b)) turtle.fillcolor((r,g,b)) turtle.begin_fill() turtle.forward(length) turtle.left(120) turtle.forward(length) turtle.left(120) turtle.forward(length) turtle.left(120) turtle.end_fill() """ This function calls the triangle function and draws the number of traingles as they are input by the user. This function uses recursive technique and prints the arrows randomly throughout the board This function also computes the total area of the triangle that is shaded and returns the value """ def draw_figures_rec(depth,length,ar1): if(depth>0 and length>0): triangle(length) turtle.up() turtle.forward(random.randint(1,MAX_DISTANCE)) turtle.left(random.randint(-MAX_ANGLE,MAX_ANGLE)) turtle.down() ar1=ar1+area_of_triangle(length) return(draw_figures_rec(depth-1,random.randint(1,MAX_SIZE),ar1)) else: return ar1 """ This function is same as the draw_figures_rec function, It also calls the triangle function and prints the arrows randomly throughout the board This function also prints the total shaded area of the triangle. """ def draw_figures_iter(depth,length): ar2=0 while(depth>0 and length>0): triangle(length) turtle.up() turtle.forward(random.randint(1,MAX_DISTANCE)) turtle.left(random.randint(-MAX_ANGLE,MAX_ANGLE)) turtle.down() ar2=ar2+area_of_triangle(length) length=random.randint(1,MAX_SIZE) depth=depth-1 if(depth==0 or length==0): return ar2 """ This function draws the board of 200 by 200 pixels and moves the turtle to the center of the figure after drawing it """ def boundary(): turtle.up() turtle.right(90) turtle.forward(200) turtle.left(90) turtle.down() turtle.forward(200) turtle.left(90) turtle.forward(400) turtle.left(90) turtle.forward(400) turtle.left(90) turtle.forward(400) turtle.left(90) turtle.forward(200) turtle.left(90) turtle.up() turtle.forward(200) turtle.right(90) turtle.down() """ So the main function takes the input from the user for the total number of the arrows and calls the draw_figures_rec function and draw_figures_iter. It prints the value of the total shaded area in the figure. """ def main(): a=int(input("arrows (0-500) ")) turtle.speed(0) if(a<=MAX_FIGURES): boundary() sum=draw_figures_rec(a,random.randint(1,30),0) print("The total area is ",sum,"units") v=input("Hit enter to continue...") turtle.reset() turtle.speed(0) boundary() sum1=draw_figures_iter(a,random.randint(1,30)) print("The total area is ",sum1,"units") print("CLose the canvas window to quit.") else: print("Arrows must be between 0 and 500 inclusive") turtle.done() main()
""" author:Sanchit Monga Lang: Python Purpose: This program performs various operations on the nodes """ from linked_code import LinkNode as Node import linked_code def convert_to_nodes(dna_string): """ This function takes the string as the input and convert it into the node data structure """ if(dna_string==""): return None else: return Node(dna_string[0],convert_to_nodes(dna_string[1:])) def is_match(dna_seq1, dna_seq2): """ This function takes the input of 2 DNA sequences and matches whether the two sequences are true or not """ if dna_seq1==None and dna_seq2==None: return True elif dna_seq1==None or dna_seq2==None: return False elif dna_seq1.value!=dna_seq2.value: return False else: return is_match(dna_seq1.rest, dna_seq2.rest) def insertion(dna_seq1,dna_seq2,index): """ This function takes the input of 2 DNA sequences and an index and insert the second DNA sequence in the first sequence at the specified index """ if index==0: return linked_code.concatenate(dna_seq2,dna_seq1) elif dna_seq1==None: raise IndexError ("Invalid Insertion Index") else: return (Node(dna_seq1.value,insertion(dna_seq1.rest,dna_seq2, index-1))) def is_palindrome(dna_seq): """ This function takes the DNA sequence in the form of Node data structure and checks whether it is palindrome or not """ if(dna_seq==None): return True elif(linked_code.length_rec(dna_seq)==1): return True elif(dna_seq.value==linked_code.value_at(dna_seq,(linked_code.length_tail_rec(dna_seq)-1))): return is_palindrome(linked_code.remove_at(linked_code.length_rec(dna_seq.rest)-1,dna_seq.rest)) else: return False def substitution(dna_seq,index,base): """ This function takes the input of the DNA sequence, index at which the base has to be replaced and the base by which the original sequence will be replaced """ if linked_code.length_rec(dna_seq)<index: raise IndexError ("Invalid Insertion Index") else: return linked_code.insert_at(index,base,linked_code.remove_at(index,dna_seq)) def convert_to_string(dna_seq): """ This function converts the DNA sequence which is a node datta structure into the string data type """ if(dna_seq==None): return "" else: return(str(dna_seq.value)+convert_to_string(dna_seq.rest)) def is_pairing(dna_seq1,dna_seq2): """ This function takes 2 DNA sequences in the form of Node data structure and check whether the corrersponding elements are matching or not """ if(dna_seq1==None and dna_seq2== None): return True elif(dna_seq1==None or dna_seq2==None): return False elif(dna_seq1.value=='A' and dna_seq2.value=='T'): return is_pairing(dna_seq1.rest,dna_seq2.rest) elif(dna_seq1.value=='G' and dna_seq2.value=='C'): return is_pairing(dna_seq1.rest,dna_seq2.rest) elif(dna_seq1.value=='T' and dna_seq2.value=='A'): return is_pairing(dna_seq1.rest,dna_seq2.rest) elif(dna_seq1.value=='C' and dna_seq2.value=='G'): return is_pairing(dna_seq1.rest,dna_seq2.rest) else: return False def deletion(dna_seq, idx, segment_size): """ This function takes the DNA sequence , index at which the element has to deleted and the segment size that has to be deleted """ if(segment_size==0): return dna_seq elif(segment_size+idx>linked_code.length_rec(dna_seq)): raise IndexError("Sequence out of range") else: return deletion(linked_code.remove_at(idx,dna_seq), idx,segment_size-1) def duplication(dna_seq, idx, segment_size): """ This function takes the dna_seq, index a and the segment size that has to be copied and added after that """ if segment_size!=0: a=segment_size while(segment_size>0): v=linked_code.value_at(dna_seq,idx) dna_seq=linked_code.insert_at(idx+a,v,dna_seq) idx+=1 segment_size-=1 return dna_seq else: return dna_seq
import sqlite3 db = sqlite3.connect("myshop.db") cursor = db.cursor() cursor.execute('SELECT * FROM Customer order by Town') for row in cursor: print '-'*10 print 'ID:', row[0] print 'First name:', row[1] print 'Second name:', row[2] print '-'*10 cursor.close() db.close()
#!/usr/bin/env python # coding: utf-8 # In[2]: #Introduction: #Pandas is a Python library. #Pandas is used to analyze data. #Why Use Pandas? #Pandas allows us to analyze big data and make conclusions based on statistical theories. #Pandas can clean messy data sets, and make them readable and relevant. #Relevant data is very important in data science. # In[9]: #Pandas supports two data structures: #>Series #>Dataframe #---------------------------Series---------------------------------- #Pandas is a one-dimensional labeled array and capable of holding data of any type (integer, string, float, python objects, etc.) #Syntax: pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False) #Parameters: #data: array- Contains data stored in Series. #index: array-like or Index (1d) #dtype: str, numpy.dtype, or ExtensionDtype, optional #name: str, optional #copy: bool, default False #Series holding the dictionary. import pandas as pd dic = { 'Id': 20, 'Name': 'Internity', 'State': 'wb','Age': 24} res = pd.Series(dic) (res) # In[6]: #---------------Dataframe-------------------- #Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes(rows and columns). # DataFrame can be created using a single list or a list of lists. import pandas as pd data = { "calories": [420, 380, 390], "duration": [50, 40, 45] } #load data into a DataFrame object: df = pd.DataFrame(data) print(df) # In[7]: #Locate Row print(df.loc[0]) # In[25]: #Panel in panda #pandas.Panel(data, items, major_axis, minor_axis, dtype, copy) # In[27]: #panel creation: import pandas as pd import numpy as np data = np.random.rand(2,4,5) p = pd.Panel(data) print p # In[28]: # Import pandas library import pandas as pd # initialize list of lists data = [['tom', 10], ['nick', 15], ['juli', 14]] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age']) # print dataframe. df # In[29]: #Creating Pandas Dataframe from a python objects #Creating DataFrame from dict of narray/lists import pandas as pd # initialise data of lists. data = {'Name':['Tom', 'Jack', 'nick', 'juli'], 'marks':[99, 98, 95, 90]} # Creates pandas DataFrame. df = pd.DataFrame(data, index =['rank1', 'rank2', 'rank3', 'rank4']) # print the data df # In[30]: #Creating Dataframe from list of dicts import pandas as pd # Initialise data to lists. data = [{'a': 1, 'b': 2, 'c':3}, {'a':10, 'b': 20, 'c': 30}] # Creates DataFrame. df = pd.DataFrame(data) # Print the data df # In[36]: import numpy as np # In[37]: # create 4x2 random array # array is a list of lists arr = np.random.rand(4, 2) arr # In[42]: #from a file: import pandas as pd # creating a data frame df = pd.read_csv("D:\Downloads\heart.csv") df # In[52]: df.head() # In[54]: df.tail() # In[55]: df.describe() # In[56]: df.info() # In[57]: #from api import requests import json # In[58]: url='https://api.covid19api.com/summary' r=requests.get(url) r # In[59]: json=r.json() json # In[60]: json.keys() # In[61]: json['Global'] # In[62]: json['Date'] # In[63]: type(json['Date']) # In[64]: type(json['Global']) # In[ ]:
fname = input("Enter file name: ") if len(fname) == 0: fname = 'romeo.txt' fh = open(fname) lst = list() # Iterates through each line in filehandle for line in fh: #Iterates through each word on line for i in line.split(): #Checks to see if word is already in list if not i in lst: #Appends words to list lst.append(i) lst.sort() print (lst)
## link = https://leetcode.com/problems/minimum-path-sum/ """ Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. """ grid = [[1,3,1],[1,5,1],[4,2,1]] """ 1 3 1 1 4 5 1 5 1 ==> 2 4 2 1 6 """ for i in range(1, len(grid[0])): grid[i][0] += grid[i-1][0] for i in range(1, len(grid[1])): grid[0][i] += grid[0][i-1] #print(grid) for row in range(1, len(grid[0])): for col in range(1, len(grid[1])): grid[row][col] += min( grid[row-1][col], grid[row][col-1] ) print(grid[-1][-1])
## https://leetcode.com/problems/2-keys-keyboard/ """ There is only one character 'A' on the screen of a notepad. You can perform two operations on this notepad for each step: Copy All: You can copy all the characters present on the screen (a partial copy is not allowed). Paste: You can paste the characters which are copied last time. Given an integer n, return the minimum number of operations to get the character 'A' exactly n times on the screen. """ n = 4 ## method 1 Mathematical Solution dp = [0] * (n+1) dp[0] = dp[1] = 0 for i in range(2, n+1): dp[i] = i for j in range(i-1, 1, -1): if i % j == 0: dp[i] = dp[j] + int(i/j) break print(dp[-1]) ## Method 2 DP solution
## https://leetcode.com/problems/coin-change/ """ You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. You may assume that you have an infinite number of each kind of coin. """ coins = [1,2,5] amount = 11 dp = [amount + 1] * (amount+1) dp[0] = 0 for i in range(1, amount+1): for c in coins: if c <= i: dp[i] = min(dp[i], dp[i-c] + 1) if dp[amount] == amount+1: print(-1) else: print(dp[-1])
""" 1. It finds the least elememt from the array and swap it with the first index element. 2. In sort algo 3. Not Stable """ arr = [8,77,4,1,6,2,7,-8] n = len(arr) ## method 1(Unstable Sort) for i in range(n): min_index = i for j in range(i+1,n): if arr[j] < arr[min_index]: min_index = j arr[min_index], arr[i] = arr[i], arr[min_index] print(arr) ## method 2 (making it stable) for i in range(n): min_index = i for j in range(i+1, n): if arr[j] < arr[min_index]: min_index = j ## swapping temp = arr[min_index] while min_index > i: arr[min_index] = arr[min_index-1] min_index -=1 arr[i] = temp print(arr)
#0.030 Class and Static Method Coding from datetime import datetime, timezone, timedelta class Timer: tz = timezone.utc #for all instance of class timer the time must be #the same time zone where program is running. @classmethod def set_tz(cls, offset , name): cls.tz = timezone(timedelta(hours=offset), name) def current_dt_utc(self): Timer.set_tz(-7,'MST') print(Timer.tz) t1 = Timer() t2 = Timer() print(t1.tz) print(t2.tz)
#********Deleting Attribute in Class******* class MyClass: language = 'python' version = '3.6' print(MyClass.version) #Output:- 3.6 #*******delattr delattr(MyClass, 'version') print(MyClass.version) #Output:- Exception
#0.024.1 Read Only Properties Conti #Caching Computed Property ''' Using Property setters is sometimes useful for controlling how other computed properties are cached. ''' ''' In Our Last program:- Circle :- is a class -->area :- is a computed property -->lazy computation :- only calculate area if requested. So if we save the value , it will save computation time in case of re- requested. -->cache value :- so if requested , we save the computation. ''' ''' In case of someone change the radius, We must have to know about it , and recalculate the area. need to able to invalidate the cache ''' ''' SO , Control setting the radius , using a property. --> So we are aware , when the property has been changed. ''' import math class Circle: def __init__(self , r): #private attribute _r to store radius. self._r = r #private attribute area to cache the area . #currently it is set to None. self._area = None #getter @property def radius(self): return self._r #setter @radius.setter def radius(self, r): if r < 0: raise ValueError('Radius must be non negative') self._r = r self._area = None #Invalidate Cache #Create a read only property for the area. @property def area(self): if self._area is None: self._area = math.pi * ( self.radius ** 2 ) return self._area P = Circle(2) print(P.area) #12.566370614359172
#********Setting Attribute in Class******* class MyClass: language = 'python' version = '3.6' print(MyClass.version) #Output:- 3.6 #setattr function setattr(MyClass,'version','4.2') print(MyClass.version) #Output:- 4.2 print(getattr(MyClass, 'version')) #Output:- 4.2 #We can use dot notation too MyClass.version = 5.2 print(MyClass.version) #Output:- 5.2 print(getattr(MyClass, 'version')) #Output:- 5.2 #**********To define a new attribute in our class setattr(MyClass, 'x', 100) #OR MyClass.y = 200 print(MyClass.x) print(MyClass.y)
#Function Attribute - Instance Methods ''' When we call a function which is inside a class , But from the instance. It Becomes a method. Which is function bound to perticular instance. That allows us inside the function body to use the state of perticular instance , that was passed in. ''' ''' We have to account for that extra argument , when we define functions in our classes - Otherwise we can not use them as methods bound to our instance. These Functions are usually called Instance Mathods:- ''' ''' NOTE:- Below:- def say_hello(self):- self will receive instance object. We often call this an instance method. At this point it is just a regular function. ''' class MyClass: def say_hello(self): print("Hello World") my_obj = MyClass() my_obj.say_hello ''' NOTE:- Now on above :- (my_obj.say_hello)it's a method. And is bound to my_obj. Function say_hello is bound to object my_obj. An instance of MyClass. ''' #OR print(my_obj.say_hello) #<bound method MyClass.say_hello of <__main__.MyClass object at 0x00000199C2547438>> my_obj.say_hello() #Hello World MyClass.say_hello(my_obj) #Hello World ''' Functions in our class can have there own paremeter. When we call corresponding instance method with argument --> they pass to the method as well. And the method receives the instance object reference as the first argument.. We have access to the instance (and class) attributes. ''' #class class MyClass: #class attribute language = 'Python' #Instance Mathod def say_hello(self, name): return f'Hello {name}! I am {self.language}.' #Instance of MyClass python = MyClass() # using below , I am invoking or calling bound method (say_hello) method bound to python. #As well passed extra Arg 'John' print(python.say_hello('John')) #in the backend-> MyClass.say_hello(python,'john') #Hello John! I am Python. #Another Instance of MyClass java = MyClass() #set property on the instance java.language = 'Java' #below if we call say_hello('John') on java object. #say_hello method has been bound with java object print(java.say_hello('John')) #So in the backend-> MyClass.say_hello(java,'john')
class MyClass: pass my_Obj = MyClass print(my_Obj) #<class '__main__.MyClass'> my_Obj = MyClass() #Calling MyClass print(my_Obj) # It will create an object of MyClass #<__main__.MyClass object at 0x0000022445CEE6D8> print(type(MyClass)) #type of class is type #<class 'type'> print(type(my_Obj)) #type of my_obj is MyClass #<class '__main__.MyClass'> print(isinstance(my_Obj,MyClass)) #my_Obj is instance of MyClass #True #****************Instantiating Class ''' When we call a class , a class instance object is created. This class instance object has its own NAMESPACE. This object has some attributes , python automatically implements to us. __dict__ :- Object local namespace __class__ :- tells us which class was used to instantiate the obj. ''' #below my_Obj-[instance of class] has its own namespace print(my_Obj.__dict__) #{} #below MyClass - [class] has its own namespace print(MyClass.__dict__)
# -*- coding:utf-8 -*- import numpy as np import matplotlib.pyplot as plt plt.figure(1) #创建图表1 plt.figure(2) #创建图表2 ax1 = plt.subplot(211) # ax2 = plt.subplot(212) x = np.linspace(0,3,100) for i in xrange(5): plt.figure(1) #选择图表1 plt.plot(x,np.exp(i*x/3)) plt.sca(ax1) #选择图表2 的子图1 plt.plot(x,np.sin(i*x)) plt.sca(ax2) plt.plot(x,np.cos(i*x)) plt.show()
# 1 kyu # Mine Sweeper # https://www.codewars.com/kata/mine-sweeper/python import numpy as np import queue from itertools import permutations class Minefield: def __init__(self, minefield, number_of_bombs): self.minefield, self.starting_positions = self.parse_map(minefield) self.n = number_of_bombs def solve(self): q = queue.Queue() [q.put(x) for x in self.starting_positions] maybe_stuck = 0 while 1: if (self.n - self.bombs_found() <= 0 and len(self.question_marks()) == 0) or q.empty(): if self.n - self.bombs_found() <= 0 and len(self.question_marks()) > 0: for qm in self.question_marks(): qm.value = open(qm.y, qm.x) if self.n - self.bombs_found() == len(self.question_marks()): if self.n - self.bombs_found() > 0: for qm in self.question_marks(): qm.value = 'x' if self.solved(): return self.map_to_string() if maybe_stuck == 0: # Put numbers adjacent to question marks in queue qms = self.question_marks() to_queue = set() for qm in qms: [to_queue.add(number) for number in qm.nearby_numbers()] [q.put(x) for x in to_queue] maybe_stuck = 1 continue else: type, solution = self.solve_stuck() if solution: # print(solution) # print('found a unique solution to this pickle') if type == 'mines': for bomb in solution: bomb.value = 'x' if type == 'safe': for confirmed_safe in solution: confirmed_safe.value = int(open(confirmed_safe.y, confirmed_safe.x)) # print(minefield.minefield) qms = self.question_marks() to_queue = set() for qm in qms: [to_queue.add(number) for number in qm.nearby_numbers()] [q.put(x) for x in to_queue] maybe_stuck = 0 continue # print(f'stuck at ({len(minefield.question_marks())} question marks)') # print(f'{n- minefield.bombs_found()} bombs remaining') print(self.minefield) return '?' box = q.get() unknowns = box.nearby_unknowns() bombs = box.nearby_bombs() # If all nearby bombs have been found, open everything else if len(unknowns) > 0 and box.value == len(bombs): for guy in unknowns: guy.value = int(open(guy.y, guy.x)) q.put(guy) maybe_stuck = 0 unknowns = box.nearby_unknowns() bombs = box.nearby_bombs() # Find bombs if box.value == len(unknowns)+len(bombs): for guy in unknowns: guy.value = 'x' maybe_stuck = 0 def solve_stuck(self, test_bombs=0): bombs_remaining = self.n - self.bombs_found() # Just a test parameter, ignore if test_bombs: bombs_remaining = test_bombs all_qms = self.question_marks() numbers = set() qms = set() for qm in all_qms: [numbers.add(number) for number in qm.nearby_numbers()] for number in numbers: [qms.add(qm) for qm in number.nearby_unknowns()] # Can change this if '?'s take too long if len(self.question_marks())*bombs_remaining > 100 and len(self.question_marks()) != len(qms): return None, False # picks 2 question marks at random to check if they could be it posibilities = [] if len(all_qms) == len(qms): bomb_range = range(bombs_remaining, bombs_remaining+1) else: bomb_range = range(1, bombs_remaining+1) for bomb_amount in bomb_range: ps = permutations(list(qms), bomb_amount) posibilities += list(set([tuple(sorted(p)) for p in ps])) unique_solution = True solution = None possible_values = [] for posibility in posibilities: # turn all cases to 'x' for bomb in posibility: bomb.value = 'x' # see if it's a valid solution for number in numbers: if number.value != number.n_nearby_bombs(): for bomb in posibility: bomb.value = '?' # print(f'{number.nearby_bombs()}') # print(f'{number.value} at {number.y}, {number.x} wasnt satisfied') break else: bad = False if len(posibility) == bombs_remaining: for qm in self.question_marks(): if qm.n_nearby_bombs() == 0: # print(f'empty spot at {qm.y}, {qm.x}') bad = True else: for qm in qms: if qm.value != 'x': if qm.n_nearby_bombs() == 0: # print(f'empty spot at {qm.y}, {qm.x}') bad = True if bad is False: possible_values.append(posibility) if solution: for bomb in posibility: bomb.value = '?' unique_solution = False if len(self.question_marks()) >= bombs_remaining: solution = posibility for bomb in posibility: bomb.value = '?' # PRINT POSSIBLE_VALUES: # print(possible_values) # print('Possible values at:') # for ps in possible_values: # print(ps) # for dimension in ps: # print(f'{dimension.y}, {dimension.x}') # print('we see they all agree on 1,1, so its gotta be correct') # END PRINT POSSIBLE_VALUES # GET VALUE IN COMMON FROM POSSIBLE_VALUES cpv = common_possible_values(possible_values) if cpv == []: safe_cases = unseen_possible_values(possible_values, qms) # if we don't have a solution, we return cpv # print('cpv', cpv) # print(self.minefield) if solution and unique_solution is True: return ('mines', solution) elif cpv != []: return ('mines', cpv) else: return ('safe', safe_cases) def parse_map(self, gamefield): self.bombs_remaining = 0 starting_positions = [] minefield = np.array([x.split(' ') for x in gamefield.split('\n')], dtype=np.object) for y, row in enumerate(minefield): for x, value in enumerate(row): minefield[y, x] = Node(y, x, value) if value != '?': self.bombs_remaining += 1 starting_positions.append(minefield[y, x]) for row in minefield: for node in row: node.get_paths(minefield) return minefield, starting_positions def map_to_string(self): rows = [] for row in self.minefield: rows.append(' '.join([str(node.value) for node in row])) return '\n'.join(rows) def solved(self): for row in self.minefield: for node in row: if node.value == '?': return False else: return True def question_marks(self): qs = [] for row in self.minefield: for node in row: if node.value == '?': qs.append(node) return qs def bombs_found(self): bs = [] for row in self.minefield: for node in row: if node.value == 'x': bs.append(node) return len(bs) class Node: def __init__(self, y, x, value): self.y = y self.x = x # Turns numbers into ints and leaves question marks self.value = value if value == '?' or value == 'x' else int(value) def get_paths(self, minefield): self.paths = [] height, width = minefield.shape if self.y > 0 and self.x > 0: self.paths.append(minefield[self.y-1, self.x-1]) if self.y < height-1 and self.x > 0: self.paths.append(minefield[self.y+1, self.x-1]) if self.x < width-1 and self.y > 0: self.paths.append(minefield[self.y-1, self.x+1]) if self.x < width-1 and self.y < height-1: self.paths.append(minefield[self.y+1, self.x+1]) if self.y > 0: self.paths.append(minefield[self.y-1, self.x]) if self.y < height-1: self.paths.append(minefield[self.y+1, self.x]) if self.x > 0: self.paths.append(minefield[self.y, self.x-1]) if self.x < width-1: self.paths.append(minefield[self.y, self.x+1]) def nearby_unknowns(self): return [box for box in self.paths if box.value == '?'] def nearby_bombs(self): return [box for box in self.paths if box.value == 'x'] def nearby_numbers(self): return [box for box in self.paths if isinstance(box.value, int)] def n_nearby_unknowns(self): return sum(1 for box in self.paths if box.value == '?') def n_nearby_bombs(self): return sum(1 for box in self.paths if box.value == 'x') def n_nearby_numbers(self): return sum(1 for box in self.paths if isinstance(box.value, int)) def __repr__(self): return str(self.value) def __gt__(self, other): return id(self) > id(other) def common_possible_values(possible_values): values = set() for guy in possible_values: for ps in guy: values.add(ps) values = list(values) common_values = [] for value in values: for every_one in possible_values: if value not in every_one: break else: common_values.append(value) return common_values def unseen_possible_values(possible_values, unknowns): qms = list(unknowns) values = set() for guy in possible_values: for ps in guy: values.add(ps) values = list(values) unseen_values = [] # print(values) # print(qms) for qm in qms: if qm not in values: unseen_values.append(qm) return unseen_values def solve_mine(mapa, n): minefield = Minefield(mapa, n) return minefield.solve() # TESTING s = ''' 1 ? ? 2 ? ? x 2 1 '''.strip() # this one has 3 bombs V s = ''' 1 2 x 1 ? ? 2 1 ? ? 2 1 ? ? 2 x ? ? ? 2 ? ? ? 1 '''.strip() s = ''' x 2 1 2 ? ? 1 ? ? 2 ? ? 2 ? ? 2 ? ? '''.strip() s = ''' 1 2 2 1 0 0 2 x x 2 1 1 2 3 ? ? ? ? 1 1 ? ? ? ? '''.strip() s = ''' x 2 x 2 x 1 1 x 2 1 1 2 1 2 1 1 1 2 ? ? 0 0 1 1 1 0 0 1 ? ? 0 0 1 x 1 1 1 2 ? ? 0 0 1 1 1 1 x 2 ? ? 0 0 0 0 0 1 1 2 ? ? '''.strip() # s = ''' # 1 ? 1 0 0 1 ? 1 # 2 ? 2 2 2 3 ? 2 # x 3 ? ? ? ? ? 1 # 1 2 ? ? ? ? ? 2 # 0 1 ? ? ? ? ? 1 # '''.strip() s = ''' x 1 ? ? ? ? ? ? ? '''.strip() # Testing for advanced situations: # minefield = Minefield(s) # test = stuck_solver(minefield, 2, test=True) # if test[1]: # if test[0] == 'safe': # print(f'Found safe square(s) at:') # if test[0] == 'mines': # print(f'Found mine(s) at:') # [print(f'({case.y}, {case.x})') for case in test[1]] # else: # print('Couldn\'t solve this situation.')
def solution(numbers): answer = 0 for i in range(1,10): if i not in numbers: answer += i return answer print(solution([1,2,3,4,6,7,8,0])) print(solution([5,8,4,0,6,7,9]))
#o comando 'from' pode serusado para chamar um arquivo python e o comando 'import' pode chamar todo o arquivo ou somente #um módulo ou definição ('def') para este caso usa-se o 'from' antes. Lembrando de usar o comando 'main'(if __name__ == '__main__':) # no arquivo origem para chamar a classe from aula7_televisao import Televisao from aula7_calculadora1 import Calculadora from aula8_contador_letras import contador_letras, teste if __name__ == '__main__': televisao = Televisao() print(televisao.ligada) televisao.power() print(televisao.ligada) calculadora= Calculadora(5, 10) print(calculadora.soma()) lista= ['cachorro', 'gato', 'elefante'] total_letras = contador_letras(lista) print('total de letras por palavra da lista: {}'.format(total_letras)) print(teste())
#trabalhando com APIs. a biblioteca 'request' é: Requests is an elegant and simple HTTP library for Python #o commando '.get' é usado para obter os dados do local citado entre ( ) import requests def retorna_dados_cep(cep): response = requests.get('http://viacep.com.br/ws/{}/json/'.format(cep)) print(response.status_code) #o resultado 200 significa que teve sucesso no requerimento print(response.json()) #o comando '.json' estabelece um formato para troca de dados entre programas, traz os dados em uma lista dados_cep = response.json() print(dados_cep['logradouro']) print(dados_cep['complemento']) return dados_cep def retorna_dados_pokemon(pokemon): response = requests.get('https://pokeapi.co/api/v2/pokemon/{}/'.format(pokemon)) dados_pokemon = response.json() return dados_pokemon def retorna_response(url): response = requests.get(url) return response.text if __name__ == '__main__': response = retorna_response('https://globallab.org/en/#.XwCPOudv_IU') print(response) #este exemplo acima mostra toda a programação de uma página de internet sem renderização # retorna_dados_cep('01001000') # dados_pokemon = retorna_dados_pokemon('pikachu') # print(dados_pokemon['sprites']['front_shiny'])
def remove_element(nums, val): i = 0 while i < len(nums): if nums[i] == val: del nums[i] else: i += 1 return len(nums) print(remove_element([0,1,2,2,3,0,4,2],2)) #5
# = in python means assigning a number. so when dealing with operators and you want to mean equal to alone you use double equal to signs # e.g. d=1 e=2 print(d==e) # inequality operator print(d !=e) # comparison operators are used with conditional statements which are 'if' statements # Logical operators # and - all conditions must be true # OR - At least one condition must be true # true and true - true # true and false - false # true or false - true # false or false - false # Not - It is to negate conditions print(True and False) print(not (True and False)) print(not (True and False or True)) # and is treated as multiplication # or is treated as addition print(not (1<3 and 2>4 or 3>3))
#Alfredo velasquez. P1E2. CONVERTIR DE CENTRIGRADOS A FAHRENHEIT c = float(input('Introduce los grados centigrados: ')) f = c*(9/5)+32 print('Son %f grados fahrenheit' % f)
def make_sqaure(size): pass def make_rectangle(length, width): pass def make_triangle(size): pass def main(): while(True): print('Hello, please enter what to print') print('1\tsquare') print('2\trectangle') print('3\ttriangle') shape = (int)(input('Input: ')) if(shape == 1): size = (int)(input('Input size:')) make_sqaure(size) elif(shape == 2): length = (int)(input('Input length: ')) width = (int)(input('Input width: ')) make_rectangle(length, width) elif(shape == 3): size = (int)(input('Input size: ')) make_triangle(size) main()
def insertionSort(b): for i in range(1, len(b)): up = b[i] j = i -1 while j >= 0 and b[j] > up: b[j+1] = b[j] j -= 1 b[j + 1] = up return b def bucketSort(x): arr = [] slot_num = 10 for i in range(slot_num): arr.append([]) # Put array elements in different buckets for j in x: index_b = int(slot_num * j) arr[index_b].append(j) # Sort individual buckets for i in range(slot_num): arr[i] = insertionSort(arr[i]) # Concatenate the result k = 0 for i in range(slot_num): for j in range(len(arr[i])): x[k] = arr[i][j] k += 1 return x # Driver code x = [0.567, 0.234, 0.123, 0.678, 0.998] print ("Sorted array is: ") print(bucketSort(x))
#Reandom number guesser program import random n = random.randint(1,100) chance = 3 while(chance): print("Guess a number") num = int(input()) if(chance != 1): if(num == n): print('Hola You have guessed the right number!!!!') elif(num > n): print("You are a little high up. Try guessing a smaller number!") else: print("You are a little low down. Try guessing a larger number!") else: if(num == n): print('Hola You have guessed the right number!!!!') else: print("Sorry you have run out of luck!") print("The correct number was {} !".format(n)) chance -= 1
# 행맨 게임 import random words = ["apple","coffee","guitar","harmony","programmers","spaghetti"] question = random.choice(words) letters = "" print("-"*50) print("Welcome To Hangman Game") print("-"*50) life = len(questions) + 2 while True: answer = True for w in question: if w in letters: print(w, end="") else: print("_", end=" ") answer = False print() if answer: print("^^ Congraulations!!") break if life == 0: print("--; You Died") break letter = input("Guess a letter: ") if letter not in letters: letters += letter if letter in question: print("YES") else: life -= 1 print(f"NO! Your life {life}") print() print("-"*50) print("Goodbye") print("-"*50)
# Binomial Dist #para atma problemi: # p = olasilik = 0.5 # n = deneyin gerceklestirilme sayisi # tura = p # yazi = 1-p '''para 6 kere atiliyorsa 3 tura cikmasi maksimum olasilik, 1 tura 5 yazi cikmasi minimum olasilik''' from scipy.stats import binom import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) x = range(7) n, p = 6, 0.5 rv = binom(n, p) ax.vlines(x, 0, rv.pmf(x), colors='k', linestyles='-', lw=1,label='Probablity of Success') ax.legend(loc='best', frameon=False) plt.show() # Std import statistics # creating a simple data - set sample = [11, 21, 78, 3, 64] # Prints standard deviation # xbar is set to default value of 1 print("Standard Deviation of sample is % s " % (statistics.stdev(sample)))
#Time complexity: O(n+k) where n is the number of elements in input array #and k is the range of the input #Auxiliary Space: O(n+k) #The main problem with this counting sort is that we cannot sort the elements #if we have negative numbers in it. Getting around that requires storing the #count of the minimum element at zero index.git def main(): print("Input a string: ") data = str(input()) print("%s" %("".join(countingSort(data)))) def countingSort(data): #The output character array containing the sorted data output = [0 for i in range(256)] #Count array to store count of individual characters count = [0 for i in range(256)] #For storing the resulting answer answer = ["" for _ in data] #store the count of each character for i in data: count[ord(i)] += 1 #Change count[i] so that count[i] now contains actual #position of this character in the output array for i in range(256): count[i] += count[i-1] #Build the output character array for i in range(len(data)): output[count[ord(data[i])]-1] = data[i] count[ord(data[i])] -= 1 #Copy the output array to the answer array, #now sorted for i in range(len(data)): answer[i] = output[i] return answer
def fact(n): out = 1 for i in range(1, n + 1): out = out * i return out def combination(m, n): res = fact(m) / (fact(m-n) * fact(n)) return int(res) def pascal_row(n): out = [] for i in range(n+1): temp = combination(n, i) out.append(temp) return out def pascal(rows): out = [] for i in range(1, rows+1): temp = pascal_row(i) out.append(temp) return out res= pascal(6) print(res)
# r --> readable # w --> writeable # a --> append # t --> text # b --> bytes # + f = open("output.txt", mode='r+') # text = f.read() f.seek(10, 2) f.write("hello") # print(text)
class Positives(object): def __init__(self): self.current = 0 def __next__(self): result = self.current self.current += 1 return result def __iter__(self): return self counts = [1, 2, 3] for item in counts: print(item) i = iter(counts) try: while True: item = next(i) print(item) except StopIteration: pass try: fp = open("sample.txt") except IOError as e: print('Unable to do this!: ', e) '''re-raise the error''' raise test_list = [1, 2, 3, 4, 5, 6, 7] def output_list(rlist): iter_list = iter(rlist) try: while True: print(next(iter_list)) except StopIteration as e: print('Come to the end of the list!:', e) output_list(test_list) iter_list = iter(test_list) for item in iter_list: print(item) def factors(n): results = [] for k in range(1, n+1): if n % k == 0: results.append(k) return results print(factors(100)) def factors(n): for k in range(1, n+1): if n % k == 0: yield k for ft in factors(100): print(ft) n = 10 square = [k*k for k in range(1, n+1) if k in (1, 2, 3, 4, 5)] print(square)
def fib(n): if n == 1: return 0 elif n == 2: return 1 else: return fib(n-1) - fib(n-2) print(fib(3)) def memo(f): cache = {} def memoized(n): if n not in cache: cache[n] = f(n) return cache[n] return memoized fib = memo(fib) fib(40) class Rlist(object): class EmptyList(object): def __len__(self): return 0 empty = EmptyList() # define an empty list def __init__(self, first, rest=empty): self.first = first self.rest = rest def __repr__(self): '''recursion''' args = repr(self.first) print(args) if self.rest is not Rlist.empty: args += ', {0}'.format(repr(self.rest)) return 'Rlist({0})'.format(args) def __len__(self): '''recursion''' return 1 + len(self.rest) def __getitem__(self, i): '''usage: s[i]''' '''recursion''' if i == 0: return self.first return self.rest[i-1] s = Rlist(1, Rlist(2, Rlist(3))) def extend_list(s1, s2): if s1 == Rlist.empty: return s2 return Rlist(s1, extend_list(s1.rest, s2)) def map_rlist(s, fn): if s is Rlist.empty: return s return Rlist(fn(s.first), map_rlist(s.rest, fn)) def filter_rlist(s, fn): if s is Rlist.empty: return s rest = filter_rlist(s.rest, fn) if fn(s.first): return Rlist(s.first, rest) return rest class Tree(object): def __init__(self, entry, left=None, right=None): self.entry = entry self.left = left self.right = right def __repr__(self): args = repr(self.entry) if self.left or self.right: args += ', {0}, {1}'.format(repr(self.left), repr(self.right)) return 'Tree({0})'.format(args) s = {1, 2, 3, 4, 5} try: x = 1/0 print(x) except ZeroDivisionError as e: print('handling a', type(e)) str(e) x = 0 class Exp(object): def __init__(self, operator, operands): self.operator = operator self.operands = operands def __repr__(self): return 'Exp({0}, {1})'.format(repr(self.operator), repr(self.operands)) def __str__(self): operands_strs = ', '.join(map(str, self.operands)) return '{0}({1})'.format(self.operator, operands_strs) from operator import mul from functools import reduce def calc_apply(operator, args): if operator in ('add', '+'): return sum(args) if operator in ('sub', '-'): if len(args) == 0: raise TypeError(operator + 'requires at least 1 argument') if len(args) == 1: return -args[0] return sum(args[:1] + [-arg for arg in args[1:]]) if operator in ('mul', '*'): return reduce(mul, args, 1) if operator in ('div', '/'): if len(args) != 2: raise TypeError(operator + ' requires exactly 2 arguments') numer, denom = args return numer/denom calc_apply('div', (1, 0, 3)) def read_eval_print_loop(): while True: expression_tree = calc_parse(input('calc> ')) print(calc_eval(expression_tree)) def calc_parse(line): tokens = tokenize(line) expression_tree = analyze(tokens) if len(tokens) > 0: raise SyntaxError('Extra token(s):' + ' '.join(tokens)) return expression_tree def tokenize(line): spaced = line.replace('(', ' ( ').replace(')', ' ) ').replace(',', ' , ') print(type(spaced)) spaced = spaced.split() print(type(spaced)) return spaced
# C = (F - 32) * 5/9 # Run F input to C output def C_temp(): F_degree = int(input('How many degrees in Fahrenheit? ')) C_degree = float(F_degree - 32) * (5/9) return C_degree print(str(C_temp()) + 'C')
#Time complexity O(n) and space complexity O(n) # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: Optional[TreeNode]) -> bool: #Initializing stack and previous element stack=[] prev= None if not root: return True #Traversing until stack is empty and applying inorder tarversal while root or stack: while root: stack.append(root) root=root.left root=stack.pop() if prev and prev.val>=root.val: return False prev=root root=root.right return True
# -*- coding: utf-8 -*- """ Created on Thu Jun 08 19:13:27 2017 @author: Administrator """ import math def is_prime(x): flag = 0 i = int(math.sqrt(x)) for j in range(1,i+1): if (x % i == 0): flag = 0 break if (j >= i): flag = 1 return flag """ Attention you must put n and x outside the loop,or I will not get the desired result """ n = 5 x = 1 print('P M') while n: y = 2 ** x - 1 if is_prime(x) and is_prime(y): print ('%d %d' %(x,y)) n -= 1 x += 1
from utils import * import time class Result(): """ Class which carries the results of an experiment. It contains data such as the dimension of the problem, and has a callback that can be placed into an iterative algorithm so it collects results and data in real time. Usage: result = Result(dims) algo = Algorithm(..., callback = result.iteration_callback, ...) output = algo.run() result.add_solver_output(output) """ def __init__(self, dims, verbose=True, print_every=2, filename=None, params_filename=None): self.dims = dims self.loss_data = [] self.verbose = verbose self.print_every = print_every self.params = [] self.start_time = time.time() self.filename=filename self.params_filename=params_filename def iteration_callback(self, *argv): """ A function which is called on every iteration of optimization. At this point, it just collects data. """ iter_n, params = argv[0], argv[1] mean, std = argv[2], argv[3] self.params.append(params) self.loss_data.append(mean) if self.filename: self.filename.write(str(mean) + ", ") if self.params_filename: self.filename.write(str(iter_n) + "\n") self.filename.write(str(params) + "\n") if self.verbose: #and iter_n % self.print_every - 1 == 0: print("Evaluation: {}, Loss: {}".format(iter_n, mean)) def add_solver_output(self, solver_output, fragment=None): """ A function adds the data from the output of a solver to the state. If function is called for a fragment then provide the fragment list. """ self.end_time = time.time() self.elapsed_time = self.end_time - self.start_time self.ground_state = read_ground_state(solver_output['aux_ops'][0]) self.min_val = solver_output['min_val'] self.opt_params = solver_output['opt_params'] self.clean_grid() self.build_result_grid(fragment) def clean_grid(self): """ Makes it so that the only points that are valid to reach are reachable. Creates a "reachable_points" set that can be used as a dictionary to map to qubits. Creates dictionary _reachable_points {qubit_index : point} """ self.reachable_points = {} counter = 0 self.W, self.H = self.dims for i in range(self.W): for j in range(i, self.H-i): self.reachable_points[counter] = (i, j) counter += 1 def build_result_grid(self, fragment=None): """ Builds a result that easily visualizes what sites are dug at the grid. If function is called for a fragment then provide the fragment list. """ self.grid = np.zeros(self.dims) #self.ground_state = self.ground_state[::-1] for i, val in enumerate(self.ground_state): if fragment is None: self.grid[self.reachable_points[i]] = val else: self.grid[fragment[i]] = val def get_loss_data(self): """ Get the loss data """ return self.loss_data def get_final_loss(self): """ Get the final loss """ return self.min_val def print_results(self): print("Results Report:") print("Solving Took {} seconds".format(self.elapsed_time)) print("Loss Function: {}".format(self.min_val)) print("Optimal Parameters: {}".format(self.opt_params)) print("Final Configuration:") print_grid(self.grid)
import turtle a = 5 print (a) b = 'hello' print(b) credit_card = 357238952792 print(credit_card) qazi_turtle = turtle.Turtle() qazi_turtle.speed(30) def square(): qazi_turtle.forward(100) qazi_turtle.right(90) qazi_turtle.forward(100) qazi_turtle.right(90) qazi_turtle.forward(100) qazi_turtle.right(90) qazi_turtle.forward(100) # square() # qazi_turtle.forward(200) # square() elephant_weight = 3000 ant_weight = 0.1 # if elephant_weight < ant_weight: # square() # else: # qazi_turtle.forward(100) # qazi = 'happy' # while qazi == 'happy': # qazi_turtle.forward(10) for i in range(4): square()
# This is a working prototype. DO NOT USE IT IN LIVE PROJECTS class KalmanFilter: def __init__(self, r, q, a=1, b=0, c=1): # R models the process noise and describes how noisy a system internally is. # How much noise can be expected from the system itself? # When a system is constant R can be set to a (very) low value. self.R = r # Q resembles the measurement noise. # How much noise is caused by the measurements? # When it's expected that the measurements will contain most of the noise, # it makes sense to set this parameter to a high number (especially in comparison to the process noise). self.Q = q # Usually you make an estimate of R and Q based on measurements or domain knowledge. self.A = a # State vector self.B = b # Control vector self.C = c # Measurement vector self.x = float('nan') # estimated signal without noise self.cov = 0.0 # Predict next value def __predict(self, u = 0): return (self.A * self.x) + (self.B * u) # uncertainty of filter def __uncertainty(self): return (square(self.A) * self.cov) + self.R def filter(self, signal, u=0): if isNaN(self.x): self.x = (1 / self.C) * signal self.cov = square(1 / self.C) * self.Q else: prediction = self.__predict(u) uncertainty = self.__uncertainty() # Kalman gain k_gain = uncertainty * self.C * (1 / ((square(self.C) * uncertainty) + self.Q)) # correction self.x = prediction + k_gain * (signal - (self.C * prediction)) self.cov = uncertainty - (k_gain * self.C * uncertainty) return self.x def square(x): return x * x def isNaN(num): return num != num
__author__ = '619635' my_age=input("Enter your age:") print("After one year, your age will be " + str(int(my_age)+1) )
__author__ = '619635' n=int(input("Eneter number")) for i in range(0,1000,n): print(i) #Priniting values in reverse for i in range(10,-1,-1): print(i)
__author__ = '619635' import random num=random.randint(1,10) while True: provideinput=int(input("Please provide your input\n")) if provideinput > num: print("your number is higher than the guess number\n") elif provideinput < num: print("your number is smaller than the guess number\n") else: print("Good you have guessed the number and the number is:",num)
__author__ = '619635' for i in range(0,100): if i%2 == 0: print(str(i) + ' is even') else: print(str(i) + ' is odd')
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> l=[1,2,3,4,5,6] >>> l [1, 2, 3, 4, 5, 6] >>> type(l) <class 'list'> >>> print(type(l)) <class 'list'> >>> id(l) 1625530265408 >>> l.append(80) >>> id(l) 1625530265408 >>> print(l,id(l)) [1, 2, 3, 4, 5, 6, 80] 1625530265408 >>> #so lists are muatable >>> #here mutable is nothing but you can edit(modify) the data type in same location >>> l=[1,2,3,4,5,6] >>> l [1, 2, 3, 4, 5, 6] >>> id(l) 1625535710272 >>> l.append('arun') >>> l [1, 2, 3, 4, 5, 6, 'arun'] >>> l.append('kumar;) SyntaxError: EOL while scanning string literal >>> l.append('kumar') >>> l [1, 2, 3, 4, 5, 6, 'arun', 'kumar'] >>> l.append(60.888) >>> l [1, 2, 3, 4, 5, 6, 'arun', 'kumar', 60.888] >>> l.append(complex(1,2)) >>> l [1, 2, 3, 4, 5, 6, 'arun', 'kumar', 60.888, (1+2j)] >>> a='arun kumar' >>> a 'arun kumar' >>> #TUPLES >>> l=[] >>> l [] >>> type(l) <class 'list'> >>> t=() >>> t=(1,2,3,4,5,6) >>> t (1, 2, 3, 4, 5, 6) >>> type(t) <class 'tuple'> >>> id(t) 1625534745472 >>> t=(2,3,4) >>> id(t) 1625535655040 >>> t=(1,'arun',1.3,complex(1,2),[1,2,3,4,5,6,'kumar',21.96,complex(6,5)]) >>> t (1, 'arun', 1.3, (1+2j), [1, 2, 3, 4, 5, 6, 'kumar', 21.96, (6+5j)]) >>> t[0] 1 >>> t[4] [1, 2, 3, 4, 5, 6, 'kumar', 21.96, (6+5j)] >>> t[4][4] 5 >>> #tuples and lists are same but main difference is tuples are immutable whether lists are mutable. >>> #we can use tuples when the user don't need to over write it. >>> #DICTIONARIES >>> ###dictionaries are also called as hashmaps >>> #it stores the values in key value apirs >>> d Traceback (most recent call last): File "<pyshell#47>", line 1, in <module> d NameError: name 'd' is not defined >>> d={'name':arun} Traceback (most recent call last): File "<pyshell#48>", line 1, in <module> d={'name':arun} NameError: name 'arun' is not defined >>> d={'name':'arun'} >>> d {'name': 'arun'} >>> d={'name':'arun','age'=90} SyntaxError: invalid syntax >>> d={'name':'arun','age':90} >>> d[age] Traceback (most recent call last): File "<pyshell#53>", line 1, in <module> d[age] NameError: name 'age' is not defined >>> d['age'] 90 >>> id(d) 1625535699904 >>> d.update('sur name','kumar') Traceback (most recent call last): File "<pyshell#56>", line 1, in <module> d.update('sur name','kumar') TypeError: update expected at most 1 argument, got 2 >>> d.update(('surname','kumar')) Traceback (most recent call last): File "<pyshell#57>", line 1, in <module> d.update(('surname','kumar')) ValueError: dictionary update sequence element #0 has length 7; 2 is required >>> help(d.update) Help on built-in function update: update(...) method of builtins.dict instance D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] >>> id(d) 1625535699904 >>> d={'name':'arun','age':90,'surname':'kumar'} >>> d {'name': 'arun', 'age': 90, 'surname': 'kumar'} >>> id(d) 1625535700928 >>>
def check_baggage(baggage_weight): try: if(baggage_weight >= 0 and baggage_weight < 40): return True else: return False except TypeError: print("INVALID baggage weight entered") def check_immigration(expiry_year): try: if(expiry_year >= 2001 and expiry_year <= 2025): return True else: return False except TypeError: print("INVALID expiry year entered") def check_security(noc_status): try: if(noc_status == 'VALID' or noc_status == 'valid'): return True else: return False except TypeError: print("INVALID noc_status entered") def traveler(): traveler_id = 1001 traveler_name = "Jhon" try: if(check_baggage(39) and check_immigration(2019) and check_security("VALID")): print(traveler_id,traveler_name) print("Allow Traveller to Fly!") else: print(traveler_id,traveler_name) print("Detain Traveller for re-checking.") except TypeError: print("INVALID values entered") except ValueError: print("INVALID values entered") traveler() ''' OUTPUT : 1001 Jhon Allow Traveller to Fly! 1002 Jhon Detain Traveller for re-checking. '''
#Python Program to find Bill Amount after discount and Validate Bill Amount bill_amount = int(input("Enter Bill Amount:")) customer_id = int(input("Enter User ID:")) if(customer_id in range(100,1001)): if(bill_amount >= 1000): bill_amount_discounted = bill_amount - (bill_amount * (5/100)) elif(bill_amount >= 500 and bill_amount < 1000): bill_amount_discounted = bill_amount - (bill_amount * (2/100)) elif(bill_amount > 0 and bill_amount < 500): bill_amount_discounted = bill_amount - (bill_amount * (1/100)) print("Customer ID:",customer_id) print("Bill Amount After discount:",bill_amount_discounted) else: print("Customer ID invalid") ''' OUTPUT : Enter Bill Amount:600 Enter User ID:101 Customer ID: 101 Bill Amount After discount: 588.0 '''
with open('courses.txt','r') as inFile: content = inFile.readlines() print("File Content : ") dictionary = dict() array =list() i = 0 for line in content: line=line.strip() print(line) dictionary[i] = line array.append(line) i += 1 print("Dictionary :",end=' ') print(dictionary) print("List : ",end=' ') print(array) ''' OUTPUT : File Content : Java Python Javascript PHP Dictionary : {0: 'Java', 1: 'Python', 2: 'Javascript', 3: 'PHP'} List : ['Java', 'Python', 'Javascript', 'PHP'] '''
def check_baggage(baggage_weight): if baggage_weight >= 0 or baggage_weight <= 40: return True else: return False def check_immigration(expiry_year): if expiry_year >= 2001 or expiry_year <= 2025: return True else: return False def check_security(noc_status): if noc_status == "valid" or noc_status == "VALID": return True else: return False traveler_id = 1001 traveler_name = "Jim" baggage_weight = 35 expiry_year = 2000 noc_status = "VALID" if check_baggage(baggage_weight)is True and check_immigration(expiry_year)is True and check_security(noc_status)is True: print("Id =",traveler_id) print("Name = ",traveler_name) print("Allow Traveler to fly!") else: print("Id =",traveler_id) print("Name = ",traveler_name) print("Detain Traveler for Re-checking!") ''' OUTPUT : Id = 1001 Name = Jim Allow Traveler to fly! '''
with open('student_details.txt','r') as inFile: content = inFile.readlines() list_of_list=list() list_of_dictionary=list() i =0 for line in content: line = line.strip() print(line) item = line.split() list_of_list.append(item) d = dict() d[item[0]]=item[1] list_of_dictionary.append(d) print(list_of_list) print(list_of_dictionary) ''' OUTPUT : 101 Rahul 102 Julie 103 Helena 104 Kally [['101', 'Rahul'], ['102', 'Julie'], ['103', 'Helena'], ['104', 'Kally']] [{'101': 'Rahul'}, {'102': 'Julie'}, {'103': 'Helena'}, {'104': 'Kally'}] '''
# -*- coding: utf-8 -*- """ Created on Thu Dec 13 21:18:49 2018 @author: Haile """ # Dependencies- modules to read csv and create file paths import csv import os # Loading election data csv and path for the result file csvpath_elec = os.path.join("Resources", "election_data.csv") csvpath_elec_result_output = os.path.join("analysis", "election_result.txt") # Total Votes total_votes = 0 # Candidate Options and Vote Counters candidate_list = [] candidate_vote_count = {} # Winning Candidate and Winning Count Tracker winner_candidate = "" winner_vote_count = 0 # Read the csv and convert it into a list of dictionaries with open(csvpath_elec) as election_data: reader = csv.reader(election_data) # defining the header header = next(reader) # For each row... for row in reader: # Run and print the loader animation print("- ", end=""), # Total vote count total_votes = total_votes + 1 # Extract the candidate name from each row candidate_name = row[2] # If the candidatename is not in the candidate list, add it to the list # and count the votes for that candidate if candidate_name not in candidate_list: # Add it to the list of candidates in the running candidate_list.append(candidate_name) # And begin tracking that candidate's voter count candidate_vote_count[candidate_name] = 0 # Then add a vote to that candidate's count candidate_vote_count[candidate_name] = candidate_vote_count[candidate_name] + 1 # Print the results and export the data to our text file with open(csvpath_elec_result_output, "w") as txt_file: # Print the final vote count (to terminal) election_results = ( f"\n\nElection Results\n" f"-------------------------\n" f"Total Votes: {total_votes}\n" f"-------------------------\n") print(election_results, end="") # Save the final vote count to the text file txt_file.write(election_results) # Determine the winner by looping through the counts for candidate in candidate_vote_count: # Retrieve vote count and percentage votes = candidate_vote_count.get(candidate) vote_per = float(votes) / float(total_votes) * 100 # Determine winning vote count and candidate if (votes > winner_vote_count): winner_vote_count = votes winner_candidate = candidate # Print each candidate's voter count and percentage (to terminal) candidate_vote_sum = f"{candidate}: {vote_per:.3f}% ({votes})\n" print(candidate_vote_sum , end="") # Save each candidate's voter count and percentage to text file txt_file.write(candidate_vote_sum ) # Print the winning candidate (to terminal) winner_candidate_sum = ( f"-------------------------\n" f"Winner: {winner_candidate}\n" f"-------------------------\n") print(winner_candidate_sum) # Save the winning candidate's name to the text file txt_file.write(winner_candidate_sum)
#!/usr/bin/env python def is_substring(s1, s2): return s1 in s2 def is_rotated(s1, s2): common = s1[len(s1) / 4:-len(s1) / 4] return is_substring(s1, s2 + s2) if __name__ == "__main__": questions = [("erbottlewat", "waterbottle"), ("abc", "bcd")] answers = [True, False] for i, q in enumerate(questions): if is_rotated(q[0], q[1]) != answers[i]: print "[FAIL] for '%s' and '%s'" % (q[0], q[1]) exit(1) print "[PASS] for '%s' and '%s'" % (q[0], q[1])
#!/usr/bin/env python """ Numbers are represented by a linked list. Implement sum. """ import sys sys.path.append("../") from llist import * def get_data_safe(node): if node == None: return 0 return node.data def sum_llst(head1, head2): ret = None n1 = head1 n2 = head2 carry = 0 while n1 != None or n2 != None: d1 = get_data_safe(n1) d2 = get_data_safe(n2) digit = d1 + d2 + carry if digit > 10: digit -= 10 carry = 1 else: carry = 0 if ret == None: ret = Node(digit) else: new_r = Node(digit) new_r.nxt = ret ret = new_r if n1 != None: n1 = n1.nxt if n2 != None: n2 = n2.nxt return ret if __name__ == "__main__": questions = [ ([7,1,6], [5,9,2]) ] answers = [[9,1,2]] for i, q in enumerate(questions): llst1 = lst_to_llst(q[0]) llst2 = lst_to_llst(q[1]) llst = sum_llst(llst1, llst2) if llst_to_lst(llst) != answers[i]: print "[FAIL] %s + %s -> %s" % (q[0], q[1], llst_to_lst(llst)) exit(1) print "[PASS] %s, %s" % (q[0], q[1])
''' A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number. A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n. As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit. Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers. ''' import math import time def divisors(n): divs = [1] for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: divs.append(i) if n/i not in divs: divs.append(n/i) divs.sort() return divs def sum_of_two(n, abd): for i in abd: if i > n / 2: break if cache[n - i]: return True return False if __name__ == '__main__': cache = [False] * 28124 t1 = time.clock() for i in range(1, 28124): if sum(divisors(i)) > i: cache[i] = True abd = [i for i in range(28124) if cache[i]] print(sum([i for i in range(1, 28124) if not sum_of_two(i, abd)])) t2 = time.clock() print('Runtime: {} s'.format(t2 - t1))
''' It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2*1**2 15 = 7 + 2*2**2 21 = 3 + 2*3**2 25 = 7 + 2*3**2 27 = 19 + 2*2**2 33 = 31 + 2*1**2 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? ''' import itertools import intlib def main(): _max = 10**4 odd_iter = (2*n + 1 for n in itertools.count(1)) primes = intlib.primes(_max) primes_set = set(primes) #membership判定用set for n in odd_iter: if n > _max: return 'Not found.' if n in primes_set: continue flag = True for p in primes: if p > n: break if intlib.is_square((n - p)//2): flag = False break if flag: return n if __name__ == '__main__': print(main())
''' The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime. There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17, 31, 37, 71, 73, 79, and 97. How many circular primes are there below one million? ''' from intlib import prime_set primes = prime_set(10**6) def is_cir_prime(n): s = str(n) for i in range(len(s)): if not int(s) in primes: return False s = s[1:] + s[0] return True if __name__ == '__main__': cir_primes = [n for n in range(2, 10**6) if is_cir_prime(n)] print(cir_primes) print(len(cir_primes))
''' How many different ways can one hundred be written as a sum of at least two positive integers? ''' def main(): MAX = 100 pre_table = [1] * (MAX + 1) for k in range(2, MAX): table = [0] * (MAX + 1) for n in range(MAX + 1): table[n] = sum(pre_table[n - i * k] for i in range(0, n//k + 1)) pre_table = table return table[MAX] if __name__ == '__main__': import time t1 = time.time() print(main()) t2 = time.time() print('{:.3f} s'.format(t2-t1))
''' The cube, 41063625 (345**3), can be permuted to produce two other cubes: 56623104 (384**3) and 66430125 (405**3). In fact, 41063625 is the smallest cube which has exactly three permutations of its digits which are also cube. Find the smallest cube for which exactly five permutations of its digits are cube. ''' import itertools from collections import defaultdict def main(): length = 5 digit = 1 d = defaultdict(list) for i in itertools.count(1): if i**3 > 10**digit: # 解があるかどうかチェック tmp = [val[0] for key, val in d.items() if len(val) == length] if tmp: return min(tmp) # 解がない場合はリセット d = defaultdict(list) digit += 1 key = ''.join(sorted(str(i**3))) d[key].append(i**3) if __name__ == '__main__': import time t1 = time.time() print(main()) t2 = time.time() print('{:.3f} s'.format(t2-t1))
''' The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a word value. For example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we shall call the word a triangle word. Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing nearly two-thousand common English words, how many are triangle words? ''' import csv d = {a : i + 1 for i, a in enumerate('ABCDEFGHIJKLMNOPQRSTUVWXYZ')} def word_to_num(word): return sum([d[a] for a in word]) if __name__ == '__main__': words = [] with open('words.txt','r',encoding='utf-8') as f: csv_reader = csv.reader(f) for row in csv_reader: words += row max_len = max([len(word) for word in words]) triangles = {n*(n+1)/2 for n in range(1, 26*max_len + 1)} #TEST #print(word_to_num('SKY') in triangles) print(len([word for word in words if word_to_num(word) in triangles]))
''' Problem 39 ---------------------- If p is the perimeter of a right angle triangle with integral length sides, {a,b,c}, there are exactly three solutions for p = 120. {20,48,52}, {24,45,51}, {30,40,50} For which value of p <= 1000, is the number of solutions maximised? ''' def count_sols(p): ans = 0 for a in range(1, p//3): for b in range(a + 1, (p - a)//2): c = p - a - b if a**2 + b**2 == c**2 : ans += 1 return ans def main(): ans = 0 n = 0 for p in range(1, 1001): m = count_sols(p) if n < m: ans = p n = m return ans if __name__ == '__main__': print(__doc__) print(count_sols(120)) print(main())
## Welcome to Beefy's Brackish Burgers! ## ## Complete with Andrew's idiotproof+++ ## ## Error Prevention Code solutions!(tm) ## ## Andrew Inc: Making overcomplicated ## ## Solutions to simple problems since ## ## 2017 ## #----------------------------------------# import os def clear(): os.system("clear") def printbill(): print('Bill: %s$' % (cash)) def printorder(): print('Order: %s' % (order)) def printall(): print('') printbill() printorder() print('') while True: global name try: name = str(input('Name: ')) except ValueError: print( "Please give us something that wouldn't break our program. Thank you!" ) continue if name == (''): print( 'Please give us a name that does not resemble the ever growing bottomless void of death. Thank you!' ) continue else: break clear() print( "Hello %s! Welcome to Beefy's Brackish Burgers! please order from our menu below." % (name)) while True: global sandwich global cash global order order = [] cash = 0.00 try: sandwich = int( input(""" Sandwiches: 1 - Chicken (5.25)$ 2 - Beef (6.25)$ 3 - Tofu (5.75)$ 4 - Reindeer (25.52)$ 5 - Skip 6 - Quit Answer: """)) print('') except ValueError: print('Please enter a sandwich numer.') continue if sandwich == 1: print("One chicken sandwich on the way!") order.append('Chicken Sandwich') cash += 5.25 break elif sandwich == 2: print("One beef sandwich on the way!") order.append('Beef Sandwich') cash += 6.25 break elif sandwich == 3: print("One tofu sandwich on the way!") order.append("Tofu Sandwich") cash += 5.75 break elif sandwich == 4: print( "Sadly tis not the season to be jolly. Reindeer are currently in short supply and our famous reindeer sandwiches will be back next christmas. Thank you!" ) continue elif sandwich == 5: print("Skipping...") order.append('No Meal') print('') break elif sandwich == 6: print("Quitting...") quit('User initiated quit') else: print("Please use a valid option!") continue clear() printorder() while True: global beverage try: beverage = int( input(""" Beverages: 1 - Small (1.00) 2 - Medium (1.75) 3 - Large (2.25) 4 - Reindeer Smoothie (14.50 5 - Skip 6 - Quit Answer: """)) print('') except ValueError: print('Please enter a beverage number. Thank you!') continue if beverage == 1: print('One small coming up!') order.append('Small Beverage') cash += 1.00 break elif beverage == 2: print('One medium coming up!') order.append('Medium Beverage') cash += 1.75 break elif beverage == 3: print('One large coming up!') order.append('Large Beverage') cash += 2.25 break elif beverage == 4: print( "Sadly tis not the season to be jolly. Reindeer are currently in short supply and our famous reindeer smoothies will be back next christmas. Thank you!" ) continue elif beverage == 5: print('Skipping...') order.append('No Beverage') break elif beverage == 6: print('Quitting') quit('User initiated quit') else: print('Please use a valid option!') clear() printorder() while True: global fries try: fries = int( input(""" Fries: 1 - Small (1.00) 2 - Medium (1.50) 3 - Large (2.00) 4 - Reindeer Rings (8.75) 5 - Skip 6 - Quit Answer: """)) print('') except ValueError: print('Please enter a fry number. Thank you!') continue if fries == 1: while True: try: a = int( input(""" Would you like to mega size that? 1 - Yes 2 - No Answer: """)) except ValueError: print("Please enter a valid answer!") continue if a == 1: print('One large coming up!') order.append('Large Fry') cash += 2 break elif a == 2: print('One small coming up!') order.append('Small Fry') cash += 1 break else: print('Please enter a valid answer!') continue break elif fries == 2: print('One medium coming up!') order.append('Medium Fries') cash += 1.75 break elif fries == 3: print('One large coming up!') order.append('Large Fries') cash += 2.25 break elif fries == 4: print( "Sadly tis not the season to be jolly. Reindeer are currently in short supply and our famous reindeer rings will be back next christmas. Thank you!" ) continue elif fries == 5: print('Skipping...') order.append('No Fries') break elif fries == 6: print('Quitting') quit('User initiated quit') else: print('Please use a valid option!') clear() printall() while True: global packets try: packets = int(input("How many ketchup packets would you like?: ")) except ValueError: continue if packets < 0: print( 'Sadly at this time BBB does not supply antimatter kethup packets. Sorry for the inconvience!' ) elif packets == 0: order.append('No Packets') break else: print("Here's your %s packets!" % (packets)) order.append(str('%s Packets' % (packets))) cash += packets * .25 break if sandwich < 4 and beverage < 4 and fries < 4: print( "You have qualified for a 1.00$ price discount by ordering a full meal!" ) cash -= 1 clear() print('Here is your order!') printall() quit('End of program.')
a = float (input("NUM 1 \n")) b = float (input("NUM 2 \n")) w = float (input("NUM 3 \n")) c = input("RAW \n") r = 0 if c=="+": r=a+b+w elif c=="-": r=a-b-w elif c=="*": r=a*b*w elif c=="/": r=a/b/w print (r)
# -*-coding: utf-8 -*- # Create by Jiang Tao on 2016/9/20 # 在Python中,这种一边循环一边计算的机制,称为生成器:generator g = (x * x for x in range(10)) print(g) # 访问生成器的元素 for n in g: print(n, end=" ") print() # 函数中含有yield关键字,那么这个函数就是一个生成器generator def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n += 1 return 'done' # 函数中遇到yield 就中断,不会调用返回值 print(fib(6)) # test,不断输出杨辉三角 def triangle(): ls = [1] while True: yield ls ls.append(0) ls = [ls[i - 1] + ls[i] for i in range(len(ls))] n = 0 for lst in triangle(): print(lst) n += 1 if n == 20: break
print("Enter the temperature(celsius) and wind speed (km/h) and I will calculate the windchill factor") temp_cel = float(input("What is the temperature in celcius?: ")) wind_kmh = float(input("What is the wind speed in km/h?: ")) wc = (13.12 + (0.6215 * temp_cel) - (11.37 * (wind_kmh ** 0.16)) + (0.3965 * temp_cel * (wind_kmh ** 0.16))) print("The windchill factor is approximately " + str(wc) + " degrees celcius.")
#! /usr/bin/env python3.3 """A simple profiling timer class for timing sections of code. To use: with Timer('A'): do work with Timer('B'): do work with Timer('C'): do work with Timer('B'): do work At exit, a debug log entry will be produced: A : 0.2000 seconds self time : 0.1000 seconds B : 0.1000 seconds C : 0.3000 seconds self time : 0.1000 seconds B : 0.2000 seconds Restrictions: Timer names must not contain '.'. Don't try to use class _Timer directly. """ import atexit import time import logging import sys # pylint:disable=W9903 # non-gettext-ed string # debugging module, no translation required. LOG = logging.getLogger(__name__) _ACTIVE_TIMERS = [] _TIMERS = {} _INDENT = 2 _SEP = '.' class _Timer: """Simple class for timing code.""" def __init__(self, name, top_level): self.name = name self.top_level = top_level self.time = 0 self.start = 0 self.active = False def __float__(self): return self.time def __enter__(self): assert not self.active assert not _ACTIVE_TIMERS or self.name.startswith(_ACTIVE_TIMERS[-1].name) self.active = True _ACTIVE_TIMERS.append(self) self.start = time.time() return self def __exit__(self, _exc_type, _exc_value, _traceback): assert self.active assert _ACTIVE_TIMERS[-1] == self delta = time.time() - self.start _ACTIVE_TIMERS.pop() self.active = False self.time += delta def is_child(self, t): '''is t a direct child of this timer?''' if t == self: return False if not t.name.startswith(self.name + _SEP): return False if _SEP in t.name[len(self.name)+len(_SEP):]: return False return True def children(self): '''list of timers nested within this timer''' return [t for t in _TIMERS.values() if self.is_child(t)] def child_time(self): '''sum of times of all nested timers''' return sum([t.time for t in self.children()]) def do_str(self, indent): """helper function for str(), recursively format timer values""" items = [" " * indent + "{:25}".format(self.name.split(_SEP)[-1]) + " " * (10 - indent) + ": {:8.4f} seconds".format(self.time)] ctimers = sorted(self.children(), key=lambda t: t.name) if ctimers: indent += _INDENT self_time = self.time - self.child_time() items.append(" " * indent + "{:25}".format("self time") + " " * (10 - indent) + ": {:8.4f} seconds".format(self_time)) for t in ctimers: items.append(t.do_str(indent)) return "\n".join(items) def __str__(self): return self.do_str(0) #pylint:disable=C0103 def Timer(name): """Create and return a timer.""" assert not _SEP in name if _ACTIVE_TIMERS: assert not name in _ACTIVE_TIMERS[-1].name.split(_SEP) full_name = _ACTIVE_TIMERS[-1].name + _SEP + name else: full_name = name if not full_name in _TIMERS: _TIMERS[full_name] = _Timer(full_name, full_name == name) return _TIMERS[full_name] @atexit.register def Report(): """Log all recorded timer activity.""" top_timers = sorted([t for t in _TIMERS.values() if t.top_level], key=lambda t: t.name) LOG.debug("\n".join(["Profiler report for {}".format(sys.argv)] + [str(t) for t in top_timers]))
import unittest from numerosRomanos import NumerosRomanos class testNumeroRomano(unittest.TestCase): def setUp(self): self.numero_romano = NumerosRomanos() def testdecimal_I(self): self.assertEqual('I', self.numero_romano.decimal_romano(1), 'I falhou') self.assertEqual('III', self.numero_romano.decimal_romano(3), 'III falhou') self.assertEqual('II', self.numero_romano.decimal_romano(2), 'II falhou') def testdecimal_IV(self): self.assertEqual('IV', self.numero_romano.decimal_romano(4), 'IV falhou') def testdecimal_V(self): self.assertEqual('V', self.numero_romano.decimal_romano(5), 'V falhou') def testdecimal_IX(self): self.assertEqual('IX', self.numero_romano.decimal_romano(9), 'IX falhou') def testdecimal_L(self): self.assertEqual('L', self.numero_romano.decimal_romano(50), 'L falhou') def testdecimal_XIX(self): self.assertEqual('XIX', self.numero_romano.decimal_romano(19), 'XIX falhou') def testdecimal_XL(self): self.assertEqual('XL', self.numero_romano.decimal_romano(40), 'XL falhou') # para quem roda o python pelo terminal inclua a linha 39 e 40 e tenha o unittest instalado # if __name__ == '__main__': # unittest.main()
""" The Lazy Startup Office https://www.codewars.com/kata/578fdcfc75ffd1112c0001a1 Solved 01-24-2017 Description: 7 kyu The Lazy Startup Office A startup office has an ongoing problem with its bin. Due to low budgets, they don't hire cleaners. As a result, the staff are left to voluntarily empty the bin. It has emerged that a voluntary system is not working and the bin is often overflowing. One staff member has suggested creating a rota system based upon the staff seating plan. Create a function binRota that accepts a 2D array of names. The function will return a single array containing staff names in the order that they should empty the bin. Adding to the problem, the office has some temporary staff. This means that the seating plan changes every month. Both staff members' names and the number of rows of seats may change. Ensure that the function binRota works when tested with these changes. Notes: All the rows will always be the same length as each other. There will be no empty spaces in the seating plan. There will be no empty arrays. Each row will be at least one seat long. An exemplar seating plan is as follows: Or as an array: [["Stefan", "Raj", "Marie"], ["Alexa", "Amy", "Edward"], ["Liz", "Claire", "Juan"], ["Dee", "Luke", "Katie"]] The rota should start with Stefan and end with Dee, taking the left-right zigzag path as illustrated by the red line: As an output you would expect in this case: ["Stefan", "Raj", "Marie", "Amy", "Edward", "Alexa", "Juan", "Liz", "Claire", "Katie", "Dee", "Luke"] """ def binRota(arr): order = [] for rows, columns in enumerate(arr): if rows % 2 == 0: for i in columns: order.append(i) else: for i in columns[::-1]: order.append(i) return order
""" Is the string uppercase? https://www.codewars.com/kata/56cd44e1aa4ac7879200010b Solved 01-24-2017 Description: 8 kyu Task Create a method is_uppercase() to see whether the string is ALL CAPS. For example: is_uppercase("c") == False is_uppercase("C") == True is_uppercase("hello I AM DONALD") == False is_uppercase("HELLO I AM DONALD") == True is_uppercase("ACSKLDFJSgSKLDFJSKLDFJ") == False is_uppercase("ACSKLDFJSGSKLDFJSKLDFJ") == True Corner Cases For simplicity, you will not be tested on the ability to handle corner cases (e.g. "%*&#()%&^#" or similar strings containing alphabetical characters at all) - an ALL CAPS (uppercase) string will simply be defined as one containing no lowercase letters. Therefore, according to this definition, strings with no alphabetical characters (like the one above) should return True. """ import re def is_uppercase(inp): if inp.upper() == inp: return True elif re.match('[a-z]',inp) != None: return False else: return False
from models.abstract_model import AbstractModel import numpy as np import utils.miscellaneous class Random(AbstractModel): """ Represents random model. """ def __init__(self, game): """ Initializes a new instance of Random model for the specified game. :param game: Game that will be played. """ self.game_config = utils.miscellaneous.get_game_config(game) def evaluate(self, input, current_phase): """ Evaluates model output with the specified input. Output is random. :param input: Input to evaluate - there's no any usage of this. :param current_phase: Current game phase - there's no any usage of this. :return: Random output. """ input_sizes = list(map(int, self.game_config["input_sizes"])) output_sizes = list(map(int, self.game_config["output_sizes"])) assert (input_sizes[current_phase] == len(input)) return [np.random.random() for _ in range(output_sizes[current_phase])] def get_name(self): """ A name of the current model. """ return "random" def get_class_name(self): """ A class name of the current model. :return: """ return "Random"
a = int(input("Proporciona un valor:")) valorMinimo = 0 valorMaximo = 5 dentroRango = (valorMinimo <= a <= valorMaximo) # (a >= valorMinimo and a <= valorMaximo) print(dentroRango) if dentroRango: print('dentro de rango') else: print('fuera de rango') vacaciones = False diaDescanso = False if vacaciones or diaDescanso: print('podemos ir al parque') else: print('tienes deberes que hacer') # con not() invertimos el valor print(not vacaciones)
class Rectangulo: def __init__(self, ancho, alto): self.ancho = ancho self.alto = alto def calcularArea(self): return self.ancho * self.alto print('Bienvenid@') ancho = int(input('Introduzca el ancho del rectangulo: ')) alto = int(input('Introduzca el alto del rectangulo: ')) rectangulo = Rectangulo(ancho, alto) print('El area del rectángulo es de', rectangulo.calcularArea())
""" Description: Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Category : easy ------------------------------------------------------------------------------------------------------------------------ Example: Input: s = "()" Output: true Input: s = "()[]{}" Output: true Input: s = "(]" Output: false Input: s = "([)]" Output: false Input: s = "{[]}" Output: true Constraints: 1 <= s.length <= 104 s consists of parentheses only '()[]{}'. ------------------------------------------------------------------------------------------------------------------------ """ def valid_parentheses(s): if len(s) % 2 == 1: return False dict = {")": "(", "}": "{", "]": "["} stack = [] for each in s: if each in dict: if stack: element = stack.pop() else: element = "!" if dict[each] != element: return False else: stack.append(each) return not stack
import math x=int(input("enter the value of x :")) y=int(input("enter the value of y :")) result=math.pow(x,y) print(result)
#!/user/bin/env python3 # -*- coding: utf-8 -*- __author__ = "HymanQin"; ''' 基础 ''' import re,math; # === 输入输出 === # a = input(); # print(a); a = 11; b = "qw"; print(a); print("hello world"); print("hello", "world", "haha"); print("hello %s" % a); print("hello %s" % (a)); print("hello %s %s" % (a, b)); # === 数据类型 === a = 11; print("a = %s,数据类型: %s" % (a, type(a))); a = 11.11; print("a = %s,数据类型: %s" % (a, type(a))); a = "abcdefg"; print("a = %s,数据类型: %s" % (a, type(a))); # NoneType 相当于null a = None; print("a = %s,数据类型: %s" % (a, type(a))); # bool a = True or False; print("a = %s,数据类型: %s" % (a, type(a))); # list a = ['aaa', 123, 12.3]; print("a = %s,数据类型: %s" % (a, type(a))); # tuple类型,初始化之后元素不能变 a = ('aaa', 123, 12.3); print("a = %s,数据类型: %s" % (a, type(a))); # dict类型,键值对存储 a = {"name": "qw", "age": 66}; print("a = %s,数据类型: %s" % (a, type(a))); # === 运算符 === print((2 + 45 / 12) * 2); # 11.5 print(15 // 2); # 地板除,取整 7 print(12 % 5); # 2 print(2 ** 3); # 乘方 8 # === ASCII 转换 === print("98-->%s;a-->%s" % (chr(98), ord('a'))) # 98-->b;a-->97 # ---- encode && decode ---- print("asd".encode("ascii")); # b'asd' print(b"asd".decode("ascii")); # asd 解码 print("中文".encode("utf-8")); # b'\xe4\xb8\xad\xe6\x96\x87' print(b'\xe4\xb8\xad\xe6\x96\x87'.decode("utf-8")); # 中文 # === 前缀字符串 === print(u'中文'); # 后面字符串是以Unicode编码 中文 print(r'dddd'); # 普通字符串 dddd print(b'qwqw'); # 后面是bytes b'qwqw' # === len === print(len("aaa")); # 3, 对于str计算字符数 print(len("中文")); # 2, 对于str计算字符数 print(len("aaa".encode("utf-8"))); # 3, 对于bytes计算字节数 print(len("中文".encode("utf-8"))); # 6, 对于bytes计算字节数 --- utf8中一个中文占3个字节 # === replace === a = "cdcassqwsdfrfqwsdfdf"; print(a.replace("qw", "===")); # cdcass===sdfrf===sdfdf print(a); # === find === print("abcdefgce".find("c")); # 2, 字符第一次出现的下标 print("abcdefgce".rfind("c")); # 7, 字符最后一次出现的下标 # === isspace === print(" ".isspace()); # true, 判断字符串是否为空格 # === 字符串格式化 === print("%d----%2d----%03d" % (2, 3, 4)); # 2---- 3----004, 2d(不足两位左边补空格)、02d(不足3位,左边补0) print("%f----%.2f" % (2.22, 3.333)); # 2.222000----3.33, .2f(保留2位小数,四舍五入)、float保留六位小数 print("%x" % 333); # 14d, 格式化为16进制 print("%s %% %s" % ("3", "2")); # 3 % 2 print(list("%s" % x for x in range(2, 10))); # ['2', '3', '4', '5', '6', '7', '8', '9'], 将2 - 10生成器,转化成字符串list print("Hi {0}, 成绩提高了{1:.1f}%".format("小名", 1.234)); # Hi 小名, 成绩提高了1.2% print("Hi {0}, 成绩提高了{1}%".format("小名", 1.234)); # Hi 小名, 成绩提高了1.234% print("Hi {0}, 成绩提高了{1}%".format("小名", "%.1f" % 1.234)); # Hi 小名, 成绩提高了1.2% print("-".join(["a", "b", "c"])); # a-b-c, 字符串拼接 # === 正则表达式 === # === 匹配字符串 === email_re = "^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$"; # 如果匹配成功,将返回一个Math对象,失败则返回None if re.match(email_re, "[email protected]"): print("ok"); else: print("error"); # === 切分字符串 === print("a b c".split(" ")); # ['a', 'b', '', 'c'] print(re.split(r"\s+", "a b c")); # ['a', 'b', 'c'] print(re.split(r"[\s\,\;]+", "a,b;; c d")); # ['a', 'b', 'c', 'd'] # === 分组 === # 分组提取电话号码 math = re.match(r"^(\d{3})-(\d{3,8})$", "010-12345"); print(math.group()); # 010-12345 print(math.group(0)); # 010-12345 print(math.group(1)); # 010 print(math.group(2)); # 12345 # 分组提起时间 math = re.match(r"^(0[0-9]|1[0-9]|2[0-3]|[0-9])\:" r"(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])\:" r"(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])$", "19:05:30"); print(math.groups()); # ('19', '05', '30') # 分组提取数字 new_line = r'截至9月2日0时,全省累计报告新型冠状病毒肺炎确诊病例653例(其中境外输入112例),' \ r'累计治愈出院626例,死亡3例,目前在院隔离治疗24例,964人尚在接受医学观察'; new_line_re = r'^截至9月2日0时,全省累计报告新型冠状病毒肺炎确诊病例(\d+)例\(其中境外输入(\d+)例\),' \ r'累计治愈出院(\d+)例,死亡(\d+)例,目前在院隔离治疗(\d+)例,(\d+)人尚在接受医学观察$'; new_line_math = re.match(new_line_re, new_line); print(new_line_math.group(0)); print(new_line_math.group(1)); # 653 print(new_line_math.group(2)); # 112 print(new_line_math.group(3)); # 626 print(new_line_math.group(4)); # 3 print(new_line_math.group(5)); # 24 print(new_line_math.group(6)); # 964 new_line_compile = re.compile(new_line_re); print(re.search(new_line_compile, new_line).group(1)); # 653 print(re.search(new_line_compile, new_line).group(2)); # 112 print(re.search(new_line_compile, new_line).group(3)); # 626 print(re.search(new_line_compile, new_line).group(4)); # 3 print(re.search(new_line_compile, new_line).group(5)); # 24 print(re.search(new_line_compile, new_line).group(6)); # 964 # 贪婪匹配 print(re.match(r"^(\d+)(0*)$", "102300").groups()); # ('102300', '') print(re.match(r"^(\d+?)(0*)$", "102300").groups()); # ('1023', '00') # === list === l = ["cas", 123, True, "cdasas"]; # 从前取值,index从0开始往后;从后取值,index从-1开始往前 print(l[0] + "-----" + l[-1]); # cas-----cdasas # 集合尾部添加元素 l.append("qwqw") print(l); l.insert(2, "cccc"); print(l); # 删除集合最后一个元素 l.pop(); # l += 12; l[0] = "aaaa"; print(l); l = list(range(1, 10)); t = ("aaa", 12, 12.2, True, None, l); l[1] = 11; print(t); print("list: %s, length: %s" % (l, len(l))); # list: [1, 11, 3, 4, 5, 6, 7, 8, 9], length: 9 # ==== tuple ==== t = tuple(range(10)); print(t); t = ("aads", 123, True, None, 12.3); print(t); # 定义只有一个元素的元祖,元素后追加“,”,以免误解成数学计算意义上的括号 t = ("cdsa",); print(t); # 集合作为元祖的元素,我们可以修改集合的元素 t = ("vsv", ["aaa", "sss"]); print(t); # ('vsv', ['aaa', 'sss']) t[1][1] = "bbbb"; print(t); # ('vsv', ['aaa', 'bbbb']) print("tuple: %s, length: %s" % (t, len(t))); # tuple: ('vsv', ['aaa', 'bbbb']), length: 2 t2 = tuple(range(1, 10)); print(t2); print((1)); print((1,)); # 代表元祖对象 # ---- dict ---- # 全称dictionary,使用key-value存储 d = {"name": "qw", "age": 22}; print(d.get("name1", "aaaaa")); # aaaaa print(d.get("name")); # qw d["name"] = "hyman"; d["aaa"] = "111dasa"; print(d); # {'name': 'hyman', 'age': 22, 'aaa': '111dasa'} d.pop("aaa"); print(d); print(len(d)); # ---- set ---- # 存储的是一组key集合,不存储value 无序 s = set(["cds", True, None, 212, 22.3]); s2 = {"cds", 212, 22.22, "cdsacdasd"}; s.add("hyman"); print(s); # s.pop(); print(s); s.remove("cds"); # 移除 print(s); # 交集、合集 print(s & s2); # {212} print(s | s2); # ==== 判断语句 ==== a = 10; if a <= 10: print("aaa"); elif 10 <= a <= 20: print("bbb"); else: print("ccc"); # 三目运算符 a, b, c = 1, 2, 3 print(a if (b > c) else c); # 3 # ==== 循环语句 ==== # l = list(range(1, 10)); # for i in l: # print(i); # i = 0; # while (i<10): # print(i); # i += 1; # print(i); # ==== 函数 ==== def test(a): a += 3; return a; print(test(8)); f = test(8); # 11 print(f); # 11 # 位置参数 def test_2(x, y="qw"): print(x, y); # 可变参数 def test_3(*num): count = 0; for i in num: count += i; return count; # 可变关键字参数 def test_4(name, **kv): if "city" in kv: print("name:%s, city:%s" % (name, kv.get("city"))); else: print("name:%s, city:%s" % (name, "sichuan")); # 命名关键字参数 def test_5(name, *, city): if not isinstance(name, (str,)): raise TypeError("Type error"); print("name:%s, city:%s" % (name, city)); if __name__ == "__main__": # 相当于main方法 print(test(8)); # 11 test_2("hello", "hyman"); # hello hyman test_2("hello"); # hello qw print(test_3()); # 0 print(test_3(*list(range(1, 9)))); # 36 print(test_3(1, 2, 3, 4, 5)); # 15 test_4("qw", **{"age": 33}); # name:qw, city:sichuan test_4("qw", **{"age": 33, "city": "cd"}); # name:qw, city:cd test_5("qw", city="cd"); # name:qw, city:cd # === 内置函数 === print(int("22")); # 数据类型转换函数,注意,如果定义变量名和函数名一样,则不会调用该函数,会报错 print(float("22.2")); print(str(22)); print(abs(-111)); # abs函数,求绝对值 print(max(12, 34, 123.4)); # max函数,求最大值 print(min(-21, -11, 0, 22.3)); # min函数,求最小值 print(" aa bb cc ".strip()); # 字符串去前后空格 print("['6K-8K']".strip('[\'\']')); # 6K-8K 移除字符串头尾指定的字符 print(hex(12)); # hex函数,将十进制数转十六进制 print(math.sqrt(3)); # 求平方根 print(sum(range(1, 101))); # 求和 print(sum(list(range(101)))); print("cdaDcdsa".capitalize()); # 将字符串第一个字符变成大写,其他小写
import random #生成随机骰子 def getRan(n): list_a = [] for x in range(n): list_a.append(random.randint(1,6)) return list_a userA = getRan(5) userB = getRan(5) print('玩家A骰子为:', userA) print('玩家B骰子为:', userB) #计算骰子总个数 def resultFuc(usera, userb): a = usera + userb b = set(a) result = [] for each_b in b: count = 0 for each_a in a: if each_b == each_a: count += 1 result.append(tuple([each_b, count])) print('总个数', result) return result result = resultFuc(userA, userB) #判断输赢 def winner(chose, result, zhai=True): finish_list = [] for i in result: if i[0] == chose[0]: finish_list.append(i) if i[0] == 1 and zhai: finish_list.append(i) print(finish_list) f = 0 for x in finish_list: f += x[1] print(f) if f >= chose[1]: print('猜对了 获胜') else: print('错了 喝酒') winner((2,8), result)
li = [1,2,3,4,5] x = 0 for i in li: x = x + i print(x) print(x)
#生成器的使用 #传统生成器 class New_Iter(object): def __init__(self): self.data = [2, 4, 8] self.step = 0 def __iter__(self): return self def __next__(self): if self.step >= len(self.data): raise StopIteration data = self.data[self.step] print (f"I'm in the idx:{self.step} call of next ()") self.step += 1 return data for i in New_Iter(): print(i) print('--------------使用yield 生成器--------------') #使用yield 生成器 def myIter(): for i, data in enumerate([1, 3, 9]): print (f"I'm in the idx:{i} call of next ()") yield data for i in myIter(): print(i)
import os, tempfile class File: """File operator""" def __init__(self, file_path): self.file_path = file_path def __str__(self): return self.file_path def _read(self): with open(self.file_path, "r") as f: return f.read() def write(self, obj): with open (self.file_path, "w") as f: return f.write(obj) def __add__(self, obj): new_file = File(os.path.join(tempfile.gettempdir(), "temp.txt")) new_file.write(self._read() + "\n" + obj._read()) return new_file def __getitem__(self, index): return self._read().split()[index] if __name__ == "__main__": a = File("/home/anton/Documents/python notebook/training/text1.txt") b = File("/home/anton/Documents/python notebook/training/text2.txt") a.write("asd") b.write("zxc") c = a + b print(a,b,c) for row in c: print(row)
"""A Probability Calculator.""" import copy import random class Hat: """ A Hat object contains a number of balls of different colors. Parameters ---------- **kwargs The keyword arguments are used for specifying the number of balls of each color that are in the hat object """ def __init__(self, **kwargs): """Specify the number of balls of each color that are in the hat.""" self.contents = [color for color, value in kwargs.items() for _ in range(value)] def draw(self, num_to_draw): """ Remove balls at random from the hat and return those balls as a list of strings. Parameters ---------- num_to_draw : int The amount of balls to draw from the hat Returns ------- drawn A list of the balls that are drawn """ if num_to_draw >= len(self.contents): return self.contents drawn = [] for _ in range(num_to_draw): random_ball = random.choice(self.contents) drawn.append(random_ball) self.contents.remove(random_ball) return drawn def experiment(hat, expected_balls, num_balls_drawn, num_experiments): """ Determine the probability of getting the expected_balls from a hat \ by performing num_experiments experiments. Parameters ---------- hat : object A hat object containing balls expected_balls : dictionary The exact group of balls to attempt to draw from the hat for the experiment num_balls_drawn : int The number of balls to draw out of the hat in each experiment num_experiments : int The number of experiments to perform Returns ------- probability the probability of getting the expected_balls from a hat """ successes = 0 for _ in range(num_experiments): temp = copy.deepcopy(hat) balls_drawn = temp.draw(num_balls_drawn) if all(balls_drawn.count(ball) >= expected_balls[ball] for ball in expected_balls.keys()): successes += 1 probability = successes / num_experiments return probability
# printing permutations of string def permutations(string,i,j): if i==j: print string return for k in range(i,j+1): m = string[i] string[i] = string[k] string[k] = m permutations(string,i+1,j) m = string[i] string[i] = string[k] string[k] = m string = "abc" permutations(list(string),0,len(string)-1)
s1 = set("Hello") print(s1) set1 = set([1, 2, 3, 4, 5, 6]) set2 = set([4, 5, 6, 7, 8, 9]) print(set1 & set2) print(set1 | set2) print(set1 - set2) # 값 한 개 추가 set1.add(7) print(set1) # 여러 값 추가 set1.update([8,9,10]) print(set1) # 값 제거 set1.remove(5) print(set1)
# guessing number s=9 j=0 while j<3: g=int(input("guess the number = ")) if g==s: print("You guessed it correctly") break else: j+=1 if j == 3: print("you are wrong") ##### use while and else funtion j =0 while j<3: g=int(input("Guess the number = ")) j+=1 if g==s: print("Bingo, it is correct") break else: print("Oops, you are wrong")
# zeros - The zeros tool returns a new array with a given shape and type filled with 's. # print numpy.zeros((1,2), dtype = numpy.int) #Type changes to int # Ones - The ones tool returns a new array with a given shape and type filled with 's. # print numpy.ones((1,2), dtype = numpy.int) #Type changes to int import numpy nums = tuple(map(int, input().split())) print (numpy.zeros(nums, dtype = numpy.int)) print (numpy.ones(nums, dtype = numpy.int))
ab = "hello Word" print(ab.find("o")) print(ab.upper()) print(ab.lower()) print(ab.replace("o", "0")) print("hello" in ab) print(len(ab)) print(ab.title()) x=10 print(10 / 3) # float output print(10 // 3) # Int output print(10 ** 3) #power function print(10 % 3) #modulus x += 3 print(x )
dic={ "name":"Amit Up", "name":"Vibha", # This one replace the value of name "Name":"Eva", "age":31, "email":"gmail" } print(dic, dic.get("surname", "Upadhyay")) # this will return Upadhyay, if key is not found. dic["name"]="Amit" dic["Mobile"]=70426 print(dic, dic.get("Mobile","new num"))
# Dictionary Question ab={"[email protected]" : "amit", "[email protected]":"vibha","[email protected]":"eva", "[email protected]":"amit" } print(ab) # Create two empty list email=[] name=[] # appended the both the list using items of the ab ditionary for n, m in ab.items(): email.append(n) name.append(m) i=len(ab) j=i-1 print(email) print(name) for n in name:
cd=[] i=0 while i<5: cd.append(int(input("Enter 5 random number tpo find the sorted list, num = "))) i+=1 print(cd) j=0 i=4 k=0 while j!=5: k=0 while k!=i: if cd[k] > cd[k+1]: temp=cd[k+1] cd[k+1]=cd[k] cd[k]=temp k = k+1 else: k=k+1 j+=1 i-=1 print(f"sorted list is {cd}")
# The from..import statement ''' If you want to directly import the argv variable into your program (to avoid typing the sys. everytime for it), then you can use the from sys import argv statement. ''' from math import sqrt print("The sqaure root of 16 is - ", int(sqrt(16))) '''WARNING: In general, avoid using the from..import statement, use the import statement instead. This is because your program will avoid name clashes and will be more readable. ''' # We can use this to make the module behave in different ways depending on whether it is being used by itself or being imported # from another module. This can be achieved using the __name__ attribute of the module if __name__ == '__main__': print('This program is being run by itself') else: print('I am being imported from another module')
for i in range(3): for j in range(3): print(f"Co-ordinates are ({i},{j})") ab=[5,2,4,2,2] for i in ab: cd="" for c in range(i): cd+="X" print(cd) print("\n") ab=[2,2,2,2,5] for i in ab: cd="" for j in range(i): cd+="X" print(cd)
# Polynomials is combination of terms with "+" or "-" and terms are (number * variable) - example x2-2xb+b2 - number == coefficient of term # nv = Monomials, nv +(-) nv = binomials, nv +(-) nv +(-) nv = Trinomials, rest are Polynomails. all can be called polynomials import numpy polyarray = numpy.array([float(x) for x in input().strip().split()]) print(polyarray) print(numpy.polyval(polyarray, float(input())))
class IceCreamMachine: def __init__(self, ingredients, toppings): self.ingredients = ingredients self.toppings = toppings def scoops(self): ab=[] cd={} for i in self.ingredients: ab.append(i) for i in ab: cd[ab[0]]=self.toppings cd[ab[1]]=self.toppings return cd if __name__ == "__main__": machine = IceCreamMachine(["vanilla", "chocolate"], ["chocolate sauce"]) print(machine.scoops()) #should print[['vanilla', 'chocolate sauce'], ['chocolate', 'chocolate sauce']]
a,b="Mr", "Amit" c=("i", "am", "Eva","Vibha") d,a=c[0:2] e,f=c[-2:] print("A",a ) print("B", b) print("C", c ) print("D",d ) print("A", a ) print("E", e ) print("F", f) print(" I am %d year old and my name is %s" % (30,"Amit")) for a in "Amit": print("Char ", a) else: print("all done")
# Python has a nifty feature called documentation strings, usually referred to by its shorter # name docstrings. DocStrings are an important tool that you should make use of since it # helps to document the program better and makes it easier to understand. Amazingly, we can # even get the docstring back from, say a function, when the program is actually running! def PMax(a,b): #below is DocString ''' there are two integer number it will print the max value of the two integer value''' x=int(a) y=int(b) if x>y: print(x, " is maximum") else: print(y, " is maximum") PMax(int(input("1st Num = ")) ,int(input("2nd Num = "))) print(PMax.__doc__) #Calling help of the function help(PMax) # The convention followed for a docstring is a multi-line string where the first line starts with a # capital letter and ends with a dot. Then the second line is blank followed by any detailed # explanation starting from the third line. You are strongly advised to follow this convention for # all your docstrings for all your non-trivial functions.
#if you break out of a for or while loop, any corresponding loop, else block is not executed. while True: s=input("Type your name = ") if s=="Eva": print("She is my lovely daughter") break print("Length of your name is ", len(s)) print("Break is over") #break and continue statement can be used with the for loop as well. while True: s=input("Enter the string = ") if s=="Eva": print("She is my lovely daughter") break if len(s)<3: print("Typer more character") continue # Continue send the command to starting point, and below line will not be displayed uuntill continue is executed print("it will start again") else: print("Continue is over")
import time import random # simplifiyng function # prints text with a timer whenever there is t2t in the text def printpause(text): i = 0 sub_start = 0 while i <= len(text): temporary = text[i:i+3] # print(temporary) if temporary == "t2t": print(text[sub_start:i]) time.sleep(2) i += 3 sub_start = i else: i += 1 print(text[sub_start:i]) time.sleep(2) # game data # list of creatures the game will choose from creatures = ["ork", "dwarf", "dragon", "vampire", "elf"] # the default weapon weapon = "old and rusty knife that nearly breaks apart" default_weapon = weapon new_weapons = [ "smartphone of eternal distraction", "holy sword of QWERTY", "the toothbrush of power and strength", "chainsaw of blood and honor"] # a random creature as the monster villain = creatures[random.randint(0, len(creatures)-1)] creature = "" # game elements # finds out the player's name and assigns a creature, # returns the players creature def intro(): name = input("Hello player, what is your name?\n") creature = creatures[len(name) % len(creatures)] printpause( name + " it shall be.t2t Mhhh....t2t It sounds like you are a(n) " + creature + ". \nIs that correct?") while True: answer = input("Type 'y' for yes and 'n' for no\n") if answer == "y": printpause( "I just know you are a(n) " + creature + " by your name. Isn't that fantastic?") break elif answer == "n": printpause( "Oh.. then you must be nothing more than an utterly" "boring human. Too bad! ") creature = "human" break else: print( "Ahh come on. I asked you a simple question." "I expect a simple answer!") printpause("But okay... enough talking. Let's start the game: \n\n\n") return creature # plays the scene that happens on the field, returns # house or cave as the next scene def field(): printpause( "You find yourself standing in an open field, filled" " with grass and yellow wildflowers. t2t" "Rumor has it that some wicked creature is somewhere around here," " and has been terrifying the nearby village.t2t" "...t2t" "In front of you is a house.t2t" "To your right is a dark cave.t2t" "Enter 1 to knock on the door of the house.t2t" "Enter 2 to peer into the cave.t2t" "You hold in your hand your "+weapon+". t2t" "What would you like to do?") while True: choice = input("(Please enter 1 or 2).\n") if choice == "1": return "house" elif choice == "2": return "cave" else: printpause("I don't know what that is.") return 0 # plays the scene at the house, alternates text depending on the weapon, # returns user's choice of "fight" or "run away" def house(): # play scenario according to choice (run or fight) printpause( "You approach the door of the houset2t" "You are about to knock when the door opens and out steps a " + villain + ".t2t" "Epp! This must be the creature you have heard about, a true " + villain + ".t2t" "The " + villain + " attacks yout2t") if creature == villain: printpause( "This seems odd to you, because you are a " + creature + "just like them. Still...") else: pass if weapon == default_weapon: printpause( "You feel under-prepared for the attack, holding only your " + weapon + "!") else: printpause( "You feel very comforable handeling the situation with your " + weapon + "!") while True: choice = input( "What would you like to do (1) fight or (2) run away?\n") if choice == "1": return "fight" elif choice == "2": return "run away" else: printpause("I don't know what that is.") return 0 # determines the outcome of the fight depending on the weapon or the creature def fight(): # chose to fight at the house influenced by creature being and weapon, if # weapon not " old and rusty knife that nearly breaks apart ", # wins the fight if creature.__eq__(villain): printpause( "The " + villain + " runs towards you and opens their arms.t2t" '"MY dear friend", they say "why don`t you come in ' 'and join me for a good old ' + villain + "-dinner?t2t" "You are slightly confused because you realise that the creature" " everyone fears is a " + creature + "just like you.t2t" "But of course you accept the invite and join your new " + villain + "-friend.") return "friends" elif weapon.__eq__(default_weapon): printpause( "You would do your best...t2t" "but your " + weapon + " breaks and you cannot match the " + villain + ".t2t" "You have been defeated!") return "game over" # has a weapon to win the fight and is not the same creature else: printpause( "As the " + villain + " moves to attack you unleash your new " + weapon + ".t2t" "The " + weapon + " is massive and you feel " "very powerful as you lift it towards the attack.t2t" "The " + villain + " looks at your shiny new toy" " and runs away!t2t" "You have rid the town of the" + villain + "." " You are victorious!") return "win" # either assigns player find a random powerful weapon or nothing happens # if they do not have the default weapon anymore def cave(): global weapon # if weapon already picked up nothing happens, # otherwise weapon = random weapon name # if weapon is still default, player picks up a brand new weapon if weapon.__eq__(default_weapon): number = random.randint(0, len(new_weapons)-1) weapon = new_weapons[number] printpause( "You walk cautiously into the cave.t2t" "Turns out to be only a very small cave.t2t" "Your eye catches a glint of metal behind a rock.t2t" "You have found the " + weapon + "!t2t" "You discard your silly old " + default_weapon + " and take the new " + weapon + " with you.t2t") # if weapon is already new, the player won't find anything anymore else: printpause( "You have been here before, and gotten all" " the good stuff.t2t" "It's just an empty cave now.t2t") print("You walk back out to the field.\n") # plays the game, works recurringly def play_game(skip_intro=0): # function that starts the play_game global weapon global creature global villain if skip_intro == 0: creature = intro() else: pass # starts the field choice = field() if choice == "house": choice = house() # when the player chose to fight if choice == "fight": choice = fight() # when creature and villain are the same if choice == "friends": print(choice) printpause( "You guys have a good time over your dinner.t2t" "The only ones not having such a good time are the" "people in the nearby village.t2t" "Instead of one " + villain + " strolling around town, there are now two.t2t" "But I guess that makes you certainly win this game" "\n Sucess: You won") # when they fought and the player won elif choice == "win": printpause("\n\n Congrats, you won! \n\n") # when they fought and the player lost elif choice == "game over": printpause("xxxt2t\n\n\n\nGAME OVER\n\n\n") # when the player decides to run away, # he ends up back on the field elif choice == "run away": printpause("You ran away, back to the field where you started. ") play_game(1) elif choice == "cave": cave() play_game(1) # if they want to restart, skip it is restarted while True: choice = input("Do you want to restart the game (y) yes or (n) no ?") if choice == "y": printpause("Excellent.t2tRestarting the game.t2t") # resetting values villain = creatures[random.randint(0, len(creatures)-1)] weapon = default_weapon play_game(0) elif choice == "n": printpause("Okay.t2tThanks for playing.t2t") quit() else: printpause("Sorry, I did not get it.") # start play_game if __name__ == '__main__': play_game()
__author__ = 'cheetah' import pandas as pd from pandas import ExcelWriter # Approach for the Problem ''' 1. The person can leaps max up to the Leap Size only i..e cap = 4 , person can make leaps of 1,2,3,4 2. Assuming if the peg size is more than Leap size , then he will do the next leap depending on the remaining size of Total Leap and the Leap Size i..e cap = 4 , peg size = 10 person can make leaps of 4 ,4 ,2 the last leap of 2 will depend on the peg appeared on that second 3. The person will wait for another Peg even though it's covering the X to Y distance Pegs = [10,3,1,9,7,5,8] Assume the first Peg was 10 and total was 10 Then 1 second leap size 4 then 2 second another 4 depending on the next peg size is 3 as compared to earlier peg size 10 <= total In 3rd second another peg size of 1 emerges ,but it's of no use and since the remaining is 2 it will make a leap and reach at Y ''' # getting the sum of pegs # removing the pegs which already used def bestLeapTime(totsize,leapsize,pegs): i = 1 tillnow = 0 newIndex = 0 while totsize > 0: idxSum = max(pegs[newIndex:i]) # find the max till the latest pegs if idxSum >= leapsize and idxSum > tillnow: #check with latest peg and covered till now nextleap = idxSum - tillnow # print(nextleap) if nextleap >= leapsize: #Case for leap with max leap totsize = totsize - leapsize tillnow = tillnow + leapsize print("Next Hop->", leapsize) else: #Case for leap with less leap size totsize = totsize - nextleap tillnow = tillnow + nextleap print("Next Hop->", nextleap) else: print("Next Hop -> Wait for Peg") if totsize > leapsize: i += 1 try: newPeg = max(pegs[:i]) # find the max next to the latest pegs if newPeg > idxSum: newIndex = i - 1 except: print("Out of range") else: i += 1 if totsize < leapsize: print("Last Hop->", totsize) else: print("Last Hop->", leapsize) totsize = totsize - leapsize return i ''' The below functions validates the Case of the inputs given 1. cutoffpeg: The remaining distance from the cap size cap = 3 tot = 9 [2,1,4,6,8,3] in the pegs basket. cutoffpeg = 9-3 = 6 ,there has to be one peg which is of the cutoffpeg else cross of the river is not possible assume cap = 8 , tot = 8 if cutoffpeg = 0 , which means the person can make a leap in max leap size and go to Y from X ''' def checkPegsValidity(Tot_dist, Max_leap, No_of_pegs): cutoffpeg = Tot_dist - Max_leap if cutoffpeg == 0: #'Case where crossing is done in 1 leap' return 1 cutofflist = [peg for peg in No_of_pegs if peg >= cutoffpeg] ''' There must be least no pegs to pave the path for the other end i..e Y from X. for 15 totsize leap size 5 15 - 5 = 10 atleast more than 1 entry of 10 should be there Works on the input Totsize 10 max leap = 4 pegs = [2,4,1,9,7,5,8] ''' lastLeap = cutofflist if len(cutofflist) < 1: #print("Crossing not possible as right size of peg not present") return "Not able to cross" else: timer = bestLeapTime(Tot_dist, Max_leap, No_of_pegs) #print("The best possible time required would -->") #print(timex) return timer ''' This function converts the line of strings into integer from the input file ''' def makepegs(peglist): newlist = list() for vals in peglist: print vals newlist.append(int(str(vals))) return newlist print("Welcome to the river crosser Guide") readlines = pd.read_csv("test.csv") type(readlines) totalcases = readlines.shape[0] # pandas shape function val = list() for cases in range(0,totalcases): totdist = readlines.iloc[cases][1] #get the Total distance maxleap = readlines.iloc[cases][2] #get the max leap print "printing raw pegs" peglist = readlines.iloc[cases][3] # get the pegs list listofpegs = list(peglist.split(',')) print listofpegs noofpegs = makepegs(listofpegs) # Make proper integer list print noofpegs timex = checkPegsValidity(totdist, maxleap, noofpegs) # check and follow the algorithm val.append(timex) readlines['Time-taken(Secs)'] = val # Add the new list of output in the data frame writer = ExcelWriter('output.xlsx') # make the output list readlines.to_excel(writer, 'Sheet1') # writer.save()
# # @lc app=leetcode.cn id=94 lang=python # # [94] 二叉树的中序遍历 # # @lc code=start # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ # 递归法 # result = [] # def helper(root): # if root: # helper(root.left) # result.append(root.val) # helper(root.right) # helper(root) # return result # 迭代法一, 栈遍历 # result, stack, cur = [], [], root # while cur or stack: # while cur: # stack.append(cur) # cur = cur.left # cur = stack.pop() # result.append(cur.val) # cur = cur.right # return result # 迭代法二, 栈模拟 result, stack = [], [] if root: stack.append(root) while stack: current = stack.pop() if current: if current.right: stack.append(current.right) stack.append(current.val) stack.append(None) if current.left: stack.append(current.left) else: result.append(stack.pop()) return result # @lc code=end
# # @lc app=leetcode.cn id=127 lang=python # # [127] 单词接龙 # # @lc code=start from collections import defaultdict import string class Solution(object): def ladderLength(self, beginWord, endWord, wordList): """ :type beginWord: str :type endWord: str :type wordList: List[str] :rtype: int """ # 单向BFS # if not beginWord or not endWord or not wordList or endWord not in wordList: # return 0 # dic = defaultdict(list) # # 预处理wordlist # for word in wordList: # for i in range(len(word)): # dic[word[:i] + '*' + word[i + 1:]].append(word) # queue = [(beginWord, 1)] # visited = {beginWord} # while queue: # current_word, level = queue.pop(0) # if current_word == endWord: # return level # for i in range(len(current_word)): # pair_word = current_word[:i] + '*' + current_word[i + 1:] # for word in dic[pair_word]: # if word not in visited: # queue.append((word, level + 1)) # visited.add(word) # dic[pair_word] = [] # return 0 # 双向BFS if endWord not in wordList: return 0 front = {beginWord} back = {endWord} distance = 1 wordList = set(wordList) while front: distance += 1 next_front = set() for word in front: for i in range(len(word)): # 'abcdefg....xyz' for c in string.lowercase: if c != word[i]: new_word = word[:i] + c + word[i + 1:] if new_word in back: return distance if new_word in wordList: next_front.add(new_word) wordList.remove(new_word) front = next_front if len(back) < len(front): front, back = back, front return 0 # print(Solution().ladderLength('hit', 'cog', ['hot','dot','dog','lot','log','cog'])) # @lc code=end