text stringlengths 37 1.41M |
|---|
# import collections
unsorted_list = [-199, 1, 4, 2, 6, -900, 3]
sorted_list = [0, 1, 3, 5, 9, 14]
def minimum(lst):
min_val = lst[0]
for e in lst[1:]:
if e < min_val:
min_val = e
return min_val
def sort_it(lst):
sorted_lst = []
while len(lst) > 0:
min_item = minimum(lst)
sorted_lst.append(min_item)
lst.remove(min_item)
return sorted_lst
print(sort_it(unsorted_list))
def unsorted_seq_search(arr, ele):
for e in arr:
if e == ele:
return True
return False
def sorted_seq_search(arr, ele):
for e in arr:
if e == ele:
return True
elif e > ele:
return False
return False
print(unsorted_seq_search(unsorted_list, 4))
print(sorted_seq_search(sorted_list, -1))
|
class BinHeap:
"""
a balanced binary tree has each node with two children. Exception could be the last level where only one child can
be there. It has methods to insert elements into the tree (which will automatically adjust the elements in correct
position. Similarly, elements removed will cause the tree to adjust itself. There is an additional method which will
create a binary tree from a list. for each element in a particular position, its left and right children can be
found in 'i * 2' and '(i * 2) + 1' position.
"""
def __init__(self):
self.heapList = [0]
self.currentSize = 0
def insert(self, k):
self.heapList.append(k)
self.currentSize += 1
self.percUp(self.currentSize)
def percUp(self, i):
while i // 2 > 0:
if self.heapList[i // 2] > self.heapList[i]:
tmp = self.heapList[i // 2]
self.heapList[i // 2] = self.heapList[i]
self.heapList[i] = tmp
i = i // 2
def delMin(self):
retval = self.heapList[1]
self.heapList[1] = self.heapList[self.currentSize]
self.currentSize -= 1
self.heapList.pop()
self.percDown(1)
return retval
def percDown(self, i):
while i * 2 <= self.currentSize:
mc = self.minChild(i)
if self.heapList[i] > self.heapList[mc]:
tmp = self.heapList[mc]
self.heapList[mc] = self.heapList[i]
self.heapList[i] = tmp
i *= 2
def minChild(self, i):
if (i * 2) + 1 > self.currentSize:
return i * 2
else:
leftChild = self.heapList[(i * 2)]
rightChild = self.heapList[(i * 2) + 1]
if leftChild < rightChild:
return i * 2
else:
return (i * 2) + 1
def buildHeap(self, alist):
i = len(alist) // 2
self.heapList = [0] + alist[:]
self.currentSize = len(alist)
while i > 0:
self.percDown(i)
i -= 1
a = BinHeap()
a.insert(2)
a.insert(6)
a.insert(3)
a.insert(5)
print(a.currentSize)
print(a.heapList)
print("*" * 15)
lst = [2, 6, 3, 5]
b = BinHeap()
b.buildHeap(lst)
print(b.currentSize)
print(b.heapList)
|
"""
A binary search tree relies on the property that the keys less than parent are found in the left subtree and keys
greater than parent are found in the right subtree. This property holds true for each parent and a child. All keys
in the left of the root are less than the root. While all keys on the right of the root are larger than the root.
"""
class TreeNode:
def __init__(self, key, val, left=None, right=None, parent=None):
self.key = key
self.payload = val
self.leftChild = left
self.rightChild = right
self.parent = parent
def hasLeftChild(self):
return self.leftChild
def hasRightChild(self):
return self.rightChild
def isLeftChild(self):
if self.parent and self.parent.hasLeftChild() == self:
return True
else:
return False
def isRightChild(self):
if self.parent and self.parent.hasRightChild() == self:
return True
else:
return False
def isRoot(self):
if self.parent is None:
return True
else:
return False
def isLeaf(self):
if self.leftChild is None and self.rightChild is None:
return True
else:
return False
def hasAnyChildren(self):
if self.leftChild or self.rightChild:
return True
else:
return False
def hasBothChildren(self):
return self.leftChild and self.rightChild
def replaceNodeData(self, key, val, lc, rc):
self.key = key
self.payload = val
self.leftChild = lc
self.rightChild = rc
if self.hasLeftChild():
self.leftChild.parent = self
if self.hasRightChild():
self.rightChild.parent = self
class BinarySearchTree:
def __init__(self):
self.root = None
self.size = 0
def length(self):
return self.size
def __len__(self):
return self.length()
def put(self, key, val):
if self.root:
self._put(key, val, self.root)
else:
self.root = TreeNode(key=key, val=val)
self.size += 1
def _put(self, key, val, currentNode):
if key < currentNode.key:
if currentNode.hasLeftChild():
self._put(key, val, currentNode.left)
else:
currentNode.left = TreeNode(key=key, val=val, parent=currentNode)
else:
if currentNode.hasRightChild():
self._put(key, val, currentNode.right)
else:
currentNode.right = TreeNode(key=key, val=val, parent=currentNode)
def __setitem__(self, key, value):
self.put(key=key, val=value)
def get(self, key):
if self.root:
res = self._get(key, self.root)
if res:
return res.payload
else:
return None
else:
return None
def _get(self, key, currentNode):
if currentNode is None:
return None
elif key == currentNode.key:
return currentNode
elif key < currentNode.key:
return self._get(key, currentNode.leftChild)
else:
return self._get(key, currentNode.rightChild)
def __getitem__(self, item):
return self.get(item)
def __contains__(self, item):
return self.get(key=item) is not None
if __name__ == "__main__":
t = BinarySearchTree()
t.put(1, 'a')
t.put(2, 'b')
t.put(9, 'c')
t.put(6, 'd')
print(f'length of t is {len(t)}')
print(f'val of 9 is {t.get(9)}')
print(f'val of 9 is {t[9]}')
|
from course import Course
import csv
from util import *
class Reader:
"""Process files to get courses"""
def __init__(self, file_name, delimiter=",", comment="#"):
self.file_name = file_name
self.delimiter = delimiter
self.comment = comment
self.courses = []
self.__process_csv()
def get_courses(self):
return self.courses
def __check_sanity(self, course_info):
""" check the sanity of the line """
try:
# should have 5 columns
assert len(course_info) == 5
# the second one should be numbers
assert course_info[1].replace(".","",1).isdigit()
# the last one should be like 1,1
# pass
return True
except:
return False
def __is_comment(self, line):
# string => boolean
return line.startswith(self.comment) or line == ""
def _get_teachers(self, teachers):
return map(str.upper, map(str.strip, teachers.strip().split(";")))
def __process_csv(self):
#try:
with open(self.file_name, "rb") as csvfile:
course_reader = csv.reader(csvfile)
for cid, name, credit, grade, teachers, start_time in course_reader:
if self.__is_comment(cid):
continue
# if the course has been allocated
pos = time_to_pos(start_time)
teachers = self._get_teachers(teachers)
course = Course(cid, name, int(credit), grade, teachers, pos)
self.courses.append(course)
#except:
# print "fail to process course file"
# exit(1)
if __name__=='__main__':
reader = Reader("test.csv")
for c in reader.get_courses():
print c.cid, c.name, c.credit, c.grade_name, c.teachers
|
#!/usr/bin/env python
# encoding: utf-8
p1 = [0,1,2,3,4]
p2 = [5,6,7,8,9]
p3 = [10, 11, 12]
class Pref:
def __init__(self, day, time):
"""每门课排课时候的要求。TODO:是否可以把start_time归到这里里面?
Attributes:
time: 时间, (listof int), 从 0 开始
day : 周数,int, 从 0 开始
"""
self.day = day
self.time = time
assert(type(day) == int)
assert(type(time) == list)
def __str__(self):
return "day:%s, time:%s" % (self.day, self.time)
def prefs(days=[0,1,2,3,4], time=p1+p2+p3, compact=0):
"""用于指定了在哪几天的哪几个时间段
Argument:
days: 排课要求排在哪几天
time: 排课要求排在这几天的哪些时间里面
Return: (listof int) * (listof int) => (listof Pref)
示例:
- 周一和周三的上午: prefs(days=[0,2], time=p1)
- 周一和周三: prefs(days=[0,2])
- 周一至周五的上午: prefs(time=p1)
"""
return ([Pref(d, time) for d in days], compact)
def prefs_notin(days=[], time=[], compact=0):
"""如果条件是“不在哪几天的哪几个时间”,则用这个函数
Arguments:
days: 不排在哪几天
time: 不排在这几个时间段
compact: 要压缩课程到几天里面
Return:
(listof int) * (listof int) => (listof Pref)
示例:
- 不在周二和周三的下午: prefs_notin([1,2],p2)
"""
total_days = [0,1,2,3,4]
total_time = p1 + p2 + p3
result = []
if time == []:
for d in filter(lambda x: x not in days,
total_days):
result.append(Pref(d, total_time))
return (result, compact)
if days == []:
preftime = filter(lambda x: x not in time,
total_time)
for d in total_days:
result.append(Pref(d,preftime))
return (result, compact)
if time != [] and days != []:
preftime = filter(lambda x: x not in time,
total_time)
for d in total_days:
if d in days:
result.append(Pref(d, preftime))
else:
result.append(Pref(d, total_time))
return (result, compact)
def prefs_notin_special(not_dict, compact=0):
"""用于指定不在某一天的某个时刻,参数可以是任意偶数多个
Argument:
not_dict: {day->time} 的dict
day: 不排在哪一天
time: 不排在那一天的某个时刻
compact: 要压缩课程到几天
Return:
int * (listof int) * ... => (listof Pref)
示例:
- 不在周三的下午和周四的晚上: prefs_notin_specially(2,p2,3,p3)
"""
total_time = p1+p2+p3
total_days = [0,1,2,3,4]
result = []
for d in total_days:
if d in not_dict:
ts = filter(lambda x: x not in not_dict[d], total_time)
result.append(Pref(d, ts))
else:
result.append(Pref(d, total_time))
return (result, compact)
def prefs_special(in_dict, compact=0):
"""用于指定某一天的某个时刻,参数可以是任意偶数多个
Arguments:
in_dict: {day->time} 的dict
day: 在某一天
time: 在那一天的某个时间段
compact: 要压缩课程到几天里面
Return:
int * (listof int) * ... => (listof Pref)
示例:
- 在周二上午和周三下午:prefs_special(1,p1,2,p2)
"""
total_time = p1 + p2 + p3
total_days = [0,1,2,3,4]
result = []
for d in in_dict:
result.append(Pref(d, in_dict[d]))
return (result, compact)
|
# The Dutch Flag Partition is used to kind of teach how a quick sort works
# You're a given a array of 0's, 1's and 2's and a pivot
# Then you must build a function to rearrange this array such that:
# All numbers smaller than the pivot must be to it's left
# All numbers bigger than the pivot must be to it's right
# Suppose the array A = (0,1,2,0,2,1,1) and the pivot index is 3
# this means A[3] is 0 so a valid partitioning would be (0,0,1,2,2,1,1) but (0,0,1,2,1,2,1) is also a valid partition
# if the pivot index is 5 then a valid partition would be (0,0,1,1,1,2,2)
# Write a program that takes an array A and an index i into A and rearranges the elements such that all elements
# less than A[i] appear first, followed by elements equal to A[i], followed by elements greater than A[i].
from typing import List
def dutchFlagBruteForce(A: List[int], i: int) -> List[int]:
#Using O(n) time and O(n) space
if not A or i >= len(A):
return []
pivot = A[i]
before = []
equal = []
after = []
for j in range(len(A)):
if (A[j] < pivot):
before.append(A[j])
elif (A[j] == pivot):
equal.append(A[j])
else:
after.append(A[j])
return before + equal + after
print(dutchFlagBruteForce([0,1,2,0,2,1,1], 1))
def dutchFlagTwoPass(A: List[int], i: int) -> List[int]:
# This solution trades space for time so it takes O(1) space but O(n²) time complexity
if not A or i>= len(A):
return []
pivot = A[i]
# The First pass groups elements smaller than the pivot
for j in range(len(A)):
for k in range(j+1, len(A)):
if(A[k] < pivot):
A[j], A[k] = A[k], A[j]
break
# The Second pass groups elements greater than the pivot
for j in reversed(range(len(A))):
for k in reversed(range(j)):
if (A[k] > pivot):
A[j], A[k] = A[k], A[j]
break
return A
print(dutchFlagTwoPass([0,1,2,0,2,1,1], 1))
# There's a better way to do it, with O(n) time complexity and O(1) space complexity
# The problem with the dutchFlagTwoPass solution is, for every element it checks if there are smaller ahead
# but we don't need to start from the beginning, we can do this only when the element being checked is less than the pivot
# so in dutchFlagTwoPass using the array (0,1,2,0,1,1) and the pivot index 1
# in the first pass we actually start at 0 and check each index trying to find an element that is smaller than 0, but we shouldn't
# 0 is already smaller than the pivot so we should just go to the next index
# This is an implementation that is O(n) but uses O(1) space
def dutchFlagSmart(A: List[int], i: int) -> List[int]:
if(not A or i>= len(A)):
return []
pivot = A[i]
small_index = 0
big_index = len(A)-1
for j in range(len(A)):
if(A[j] < pivot):
A[j], A[small_index] = A[small_index], A[j]
small_index += 1
for j in reversed(range(len(A))):
if(A[j]> pivot):
A[j], A[big_index] = A[big_index], A[j]
big_index -=1
return A
print(dutchFlagSmart([0,1,2,0,2,1,1], 1)) |
#Calculate the maxDepth of an N-ary Tree
import collections
class Solution:
def maxDepth(self, root):
if(not root):
return 0
q = collections.deque()
depth = 1
q.append([root, depth]) #Depth keeps the state of which depth we are
while(q):
node = q.pop()
for child in node[0].children:
q.appendleft([child, node[1]+1]) #this way we only add once the depth state
depth = node[1]
return depth |
a=str(input())
opening= "[{("
closing = "]})"
def isCorrectMatching(str:str)-> bool:
l = []
for i in str:
if i in opening:
l.append(i)
if i in closing:
if not len(l):
return False
c = l.pop()
if closing.index(i) != opening.index(c):
return False
if len(l) == 0:
return True
else:
return False
print(isCorrectMatching(a)) |
#
# | 1 | 2 | 3 | 4 |
# | 12 | 13 | 14 | 5 |
# | 11 | 16 | 15 | 6 |
# | 10 | 9 | 8 | 7 |
#
# This is the spiral order of an array 4x4
# Write a function that receives an array NxN and returns the spiral form of this array
from typing import List
A = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]
def matrix_in_spiral_order(square_matrix: List[List[int]]) -> List[int]:
# We set the value of visited values to be 0, (a number that is assumed not to be in the matrix)
shift = ((0,1),(1,0),(0,-1),(-1,0))
direction, x, y = 0, 0, 0
spiral_ordering = []
for _ in range(len(square_matrix)*len(square_matrix)):
spiral_ordering.append(square_matrix[x][y])
square_matrix[x][y] = 0
next_x = x + shift[direction][0]
next_y = y + shift[direction][1]
if(next_x not in range(len(square_matrix))
or next_y not in range(len(square_matrix))
or square_matrix[next_x][next_y] == 0):
direction = (direction + 1) & 3
next_x = x + shift[direction][0]
next_y = y + shift[direction][1]
x,y = next_x, next_y
return spiral_ordering
print(matrix_in_spiral_order(A)) |
def main():
num=int(input('Ingrese numeros enteros positivos (finalice con 0):\n'))
while num<0:
print('Error. Ingrese numero mayor a 0:')
num=int(input())
if num>0:
max=num
min=num
while num!=0:
if max<num:
max=num
elif num<0:
print('Error. Ingrese numero mayor a 0:')
elif min>num:
min=num
num=int(input())
if num==0:
print('El menor es {:d} y el mayor {:d}'.format(min,max))
main()
|
print('Ejercicio n5')
print('')
num1=int(input('Ingrese numero: '))
n0=str((num1//1%10)**2)
n1=str((num1//10%10)**2)
n2=str((num1//100%10)**2)
n3=str((num1//1000%10)**2)
n4=str((num1//10000%10)**2)
print(n4+'-'+n3+'-'+n2+'-'+n1+'-'+n0) |
def triangulo(catetos):
for f in range (catetos):
for c in range (catetos):
if c<=f:
print('*',end='')
print('') #Debe ir fuera del 'for c' (columna)
def main():
catetos=int(input('Ingrese base: '))
while catetos<3: #VALIDACION
print('ERROR. Ingrese numero MAYOR o IGUAL a tres')
catetos=int(input())
triangulo(catetos)
main()
|
def estaEnLista(numero,lista):
if numero in lista:
return True
else:
return False
def cargarLista():
print('Ingresar numeros,o 0 (cero ) para terminar: ')
n=int(input())
lista=[]
while n!=0:
while n<0 and n!=0:
print('Error, numero NO positivo.')
n=int(input())
while estaEnLista(n,lista) and n!=0:
print('Error, número repetido.')
n=int(input())
lista.append(n)
n=int(input())
if n==0:
return lista
def main():
lst=cargarLista()
print('La lista contiene:\n',lst)
main() |
def res(a,b):
if a>=b:
return a-b
elif b>=a:
return b-a
def condicion(a,b):
if a>=b and res(a,b)>=b and res(a,b)<=a:
return 'SI cumple condicion'
elif b>=a and res(a,b)<=b and res(a,b)>=a:
return 'SI cumple condicion'
else:
return 'NO cumple condicion'
def main():
a=int(input('Ingrese numero A: '))
b=int(input('Ingrese numero B: '))
print(condicion(a,b))
main() |
print('Ejercicio 10')
b=int(input('Ingrese numero binario (5 bits max): '))
n=len(str(b))
z=b//10000%10*2**4
x=b//1000%10*2**3
c=b//100%10*2**2
v=b//10%10*2**1
n=b%10*2**0
t=x+c+v+n+z
print('Número en decimal: '+str(t))
|
def inserOrd(lst,num):
pos=0
while pos<len(lst) and num!='':
if num>=lst[pos] and num<=lst[pos+1]:
lst.insert(pos+1,num)
num=''
else:
pos+=1
return lst
def main():
print('Ingresar numeros,o 0 (cero ) para terminar: ')
n=int(input())
lista=[]
while n!=0:
while n<0 and n!=0:
print('Error, numero NO positivo.')
n=int(input())
while n in lista and n!=0:
print('Error, número repetido.')
n=int(input())
while len(lista)>1 and n<lista[-1] and n!=0:
print('ERROR. La lista va de menor a mayor')
n=int(input())
lista.append(n)
n=int(input())
if n==0:
print('Lista generada:\n',lista)
num=int(input('\nIngrese valor a insertar: '))
print('\nLa lista con la inserción ordenada es:\n',inserOrd(lista,num))
main() |
def aBinario(n):
binario=0
potencia=0
while n!=0:
r=n%2
n=n//2
binario=binario+(r*10**potencia)
potencia=potencia+1
return binario
def main():
num=int(input('Ingrese un numero decimal: '))
cifras=len(str(num))
##validacion
while not ((num>0 and num<1000) or cifras<4):
print('ERROR. Ingrese un numero decimal positivo y de 3 cifras.')
num=int(input())
##
print()
print('Numero en binario: {}.'.format(aBinario(num)))
main() |
# Write a function to combine two lists of equal length into one, alternating elements.
# combine(['a','b','c'],[1,2,3]) → ['a', 1, 'b', 2, 'c', 3]
def combine(nums1, nums2):
"""
returns list of list1 and list2 elements alternating
>>> combine(['a','b','c'],[1,2,3])
['a', 1, 'b', 2, 'c', 3]
"""
return sum([list(i) for i in zip(nums1, nums2)], [])
# test = []
# tuples = zip(nums1, nums2)
# for i in tuples:
# test.append(list(i))
# return sum(test, [])
nums1 = ['a', 'b', 'c']
nums2 = [1, 2, 3]
print(combine(nums1, nums2))
|
# Write a function that takes n as a parameter, and returns a list containing the first n Fibonacci Numbers.
# fibonacci(8) → [1, 1, 2, 3, 5, 8, 13, 21]
def fibonacci(n):
"""
>>> fibonacci(8)
[1, 1, 2, 3, 5, 8, 13, 21]
"""
if n >= len(fibonacci_cache):
fib = fibonacci(n-1) + fibonacci(n-2)
fibonacci_cache.append(fib)
return fib
return fibonacci_cache[n]
fibonacci_cache = [0, 1]
print(fibonacci(8))
print(fibonacci_cache)
|
# Lab 17: Palindrome and Anagram
from string import punctuation
def check_palindrome(input):
for symbols in punctuation:
input = input.replace(symbols, '').lower().replace(' ', '')
return input == input[::-1]
def check_anagram(input1, input2):
for symbols in punctuation:
input1 = input1.replace(symbols, '').lower().replace(' ', '')
list1 = list(input1)
list1.sort()
for symbols in punctuation:
input2 = input2.replace(symbols, '').lower().replace(' ', '')
list2 = list(input2)
list2.sort()
return list1 == list2
while True:
function = input("Would you like to check for a (palindrome) or (anagram)?\n> ").strip().lower()
if function in ['p', 'palindrome', 'a', 'anagram']:
break
else:
print("Please select one of the choices!")
if function.startswith('p'):
input1 = input("What would you like to check to see if it is a palindrome?\n> ").strip()
print(f"Is {input1} a palindrome? : {check_palindrome(input1)}")
else:
input1 = input("What is our first word for the anagram checker?\n> ").strip()
input2 = input("What is our second word for the anagram checker?\n> ").strip()
print(f"Is {input1} an anagram of {input2}? : {check_anagram(input1, input2)}")
|
#this code was from my intro course, but I have added lists and commented out old code that I have changed
# The quote “Through dangers untold and hardships unnumbered I have fought my way here to the castle beyond the Goblin City to take back the child you have stolen, for my will is as strong as yours and my kingdom as great. You have no power over me!”
import random
ask_question = input("Do you want to try my madlib? yes or no\n>")
while True:
while ask_question.lower() not in ["yes", "no"]:
ask_question = input("I'm looking for a (yes) or (no)\n>")
if ask_question.lower() == "yes":
noun_list = []
ploural_noun_list = []
verb_list = []
# mad_dangers = input("Give me a plural noun: ")
ploural_noun_list.append(input("Give me a plural noun: "))
# mad_hardships = input("Give me another plural noun: ")
ploural_noun_list.append(input("Give me another plural noun: "))
# mad_fought = input("Give me past tense verb: ")
verb_list.append(input("Give me past tense verb: "))
mad_castle = input("Give me a building type: ")
mad_goblin = input("Give me a creature: ")
# mad_child = input("Give me a noun: ")
noun_list.append(input("Give me a noun: "))
# mad_stolen = input("Give me past tense verb: ")
verb_list.append(input("Give me past tense verb: "))
# mad_will = input("Give me a noun: ")
noun_list.append(input("Give me a noun: "))
# mad_kingdom = input("Give me a noun: ")
noun_list.append(input("Give me a noun: "))
# mad_power = input("Give me a noun: ")
noun_list.append(input("Give me a noun: "))
random.shuffle(noun_list)
random.shuffle(ploural_noun_list)
random.shuffle(verb_list)
# print(f"Through {mad_dangers} untold and {mad_hardships} unnumbered I have {mad_fought} my way here to the {mad_castle} beyond the {mad_goblin} City to take back the {mad_child} you have {mad_stolen}, for my {mad_will} is as strong as yours and my {mad_kingdom} as great. You have no {mad_power} over me!")
print(f"Through {ploural_noun_list[0]} untold and {ploural_noun_list[1]} unnumbered I have {verb_list[0]} my way here to the {mad_castle} beyond the {mad_goblin} City to take back the {noun_list[0]} you have {verb_list[1]}, for my {noun_list[1]} is as strong as yours and my {noun_list[2]} as great. You have no {noun_list[3]} over me!")
ask_question = input("Do you want to try again?\n>")
if ask_question.lower() == "no":
print("Aww, well you're no fun.")
break
|
import random
import string
password_upper_letters = int(input("How many upper case letters should our password have?\n> "))
password_lower_letters = int(input("How many lower case letters should our password have?\n> "))
password_numbers = int(input("How many numbers should our password have?\n> "))
password_special_characters = int(input("How many special characters should our password have?\n> "))
pw_up_letters = ''
for num in range(password_upper_letters):
pw_up_letters += random.choice(string.ascii_uppercase)
pw_low_letters = ''
for num in range(password_lower_letters):
pw_low_letters += random.choice(string.ascii_lowercase)
pw_numbers = ''
for num in range(password_numbers):
pw_numbers += random.choice(string.digits)
pw_puncuations = ''
for num in range(password_special_characters):
pw_puncuations += random.choice(string.punctuation)
random_password = pw_up_letters + pw_low_letters + pw_numbers + pw_puncuations
rp_list = list(random_password)
random.shuffle(rp_list)
random_password = ''.join(rp_list)
print(f"Your random password is: {random_password}")
|
a = float(input('\033[1;35m''Qual a quantidade de Kms percorridos: Km: '))
b = float(input('\033[1;35m''Qual a quantidade de dias alugados: Dias: '))
aa = a*0.15
bb = b*60
print('\033[1;31m''_'*45)
print('O valor total a pagar é de: ''\033[4;32m''R$ {:.2f}''\033[m'.format(aa+bb))
print('\033[1;31m''_'*45) |
n = soma = cont = 0
while n != 999:
n = int(input('Digite um numero ou 999 para parar: '))
if n == 999:
break
cont += 1
soma += n
print(f'O programa foi encerrado e a soma dos {cont} valores digitados é de {soma}') |
largura = float(input('Qual a largura da sua parede? '))
altura = float(input('Qual a altura da sua parede? '))
area = largura*altura
print('Sua parede tem a dimenção de {}x{} e sua área é de {:.2f}'.format(largura,altura,area))
print('Para pintar sua parede, serão necessários {:.2F} litros de tinta.'.format(area/2)) |
n = 0
cont = 0
while n != 999:
n = int(input('Digite um numero ou 999 para parar: '))
cont += n
print(f'O número escolhido foi {n} e a soma até agora é de {cont}')
if n == 999:
cont - cont - 999
print(f'O programa foi encerrado e a soma até agora é de {cont}') |
#media de idade
#homem mais velho
#mulheres com menos de 20 anos
# Passo 1: Criar variáveis e importar libs
from statistics import mean #pegando a média
from time import sleep
nomem , nomef = [],[] #separando nomes em listas por sexo
idadem , idadef = [],[] #separando idades em listas por sexo
sexo_marculino , sexo_feminino = [],[] #separando listas por sexo
cont = 0 # Atribuindo variável de contagem
# Passo 2: Inputs das informações necessárias
for i in range(0,4): # Estabelecendo numeros de laços e separação das listas
sexo = (input('\nDigite (M) para Masculino ou (F) para Feminino: ')).capitalize()
sleep(0.5)
if sexo == 'M':
sexo_marculino.append('M')
elif sexo == 'F':
sexo_feminino.append('F')
else:
print('Você digitou um valor inválido.\nPor favor, reinicie o programa!!\n')
break
if sexo == 'M':
nomem.append (input('\nDigite seu nome: ').strip().title())
else:
nomef.append(input('\nDigite seu nome: ').strip().title())
if sexo == 'M':
idadem.append(int(input('\nDigite sua idade: ')))
else:
idadef.append(int(input('\nDigite sua idade: ')))
# Passo 3: Criar variáveis para resolução do 2º problema (nome do homem mais velho)
hmax = max(idadem) # atribuir idade máxima a uma variável
hmaxp = idadem.index(hmax) # ************ Localiza a posição na lista de acordo com o parametro"()" ******************
# Passo 4: Criar variáveis para resolução do 3º problema (mulheres abaixo dos 20 anos)
fmen = 0
fm = []
for f in idadef:
if f <= 20:
# print(f)
# print(fmen)
f = fmen + 1
fm.append(f)
# Passo 5: Imprimir as informações solicitadas
print(f'\nA média das idades é {mean(idadem+idadef):.2f}.' # Chamo a função média da LIB statistcs
f'\nO homen mais velho é {nomem[hmaxp]}' # Chamo o format da lista "nomem" passando o parametro da hmaxp
# achado atravez do index
f'\nA quantidade de mulheres abaixo de 20 anos é de {len(fm)}')
#print(fm)
#print(f'{nomem}\n{nomef}\n{idadem}\n{idadef}\n{sexo_marculino}\n{sexo_feminino}')
#print(hmaxp)
#print(hmax)
#hmax = max(idadem) #atribuir idade máxima a uma variável """ex linha 28"""
#for hmax in idadem: ex linha 29
# while idadem != hmax:
# print('.')
# cont += 1
#print(cont)
|
# Mark Tarakai
# CS5400: Introduction to Artificial Intelligence -- Section 1A
# Puzzle Assignment Series: Mechanical Match -- Segment II
# Iterative-deepening Depth-limiting Search
# Necessary libraries
from copy import deepcopy
import time
import sys
# Read in the puzzle file to instantiate the puzzle. The puzzle file is
# specified on the command line and the argument is parsed below.
# NEW FEATURE: As requested by the TAs, correct format is handled, and lack
# of parameter is handled. This can handle any file of type 'puzzle*.txt' and
# will produce the associated 'solution*.txt'
try:
sys.argv[1]
except:
print("Execution Failure:")
print("No parameter detected. Retry with correct file as parameter.")
quit()
exec_param = sys.argv[1]
if exec_param[0:6] != "puzzle":
print("Execution Failure:")
print("Please use specified files from problem prompt: 'puzzle*.txt'.")
quit()
if exec_param[7:11] != ".txt":
print("Execution Failure:")
print("Incorrect format. Please retry with specified 'puzzle*.txt' files.")
quit()
else:
file = open(exec_param,'r')
# This function creates the puzzle object, and reads in the correct pieces from
# the problem prompt. It reads in everything as ints, and iteratively places the
# pieces into the puzzle. Whitespace is stripped.
class Puzzle:
quota = int(file.readline())
maxSwaps = int(file.readline())
deviceTypes = int(file.readline())
gridWidth = int(file.readline())
gridHeight = int(file.readline())
poolHeight = int(file.readline())
bonusRules = file.readline()
grid = []
# Push the puzzle into a 2D array
for i in range(gridHeight):
grid.append([0 for i in range(gridWidth)])
for i in range(gridHeight):
line = file.readline()
line = "".join(line.split())
for j, num in enumerate(line):
grid[i][j] = int(num)
# Create state object, constructor takes parameters from a puzzle class object,
# score is placed here.
class State:
def __init__(self, grid, gridWidth, gridHeight, poolHeight,
deviceTypes, score = 0):
self.grid = deepcopy(grid)
self.gridWidth = gridWidth
self.gridHeight = gridHeight
self.poolHeight = poolHeight
self.deviceTypes = deviceTypes
self.score = score
# Create node object for BFTS with all the criteria from both the professor
# and textbook. Constructor sets them initially to none-type, with a 0 pathcost
class Node:
def __init__(self, State = None, Parent = None, Action = None,
pathCost = 0):
self.State = State
self.Parent = Parent
self.Action = Action
self.pathCost = pathCost
# This is a data structure used to hold the frontier. It is a queue and
# it features all of the generic operations, ones needed for this problem
# This is not required for this ID-DLS implementation, as it works
# recursively and takes advantage of the call stack. If a data structure were
# used, the implementation would involve a STACK due to the LIFO nature of DLS.
'''
class Queue():
def __init__(self):
self.structure = []
def push(self,item):
self.structure.insert(0,item)
def pop(self):
return self.structure.pop()
def isEmpty(self):
return self.structure == []
def howBig(self):
return len(self.structure)
'''
# This function finds a matching row, so if a row/col has three or more,
# the function places the coordinates of those in a list, which is
# passed to a function to make 0.
def findMatches(grid, gridWidth, gridHeight, poolHeight):
makeVacant = []
for i in range(poolHeight, gridHeight):
sameCheck = 0
matchQuant = 0
for j in range(gridWidth):
if j == 0:
sameCheck = grid[i][j]
else:
if sameCheck == grid[i][j]:
matchQuant = matchQuant + 1
if matchQuant >= 2 and j == gridWidth - 1:
for n in range(matchQuant + 1):
makeVacant.append((i, j-n))
else:
if matchQuant < 2:
sameCheck = grid[i][j]
matchQuant = 0
else:
for n in range(matchQuant +1):
makeVacant.append((i, j-1-n))
sameCheck = grid[i][j]
matchQuant = 0
# check the columns for matches
for j in range(gridWidth):
sameCheck = 0
matchQuant = 0
for i in range(poolHeight, gridHeight):
if i == 0:
sameCheck = grid[i][j]
else:
if sameCheck == grid[i][j]:
matchQuant = matchQuant + 1
if matchQuant >= 2 and i == gridHeight - 1:
for n in range(matchQuant + 1):
makeVacant.append((i-n,j))
elif sameCheck != grid[i][j]:
if matchQuant < 2:
sameCheck = grid[i][j]
matchQuant = 0
else:
for n in range(matchQuant + 1):
makeVacant.append((i-1-n,j))
sameCheck = grid[i][j]
matchQuant = 0
return makeVacant
# This function makes the list of needed vacancies, vacant.
def Vacantize(makeVacant, grid):
for i in makeVacant:
grid[i[0]][i[1]] = 0
# This function fills the board vacancies, it handles the cascading effect
# desired by the instructor, and gets a new device.
def fillBoard(deviceTypes, grid, gridWidth, gridHeight, poolHeight):
numReplaced = 0
for i in range(poolHeight, gridHeight):
for j in range(gridWidth):
if grid[i][j] == 0:
for x in range(i):
grid[i-x][j] = grid[i-x-1][j]
numReplaced = numReplaced + 1
grid[0][j] = makeNewDevice(grid,deviceTypes,j,numReplaced)
# This function fabricates a new device to place on the board, as asked by the
# fill board function. It uses the formula given in the Puzzle Assignment
# Series prompt.
def makeNewDevice(grid, deviceTypes, j, numReplaced):
deviceType = grid[1][j]
newDevice = ((int(deviceType)+j+numReplaced)%deviceTypes)+1
return newDevice
# This function is not needed for any type of purpose, but allows the user
# to print a well-formatted grid if needed. Particularly useful if code is
# to be tested in Python IDLE.
def gridPrint(grid):
for row in grid:
print(*row)
# Look operations, these four functions return the device value in the direction
# specified. This methodology was adapted to avoid full board scans for every
# swap.
def lookUp(grid, i, j, poolHeight):
if i-1 >= poolHeight:
return grid[i-1][j]
else:
return 0
def lookDown(grid, i, j, gridHeight):
if i+1 < gridHeight:
return grid[i+1][j]
else:
return 0
def lookRight(grid, i, j, gridWidth):
if j+1 < gridWidth:
return grid[i][j+1]
else:
return 0
def lookLeft(grid, i, j):
if j-1 > 0:
return grid[i][j-1]
else:
return 0
'''
This is the possible actions function specified by the textbook and professor.
The logic is extremely difficult to derive from the code, due to the nature
of the traversals, but will be broken down here. The two scan directions are
vertical and horizontal, and they are individual processes in the function.
For both, the function appends the first element in the grid to a list. Then
it is compared to the next one, if this matches, it continues. If this does not
match, it looks down and looks up to see if a middle swap is possible. If this
is not possible it moves. An identical process occurs for the vertical swaps.
It then returns a set of tuples of two coordinates (in one tuple). These are
the possible swaps for the given state, a parameter in the function call.
'''
def Actions(s):
possibleActions = set()
for i in range(s.poolHeight, s.gridHeight):
tempMatch = []
size_match = len(tempMatch)
for j in range(s.gridWidth):
if j == 0:
tempMatch.append(s.grid[i][j])
else:
if s.grid[i][j] == tempMatch[0]:
tempMatch.append(s.grid[i][j])
if j == s.gridWidth-1:
if len(tempMatch) > 1:
if lookUp(s.grid,i,j-2,
s.poolHeight) == tempMatch[0]:
if(i-1,j-2,i,j-2) not in possibleActions:
possibleActions.add((i,j-2,i-1,j-2))
if lookLeft(s.grid,i,j-2) == tempMatch[0]:
if(i,j-3,i,j-2) not in possibleActions:
possibleActions.add((i,j-2,i,j-3))
if lookDown(s.grid,i,j-2,
s.gridHeight) == tempMatch[0]:
if(i-1,j-2,i,j-2) not in possibleActions:
possibleActions.add((i,j-2,i-1,j-2))
else:
if len(tempMatch) > 1:
# right of match sequence
if lookUp(s.grid, i, j, s.poolHeight) == tempMatch[0]:
if (i-1,j,i,j) not in possibleActions:
possibleActions.add((i,j,i-1,j))
if lookRight(s.grid, i, j, s.gridWidth) == tempMatch[0]:
if (i,j+1,i,j) not in possibleActions:
possibleActions.add((i,j,i,j+1))
if lookDown(s.grid, i, j, s.gridHeight) == tempMatch[0]:
if (i+1,j,i,j) not in possibleActions:
possibleActions.add((i,j,i+1,j))
# left of match sequence
if j-(len(tempMatch)+1) >= 0:
if lookUp(s.grid, i, j-(len(tempMatch)+1),
s.poolHeight) == tempMatch[0]:
if (i-1,j-(len(tempMatch)+1),i,
j-(len(tempMatch)+1)) not in possibleActions:
possibleActions.add((i,j-(len(tempMatch)+1),
i-1,j-(len(tempMatch)+1)))
if lookDown(s.grid, i, j-(len(tempMatch)+1),
s.gridHeight) == tempMatch[0]:
if (i+1,j-(len(tempMatch)+1),i,
j-(len(tempMatch)+1)) not in possibleActions:
possibleActions.add((i,j-(len(tempMatch)+1),
i+1,j-(len(tempMatch)+1)))
if lookLeft(s.grid, i,
j-(len(tempMatch)+1)) == tempMatch[0]:
if (i,j-(len(tempMatch)+2),i,
j-(len(tempMatch)+1)) not in possibleActions:
possibleActions.add((i,j-(len(tempMatch)+1),
i,j-(len(tempMatch)+2)))
else:
# discover if swapping the middle yields a match
if j+1 < s.gridWidth:
if s.grid[i][j+1] == tempMatch[0]:
if lookUp(s.grid, i, j,
s.poolHeight) == tempMatch[0]:
if (i-1,j,i,j) not in possibleActions:
possibleActions.add((i,j,i-1,j))
if lookDown(s.grid, i, j,
s.poolHeight) == tempMatch[0]:
if (i+1,j,i,j) not in possibleActions:
possibleActions.add((i,j,i+1,j))
tempMatch = []
tempMatch.append(s.grid[i][j])
for j in range(s.gridWidth):
tempMatch = []
for i in range(s.poolHeight,s.gridHeight):
if i == s.poolHeight:
tempMatch.append(s.grid[i][j])
else:
if s.grid[i][j] == tempMatch[0]:
tempMatch.append(s.grid[i][j])
if i == s.gridHeight-1:
if len(tempMatch) > 1:
if lookUp(s.grid,i-2,j,
s.poolHeight) == tempMatch[0]:
if(i-3,j,i-2,j) not in possibleActions:
possibleActions.add((i-2,j,i-3,j))
if lookLeft(s.grid,i-2,j) == tempMatch[0]:
if(i-2,j-1,i,j) not in possibleActions:
possibleActions.add((i-2,j,i-2,j-1))
if lookRight(s.grid,i-2,j,
s.gridWidth) == tempMatch[0]:
if(i-2,j+1,i-2,j) not in possibleActions:
possibleActions.add((i-2,j,i-2,j+1))
else:
if len(tempMatch) > 1:
# bottom of match sequence
if lookLeft(s.grid,i,j) == tempMatch[0]:
if(i,j-1,i,j) not in possibleActions:
possibleActions.add((i,j,i,j-1))
if lookDown(s.grid,i,j,s.gridHeight) == tempMatch[0]:
if(i+1,j,i,j) not in possibleActions:
possibleActions.add((i,j,i+1,j))
if lookRight(s.grid,i,j,s.gridWidth) == tempMatch[0]:
if(i,j+1,i,j) not in possibleActions:
possibleActions.add((i,j,i,j+1))
# top of match sequence
if i-(len(tempMatch)+1) >= s.poolHeight:
if lookLeft(s.grid, i-(len(tempMatch)+1),
j) == tempMatch[0]:
if (i-(len(tempMatch)+1),j-1,
i-(len(tempMatch)+1),
j) not in possibleActions:
possibleActions.add((i-(len(tempMatch)+1),
j,i-(len(tempMatch)+1),j-1))
if lookUp(s.grid,i-(len(tempMatch)+1),j,s.poolHeight) == tempMatch[0]:
if(i-(len(tempMatch)+2),j,i-(len(tempMatch)+1),j) not in possibleActions:
possibleActions.add((i-(len(tempMatch)+1),j,i-(len(tempMatch)+2),j))
if lookRight(s.grid,i-(len(tempMatch)+1),j,s.gridWidth) == tempMatch[0]:
if (i-(len(tempMatch)+1),j+1,i-(len(tempMatch)+1),j) not in possibleActions:
possibleActions.add((i-(len(tempMatch)+1),j,i-(len(tempMatch)+1),j+1))
else:
# discover if swapping the middle yields a match
if i+1 < s.gridHeight:
if s.grid[i+1][j] == tempMatch[0]:
if lookLeft(s.grid,i,j) == tempMatch[0]:
if(i,j-1,i,j) not in possibleActions:
possibleActions.add((i,j,i,j-1))
if lookRight(s.grid,i,j,
s.gridWidth) == tempMatch[0]:
if(i,j+1,i,j) not in possibleActions:
possibleActions.add((i,j,i,j+1))
tempMatch = []
tempMatch.append(s.grid[i][j])
return possibleActions
# This function performs the actual swap. It takes the action and state to
# perform the operation to a grid by reference
def swap(s,a):
i_to = a[0]
j_to = a[1]
i_from = a[2]
j_from = a[3]
temp = s.grid[i_from][j_from]
s.grid[i_from][j_from] = s.grid[i_to][j_to]
s.grid[i_to][j_to] = temp
# This functions stabilizes the board. It continues to fill and match until the
# match location list is empty. No matches remain if this is reached.
def stabilizeBoard(s):
match_loc = findMatches(s.grid,s.gridWidth,s.gridHeight,s.poolHeight)
while match_loc:
for loc in match_loc:
s.score = s.score + 1
Vacantize(match_loc,s.grid)
fillBoard(s.deviceTypes, s.grid, s.gridWidth, s.gridHeight,
s.poolHeight)
match_loc = findMatches(s.grid,s.gridWidth,s.gridHeight,s.poolHeight)
# This function is the TRANSITION MODEL, it takes a state and action and returns a
# new state based on those two parameters. It performs the necessary operations,
# and "brings together" the rest of the program, by performing the action,
# stabilizing the board and returning a new state with this information
def Result(s,a):
newState = State(s.grid,s.gridWidth,s.gridHeight,s.poolHeight,
s.deviceTypes,s.score)
swap(newState,a)
stabilizeBoard(newState)
return newState
# This function creates child-nodes. It creates an Node object based on state
# of parent, path-cost, and action and returns it for use in the pertinent
# algorithm
def ChildNode(parent,a):
childNode = Node(Result(parent.State, a), parent, a,
parent.pathCost + 1)
return childNode
# This solves the puzzle and appends the parent nodes to a solution list
# to follow the traversal of the tree. It continues while the parent does
# not exist.
def Solve(node):
solution = []
while node.Parent != None:
solution.append(node.Action)
node = node.Parent
return solution
'''
This function is an exact copy of the ID-DLS given in lecture by the professor.
The framework involves three functions, which is identical to the textbook.
These will be visited and described individually for clarity of their purpose.
'''
# This is the operating environment for the Recursive DLS function. It creates
# a state object with the initial conditions. It also creates the root node
# with the initial state and feeds that to the first function call to the R_DLS
# The result from here is returned to the driving function, the ID_DLS
def DLS(puzzle,limit):
init_state = State(newPuzzle.grid,newPuzzle.gridWidth,newPuzzle.gridHeight,
newPuzzle.poolHeight,newPuzzle.deviceTypes,0)
init_node = Node(init_state)
return Recursive_DLS(init_node,puzzle,limit)
'''
This function follows the recursive implementation of DLS in the textbook.
If the goal state is reached, it is appended to the solution list and passed to
the print function. Otherwise, the result follows the depth and increments down
to the root each time with the limit-1 parameter in the recursive call. If the
cutoff finally overcome, it is returned to the DLS.
'''
def Recursive_DLS(node,puzzle,limit):
if node.State.score >= newPuzzle.quota:
sol = Solve(node)
return sol
elif limit == 0:
return "cutoff"
else:
cutoff_occurred = False
actionSet = Actions(node.State)
for action in actionSet:
child = ChildNode(node,action)
result = Recursive_DLS(child,puzzle,limit-1)
if result == "cutoff":
cutoff_occurred = True
else:
return result
if cutoff_occurred:
return "cutoff"
else:
return []
# This is the driving function for the ID_DLS. The depth is incremented every
# time a cutoff is reached, and returns the result if the R_DLS doesn't return
# cutoff. This ensure that only the optimal depth is reached.
def ID_DLS(puzzle):
depth = 0
result = "cutoff"
while result == "cutoff":
result = DLS(puzzle,depth)
if result == "cutoff":
depth = depth + 1
return result
'''
This function takes the solution, the puzzle, and the time taken and prints it
out to a text file 'solution*.txt'. This assumes the file follows the
'puzzle*.txt' format and will create a solution*.txt output file based on the
input file. It also writes execution time and is formatted exactly to course
regulations.
'''
def printOut(Puzzle, Solution, TimeTaken):
file_name = "solution"+exec_param[6]+".txt"
solfile = open(file_name, 'w')
quota = str(Puzzle.quota) + "\n"
maxSwaps = str(Puzzle.maxSwaps)+"\n"
devicetypes = str(Puzzle.deviceTypes)+"\n"
gridWidth = str(Puzzle.gridWidth)+"\n"
gridHeight = str(Puzzle.gridHeight)+"\n"
poolHeight = str(Puzzle.poolHeight)+"\n"
bonusRules = str(Puzzle.bonusRules)
solfile.write(quota)
solfile.write(maxSwaps)
solfile.write(devicetypes)
solfile.write(gridWidth)
solfile.write(gridHeight)
solfile.write(poolHeight)
solfile.write(bonusRules)
for Row in Puzzle.grid:
for num in Row:
PrintNum = str(num)+" "
solfile.write(PrintNum)
solfile.write("\n")
if solution == []:
solfile.write("No Solution")
else:
for swap in reversed(solution):
solfile.write("({},{}),({},{})\n".format(swap[1],swap[0],
swap[3],swap[2]))
TimeTaken = str(TimeTaken)
solfile.write(TimeTaken)
solfile.close()
newPuzzle = Puzzle()
start = time.clock()
solution = ID_DLS(newPuzzle)
total = (time.clock() - start)
printOut(newPuzzle, solution, total)
file.close() |
print "raw_input returns a string"
raw = raw_input("Enter a string: ")
print type(raw)
print "input preserves type (used for int or float)"
a = input("Enter a number: ")
print type(a)
|
#this program recieves personal information from users
print("Personal Information")
name=input("What is your name?")
age=input("How old are you?")
d_o_b=input("When were you born?")
home_address=input("Where do you live?")
school_name=input("What school do you attend?")
sex=input("Are you male or female?")
print("Nice to meet you"+name)
|
#this file is making the main code run
import tictactoeiteration1lvl
a = tictactoeiteration1lvl.Game()
print("X or O")
x=input()
if x == "X":
a.user_sign = "X"
else:
a.user_sign = "O"
print("Wanna play first.. (type \'yes\' or \'no\')")
get_input = input()
if get_input == "yes":
a.display()
while True:
if a.winner == None:
a.user_play()
if a.winner == None:
a.cpu_play()
else:
break
print("Game Ends..! Congratulations to %s i.e. our winner" % a.winner)
else:
while True :
if a.winner == None:
a.cpu_play()
if a.winner == None:
a.user_play()
else:
break
print("Game Ends..! Congratulations to %s i.e. our winner" % a.winner)
|
class driver():
@staticmethod
def age(x):
if x>=18:
print("you are free to drive a car in india.")
else:
print("you are not alowed to drive a car in India")
driving = driver()
x = int(input("what is your age: "))
driving.age(x)
|
class Employee:
raise_amount = 1.04
def __init__(self, firstName, lastName, salary):
self.first = firstName
self.last = lastName
self.pay = salary
def fullName(self):
return ('{} {}' .format(self.first, self.last))
def currentSalary(self):
self.pay = int(self.pay*self.raise_amount)
return self.pay
#subclass of Employee superclass
class Developer(Employee):
raise_amount=1.10
def __init__(self, firstName, lastName, salary, prog_lang):
super().__init__(firstName, lastName, salary)
self.prog_lang = prog_lang
def details(self):
return('\nName: {} {} \n salary: {} \n Proficiency: {}'.format(self.first, self.last, self.pay, self.prog_lang))
#subclass of Employee
class Manager(Employee):
def __init__(self, firstName, lastName, salary, employees = None):
super().__init__(firstName, lastName, salary)
if employees is None:
self.employees=[]
else:
self.employees=employees
emp=Employee('Neville', 'Lusimba', 50000)
#We can raise the salary of an individual by applying a percentage increment
emp1 = Developer('Brian', 'Sim', 90000, 'Python')
print (emp1.currentSalary()) |
#EXAMPLES OF TUPLES
tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
#empty tuple
tup1 = ()
#one value tuple (needs a comma after)
tup1 = (50,)
#Accessing Values in Tuples
tup4 = ('physics', 'chemistry', 1997, 2000)
tup5 = (1, 2, 3, 4, 5, 6, 7 )
print ("tup4[0]: ", tup1[0])
print ("tup5[1:5]: ", tup2[1:5])
tup6= (12, 34.56)
tup7 = ('abc', 'xyz')
# Following action is not valid for tuples
# tup1[0] = 100;
# So let's create a new tuple as follows
tup8 = tup6 + tup7
print (tup8)
#Basic Tuples Operations
len((1, 2, 3))
(1, 2, 3) + (4, 5, 6)
('Hi!',) * 4
3 in (1, 2, 3)
for x in (1,2,3) : print (x, end = ' ')
#Indexing, Slicing, and Matrixes
T=('C++', 'Java', 'Python')
print(T[2])
print(T[-2])
print(T[1:]) |
"""
We have a list of Annual rainfall recordings of cities. Each element in the list is of the form (c, r) where c is the city and r is
the annual rainfall for a particular year. The list may have multiple entries for the same city, corresponding to rainfall recordings
in different years.
Write a Python function rainaverage(l) that takes as input a list of rainfall recordings and comptes the average rainfall for each city.
The output should be a list of pairs (c, ar) where c is the city and ar is the average rainfall for this city among recordings in the same
input list. The output should be sorted in the dictionary with respect to the city name
"""
def Convert(tup, di):
for a, b in tup:
di.setdefault(a, []).append(b)
return di
# Driver Code
citav = [('Bombay', 848), ('Madras', 103),('Bombay', 923),('Bangalore', 201), ('Madras', 128), ('Bangalore', 201.0),('Bombay', 885.5), ('Madras', 115.5)]
dictionary = {}
x = Convert(citav, dictionary)
B = x['Bombay']
M = x['Madras']
Ba = x['Bangalore']
def rainaverage(B):
for x in range(len(B)):
sum = 0
sum +=B[x]
return sum
Bombay = rainaverage(B)
Madras = rainaverage(M)
Bangalore = rainaverage(Ba)
Avlist = [ ('Bangalore', Bangalore), ('Bombay', Bombay), ('Madras', Madras)]
print(Avlist)
|
# First, import the fractions module and extract the class Fraction
from fractions import Fraction
#You can use the fraction (entered as (numerator, denominator)) in any context as any other integer or floating point number
f = Fraction(3, 4)
print (f)
y= 3
def sum (f, y):
return f+y
print (sum(f, y)) |
numbers = [1,2,3,4,5]
def square(x):
return x**2
print(list(map(square,numbers)))
print(list(map(lambda x: x**2,numbers))) |
import numpy as np
#Input array
X=np.array([[1,0,1,0],[1,0,1,1],[0,1,0,1]])
#Output
y=np.array([[1],[1],[0]])
#Sigmoid Function
def sigmoid (x):
return 1/(1 + np.exp(-x))
#Derivative of Sigmoid Function
def derivatives_sigmoid(x):
return x * (1 - x)
#Variable initialization
epoch=5000
#Setting training iterations
lr=0.1
#Setting learning rate
inputlayer_neurons = X.shape[1]
#number of features in data set
hiddenlayer_neurons = 3
#number of hidden layers neurons
output_neurons = 1
#number of neurons at output layer
#weight and bias initialization
wh=np.random.uniform(size=(inputlayer_neurons,hiddenlayer_neurons))
bh=np.random.uniform(size=(1,hiddenlayer_neurons))
wout=np.random.uniform(size=(hiddenlayer_neurons,output_neurons))
bout=np.random.uniform(size=(1,output_neurons))
for i in range(epoch):
#Forward Propogation
hidden_layer_input1=np.dot(X,wh)
hidden_layer_input=hidden_layer_input1 + bh
hiddenlayer_activations = sigmoid(hidden_layer_input)
output_layer_input1=np.dot(hiddenlayer_activations,wout)
output_layer_input= output_layer_input1+ bout
output = sigmoid(output_layer_input)
#Backpropagation
E = y-output
slope_output_layer = derivatives_sigmoid(output)
slope_hidden_layer = derivatives_sigmoid(hiddenlayer_activations)
d_output = E * slope_output_layer
Error_at_hidden_layer = d_output.dot(wout.T)
d_hiddenlayer = Error_at_hidden_layer * slope_hidden_layer
wout += hiddenlayer_activations.T.dot(d_output) *lr
bout += np.sum(d_output, axis=0,keepdims=True) *lr
wh += X.T.dot(d_hiddenlayer) *lr
bh += np.sum(d_hiddenlayer, axis=0,keepdims=True) *lr
print (output)
|
wakeup_times = [16, 49, 3, 12, 56, 49, 55, 22, 13, 46, 19, 55, 46, 13, 25, 56, 9, 48, 45,0]
def bubble_sort_1(l):
# TODO: Implement bubble sort solution
for i in range(len(l)-1):
for j in range(len(l)-1):
if l[j]>l[j+1]:
l[j],l[j+1] =l[j+1], l[j]
bubble_sort_1(wakeup_times)
print("Pass" if (wakeup_times[0] == 0) else "Fail")
|
# action.py: The Action class!
#
# Some Documentation:
#
# Actions have different types, and these different types have different attributes to go with them
# (Sort of like pygame events)
#
# The constructor format is as follows:
# Action(type (string), description (string), start (datetime), duration (timedelta), params (a list of additional parameters))
#
# The different types are:
# testType: No special parameters (just pass None as params), used for debugging purposes
# movement: When the player moves from one tile to another.
# params[0] should be a path of tiles to go through,
# params[1] should be a string representing their method of moving (ie walking, bike, car, etc).
# The duration field should be None to calculate based on params[1]
# After initialisation, self.path is the path, self.method is the method of transport.
# scavenge: When the player is scavenging a tile for supplies.
# params[0] should be the location.
# After initialisation, self.location is the location.
# fortify: When the player strengthens the tile to better defend against invading zombies.
# params[0] should be the location,
# params[1] should be the list of supplies (or just amount, depends how we implement) used for fortification
# (or pass None, this makes the player attempt to fortify with what they have).
# After initialisation, self.location is the location, self.supplies is the list of supplies.
# sweep: When the player "sweeps" an area for zombies
# params[0] should be the location.
# After initialisation, self.location is the location.
import math
import datetime
class Action:
WALKING_SPEED = 1.0 #tiles/minute
def __init__(self, type, desc, startTime, duration, params):
"""Actions are of different types, have a description, parameters based on type, and a start time and duration"""
self.type = type
self.desc = desc
self.startTime = startTime
self.duration = duration
#TestType
if self.type == "testType":
pass
#Movement
elif self.type == "movement":
#Put the params in!
self.path = params[0] #NOTE: In current implementation, path is only two nodes long... FIX LATER
self.method = params[1]
#Calculate the actual duration
#Currently ignores method
#distance = math.sqrt(math.fabs((self.path[len(self.path)-1][0] - self.path[0][0])**2+(self.path[len(self.path)-1][1] - self.path[0][1])**2))
distance = len(self.path) - 1
self.duration = datetime.timedelta(minutes = distance/Action.WALKING_SPEED)
#Scavenging
elif self.type == "scavenge":
pass
#Fortification
elif self.type == "fortify":
pass
#Sweep
elif self.type == "sweep":
pass
#Invalid
else:
print "Invalid Action Type!"
def isDone(self, currTime):
return self.startTime + self.duration <= currTime
def isStarted(self, currTime):
return self.startTime < currTime
def timeRemaining(self, currTime):
return (self.startTime + self.duration) - currTime
|
# 不定長度參數
def sum01(*m,**n): # *可變的參數串列 , **可變的字典列表 涵義不同,順序不可對調
print(m)
print(n)
sum01(1,2,3)
sum01(a=10,b=20,c=30)
sum01(1,2,3,a=10,b=20,c=30)
# sum01(a=10,b=20,c=30,1,2,3) # 格式不符合無法執行
print(sum([10,20])) # 原始sum函數用法
# 一級函式可修改名稱
print(type(sum01))
s = sum01
print(s(5,6,7)) |
# list (append,insert,remove), set (add),
"""
s = [10,20,30]
print(s)
print(type(s))
print(s[0])
print(s[1])
print(s[2])
s.append(40)
print(s)
s.insert(2,10)
print(s)
s.remove(20)
print(s)
"""
t = {10,30,20} # set 用大括弧 (類似dict但沒有key跟冒號 dict01 = {id_01 : apple})
print(t)
print(type(t))
t.add(25) # set加入元素必須用add(不可用append,insert), 加入的元素順序沒有一定, set元素可用remove移除
print(t)
t.remove(20)
print(t)
t2 = list(t) # set轉list
print(t2)
print(type(t2))
|
# type的練習 + 參數格式化( %() 與 .format )用在print的練習
'''
name = "Maud"
health = 746.567
nstr = 20
nint = 18
nluk = 44
#參數格式化 by %()
print("%s is your character\'s name. \t %s will start their travel." %(name, name)) # %() 參數格式化,一個蘿蔔一個坑的概念
print("%s is your character\'s name. \t %s will start their travel." %(name, name), end=" ...\n=================\n")
print("%s \'s health is %d." %(name, health)) # %()內填入的變數需要1.依出現順序排列、2.宣告+前面句子的type相符(浮點與整數可互換),不然會出錯
print("health is %d, %s is alive." %(health, name))
print("health is %5d, %5s is alive." %(health, name)) # %5d 整數固定為5位數(沒有數值則用空白補上)
print("health is %8.2d, %5s is alive." %(health, name)) # %8.2f 數固定為8位數(包含小點+小數)(沒有數值則用空白補上),小數點捨入至後二位,但%d強制捨去小數,故不顯示
print("health is %s, %s is alive." %(health, name))
print("health is %f, %s is alive." %(health, name))
print("health is %.2f, %s is alive." %(health, name)) # %.2f 小數點捨入至後二位
print("health is %6.8f, %s is alive." %(health, name)) # %6.8f 數固定為14位數(包含小點+小數)(沒有數值則用空白補上),小數點捨入至後八位
print("health is %2.8f, %s is alive." %(health, name)) # %2.8f 數固定為二位數(包含小點+小數)(超過則不補空白),小數點捨入至後八位
#參數格式化 by format
print("力量:%d、法力:%d、運氣:%d" %(nstr, nint, nluk)) #參數格式化 by %(),對照組
print("力量:{}、法力:{}、運氣:{}".format(nstr, nint, nluk)) #參數格式化 by format,類似 %() 但優點是不須再前面句子定義變數type
# round 四捨五入 (不是小數捨去)
pi=3.141592653589
print("pi is ",pi , end=".\n")
print("pi is ",round(pi,3) , end=".\n")
print("pi is ",round(pi,4) , end=".\n")
print("pi is ",round(pi,5) , end=".\n")
print("pi is ",round(pi,6) , end=".\n")
'''
# 變數type辨別與轉換
# 轉換成int int(變數名稱)
# float float(變數名稱)
# string str(變數名稱)
# 用油量與油價計算
kl = input("輸入公升數: ") # 變數kl被系統默認為 字串,導致無法無法做後續浮點數運算
print(type(kl)) # 檢測變數kl的type
print("================")
kl=float(kl)
print(type(kl)) # 修改type後,再次檢測變數kl的type
oil_price = 21.8 #2020.03.21 95價格
cal = oil_price * kl
print("您共需付{}元,謝謝您的惠顧~" .format(cal))
print(type(cal))
exit() |
l1=['a','b']
l2=['c','d']
l3=[]
for i in l2:
l=[j+i for j in l1]
l3.append(l)
print l3
|
def fine(d1,m1,y1,d2,m2,y2):
return_date = d1
due_date = d2
fine = 0
#check year
if(y1>y2):
fine = 10000
print(fine)
return fine
#check month
elif(m1>m2 and y1==y2):
fine = 500*(m1-m2)
print(fine)
return fine
#check day
elif(d1>d2 and y1==y2 and m1==m2):
fine = 15*(d1-d2)
print(fine)
return fine
#if returned before the date
else:
fine = 0
print(fine)
return fine
fine(9,6,2015,6,6,2015) |
def reduceString(str):
stringList = list(str)
answer = []
joined = ''
i = 0
while i < len(stringList):
if i == len(stringList)-1:
answer.append(stringList[i])
print 'trig'
i = i+1
if i < len(stringList):
if stringList[i] != stringList[i+1]:
answer.append(stringList[i])
i = i + 1
else:
i = i + 2
if len(answer) == 0:
print 'Empty String'
else:
separator = ''
joined = separator.join(answer)
print joined
reduceString('acdqglrfkqyuqfjkxyqvnrtysfrzrmzlygfveulqfpdbhlqdqrrqdqlhbdpfqluevfgylzmrzrfsytrnvqyxkjfquyqkfrlacdqj') |
Squares = int(input("Enter a value:"))
i = 1
sum = 0
while(i<=Squares):
sum = sum+(i**2)
i = i+1
if i>= Squares:
print ("Sum of square is:",sum) |
print("LUTFEN AKLINIZDA 0-100 ARASI BIR SAYI TUTUNUZ... ")
tahmin = 50
yuksek =[100]
dusuk = [0]
while True:
if not tahmin==99:
tahmin = (max(dusuk) + min(yuksek))/2
tahmin = int(tahmin)
else:
tahmin = tahmin + 1
print("PC' nin tahmini = " , tahmin)
sonuc = input("Tahminimiz buyukse '-', Kucukse '+', Dogru ise 'enter' tusuna basiniz :")
if sonuc=="+":
dusuk.append(tahmin)
elif sonuc=="-":
yuksek.append(tahmin)
elif sonuc=="":
print("TEBRIKLER KAZANDINIZ")
break
else:
print("Hatali Islem : Lutfen istenilen sembollerden birini giriniz...")
|
import datetime
import time
class Timer:
def __init__(self):
self.dictStartTime = {'__init__': time.time()}
self.dictEndTime = {}
def startTimer(self, desc):
self.dictStartTime[desc] = time.time()
def endTimer(self, desc):
self.dictEndTime[desc] = time.time()
return self.dictEndTime[desc] - self.dictStartTime[desc]
def currElapseTime(self, desc):
return time.time() - self.dictStartTime[desc]
def elapseTime(self, desc):
return self.dictEndTime[desc] - self.dictStartTime[desc]
def strElapseTime(self, desc):
return Timer.makeStrElapseTime(self.dictEndTime[desc]
- self.dictStartTime[desc])
@staticmethod
def makeStrElapseTime(elapseTime):
return datetime.timedelta(seconds=elapseTime)
|
word=input("enter a word")
list=[ord(x) for x in word]
print(list) |
def longestword(word):
final = []
for i in word:
final.append((len(i), i))
final.sort()
print("The longest word in the list is:", final[-1][1], " and its length is:", len(final[-1][1]))
a = []
n = int(input("Enter the no of words:"))
for i in range(0, n):
w = input("Enter the word:")
a.append(w)
longestword(a) |
class Publisher:
"information about books"
def __init__(self, pubname):
self.pubname = pubname
def display(self):
print("Publisher Name:", self.pubname)
class Book(Publisher):
def __init__(self, pubname, title, author):
Publisher.__init__(self, pubname)
self.title = title
self.author = author
def display(self):
print("Title: ", self.title)
print("Author: ", self.author)
class Python(Book):
def __init__(self, pubname, title, author, price, no_of_pages):
Book.__init__(self, pubname, title, author)
self.price = price
self.no_of_pages = no_of_pages
def display(self):
print("Title: ", self.title)
print("Author: ", self.author)
print("Price: ", self.price)
print("Number of pages: ", self.no_of_pages)
s1 = Python("ak books", "Taming Python By Programming ", ' Jeeva Jose ', 200, 219)
s1.display() |
class Bank:
accountNo = "no.txt"
name = "name.txt"
typeOfAccount = "acc.txt"
balance = 0
def __init__(self,accountNo,name,typeOfAccount,balance):
self.accountNo = accountNo
self.name = name
self.typeOfAccount = typeOfAccount
self.balance = balance
def deposit(self,amount):
self.balance = self.balance + amount
def withdraw(self,amount):
self.balance = self.balance - amount
acc1 = Bank("ACC31323","Laika","Savings",10000)
acc2 = Bank("ACC09932","Megan","Current",8400)
acc1.withdraw(4531)
acc2.deposit(5600)
print(acc1.balance)
print(acc2.balance) |
"""
Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês. Calcule e mostre o total do seu salário no referido mês.
"""
valor_hora = float(input("Valor da hora trabalhada: "))
horas_mes = int(input("Quantos horas trabalha por mes? "))
salario = valor_hora*horas_mes
print("O salario é R$6{}".format(salario))
|
#function for checking if a number is prime
def is_prime_number(x):
if x >= 2:
for y in range(2,x):
if not ( x % y ):
return False
else:
return False
return True
#function for XORing two strings
def XOR(a,b):
a,b = str(a),str(b)
assert(len(a) <= len(b))
result = ""
for i in range(len(a)):
result += str(int(a[i]) ^ int(b[i]))
return result
#function for finding the modular inverse
def modInverse(a, m) :
a = a % m
for x in range(1, m) :
if ((a * x) % m == 1) :
return x
return 1
#######################################################
########### Key Generation ###########
#######################################################
def key_generation(p,q):
try:
#making sure p and q are congruent to
assert(is_prime_number(p))
assert(is_prime_number(q))
assert(p % 4 == 3)
assert(q % 4 == 3)
#creating N, public key
N = p * q
#print("Public Key =", N)
#split_string_m = str(m)
print(f'Llave generada: {N}')
return N
except AssertionError as e:
print('Error con los numeros elegidos: ', str(e))
#######################################################
########### Encryption ###########
#######################################################
def encrypt(msg,X0,key):
X = []
X.append(X0)
hash_bytes=''
for char in msg:
bin_text=str(bin(ord(char))).replace('0b','')
while len(bin_text)<7:
bin_text= '0'+bin_text
hash_bytes+=bin_text
b = ""
L = len(str(hash_bytes))
for i in range(L):
string_x = bin(X[-1])[2:]
size = len(string_x)
b_i = string_x[size-1]
b = b_i + b
new_x = (X[i] ** 2) % key
X.append(new_x)
str_m = str(hash_bytes)
ciphertext = XOR(str_m, b)
XL = X[-1]
X0 = X[0]
XL_check = pow(X0,pow(2,L),key)
assert (XL == XL_check)
sent_message = (ciphertext, XL)
return sent_message
#######################################################
########### Decryption ###########
#######################################################
def decrypt(p,q,encrypted):
ciphertext,XL=encrypted
XL=int(XL)
L = len(str(ciphertext))
N=p*q
firstExponent = (((p+1)//4)**L) % (p-1)
firstPhrase = "({}^{}) mod {}".format(XL,firstExponent,p)
r_p = pow(XL,firstExponent,p)
secondExponent = (((q+1)//4)**L) % (q-1)
secondPhrase = "({}^{}) mod {}".format(XL,secondExponent,q)
r_q = pow(XL,secondExponent,q)
NEWX0 = (q*modInverse(q,p)*r_p + p*modInverse(p,q)*r_q)%N
NEWX = []
NEWX.append(NEWX0)
b = ""
for i in range(L):
string_x = bin(NEWX[-1])[2:]
size = len(string_x)
b_i = string_x[size-1]
b = b_i + b
new_x = (NEWX[i] ** 2) % N
NEWX.append(new_x)
plaintext = XOR(ciphertext,b)
return plaintext
def bin_toAscii(msg):
msg_split=[msg[i:i+7] for i in range(0,len(msg),7)]
salida=''
for msg in msg_split:
while len(msg) < 7:
msg='0'+msg
salida+=chr(int(msg,base=2))
return salida |
##LC 1180. Count Substrings with Only One Distinct Letter
#Solution
class Solution(object):
def countLetters(self, S):
"""
:type S: str
:rtype: int
"""
rep = ans = 0
cur = ''
S += '/'
for s in S:
if s == cur:
rep += 1
else:
ans += rep*(rep+1)/2
cur = s
rep = 1
return ans
#Result Runtime: 16 ms / 85.37%; Memory Usage: 13.4 MB / 86.59%
#Instruction: how many distinct letter substrings for a N repeated string?
|
##LC 1213. Intersection of Three Sorted Arrays
#Solution
class Solution(object):
def arraysIntersection(self, arr1, arr2, arr3):
"""
:type arr1: List[int]
:type arr2: List[int]
:type arr3: List[int]
:rtype: List[int]
"""
read1 = read2 = read3 = 0
ints = []
while read1 < len(arr1) and read2 < len(arr2) and read3 < len(arr3):
if arr1[read1] == arr2[read2] and arr1[read1] == arr3[read3]:
ints.append(arr1[read1])
minm = min(arr1[read1], arr2[read2], arr3[read3])
read1 += (arr1[read1] == minm)
read2 += (arr2[read2] == minm)
read3 += (arr3[read3] == minm)
return ints
#Result Runtime: 60 ms / 89.19%; Memory Usage: 13.6 MB / 76.58%
#Instruction: since the arrays are sorted, we just need to compare the smallest of each array without looking back, note that 'a==b==c' is different with '(a==b)==c'.
|
dic1={1:'nikhi',2:'bijit'}
key1=2
def solution(dic1, key1):
if dic1.has_key(key1):
return True
else:
return False
solution(dic1,key1)
|
'''THE FUNCTION TAKE ALTERNATIVE LETTERS FROM EACH AND FORM A NEW WORD'''
def interlock(word1,word2):
res=[]
if len(word1)==len(word2):
list1=list(word1)
list2=list(word2)
for i in range(len(list1)):
res.append(list1[i])
res.append(list2[i])
return "".join(res)
else:
return None
print interlock('legend','legecy')
print interlock('hello','heck')
|
''' FUNCTION TAKE A LIST OF WORDS AND SORT THEM FROM LONGEST TO SHORTEST '''
import random
def sort_by_length(lst):
res=[]
for i in lst:
res.append((len(i),i))
# res.sort(len(i))
res.sort(reverse=True)
res1=[]
for length,word in res:
res1.append(word)
print 'The sorted list is:',
return res1
print sort_by_length(['srt','defr','pufr','fdddddd'])
|
def pal(word1,word2):
if len(word1)==len(word2):
if word1[:]==word2[::-1]:
return 'given two are palindrome:',word1,word2
else:
return 'they are NOT'
else:
return 'not in same length'
print pal('sonu','unos')
print pal('sonu','sasi')
print pal('sonu','ssssssss')
|
def avoids(word,str):
for letter in word:
if letter in str:
return False
return True
avoids('sonu','ejjhdsklcjjb')
|
''' FIND ANGRAMS IN A WORD LIST '''
def anagram():
dict1={}
with open('word.txt')as f:
for i in f:
i=i.strip()
key=sortd(i)
if key in dict1:
value=dict1.get(key)+","+i
print value
dict1[key]=value
else:
dict1[key]=i
return dict1
def sortd(i):
char=[x for x in i]
char.sort()
return "".join(char)
print anagram()
|
def gcd(m,n):
if m<n:
m,n=n,m
while True:
r=m%n
if r==0:
print n
else:
m=n
n=r
gcd(4,18)
|
''' THIS FUNCTION TAKE ANY NO.OF ARGUMENTS AND RETURNS THEIR SUM '''
def sumall(*arg):
sum=0
for i in arg:
sum=sum+i
print 'The sum is:',
return sum
print sumall(55,66,44,2,8,63,22,58)
|
def sequence(n):
while n!= 1:
print n,
if n%2==0:
n=n/2
else:
n=n*3+1
sequence(7)
|
'''FUNCTION TAKE TWO STRINGS AND RETURN TRUE IF THEY ARE ANAGRAMS'''
def is_anagram(str1,str2):
lst1=sorted(list(str1))
lst2=sorted(list(str2))
if lst1==lst2:
return True
else:
return False
print is_anagram('arundhathi','anirudh')
print is_anagram('amaze','eamza')
|
"""各列の組から新しい特徴量を作成する"""
import pandas as pd
import numpy as np
import itertools
def plus(x):
"""
Args:
x (DataFrame): 説明変数
Returns:
DataFrame: xのすべての列の要素が2の組それぞれの和
"""
print("plus...")
df = pd.DataFrame(np.zeros((x.shape[0], 1)))
df.columns = ["to_delete"]
name_list = []
i = 0
for comb in list(itertools.combinations(x.columns.values, 2)):
print(i/len(list(itertools.combinations(x.columns.values, 2))))
plus_df = x.loc[:, comb].sum(axis=1)
name = str(comb[0])+'+'+str(comb[1])
name_list.append(name)
df = pd.concat((df, plus_df), axis=1)
i += 1
df = df.drop("to_delete", axis=1)
df.columns = name_list
return df
def minus(x):
"""
Args:
x (DataFrame): 説明変数
Returns:
DataFrame: xのすべての列の要素が2の組それぞれの差
"""
print("minus...")
df = pd.DataFrame(np.zeros((x.shape[0], 1)))
df.columns = ["to_delete"]
name_list = []
i = 0
for comb in list(itertools.combinations(x.columns.values, 2)):
print(i / len(list(itertools.combinations(x.columns.values, 2))))
x1 = x.loc[:, comb[0]]
x2 = x.loc[:, comb[1]]
minus_df = x1 - x2
name = str(comb[0])+'-'+str(comb[1])
name_list.append(name)
df = pd.concat((df, minus_df), axis=1)
i += 1
df = df.drop("to_delete", axis=1)
df.columns = name_list
return df
def times(x):
"""
Args:
x (DataFrame): 説明変数
Returns:
DataFrame: xのすべての列の要素が2の組それぞれの積
"""
print("times...")
df = pd.DataFrame(np.zeros((x.shape[0], 1)))
df.columns = ["to_delete"]
name_list = []
i = 0
for comb in list(itertools.combinations(x.columns.values, 2)):
print(i / len(list(itertools.combinations(x.columns.values, 2))))
x1 = x.loc[:, comb[0]]
x2 = x.loc[:, comb[1]]
times_df = x1 * x2
name = str(comb[0])+'*'+str(comb[1])
name_list.append(name)
df = pd.concat((df, times_df), axis=1)
i += 1
df = df.drop("to_delete", axis=1)
df.columns = name_list
return df
def div(x):
"""
Args:
x (DataFrame): 説明変数
Returns:
DataFrame: xのすべての列の要素が2の組それぞれの商
"""
print("div...")
df = pd.DataFrame(np.zeros((x.shape[0], 1)))
df.columns = ["to_delete"]
name_list = []
i = 0
for comb in list(itertools.combinations(x.columns.values, 2)):
print(i / len(list(itertools.combinations(x.columns.values, 2))))
x1 = x.loc[:, comb[0]]
x2 = x.loc[:, comb[1]]
div_df = x1 * x2
name = str(comb[0])+'/'+str(comb[1])
name_list.append(name)
df = pd.concat((df, div_df), axis=1)
i += 1
df = df.drop("to_delete", axis=1)
df.columns = name_list
return df
def all_arithmetic(x):
"""各組に対してすべての四則演算をする
Args:
x (DataFrame): 説明変数
Returns:
DataFrame: xのすべての列の要素が2の組それぞれの和、差、積、商
"""
plus_df = plus(x)
minus_df = minus(x)
times_df = times(x)
div_df = div(x)
df = pd.concat((x, plus_df), axis=1)
df = pd.concat((df, minus_df), axis=1)
df = pd.concat((df, times_df), axis=1)
df = pd.concat((df, div_df), axis=1)
return df
|
#Zahlenraten.py
Versuch = False
import random
zufallszahl = random.randint(1,5)
#Benutzer soll die Zahl dews COmpzuetrs erraten
while(Versuch == False):
v = input ("Geben sie eine zufällige Zahl zwischen 1 und 5 ein!")
if(int(v) == zufallszahl):
Versuch = True
print ("Sehr gut")
else:
print ("Nächster Versuch:")
# Ausgabe wie viele Versuche waren nötig |
#!/usr/bin/env python3
""" List documents """
import pymongo
def list_all(mongo_collection) -> list:
""" Lists all documents in a collection
Args:
mongo_collection: Collection of object
Return:
List with documents, otherwise []
"""
documents: list = []
for document in mongo_collection.find():
documents.append(document)
return documents
|
'''
def my_func(i):
if i == 0:
return
print("hi world")
my_func(i-1)
my_func(10)
'''
def fib_numbers(i):
if i <= 1:
return 1
else:
return fib_numbers(i-1) + fib_numbers(i-2)
print(fib_numbers(100))
# creating a list of fibonacci numbers using a generator
print([fib_numbers(i) for i in range(15)])
|
from data_structures.stack import Stack
class QueueStack:
def __init__(self):
self._stack1 = Stack()
self._stack2 = Stack()
def enqueue(self, item):
"""Add item to the enqueue stack.
Parameters:
item: item to add to the queue
"""
while len(self._stack1) > 0:
self._stack2.push(self._stack1.pop())
self._stack2.push(item)
def dequeue(self):
"""Remove item from the queue.
Returns:
item: First item in queue
"""
while len(self._stack2) > 0:
self._stack1.push(self._stack2.pop())
return self._stack1.pop()
myqueue = QueueStack()
myqueue.enqueue("Hooray1")
myqueue.enqueue("Hooray2")
print(myqueue.dequeue()) |
import sqlalchemy
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# define how to connect to the database
engine = create_engine(
# TODO: change this to point to your MySQL instance!
'postgresql+psycopg2://{user}:{pw}@{url}/{db}'.format(user='postgres',pw='mysecretpassword',url='localhost',db='postgres'),
# logging of SQL query
echo=False
)
# Extend your objects from this class
Base = declarative_base()
# Define your objects and tables
class Fish(Base):
__tablename__ = 'fishies'
id = Column(Integer, primary_key=True)
name = Column(String(50), unique=True)
age = Column(Integer)
def __str__(self):
return f'{self.id} | {self.name} | {self.age}'
# create all the fishies
Base.metadata.create_all(engine)
# Create a database session
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()
# Insert fishies into our database
session.add_all([
Fish(name='Bob', age=30),
Fish(name='Allan', age=9),
Fish(name='Joe', age=7),
Fish(name='Simon', age=12),
Fish(name='Michael', age=15)
])
session.commit()
# query fishes
print("All fishies:")
for f in session.query(Fish):
print(f)
# query fishies with a filter
print("Fishies older than 10")
for f in session.query(Fish).filter(Fish.age > 10):
print(f)
# get a fish by a specific id
print("Fishy with id 1")
f = session.query(Fish).filter(Fish.id == 1).one()
print(f) |
import unittest
from data_structures.doubly_linked_list import DoublyLinkedList
class TestLinkedlist(unittest.TestCase):
def test_first_item(self):
test_list = DoublyLinkedList()
test_list.insert_front(5)
test_list.insert_front(9)
pop = test_list.pop_front()
self.assertEqual(9, pop, "first item did not insert correctly")
def test_pop_from_front(self):
test_list = DoublyLinkedList()
test_list.insert_front(5)
test_list.insert_front(7)
test_list.insert_front(9)
front_pop = test_list.pop_front()
node = test_list.pop_front()
self.assertEqual(7, node._node_value, "First item isn't the second item before pop from front")
unittest.main(argv=[''], verbosity=2, exit=False) |
import time
def decorator_time(func):
def wrapper(x): #this is a new version of timed function, with additional functionality
print('Executing the wrapper')
start = time.time()
func(x)
end = time.time()
print(f'Time elapsed: {end - start}')
return wrapper
#@decorator_time
def time_function(x):
print('Executing original function')
time.sleep(x)
wrapper = decorator_time(time_function) # This is how we would call it without using the @decorator sugar
# because the wrapper is now a new function entirely, which decorates the original function (timed_function)
test_output = wrapper(3)
print(test_output) |
class Stack():
def __init__(self):
self._data = list()
#push complexity: O(1)
def push(self, item):
self._data.append(item)
# pop complexity: O(1) if implemented as a python list. Because we can directly access the index
def pop(self):
item = self._data[len(self._data) -1] #could also use pop
del self._data[len(self._data) -1] # deletes the specified item at the index. We haven't used 'remove' because it's a little more memory intensive
return item
# peek complexity: O(1)
def peek(self, item):
# same as pop method, but doesn't remove from list. Peeks at the top of the stack, but no delete
return self._data[-1]
# len complexity: O(n)
def __len__(self):
return len(self._data)
def __repr__(self):
return self._data
|
from math import *
x = float(input("Введіть х ="))
e = 2.71828
y = atan(x) + ((pow(e,0.6*x-1)-pow(x+6.1,3/2))/(log(x)+pow(log10(x),2)))
print (y)
|
# funcao fatorial
def fatorial(n):
if n < 0:
return 0
fat = 1
while (n > 1):
fat = (fat * n)
n -= 1
return fat
def test_fatorial0():
assert fatorial(0) == 1
def test_fatorial1():
assert fatorial(1) == 1
def test_fatorial2():
assert fatorial(2) == 2
def test_fatorial3():
assert fatorial(3) == 6
def test_fatorial4():
assert fatorial(4) == 24
def test_fatorial5():
assert fatorial(5) == 120
def test_fatorial10():
assert fatorial(10) == 3628800
def test_fatorial_negativo():
assert fatorial(-10) == 0
|
valor = int(input("Digite o valor de n: "))
aux = 1
while (valor > 1):
aux *= valor
valor -= 1
print(aux)
|
import random
from blackjackart import logo
from os import system
def screen_clear():
_=system('cls')
def deal_card():
cards=[11,2,3,4,5,6,7,8,9,10,10,10,10]
card=random.choice(cards)
return card
def calculate_score(cards):
if sum(cards)==21 and len(cards)==2:
return 0
if 11 in cards and sum(cards)>21:
cards.remove(11)
cards.append(1)
return sum(cards)
def compare(user_score,comp_score):
if user_score==comp_score:
return "DRAW"
elif comp_score==0:
return "LOSE, Opponent has Blackjack "
elif user_score==0:
return "WIN with a Blackjack"
elif user_score>21:
return "You went Over, You lose"
elif comp_score>21:
return "Opponent went over. You win"
elif user_score>comp_score:
return "You win"
else:
return "You lose"
def play_game():
print(logo)
is_gameover=False
user_card=[]
computer_card=[]
for _ in range(2):
new_card=deal_card()
user_card.append(new_card)
computer_card.append(deal_card())
while not is_gameover:
user_score=calculate_score(user_card)
comp_score=calculate_score(computer_card)
print(f"{user_card} {user_score}")
print(f"{computer_card[0]}")
if user_score==0 or comp_score==0 or user_score>21:
is_gameover=True
else:
choice=input("Type 'y' to get another card, type 'n' to pass: ")
if choice=="y":
user_card.append(deal_card())
else:
is_gameover=True
while comp_score!=0 and comp_score<17:
computer_card.append(deal_card())
comp_score=calculate_score(computer_card)
print(f"Your Final deck: {user_card} ,final score: {user_score}")
print(f"Opponent Final deck: {computer_card} ,final score: {comp_score}")
print(compare(user_score,comp_score))
while input("Do you want to play a game of Blackjack? Type 'y' or 'n': ")=="y":
screen_clear()
play_game()
|
#!/usrbin/env python3
# -*- coding:utf-8 -*-
import json,time
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
def login(): #登录模块
for i in range(3):
username = input('please input yuor name:')
if user_dict.get(username): #判断用户名是否存在
if user_dict[username]['status'] >= 3: #判断是否被锁定,status大于等于3即为锁定状态
print('输入错误3次,账号被锁定')
break
else:
password = input('please input your password:') #判断密码是否正确,正确将status置为0,错误加1
if user_dict[username]['pwd'] == password:
print('\033[32;1mWelcome\033[0m')
user_dict[username]['status'] = 0
return username
else:
user_dict[username]['status'] += 1
print('密码输入错误')
else:
print('用户名不存在')
def shopping(username): #购物模块
this_time_shop = [] #本次购物列表
if user_dict[username].get('salary'): #判断用户是否输入过工资,输入过在字典中取出。
print('您的余额为\033[32;1m{}\033[0m'.format(user_dict[username]['salary']))
salary = user_dict[username]['salary']
else:
salary = input('请输入您的工资:')
salary = int(salary)
user_dict[username]['salary'] = salary
while True:
print('*' * 50)
for thing in goods: #商品列表,用于退出时打印本次购买的商品
print('{}.{}\t{}'.format(goods.index(thing),thing['name'],thing['price']))
print('*' * 50)
choose = input('\033[34;1m请选择您要买的商品编号(按q退出,s查询消费记录):\033[0m')
if choose.isdigit():
choose = int(choose)
if int(choose) in range(len(goods)): #判断驶入编号是否在列表中
if salary >= goods[choose]['price']: #判断余额是否能购买此商品
this_time_shop.append(goods[choose])
now_time = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
shop_list = [goods[choose]['name'],goods[choose]['price'],now_time] #将商品写入文件,用于查询历史记录
user_dict[username]['salary'] = salary - goods[choose]['price'] #工资余额写入文件
print('\033[32;1m您已购买商品:{}\033[0m'.format(goods[choose]['name']))
if user_dict[username].get('shop'):
user_dict[username]['shop'].append(shop_list)
else:
user_dict[username]['shop'] = [shop_list]
else:
print('\033[31;1m商品不存在\033[0m')
elif choose == 'q': #退出程序
if len(this_time_shop) > 0:
print('您本次已购买以下商品:')
for thing in this_time_shop:
print('{}.{}\t{}'.format(this_time_shop.index(thing), thing['name'], thing['price']))
else:
print('\033[33;1m您本次没有购买商品\033[0m')
print('您的余额为\033[32;1m{}\033[0m'.format(user_dict[username]['salary']))
break
elif choose == 's': #查询历史记录
if user_dict[username].get('shop'):
print('\033[32;1m以下为您的历史消费记录:\033[0m')
print('\033[35;1m*\033[0m'*50)
for i in user_dict[username]['shop']:
print(i[0]+'\t'+str(i[1])+'\t'+i[2])
print('\033[35;1m*\033[0m' * 50)
else:
print('\033[36;1m您还没有购买过任何商品\033[0m')
with open('user.txt','r') as f: #将用户信息状态加载到内存中
user_dict = json.loads(f.read())
username = login()
shopping(username)
with open('user.txt','w') as f: #将更新过的用户信息写入文件
f.write(json.dumps(user_dict)) |
#MIT 6.00 2008 OCW
#Problem Set 2
#ps2a.py
#This program calculates the largest number of chicken McNuggets that cannot be purchased
#by using combinations of 6, 9, and 20 packs of McNuggets
#Function tests if there exists non-negative integers a,b,c such that 6a+9b+20c=n
#precondition: n is a non-negative integer that we are solving for in the above equation, representing number of chicken McNuggets
#postcondition: function returns boolean of true if the 6a+9b+20c=n is solved, and false if not
def test(n):
found=False #found is loop sentinel to indicate whether 6a+9b+20c=n has been solved
for c in range(n/20+1): #iterate thru possible range of values for largest pack size
if found:
break
for b in range(n/9+1): #iterate thru range of possible medium box sizes
if found:
break
for a in range(n/6+1): #iterate thru range of possible small box sizes
if(n==(6*a)+(9*b)+(20*c)):
found=True
break
return(found)
#function reads menu/background
def readBackGround():
print 'This problem set examines Diophantine equations.\n'
print 'A Diophantine equation is a polynomial equation where the variables can only take on integer values.'
print 'For example, x^n + y^n = z^n is a famous Diophantine equation. For n=2, there are infinitely many solutions'
print 'called the Pythagorean triples, e.g. 3^2 + 4^2 = 5^2 \n'
print 'This program looks at the Diophantine equation 6a + 9b + 20c = n'
print 'which models the way different combinations of small, medium, and large boxes of chicken McNuggets'
print 'can be purchased to arrive at a total of n chicken McNuggets. \n'
print 'This program calculates the largest number of chicken McNuggets that cannot be purchased'
print 'by using combinations of 6, 9, and 20 packs of McNuggets.\n'
#Variable declarations
n=1 #n is number to be purchased using integer combinations of 6, 9, and 20 packs
count=0 #count of consecutive n values that pass test; when 6 reached, we know by theorem that any larger number n can be bought
largest=0 #largest number of McNuggets that fail test
readBackGround() #read problem set background info
#driver program for test
while (count<6):
if test(n): #For each instance of n, perform test. If pass, increment counter
count=count+1
else: #If test fails, new largest value is n, reset counter to 0
count=0
largest=n
n=n+1
#print final output message
print 'The largest number of McNuggets that cannot be bought in exact quantity: ',largest
|
# Given a string s, find the length of the longest substring without repeating characters.
#
# Example 1:
# Input: s = "abcabcbb"
# Output: 3
# Explanation: The answer is "abc", with the length of 3.
def length_of_longest_substring(s):
len_longest_substring = 0
unique_list = []
for element in s:
if element in unique_list:
if unique_list[-1] == element:
unique_list.clear()
else:
repeated_index = unique_list.index(element)
unique_list = unique_list[repeated_index+1:]
unique_list.append(element)
if len(unique_list) > len_longest_substring:
len_longest_substring = len(unique_list)
return len_longest_substring
if __name__ == "__main__":
input_string0 = "abcabcbb"
input_string1 = "pwwkew"
input_string2 = "bbbbb"
input_string3 = ""
input_string4 = "aab"
input_string5 = "dvdf"
print(length_of_longest_substring(input_string5)) |
# Given an array of integers nums and an integer target,
# return indices of the two numbers such that they add up to target.
# You may assume that each input would have exactly one solution,
# and you may not use the same element twice.
# You can return the answer in any order.
# Constraints:
# 2 <= nums.length <= 10^3
# -10^9 <= nums[i] <= 10^9
# -10^9 <= target <= 10^9
# Only one valid answer exists.
def two_sum(nums, target):
if len(nums) < 2:
return -1
for i in range(len(nums) - 1):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return -1
if __name__ == '__main__':
input_list = [2,5,5]
print(two_sum(input_list, 10))
|
# Given a non-negative integer x, compute and return the square root of x.
# Since the return type is an integer, the decimal digits are truncated,
# and only the integer part of the result is returned.
#
# Example 1:
# Input: x = 4
# Output: 2
#
# Example 2:
# Input: x = 8
# Output: 2
# Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
import math
def my_sqrt(number):
return int(math.sqrt(number))
if __name__ == '__main__':
input_number = 8
print(my_sqrt(input_number)) |
# -*- coding: utf-8 -*-
"""
Created on Tue May 12 21:29:57 2020
@author: Ayush Singh
"""
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#
def diagonalDifference(arr):
pSum=0
sSum=0
for i in range(0,n):
pSum= pSum+arr[i][i]
for j in range(0,n):
sSum= sSum+arr[j][(n-1)-j]
diff= abs(pSum-sSum)
return diff
# Write your code here
n = int(input().strip())
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
result = diagonalDifference(arr)
print(result)
|
"""
7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
"""
# Solution
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
list = []
mod = []
res = 0
i = 0
quotient = 0
res_q =x
mark = 0
def divs(x): # a function to get the list of remainder and a quotient which can be used as input in next iteration
res_mod = x % 10
quotient = x // 10
mod.append(res_mod)
return (mod, quotient)
if res_q < 0: # if res_q is a negtive number, we should change it into a positive number
res_q = 0 - res_q
mark = 1 # like a flag, to decide if the final result need to add "-" before it be returned
else:
res_q = res_q
if res_q == 0: # 0 can be a special num, we should consider it seperately
return 0
while res_q != 0: # a loop to call function: get the list of remainder
result = divs(res_q)
res_q = result[1]
i = len(result[0]) - 1
for j in result[0]: # reverse
res = res + j * (10 ** i)
i = i - 1
if res > ((2 ** 32) // 2): # reverse integer should be a 32bit signed number: 32bit- like a space which has the size of 2**31
return 0 # for here, reverse integer is a signed number,therefor the range of the space should be [-(2**31)/2,(2**31)/2]
if mark == 1:
return -res
else:
return res
|
#!/usr/bin/env python
from random import *
import binascii
def randomlist(n = 0):
lst = []
for i in range(0,n):
lst.append(randint(1,1000))
return lst
#bubble sort
def bubble(lst):
for i in range(0, len(lst)):
for j in range(i, len(lst)):
if lst[i] > lst[j]:
lst[j],lst[i] = lst[i], lst[j]
return lst
#insertion sort
def insertion(lst):
for i in range(1,len(lst)):
j = i - 1
while j >= 0 and lst[j] > lst[j+1]:
lst[j+1],lst[j] = lst[j],lst[j+1]
j -= 1
return lst
#selection sort
def selection(lst):
slst = []
print lst
for i in range(0,len(lst)):
min = lst[i]
pos = None
for j in range(i,len(lst)):
if min > lst[j]:
min = lst[j]
pos = j
if pos:
lst[pos] = lst[i]
lst[i] = min
return lst
#bucket sort
def bucket(lst):
blst = [0] * (max(lst) + 1)
for el in lst:
blst[el] +=1
lst = []
for i, num in enumerate(blst):
if num != 0:
lst.extend([i]*blst[i])
return lst
def int_to_bin_str(num):
strr = ""
if num == 0:
return "0"
while num > 0:
strr = str(num%2) + strr
num /=2
return strr
def str_to_int(strr):
if strr == "0":
return 0
r = 0
for i in range(1,len(strr)+1):
if strr[-i] == "1":
r = r + 2**(i-1)
return r
#radix sort
def radix(lst):
binary_lst = [int_to_bin_str(el) for el in lst]
mmax = len(int_to_bin_str(max(lst)))
rest = []
for i in range(1, mmax+1):
buckets = [[],[]]
for el in binary_lst:
if (len(el)) > i:
if (el[-i] == "0"):
buckets[0].append(el)
else:
buckets[1].append(el)
else:
rest.append(el)
binary_lst = buckets[0] + buckets[1]
return [str_to_int(el) for el in rest + binary_lst]
#merge sort
def merge(lst, rst):
r = []
i = j = 0
while i < len(lst) and j < len(rst):
if lst[i] <= rst[j]:
r.append(lst[i])
i += 1
else:
r.append(rst[j])
j += 1
while i < len(lst):
r.append(lst[i])
i += 1
while j < len(rst):
r.append(rst[j])
j += 1
return r
def merge_sort(lst):
if len(lst) <= 1:
return lst
return merge(merge_sort(lst[0:len(lst)/2]), \
merge_sort(lst[(len(lst)/2):]))
#quick sort
# lame version
def quicksort(lst):
if(len(lst) <= 1):
return lst
pivot = len(lst)/2
left = [el for el in lst if el < lst[pivot]]
right = [el for el in lst if el > lst[pivot]]
#print left, right
return quicksort(left) + [lst[pivot]] + quicksort(right)
#heap sort
def heap_sort(lst):
pass
if __name__ == "__main__":
test_list = randomlist(10)
print bubble(test_list)
print insertion(test_list)
print selection(test_list)
print bucket(test_list)
print radix(test_list)
print merge_sort(test_list)
print quicksort(test_list)
# print heapsort(test_list) |
#This python script simply creates a postgresqsl table
import psycopg2
def create_tables():
""" create tables in the PostgreSQL database"""
command ="CREATE TABLE geo_table (Town VARCHAR ,latitude FLOAT(45),longitude FLOAT(45))"
conn = None
try:
# connect to the PostgreSQL server
conn = psycopg2.connect(dbname="apitest", user="Priyanshu", password="pr1yanshu")
cur = conn.cursor()
# create table one by one
#for command in commands:
cur.execute(command)
# close communication with the PostgreSQL database server
cur.close()
# commit the changes
conn.commit()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
print("/dberror")
finally:
if conn is not None:
conn.close()
if __name__ == '__main__':
create_tables()
|
__author__ = 'Binh Le'
def ValConve(c):
if(c=="C"):
return 12
if(c=="O"):
return 16
if(c=="H"):
return 1
return 0
def IsVal(Arg):
if((Arg=='(')or(Arg==')')or(Arg=='C')or(Arg=='O')or(Arg=='H')):
return 0
return 1
def IsLetter(Arg):
if((Arg=='C')or(Arg=='O')or(Arg=='H')):
return 1
return 0
def Handle(Arg):
Mass = 0
StackMass = []
MassTemp = 0
OpenPar = False
Temp = 0
TempSum = 0
for c in Arg:
if(c=="("):
StackMass.append(-1)
elif(IsLetter(c)==1):
StackMass.append(ValConve(c))
elif(IsVal(c)==1):
MassTemp = int(c)*StackMass.pop()
StackMass.append(MassTemp)
elif(c==")"):
while(OpenPar==False):
Temp = StackMass.pop()
if(Temp==-1):
OpenPar =True
StackMass.append(TempSum)
else:
TempSum += Temp
OpenPar = False
TempSum =0
while(len(StackMass)!=0):
c = StackMass.pop()
if(c!=-1):
Mass +=c
return Mass
if __name__ == '__main__':
Arg = []
Arg = raw_input()
print(Handle(Arg))
pass |
import sys
import os
from database import Database
from table import Table
currentDb = "NA"
DIRECTORY = "PA2/"
def main():
try:
#runs through the input and processes all of the commands
sqlInput = input().rstrip("\r\n")
while sqlInput.lower() != ".exit":
while sqlInput[:2] != "--" and len(sqlInput) != 0 and not sqlInput.endswith(";"):
#allow multi-line input. A space is added to the end of the line
#(double spaces are filtered out anyway)
sqlInput = sqlInput + " " + input("-->").strip("\r\n")
parse_line(sqlInput.split(";")[0])#,currentDb)
sqlInput = input().rstrip("\r\n")
except EOFError:
#no more commands, so exit
pass
print("Exiting")
#This is the parser function which processes the input commands.
def parse_line(line):
global currentDb
words = line.split()
if line[:2] == "--" or len(line) == 0:
pass #ignore
else:
try:
if words[0].lower() == "create":
if words[1].lower() == "database":
if not db_exists(words[2].lower()):
currentDatabase = Database(words[2].lower())
currentDb = words[2].lower()
currentDatabase.create()
print("Database '" + words[2] + "' created")
else:
print("!Failed to create database '" + words[2] + "' because it already exists")
elif words[1].lower() == "table":
if currentDb == "NA":
print("!Failed to create table '"+ words[2] +"' because no database is being used")
else:
if not tb_exists(words[2].lower(), currentDb):
currentTable = Table(words[2].lower(), currentDb)
currentTable.create()
currentWord = 3
wordCount = len(words)
nextWord = words[currentWord]
while currentWord < wordCount:
#calls the add_column method on each argument
atrName = words[currentWord].strip("()")
if words[currentWord + 1][:3] == "int":
currentTable.add_column(int,atrName, 0)
elif words[currentWord + 1][:5] == "float":
currentTable.add_column(float,atrName, 0)
elif words[currentWord + 1][:4] == "char":
currentTable.add_column("char",atrName, words[currentWord + 1][words[currentWord + 1].find('(')+1:words[currentWord + 1].find(')')])
elif words[currentWord + 1][:7] == "varchar":
currentTable.add_column("varchar",atrName, words[currentWord + 1][words[currentWord + 1].find('(')+1:words[currentWord + 1].find(')')])
currentWord += 2
print("Table '" + words[2] + "' created")
else:
print("!Failed to create table '"+ words[2] +"' because it already exists")
else:
print('Syntax: "create <table | database> [(<tableAttrName> <tableAttrType>, ... )]"')
elif words[0].lower() == "drop":
if words[1].lower() == "table":
if currentDb == "NA":
print("!Failed to delete table '" + words[2] + "' because no database is being used")
elif tb_exists(words[2].lower(), currentDb):
currentTable = Table(words[2].lower(), currentDb)
currentTable.drop()
print("Table '" + words[2] + "' deleted")
else:
print("!Failed to delete table '" + words[2] + "' because it does not exist")
elif words[1].lower() == "database":
#delete from list
if db_exists(words[2].lower()):
if currentDb == words[2].lower():
#dropping the current database
currentDb = "NA"
currentDb = Database(words[2].lower())
currentDb.drop()
print("Database '" + words[2] + "' deleted")
else:
print("!Failed to delete database '" + words[2] + "' because it does not exist")
elif words[0].lower() == "select":
if currentDb == "NA":
print("!Failed to query table '" + words[3] + "' because no database is being used")
else:
attributes = [] #what columns to select
tables = [] #what tables to join
conditions = [] #what conditions to apply
currentWord = 1
tablStart = 0
condStart = 0
for word in words[1:]:
if word.lower() == "from":
attributes = "".join(words[1:currentWord]).split(",")
tablStart = currentWord + 1
elif word.lower() == "where":
tables = "".join(words[tablStart:currentWord]).split(",")
condStart = currentWord + 1
currentWord += 1
if condStart != 0:
#the where keyword was used
conditions = " ".join(words[condStart:currentWord]).split(",")
else:
tables = "".join(words[tablStart:currentWord]).split(",")
#make sure table names are valid before calling function
for tableName in tables:
if not tb_exists(tableName.lower(), currentDb):
print("!Failed to select from '" + tableName + "' because it does not exist")
return
selectDB = Database(currentDb)
selectDB.select(attributes, tables, conditions)
elif words[0].lower() == "use":
if db_exists(words[1].lower()):
currentDb = words[1].lower()
print("Using database '" + words[1] + "'")
else:
print("!Failed to use database '" + words[2] + "' because it does not exist")
elif words[0].lower() == "alter":
if words[1].lower() == "table":
if currentDb == "NA":
print("!Failed to alter table '" + words[2] + "' because no database is being used")
elif words[3].lower() == "add":
if tb_exists(words[2].lower(), currentDb):
currentTable = Table(words[2].lower(), currentDb)
if words[5] == "int":
currentTable.add_column(int,words[4], 0)
elif words[5]== "float":
currentTable.add_column(float, words[4], 0)
elif words[5][:4] == "char":
currentTable.add_column("char", words[4], words[5][4:].strip("()"))
elif words[5][:7] == "varchar":
currentTable.add_column("varchar", words[4], words[5][7:].strip("()"))
print("Table '" + words[2] + "' modified")
else:
print("!Failed to alter table '" + words[2] + "' because it does not exist")
else:
print('Syntax: "alter table add <attrName> <attrType>"')
elif words[0].lower() =="update":
FILE = words[1].lower()
print("Updating " +words[1]+ ":")
currentTable = Table(FILE, currentDb)
if words[2] == "set":
attr = words[3]
newValue = words[5].strip("''")
print (" Setting attribute : " + attr + " to new value: " +newValue+ " ")
if words[6] == "where":
whereAttr = words[7]
oldValue = words[9].strip("''")
currentTable.update(attr,newValue, whereAttr, oldValue)
print(" Where " +whereAttr+" is: " + oldValue + " ")
else:
print("Invalid no where command")
else:
print("Invalid command")
elif words[0].lower() == "insert":
if currentDb == "NA":
print("!Failed to insert to table '" + words[2] + "' because no database is being used")
elif words[1].lower() == "into":
if tb_exists(words[2].lower(), currentDb):
arguments = "".join(words[3:]).replace('(',',').replace(')','').split(',')
if arguments[0].lower() == "values":
currentTable = Table(words[2].lower(), currentDb)
if currentTable.insert(arguments[1:]):
print("1 new record inserted")
else:
print("Invalid insertion command: " + arguments[0])
else:
print("!Failed to insert into table '" + words[2] + "' because it does not exist")
elif words[0].lower() == "delete":
FILE = words[2].lower()
currentTable = Table(FILE, currentDb)
if words[3] == "where":
whereAttr = words[4]
relation = words[5]
oldValue = words[6].replace('"', '')
print("Deleting from " +words[2])
currentTable.delete(whereAttr, relation, oldValue)
else:
print("Invalid line: " + line)
except IndexError:
print("Invalid line: " + line)
def db_exists (name):
filePath = DIRECTORY+name+""
return os.path.exists(filePath)
def tb_exists(tname, currentDb):
filePath = DIRECTORY+currentDb+"/"+tname+".txt"
return os.path.isfile(filePath)
if __name__ == "__main__":
main()
|
arr = [17,18,5,4,6,1]
arr[len(arr)-1] = -1
for i in range(len(arr)-1):
arr[i] = max(arr[i+1:])
print(arr)
|
"""
4)Given an array with many numbers, display as output the total number
of numbers having even number of digits
"""
mylist = list(map(int, input("Please enter the List(with spaces) Sharvari: ").split()))
print(mylist)
def sharvari(mylist):
count,count1 = 0,0
for i in mylist:
while i!=0:
i = i//10
count+=1
if count%2 ==0:
count1+=1
return count1
print(sharvari(mylist))
|
def estimatinge(x):
a = x
b = (1+1/a)**a
return float(b)
c = int(input("Number of decimal points of accuracy: "))
ans = estimatinge(x)
print("The estimate of the constant e is:",ans)
|
#Paulina Romo Villalobos
def gcd(n,m):
if(n == m):
answer = n
elif(n > m):
answer = gcd((n-m), m)
else:
answer = gcd(n, (m-n))
return answer
x = int(input("First number: "))
y = int(input("Second number "))
gcdiv = gcd(n, m)
print("GCD of", x , "and", y, ": ", gcdiv)
|
import sys
import os
import enum
import re
import socket
class HttpRequestInfo(object):
"""
Represents a HTTP request information
Since you'll need to standardize all requests you get
as specified by the document, after you parse the
request from the TCP packet put the information you
get in this object.
To send the request to the remote server, call to_http_string
on this object, convert that string to bytes then send it in
the socket.
client_address_info: address of the client;
the client of the proxy, which sent the HTTP request.
requested_host: the requested website, the remote website
we want to visit.
requested_port: port of the webserver we want to visit.
requested_path: path of the requested resource, without
including the website name.
NOTE: you need to implement to_http_string() for this class.
"""
def __init__(self, client_info, method: str, requested_host: str,
requested_port: int,
requested_path: str,
headers: list):
self.method = method
self.client_address_info = client_info
self.requested_host = requested_host
self.requested_port = requested_port
self.requested_path = requested_path
# Headers will be represented as a list of lists
# for example ["Host", "www.google.com"]
# if you get a header as:
# "Host: www.google.com:80"
# convert it to ["Host", "www.google.com"] note that the
# port is removed (because it goes into the request_port variable)
self.headers = headers
def to_http_string(self):
"""
Convert the HTTP request/response
to a valid HTTP string.
As the protocol specifies:
[request_line]\r\n
[header]\r\n
[headers..]\r\n
\r\n
(just join the already existing fields by \r\n)
You still need to convert this string
to byte array before sending it to the socket,
keeping it as a string in this stage is to ease
debugging and testing.
"""
method = self.method
path = self.requested_path
version = "HTTP/1.0\r\n"
http_string = method+' ' + path+' ' + version
for header in self.headers:
http_string += header[0] + ':' + ' ' + header[1] + '\r\n'
http_string += '\r\n'
print("*" * 50)
print("[to_http_string] Implement me!")
print("*" * 50)
return http_string
def to_byte_array(self, http_string):
"""
Converts an HTTP string to a byte array.
"""
return bytes(http_string, "UTF-8")
def display(self):
print(f"Client:", self.client_address_info)
print(f"Method:", self.method)
print(f"Host:", self.requested_host)
print(f"Port:", self.requested_port)
stringified = [": ".join([k, v]) for (k, v) in self.headers]
print("Headers:\n", "\n".join(stringified))
class HttpErrorResponse(object):
"""
Represents a proxy-error-response.
"""
def __init__(self, code, message):
self.code = code
self.message = message
def to_http_string(self):
""" Same as above """
object = self.message + ' ' + self.code
print("error type",object)
return object
def to_byte_array(self, http_string):
"""
Converts an HTTP string to a byte array.
"""
return bytes(http_string, "UTF-8")
def display(self):
print(self.to_http_string())
class HttpRequestState(enum.Enum):
"""
The values here have nothing to do with
response values i.e. 400, 502, ..etc.
Leave this as is, feel free to add yours.
"""
INVALID_INPUT = 0
NOT_SUPPORTED = 1
GOOD = 2
PLACEHOLDER = -1
def entry_point(proxy_port_number):
"""
Entry point, start your code here.
Please don't delete this function,
but feel free to modify the code
inside it.
"""
setup_sockets(proxy_port_number)
print("*" * 50)
print("[entry_point] Implement me!")
print("*" * 50)
return None
def setup_sockets(proxy_port_number):
print("HTTP proxy !!!!!!!!!!!!!!!!!!!!")
print("Starting HTTP proxy on port:", proxy_port_number)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', int(proxy_port_number)))
s.listen(15)
client, address = s.accept()
print("GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG")
space = ""
emt = ""
while 1:
string = client.recv(11000)
print("recieved data", string)
if string == b'\r\n':
emt = space
break
else:
space += string.decode('utf-8')
pt = str(space.split("\r\n"))
print("ur request is :", string)
u = pt.split()[1][0:3]
print("ur proxy is fine !!!")
e = str(space.split("\r\n"))
l = e.split()[1][0:6]
if u != "www" and l != "http:/":
space += "\r\n"
print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
command = http_request_pipeline(("127.0.0.1", 9877), space)
print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
s.connect(command.requested_host, command.requested_port)
print("hosttt", command.requested_host)
s.sendall((command.method + " " + command.requested_path + " " + "HTTP/1.0" + "\r\n\r\n").encode('utf-8'))
rec = str(s.recv(4096)), 'utf-8'
print("RECIEVED DATA!!!!!")
print("ur data ----------------------->", rec)
client.close()
s.close()
# when calling socket.listen() pass a number
# that's larger than 10 to avoid rejecting
# connections automatically.
print("*" * 50)
print("[setup_sockets] Implement me!")
print("*" * 50)
return None
"""def logic(clientSocket, s, client_address):
Example function for some helper logic, in case you
want to be tidy and avoid stuffing the main function.
Feel free to delete this function.
while (1) :
data = clientSocket.recv(1024)
string = ""
string += data
last_char = string[-1]
if last_char == "\r\n" and data == "\r\n":
break
if isinstance(http_request_pipeline(string, client_address), HttpErrorResponse):
str = HttpErrorResponse.to_byte_array(HttpErrorResponse.to_http_string())
clientSocket.send(str)
clientSocket.close()
if isinstance(http_request_pipeline(string), parse_http_request()):
IPaddr = s.gethostbyname(string)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(IPaddr, 80)
s.close()
print("KKKKKKKKKKKKKKKKKKKK")
pass
"""
def http_request_pipeline(source_addr, http_raw_data):
"""
HTTP request processing pipeline.
- Validates the given HTTP request and returns
an error if an invalid request was given.
- Parses it
- Returns a sanitized HttpRequestInfo
returns:
HttpRequestInfo if the request was parsed correctly.
HttpErrorResponse if the request was invalid.
Please don't remove this function, but feel
free to change its content
"""
# Parse HTTP request
# Return error if needed, then:
validity = check_http_request_validity(http_raw_data)
if validity == HttpRequestState.GOOD:
parse_http_request(source_addr, http_raw_data)
if validity == HttpRequestState.INVALID_INPUT:
code = '400'
message = 'Bad Request'
object = HttpErrorResponse(code, message)
object.to_http_string()
return object
if validity == HttpRequestState.NOT_SUPPORTED:
code = '501'
message = 'Not Implemented'
object = HttpErrorResponse(code, message)
object.to_http_string()
return object
sanitize_http_request(http_raw_data)
# Validate, sanitize, return Http object.
print("*" * 50)
print("[http_request_pipeline] Implement me!")
print("*" * 50)
return None
def parse_http_request(source_addr, http_raw_data):
"""
This function parses a "valid" HTTP request into an HttpRequestInfo
object.
"""
r1 = http_raw_data.split('\n')[0]
method = r1.split()[0]
path = r1.split()[1]
if path == "/":
r2 = http_raw_data.split('\n')[1]
host = r2.split()[0]
if host == "Host:":
host = re.sub("[:]", "", host)
r3 = r2.split(':')
url = r2.split()[1]
headers = []
r3 = ' '.join(r3).replace('\r', '').split()
headers.append(r3)
headers.append(url)
headers
requested_host = headers[0:]
requested_path = path
portno = re.findall(r'[0-9]+', r2)
if portno == []:
portno = "80"
requested_port = portno
requested_host = url
print("*" * 50)
print("[parse_http_request] Implement me!")
print("*" * 50)
# Replace this line with the correct values.
request_info = HttpRequestInfo(source_addr, method, requested_host, requested_port, requested_path, headers)
return request_info
def check_http_request_validity(http_raw_data) -> HttpRequestState:
"""
Checks if an HTTP request is valid
returns:
One of values in HttpRequestState
"""
global version
r1 = http_raw_data.split('\n')[0]
r2 = http_raw_data.split('\n')[1]
if (re.search("GET", r1) != None) and (re.search("/", r1) != None) and (re.search("HTTP/1.0", r1) != None) and (re.search(":", r2)):
return HttpRequestState.GOOD
if (re.search("GET", r1) != None) and (re.search("http://", r1) != None) and (re.search("HTTP/1.0", r1) != None):
return HttpRequestState.GOOD
if (re.search("GET", r1)!=None) and (re.search("/", r1)!=None) and (re.search("HTTP/1.0",r1)!=None) :
if (re.search(":", r2) == None) :
return HttpRequestState.INVALID_INPUT
if(re.search("GOAT", r1)!=None):
return HttpRequestState.INVALID_INPUT
if (re.search("HEAD"or"POST" or "PUT" , r1)!=None) and (re.search("/",r1)!=None) and (re.search("HTTP/1.0", r1) != None) and (re.search(":", r2)):
return HttpRequestState.NOT_SUPPORTED
if (re.search("HEAD"or"POST" or "PUT" ,r1)!=None) and (re.search("/",r1)!=None) and (re.search("HTTP/1.0",r1)!=None):
return HttpRequestState.INVALID_INPUT
if (re.search("HEAD"or"POST" or "PUT", r1) != None) and (re.search("HTTP/1.0", r1) == None) and (re.search(":", r2) != None):
return HttpRequestState.INVALID_INPUT
print("*" * 50)
print("[check_http_request_validity] Implement me!")
print("*" * 50)
return HttpRequestState.PLACEHOLDER
def sanitize_http_request(request_info: HttpRequestInfo):
"""
Puts an HTTP request on the sanitized (standard) form
by modifying the input request_info object.
for example, expand a full URL to relative path + Host header.
returns:
nothing, but modifies the input object
"""
print("*" * 50)
print("[sanitize_http_request] Implement me!")
print("*" * 50)
return request_info
#######################################
# Leave the code below as is.
#######################################
def get_arg(param_index, default=None):
"""
Gets a command line argument by index (note: index starts from 1)
If the argument is not supplies, it tries to use a default value.
If a default value isn't supplied, an error message is printed
and terminates the program.
"""
try:
return sys.argv[param_index]
except IndexError as e:
if default:
return default
else:
print(e)
print(
f"[FATAL] The comand-line argument #[{param_index}] is missing")
exit(-1) # Program execution failed.
def check_file_name():
"""
Checks if this file has a valid name for *submission*
leave this function and as and don't use it. it's just
to notify you if you're submitting a file with a correct
name.
"""
script_name = os.path.basename(__file__)
import re
matches = re.findall(r"(\d{4}_){,2}lab2\.py", script_name)
if not matches:
print(f"[WARN] File name is invalid [{script_name}]")
else:
print(f"[LOG] File name is correct.")
def main():
"""
Please leave the code in this function as is.
To add code that uses sockets, feel free to add functions
above main and outside the classes.
"""
print("\n\n")
print("*" * 50)
print(f"[LOG] Printing command line arguments [{', '.join(sys.argv)}]")
check_file_name()
print("*" * 50)
#http_request_pipeline(123,"HEAD / HTTP/1.0\r\nHost: www.google.com\r\n\r\n")
# This argument is optional, defaults to 18888
proxy_port_number = get_arg(1, 18888)
entry_point(proxy_port_number)
if __name__ == "__main__":
main() |
#!/usr/bin/env python3
import os
def format_history_statistics(dictionary):
"""Output dictionary in specific format: <value key>.
Parameters:
----------
dictionary : dict
Dictionary to print in specified format.
"""
for key in dictionary.keys():
print(str(dictionary[key]) + ' ' + str(key))
def get_history_statistics():
"""Calculate a count of unique commands that were used in conjunction with sudo.
Returns:
----------
dict
Dictionary of unique commands (as keys) and number of their occurrence (as values).
"""
sudo_history_stats = {}
if os.path.exists(os.path.expanduser('~/.bash_history')):
with open(os.path.expanduser('~/.bash_history'), 'r') as history_file:
for history_record in history_file:
if history_record.startswith('sudo '):
if history_record.rstrip() not in sudo_history_stats.keys():
sudo_history_stats[history_record.rstrip()] = 1
else:
sudo_history_stats[history_record.rstrip()] += 1
return sudo_history_stats
if __name__ == "__main__":
format_history_statistics(get_history_statistics())
|
# Sales by Match
#
# There is a large pile of socks that must be paired by color. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
#
# Example
# There is one pair of color and one of color . There are three odd socks left, one of each color. The number of pairs is .
#
# Function Description
#
# Complete the sockMerchant function in the editor below.
#
# sockMerchant has the following parameter(s):
# int n: the number of socks in the pile
# int ar[n]: the colors of each sock
#
# Returns
# int: the number of pairs
#
# Input Format
# The first line contains an integer , the number of socks represented in .
# The second line contains space-separated integers, , the colors of the socks in the pile.
#!/bin/python3
import math
import os
import random
import re
import sys
import pdb
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
dict_count = {}
for i in ar:
if i in dict_count:
dict_count[i] += 1
else:
dict_count[i] = 1
return sum([int(i/2) for i in dict_count.values()])
if __name__ == '__main__':
#fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
ar = list(map(int, input().rstrip().split()))
result = sockMerchant(n, ar)
#fptr.write(str(result) + '\n')
#fptr.close() |
#!/usr/bin/python3
"""Minimum copy and paste operations"""
import itertools
def minOperations(n):
"""Find the minimum number of "copy all" and "pastes" needed to get n"""
if n < 2:
return 0
dividend = n
ret = 0
for divisor in itertools.count(2):
while dividend % divisor == 0:
dividend /= divisor
ret += divisor
if dividend == 1:
return ret
|
############### Transforming Data
# Print the head of the homelessness data
print(homelessness.head())
# Import pandas using the alias pd
import pandas as pd
# Print the values of homelessness
print(homelessness.values)
# Print the column index of homelessness
print(homelessness.columns)
# Print the row index of homelessness
print(homelessness.index)
# Sort homelessness by individual
homelessness_ind = homelessness.sort_values(by=['individuals'])
# Print the top few rows
print(homelessness_ind.head())
# Select the individuals column
individuals=homelessness[['individuals']]
# Print the head of the result
print(individuals.head())
# Filter for rows where individuals is greater than 10000
ind_gt_10k = homelessness[homelessness['individuals']>10000]
# See the result
print(ind_gt_10k)
# Subset for rows in South Atlantic or Mid-Atlantic regions
south_mid_atlantic=homelessness[homelessness['region'].isin(['South Atlantic','Mid-Atlantic'])]
print(south_mid_atlantic)
homelessness.region
# Add total col as sum of individuals and family_members
homelessness['total'] = homelessness['individuals'] + homelessness['family_members']
# Add p_individuals col as proportion of individuals
homelessness['p_individuals'] = homelessness['individuals'] / homelessness['total']
# See the result
print(homelessness)
############### Aggregating Data
# Print the head of the sales DataFrame
print(sales.head())
# Print the info about the sales DataFrame
print(sales.info())
# Print the mean of weekly_sales
print(sales['weekly_sales'].mean())
# Print the median of weekly_sales
print(sales['weekly_sales'].median())
# Print the maximum of the date column
print(sales.date.max())
# Print the minimum of the date column
print(sales.date.min())
# A custom IQR function
def iqr(column):
return column.quantile(0.75) - column.quantile(0.25)
# Print IQR of the temperature_c column
print(sales.temperature_c.agg(iqr))
# Sort sales_1_1 by date
sales_1_1 = sales_1_1.sort_values(by='date')
# Get the cumulative sum of weekly_sales, add as cum_weekly_sales col
sales_1_1['cum_weekly_sales'] = sales_1_1['weekly_sales'].cumsum()
# Get the cumulative max of weekly_sales, add as cum_max_sales col
sales_1_1['cum_max_sales'] = sales_1_1['weekly_sales'].cummax()
# See the columns you calculated
print(sales_1_1[["date", "weekly_sales", "cum_weekly_sales", "cum_max_sales"]])
# Drop duplicate store/type combinations
store_types = sales.drop_duplicates(subset=['store','type'])
print(store_types.head())
# Drop duplicate store/department combinations
store_depts = sales.drop_duplicates(subset=['store','department'])
print(store_depts.head())
# Subset the rows where is_holiday is True and drop duplicate dates
holiday_dates = sales[sales['is_holiday']==True].drop_duplicates(subset='date')
# Print date col of holiday_dates
print(holiday_dates)
# Count the number of stores of each type
store_counts = store_types['type'].value_counts()
print(store_counts)
# Get the proportion of stores of each type
store_props = store_types.type.value_counts(normalize=True)
print(store_props)
# Count the number of each department number and sort
dept_counts_sorted = store_depts.department.value_counts(sort=True)
print(dept_counts_sorted)
# Get the proportion of departments of each number and sort
dept_props_sorted = store_depts.department.value_counts(sort=True, normalize=True)
print(dept_props_sorted)
# Calc total weekly sales
sales_all = sales["weekly_sales"].sum()
# Subset for type A stores, calc total weekly sales
sales_A = sales[sales["type"] == "A"]["weekly_sales"].sum()
# Subset for type B stores, calc total weekly sales
sales_B = sales[sales["type"] == "B"]["weekly_sales"].sum()
# Subset for type C stores, calc total weekly sales
sales_C = sales[sales["type"] == "C"]["weekly_sales"].sum()
# Get proportion for each type
sales_propn_by_type = [sales_A, sales_B, sales_C] / sales_all
print(sales_propn_by_type)
# From previous step
sales_by_type = sales.groupby("type")["weekly_sales"].sum()
# Group by type and is_holiday; calc total weekly sales
sales_by_type_is_holiday = sales.groupby(["type", "is_holiday"])["weekly_sales"].sum()
print(sales_by_type_is_holiday)
# Import numpy with the alias np
import numpy as np
# For each store type, aggregate weekly_sales: get min, max, mean, and median
sales_stats = sales.groupby("type")["weekly_sales"].agg([np.min, np.max, np.mean, np.median])
# Print sales_stats
print(sales_stats)
# For each store type, aggregate unemployment and fuel_price_usd_per_l: get min, max, mean, and median
unemp_fuel_stats = sales.groupby("type")[["unemployment", "fuel_price_usd_per_l"]].agg([np.min, np.max, np.mean, np.median])
# Print unemp_fuel_stats
print(unemp_fuel_stats)
# Pivot for mean weekly_sales by store type and holiday
mean_sales_by_type_holiday = sales.pivot_table(values="weekly_sales", index="type", columns="is_holiday")
# Print mean_sales_by_type_holiday
print(mean_sales_by_type_holiday)
# Print the mean weekly_sales by department and type; fill missing values with 0s; sum all rows and cols
print(sales.pivot_table(values="weekly_sales", index="department", columns="type", fill_value=0, margins=True))
############### Slicing and Indexing
# Look at temperatures
print(temperatures)
# Index temperatures by city
temperatures_ind = temperatures.set_index("city")
# Look at temperatures_ind
print(temperatures_ind)
# Reset the index, keeping its contents
print(temperatures_ind.reset_index())
# Reset the index, dropping its contents
print(temperatures_ind.reset_index(drop=True))
# Make a list of cities to subset on
cities = ["Moscow", "Saint Petersburg"]
# Subset temperatures using square brackets
print(temperatures[temperatures["city"].isin(cities)])
# Subset temperatures_ind using .loc[]
print(temperatures_ind.loc[cities])
# Index temperatures by country & city
temperatures_ind = temperatures.set_index(['country','city'])
# List of tuples: Brazil, Rio De Janeiro & Pakistan, Lahore
rows_to_keep = [('Brazil','Rio De Janeiro'), ('Pakistan','Lahore')]
# Subset for rows to keep
print(temperatures_ind.loc[rows_to_keep])
# Sort temperatures_ind by index values
print(temperatures_ind.sort_index(level=['country','city']))
# Sort temperatures_ind by index values at the city level
print(temperatures_ind.sort_index(level=['city']))
# Sort temperatures_ind by country then descending city
print(temperatures_ind.sort_index(level=['country','city'],
ascending=[True,False]))
# Sort the index of temperatures_ind
temperatures_srt = temperatures_ind.sort_index(level=['country','city'])
# Subset rows from Pakistan to Russia
print(temperatures_srt.loc['Pakistan':'Russia'])
# Try to subset rows from Lahore to Moscow
print(temperatures_srt.loc['Lahore':'Moscow'])
# Subset rows from Pakistan, Lahore to Russia, Moscow
print(temperatures_srt.loc[('Pakistan','Lahore'):('Russia','Moscow')])
# Subset rows from India, Hyderabad to Iraq, Baghdad
print(temperatures_srt.loc[('India','Hyderabad'):('Iraq','Baghdad')])
# Subset columns from date to avg_temp_c
print(temperatures_srt.loc[:,'date':'avg_temp_c'])
# Subset in both directions at once
print(temperatures_srt.loc[('India','Hyderabad'):('Iraq','Baghdad'), 'date':'avg_temp_c'])
# Use Boolean conditions to subset temperatures for rows in 2010 and 2011
temperatures_bool = temperatures[(temperatures.date >= '2010-01-01') & (temperatures.date <= '2011-12-31')]
print(temperatures_bool)
# Set date as an index and sort the index
temperatures_ind = temperatures.set_index('date').sort_index(level='date')
# Use .loc[] to subset temperatures_ind for rows in 2010 and 2011
print(temperatures_ind.loc['2010-01-01':'2011-12-31'])
# Use .loc[] to subset temperatures_ind for rows from Aug 2010 to Feb 2011
print(temperatures_ind.loc['2010-08-01':'2011-02-28'])
# Get 23rd row, 2nd column (index 22, 1)
print(temperatures.iloc[22,1])
# Use slicing to get the first 5 rows
print(temperatures.iloc[0:5])
# Use slicing to get columns 3 to 4
print(temperatures.iloc[:,2:4])
# Use slicing in both directions at once
print(temperatures.iloc[0:5,2:4])
# Add a year column to temperatures
temperatures['year'] = temperatures.date.dt.year
# Pivot avg_temp_c by country and city vs year
temp_by_country_city_vs_year = temperatures.pivot_table(values='avg_temp_c', index=['country','city'], columns='year')
# See the result
print(temp_by_country_city_vs_year)
# Subset for Egypt to India
temp_by_country_city_vs_year.loc['Egypt':'India']
# Subset for Egypt, Cairo to India, Delhi
temp_by_country_city_vs_year.loc[('Egypt','Cairo'):('India','Delhi')]
# Subset in both directions at once
temp_by_country_city_vs_year.loc[('Egypt','Cairo'):('India','Delhi'), 2005:2010]
# Get the worldwide mean temp by year
mean_temp_by_year = temp_by_country_city_vs_year.mean()
# Filter for the year that had the highest mean temp
print(mean_temp_by_year[mean_temp_by_year>=mean_temp_by_year.max()])
# Get the mean temp by city
mean_temp_by_city = temp_by_country_city_vs_year.mean(axis='columns')
# Filter for the city that had the lowest mean temp
print(mean_temp_by_city[mean_temp_by_city<=mean_temp_by_city.min()])
############### Creating and Visualizing DataFrames
# Import matplotlib.pyplot with alias plt
import matplotlib.pyplot as plt
# Look at the first few rows of data
print(avocados.head())
# Get the total number of avocados sold of each size
nb_sold_by_size = avocados.groupby(["size"])["nb_sold"].sum()
# Create a bar plot of the number of avocados sold by size
nb_sold_by_size.plot(kind='bar')
# Show the plot
plt.show()
# Import matplotlib.pyplot with alias plt
import matplotlib.pyplot as plt
# Get the total number of avocados sold on each date
nb_sold_by_date = avocados.groupby(["date"])["nb_sold"].sum()
# Create a line plot of the number of avocados sold by date
nb_sold_by_date.plot(kind='line')
# Show the plot
plt.show()
# Scatter plot of nb_sold vs avg_price with title
avocados.plot(x='nb_sold', y='avg_price', kind='scatter',
title = "Number of avocados sold vs. average price")
# Show the plot
plt.show()
# Histogram of conventional avg_price
avocados[avocados.type=='conventional']['avg_price'].hist()
# Histogram of organic avg_price
avocados[avocados.type=='organic']['avg_price'].hist()
# Add a legend
plt.legend(['conventional','organic'])
# Show the plot
plt.show()
# Import matplotlib.pyplot with alias plt
import matplotlib.pyplot as plt
# Check individual values for missing values
print(avocados_2016.isna())
# Check each column for missing values
print(avocados_2016.isna().any())
# Bar plot of missing values by variable
avocados_2016.isna().sum().plot(kind='bar')
# Show plot
plt.show()
# Remove rows with missing values
avocados_complete = avocados_2016.dropna(how='any')
# Check if any columns contain missing values
print(avocados_complete.isna().any())
# List the columns with missing values
cols_with_missing = ["small_sold", "large_sold", "xl_sold"]
# Create histograms showing the distributions cols_with_missing
avocados_2016[cols_with_missing].hist()
# Show the plot
plt.show()
# Create a list of dictionaries with new data
avocados_list = [{'date':'2019-11-03','small_sold': 10376832,'large_sold': 7835071},
{'date':'2019-11-10','small_sold':10717154,'large_sold':8561348}]
# Convert list into DataFrame
avocados_2019 = pd.DataFrame(avocados_list)
# Print the new DataFrame
print(avocados_2019)
# Create a dictionary of lists with new data
avocados_dict = {
"date": ['2019-11-17','2019-12-01'],
"small_sold": [10859987,9291631],
"large_sold": [7674135,6238096]
}
# Convert dictionary into DataFrame
avocados_2019 = pd.DataFrame(avocados_dict)
# Print the new DataFrame
print(avocados_2019)
# Read CSV as DataFrame called airline_bumping
airline_bumping = pd.read_csv('airline_bumping.csv')
# Take a look at the DataFrame
print(airline_bumping.head())
# Create airline_totals_sorted
airline_totals_sorted = airline_totals.sort_values('bumps_per_10k', ascending=False)
# Print airline_totals_sorted
print(airline_totals_sorted)
# Save as airline_totals_sorted.csv
airline_totals_sorted.to_csv('airline_totals_sorted.csv') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.