text
stringlengths 37
1.41M
|
---|
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 22 19:52:58 2019
@author: Joe
"""
#Creating a simple list of friend names
friends = ["Ben","Yarden","Michael"]
print(friends)
#Adding Gabi's name to the end of the list
friends.append("Gabi")
print(friends)
#Adding Abby's name between Ben and Yarden in the list
friends.insert(1,"Abby")
print(friends)
#Removing Yarden's name from the list
del friends[2]
print(friends)
#Creating a new pop list
oldest=friends.pop(0)
message="The oldest friend I have is " + oldest + "."
print(message)
#Creating a list of dinner guests
dinner= ["Julius Ceasar", "Marcus Crassus" , "Gnaeus Pompeius"]
invitation= "\nDearest " + dinner[0] + ",\nWould you do me the \
pleasure of joining me at my villa in Campania for \
Saturnalia? \nI can assure you that my wines are of\
the finest vintage and my vomitorium of the most sublime\
quality.\nI look forward to your response!\nYours truly,\n\
Joe\n\n"
print(invitation)
#Pompeius Magnus is in the dog house
#Better invite Mark Antony instead
del dinner[2]
dinner.append("Mark Antony")
print(dinner)
#Turns out Cato found out about our party and is quite
#Cross the he wasn't invited. Better add him to the list
dinner.insert(1, "Marcus Porcious Cato")
print(dinner)
|
# Creating a test for the class created in Employee.py
import unittest
from Employee import Employee
class EmployeeTestCase(unittest.TestCase):
"""Test for 'Employee.py'"""
def setUp(self):
"""Creates an employee for use in all test methods"""
self.my_employee = Employee('joe', 'pickert', 65000)
def test_give_default_raise(self):
"""Test to ensure that default raise == $5000"""
self.my_employee.give_raise()
self.assertEqual(self.my_employee.salary, 70000)
def test_give_cust_raise(self):
"""Test to ensure that custom raises are applied appropriately"""
self.my_employee.give_raise(10000)
self.assertEqual(self.my_employee.salary, 75000)
unittest.main()
|
# creating a dictionary of personal information
stranger = {
'first_name' : 'pablo',
'last_name' : 'sandoval',
'hometown' : 'syracuse',
'sport' : 'baseball'
}
print("The stranger's first name is " + stranger['first_name'].title() +".")
print("His last name is " + stranger['last_name'].title() + ".")
print("He was born in " +stranger['hometown'].title() +" and likes to play "
+ stranger['sport'] +".")
# using a loop to print all key-value pairs
for key, value in stranger.items():
print("\nKey: " + key)
print("Value: "+ value.title())
# creating a dictionary of friends and their favorite languages
favorites = {
'ben' : 'english',
'yarden' : 'hebrew',
'michael' : 'german',
'joe' : 'spanish',
'wesley' : 'mandarin'
}
# reporting each person's favorite language
print("\nSome of my friends' favorite languages: ")
for name, value in favorites.items():
print(name.title() + "'s favorite languge is " + value.title() +".")
# reporting only the names in my dictionary
print("\nI chose to include the following people in my list: ")
for name in favorites.keys():
print(name.title())
# reporting only the languages in my dictionary
print("\nThese were some of my friends' favorite languages: ")
for language in favorites.values():
print(language.title())
# creating a list of rivers and a country that they abutt
rivers = {
'rhine' : 'germany',
'danube' : 'romania',
'yellow' : 'china'
}
# printing each river and its associated country
print('\nThese are some well known rivers and the countries they run through:')
for key, value in rivers.items():
print('The ' + key.title() + ' River runs through ' + value.title() +'.')
# printing respective lists of just the rivers and countries respectively
print('\nThe rivers included in this list were:')
for river in rivers.keys():
print('The ' + river.title())
print('\nThe countries included in this list were: ')
for country in rivers.values():
[print(country.title())]
# creating a dictionary with nested lists of favorite bikes
bikebrands = {
'joe' : ['giant', 'specialized'],
'topher' : ['trek', 'salsa'],
'alec' : ['yeti', 'trek']
}
print("These are a few of my friends' favorite bike brands: ")
for name, bikes in bikebrands.items():
print(name.title() + "'s favorite bike brands are: ")
for bike in bikes:
print("\t" + bike.title())
# creating nested dictionaries
senators = {
'ceasar' : {
'praenomen' : 'gaius',
'gens' : 'julius',
'cognomen' : 'caesar',
'offices' : ['quaestor', 'aedile', 'praetor', 'consul', 'dictator']
},
'cicero' : {
'praenomen' : 'marcus',
'gens' : 'tullius',
'cognomen' : 'cicero',
'offices' : ['quaestor', 'aedile', 'praetor', 'consul']
},
'clodius' : {
'praenomen' : 'publius',
'gens' : 'clodius',
'cognomen' : 'pulcher',
'offices' : ['quaestor', 'aedile', 'tribune of the plebs']
}
}
print("\nThese are a few of Rome's most famous Senators:")
for senator, info in senators.items():
print("\nCommon name: " + senator.title())
print("\tFull name: " + info['praenomen'].title() + " " + info['gens'].title() + " " +
info['cognomen'].title())
print("\tMagesterial offices held: ")
for office in info['offices']:
print("\t\t" + office.title())
|
import sys
from random import randrange
#Author: J. Andrew Key
#Objective: Implement quicksort (aka "partition-exchange" sort) that makes
#on average, O(n log n) comparisons to sort n items. This solution benefits
#from "list comprehensions", which keeps the syntax concise and easy to read.
def quicksort(list):
# an empty list is already sorted, so just return it
if list == []:
return list
else:
#select a random pivot value and remove it from the list
pivot = list.pop(randrange(len(list)))
#filter all items less than the pivot and quicksort them
lesser = quicksort([l for l in list if l < pivot])
#filter all items greater than the pivot and quicksort them
greater = quicksort([l for l in list if l >= pivot])
#return the sorted results
return lesser + [pivot] + greater
#Python is a dynamically typed language, allowing us to easily sort a list of
#integers or strings with the same function.
#1. Sorting an unsorted list of integers
l = [5,3,4,1,89]
print "Quicksorting a list of integers"
print "\tunsorted -> " + str(l)
print "\tsorted -> " + str(quicksort(l))
#2. Sorting an unsorted list of strings
print "Quicksorting a list of strings"
l = ["andy", "jimmy", "tom", "lucy", "skye", "jill"]
print "\tunsorted -> " + str(l)
print "\tsorted -> " + str(quicksort(l))
|
#!/usr/bin/env python2.7
import time
import datetime
d1 = datetime.datetime(2005,2,16)
d2 = datetime.datetime(2004,12,31)
print (d1 - d2).days
|
class ResizableArray(object):
"""Class representing resizable array implementation"""
def __init__(self, capacity):
self.capacity = capacity
self.size = 0
self.arr = [None] * self.capacity
def __getitem__(self, key):
self._check_index_range(key)
return self.arr[key]
def __setitem__(self, key, value):
self._check_index_range(key)
self.arr[key] = value
def __delitem__(self, key):
self._check_index_range(key)
self.arr[key:] = self.arr[key+1:]
self.size -= 1
if self.size <= self.capacity / 2:
self._reduce_array_capacity()
def __len__(self):
return self.size
def append(self, value):
if self.size == self.capacity:
self._double_array_capacity()
self.arr[self.size] = value
self.size += 1
def _double_array_capacity(self):
self.capacity *= 2
new_arr = [None] * self.capacity
for index, value in enumerate(self.arr):
new_arr[index] = self.arr[index]
self.arr = new_arr
def _reduce_array_capacity(self):
self.capacity = 1 if self.capacity == 1 else int(self.capacity / 2)
new_arr = [None] * self.capacity
if len(self.arr) != 0:
for index, value in enumerate(new_arr):
new_arr[index] = self.arr[index]
self.arr = new_arr
def _check_index_range(self, index):
if index < 0 or index >= self.size:
raise IndexError('Index our of range')
|
import random
import seven_up_deck
# ********************************************************
# CLASS: Round
# ********************************************************
class Round():
# ********************************************************
# METHOD: __init__
# ********************************************************
def __init__(self, round_num, num_cards, users, dealer, trump):
print 'ROUND[' + str(round_num) + ']: Num Cards = ' + str(num_cards) + ', Dealer = ' + users[dealer].name
self.num_cards = num_cards
self.users = users
self.dealer = dealer
self.deck = seven_up_deck.Deck()
self.deck.shuffle()
self.deal()
# self.deck.print_deck()
self.trump = trump
self.trump_card = self.deck.pull_card()
if self.trump:
print 'TRUMP: ' + seven_up_deck.card_to_string(self.trump_card)
else:
print 'NO TRUMP'
# ********************************************************
# METHOD: deal
# ********************************************************
def deal(self):
for index in range(0,self.num_cards):
for id in self.users:
card = self.deck.pull_card()
self.users[id].add_card(card)
|
# -*- coding: utf-8 -*-
import time
def timer(func):
'''A simple decorator to count time.
'''
def wrapper(*args, **kwds):
time_begin = time.time()
ret = func(*args, **kwds)
time_end = time.time()
time_cost = time_end - time_begin
print 'call %s cost %f second(s)' % (func.__name__, time_cost)
return ret
return wrapper
|
##################################################################################################################################
# Kruskal's algorithm:It computes the minimum spanning tree of a network.Minimum spanning tree is optimization of graph #
# and also ensure that all nodes have connection between them, and MST has weight lesser than main spanning tree. #
# in terms of Networking, using this algorithm network do not form a loop, and broadcast strom can be eliminated #
# Input - it accepts a 2d array- first Row and first Column represent vertices, between them weight of the edge #
# Output - the length of the minimum spanning tree #
# ################################################################################################################################
def Kruskal(data):
"""
Kruskal algorithm, it consists of two part. First Part: Sorting edges in ascending order by their weight.
Second Part: Take a graph with total number(n) of vertices,keep adding the shortest(least weight) edge,
while avoiding the creation of cycles, until (n-1) edges have been added.
"""
edges = []
total_weight = 0
num_vertices = 0
for i, line in enumerate(data): # looping through raw and column of matrix
num_vertices += 1
for j, weight in enumerate(line.rstrip().decode('ascii').split(',')):
if weight == '-' or i >= j: # if weight is other than number
continue
total_weight += int(weight)
edges.append([int(weight), i, j]) # Collecting edges and their weight
edges = sorted(edges)
graph = {}
min_weight = 0
for edge in edges:
weight, node1, node2 = edge
undis = set(range(num_vertices))
s = [node1]
while len(s):
v = s.pop()
if v in undis: # checking one of the vertex of edge in the undiscovered node
undis.remove(v)
if v in graph:
try:
nodes = graph[v].iterkeys()
except AttributeError:
nodes = graph[v].keys()
s.extend(nodes)
if node2 in undis: # Checking the Second vertex of edge with minimum weight
if node1 not in graph:
graph[node1] = {}
graph[node1][node2] = weight # adding not forming loop edges in graph
if node2 not in graph:
graph[node2] = {}
graph[node2][node1] = weight
min_weight += weight # calculating minimum weight from edges added in graphs
return total_weight - min_weight
|
import random
number = random.randint(1,10)
name = input('Hi, Whats your name? ')
print ("Well", name, "I have a number in mind between 1 and 10, take a guess")
guess1 = int(input()) # convert input from string to integer
while guess1 != number:
if guess1 > number:
print ('your guess is too high. Try again.')
elif guess1 < number:
print ('your guess is too low. Try again.')
guess1 = int(input()) # asks user to take another guess
print("excellent!")
|
import re
def checkio(data: str) -> bool:
small = big = digit = False
for l in data:
if l.isdigit():
digit = True
continue
if l.isupper():
big = True
continue
if l.islower():
small = True
continue
return small and big and digit and len(data) >= 10
#Some hints
#Just check all conditions
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio('A1213pokl') == False, "1st example"
assert checkio('bAse730onE4') == True, "2nd example"
assert checkio('asasasasasasasaas') == False, "3rd example"
assert checkio('QWERTYqwerty') == False, "4th example"
assert checkio('123456123456') == False, "5th example"
assert checkio('QwErTy911poqqqq') == True, "6th example"
assert checkio('aaaaaaaaaaaaaaaaaaaaa') == False, "7th example"
print("Coding complete? Click 'Check' to review your tests and earn cool rewards!")
|
# Maintain the doubly linkedlist and dictionary of node
class Node:
def __init__(self, key:int, value:int):
self.key = key
self.value = value
self.prev = None
self.next = None
class LRUCache:
def __init__(self, capacity:int):
self.capacity = capacity
self.dic = {}
self.head = Node(0,0)
self.tail = Node(-1,-1)
self.head.next = self.tail
self.tail.prev = self.head
def get(self, key:int) -> int:
if key in self.dic:
node = self.dic[key]
self.removeFromList(node)
self.insertAtHead(node)
return node.value
return -1
def put(self, key:int, value:int) -> None:
if key in self.dic:
node = self.dic[key]
self.removeFromList(node)
node.value = value
self.insertAtHead(node)
else:
if len(self.dic) >= self.capacity:
self.removeFromTail()
node = Node(key,value)
self.insertAtHead(node)
self.dic[key] = node
def insertAtHead(self,node):
head_next = self.head.next
node.next = head_next
node.prev = self.head
self.head.next = node
head_next.prev = node
def removeFromList(self, node):
node.prev.next = node.next
node.next.prev = node.prev
def removeFromTail(self, node):
if len(self.dic) <= 0 :
return
before_tail = self.tail.prev
del self.dic[before_tail.key]
self.removeFromList(before_tail)
obj1 = LRUCache(5)
obj1.put(1,10)
obj1.put(2,2)
obj1.put(3,3)
param1 = obj1.get(1)
print(param1)
|
def nombreMystere(y):
#On récupère chaque chiffre des unités, dizaines et centaines
c=y//100
d=(y-c*100)//10
u=(y-c*100-d*10)//1
#On teste les différentes conditions :
#On comprends vite que le chiffre des dizaines sera forcément 4 d'après la conditions 5
if (d!=4):
return False
if (c+d+u>10):
return False
if (c==0):
if(u!=2):
return False
if (((d+u)%2)==0):
return False
if ((d==1)or (d==7)or(u==1) or(u==7)):
return False
else:
return True
elif (u==3):
if (((d+c)%2)==0):
return False
if ((d==1)or(d==7)or(u==1)or(u==7)or(c==1)or(c==7)):
return False
else :
return True
ok=False
mystery_number=20
while ((ok==False) and (mystery_number<901)): #On voit rapidement que tous les nombres >900 ne peuvent pas vérifier les conditons 2 et 3 en même temps
if (nombreMystere(mystery_number)==True):
print("Le nombre mystère est :", mystery_number)
mystery_number=mystery_number+1
|
def area(p):
return 0.5 * abs(sum(x0*y1 - x1*y0
for ((x0, y0), (x1, y1)) in segments(p)))
def segments(p):
return zip(p, p[1:] + [p[0]])
def checkio(data):
return area(data)
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio([[1, 1], [9, 9], [9, 1]]) == 32, "The half of the square"
assert checkio([[4, 10], [7, 1], [1, 4]]) == 22.5, "Triangle"
assert checkio([[1, 2], [3, 8], [9, 8], [7, 1]]) == 40, "Quadrilateral"
assert checkio([[3, 3], [2, 7], [5, 9], [8, 7], [7, 3]]) == 26, "Pentagon"
assert checkio([[7, 2], [3, 2], [1, 5],
[3, 9], [7, 9], [9, 6]]) == 42, "Hexagon"
assert checkio([[4, 1], [3, 4], [3, 7], [4, 8],
[7, 9], [9, 6], [7, 1]]) == 35.5, "Heptagon"
|
def checkio(number):
n = number
d = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
# 21 - twenty-one
30: 'thirty',
40: 'forty',
50: 'fifty',
60: 'sixty',
70: 'seventy',
80: 'eighty',
90: 'ninety',
100: 'hundred'
}
def f(n):
if n <= 20:
return d[n]
a = (n / 10) * 10
b = n % 10
if b == 0:
return "{0}".format(d[a])
else:
return "{0} {1}".format(d[a], d[b])
if n < 100:
return f(n)
else:
a = (n / 100) % 10
b = n % 100
if b == 0:
return "{0} {1}".format(d[a], d[100])
else:
return "{0} {1} {2}".format(d[a], d[100], f(b))
if __name__ == '__main__':
assert checkio(4) == 'four', "First"
assert checkio(133) == 'one hundred thirty three', "Second"
assert checkio(12)=='twelve', "Third"
assert checkio(101)=='one hundred one', "Fifth"
assert checkio(212)=='two hundred twelve', "Sixth"
assert checkio(40)=='forty', "Seventh, forty - it is correct"
print 'All ok'
|
from fractions import gcd
def checkio(values):
'Calculate the greatest common divisor of two numbers'
a, b = values
return gcd(a, b)
if __name__ == '__main__':
assert checkio((12, 8)) == 4, "First"
assert checkio((14, 21)) == 7, "Second"
print 'All ok'
|
from fractions import Fraction
class Matrix(object):
def __init__(self, matrix):
self.matrix = matrix
self.n = len(matrix)
def replace_col(self, col, data):
for i in range(self.n):
self.matrix[i][col] = data[i]
def sub_determinant(self, i, j):
matrix = []
for i_ in range(self.n):
row = []
for j_ in range(self.n):
if not (i_ == i or j_ == j):
row.append(self.matrix[i_][j_])
if row:
matrix.append(row)
return Matrix(matrix)
def determinant(self):
if self.n == 1:
return self.matrix[0][0]
elif self.n == 2:
(a, b), (c, d) = self.matrix
return a*d - b*c
else:
return sum(
((-1) ** i) * self.matrix[0][i] * self.sub_determinant(0, i).determinant()
for i in range(self.n)
)
def __str__(self):
return '\n'.join(str(row) for row in self.matrix)
METALS = ('gold', 'tin', 'iron', 'copper')
def checkio(alloys):
"""
Find proportion of gold
"""
A = []
b = []
for k, v in alloys.items():
metals = k.split('-')
eq = []
for metal in METALS:
if metal in metals:
eq.append(Fraction(1, 1))
else:
eq.append(Fraction(0, 1))
A.append(eq)
b.append(v)
A.append([Fraction(1, 1), Fraction(1, 1), Fraction(1, 1), Fraction(1, 1)])
b.append(Fraction(1, 1))
A = Matrix(A)
D = A.determinant()
A.replace_col(0, b)
Dx = A.determinant()
return Dx / D
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio({
'gold-tin': Fraction(1, 2),
'gold-iron': Fraction(1, 3),
'gold-copper': Fraction(1, 4),
}) == Fraction(1, 24), "1/24 of gold"
assert checkio({
'tin-iron': Fraction(1, 2),
'iron-copper': Fraction(1, 2),
'copper-tin': Fraction(1, 2),
}) == Fraction(1, 4), "quarter"
|
#for迴圈
#for 變數 in 字串OR列表:
# 要重複執行的程式碼
# for letter in "小白你好":
# print(letter)
# for num in [0,1,2,3,4]:
# print(num)
# for num in range(2,10):
# print(num)
# print(pow(2,6))
# 2*2*2*2*2
def power(base_num,pow_num):
result = base_num
for index in range(pow_num-1):
result=result*base_num
return result
print (power(2,5))
|
#類別class 物件object
class phone:
def __init__ (self,os,number,is_waterproof): #底線案兩次 變長底線
self.os = os
self.number = number
self.is_waterproof = is_waterproof
phone1 = phone ("ios",123,True)
print (phone1.os)
phone2 =phone ("android",456,False)
print (phone2.number)
|
#如何使用字串、字串用法
print("hello \nMr.white")
print("hello \n \"mr.white\"")
#hello" mr. white
print("hello " + "mr.white")
phrase = "hello"
print(phrase + " mr. white")
# 函式 fuction
phrase = "HELLO MR. wHITE"
#字母變小寫 /檢查字母是否都是小寫
print(phrase.lower().islower())
#字母變大寫
print(phrase.upper())
print(phrase.islower())
#檢查字母是否大寫
print(phrase.isupper())
#第幾個字母
print(phrase[4])
#字母位子在第幾個
print(phrase.index("M"))
#字母替換
print(phrase.replace("M","Z"))
|
# 2. Реализовать функцию, принимающую несколько параметров, описывающих данные пользователя: имя, фамилия,
# год рождения, город проживания, email, телефон. Функция должна принимать параметры как именованные аргументы.
# Реализовать вывод данных о пользователе одной строкой.
fields = ('Name ', 'Second name ', 'Year of birth ', 'Where do you live ', 'Your email ', 'Your telephone ')
data = []
while True:
change = input ('Нажмите любую кнопку или q для выхода - ')
if change == 'q':
break
person = {}
for field in fields:
person[field] = input(f'Введите значение поля - {field} ')
data.append(person)
print(data)
|
#!/usr/bin/python3.6
import pygame, sys
from pygame.locals import *
pygame.init() # activates Pygame, always the first command after import statements
FPS = 30 # frames per second setting
fpsClock = pygame.time.Clock()
# set up the window
DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32) # creates a surface object of size width x height
pygame.display.set_caption('Animation') # sets the text at the top of the window
WHITE = (255, 255, 255)
catImg = pygame.image.load('cat.png') # load cat image and place it on screen
catx = 20
caty = 20
direction = 'down'
while True: # main game loop: 1) handles events, 2) updates game state, 3) draws game state to screen
DISPLAYSURF.fill(WHITE)
if direction == 'right':
catx += 5
if catx ==280:
direction = 'up'
elif direction == 'down':
caty += 5
if caty == 220:
direction = 'right'
elif direction == 'left':
catx -= 5
if catx == 10:
direction = 'down'
elif direction == 'up':
caty -= 5
if caty == 10:
direction = 'left'
DISPLAYSURF.blit(catImg, (catx, caty)) # blit: draw the contents of one surface onto another...e.g. copy the cat image to surface object
for event in pygame.event.get(): # event handling: checks to see if certain events have occurred
if event.type == QUIT:
pygame.mixer.music.stop()
pygame.quit() # deactivates Pygame...opposite of pygame.init()
sys.exit() # terminates program
pygame.display.update() # draws the surface object held by the DISPLAYSURF variable
fpsClock.tick(FPS)
|
#Get name
name = input("What is your name?\n")
#Print name
print("Hello,", name)
|
#Pedro Gallin
#9/15/17
#warmUp3.py- sees if a number is divisible by 2 or three
num = int(input('Enter a number: '))
if num%2 == 0 and num%3 == 0:
print(num,'Is divisible by 3 and 2')
elif num%2 == 0:
print(num,'Is divisible by 2')
elif num%3 == 0:
print(num,'is diviseble by 3')
else:
print(num,'Is not divisible by 2 or 3')
|
#Pedro Gallino
#9/14/17
#fortuneTeller.py - tells a fortune
color = (input('Pick a color red or blue: '))
num = int(input('Pick a number from 1-4: '))
if color == 'red' and num == 1:
print('You will live to be 200 years old')
elif color == 'red' and num == 2:
print('You will survive a mountain lion attack')
elif color == 'red' and num == 3:
print('You will meet the most annoying person ever: Clay')
elif color == 'red' and num == 4:
print('You will find a bear in your bedroom today')
elif color == 'blue' and num == 1:
print('You will win the powerball')
elif color == 'blue' and num == 2:
print('you will loose 100,000 dollars tomorrow')
elif color == 'blue' and num == 3:
print('You will crash your car and loose an eye')
elif color == 'blue' and num == 4:
print('you will find an iphone X on the ground two years from now')
else:
print("This doesn't work")
|
class StdOutException(Exception):
"""
Raised when data is written to stdout
"""
def __init__(self, text, errno=1):
"""
:text: Output text
;errno: Exit status of program
"""
self.text = text
self.errno = errno
def __str__(self):
return self.text
class StdErrException(Exception):
"""
Raised when data is written to stderr
"""
def __init__(self, text, errno=2):
"""
:text: Error text
;errno: Exit status of program
"""
self.text = text
self.errno = errno
def __str__(self):
return self.text
class CommandNotFoundException(Exception):
"""
Raised when an unknown command is requested
"""
def __init__(self, prog):
self.prog = prog
def __str__(self):
return f"Command `{self.prog}' not found."
class ExtraOperandException(StdErrException):
"""
Raised when an argument is expected but not found
"""
def __init__(self, program, operand, errno=1):
"""
:program: Program that caused the error
:operand: Value of the extra operand
;errno: Exit status of program
"""
self.program = program
self.operand = operand
self.errno = errno
def __str__(self):
return (
"{0}: extra operand `{1}'. Try {0} --help' for more ".format(
self.program, self.operand
)
+ "information."
)
class MissingOperandException(StdErrException):
"""
Raised when an argument is expected but not found
"""
def __init__(self, program, errno=1):
"""
:program: Program that caused the error
;errno: Exit status of program
"""
self.program = program
self.errno = errno
def __str__(self):
return (
"{0}: missing operand. Try `{0} --help'".format(self.program)
+ " for more information."
)
|
print("Welcome to band name generator")
city = input("Enter the name of the city you grew up in\n")
pet = input("Enter the name of your first pet\n")
print("Your band name can be " + city +" "+ pet)
|
def nextCollatzNumber(n):
if n % 2 == 0:
return n / 2
else:
return 3*n + 1
def CollatzChain(n):
start = n
count = 1
if n == 1:
return count
while nextCollatzNumber(start) != 1:
count += 1
start = nextCollatzNumber(start)
return count + 1
def lookForLongestCollatz(n):
longestChain = 0
num = 0
for i in range(1, n):
chain = CollatzChain(i)
if chain > longestChain:
longestChain = chain
num = i
return num
print lookForLongestCollatz(1000000)
|
from math import sqrt
def divisors(m):
count = 0
for i in range(1, int(sqrt(m)) + 1):
if m % i == 0:
if not (m / i == i):
count += 2
else:
count += 1
return count
def consecSameDivs(m, n):
consecSameDivisors = 0
prev = divisors(m) # number of divisors for 2, to start
for i in range(m + 1, n):
numDivs = divisors(i)
if numDivs == prev:
consecSameDivisors += 1
prev = numDivs
print(i)
return consecSameDivisors
print consecSameDivs(2, (10**7))
|
'''
[3,5] [3,6]
[4,5] [5,6][6,7]
[4,6][6,8]
3: [4,5][5,6][6,7]
'''
def answer(meetings):
sort = sorted(meetings)
uniq = []
for x in sort:
if x not in uniq:
uniq.append(x)
print uniq
meetings = []
for x in range(0, len(uniq) - 1):
print x
if (uniq[x][1] - 1 in range(uniq[x + 1][0], uniq[x + 1][1])):
print meetings
return len(meetings)
|
def answer(x, y, z):
sort = sorted([x, y, z])
time = str(sort[0]) + "/" + str(sort[1]) + "/" + str(sort[2])
a = sort[0]
b = sort[1]
c = sort[2]
# February
if (a == 2) and (b > 28):
return "Ambiguous"
if (a == 2) and (c < 29) and (c != b):
return "Ambiguous"
# Months with 30 days
if (a in [4, 6, 9, 11]) and (b > 30):
return "Ambiguous"
if (a in [4, 6, 9, 11]) and (c < 31) and (c != b):
return "Ambiguous"
# Repeats: Same Month/Day + Year/Month
if (b < 13) and (b != a):
return "Ambiguous"
if (c < 32) and (c != b):
return "Ambiguous"
# Constraints to double check everything
if (b > 31):
return "Ambiguous"
if (a > 12):
return "Ambiguous"
if (a < 10):
a = "0" + str(a)
if (b < 10):
b = "0" + str(b)
if (c < 10):
c = "0" + str(c)
return str(a) + "/" + str(b) + "/" + str(c)
|
# Basic script to simulate problem #9 for miniproject 1 in ISYE6644 - Simulation class
# Written by: Spencer Vore & Jessica Warr
import random
import sys
import math
import matplotlib.pyplot as plt
import statistics
import argparse
# Function to take the next turn
def take_turn(player, verbose=False, print_end_state=False):
'''Takes one turn in the game for specified player.
player - Name of the player in the global simulation state who
is taking the turn.
verbose - If True, run all print statements.
print_end_state - If true, print final results of the game to
the terminal. (verbose=True overrides false values)
'''
if verbose: print(f"PLAYER {player} IS NOW TAKING THEIR TURN.")
dice_roll = random.randint(1,6)
if verbose: print(f"\tRolled value of dice is {dice_roll}.")
# Possibilities for dice rolls
if dice_roll == 1:
if verbose: print(f"\tNothing happens during player's turn.")
pass
if dice_roll == 2:
if verbose: print(f"\tPlayer takes all {GameState['pot']} coins in the pot.")
GameState[player] += GameState['pot']
GameState['pot'] = 0
if dice_roll == 3:
coins_to_take = int(math.floor(GameState['pot'] / 2))
if verbose: print(f"\tPlayer takes half of the coins (i.e. {coins_to_take}) from the pot.")
GameState[player] += coins_to_take
GameState['pot'] -= coins_to_take
if dice_roll >= 4:
if verbose: print(f"\tPlayer must put one coin into the pot.")
# Check if current player has lost the game
if GameState[player] == 0:
GameState['game_over'] = True
GameState['loser'] = player
if verbose or print_end_state:
print("\n\nEND OF GAME")
print(f"Player {player} has no coins to put into the pot. They lose. :)")
print(f"Game ended on cycle number {GameState['cycle_number']}")
print(f"Final game state is {GameState}.\n\n")
return GameState['cycle_number']
# If player didn't lose, update game state
GameState[player] -= 1
GameState['pot'] += 1
# Validation - check that no coins were lost in the code or fell under the game table
# NO CHEATING
assert total_coins == GameState['A'] + GameState['B'] + GameState['pot']
# Print info about what the dice roll made happen
if verbose: print(f"\tPlayer {player} now has {GameState[player]} coins "
f"and the pot now has {GameState['pot']} coins.")
return GameState['cycle_number']
def play_game(verbose=False, print_end_state=False):
'''Plays the game once.
verbose - If True, run all print statements.
print_end_state - If true, print final results of the game to
the terminal. (verbose=True overrides false values)
'''
if verbose: print("\nSTARTING GAME SIMULATION")
# Define initial game state - number of coins in each category
global GameState
GameState = {'A': 4, 'B': 4, 'pot': 2, 'cycle_number': 0,
'game_over': False, 'loser': '?'}
# Calculate total coins in the system for validation
global total_coins
total_coins = GameState['A'] + GameState['B'] + GameState['pot']
# Start taking turns, and never stop until loss condition in take_turn function is reached!
while GameState['game_over'] == False:
if verbose: print(f"\nCYCLE NUMBER: {GameState['cycle_number']}")
if verbose: print(f"\nCurrent Game State is {GameState}\n")
take_turn('A', verbose, print_end_state)
if verbose: print(f"\nCurrent Game State is {GameState}\n")
if not GameState['game_over']: take_turn('B', verbose, print_end_state)
# Update turn number
GameState['cycle_number'] += 1
return (GameState['cycle_number'], GameState['loser'])
def repeat_game(n=10000, verbose=False, print_end_state=True, make_charts=True):
'''Repeats the game many time (i.e. performs a Monte Carlo Simulation
to determine the most likely range of possible game outcomes.
n - Number of games to play in the simulation.
verbose - If True, run all print statements.
print_end_state - If true, print final results of the game to
the terminal. (verbose=True overrides false values)
'''
#List of cycles per game
cycles = []
losers = {'A': 0, 'B': 0}
#Loop to play the game
for i in range(n):
cycles_in_game, who_lost = play_game(verbose=verbose, print_end_state=False)
cycles.append(cycles_in_game)
losers[who_lost] +=1
if verbose: print(cycles)
# Find the average of the cycle lengths
if verbose or print_end_state:
avg_num_cycles = round(sum(cycles)/len(cycles),2)
print(f"\n{n} games were played in this simulation")
print(f"The mean number of cycles is {avg_num_cycles}")
print(f"The median number of cycles is {statistics.median(cycles)}")
print(f"The mode of the number of cycles is {statistics.mode(cycles)}")
print(f"The standard deviation of the number of cycles is {round(statistics.stdev(cycles), 2)}")
#Just for an idea of the size of the histogram, here's the min and max
min_cycles = min(cycles)
print(f"The min number of cycles is {min_cycles}")
max_cycles = max(cycles)
print(f"The max number of cycles is {max_cycles}")
print(f"Player A lost {losers['A']} games and Player B lost {losers['B']} games\n")
print(f"Justin Bieber rocks! =P")
#Plot a histogram of the cycle lengths
if make_charts:
x_tick_spacing = 10
binwidth = 2
_ = plt.hist(cycles, bins=range(0, max(cycles) + binwidth, binwidth),
edgecolor='black', linewidth=0.5)
plt.title(f"Histogram of Cycle Lengths over {n} games")
plt.xticks(range(0, max(cycles)+1, x_tick_spacing))
plt.xlabel("Number of cycles in a game")
plt.ylabel("Number of games")
plt.show()
return
# Command Line Application to control the game simulation
def cli():
'''Defines logic for command line interface and kicks off simulation based on passed in arguments.'''
# Initialize CLI
parser= argparse.ArgumentParser(description="Use this tool to simulate playing \"The Game\". For miniproject 1.")
# Command line options are defined here
parser.add_argument('sim_mode', action='store', choices=['single', 'multi'],
help='Either single or multi mode. Single runs a single game. '
'multi runs a lot of games.')
parser.add_argument('-v', '--verbose', action='store_true',
default=False, help="If this flag is set, run command in verbose mode "
"and print lots more output to the terminal.")
parser.add_argument('-r', '--random-seed', action='store', default=None,
help='Set random seed for pseudo random number generator in simulation. '
'If this is not set, it will just use the default seed (i.e. system time).')
parser.add_argument('-n', action='store', type=int, default=10000,
help='Number of games to play if running in multi sim-mode.')
parser.add_argument('--no-charts', action='store_true',
help='Set this flag to disable histogram generation when running in multi sim-mode.')
# Extract command line arguments and execute program based on them
args = parser.parse_args()
verbose = args.verbose
if verbose: print(f"Input arguments passed in are {args}.")
# Set seed
seed = args.random_seed
if seed is None:
if verbose: print(f"No user seed provided, so using default seed (i.e. system time)")
random.seed()
else:
# import seed from command line tool
if verbose: print(f"Seed passed into function is {seed}")
random.seed(seed)
# Run different functions depending on the simulation mode
if args.sim_mode == 'single':
play_game(verbose=verbose, print_end_state=True)
elif args.sim_mode == 'multi':
n = args.n
charts = not args.no_charts
repeat_game(n=n, verbose=verbose, print_end_state=True, make_charts=charts)
return
# This is a pretty standard piece of boilerplate python.
# It only runs the program if this script is executed
# as the main program (vs something else)
if __name__ == "__main__":
cli()
|
# Copyright (c) 2021 www.SyedAdnan.com
# Title: Function to calculate max profit from stock prices
# Purpose: Coding exercies for Latitude
# Author: Syed Adnan
# Date: 26 Sep, 2021
def get_max_profit(prices):
"""Accept stock prices and return max profit after evaluation
Parameters
----------
prices : list
Stock prices from yesterday as list of integers
Returns
-------
int
An integer value of the max profit
"""
# Validate if prices are passed
if len(prices)==0 or len(prices) < 2:
return 0
# Validate if all prices are integer
if not check_integer_prices(prices):
return 0
# Get stock buying and selling values from start of the day.
max_profit = prices[1] - prices[0]
low = prices[0]
# Iterating the prices values to evaluate
for i in prices:
# Skip the first price in list
if prices[0] == i:
continue
potential_profit = i - low
max_profit= max(max_profit, potential_profit)
low = min(low, i)
# Returning the max_profit value
return max_profit
def check_integer_prices(prices):
"""Validate if all stock prices values are integer
Parameters
----------
prices : list
Stock prices from yesterday as list
Returns
-------
Boolean
True if all values are int, else False
"""
return True if all(isinstance(x, int) for x in prices) else False
|
"""
You are given an array of integers representing coordinates of obstacles situated on a straight line.
Assume that you are jumping from the point with coordinate 0 to the right. You are allowed only to make jumps of the same length represented by some integer.
Find the minimal length of the jump enough to avoid all the obstacles.
Example
For inputArray = [5, 3, 6, 7, 9], the output should be
avoidObstacles(inputArray) = 4.
Check out the image below for better understanding:
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.integer inputArray
Non-empty array of positive integers.
Guaranteed constraints:
2 ≤ inputArray.length ≤ 1000,
1 ≤ inputArray[i] ≤ 1000.
[output] integer
The desired length.
"""
def avoidObstacles(inputArray):
sequence_table = {key1:[key1*key2 for key2 in range(1, 1000)] for key1 in range(1, 10)}
inputArray = sorted(inputArray)
options = []
for k, v in sequence_table.items():
check = any(item in v for item in inputArray)
if check == False:
options.append(k)
return options[0]
def avoidObstacles(inputArray):
# sort the list in ascending order
obs = sorted(inputArray)
# set jump distance to 1
jump_dist = 1
# flag to check if current jump distance
# hits an obstacle
obstacle_hit = True
while(obstacle_hit):
obstacle_hit = False
jump_dist += 1
# checking if jumping with current length
# hits an obstacle
for i in range(0, len(obs)):
if obs[i] % jump_dist == 0:
# if obstacle is hit repeat process
# after increasing jump distance
obstacle_hit = True
break
return jump_dist
# inputArray = [5, 3, 6, 7, 9] # 4
# inputArray = [2, 3] # 4
# inputArray = [1, 4, 10, 6, 2] # 7
inputArray = [1000, 999] # 6
# inputArray = [19, 32, 11, 23] # 3
# inputArray = [5, 8, 9, 13, 14] # 6
print(avoidObstacles(inputArray))
|
"""
Two arrays are called similar if one can be obtained from another by swapping at most one pair of elements in one of the arrays.
Given two arrays a and b, check whether they are similar.
Example
For a = [1, 2, 3] and b = [1, 2, 3], the output should be
areSimilar(a, b) = true.
The arrays are equal, no need to swap any elements.
For a = [1, 2, 3] and b = [2, 1, 3], the output should be
areSimilar(a, b) = true.
We can obtain b from a by swapping 2 and 1 in b.
For a = [1, 2, 2] and b = [2, 1, 1], the output should be
areSimilar(a, b) = false.
Any swap of any two elements either in a or in b won't make a and b equal.
Input/Output
[execution time limit] 4 seconds (py3)
[input] array.integer a
Array of integers.
Guaranteed constraints:
3 ≤ a.length ≤ 105,
1 ≤ a[i] ≤ 1000.
[input] array.integer b
Array of integers of the same length as a.
Guaranteed constraints:
b.length = a.length,
1 ≤ b[i] ≤ 1000.
[output] boolean
true if a and b are similar, false otherwise.
"""
def areSimilar(a, b):
return sorted(a) == sorted(b) and sum([i != j for i, j in zip(a, b)]) <=2
from collections import Counter as C
def areSimilar(A, B):
return C(A) == C(B) and sum(a != b for a, b in zip(A, B)) < 3
# A = [1, 2, 2]
# B = [2, 1, 1]
# areSimilar(A, B)
A = [1, 2, 3]
B = [2, 1, 3]
areSimilar(A, B)
|
"""
Given a year, return the century it is in. The first century spans from the year 1 up to and including
the year 100, the second - from the year 101 up to and including the year 200, etc.
Example
For year = 1905, the output should be
centuryFromYear(year) = 20;
For year = 1700, the output should be
centuryFromYear(year) = 17.
Input/Output
[execution time limit] 4 seconds (py3)
[input] integer year
A positive integer, designating the year.
Guaranteed constraints:
1 ≤ year ≤ 2005.
[output] integer
The number of the century the year is in.
"""
def century(year):
century = 0
remainder = year % 100
if remainder >=1:
century = year // 100 + 1
else:
century = year // 100
return century
def century(year):
return (year + 99) // 100
|
def newfunct(start, end, step):
while start <= end:
if start % 3 == 0 and start % 5 == 0:
print("FizzBuzz")
elif start % 3 == 0:
print("Buzz")
elif start % 5 == 0:
print("Fizz")
else:
print(start)
start = start + step
|
print('Введите значения переменных типа int: ')
a = int(input())
b = int(input())
print('Вы ввели числа :',a,'и',b)
summ = a + b
minus = a - b
mltplctn = a * b
share = a / b
print('Сумма веденных числе равна :',summ )
print('Разность веденных числе равна :',minus )
print('Произведение веденных числе равно :',mltplctn )
print('Частное веденных числе равно :',share )
|
__author__ = 'steve1281'
import collections
MyDQ = collections.deque("abcdef",10)
print("Starting state:")
for i in MyDQ:
print(i, end=' ')
print()
print('Appending and extending right')
MyDQ.append('h')
MyDQ.extend('ij')
for i in MyDQ:
print(i, end=' ')
print()
print('MyDQ contains {0} items.'.format(len(MyDQ)))
print('Popping right')
print('Popping {0}'.format(MyDQ.pop()))
for i in MyDQ:
print(i, end=' ')
print()
print('Appending and extending left')
MyDQ.appendleft('a')
MyDQ.extendleft('bc')
for i in MyDQ:
print(i, end=' ')
print()
print('MyDQ contains {0} items.'.format(len(MyDQ)))
print('Popping Left')
print('Popping {0}'.format(MyDQ.popleft()))
for i in MyDQ:
print(i, end=' ')
print()
print('Removing')
MyDQ.remove('a')
for i in MyDQ:
print(i, end=' ')
print()
|
__author__ = 'steve1281'
meal = ""
print("1. Eggs")
print("2. Pancakes")
print("3. Waffles")
print("4. Oatmeal")
mainChoice = int(input("Choose a breakfast item: "))
if (mainChoice == 2) :
meal = "Pancakes"
elif (mainChoice == 3):
meal = "Waffles"
if (mainChoice == 1):
print("1. Wheat Toast")
print("2. Sour Dough")
print("3. Rye Toast")
print("4. Pancakes")
bread = int(input('Choose a type of bread: '))
if (bread == 1) :
print("You chose eggs with wheat toast.")
elif (bread == 2) :
print("You chose eggs with sour dough.")
elif (bread == 3) :
print("You chose eggs with rye toast.")
elif (bread == 4) :
print("You chose eggs with pancakes.")
else :
print("We have eggs, but not that kind of bread.")
elif (mainChoice == 2) or (mainChoice == 3):
print("1. Syrup")
print("2. Strawberries")
print("3. Powdered Sugar")
topping = int(input("Choose a topping: "))
if (topping == 1):
print ("You chose "+ meal + " with syrup" )
elif (topping == 2) :
print("You chose "+ meal + " with strawberries")
elif (topping == 3) :
print("You chose "+ meal + " with powdered sugar")
else:
print("We have " + meal + ", but not that topping.")
elif (mainChoice == 4):
print ("You chose oatmeal.")
else :
print("We don't serve that breakfast item!")
|
__author__ = 'steve1281'
Colors = ["Red","Orange","Yellow","Green","Blue",]
ColorSelect = ""
while str.upper(ColorSelect) != "QUIT":
ColorSelect = input("Please enter a color name: ")
if (Colors.count(ColorSelect) >= 1):
print("The color exists in the list!")
elif (str.upper(ColorSelect) != "QUIT"):
print("The color ",ColorSelect," does not exist in the list.")
|
# list = ["bike","bike","cricket","travel bag",2,"drawers","bed","suitcase"]
#
# print (list)
#
# # length of a list
# print(len(list))
# #get the first item in a list
# print (list[0])
# # add an item in a list
# list.append("bed")
# print (list)
# #remove an item from a list
# list.remove('bed')
# print("after remove",list)
# # count items in a list
# print ("counted bike",list.count("bike"))
myNumbers = [3,4,7,1,1]
# # find the minimum and maximum numbers in a list
# print(max(myNumbers))
# print (min(myNumbers))
greatest = 0
for i in myNumbers:
if i > greatest:
greatest = i
print ("our greatest number is ",greatest)
# clear the whole list
myNumbers.clear()
print(myNumbers)
#ASSIGNMENT: use an if statement and a for loop to find the smallest number in a list.
|
# Data types
# boolean
# integer float
# String
# List
# Dictionary
# Tuple
a = 6
b = "5"
print (type(b))
# type casting is changing one variable to another
b = int(b)
a = str(a)
print (type(b))
print (type(a))
|
#!/usr/bin/env python
"""
基于双端链表 实现的 双端队列 时间复杂度 增删 O(1),查询 O(n);空间复杂度 O(n)
"""
class deq():
def __init__(self, value):
self.va = value
self.prior = self
self.next = self
class MyCircularDeque(object):
def __init__(self, k):
"""
Initialize your data structure here. Set the size of the deque to be k.
:type k: int
"""
self.head = deq(-1)
self.tail = deq(-1)
self.head.next = self.tail
self.head.prior = self.tail
self.tail.prior = self.head
self.tail.next = self.head
self.size = 0
self.capacity = k
def insertFront(self, value):
"""
Adds an value at the front of Deque. Return true if the operation is successful.
:type value: int
:rtype: bool
"""
if self.size < self.capacity:
item = deq(value)
item.next = self.head.next
item.prior = self.head
self.head.next.prior = item
self.head.next = item
self.size += 1
return True
else:
return False
def insertLast(self, value):
"""
Adds an value at the rear of Deque. Return true if the operation is successful.
:type value: int
:rtype: bool
"""
if self.size < self.capacity:
item = deq(value)
item.prior = self.tail.prior
item.next = self.tail
self.tail.prior.next = item
self.tail.prior = item
self.size += 1
return True
else:
return False
def deleteFront(self):
"""
Deletes an value from the front of Deque. Return true if the operation is successful.
:rtype: bool
"""
if self.size > 0:
self.head.next = self.head.next.next
self.head.next.prior = self.head
self.size -= 1
return True
else:
return False
def deleteLast(self):
"""
Deletes an value from the rear of Deque. Return true if the operation is successful.
:rtype: bool
"""
if self.size > 0:
self.tail.prior = self.tail.prior.prior
self.tail.prior.next = self.tail
self.size -= 1
return True
else:
return False
def getFront(self):
"""
Get the front value from the deque.
:rtype: int
"""
if self.size > 0:
return self.head.next.va
else:
return -1
def getRear(self):
"""
Get the last value from the deque.
:rtype: int
"""
if self.size > 0:
return self.tail.prior.va
else:
return -1
def isEmpty(self):
"""
Checks whether the circular deque is empty or not.
:rtype: bool
"""
return self.size == 0
def isFull(self):
"""
Checks whether the circular deque is full or not.
:rtype: bool
"""
return self.size == self.capacity
# Your MyCircularDeque object will be instantiated and called as such:
# obj = MyCircularDeque(3)
# print(True)
# print(obj.insertFront(1))
# print(obj.insertLast(2))
# print(obj.insertFront(3))
# print(obj.insertFront(4))
# print(obj.getRear())
# print(obj.isFull())
# print(obj.deleteLast())
# print(obj.insertFront(4))
# print(obj.getFront())
|
'''
2
3 问题简述:一只小猴子吃桃子的问题。
4 话说,一只小猴子第一天摘下若干个桃子,并吃了一半。
5 感觉到吃的还不瘾,于是又多吃了一个;
6 第二天早上,又将剩下的桃子吃掉一半,又多吃了一个。
7 以后每天早上,都吃了前一天剩下的一半零一个。
8 python问题:
9 请问,到了第10天早上想再吃时,却发现只剩下一个桃子了。
10 求第一天共摘了多少?
11
12 # 逆向思维
13 s2 = 1
14 for day in range(9,0,-1):
15 s1 = (s2 + 1)*2
16 s2 = s1
17 print(s1)
18 '''
# no 1
def foo(n=10, a=1): # n = 10 是因为 当n = 2的时候已经是答案了,但是此时的 获取不到a 要等 n==1 的时候去获取a
if n == 1:
return a
a = (a + 1) * 2
return foo(n-1, a)
print((foo(10))) # 1534
# no 2 n只是一个循环条件
def foo(n=10):
if n == 1:
return 1
return (foo(n-1) + 1) * 2
print(foo())
def foo(n=1):
if n == 10:
return 1
return (foo(n+1) + 1) * 2
print(foo())
|
def setInterval(s,f,b):
n = len(s)
A = []
A.append(b[0])
k = 1
for i in range(2,n):
if s[i] >= f[k] :
A.append(b[i])
k = i
#print A
print "Enter Number of elements"
n = input()
MAX = 100000000
from random import randint
s = []
f = []
k = []
for i in range(0,n):
x,y = [randint(0,MAX-1),randint(0,MAX-1)] #[int(x) for x in raw_input().strip().split()]
s.append(x)
f.append(y)
k.append([x,y])
from time import time
t0 = time()
#print k
f.sort()
setInterval(s,f,k)
t1 = time()
print "Total Execution time :: ",(t1-t0)
|
def multiply(a,b):
if(a<10 or b<10):
return (a*b)
x=str(a)
y=str(b)
lenA=len(x)
lenB=len(y)
xUHalf = int(x[0:(lenA/2)])
yUHalf = int(y[0:(lenB/2)])
xLHalf = int(x[(lenA/2):])
yLHalf = int(y[(lenB/2):])
p0=multiply(xUHalf,yUHalf)
p1=multiply(xLHalf,yLHalf)
p2=multiply(xLHalf+xUHalf,yLHalf+yUHalf) - p0 -p1
return (p0*(pow(10,lenA))) + (p2*pow(10,lenA/2)) + p1
print "Enter numbers"
a=input()
b=input()
lenA = len(str(a))
from time import time
t0 = time()
if a>b:
print "Result of multiplication is :: ",multiply(a,b)
else:
print "Result of multiplication is :: ",multiply(b,a)
t1 = time()
print "Total Execution time :: ",round(t1-t0,3),"For ",lenA," digits"
|
S = input()
count = 0
longest = 0
for l in S:
if l in ['A', 'C', 'G', 'T']:
count += 1
else:
if count > longest:
longest = count
count = 0
print(longest)
|
from math import sqrt, floor
def is_prime(n):
if n < 2: return False
if n == 2: return True
if n % 2 == 0: return False
for i in range(3, floor(sqrt(n))+1, 2):
if n % i == 0: return False
return True
val = (lambda x: x if x % 2 != 0 or x == 2 else x + 1)(int(input()))
for i in range(val, val * 2 + 1):
if is_prime(i):
print(i)
exit()
|
import math
minutes = []
for _ in range(5):
minutes.append(int(input()))
minutes.sort(reverse = True, key = lambda x: x % 10 if x % 10 != 0 else 10)
x = 0
for minute in minutes:
x = math.ceil(x / 10) * 10
x += minute
print(x)
|
heights = []
for i in range(10): heights.append(int(input()))
heights.sort(reverse=True)
for i in range(3): print(heights[i])
|
i = input()
print("yes" if len(set(i)) == len(i) else "no")
|
s = input()
p = int(s[:2])
a = int(s[2:])
if 0 < p < 13 and 0 < a < 13:
print("AMBIGUOUS")
elif 0 < p < 13 and 0 <= a < 100:
print("MMYY")
elif 0 <= p < 100 and 0 < a < 13:
print("YYMM")
else:
print("NA")
|
from math import sqrt, floor
n = int(input())
for i in range(floor(sqrt(n)), 0, -1):
if n % i == 0:
j = n // i
print(i+j-2)
exit()
|
from math import atan, degrees
a,b,x = map(int,input().split())
o = 2 * x / (a*a) - b
if o < 0:
h = 2 * (x / a) / b
print(degrees(atan(b/h)))
else:
print(degrees(atan((b-o)/a)))
|
from Database import Database
import re
class UserInterface:
def __init__(self):
return None
def printoutinfo(self, **kwargs): # Used Kwargs here to display dictionary infos
for i in kwargs.items():
print(i)
def InteractiveMenu(self):
B = Database()
B.ReadCarbonEmission()
B.ReadTemperature()
B.FillinCO2andTempdata() # Create a default dict that contains both CO2 and Temperature tuples
print('Welcome!\n')
print('This is a program that allows you to select a year where the data from two files')
print('overlap and compares the CO2 emission levels to the temperature for the selected year.\n')
menu = {}
menu['1'] = "Search Temperature data by year."
menu['2'] = "Search Carbon Dioxide data by year."
menu['3'] = "Search year and see if there is Temperature and Carbon Dioxide data overlap."
menu['4'] = "The average of the CO2 emissions."
menu['5'] = "Search a year and see if the CO2 level is above average."
menu['6'] = "Search a year and see if the CO2 level is below average."
menu['7'] = "Displays all the Carbon Dioxide data."
menu['8'] = "Displays all the Temperature data."
menu['9'] = "Displays both the Carbon Dioxide data and temperature data"
menu['0'] = "Exit"
while True:
options = menu.keys()
for entry in sorted(options):
print(entry, menu[entry])
selection = input("Please Select: ")
if selection == '1':
y = []
val = input("Which year or years do you want to search? Press s to stop\n")
while True:
if val == 's' or val == 'S':
break;
if (re.search("[12][089][0-9][0-9]{1}$", val) == None) or (
re.search("\d{4}", val) == None): # Using
# regular expression to check for valid years
print("You entered an invalid year")
y.append(val)
val = input()
B.SearchTemperatureByYear(y)
elif selection == '2':
y = []
val = input("Which year or years do you want to search? Press s to stop\n")
while True:
if val == 's' or val == 'S':
break;
if (re.search("[12][089][0-9][0-9]{1}$", val) == None) or (
re.search("\d{4}", val) == None): # Using regular expression to check for valid years
print("You entered an invalid year")
y.append(val)
val = input()
B.SearchCarbonDioxideByYear(y)
elif selection == '3':
y = []
val = input("Which year or years do you want to search? Press s to stop\n")
while True:
if val == 's' or val == 'S':
break;
if (re.search("[12][089][0-9][0-9]{1}$", val) == None) or (
re.search("\d{4}", val) == None): # Using regular expression to check for valid years
print("You entered an invalid year")
val = input()
y.append(val)
val = input()
B.SearchCarbonDioxideAndTemperatureByYear(y)
elif selection == '4':
print("The average of the CO2 emission is", B.TheAverageCO2emission())
elif selection == '5':
val = input("What year do you want to search?\n")
while (re.search("[12][09][0-9][0-9]{1}$", val) == None) or (
re.search("\d{4}", val) == None): # Using regular expression to check for valid years
print("You entered an invalid year")
val = input()
if B.CheckIfYearIsAboveCO2Average(val) is True:
print("{} is above the CO2 average".format(val))
else:
print("{} is not above the CO2 average".format(val))
elif selection == '6':
val = input("What year or years do you want to search?\n")
while (re.search("[12][09][0-9][0-9]{1}$", val) == None) or (
re.search("\d{4}", val) == None): # Using regular expression to check for valid years
print("You entered an invalid year")
val = input()
if B.CheckIfYearIsBelowCO2Average(val) is True:
print("{} is below the CO2 average".format(val))
else:
print("{} is not below the CO2 average".format(val))
elif selection == '7':
self.printoutinfo(**B.CarbonDioxideDatabase)
elif selection == '8':
self.printoutinfo(**B.TemperatureDatabase)
elif selection == '9':
self.printoutinfo(**B.CO2andTempDatabase)
elif selection == '0':
print("Goodbye")
break
else:
print("Unknown Option Selected!\n")
|
n = abs(int(input("Введите целое положительное число, например 10, 20, 30")))
max = n % 10
while n >= 1:
n = n // 10
if n % 10 > max:
max = n % 10
if n >= 9:
continue
else:
print("Максимальная цифра в числе", max)
break
|
import os
# Functions in this file converts the dataset which is in text csv format into
# a list of Python dictionaries.
DATADIR = ""
DATAFILE = "TrainingData.txt"
def parse_file(datafile):
'''
This function converts the dataset(comprising of information regarding
around 2000 films) in csv format to a list of python dictionaries.
'''
data = []
with open(datafile, "rb") as f:
header = f.readline().split(",")
# The header variable is a list which stores the names of the keys
# in our output list of dictionaries.
# The first line in the database is the names of the featues separated
# by commas. ie a python string.
# Calling split on this string with delimiter comma(",") returns the
# names of the features as a list
counter = 0
for line in f:
if counter == 1050:
break
fields = line.split()
# The values themselves are separated by spaces in the dataset.
# Space is the default argument for the split method. So there is no
# need to provide the parameter here.
# Now the values of the attributes for a single film is stored as a
# list in the fields variable
entry = {}
for i, value in enumerate(fields):
entry[header[i].strip()] = value.strip()
# Strip method removes the unnecessary whitespaces from the
# the beginning and end of a string.
# This for loop populates the list of dictionaries,
# by assigning the appropriate values
data.append(entry)
counter += 1
return data
#------------------------------------------------------------- def getMeanDic():
#------------------------------------------------------------ filmDic=test()
#------------------------------------------------------ for film in filmDic:
#----------------------------------------------------- for feat in film:
def test():
# The test function is the driver program.
# This runs the parse_file method on our input dataset
# by calling it with the proper arguments.
datafile = os.path.join(DATADIR, DATAFILE)
d = parse_file(datafile)
return d
test()
def featureMean():
filmDic = test()
meanDic = {'tomatoUserRating': '3.4', 'tomatoReviews': '160', 'tomatoUserReviews': '285130', 'tomatoRotten': '51', 'tomatoMeter': '68', 'Metascore': '62', 'BoxOffice': '92900000.0', 'Year': '2000', 'tomatoFresh': '109', 'imdbRating': '7.2', 'imdbVotes': '192547'}
for item in meanDic:
total = 0
count = 0
for film in filmDic:
if(film[item] != 'N/A'):
count += 1
total += float(film[item])
meanDic[item] = int(total / count)
return meanDic
def filler():
filmDic = test()
meanDic = featureMean()
for item in meanDic:
for film in filmDic:
if(film[item] == 'N/A'):
film[item] = meanDic[item]
return filmDic
def nullcheck():
filmDic = filler()
# items=featureMean()
count = 0
for film in filmDic:
for feature in film:
if(film[feature] == 'N/A'):
count += 1
return count
|
import math
operator = "+-*/"
def add(s1, s2):
result = ""
if len(s1) > len(s2):
s1,s2 = s2,s1
diff = len(s2) - len(s1)
carry = 0
for i in range(len(s1) - 1, -1, -1):
temp = int(s1[i]) + int(s2[i + diff]) + carry
result += str(temp % 10)
carry = temp // 10
for i in range(len(s2) - len(s1) - 1, -1, -1):
temp = int(s2[i]) + carry
result += str(temp % 10)
carry = temp // 10
if carry:
result += str(carry)
return result[::-1]
def isSmaller(s1, s2):
if len(s1) > len(s2):
return False
elif len(s1) < len(s2):
return True
for i in range(len(s1)):
if s1[i] > s2[i]:
return False
elif s1[i] < s2[i]:
return True
return False
def sub(s1, s2):
result = ""
sign = ""
if isSmaller(s1, s2):
s1,s2 = s2,s1
sign = "-"
diff = len(s1) - len(s2)
carry = 0
for i in range(len(s2) - 1, -1, -1):
temp = int(s1[i + diff]) - int(s2[i]) - carry
if temp < 0:
temp += 10
carry = 1
else:
carry = 0
result += str(temp)
# print result
for i in range(len(s1) - len(s2) - 1, -1, -1):
if s1[i] == '0' and carry:
result += '9'
continue
temp = int(s1[i]) - carry
if temp > 0 or i > 0:
result += str(temp)
carry = 0
result = result[::-1].lstrip('0')
if result == "":
result = '0'
return sign + result
def mul(s1, s2):
if len(s1) == 0 or len(s2) == 0:
return 0
result = [0] * (len(s1) + len(s2)) # maximum possible digits
i_1 = 0
for i in range(len(s1) - 1, -1, -1):
carry = 0
i_2 = 0
num_1 = int(s1[i])
for j in range(len(s2) - 1, -1, -1):
num_2 = int(s2[j])
temp = num_1 * num_2 + result[i_1 + i_2] + carry
carry = temp // 10
result[i_1 + i_2] = temp % 10
i_2 += 1
if carry:
result[i_1 + i_2] += carry
i_1 += 1
i = len(result) - 1
while i >= 0 and result[i] == 0:
i -= 1
if i == -1:
return "0"
r = ""
while i >= 0:
r += str(result[i])
i -= 1
return r
def div(s1, s2):
result = ""
i = 0
temp_1 = int(s1[i])
divisor = int(s2)
while temp_1 < divisor:
if i == len(s1) -1:
break
temp_1 = temp_1 * 10 + int(s1[i + 1])
i += 1
i += 1
while len(s1) > i:
result += str(int(math.floor(temp_1 // divisor)))
temp_1 = (temp_1 % divisor) * 10 + int(s1[i])
i += 1
result += str(int(math.floor(temp_1 // divisor)))
if len(result) == 0:
return "0"
return result
def total(st):
result = st[0]
for i in st[1:]:
if i[0] == "-" and result[0] == "-":
result = "-" + add(result[1:], i[1:])
elif i[0] == "-":
result = sub(result, i[1:])
elif result[0] == "-":
result = sub(i, result[1:])
else:
result = add(result, i)
return result
def calculate(exp):
if len(exp) == 0:
return 0
stack = []
sign = '+'
result = ""
while len(exp) > 0:
ch = exp.pop(0)
if ch.isdigit():
result += ch # to accomodate number > 1 digit
if ch == '(':
result = calculate(exp) # prioritize to calculate inside parenthesis
if len(exp) == 0 or ch in operator or ch == ')':
if sign == '+':
stack.append(result)
elif sign == '-':
if result[0] == "-":
stack.append(result[1:])
else:
stack.append("-"+result)
elif sign == '*':
if stack[-1][0] == '-' and result[0] == "-":
stack[-1] = mul(stack[-1][1:], result[1:])
elif stack[-1][0] == "-":
stack[-1] = "-" + mul(stack[-1][1:], result)
elif result[0] == "-":
stack[-1] = "-" + mul(stack[-1], result[1:])
else:
stack[-1] = mul(stack[-1], result)
elif sign == '/':
if stack[-1][0] == '-' and result[0] == "-":
stack[-1] = div(stack[-1][1:], result[1:])
elif stack[-1][0] == "-":
stack[-1] = "-" + div(stack[-1][1:], result)
elif result[0] == "-":
stack[-1] = "-" + div(stack[-1], result[1:])
else:
stack[-1] = div(stack[-1], result)
sign = ch
result = ""
if ch == ')':
break # return immediately to denotes blocks (....) done calculated
return total(stack)
if __name__ == "__main__":
exp = list(raw_input())
print(calculate(exp))
|
from matplotlib import pyplot
from PlotInfo import PlotInfo
from Marker import Marker
from LabelProperties import LabelProperties
class Label(PlotInfo):
"""
Labels a point on the plot with text and/or arrows
"""
def __init__(self, x, y, text=None, bbox=None):
PlotInfo.__init__(self, "label")
self.x = x
"""
The label's x coordinate
"""
self.y = y
"""
The label's y coordinate
"""
self.text = text
"""
The text that should be displayed with the label
"""
self.textX = x
self.textY = y
self.arrow = None
self._marker = Marker()
self._labelProperties = LabelProperties()
if bbox:
self.bbox = dict(bbox)
else:
self.bbox = None
@property
def marker(self):
"""
The marker type that should be used to mark the labeled point
"""
return self._marker.marker
@marker.setter
def marker(self, value):
self._marker.marker = value
@property
def textOffset(self):
return (self.textX - self.x, self.textY - self.y)
@textOffset.setter
def textOffset(self, offset):
if type(offset) not in [tuple, list] or len(offset) != 2:
raise AttributeError, "Expected a two-element tuple when " \
"setting textOffset"
self.setTextOffset(offset[0], offset[1])
def setTextOffset(self, x, y):
self.textX = self.x + x
self.textY = self.y + y
@property
def textPosition(self):
return (self.textX, self.textY)
@textPosition.setter
def textPosition(self, pos):
if type(pos) not in [tuple, list] or len(pos) != 2:
raise AttributeError, "Expected a two-element tuple when " \
"setting textOffset"
self.setTextPosition(pos[0], pos[1])
def setTextPosition(self, x, y):
self.textX = x
self.textY = y
@property
def labelProperties(self):
"""
A dictionary of properties that control the appearance of the label. See
:ref:`styling-labels` for more information on which properties can be
set.
"""
return self._labelProperties
@labelProperties.setter
def labelProperties(self, propsobj):
self.labelProperties.update(propsobj)
@property
def rotation(self):
return self._labelProperties["rotation"]
@rotation.setter
def rotation(self, value):
self._labelProperties["rotation"] = value
def hasArrow(self, style="->", color="black"):
"""
Defines an arrow between the label's text and its point. Valid arrow
styles are given in `Matplotlib's documentation <http://matplotlib.github.com/users/annotations_guide.html?highlight=arrowprops#annotating-with-arrow>`_.
"""
self.arrow = dict(facecolor=color, arrowstyle=style)
def draw(self, fig, axis, transform=None):
kwdict = {}
kwdict["xytext"] = (self.textX, self.textY)
kwdict["xycoords"] = "data"
kwdict["textcoords"] = "data"
kwdict["arrowprops"] = self.arrow
kwdict["horizontalalignment"] = "center"
kwdict.update(self.labelProperties)
# For props, see
# http://matplotlib.sourceforge.net/api/artist_api.html#matplotlib.patches.Rectangle
if self.bbox: kwdict["bbox"] = self.bbox
handles = []
labels = []
handles.append(axis.annotate(self.text, (self.x, self.y), **kwdict))
labels.append(None)
if self.marker is not None:
handles.append(axis.scatter([self.x],[self.y],marker=self.marker,
color="black"))
labels.append(None)
return [handles, labels]
|
import pylab
from matplotlib import pyplot
import os
from boomslang import PlotLayout
from Utils import getGoldenRatioDimensions, _check_min_matplotlib_version
class WeightedPlotLayout(PlotLayout):
"""
A more sophisticated version of :class:`boomslang.PlotLayout.PlotLayout`
that allows some plots to be wider than others.
Like PlotLayout, WeightedPlotLayout allows plots to be grouped together
into named groupings, with one grouping per row. However, it does not have
a fixed width in number of plots to guide layout. Instead, the _weights_ of
the plots in a grouping determine how wide each plot in the grouping
is. Any plot that has no grouping or is the only plot in its grouping will
take up an entire row regardless of its weight.
For example, if there are two plots in a grouping and both plots have
weight 1, they will each take up half the row. If one of the plots has
weight 2 and the other has weight 1, the first plot will take up 2/3 of the
row and the second will take up the remaining 1/3.
"""
def __init__(self):
super(WeightedPlotLayout,self).__init__()
self.groupedWeights = {}
self.weights = []
self.figTitle = None
self.usePlotParams = False # Include plot's parameters in
# computing layout.
def addPlot(self, plot, grouping=None, weight=1):
"""
Add `plot` to the layout, optionally grouping it with all other plots
added to the group `grouping`. `weight` denotes the plot's weight
within its grouping.
"""
super(WeightedPlotLayout,self).addPlot(plot, grouping=grouping)
if grouping not in self.groupedWeights:
self.groupedWeights[grouping] = []
self.groupedWeights[grouping].append(weight)
def setFigTitle(self, title=None):
self.figTitle = title
def _doPlot(self):
if len(self.groupedPlots) + len(self.plots) == 0:
print "WeightedPlotLayout.plot(): No data to plot!"
return
oldRCParams = {}
if self.rcParams is not None:
for (key,val) in self.rcParams.items():
oldRCParams[key] = pylab.rcParams[key]
pylab.rcParams[key] = val
numRows = len(self.groupedPlots.keys()) + len(self.plots)
maxRowLength = max([len(self.groupedPlots[f])
for f in self.groupedPlots.keys()])
if self.groupOrder is not None:
keyList = self.groupOrder
else:
keyList = sorted(self.groupedPlots.keys())
if self.figdimensions is not None:
fig = pyplot.figure(figsize=(self.figdimensions[0],
self.figdimensions[1]))
elif self.dimensions is not None:
fig = pyplot.figure(figsize=(self.dimensions[0] * maxRowLength,
self.dimensions[1] * numRows))
else:
(figWidth, figHeight) = getGoldenRatioDimensions(8.0)
figWidth *= maxRowLength
figHeight *= numRows
fig = pyplot.figure(figsize=(figWidth, figHeight))
plotHandles = []
plotLabels = []
# Force a call to plotParams since we need them here
if self.plotParams is None:
self.setPlotParameters(**dict())
figTop = self.plotParams["top"]
figLeft = self.plotParams["left"]
wspace = self.plotParams["wspace"]
hspace = self.plotParams["hspace"]
height = figTop - self.plotParams["bottom"]
rowHeight = height / (numRows + (numRows - 1) * hspace)
hgap = self.plotParams["hspace"] * rowHeight
rowWidth = self.plotParams["right"] - figLeft
# To contain a list of plots and rects, so we can do the
# information collection in one pass
plotInfo = []
def applyParams(r, pp):
if pp is None: return r
left, bottom, width, height = r
return [
left + width * pp.get('left',0),
bottom + height * pp.get('bottom',0),
width * (pp.get('right',1) - pp.get('left',0)),
height * (pp.get('top',1) - pp.get('bottom',0))
]
# Generate rects for grouped plots
currentRow = 0
for grouping in keyList:
plots = self.groupedPlots[grouping]
weights = self.groupedWeights[grouping]
totalWeight = 1.0 * sum(weights)
numPlots = len(plots)
# hspace, wspace behavior defined in matplotlib/axes.py
# in the class SubplotBase
unitWidth = rowWidth / (numPlots + (numPlots-1) * wspace)
availableWidth = unitWidth * numPlots
wgap = unitWidth * wspace
bottom = figTop - rowHeight - (rowHeight + hgap) * currentRow
left = figLeft
for i in range(0, len(plots)):
plot = plots[i]
myWidth = availableWidth * weights[i] / totalWeight
rect = [left, bottom, myWidth, rowHeight]
if self.usePlotParams and hasattr(plot,'plotParams'):
rect = applyParams(rect, plot.plotParams)
plotInfo.append((plot, rect))
left += myWidth + wgap
currentRow += 1
# Generate rects for ungrouped plots
for plot in self.plots:
bottom = figTop - rowHeight - (rowHeight + hgap) * currentRow
left = figLeft
rect = [left, bottom, rowWidth, rowHeight]
if self.usePlotParams and hasattr(plot,'plotParams'):
rect = applyParams(rect, plot.plotParams)
plotInfo.append((plot, rect))
currentRow += 1
# Plot everything
for (plot, rect) in plotInfo:
ax = fig.add_axes(rect)
(currPlotHandles, currPlotLabels) = plot.drawPlot(fig, ax)
for i in xrange(len(currPlotHandles)):
if currPlotLabels[i] in plotLabels:
continue
if isinstance(currPlotHandles[i], list):
plotHandles.append(currPlotHandles[i][0])
else:
plotHandles.append(currPlotHandles[i])
plotLabels.append(currPlotLabels[i])
if self.figTitle is not None:
fig.suptitle(self.figTitle)
for (key,val) in oldRCParams.items():
pylab.rcParams[key] = val
return fig
|
class BoundedFloat(object):
"""
BoundedFloats behave like floats, but are required to be within
`minimum` (inclusive) and `maximum` (exclusive)
"""
def __init__(self, name, minimum, maximum, default=None):
self.name = name
self.min = float(minimum)
self.max = float(maximum)
if default != None:
if default < self.min or default >= self.max:
raise ValueError("Default value %.2f out-of-bounds [%.2f,%.2f)",
default, self.min, self.max)
self.default = default
def __set__(self, instance, value):
if not isinstance(value, float):
raise TypeError("Value %s not a float", value)
if value >= self.max or value < self.min:
raise ValueError("Value %f out-of-bounds [%.2f, %.2f)", value,
self.min, self.max)
instance.__dict__[self.name] = value
def __get__(self, instance, owner):
if self.name not in instance.__dict__:
if self.default == None:
instance.__dict__[self.name] = self.min
else:
instance.__dict__[self.name] = self.default
return instance.__dict__[self.name]
|
# Python3 code to demonstrate working of
# Group and count similar records
# using Counter() + loop + set()
from collections import Counter
# initialize list
test_list = ['gfg','is', 'best', 'gfg', 'is', 'for', 'geeks']
# printing original list
print("The original list : " + str(test_list))
# Group and count similar records
# using Counter() + loop + set()
res = []
temp = set()
counter = Counter(test_list)
print(counter)
for sub in test_list:
print(sub)
if sub not in temp:
res.append(counter[sub])
temp.add(sub)
print(res)
print(temp)
# # printing result
# print("Grouped and counted list is : " + str(res))
|
def print_as_a_string(age=22, name='Dash'):
print(name + ' ' + str(age))
print_as_a_string()
def number_of_decades_lived(age=32):
print('Number of Decades Lived', age / 10)
number_of_decades_lived(int(input('Enter Your Age: ')))
|
import re
repeat = 30
pattern = "a?" * repeat + "a" * repeat
string = "a" * 2 * repeat
# string = "a" * repeat
print(f'"{pattern}" "{string}"')
ret = re.match(pattern, string)
print(ret[0])
|
#实现输入十个数,求和
'''
b = 0
sum = 0
while b<10:
a = int(input("请输入数字:"))
sum = a+sum
b+=1
print("数字之和为:",sum)
#从键盘依次输入10个数,最后打印最大的数、10个数的和、和平均数。
b = 0
sum = 0
big = 0
while b<10:
a = int(input("请输入数字:"))
sum = a+sum
if a>big:
big = a
b+=1
pingjun=sum/big
print("数字之和为:",sum)
print("最大数值为:",big)
print("平均值为:",pingjun)
#使用random模块,如何产生 50~150之间的数?
import random
num = random.randint(50,150)
print(num)
#从键盘输入任意三边,判断是否能形成三角形,若可以,则判断形成什么三角形(结果判断:等腰,等边,直角,普通,不能形成三角形。)
a=int(input("请输入第一个边长:"))
b=int(input("请输入第二个边长:"))
c=int(input("请输入第三个边长:"))
if a==b==c:
print("等边三角形")
elif a+b>c and b+c>a and a+c>b:
print("普通三角形")
elif a==b or b==c or c==a:
print("等腰三角形")
elif a*a+b*b==c*c or b*b+c*c==a*a or a*a+c*c==b*b:
print("直角三角形")
else:
print("不构成三角形")
#有以下两个数,使用+,-号实现两个数的调换。
a=56
b=78
print("a=",a+22)
print("b=",b-22)
#实现登陆系统的三次密码输入错误锁定功能(用户名:root,密码:admin)
name = 'root'
passwd = 'admin'
a=name
b=passwd
c =0
d =0
e=0
while e<3:
c = input("请输入账号:")
d = input("请输入密码:")
if c == a and d == a:
print("正确")
else:
print("密码错误")
e+=1
print("锁定")
#星号三角形
for i in range(8):
for j in range(0, 10 - i):
print(end=" ")
for k in range(10 - i, 10):
print("*", end=" ")
print("")
#使用while循环实现99乘法表
a=1
b=1
while a<=9:
while b<=a:
print(a,"*",b,"=",a*b)
b += 1
print("\t")
b=0
a+=1
#倒叙99乘法表
a=9
b=9
while a>=1:
while b>=a:
print(a,"*",b,"=",a*b,end="\t")
b -= 1
print()
b=9
a-=1
a =20
sun = 3
moon = 2
day =0
while 1:
a -=sun
if a==0: break
a +=moon
day +=1
print(day)
#判断下列变量命名是否合法 char,Oax_li,fLul,BYTE,Cy%ty,$123,3_3 ,T_T
help("keywords")
#游戏
import random
import time
num = random.randint(0, 10)
gold=0
n=0
asd=20
print("您的初始资金为0")
while 1:
n+=1
a = int(input("请输入一个数字:"))
if num > a:
print("你猜的数字小了")
elif num < a:
print("你猜的数字大了")
elif num==a:
print("你成功了")
print("你猜了",n,"次")
if n<3:
gold+=200
print("游戏结束,您的资金为",gold)
else:
print("资金不加不减")
break
if n==20:
print("您已经猜了20次了系统需要休息一下")
while 1:
time.sleep(1)
print("还有",asd,"秒")
asd-=1
if asd==0:
break
elif n==6:
print("您已经猜了60次了系统锁定")
while 1:
time.sleep(1)'''
|
userinput = input ("Let's party! How long until the party? (Give me a number.) ")
usernum = int(userinput, 10)
if (usernum < 1):
print ("PARTY NOW!!!")
else:
for i in range (usernum, 0, - 1):
print(i)
if (i == 1):
print("PARTY TIME!")
|
"""
1. Given a string, find the longest substring
which is palindrome. For example, if the given
string is "ababad", the output should be "ababa".
"""
"""First thing is to anaylze the problem.
Since it's a palindrome, we know if its backwards
it will be the same forward. So we reverse the string
with the [start:stop:step] index slice parameters
and then compare it to itself and see if it's the same.
In this case I used the [::-1] parameters
so I can start at the VERY beginning and the VERY end
when reversing. If you dont do this you wont be slicing
the whole list since the STOP parameter is where you will
stop and it wont be counted."""
"""string is what we will be taking in so we can have
any test case. palinSave will be the biggest palindrome"""
"""The double for loop allows us to start at the beginning,
check the whole length, and go to the next index and check
the whole length again. My 2nd loop range has a
(len(string),0,-1) in order to reverse it using -1
as a reverse step. Going reverse made more sense to me conceptually"""
def palin():
string=input("Add a string: ")
if len(string)==1 or string=="":
return string
#saves first index so if no palindrome this would pass
palinSave=string[0]
#init
start=0
counter=len(string)
while start< len(string):
#for letter in range(0,len(string))
#for endletter in range(len(string),0,-1)
palinCheck=string[start:counter]
palinCompare=palinCheck[::-1]
if palinCheck==palinCompare:
#Now that we found one, check if its the longest
if len(palinCheck)>len(palinSave):
palinSave=palinCheck
if counter!=start:
counter-=1
else:
counter=len(string)
start+=1
return palinSave
result= palin()
print(result)
"""
2. Given a string str, the task is to print all the
permutations of str. A permutation is an
arrangement of all or part of a set of objects,
with regard to the order of the arrangement.
For example, if given "abb", the output should be
"abb abb bab bba bab bba"
"""
def perms():
from itertools import permutations
string=input()
allperms= list(permutations(string))
#Creates a structure with no duplicates
set_of_all_perms=set(allperms)
for i in allperms:
i="".join(i)
print(i)
"""I just used python's permutations module from the
itertools library because I felt like there wasnt a point
in reinventing the wheel. But, here's what I'd do if I
didnt use the module:
Basically, I'd use shuffle to create the perms but I
wont add them unless they arent in the list.
I'd use the factorial length of the string as my length.
If there are duplicates, Ill cut the size down in half
This runtime is terrible and I prefer my above solution:
"""
def secondSolution (string):
import random
total=1
for num in range(len(string)+1):
if num==0:
continue
else:
total*=num
dupliCheck=dict.fromkeys(string)
if len(string)!=len(dupliCheck) :
total/=2
string= list(string)
perms=[]
random.shuffle(string)
grabber="".join(string)
print(grabber)
perms.append(grabber)
while len(perms)<total:
random.shuffle(string)
grabber="".join(string)
if grabber in perms:
pass
else:
perms.append(grabber)
print(perms)
print(len(perms))
#Way more work :/
|
import binarytree
from binarytree import Node, build
#Creates a mirror of the tree
def mirror():
#Pass in any values to create a tree
values = [7, 3, 2, 6, 9, 1, 5, 8]
if len(values)==1:
print(values)
elif len(values)==0:
print("None")
else:
tree1=build(values)
for i in range(len(tree1)):
try:
temp=tree1[i].left
tree1[i].left=tree1[i].right
tree1[i].right=temp
except:
print("no index")
print(tree1)
#By alternating, we're able to go down the path where the leaf is
def make_branches(leaf,branches,branchess):
for num in range(len(tree1)):
if leaves[leaf] in tree1[num].left:
#adds to branch
branches.append(tree1[num].left)
#checks if we're done with this branch
if tree1[num].left==leaves[leaf]:
branchess.append(branches)
branches=[]
break
elif leaves[leaf] in tree1[num].right:
branches.append(tree1[num].right)
if tree1[num].right==leaves[leaf]:
branchess.append(branches)
branches=[]
break
#This runs the code that recursively creates root to leaf branches
#Pass in any values you'd like
values = [7, 3, 2, 6, 9, 1, 5, 8]
if len(values)==1:
print(values)
elif len(values)==0:
print("None")
else:
tree1=build(values)
branchess=[]
branch=list(tree1)
leaves=tree1.leaves
for leaf in range(len(leaves)):
branches=[tree1[0]]
make_branches(leaf,branches,branchess)
print(branchess)
#MUST RUN BRANCH CREATION FUNCTION FIRST
#finds max difference between node and differences
def max_diff(branchess):
branchess.extend((list(tree1),list(tree1.left),list(tree1.right)))
newBranch=[]
newBranches=[]
#This is to get rid of the new lines and help us retrieve the numeric representation of the nodes
for branch in branchess:
branch=str(branch).strip('\n')
for i in list(branch):
if i.isnumeric():
newBranch.append(int(i))
newBranches.append(newBranch)
newBranch=[]
print(newBranches)
maxDiff=0
#this is to compare the differences between each node and it's decendants
for branchDiff in newBranches:
if maxDiff<(max(branchDiff)-min(branchDiff)):
maxDiff=(max(branchDiff)-min(branchDiff))
print(maxDiff)
|
words = set()
with open('words.txt') as file:
for line in file:
words.add(line.strip())
sentence = input('Enter a sentence and I will spell check every word => ')
set_words = set(sentence.split(' '))
print('Misspelled words: ' + ', '.join(set_words.difference(words)))
|
# -*- coding: utf-8 -*-
"""
Created on Wed May 15 04:30:17 2019
@author: 140524
"""
# factorial program using recursive program
def factorial(num):
if num==0:
return 1
else:
return num*factorial(num-1)
n=int(input("enter your number: "))
factorial(n)
# examples from edureka - functions
def print_name(str1):
return print("welcome to edureka", str1)
n = input("enter your name: ")
print_name(n)
|
# coding: utf-8
# # Functions
####[5]:
import os, sys, json
# Now we are good to get started with functions
####[1]:
def process(file_path):
if os.path.exists(file_path):
rp = open(file_path, 'r')
for line in rp:
print(line)
rp.close()
####[8]:
def add(n1, n2):
return n1+n2 if n1 > n2 else n2-n1
# add(10, 30)
n1 = input('Enter first number : ')
n2 = input('Enter second number : ')
n1 = int(n1)
n2 = int(n2)
add(n1, n2)
####[14]:
def new(a,b):
return b
def third():
print('Hello world!')
new(1,2)
third()
# # Function Arguments
# #### This is fourth level heading
X = 30
def add(a, b):
global X
X = X + 1
c = a + b
#if c > 10:
# print(c)
return c
add(10,20)
print(X)
print(c)
####[10]:
add(3, 4)
####[9]:
add('python', 'anaconda')
####[12]:
add('anaconda', 'python')
# # Built-In Functions
####[6]:
#Python. | dir() function. dir() is a powerful inbuilt function in Python3,
#which returns list of the attributes and methods of any object
#(say functions , modules, strings, lists, dictionaries etc.)
dir()
####[7]:
abs(-10)
####[10]:
sum(20, 30)
####[11]:
sum([20,30,40])
####[34]:
chr(65)
####[35]:
chr(97)
####[14]:
int(12.36)
####[58]:
marks = []
any(marks)
marks = [45, 54, 99, 81, 12, -3]
any(marks)
####[60]:
marks.append(0)
all(marks)
####[61]:
list(reversed([10, 40, 30]))
####[63]:
sorted(marks, reverse=False)
####[20]:
names = ['Python', 'Steve', 'Jobs']
all(names)
####[21]:
for x in reversed([10, 40, 30]):
print(x)
####[14]:
#It allows us to loop over something and have an automatic
#counter.
# when just one var in taken to loop over the iterable with enumerate
#the it prints indivitual tuples
for index in enumerate([10, 20, 30],23):
print(index)
# or
for val in enumerate([10, 20, 30],23):
print(val)
# but when 2 vars are looped over then it prints the following way
for index,val in enumerate([10, 20, 30],23):
print(index,val)
####[65]:
bin(2)
####[16]:
oct(40)
####[37]:
hex(4)
####[38]:
int(hex(4))
####[17]:
v = 0x4
print(v)
####[22]:
oc = 0o77
oc
# # Lambda, map, filter and reduce
####[ ]:
def sq_func(x):
return x**2 if x > 10 else x**3
sq_func(3)
####[42]:
#Python allows you to create anonymous function i.e function having no names
#using a facility called lambda function. lambda functions are small functions usually
#not more than a line. ...
#The result of the expression is the value when the lambda is applied to an argument
sq = lambda x : x**2 if x > 10 else x**3 # def add(x, y)
sq(3)
####[41]:
sq(12)
####[44]:
marks
####[47]:
def categorize_marks(mark):
if mark > 70:
return 'Perfect'
else:
return 'Needs Improvement'
marks = [45, 54, 99, 81, 12, -3]
for mark in marks[:-1]:
print(categorize_marks(mark))
####[57]:
list(map(categorize_marks, marks))
####[48]:
list(map(lambda x: 'Perfect' if x >= 70 else 'Needs Improvement', marks)) # concise way of transforming values
####[49]:
list(filter(lambda x: (x >= 50 and x <= 75) or (x < 10 or x > 80), marks)) # concise way of filtering values
####[50]:
high_marks = []
for x in marks:
if x >= 50:
high_marks.append(x)
print(high_marks)
####[51]:
for x in filter(lambda x: x >= 50, marks):
print(x)
####[30]:
def is_gt_50(mark):
return mark>=50
list(filter(is_gt_50, marks))
####[50]:
#will give range of values range(1,6) as (1,2,3,4,5)
from functools import reduce
reduce((lambda x, y: x+y), range(1,6))
####[ ]:
# 1,2,3,4,5 = (((1*2)*3)*4)*5 => 1*2 (x) 3(y) = x* y = (1*2*3) saved to x (1 * 2 * 3) y (4)
####[67]:
####[42]:
# Generator
def elements(int_input):
for x in range(1, int_input+1):
return x
print('Hello')
def elementss(int_input):
for x in range(1, int_input+1):
print('Hello')
return x
print(elements(5))
print(elementss(5))
# or
def elements(int_input):
i=1
while i<=int_input:
yield i
i=i+1
gen = elements(5)
next(gen)
#--
next(gen)
# and so on
# or
for i in gen:
print(i)
# list(elements(5))
# range(1, 11)
# for value in elements(5):
# print(value)
# # Function arguments - positional, keywords, arbitrary length
####[33]:
# non-default arguments - specify value for every argument
# default arguments - default to value specified
# positional notation - passing and defining arguments
# keyword notation - passing and defining arguments
def fun1(a,b,c,d=60):
print(a,b,c)
print(d)
# fun1(10, 20, 30) # positional
#fun1(10, 20, 30,40)
# fun1(a=10,c=20,b=45) # keyword notation
#fun1(a=10, c=30, b=20, d=40, e=50)
#Arbitrary
def greet(*names):
"""This function greets all
the person in the names tuple."""
# names is a tuple with arguments
for name in names:
print("Hello",name)
greet("Monica","Luke","Steve","John")
# **Python Function - Variable Length Arguments with *args
# Keyword arguments and **kwargs
def bar(first, second, third, **options):
if options.get("action") == "sum":
print("The sum is: %d" %(first + second + third))
if options.get("number") == "first":
return first
result = bar(1, 2, 3, action = "sum", number = "first")
print("Result: %d" %(result))
def fun(a,b,c,d=60,*p,**kwargs):
print(a,b,c)
print(p)
print(d)
print(kwargs)
# fun(10, 20, 30) # positional
# fun(a=10,c=20,b=45) # keyword notation
fun(a=10, c=30, b=20, d=40, e=50)
# fun(10, 20)
def myFunction(arg1, arg2, arg3, *args, **kwargs):
print ('First Normal Argument : ' + str(arg1))
print ('Second Normal Argument : ' + str(arg2))
print ('Third Normal Argument : ' + str(arg3))
print ('Non-keyworded Argument : ' + str(args))
print ('Keyworded Argument : ' + str(kwargs))
myFunction(1, 2, 3, 4, 5, 6, 7, name='Mandar', country='India', age=25)
#Keyworded Argument : {'country': 'India', 'age': 25, 'name': 'Mandar'}
####[30]:
def pass_the_world(*c):
print(type(c), c)
pass_the_world()
pass_the_world(10,20,30,40,*list(range(10)))
###########################################################################
####[38]:
# non-default arguments
# default arguments
# positional notation - passing and defining arguments
# keyword notation - passing and defining arguments
def format_name(fname, lname, mname=None, reverse=True):
print(type(fname), type(lname), type(reverse))
if reverse:
return lname + ' ' + fname
else:
return fname + ' ' + lname
# print(format_name('Python', 'Spark'))
# oracle : username, password, tnsname
# mysql: username, password, host, port, ssl-key, ssl-ca, ssl-cert
def connect(db_type, **kwargs):
oracle_template = 'jdbc:client:://{username}:{password}/{tnsname}/{host}/{port}'
if db_type == 'Oracle':
cxn_str = oracle_template.format(**kwargs) # 'jdbc:client:://{username}:{password}/{tnsname}
print(cxn_str)
elif db_type =="mysql":
cxn_str = oracle_template.format(**kwargs) # 'jdbc:mysql://hist:port/username/password/sslc/sslk'
print(cxn_str)
def add_marks(standard, names=None, **marks):
return sum(marks)
def master(ndf1, ndf2, df1=2, df2=3, d=3, *args, **kwargs):
print(ndf1, ndf2, df1, df2)
print(type(args))
print(type(kwargs))
print(args)
print(kwargs)
master(10, 20, df1=30, k=10, v=20, d=30, p=50)
print(add_marks('Xth', marks=[10, 20, 30, 40, 90, 100, 45, 54]))
# connect('mysql', username='Python', password='Anaconda', tnsname='Disaster', host='cloudserver', port='3306')
####[59]:
def flexi(*args):
print(type(args))
print(args)
# flexi()
flexi(10,20,30)
# flexi(10)
####[63]:
def afun(a,b,c=100,*args):
print(a,b,c)
print(args)
print(a+b+c+sum(args))
print('------')
# afun(10,20)
# afun(10,20,30)
afun(10,20,30,40,50,63,75,81,0,12)
####[65]:
def afun(a,b,c=45,*args,**kwargs):
print(a,b,c)
print(args)
print(kwargs)
print('------')
# afun(10,20)
# afun(10,20,30)
# afun(10,20,30,40,50,63,75,81,0,12)
afun(10,20,30,40,50,63,75,81,0,12,d=40,e=50,f=60)
# # Classes
####[1]:
class Number():
pass
x = Number
y = Number()
print(x)
print(y)
##############
# File one.py
def func():
print("func() in one.py")
print("top-level in one.py")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py is being imported into another module")
####[25]:
class EdurekaCustomer(object):
'''
This class is used to represent Edureka Customer.
'''
DEFAULT_DISC = '3%'
DISC_STRATEGY = lambda age: '20%' if age <= 40 else '15%'
def __get_default_pwd(cls):
import random, string
return ''.join([random.choice(string.ascii_letters + string.digits) for x in range(10)])
def __init__(self, name, email, phone, age, userid):
print('Inside constructor')
self.name = name
self.email = email
self.phone = phone
self._age = age
self.userid = userid
self.__pwd = self.__get_default_pwd()
@property
def hashed_pwd(self):
import base64
return base64.b64encode(self.__pwd.encode())
def set_phone(self, val):
self.phone = phone
def get_phone(self):
return self.phone
def set_pwd(self, pwd):
self.__pwd = pwd # base64
@classmethod # decorator
def owned_by_class(cls, arg1):
print(cls.DISC_STRATEGY(30))
print(arg1)
cls.i_am_static('called from owned_by_class')
def available_discount(self, wealthy_customer=False):
if not wealthy_customer:
self.i_am_static('called from available_discount')
return self.DISC_STRATEGY(self.age)
else:
return self.DEFAULT_DISC
def __del__(self):
print('This is my last breath, interpreter will perform the rites.')
@staticmethod
def i_am_static(msg):
print(msg, 'Did you notice, I do not require self/cls as first argument')
return 'Statically simple'
# def get_pwd(self, pin):
# pin_from_db = self.__fetch_pin()
# if pin == pin_from_db:
# return self.__pwd
# else:
# raise Exception('AuthorizationError : pin mismatch')
ob = EdurekaCustomer('Python Enthusiast', '[email protected]', '999999999', 30, 'pyenthu')
# print(ob)
print(ob.get_phone())
print(ob.name, ob.email, ob._age, ob.phone)
print(ob._EdurekaCustomer__pwd)
print(ob.hashed_pwd)
# ob.i_am_static('called by object')
# EdurekaCustomer.i_am_static('called by class')
# print(ob.get_pwd())
# del ob
# print(ob)
# ob.owned_by_class('random')
# EdurekaCustomer.owned_by_class('classy')
# print(ob.available_discount())
# print(EdurekaCustomer.__dict__)
# print(EdurekaCustomer.__doc__)
# print(EdurekaCustomer.__bases__)
# print(EdurekaCustomer.__mro__)
# print(EdurekaCustomer.__name__)
# print(EdurekaCustomer.DEFAULT_DISC)
# print(EdurekaCustomer.owned_by_class('abc'))
# print(EdurekaCustomer.i_am_static('Hello'))
####[20]:
import base64
pwd = 'aO4Ly1WlMT'
print()
####[23]:
print(base64.b64encode(pwd.encode()))
####[29]:
SOME_VAR = 'Something'
class Species(object):
PLANET = 'Any'
def get_planet(self):
return self.PLANET
class People(Species):
PLANET = 'Earth'
def __init__(self, name, eth, age):
print('Inside Init!')
self._name = name
self.ethnicity = eth
self.__age = age
def __str__(self):
return 'Name, Ethnicity and Age : {}, {}, {}'.format(self._name, self.ethnicity, self.__age)
def get_name(self):
return self._name
def get_age(self, pretty=True):
return self.__age if not pretty else '{} yrs old'.format(self.__age)
def __get_db_connection(self):
return cxn
def __validate_key(self, key):
return 'pwd'
def get_pwd(self, key):
# verify the key in a db table and fetch associated pwd if key is correct
return 'Authenticated. Password is :', ''
def is_old(self):
return self.__age > 60
# def get_planet(self):
# return 'Mostly {} if a person is not cosmonaut.'.format(self.PLANET)
def lives_under_water(self):
return 'Depends. If it is '
x = People('Adam', 'US', 45)
print(x)
x.weight = '60 pounds'
print(x)
is_old = x.is_old()
x._name = 'Brian Adams'
is_old = 'is' if is_old else 'is not'
print('Person {} {} old, age is {}, weight is {}'.format(x._name, is_old, x.get_age(), x.weight))
print('I am on planet : {}'.format(x.get_planet()))
####[ ]:
class Vector(object): # N x 1 or 1 x N
def __init__(self, *elements):
self.elements = list(elements)
def get_elements(self):
return self.elements
# for overloading +
def __add__(self, other):
values = []
for x, y in zip(self.elements, other.get_elements()):
values.append(x+y)
return values
def __sub__(self, other):
pass
def __len__(self):
return self.no_of_pages
book1 = Book('Author', 'Name', 'No of Pages')
len(book1)
####[32]:
import abc
print(abc.__name__)
print(abc.__doc__)
####[86]:
dir(Number)
####[135]:
# self - a pointer to current object under consideration
# cls - a pointer to the class from which object is derived
class Account():
account_type = 'Savings'
def __init__(self, account_id, name, password):
self.id = account_id
self.name = name
self.__pwd = password
@classmethod
def _cls_method(cls):
print('This is a class method')
def welcome(self):
print(self.__get_welcome_message())
def __get_welcome_message(self):
if self.account_type == 'Savings':
return 'Dear {}, we have some exciting offers for Savings account customers. Please connect with us for more details.'.format(self.name)
else:
return 'Dear {}, welcome to bank XYZ.'.format(self.name)
def __del__(self):
print('Invoking destructor, happy ending {}'.format(self.name))
#dir(Account)
####[136]:
ob1 = Account(123, 'Python', 'anaconda')
print(ob1.__dict__)
ob1.welcome()
print(Account.account_type)
Account._cls_method()
ob1._cls_method()
# print(Account.__dict__)
# print(Account.__doc__)
####[137]:
del ob1
####[138]:
ob1
####[93]:
print(Account.__name__)
####[111]:
Account.account_type = 'Current'
ob = Account()
#dir(ob)
####[112]:
ob.account_type
####[113]:
ob.welcome()
####[109]:
print(ob.__dict__)
####[110]:
ob.name = 'Bob'
print(ob)
# ####heritance, Encapsulation/Abstraction, Overriding and Polymorphism
####[16]:
class JustForClarity():
def does_it_eat(self):
return 'God knows what you expect me to return.'
class Species():
def does_it_eat(self):
return 'Depends'
def lives_under_water(self):
raise NotImplementedError
class People(Species):
def needs_oxygen(self):
return True
def needs_water(self):
return True
def does_it_eat(self):
output = super(People, self).does_it_eat()
return '{}, as long as the person is not fasting.'.format(output)
def lives_under_water(self):
return 'Is usually on land unless its too hot when a person would prefer swimming.'
class Civilization(People):
pass
# def does_it_eat(self):
# return 'Civilized to eat only well cooked food.'
class Asians(Civilization, JustForClarity):
pass
class Americans(People):
pass
s1 = Species()
#print(s1.does_it_eat())
#print(s1.lives_under_water())
p1 = People()
#print(p1.does_it_eat())
#print(p1.lives_under_water())
a1 = Asians()
#print(a1.does_it_eat())
print(Asians.__mro__)
print(a1.does_it_eat())
####[ ]:
# [<one-position>] - lists, tuples, strings, sets
# [start:stop:step] - lists, tuples, strings, sets
class ConnectToDB():
def __init__(self, connect_to='Postgres'):
self._connect_to = connect_to
self.__establish_cxn()
def __connect_to_postgres(self):
pass
def __connect_to_mysql(self):
pass
def __establish_cxn(self):
if self._connect_to == 'Postgres':
self.__connect_to_postgres()
else:
self.__connect_to_mysql()
def setCxnToMysql(self):
if self._connect_to != 'MySQL':
self._connect_to = 'MySQL'
self.__establish_cxn()
def setCxnToPostgres(self):
if self._connect_to != 'Postgres':
self._connect_to = 'Postgres'
self.__establish_cxn()
def __add__(self):
pass
def __subtract__(self):
pass
def __len__(self):
return self.__no_of_pages
# # Standard Libraries - sys, os, json, random, re, datetime,
# # string, dateutil, math
####[17]:
import sys
print(sys.argv)
####[4]:
import os
import random
import sys
import string
import datetime
from datetime import datetime, date, timedelta
from dateutil import parser
import json
# l1 = sys.argv
# print('Welcome {} to Python world!'.format(l1[1]))
# print(os.getcwd())
# os.chdir(l1[2])
# print(os.getcwd())
# print(random.randrange(12))
# print(random.randint(10, 13))
# lot = ['abc123', 'def345', 'ghi987']
# print(random.choice(lot))
# random.choice
# list of letters + list of digits
# print(string.ascii_letters + string.digits + string.punctuation)
# print(''.join([random.choice(string.ascii_letters + string.digits + string.punctuation) for x in range(100)]))
####[16]:
import datetime
print(date.today())
print(datetime.today())
print(datetime.utcnow())
print(date.isoweekday(date.today() + timedelta(3)))
print(parser.parse('2018-10-06T20:53:24.999+05:30'))
####[18]:
# print(datetime.date.today())
# print(datetime.date.today() - datetime.timedelta(1))
# print(parser.parse('2018-08-05'))
emp = {'name': 'Steve', 'age': 25, 'salary': 12000,
'addresses': {'primary': "White House",
'secondary': '''Trump Towers'''}
}
jemp = json.dumps(emp)
print(type(emp), type(jemp))
print(jemp)
# [] () . + {2,3} ? *
####[19]:
# print('-----------------------------------')
jstr = '{"name": "Steve", "age": 25, "salary": 12000, "addresses": {"primary": "White House", "secondary": "Trump Towers"}}'
jdict = json.loads(jstr)
print(jdict)
print(type(jstr), type(jdict))
####[28]:
import re
####[32]:
s1 = 'Python is wonderful'
m1 = re.findall('ful', s1, re.IGNORECASE)
m1
|
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if board:
m, n = len(board), len(board[0])
def check(board, i, j):
"""
Checks for 'O' that are connected to the 'O's on the border and
changes all connected Os to P.
"""
if (i >= 0 and i < m) and (j >= 0 and j < n) and board[i][j] == "O":
board[i][j] = "P"
check(board, i + 1, j)
check(board, i - 1, j)
check(board, i, j + 1)
check(board, i, j - 1)
for i in range(m):
for j in range(n):
if board[i][j] == "O" and (
i == 0 or j == 0 or i == m - 1 or j == n - 1
): # check for O on borders
check(board, i, j)
for i in range(m):
for j in range(n):
if board[i][j] == "O":
board[i][j] = "X"
elif board[i][j] == "P":
board[i][j] = "O"
|
"Write a function for what you can buy in Splendor board game based on the cost of the card and how many tokens you have"
def can_buy(cost_of_card, tokens_of_player):
'Method 1'
print(tokens_of_player['blue'])
print(cost_of_card['blue'])
blue_passes = tokens_of_player['blue'] >= cost_of_card['blue']
green_passes = tokens_of_player['green'] >= cost_of_card['green']
red_passes = tokens_of_player['red'] >= cost_of_card['red']
if blue_passes and green_passes and red_passes:
return True
else:
return False
def can_buy(cost_of_card, tokens_of_player):
'Method 2'
passes = []
passes.append(tokens_of_player['blue'] >= cost_of_card['blue'])
passes.append(tokens_of_player['green'] >= cost_of_card['green'])
passes.append(tokens_of_player['red'] >= cost_of_card['red'])
if all(passes):
return True
else:
return False
def can_buy(cost_of_card, tokens_of_player):
'Method 3'
passes_all = True
for color in cost_of_card.keys():
passes = tokens_of_player[color] >= cost_of_card[color]
passes_all = passes_all and passes
return passes_all
def can_buy(cost_of_card, tokens_of_player):
'Method 4'
for color in cost_of_card.keys():
passes = tokens_of_player[color] >= cost_of_card[color]
if passes:
pass
else:
return False
return True
def can_buy(cost_of_card, tokens_of_player):
'Method 5'
for color in cost_of_card.keys():
if tokens_of_player[color] >= cost_of_card[color]:
pass
else:
return False
return True
def can_buy(cost_of_card, tokens_of_player):
'Method 6'
for color, cost_count in cost_of_card.items():
if tokens_of_player[color] >= cost_count:
pass
else:
return False
return True
def can_buy(cost_of_card, tokens_of_player):
'Method 7'
def passes_for_color(color):
return tokens_of_player[color] >= cost_of_card[color]
return all(passes_for_color, cost_of_card.keys())
def can_buy(cost_of_card, tokens_of_player):
'Method 8'
return all(lambda color: tokens_of_player[color] >= cost_of_card[color], cost_of_card.keys())
def purchase(card_cost, tokens_of_player):
pass
card_cost = {'blue': 1, 'green': 2, 'red': 1}
tokens_1 = {'blue': 1, 'green': 2, 'red': 1}
print(can_buy(card_cost, tokens_1))
|
'''Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.'''
'''Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.'''
'''Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
'''
'''
Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
'''
if input[right_index] -input[left_input] > max_profit
max_profit = new_profit
|
"""Roman numerals consist of seven different symbols:
I, V, X, L, C, D and M, with the following values
for each symbol:
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
The roman numerals are written next to each other and are added, if they are equal or greater in value reading from left to right, to get their Arabic numeral equivalent. For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X II. The number twenty seven is written as XXVII, which is XX V II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Create a function called romanNumeral, that takes as input an integer and returns it's roman numeral. Input is guaranteed to be within the range from 1 to 3000."""
class Converter:
def int_to_Roman(self, digit: str)-> int:
arabic = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
roman = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
roman_numeral = ''
i = 0
while digit > 0:
for _ in range(digit // arabic[i]):
roman_numeral += roman[i]
digit -= arabic[i]
i += 1
return roman_numeral
print(Converter().int_to_Roman(2940))
print(Converter().int_to_Roman(409))
|
<<<<<<< HEAD
def arrayStringsAreEqual(word1, word2):
"Given two string arrays word1 and word2, return true if the two arrays represent the same string, and false otherwise. A string is represented by an array if the array elements concatenated in order forms the string."
# concatenate all strings for word1
word1_concat = "".join(word1)
# concatenate all strings for word2
word2_concat = "".join(word2)
# if word1 == word2:
if word1_concat == word2_concat:
return True
else:
return False
# return true
# else return false
print(arrayStringsAreEqual(word1 = ["ab", "c"], word2 = ["a", "bc"]))
# Output: true
print(arrayStringsAreEqual(word1 = ["a", "cb"], word2 = ["ab", "c"]))
# Output: false
print(arrayStringsAreEqual(word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]))
# Output: true
=======
class Solution:
def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
word1_concat = "".join(word1)
word2_concat = "".join(word2)
if word1_concat == word2_concat:
return True
else:
return False
>>>>>>> 5d0a94d9777893ecfe1daa85b0e94fa43af7a519
|
def nums(num):
prev = 0
for i in range(num):
sum=prev+i
print(sum)
prev = i
num = int(input("Enter number: "))
nums(num)
|
# coding: utf-8
# # Python的日期和时间处理
# ## datetime模块
# In[1]:
from datetime import datetime
# In[2]:
now = datetime.now()
print(now)
# In[3]:
print('年: {}, 月: {}, 日: {}'.format(now.year, now.month, now.day))
# In[4]:
diff = datetime(2017, 3, 4, 17) - datetime(2017, 2, 18, 15)
print(type(diff))
print(diff)
print('经历了{}天, {}秒。'.format(diff.days, diff.seconds))
# ## 字符串和datetime转换
#
# ### datetime -> str
# In[5]:
# str()
dt_obj = datetime(2017, 3, 4)
str_obj = str(dt_obj)
print(type(str_obj))
print(str_obj)
# In[6]:
# datetime.strftime()
str_obj2 = dt_obj.strftime('%d-%m-%Y')
print(str_obj2)
# ### str -> datetime
# In[7]:
# strptime
dt_str = '2017-02-18'
dt_obj2 = datetime.strptime(dt_str, '%Y-%m-%d')
print(type(dt_obj2))
print(dt_obj2)
# In[8]:
# dateutil.parser.parse
from dateutil.parser import parse
dt_str2 = '2017/02/18'
dt_obj3 = parse(dt_str2)
print(type(dt_obj3))
print(dt_obj3)
# In[9]:
# pd.to_datetime
import pandas as pd
s_obj = pd.Series(['2017/02/18', '2017/02/19', '2017-02-25', '2017-02-26'], name='course_time')
print(s_obj)
# In[10]:
s_obj2 = pd.to_datetime(s_obj)
print(s_obj2)
# In[11]:
# 处理缺失值
s_obj3 = pd.Series(['2017/02/18', '2017/02/19', '2017-02-25', '2017-02-26'] + [None],
name='course_time')
print(s_obj3)
# In[12]:
s_obj4 = pd.to_datetime(s_obj3)
print(s_obj4) # NAT-> Not a Time
#%%
|
# coding: utf-8
# # 第3讲 Python语言基础
# ## 3.1 Python数据类型
# ### 3.1.1 字符串
# 在Python中用引号引起来的字符集称之为字符串,比如:'hello'、"my Python"、"2+3"等都是字符串
# Python中字符串中使用的引号可以是单引号、双引号跟三引号
# In[ ]:
print ('hello world!')
# In[ ]:
c = 'It is a "dog"!'
print (c)
# In[ ]:
c1= "It's a dog!"
print (c1)
# In[ ]:
c2 = """hello
world
!"""
print (c2)
# - 转义字符'\'
# 转义字符\可以转义很多字符,比如\n表示换行,\t表示制表符,字符\本身也要转义,所以\\表示的字符就是\
# In[ ]:
print ('It\'s a dog!')
print ("hello world!\nhello Python!")
print ('\\\t\\')
# 原样输出引号内字符串可以使用在引号前加r
# In[ ]:
print (r'\\\t\\')
# - 子字符串及运算
# In[ ]:
s = 'Python'
print( 'Py' in s)
# 取子字符串有两种方法,使用[]索引或者切片运算法[:],这两个方法使用面非常广
# In[ ]:
print (s[2])
# In[ ]:
print (s[1:4])
# - 字符串连接与格式化输出
# In[ ]:
word1 = '"hello"'
word2 = '"world"'
sentence = word1.strip('"') + ' ' + word2.strip('"') + '!'
print( 'The first word is %s, and the second word is %s' %(word1, word2))
print (sentence)
# ### 3.1.2 整数与浮点数
# Python可以处理任意大小的整数,当然包括负整数,在程序中的表示方法和数学上的写法一模一样
# In[ ]:
i = 7
print (i)
# In[ ]:
7 + 3
# In[ ]:
7 - 3
# In[ ]:
7 * 3
# In[ ]:
7 ** 3
# In[ ]:
7 / 3#Python3之后,整数除法和浮点数除法已经没有差异
# In[ ]:
7 % 3
# 浮点数
# In[ ]:
7.0 / 3
# In[ ]:
3.14 * 10 ** 2
# 其它表示方法
# In[ ]:
0b1111
# In[ ]:
0xff
# In[ ]:
1.2e-5
# 更多运算
# In[ ]:
import math
print (math.log(math.e)) # 更多运算可查阅文档
# ### 3.1.3 布尔值
# In[ ]:
True
# In[ ]:
False
# In[ ]:
True and False
# In[ ]:
True or False
# In[ ]:
not True
# In[ ]:
True + False
# In[ ]:
18 >= 6 * 3 and 'py' in 'Python'
# ### 3.1.4 日期时间
# In[ ]:
import time
now = time.strptime('2016-07-20', '%Y-%m-%d')
print (now)
# In[ ]:
type(now)
# In[ ]:
time.strftime('%Y-%m-%d', now)
# In[ ]:
import datetime
someDay = datetime.date(1999,2,10)
anotherDay = datetime.date(1999,2,15)
deltaDay = anotherDay - someDay
deltaDay.days
# In[ ]:
import time as t
date_formate = "%Y-%m-%d" # year-month-day
t.strptime('2016-06-22', date_formate)
# ### 3.1.5其它
# 空值none
# In[ ]:
print( None)
# 复数complex
# In[ ]:
cplx = (4 + 2j) * (3 + 0.2j)
print (cplx)
# - 查看变量类型
# In[ ]:
type(None)
# In[ ]:
type(s)
# In[ ]:
type(cplx)
# - 类型转换
# In[ ]:
str(10086)
# In[ ]:
float(10086)
# In[ ]:
int('10086')
# In[ ]:
complex(10086)
# ## 3.2 Python数据结构
# 列表(list)、元组(tuple)、集合(set)、字典(dict)
# ### 3.2.1 列表(list)
# 用来存储一连串元素的容器,列表用[]来表示,其中元素的类型可不相同。
# In[ ]:
students = ["ming", "hua", "li", "juan", "yun", 3]
print (students)
# 列表索引和切片
# In[ ]:
# 索引从0开始,含左不含右
print ('[4]=', students[4])
print ('[-4]=', students[-4])
print ('[0:4]=', students[0:4])
print( '[4:]=', students[4:])
print ('[0:4:2]=', students[0:4:2])
print ('[-5:-1:]=', students[-5:-1:])
print ('[-2::-1]=', students[-2::-1])
# 修改列表
# In[ ]:
students[3] = "小月"
print (students[3])
students[5]="小楠"
print (students[5])
students[5]=19978
print (students[5])
# 插入元素
# In[ ]:
students.append('han') # 添加到尾部
students.extend(['long', 'wan'])
print (students)
# In[ ]:
scores = [90, 80, 75, 66]
students.insert(1, scores) # 添加到指定位置
students
# 删除元素
# In[ ]:
print (students.pop(1)) # 该函数返回被弹出的元素,不传入参数则删除最后一个元素
print (students)
# 判断元素是否在列表中等
# In[ ]:
print( 'wan' in students)
print ('han' not in students)
# In[ ]:
students.count('wan')
# In[ ]:
students.index('wan')
# range函数生成整数列表
# In[ ]:
print (range(10))
print (range(-5, 5))
print (range(-10, 10, 2))
print (range(16, 10, -1))
# ### 3.2.2 元组(tuple)
# 元组类似列表,元组里面的元素也是进行索引计算。列表里面的元素的值可以修改,而元组里面的元素的值不能修改,只能读取。元组的符号是()。
# In[ ]:
studentsTuple = ("ming", "jun", "qiang", "wu", scores)
studentsTuple
# In[ ]:
try:
studentsTuple[1] = 'fu'
except TypeError:
print ('TypeError')
# In[ ]:
scores[1]= 100
studentsTuple
# In[ ]:
'ming' in studentsTuple
# In[ ]:
studentsTuple[0:4]
# In[ ]:
studentsTuple.count('ming')
# In[ ]:
studentsTuple.index('jun')
# In[ ]:
len(studentsTuple)
# ### 3.2.3 集合(set)
# Python中集合主要有两个功能,一个功能是进行集合操作,另一个功能是消除重复元素。 集合的格式是:set(),其中()内可以是列表、字典或字符串,因为字符串是以列表的形式存储的
# In[ ]:
studentsSet = set(students)
print (studentsSet)
# In[ ]:
studentsSet.add('xu')
print (studentsSet)
# In[ ]:
studentsSet.remove('xu')
print (studentsSet)
# In[ ]:
a = set("abcnmaaaaggsng")
print ('a=', a)
b = set("cdfm")
print ('b=', b)
#交集
x = a & b
print( 'x=', x)
#并集
y = a | b
print ('y=', y)
#差集
z = a - b
print( 'z=', z)
#去除重复元素
new = set(a)
print( z)
# ### 3.2.4字典(dict)
# Python中的字典dict也叫做关联数组,用大括号{}括起来,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度,其中key不能重复。
# In[ ]:
k = {"name":"weiwei", "home":"guilin"}
print (k["home"])
# In[ ]:
print( k.keys())
print( k.values())
# In[ ]:
a={"success":True,"reason_code":"200","reason_desc":"获取成功",
"rules":[{"rule_id":"1062274","score":7,"conditions":[{"address_a_value":
"南通市","address_a":"mobile_address","address_b":"true_ip_address","address_b_value":"南京市","type":"match_address"}]}]}
print(a["success"])
# 添加、修改字典里面的项目
# In[ ]:
k["like"] = "music"
k['name'] = 'guangzhou'
print (k)
# 判断key是否存在
# In[ ]:
print ('name' in k)
#has_key方法在python2中是可以使用的,在python3中删除了。
#print (k.has_key('name'))
#改为:
if 'name' in k:
print("Yes")
# In[ ]:
k.get('edu', -1) # 通过dict提供的get方法,如果key不存在,可以返回None,或者自己指定的value
# 删除key-value元素
# In[ ]:
k.pop('like')
print (k)
# ### 2.2.5 列表、元组、集合、字典的互相转换
# In[ ]:
tuple(students)
# In[ ]:
list(k)
# In[ ]:
zl = zip(('A', 'B', 'C'), [1, 2, 3, 4]) # zip可以将列表、元组、集合、字典‘缝合’起来
print (zl)
print (dict(zl))
# *练习:小明的语文成绩是80分,数学成绩是70分,小红两门课的成绩则分别是90分和95分,尝试生成一个嵌套字典,可用于方便的查找分数
# ## 3.3 Python控制流
# 在Python中通常的情况下程序的执行是从上往下执行的,而某些时候我们为了改变程序的执行顺序,使用控制流语句控制程序执行方式。Python中有三种控制流类型:顺序结构、分支结构、循环结构。
# 另外,Python可以使用分号";"分隔语句,但一般是使用换行来分隔;语句块不用大括号"{}",而使用缩进(可以使用四个空格)来表示
# ### 3.3.1 顺序结构
# In[ ]:
s = '7'; num = int(s) # 一般不使用这种分隔方式
num -= 1 # num = num - 1
num *= 6 # num = num * 1
print (num)
# ### 3.3.2 分支结构:Python中if语句是用来判断选择执行哪个语句块的
# =============================================================================
# if <True or Flase表达式>:
# 执行语句块
# elif <True or Flase表达式>:
# 执行语句块
# else: # 都不满足
# 执行语句块
# =============================================================================
# elif子句可以有多条,elif和else部分可省略
# In[ ]:
salary = 30000
if salary > 10000:
print ("Wow!!!!!!!")
elif salary > 5000:
print ("That's OK.")
elif salary > 3000:
print ("5555555555")
else:
print ("..........")
#%%
# ### 3.3.3 循环结构
# while 循环
# =============================================================================
# while <True or Flase表达式>:
# 循环执行语句块
# else: # 不满足条件
# 执行语句块
# =============================================================================
#else部分可以省略
# In[ ]:
a = 1
while a < 10:
if a <= 5:
print (a)
else:
print ("Hello")
a = a + 1
else:
print ("Done")
# - for 循环
# =============================================================================
# for (条件变量) in (集合):
# 执行语句块
# =============================================================================
# “集合”并不单指set,而是“形似”集合的列表、元组、字典、数组都可以进行循环
# 条件变量可以有多个
# In[ ]:
heights = {'Yao':226, 'Sharq':216, 'AI':183}
for i in heights:
print (i, heights[i])
# In[ ]:
#for key, value in heights.items():-Python3 不能使用dict.iteritems(),改为dict.items()
for key, value in heights.items():
print(key, value)
# In[ ]:
total = 0
for i in range(1, 101):
total += i
print (total)
# *** 练习:使用循环和分支结构输出20以内的奇数
# ### 3.3.4 break、continue和pass
#break:跳出循环
#continue:跳出当前循环
#pass:占位符,什么也不做
# In[ ]:
for i in range(1, 5):
if i == 3:
break
print (i)
# In[ ]:
for i in range(1, 5):
if i == 3:
continue
print (i)
# In[ ]:
for i in range(1, 5):
if i == 3:
pass
print (i)
# ### 3.3.5 列表生成式
# 三种形式
# - [<表达式> for (条件变量) in (集合)]
# - [<表达式> for (条件变量) in (集合) if <'True or False'表达式>]
# - [<表达式> if <'True or False'表达式> else <表达式> for (条件变量) in (集合) ]
# In[ ]:
fruits = ['"Apple', 'Watermelon', '"Banana"']
[x.strip('"') for x in fruits]
# In[ ]:
[x ** 2 for x in range(21) if x%2]
# *练习:使用列表生成式生成一个布尔值列表,每个布尔值对应判断 range(21)中的每个元素是否是奇数。* 提示:if-else语句在for循环语句之前
# In[ ]:
[m + n for m in 'ABC' for n in 'XYZ']
# In[ ]:
d = {'x': 'A', 'y': 'B', 'z': 'C' }
[k + '=' + v for k, v in d.items()]
# ## 3.4 Python函数
# 函数是用来封装特定功能的实体,可对不同类型和结构的数据进行操作,达到预定目标
# ### 3.4.1 调用函数
# - Python内置了很多有用的函数,我们可以直接调用,进行数据分析时多数情况下是通过调用定义好的函数来操作数据的
# In[ ]:
str1 = "as"
int1 = -9
print (len(str1))
print (abs(int1))
# In[ ]:
fruits = ['Apple', 'Banana', 'Melon']
fruits.append('Grape')
print (fruits)
# ### 3.4.2 定义函数
# 当系统自带函数不足以完成指定的功能时,需要用户自定义函数来完成。
# =============================================================================
# def 函数名():
# 函数内容
# 函数内容
# <return 返回值>
# =============================================================================
# In[ ]:
def my_abs(x):
if x >= 0:
return x
else:
return -x
my_abs(-9)
# 可以没有return
# In[ ]:
def filter_fruit(someList, d):
for i in someList:
if i == d:
someList.remove(i)
else:
pass
print (filter_fruit(fruits, 'Melon'))
print (fruits)
# 多个返回值的情况
# In[ ]:
def test(i, j):
k = i * j
return i, j, k
a , b , c = test(4, 5)
print (a, b , c)
type(test(4, 5))
# ### 3.4.3 高阶函数
# - 把另一个函数作为参数传入一个函数,这样的函数称为高阶函数
# 函数本身也可以赋值给变量,函数与其它对象具有同等地位
# In[ ]:
myFunction = abs
myFunction(-9)
# - 参数传入函数
# In[ ]:
def add(x, y, f):
return f(x) + f(y)
add(7, -5, myFunction)
# - 常用高阶函数
# map/reduce: map将传入的函数依次作用到序列的每个元素,并把结果作为新的list返回;reduce把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
# In[ ]:
myList = [-1, 2, -3, 4, -5, 6, 7]
map(abs, myList)
# In[ ]:
from functools import reduce
def powerAdd(a, b):
return pow(a, 2) + pow(b, 2)
reduce(powerAdd, myList) # 是否是计算平方和?
# filter: filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素
# In[ ]:
def is_odd(x):
return x % 3 # 0被判断为False,其它被判断为True
filter(is_odd, myList)
# sorted: 实现对序列排序,默认情况下对于两个元素x和y,如果认为x < y,则返回-1,如果认为x == y,则返回0,如果认为x > y,则返回1
# 默认排序:数字大小或字母序(针对字符串)
# In[ ]:
sorted(myList)
# 自定义排序规则
# In[ ]:
def reversed_cmp(x, y):
if x > y:
return -1
if x < y:
return 1
return 0
sorted(myList, reversed_cmp)
# *练习:自定义一个排序规则函数,可将列表中字符串忽略大小写地,按字母序排列,列表为['Apple', 'orange', 'Peach', 'banana']。提示:字母转换为大写的方法为some_str.upper(),转换为小写使用some_str.lower()
# - 返回函数: 高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回
# In[ ]:
def powAdd(x, y):
def power(n):
return pow(x, n) + pow(y, n)
return power
myF = powAdd(3, 4)
myF
# In[ ]:
myF(2)
# - 匿名函数:高阶函数传入函数时,不需要显式地定义函数,直接传入匿名函数更方便
# In[ ]:
f = lambda x: x * x
f(4)
# 等同于:
# In[ ]:
def f(x):
return x * x
# In[ ]:
map(lambda x: x * x, myList)
# 匿名函数可以传入多个参数
# In[ ]:
reduce(lambda x, y: x + y, map(lambda x: x * x, myList))
# 返回函数可以是匿名函数
# In[ ]:
def powAdd1(x, y):
return lambda n: pow(x, n) + pow(y, n)
lamb = powAdd1(3, 4)
lamb(2)
# ## 3.5 Python模块
# 模块是可以实现一项或多项功能的程序块,Python本身就内置了很多非常有用的模块,只要安装完毕,这些模块就可以立刻使用
# In[ ]:
# 可以通过安装第三方包来增加系统功能,也可以自己编写模块。引入模块有多种方式
# In[ ]:
import pandas as pd
df = pd.DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'], 'data1': range(7)})
df.head(2)
# In[ ]:
from pandas import DataFrame
df1 = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'], 'data1': range(7)})
df1.head(5)
# In[ ]:
# 尽量不使用 'from ... import *' 这种方式,可能造成命名混乱
from pandas import *
df2 = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'], 'data1': range(7)})
crosstab(df2.key, df2.data1)
# ## 3.6 使用pandas读写数据
# - pandas可以读取文本文件、json、数据库、Excel等文件
# - 使用read_csv方法读取以逗号分隔的文本文件作为DataFrame,其它还有类似read_table, read_excel, read_html, read_sql等等方法
# In[5]:
import os
os.chdir(r'D:\Python_book\3Programing')#设置读取文件的路径
#%%
import pandas as pd
one = pd.read_csv('One.csv',sep=",")
one.head()
# In[6]:
#get_ipython().magic('pinfo pd.read_csv')
# In[ ]:
hsb2 = pd.read_table('hsb2.txt')
hsb2.head()
# In[ ]:
html = pd.read_html('http://www.fdic.gov/bank/individual/failed/banklist.html') # Return a list
html
# In[ ]:
xls = pd.read_excel('hsb2.xlsx', sheetname=0)
xls.head()
# 写入文件
# In[ ]:
xls.to_csv('copyofhsb2.csv')
# ## 其它
# - 标识符第一个字符只能是字母或下划线,第一个字符不能出现数字或其他字符;标识符除第一个字符外,其他部分可以是字母或者下划线或者数字,标识符大小写敏感,比如name跟Name是不同的标识符。
# - Python规范:类标识符每个字符第一个字母大写;对象\变量标识符的第一个字母小写,其余首字母大写,或使用下划线'_' 连接;函数命名同普通对象。建议
# - 关键字
# 关键字是指系统中自带的具备特定含义的标识符
# In[ ]:
# 查看一下关键字有哪些,避免关键字做自定义标识符
import keyword
print (keyword.kwlist)
# - 注释
# Python中的注释一般用#进行注释
# In[ ]:
# print 'hello world' # Do nothing
# - 帮助
# In[ ]:
#get_ipython().magic('pinfo scores')
# In[ ]:
help(scores)
#%%
|
class LinkedList :
class Node :
__slots__ = 'element' , 'next'
def __init__(self, element, next):
self.element = element
self.next = next
def __init__(self):
self.head = None
self.tail = None
self.size = 0
def __len__(self):
return self.size
def is_empty(self):
return self.size == 0
def add_first(self, e):
newest = self.Node(e, None)
if self.is_empty() :
self.head = newest
self.tail = newest
else :
newest.next = self.head
self.head = newest
self.size += 1
def add_last(self, e):
newest = self.Node(e, None)
if self.is_empty():
self.head = newest
self.tail = newest
else :
self.tail.next = newest
self.tail = newest
self.size += 1
def add_any(self, e, pos):
newest = self.Node(e, None)
thead = self.head
i = 1
while i < pos :
thead = thead.next
i += 1
newest.next = thead.next
thead.next = newest
self.size += 1
def del_first(self):
if self.is_empty():
return 'The linked list is Empty.'
del_element = self.head.element
self.head = self.head.next
self.size -= 1
if self.is_empty():
self.head = None
self.tail = None
return del_element
def del_last(self):
if self.is_empty():
return 'The Linked List is Empty'
thead = self.head
i = 0
while i < self.size-2 :
thead = thead.next
i += 1
del_element = self.tail.element
self.tail = thead
self.tail.next = None
self.size -= 1
if self.is_empty():
self.head = None
self.tail = None
return del_element
def del_any(self, pos):
if self.is_empty():
return 'The Linked List is Empty'
if pos == 0:
self.del_first()
return 0
thead = self.head
i = 1
while i < pos-1 :
thead = thead.next
i += 1
del_element = thead.next.element
thead.next = thead.next.next
self.size -= 1
return del_element
def display(self):
thead = self.head
while thead :
print(thead.element, end = "-->")
thead = thead.next
print()
L = LinkedList()
L.add_first(10)
L.add_first(20)
L.add_first(60)
L.add_first(50)
L.display()
L.add_last(90)
L.add_last(777)
L.display()
L.add_any(40,3)
L.display()
L.del_first()
L.display()
L.del_last()
L.display()
L.del_any(1)
L.display()
|
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 2 10:16:47 2019
@author: roush
"""
#
# write up_heapify, an algorithm that checks if
# node i and its parent satisfy the heap
# property, swapping and recursing if they don't
#
# L should be a heap when up_heapify is done
#
def up_heapify(L, i):
# if node is the root, we're done
if parent(i) < 0: return
# if parent is larger, swap nodes and recurse on parent
if L[parent(i)] > L[i]:
L[parent(i)], L[i] = L[i], L[parent(i)]
up_heapify(L, parent(i))
# otherwise, heap property is satisfied
return
def parent(i):
return int((i-1)/2)
def left_child(i):
return 2*i+1
def right_child(i):
return 2*i+2
def is_leaf(L,i):
return (left_child(i) >= len(L)) and (right_child(i) >= len(L))
def one_child(L,i):
return (left_child(i) < len(L)) and (right_child(i) >= len(L))
def test():
L = [2, 4, 3, 5, 9, 7, 7] # this is a heap
L.append(1)
up_heapify(L, 7)
print(L)
#assert 1 == L[0]
#assert 2 == L[1]
test()
|
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 27 17:47:44 2019
@author: roush
Sort a list by using the comparison model
BigO (or BigTheta) == n*log(n)??
"""
import random
testlist = [4,1,55,1,311,556,2,33,44,109,592958,5293,50]
def sort_list(a_list):
for fillslot in range(len(a_list)): # iterate through positions in list
position_of_min = fillslot # minimum value could be that in the fillslot
for position in range(fillslot,len(a_list)): # iterate from fillslot to end of list
if a_list[position] < a_list[position_of_min]:
position_of_min = position
intermediate = a_list[fillslot] # place to store current fillslot value, since it's about to replaced
a_list[fillslot] = a_list[position_of_min]
a_list[position_of_min] = intermediate # swap position of original min value with fillslot value
return a_list
print(sort_list(testlist))
|
'''
37. Write a Python program to display your details like name, age, address in three different lines.
'''
name = input("Please enter your name : ")
age = int(input("Please enter your age : "))
adress = input("Please enter your adress : ")
print(f"{name}\n{age}\n{adress}")
|
'''
6. Write a Python program which accepts a sequence of comma-separated numbers
from user and generate a list and a tuple with those numbers.
'''
import re
inputStr = input("Please enter sequence of comma-separated numbers : ").split(',')
myList = list(inputStr)
myTuple = tuple(inputStr)
print(myList)
print(myTuple)
|
'''
27. Write a Python program to concatenate all elements in a list into a string and return it.
'''
def function(list):
new_str = ""
for item in list:
new_str += str(item)
return new_str
my_list = [2,5,1,2131,435,6]
my_list2 = ["hello","world","my","name","is","bat"]
print(function(my_list))
print(function(my_list2))
|
import cv2 as cv
import numpy as np
import torch
def image_normalization(img, img_min=0, img_max=255):
"""This is a typical image normalization function
where the minimum and maximum of the image is needed
source: https://en.wikipedia.org/wiki/Normalization_(image_processing)
:param img: an image could be gray scale or color
:param img_min: for default is 0
:param img_max: for default is 255
:return: a normalized image, if max is 255 the dtype is uint8
"""
img = np.float32(img)
epsilon = 1e-12 # whenever an inconsistent image
img = (img-np.min(img))*(img_max-img_min) / \
((np.max(img)-np.min(img))+epsilon)+img_min
return img
# def visualize_result(imgs_list, arg):
# """
# function for tensorflow results
# :param imgs_list: a list of prediction, gt and input data
# :param arg:
# :return: one image with the whole of imgs_list data
# """
# n_imgs = len(imgs_list)
# data_list = []
# for i in range(n_imgs):
# tmp = imgs_list[i]
# if tmp.shape[1] == 3:
# tmp = np.transpose(np.squeeze(tmp), [1, 2, 0])
# tmp = restore_rgb(
# [arg.channel_swap, arg.mean_pixel_values[:3]], tmp)
# tmp = np.uint8(image_normalization(tmp))
# else:
# tmp = np.squeeze(tmp)
# if len(tmp.shape) == 2:
# tmp = np.uint8(image_normalization(tmp))
# tmp = cv.bitwise_not(tmp)
# tmp = cv.cvtColor(tmp, cv.COLOR_GRAY2BGR)
# else:
# tmp = np.uint8(image_normalization(tmp))
# data_list.append(tmp)
# img = data_list[0]
# if n_imgs % 2 == 0:
# imgs = np.zeros((img.shape[0] * 2 + 10, img.shape[1]
# * (n_imgs // 2) + ((n_imgs // 2 - 1) * 5), 3))
# else:
# imgs = np.zeros((img.shape[0] * 2 + 10, img.shape[1]
# * ((1 + n_imgs) // 2) + ((n_imgs // 2) * 5), 3))
# n_imgs += 1
# k = 0
# imgs = np.uint8(imgs)
# i_step = img.shape[0]+10
# j_step = img.shape[1]+5
# for i in range(2):
# for j in range(n_imgs//2):
# if k < len(data_list):
# imgs[i*i_step:i*i_step+img.shape[0], j*j_step:j *
# j_step+img.shape[1], :] = data_list[k]
# k += 1
# else:
# pass
# return imgs
# def cv_imshow(title='image', img=None):
# cv.imshow(title, img)
# cv.waitKey(0)
# cv.destroyAllWindows()
def tensor2edge(tensor):
print(tensor.shape)
tensor =torch.squeeze(tensor) if len(tensor.shape)>2 else tensor
tmp = torch.sigmoid(tensor)
tmp = tmp.cpu().detach().numpy()
# tmp = np.transpose(np.squeeze(tmp[1]), [1, 2, 0])
tmp = np.uint8(image_normalization(tmp))
tmp = cv.bitwise_not(tmp)
tmp = cv.cvtColor(tmp, cv.COLOR_GRAY2BGR)
cv.imshow('test_img', tmp)
cv.waitKey(0)
cv.destroyAllWindows()
|
#coding=utf-8
name=input('为什么叫我贝塔?')
if name=='巧碧螺':
print('yes its me!')
else:
print('飞机刷没了!!')
|
#coding=utf-8
#字符串
for i in 'abcd':
print(i)
#列表
l1=[1,2,'heygor','ladeng']
for a in l1:
print(a)
print('*'*20)
#函数
#内置函数range()
#range(10) 0-9
#range(1,10) 1-9
for i in range(10):
print(i)
print('*'*20)
for i in range(1,10):
print(i)
print('*'*20)
for i in range(-5,5):
#print(i)
if i<0:
print(-i)
else:
print(i)
|
#!/usr/bin/env python
# encoding: utf-8
"""Transform a YAML file into a LaTeX Beamer presentation.
Usage: bin/yml2tex input.yml > output.tex
"""
from pygments import highlight
from pygments.lexers import get_lexer_for_filename
from pygments.formatters import LatexFormatter
import yaml
def separate(doc):
"""
Given the parsed document structure, return a separated list where the first
value is a key and the second value all its underlying elements.
For example, the first value might be a section and the second value all
its subsections.
Examples:
>>> separate([{'a': [{'b': [{'c': ['d', 'e', 'f']}]}]}])
[('a', [{'b': [{'c': ['d', 'e', 'f']}]}])]
>>> separate([{'c': ['d', 'e', 'f']}])
[('c', ['d', 'e', 'f'])]
"""
return [(k, j[k]) for i, j in enumerate(doc) for k in j]
def section(title):
"""
Given the section title, return its corresponding LaTeX command.
"""
return '\n\n\section{%s}' % title
def subsection(title):
"""
Given the subsection title, return its corresponding LaTeX command.
"""
return '\n\subsection{%s}' % title
def frame(title, items):
"""
Given the frame title and corresponding items, delegate to the appropriate
function and returns its LaTeX commands.
"""
if title.startswith('include'):
out = code(title)
elif title.startswith('image'):
out = image(title)
else:
out = "\n\\frame {"
out += "\n\t\\frametitle{%s}" % title
out += itemize(items)
out += "\n}"
return out
def itemize(items):
"""
Given the items for a frame, returns the LaTeX syntax for an itemized list.
If an item itself is a dictionary, a nested list will be created.
The script doesn't limit the depth of nested lists. However, LaTeX Beamer
class limits lists to be nested up to a depth of 3.
"""
out = "\n\t\\begin{itemize}[<+-| alert@+>]"
for item in items:
if isinstance(item, dict):
for i in item:
out += "\n\t\\item %s" % i
out += itemize(item[i])
else:
out += "\n\t\\item %s" % item
out += "\n\t\end{itemize}"
return out
def code(title):
"""
Return syntax highlighted LaTeX.
"""
filename = title.split(' ')[1]
try:
lexer = get_lexer_for_filename(filename)
except:
lexer = get_lexer_by_name('text')
f = open(filename, 'r')
code = highlight(f.read(), lexer, LatexFormatter())
f.close()
out = "\n\\begin{frame}[fragile,t]"
out += "\n\t\\frametitle{Code: \"%s\"}" % filename
out += code
out += "\n\end{frame}"
return out
def image(title):
"""
Given a frame title, which starts with "image" and is followed by the image
path, return the LaTeX command to include the image.
"""
out = "\n\\frame[shrink] {"
out += "\n\t\\pgfimage{%s}" % title.split(' ')[1]
out += "\n}"
return out
def header():
"""
Return the LaTeX Beamer document header declarations.
"""
out = "\documentclass[slidestop,red]{beamer}"
out += "\n\usepackage[utf8]{inputenc}"
out += "\n\usepackage{fancyvrb,color}"
out += r'''
% pygments
\newcommand\at{@}
\newcommand\lb{[}
\newcommand\rb{]}
\newcommand\PYbh[1]{\textcolor[rgb]{0.00,0.50,0.00}{\textbf{#1}}}
\newcommand\PYbg[1]{\textcolor[rgb]{0.73,0.40,0.53}{\textbf{#1}}}
\newcommand\PYbf[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
\newcommand\PYbe[1]{\textcolor[rgb]{0.73,0.13,0.13}{#1}}
\newcommand\PYbd[1]{\textcolor[rgb]{0.00,0.50,0.00}{\textbf{#1}}}
\newcommand\PYbc[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
\newcommand\PYbb[1]{\textcolor[rgb]{0.00,0.00,0.50}{\textbf{#1}}}
\newcommand\PYba[1]{\textcolor[rgb]{0.00,0.50,0.00}{\textbf{#1}}}
\newcommand\PYaJ[1]{\textcolor[rgb]{0.69,0.00,0.25}{#1}}
\newcommand\PYaK[1]{\textcolor[rgb]{0.73,0.13,0.13}{#1}}
\newcommand\PYaH[1]{\textcolor[rgb]{0.10,0.09,0.49}{#1}}
\newcommand\PYaI[1]{\fcolorbox[rgb]{1.00,0.00,0.00}{1,1,1}{#1}}
\newcommand\PYaN[1]{\textcolor[rgb]{0.74,0.48,0.00}{#1}}
\newcommand\PYaO[1]{\textcolor[rgb]{0.00,0.00,1.00}{\textbf{#1}}}
\newcommand\PYaL[1]{\textcolor[rgb]{0.00,0.00,1.00}{#1}}
\newcommand\PYaM[1]{\textcolor[rgb]{0.73,0.73,0.73}{#1}}
\newcommand\PYaB[1]{\textcolor[rgb]{0.00,0.50,0.00}{#1}}
\newcommand\PYaC[1]{\textcolor[rgb]{0.00,0.25,0.82}{#1}}
\newcommand\PYaA[1]{\textcolor[rgb]{0.00,0.63,0.00}{#1}}
\newcommand\PYaF[1]{\textcolor[rgb]{0.63,0.00,0.00}{#1}}
\newcommand\PYaG[1]{\textcolor[rgb]{1.00,0.00,0.00}{#1}}
\newcommand\PYaD[1]{\textcolor[rgb]{0.67,0.13,1.00}{#1}}
\newcommand\PYaE[1]{\textcolor[rgb]{0.25,0.50,0.50}{\textit{#1}}}
\newcommand\PYaZ[1]{\textcolor[rgb]{0.73,0.13,0.13}{#1}}
\newcommand\PYaX[1]{\textcolor[rgb]{0.73,0.13,0.13}{#1}}
\newcommand\PYaY[1]{\textcolor[rgb]{0.00,0.50,0.00}{#1}}
\newcommand\PYaR[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
\newcommand\PYaS[1]{\textcolor[rgb]{0.10,0.09,0.49}{#1}}
\newcommand\PYaP[1]{\textcolor[rgb]{0.00,0.00,0.50}{\textbf{#1}}}
\newcommand\PYaQ[1]{\textcolor[rgb]{0.49,0.56,0.16}{#1}}
\newcommand\PYaV[1]{\textcolor[rgb]{0.82,0.25,0.23}{\textbf{#1}}}
\newcommand\PYaW[1]{\textcolor[rgb]{0.00,0.00,1.00}{\textbf{#1}}}
\newcommand\PYaT[1]{\textcolor[rgb]{0.25,0.50,0.50}{\textit{#1}}}
\newcommand\PYaU[1]{\textcolor[rgb]{0.50,0.00,0.50}{\textbf{#1}}}
\newcommand\PYaj[1]{\textcolor[rgb]{0.10,0.09,0.49}{#1}}
\newcommand\PYak[1]{\textcolor[rgb]{0.25,0.50,0.50}{\textit{#1}}}
\newcommand\PYah[1]{\textcolor[rgb]{0.00,0.50,0.00}{#1}}
\newcommand\PYai[1]{\textcolor[rgb]{0.63,0.63,0.00}{#1}}
\newcommand\PYan[1]{\textbf{#1}}
\newcommand\PYao[1]{\textcolor[rgb]{0.67,0.13,1.00}{\textbf{#1}}}
\newcommand\PYal[1]{\textcolor[rgb]{0.73,0.40,0.53}{#1}}
\newcommand\PYam[1]{\textcolor[rgb]{0.00,0.50,0.00}{\textbf{#1}}}
\newcommand\PYab[1]{\textit{#1}}
\newcommand\PYac[1]{\textcolor[rgb]{0.73,0.13,0.13}{#1}}
\newcommand\PYaa[1]{\textcolor[rgb]{0.50,0.50,0.50}{#1}}
\newcommand\PYaf[1]{\textcolor[rgb]{0.25,0.50,0.50}{\textit{#1}}}
\newcommand\PYag[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
\newcommand\PYad[1]{\textcolor[rgb]{0.73,0.13,0.13}{#1}}
\newcommand\PYae[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
\newcommand\PYaz[1]{\textcolor[rgb]{0.00,0.50,0.00}{\textbf{#1}}}
\newcommand\PYax[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
\newcommand\PYay[1]{\textcolor[rgb]{0.60,0.60,0.60}{\textbf{#1}}}
\newcommand\PYar[1]{\textcolor[rgb]{0.53,0.00,0.00}{#1}}
\newcommand\PYas[1]{\textcolor[rgb]{0.10,0.09,0.49}{#1}}
\newcommand\PYap[1]{\textcolor[rgb]{0.73,0.40,0.13}{\textbf{#1}}}
\newcommand\PYaq[1]{\textcolor[rgb]{0.00,0.50,0.00}{#1}}
\newcommand\PYav[1]{\textcolor[rgb]{0.40,0.40,0.40}{#1}}
\newcommand\PYaw[1]{\textcolor[rgb]{0.00,0.50,0.00}{\textbf{#1}}}
\newcommand\PYat[1]{\textcolor[rgb]{0.73,0.13,0.13}{\textit{#1}}}
\newcommand\PYau[1]{\textcolor[rgb]{0.10,0.09,0.49}{#1}}
% end pygments'''
out += "\n\n\usetheme{Antibes}"
out += "\n\setbeamertemplate{footline}[frame number]"
out += "\n\usecolortheme{lily}"
out += "\n\\beamertemplateshadingbackground{blue!5}{yellow!10}"
out += "\n\n\\title{Example Presentation Created with the Beamer Package}"
out += "\n\\author{Arthur Koziel}"
out += "\n\date{\\today}"
out += "\n\n\\begin{document}"
out += "\n\n\\frame{\\titlepage}"
out += "\n\n\section*{Outline}"
out += "\n\\frame {"
out += "\n\t\\frametitle{Outline}"
out += "\n\t\\tableofcontents"
out += "\n}"
out += "\n\n\AtBeginSection[] {"
out += "\n\t\\frame{"
out += "\n\t\t\\frametitle{Outline}"
out += "\n\t\t\\tableofcontents[currentsection]"
out += "\n\t}"
out += "\n}"
return out
def footer():
"""
Return the LaTeX Beamer document footer.
"""
out = "\n\end{document}"
return out
def main(text):
"""
Return the final LaTeX presentation after invoking all necessary functions.
"""
doc = yaml.load(text)
out = header()
for sections, doc in separate(doc):
out += section(sections)
for subsections, doc in separate(doc):
out += subsection(subsections)
for frames, items in separate(doc):
out += frame(frames, items)
out += footer()
return out.encode('utf-8')
|
"""
Write a function that will receive a 2D list of integers. The function should return the count of how many rows of the list have even sums
and the count of how many rows have odd sums.
For example if the even count was 2, and odd count was 4 your function should return them in a list like this: [2, 4].
"""
# Function Dec.
def get_rows_count(L):
new_list = []
# Iterating through Lists
for i in L:
new_list.append(sum(i))
even_count = 0
odd_count = 0
# Checking Even-Odd
for j in new_list:
if j % 2 == 0:
even_count += 1
else:
odd_count += 1
return [even_count, odd_count]
|
"""
Write a function that accepts a list of integers and returns a new list which is the sorted version (ascending order) of the original list
(Original list should not be modified). You may NOT use the built in sort() or sorted() functions. Notice that the original list should not
be modified
"""
# Function Dec.
def sorting (L1):
L = L1
for i in range(len(L)):
# Next Value from the list
# For comp.
for j in range(i + 1, len(L)):
if L[i] > L[j]:
L[i], L[j] = L[j], L[i]
return L
|
"""
Write a function that accepts two lists A and B and returns a new list which contains all the elements of list A followed by elements of
list B. Notice that the behaviour of this function is different from list.extend() method because the list.extend() method extends the
list in place, but here you are asked to create a new list and return it. Your function should not return the original lists.
For example if the input lists are:
A = ['p', 'q', 6, 'k']
B = [8, 10]
Then your function should return a list such as:
['p', 'q', 6, 'k', 8, 10]
"""
# Function Dec.
def extend_list(A, B):
# Logic
new_list = A + B
return new_list
|
"""
Write a function that accepts two input lists and returns a new list which contains only the unique elements from both lists.
"""
# Function Dec.
def get_unique(L1, L2):
L1.append(L2)
new_list = []
# Accessing the List
for i in L1:
# Logic
if i not in new_list:
new_list.append(i)
return new_list
|
"""
Write a function named find_longest_word that receives a string as parameter and returns the longest word in the string. Assume that the
input to this function is a string of words consisting of alphabetic characters that are separated by space(s). In case of a tie between
some words return the last one that occurs
"""
# Function Dec.
def find_longest_word(str):
# Splitting string into list
str = str.split()
# Getting first element
# Assigning it as max length word
max_length = str[0]
longest_word = len(str[0])
# Accessing all the words in List
for word in str:
# Logic
if len(word) >= longest_word:
max_length = word
return max_length
|
"""
Write a function that accepts an alphabetic character and returns the number associated with it from the ASCII table.
"""
#Function Dec.
def get_asc(n):
# Using
return ord(n)
|
"""
Write a function that accepts two positive integers a and b (a is smaller than b)and returns a list that contains all the odd numbers
between a and b (including a and including b if applicable) in descending order.
"""
# Function Decl.
def odd_num(a, b):
num = b
# An empty list
l = []
# Logicc and adding odds
while num >= a:
if num % 2 != 0:
l.append(num)
num -= 1
return l
|
"""
Write a program using while loops that asks the user for a positive integer 'n' and prints a triangle using numbers from 1 to 'n'.
For example if the user enters 6 then the output should be like this :
(There should be no spaces between the numbers)
1
22
333
4444
55555
666666
"""
# Getting User Input
n = int(input('Enter a Number: '))
i = 1
# Condition
while i <= n:
# Logic for Pattern
print (i * str(i))
i += 1
|
"""
Write a function that accepts a 2 Dimensional list of integers and returns the average.
Remember that average = (sum_of_all_items) / (total_number_of_items).
"""
# Function Dec.
def avg_list(L):
total_sum = 0
# Accessing every row
for row in range(len(L)):
# Accessing every column
for col in range(len(L[0])):
# Sum and avg
total_sum += L[row][col]
avg = total_sum/(len(L)+len(L[0]))
return int(avg)
|
"""
Write a function that accepts a positive integer n and returns the ascii character associated with it.
"""
#Function Dec.
def get_asc(n):
return chr(n)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.