text
stringlengths 37
1.41M
|
---|
"""
Remove Duplicates from Sorted List
==================================
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
"""
from __future__ import print_function
from linked_list import Node
def remove_duplicates(l):
last_unique = l
node = l.next
while node:
if node.val != last_unique.val:
last_unique.next = node
last_unique = node
node = node.next
last_unique.next = None
return l
for l in (
Node.from_iterable([1, 1, 2]),
Node.from_iterable([1, 1, 2, 3, 3])
):
print('Before:', l)
print('After:', remove_duplicates(l))
|
"""
Merge Two Sorted Lists II
=========================
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note: You have to modify the array A to contain the merge of A and B.
Do not output anything in your code.
TIP: C users, please malloc the result into a new array and return the result.
If the number of elements initialized in A and B are m and n respectively,
the resulting size of array A after your code is executed should be m + n
Example :
Input :
A : [1 5 8]
B : [6 9]
Modified A : [1 5 6 8 9]
"""
from __future__ import print_function
def merge(a, b):
m = len(a)
n = len(b)
res = []
i = j = 0
while i<m and j<n:
if a[i] <= b[j]:
res.append(a[i])
i += 1
else:
res.append(b[j])
j += 1
res.extend(a[i:m])
res.extend(b[j:n])
return res
print(merge([1, 5, 8], [6, 9]))
|
"""
2 Sum
=====
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 < index2.
Please note that your returned answers (both index1 and index2 ) are not zero-based.
Put both these numbers in order in an array and return the array from your function ( Looking at the function signature will make things clearer ).
Note that, if no pair exists, return empty list.
If multiple solutions exist, output the one where index2 is minimum.
If there are multiple solutions with the minimum index2, choose the one with minimum index1 out of them.
Input: [2, 7, 11, 15], target=9
Output: index1 = 1, index2 = 2
Note: Diffk II problem is solved with the same trick.
"""
from __future__ import print_function
import sys
def find_2_sum(arr, target):
# First positions of numbers in array.
positions = {}
for i, el in enumerate(arr):
if el not in positions:
positions[el] = i
min_i1 = min_i2 = sys.maxsize
for el, i1 in positions.items():
i2 = positions.get(target - el, -1)
if i2 != -1 and i1 < i2 and i2 < min_i2:
min_i1 = i1
min_i2 = i2
return (min_i1, min_i2)
print(find_2_sum([2, 7, 11, 15], 9))
|
"""
Balanced Binary Tree
====================
Given a binary tree, determine if it is height-balanced.
Height-balanced binary tree : is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Return 0 / 1 ( 0 for false, 1 for true ) for this problem
Example :
Input :
1
/ \
2 3
Return : True or 1
Input 2 :
3
/
2
/
1
Return : False or 0
Because for the root node, left subtree has depth 2 and right subtree has depth 0.
Difference = 2 > 1.
"""
from __future__ import print_function
class Node:
def __init__(self, data, l=None, r=None):
self.data = data
self.left = l
self.right = r
def height_balanced(node):
"""
Returns a height of a tree and a boolean indicating whether it is balanced.
"""
if node is None:
return -1, True
if node.left is None and node.right is None:
return 0, True
left_height, left_balance = height_balanced(node.left)
right_height, right_balance = height_balanced(node.right)
height = max(left_height, right_height) + 1
balanced = left_balance and right_balance and abs(left_height-right_height) <= 1
return height, balanced
print(height_balanced(Node(1, Node(2), Node(3))))
print(height_balanced(Node(1, Node(2, Node(3)))))
|
# -*- coding: utf-8 -*-
"""
Largest Rectangle in Histogram
==============================
Given n non-negative integers representing the histogram’s bar height where the width of each bar is 1,
find the area of largest rectangle in the histogram.
For example,
Given height = [2,1,5,6,2,3],
return 10.
Solution
--------
Problem can be solved with two stacks in O(N).
"""
from __future__ import print_function
def largest_rect(hist):
heights = []
positions = []
max_area = 0
hist.append(0) # Fake zero bar
for i, h in enumerate(hist):
if not heights or h > heights[-1]:
heights.append(h)
positions.append(i)
else:
while heights and h <= heights[-1]:
area = heights[-1] * (i - positions[-1])
max_area = max(max_area, area)
heights.pop()
p = positions.pop()
heights.append(h)
positions.append(p)
return max_area
print(largest_rect([1, 3, 2, 1, 2]))
|
"""
Combinations
============
Given two integers n and k, return all possible combinations of k numbers out of 1 2 3 ... n.
Make sure the combinations are sorted.
To elaborate,
Within every entry, elements should be sorted. [1, 4] is a valid entry while [4, 1] is not.
Entries should be sorted within themselves.
Example :
If n = 4 and k = 2, a solution is:
[
[1,2],
[1,3],
[1,4],
[2,3],
[2,4],
[3,4],
]
"""
from __future__ import print_function
def combinations(n, k, min_n=1):
if k == 0:
yield []
elif n+1-min_n == k:
yield list(range(min_n, n+1))
else:
for c in combinations(n, k-1, min_n+1):
yield [min_n] + c
for c in combinations(n, k, min_n+1):
yield c
for c in combinations(5, 3):
print(c)
|
"""
Hotel Bookings Possible
=======================
A hotel manager has to process N advance bookings of rooms for the next season.
His hotel has K rooms. Bookings contain an arrival date and a departure date.
He wants to find out whether there are enough rooms in the hotel to satisfy the demand.
Write a program that solves this problem in time O(N log N) .
Input:
First list for arrival time of booking.
Second list for departure time of booking.
Third is K which denotes count of rooms.
Output:
A boolean which tells whether its possible to make a booking.
Return 0/1 for C programs.
O -> No there are not enough rooms for N booking.
1 -> Yes there are enough rooms for N booking.
Example :
Input :
Arrivals : [1 3 5]
Departures : [2 6 8]
K : 1
Return : False / 0
At day = 5, there are 2 guests in the hotel. But I have only one room.
Solution
--------
First, we sort arrays of arrivals and departures - O(NlogN)
Then, we create a mergesort-like procedure with two iterators and keep a counter of guests,
so when we get time from arrivals, we increment a counter, and
when we get time from departures, we decrement a counter.
If it never exceeds K, then there are enough rooms in hotel.
"""
from __future__ import print_function
def bookings_possible(arr, dep, k):
arr.sort()
dep.sort()
num_rooms_busy = 0
arr_iter = iter(arr)
dep_iter = iter(dep)
a = next(arr_iter, None)
d = next(dep_iter, None)
while True:
# All arrivals are processed
if a is None:
break
# Guest arrives
if a < d:
num_rooms_busy += 1
if num_rooms_busy > k:
return False
a = next(arr_iter, None)
# Guest departures
else:
num_rooms_busy -= 1
d = next(dep_iter, None)
return True
for arr, dep, k in (
([1, 3, 5], [2, 6, 8], 1),
):
print(arr, dep, k, bookings_possible(arr, dep, k))
|
"""
Sum Of Fibonacci Numbers
========================
How many minimum numbers from fibonacci series are required such that sum of numbers should be equal to a given Number N?
Note: repetition of number is allowed.
Example:
N = 4
Fibonacci numbers : 1 1 2 3 5 .... so on
here 2 + 2 = 4
so minimum numbers will be 2
"""
from __future__ import print_function
from collections import deque
def num_fib(n):
# First lets find all Fibonacci numbers less or equal that n.
fib = [1, 2]
while fib[-1] <= n:
fib.append(fib[-1] + fib[-2])
fib.pop()
fib.reverse()
# Organize search in a BFS like manner.
# We can go from n to n-fib1, n-fib2 ... n-fibk
# We should find minimum number of such transitions that get us to zero.
q = deque()
addendums = [[] for _ in range(n+1)]
q.append(n)
while q:
k = q.popleft()
ns = len(addendums[k])
for f in fib:
if k-f >= 0 and not addendums[k-f]:
addendums[k-f] = addendums[k] + [f]
if k-f == 0:
break
q.append(k-f)
return addendums[0]
print(num_fib(40000))
|
"""
Remove Duplicates from Sorted List II
=====================================
Given a sorted linked list, delete all nodes that have duplicate numbers,
leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
"""
from __future__ import print_function
from linked_list import Node
def remove_duplicates2(l):
first_unique = last_unique = None
node = l
while node:
c = 1
# count duplicates
while node.next and node.val == node.next.val:
c += 1
node = node.next
# process uniques
if c == 1:
if last_unique:
last_unique.next = node
else:
first_unique = node
last_unique = node
node = node.next
return first_unique
for l in (
Node.from_iterable([1, 2, 3, 4, 4, 5, 5, 6]),
Node.from_iterable([1, 1, 2, 3, 3, 4, 5]),
Node.from_iterable([1, 1, 2, 2, 3, 3, 3])
):
print('Before:', l)
print('After:', remove_duplicates2(l))
|
"""
Maximum Consecutive Gap
=======================
Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Try to solve it in linear time/space.
Example :
Input : [1, 10, 5]
Output : 5
Solution
--------
The constraints of the problem can be met with sorting an array with radix sort, but there exists more elegant solution.
1. Find min and max of an array
2. If we divide segment [min; max] in N+1 equal parts:
d = (max-min)/(N+1), [min+i*d; min+d*(i+1)] for i in 0..N,
then according to the Dirichlet's principle at least on of the inner segments
would contain no point from the array. Therefore maximum gap can not be shorter than d.
Thus difference between two points from the same segment the can not be the greatest.
It can happen only between points from different segments.
Consecutive gaps are formed between max elem of the segment and min elem of the next nonempty segment.
If we keep arrays of segment mins and maxs we solve the problem in linear time, linear space.
"""
from __future__ import print_function
def max_gap(arr):
n = len(arr)
if n == 1:
return 0
arr_min = min(arr)
arr_max = max(arr)
d = (arr_max - arr_min)/(n+1.)
# arr_max+1, arr_min-1 are used for empty buckets
# We could use None or MAX_INT, MIN_INT instead
mins = [arr_max+1]*(n+1)
maxs = [arr_min-1]*(n+1)
for el in arr:
index = int((el-arr_min)/d)
# max elem goes into last bucket
if el == arr_max:
index = n
mins[index] = min(mins[index], el)
maxs[index] = max(maxs[index], el)
# skip empty segments
mins = [m for m in mins if m != arr_max+1]
maxs = [m for m in maxs if m != arr_min-1]
gap = 0
for i in range(len(mins)-1):
gap = max(gap, mins[i+1] - maxs[i])
return gap
print(max_gap([1, 10, 5, 7, 4]))
|
"""
Clone Graph
===========
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
"""
from __future__ import print_function
class Node:
def __init__(self, label, neighbours=None):
self.label = label
if neighbours is None:
neighbours = []
self.neighbours = neighbours
def __repr__(self):
return '{%r}->%r' % (self.label, [n.label for n in self.neighbours])
n1 = Node('1')
n2 = Node('2')
n3 = Node('3')
n4 = Node('4')
n5 = Node('5')
n1.neighbours = [n2, n3]
n2.neighbours = [n1, n4]
n3.neighbours = [n1, n4, n5]
n4.neighbours = [n2, n3]
n5.neighbours = [n3]
graph = [n1, n2, n3, n4, n5]
def clone(graph):
id_index = {id(n): i for i, n in enumerate(graph)}
graph_copy = [Node(n.label) for n in graph]
for i, n in enumerate(graph):
for v in n.neighbours:
vi = id_index[id(v)]
v_copy = graph_copy[vi]
graph_copy[i].neighbours.append(v_copy)
return graph_copy
graph_copy = clone(graph)
for n in graph_copy:
print(n)
|
"""
Merge Two Sorted Lists
======================
Merge two sorted linked lists and return it as a new list.
The new list should be made by splicing together the nodes of the first two lists, and should also be sorted.
For example, given following linked lists:
5 -> 8 -> 20
4 -> 11 -> 15
The merged list should be:
4 -> 5 -> 8 -> 11 -> 15 -> 20
"""
from __future__ import print_function
from linked_list import Node
def merge(l1, l2):
if l1.val <= l2.val:
head = tail = l1
l1 = l1.next
else:
head = tail = l2
l2 = l2.next
while l1 and l2:
if l1.val <= l2.val:
tail.next = l1
tail = l1
l1 = l1.next
else:
tail.next = l2
tail = l2
l2 = l2.next
if l1:
tail.next = l1
else:
tail.next = l2
return head
l1 = Node.from_iterable([5, 8, 20])
l2 = Node.from_iterable([4, 11, 15])
print(merge(l1, l2))
|
def table(number):
for i in range(1,11):
print "%s * %s = %s"%(number,i,(number*i))
inp = input("enter a number : ")
table(inp)
|
def read_lines(filename):
'''
read the content of a given file
'''
fobj = open(filename,"r")
data = fobj.readlines()
fobj.close()
return data
data1 = read_lines("sample.txt")
#print data1
########################################################
fobj = open("C:\\Users\\Ram\\Desktop\\text.txt","r+")
#print fobj.read()
data = fobj.readlines()
i = 1
for line in data:
#print(str(i)+"."+line),
i+= 1
#fobj.write("this is the appended line \n")
fobj.close()
with open("C:\\Users\\Ram\\Desktop\\text.txt") as f:
a = f.readlines()
print a
for i in a:
print i
f.close()
|
def fibo(num):
if (num<=1):
return num
else:
return (fibo(num-1) + fibo(num-2))
num = int(input("enter a number of terms : "))
print " Fibonacci sequence"
for i in range(num):
print fibo(i)
|
def Bubble_Sort(lst):
print lst
sort = True
while sort:
sort = False
for i in range(len(lst)-1):
if lst[i] > lst[i+1]:
lst[i],lst[i+1] = lst[i+1],lst[i]
sort = True
return lst
seq = [2,1,3,12,4,6,7,11,8,10,9]
print Bubble_Sort(seq)
|
print "A"
for row in range(1,5):
for col in range(1,8):
if row+col ==5 or col-row == 3 or ((row ==3) and (col>1 and col<7)):
print '*',
else:
print " ",
print ""
print "K"
for row in range(1,8):
for col in range(1,5):
if col == 1 or row+ col == 5 or row-col == 3:
print '*',
else:
print " ",
print ""
print " M "
for row in range(1,6):
for col in range(1,6):
if col==1 or col==5 or (row==col==2) or (row==col==3) or (row==2 and col==4) :
print '*',
else:
print " ",
print ""
print " S "
for row in range(1,8):
for col in range(1,5):
if row == 1 or row == 4 or row == 7 or (col==1 and (row >1 and row <4)) or (col == 4 and (row > 4 and row < 7)):
print "*",
else :
print " ",
print ""
|
print('사자성어 맞추기 게임을 시작합니다')
print('---------------------------------')
a = ['개과천선','구사일생','군계일학', '무용지물', '동고동락']
b = print(input('미리 준비해두면 근심 걱정이 없다 \n 이 말의 사자성어는? :')
for i in a :
if i == a[0] :
print(success)
else :
print(failed)
print(ends)
|
student = []
#
# for i in range(5) :
# scores = int(input('학생' + str(i+1) + 'student score : ')
# student.append(scores)
# print(sum/len(student))
#
b = input('학생 수 입력 : ')
scores=[]
sum_s = 0
for i in range(int(b)) :
score = input('학생' + str(i+1) + ' 점수 입력 : ')
scores.append(score)
for s in scores :
sum_s += int(s)
avg = sum_s / len(scores)
print("총점 : %d" % sum_s)
print('평균 : %.2f' % avg)
|
def showinfo() :
print('홍길동')
print('20')
print('010-1234-1234')
showinfo()
# 첫번째 방법
def sum(n1,n2) :
print(input('숫자1 입력 : %d \n숫자2 입력 : %d \n합 : %d ' % (n1, n2, n1+n2) ))
# 두번째 방법
def sum1(n1,n2) :
print('합 :', n1+n2)
n1 = int(input('숫자1 입력 : '))
n2 = int(input('숫자2 입력 : '))
sum1(n1,n2)
# 세번째 방법
def sum3() :
n1 = int(input('숫자1 입력 : '))
n2 = int(input('숫자2 입력 : '))
return n1+n2
print('두 수의 합 : ', sum3())
def get_area() :
n1 = int(input('가로길이 입력 : '))
n2 = int(input('세로길이 입력 : '))
return n1 * n2
print('사각형의 면적 : ', get_area())
|
# 상품을 리스트에 추가
# 엔터키 누르면 입력 종료되고 등록된 상품 리스트 출력
products = []
while True :
product = input('상품등록(엔터키만 누르면 종료) : ')
if product == '' :
break
products.append(product)
print('등록된 상품 : ', end=' ')
for product in products :
print(product, end=' ')
nums =[1,2,3,4]
nums[2:2] = [90,91]
print(nums)
|
# 랜덤숫자 생성(난수).py
# 파이썬에서 난수(random number) 사용하기 위해서는 모듈(random)을 사용해야 함
# random 모듈의 randint() 함수를 이용해서 난수를 발생시켜 봄
# randint(최소, 최대)
# 최소부터 최대 사이의 임의의 정수 반환해주는 함수
# 모듈을 프로그램 안으로 갖고 와야 함
# from random import randint
# n = randint(1,100) - 1부터 100 사이에서 임의 숫자 하나를 반환
from random import randint
n = randint(1,100)
print(n)
n1 = randint(1,5)
print(n1)
|
#Funciones de conversion de Decimal a Binario/Octal/Hexadecimal
def decimalabinario(a):
binario = []
while a > 0:
binario.insert(0, a % 2)
a = a // 2
binario = "".join(str(i) for i in binario)
return(binario)
def decimalaoctal(b):
octal = []
while b > 0:
octal.insert(0, b % 8)
b = b // 8
octal = "".join(str(i) for i in octal)
return(octal)
def decimalahexadecimal(b):
hexadecimal = []
while b > 0:
hexadecimal.insert(0, b % 16)
b = b // 16
e=[]
for h in hexadecimal:
if h == 10:
h = "A"
if h == 11:
h = "B"
if h == 12:
h = "C"
if h == 13:
h = "D"
if h == 14:
h = "E"
if h == 15:
h = "F"
e.append(h)
e="".join(str(i) for i in e)
return (e)
#Funciones de conversion de Binario a Decimal/Octal/Hexadecimal
def binariodecimal(b):
binario = []
for i in b:
binario.append(int(i))
binario.reverse()
x = len(binario)
e = 0
for i in range(0, x):
h = binario[i] * (2 ** i)
e = e + h
return(e)
def binariooctal(b):
binario = []
for i in b:
binario.append(int(i))
binario.reverse()
x = len(binario)
e = 0
for i in range(0, x):
h = binario[i] * (2 ** i)
e = e + h
octal = []
while e > 0:
octal.insert(0, e % 8)
e = e // 8
octal = "".join(str(i) for i in octal)
return (octal)
def binariohexadecimal(b):
binario = []
for i in b:
binario.append(int(i))
binario.reverse()
x = len(binario)
o = 0
for i in range(0, x):
v = binario[i] * (2 ** i)
o = o + v
hexadecimal = []
while o > 0:
hexadecimal.insert(0, o % 16)
o = o // 16
e = []
for h in hexadecimal:
if h == 10:
h = "A"
if h == 11:
h = "B"
if h == 12:
h = "C"
if h == 13:
h = "D"
if h == 14:
h = "E"
if h == 15:
h = "F"
e.append(h)
e = "".join(str(i) for i in e)
return (e)
#Funciones de conversion de Octal a Decimal/Binario/Hexadecimal
def octaldecimal(b):
octal = []
for i in b:
octal.append(int(i))
octal.reverse()
x = len(octal)
e = 0
for i in range(0, x):
h = octal[i] * (8 ** i)
e = e + h
return (e)
def octalbinario(b):
octal = []
for i in b:
octal.append(int(i))
octal.reverse()
x = len(octal)
e = 0
for i in range(0, x):
h = octal[i] * (8 ** i)
e = e + h
binario = []
while e > 0:
binario.insert(0, e % 2)
e = e // 2
binario = "".join(str(i) for i in binario)
return (binario)
def octalhexadecimal(b):
octal = []
for i in b:
octal.append(int(i))
octal.reverse()
x = len(octal)
z = 0
for i in range(0, x):
q = octal[i] * (8 ** i)
z = z + q
hexadecimal = []
while z > 0:
hexadecimal.insert(0, z % 16)
z = z // 16
e = []
for h in hexadecimal:
if h == 10:
h = "A"
if h == 11:
h = "B"
if h == 12:
h = "C"
if h == 13:
h = "D"
if h == 14:
h = "E"
if h == 15:
h = "F"
e.append(h)
e = "".join(str(i) for i in e)
return (e)
#Funciones de conversion de Hexadecimal a Decimal/Binario/Octal
def hexadecimaldecimal(b):
hexadecimal = []
for i in b:
if i == "A" or i == "B" or i == "C" or i == "D" or i == "E" or i == "F":
hexadecimal.append(i)
else:
hexadecimal.append(int(i))
d = []
for h in hexadecimal:
if h == "A":
h = 10
if h == "B":
h = 11
if h == "C":
h = 12
if h == "D":
h = 13
if h == "E":
h = 14
if h == "F":
h = 15
d.append(h)
octal = []
for i in d:
octal.append(int(i))
octal.reverse()
x = len(octal)
p = 0
for i in range(0, x):
j = octal[i]*(16 ** i)
p = p + j
return (p)
def hexadecimaloctal(b):
hexadecimal = []
for i in b:
if i == "A" or i == "B" or i == "C" or i == "D" or i == "E" or i == "F":
hexadecimal.append(i)
else:
hexadecimal.append(int(i))
d = []
for h in hexadecimal:
if h == "A":
h = 10
if h == "B":
h = 11
if h == "C":
h = 12
if h == "D":
h = 13
if h == "E":
h = 14
if h == "F":
h = 15
d.append(h)
octal = []
for i in d:
octal.append(int(i))
octal.reverse()
x = len(octal)
p = 0
for i in range(0, x):
j = octal[i] * (16 ** i)
p = p + j
octal = []
while p > 0:
octal.insert(0, p % 8)
p = p // 8
octal = "".join(str(i) for i in octal)
return (octal)
def hexadecimalbinario(b):
hexadecimal = []
for i in b:
if i == "A" or i == "B" or i == "C" or i == "D" or i == "E" or i == "F":
hexadecimal.append(i)
else:
hexadecimal.append(int(i))
d = []
for h in hexadecimal:
if h == "A":
h = 10
if h == "B":
h = 11
if h == "C":
h = 12
if h == "D":
h = 13
if h == "E":
h = 14
if h == "F":
h = 15
d.append(h)
octal = []
for i in d:
octal.append(int(i))
octal.reverse()
x = len(octal)
p = 0
for i in range(0, x):
j = octal[i] * (16 ** i)
p = p + j
binario = []
while p > 0:
binario.insert(0, p % 2)
p = p // 2
binario = "".join(str(i) for i in binario)
return (binario)
#Inicio Programa
while True:
try:
print("Bienvenido al Conversor de Numeros!")
desc=input("En que base se encuentra su numero? decimal / binario / octal / hexadecimal : ")
if desc==("hexadecimal") or desc==("binario") or desc==("octal"):
n=input("Ingrese su valor a convertir : ").upper()
else:
n=int(input("Ingrese su valor a convertir : "))
desc2=input("A que base quiere convertir el valor ingresado? decimal / binario / octal / hexadecimal : ")
if desc=="decimal" and desc2=="binario":
y=decimalabinario(n)
print("La conversion de su valor a binario es: ", y, "\n")
if desc == "decimal" and desc2 == "octal":
y = decimalaoctal(n)
print("La conversion de su valor a octal es: ", y, "\n")
if desc == "decimal" and desc2 == "hexadecimal":
y = decimalahexadecimal(n)
print("La conversion de su valor a hexadecimal es: ", y, "\n")
if desc == "binario" and desc2 == "decimal":
y = binariodecimal(n)
print("La conversion de su valor a decimal es: ", y, "\n")
if desc == "binario" and desc2 == "octal":
y = binariooctal(n)
print("La conversion de su valor a octal es: ", y, "\n")
if desc == "binario" and desc2 == "hexadecimal":
y = binariohexadecimal(n)
print("La conversion de su valor a hexadecimal es: ", y, "\n")
if desc == "hexadecimal" and desc2 == "decimal":
y = hexadecimaldecimal(n)
print("La conversion de su valor a decimal es: ", y, "\n")
if desc == "hexadecimal" and desc2 == "octal":
y = hexadecimaloctal(n)
print("La conversion de su valor a octal es: ", y, "\n")
if desc == "hexadecimal" and desc2 == "binario":
y = hexadecimalbinario(n)
print("La conversion de su valor a binario es: ", y, "\n")
if desc == "octal" and desc2 == "decimal":
y = octaldecimal(n)
print("La conversion de su valor a decimal es: ", y, "\n")
if desc == "octal" and desc2 == "hexadecimal":
y = octalhexadecimal(n)
print("La conversion de su valor a octal es: ", y, "\n")
if desc == "octal" and desc2 == "binario":
y = octalbinario(n)
print("La conversion de su valor a binario es: ", y, "\n")
decs3=input("quiere seguir convirtiendo valores? si / no : ")
if decs3=="no":
break
except:
print("Se acaba de cometer algun error a la hora de ingresar valores, Recuerde que solo puede ingresar numeros y letras", "\n")
decs3 = input("quiere intentar convertir un valor otra vez? si / no : ")
if decs3 == "no":
break
|
from dataclasses import dataclass
@dataclass
class Triangle(object):
height: int = 0
width: int = 0
def print_area(self) -> None:
print(f'triangle area is: {self.height * self.width / 2}')
def initilise() -> Triangle:
return Triangle
|
def split_and_join(line):
return(line.replace(" ", "-"))
# new_s = ""
# for i in line:
# if (i == " "):
# new_s += "-"
# else:
# new_s += i
# return(new_s)
if __name__ == '__main__':
line = input()
result = split_and_join(line)
print(result)
|
# This will be more of proof of concept to figure out if keying in the model and allowing users
# to play around with the variables to get the model on different steady states. we will see. :)
# pretty sure I'm doing this wrong. Need to reference my notes on Recursive dynamic programming.
class model:
def __init__(self, k0, k1, y, l, a, t):
self.k0 = k0
self.k1 = k1
self.y = y
self.l = l
self.a = a
self.t = t
self.vars = [i for i in dir(self) if not callable(i) if not i.startswith("__")]
def solow(k_0=1, l_0=1, a_0=None, alpha=0.5, d=0.04, g=0.03, n=None, s=0.1, duration=200):
# k_0 is initial capital, l_0 is initial labor, a_0 is initial labor tech, g is growth of pop.
# n is development of technology, s is savings rate.
if a_0 == None:
y_0 = (k_0 ** alpha) * (l_0 ** (1 - alpha))
k1points = list()
k0points = list()
lpoints = list()
ypoints = list()
# apoints = list()
t = list()
for i in range(0, duration):
k_1 = (s * y_0) - (d + g)*k_0
l_1 = (1 + g) * l_0
# a_1 = (1 + n) * a_0
y_1 = (k_1 ** alpha) * (l_1 ** (1 - alpha))
k1points.append(k_1)
k0points.append(k_0)
lpoints.append(l_0)
ypoints.append(y_1)
# apoints.append(a_0)
t.append(i)
k_0 = k_1
l_0 = l_1
y_0 = y_1
# a_0 = a_1
return model(k0points, k1points, ypoints, lpoints, None, t)
else:
y_0 = (k_0 ** alpha) * ((a_0 * l_0) ** (1 - alpha))
k1points = list()
k0points = list()
lpoints = list()
ypoints = list()
apoints = list()
t = list()
for i in range(0, duration):
k_1 = (s * y_0) - (d + g)*k_0
l_1 = (1 + g) * l_0
a_1 = (1 + n) * a_0
y_1 = ((k_1 ** alpha) * (a_1 * l_1) ** (1 - alpha))
k1points.append(k_1)
k0points.append(k_0)
lpoints.append(l_0)
ypoints.append(y_1)
apoints.append(a_0)
t.append(i)
k_0 = k_1
l_0 = l_1
y_0 = y_1
a_0 = a_1
return model(k0points, k1points, ypoints, lpoints, apoints, t)
# I don't think this is right, it's giving me some messed up graphs. I'll make sure my formulation is
# correct next time I work on this.
# I have tried everything. I even went through and quadruple checked my formulations. I've tried
# graphing different parameters to get different lines, all to try to get the traditional
# model graph. I have no idea what's going on and I'm lost. I did however learn a lot. Maybe I
# can make something similar but with a statistical tool and some data... I'd like to pack this
# into a .exe and send to people for them to look at, but idk if it's worth it. I'm kinda proud
# of it, even though it's broken. :)
if __name__ == "__main__":
solow()
|
"""Implement quick sort in Python.
Input a list.
Output a sorted list."""
def quicksort(array):
quick(array,0,len(array)-1)
print "ok"
return []
def partition(Array,low,up):
i = low+1
j = up
pivot = Array[low]
while(i<=j):
while(Array[i]<pivot and i<up):
i = i+1
while(Array[j]>pivot):
j = j-1
if(i<j):
Array[i],Array[j] = Array[j],Array[i]
i = i+1
j = j-1
else:
i = i+1
Array[low] = Array[j]
Array[j] = pivot
return j
def quick(Array,low,up):
if(low>=up):
#print Array
return Array
else:
piv_loc = partition(Array,low,up)
quick(Array,low,piv_loc-1)
quick(Array,piv_loc+1,up)
# quick(Array,low,up)
# Array = [48,44,19,59,72,80,42,65,82,8,95,68]
# low = 0
# up = len(Array) - 1
# for i in Array:
# print i,s
test = [21, 4, 1, 3, 9, 20, 25, 6, 21, 14]
print test
quick(test,0,len(test)-1)
# for i in range(len(test)):
# print ("%d" %test[i]),
quicksort(test)
|
import random
print("***** RANDOM NUMBER GUESSING GAME *****")
print("\n")
print("I'm thinking of a number between 1-10.")
print("Can you guess it?")
my_number = random.randint(1,10)
your_number = input("Try below: \n")
while (your_number != my_number):
your_number = input("Try again: \n")
if (your_number == my_number):
print("You got it!")
|
print "You are transported to Victorian England. You are now in a room with Mr. Darcy. What do you do? Do you..."
print "1. Kiss him."
print "2. Shoot him with a revolver."
decision = raw_input("> ")
if decision == "1":
print "You have uncovered the secret to happiness! You are now Mrs. Darcy and will inherit Pemberley estate when your husband passes."
else:
print "Oops. You shot the hero of the romantic story. He was your one true love and you die a miserable old hag."
|
num1, num2 = raw_input("Enter a number and a divisor.").split()
num1 = int(num1)
num2 = int(num2)
if num2 == 0:
raise ValueError('Cannot divide by zero')
if num1 % num2 == 0:
print("Divides perfectly!")
else:
print("Oops! Still a remainder.")
|
from copy import deepcopy
def solveBackTrack(A, D, R2, R1, order):
#remove the unity restrictions from D
#print("D: ", D)
D = constrictR1(D, R1, order)
print("D after unity constriction: ", D)
AC3(order, D, R2)
print("D after AC3: ", D)
s = backTrack(A, D, R2, order)
return s
def backTrack(A, D, R2, order):
if(None not in A):
return A
for i in range(len(A)):
if (not A[i]):
ind = i
break
#print("ind: ", ind)
#print("D: ", D)
print("C = ", D[2], " P = ", D[1], "F = ", D[0])
for ele in D[ind]:
Atemp = deepcopy(A)
Atemp[ind] = ele
global step
step=step + 1
print("Etape", step,". AV ", "C = ", Atemp[2], " P = ", Atemp[1], "F = ", Atemp[0])
#print(order[ind],": ", ele)
#print("D: ", D)
Dtemp = deepcopy(D)
Dtemp = forwardCheck(Atemp, Dtemp, ind, R2, order)
#print("Dtemp: ", Dtemp)
if(Dtemp):
return backTrack(Atemp, Dtemp, R2, order)
def AC3(order, D, R2):
workList = []
for x in order:
for key in R2:
if x in key:
workList.append(key)
while(True):
couple = workList.pop()
#see if couple actually works for all the values of one of the couples
changed = reduce(x, order, D, couple)
if(changed):
if(not D):
break
else:
for key in R2:
if(x in key and (not key in workList)):
workList.append(key)
if(not workList):
break
def reduce(x, order, D, couple):
#(x,y) = couple
if(x == couple[0]):
y = couple[1]
else:
y = couple[0]
#print("x: ", x, "y: ", y)
for i, ele in enumerate(order):
#print("order: ", order)
#print("ele: ", ele)
if(ele == y):
indy = i
if(ele == x):
indx = i
#print("indy: ", indy)
changed = False
for xv in D[indx]:
keepXV = False
for yv in D[indy]:
if((xv, yv) in R2.get(couple)):
keepXV = True
if(not keepXV):
changed = True
D[indx].remove(xv)
return changed
def forwardCheck(A, D, ind, R2, order):
#look at what I have to remove from the domain of others
#my value is in A[ind]
#make sure that A[ind],z exists
#print("A: ", A)
#print("ind: ", ind)
xele = A[ind]
for nex in range(ind, len(A)):
let = order[ind]
#print("x: ", let)
nextLet = order[nex]
#print("y: ", nextLet)
#print((let, nextLet))
for eleNext in D[nex]:
#print("eleNext: ", eleNext)
#print("xele: ", xele)
if(R2.get(( let, nextLet))):
if(not (xele, eleNext) in R2.get((let, nextLet))):
D[nex].remove(eleNext)
global step
step= step+1
print("Etape", step,". FC ", "C = ", D[2], " P = ", D[1], "F = ", D[0])
return D
def constrictR1(D, R1, order):
for i, cons in enumerate(R1):
#print("const: ", cons)
#print("i: ", i)
for ele in D[i]:
if not ele in R1.get(order[i]):
global step
step=step+1
D[i].remove(ele)
print("Etape", step, ". CU ", "C = ", D[2], " P = ", D[1], "F = ", D[0])
return D
#main
#F P C
order = ["F", "P", "C"]
R2 = {
("F","C") : [(1,4), (1,3), (2,4), (4,1), (3,1), (4,2)],
("P", "C") : [(1,3), (1,4), (2,3), (2,4), (3,1), (4,1), (3,2), (4,2)],
("F","C") : [(1,4), (1,3), (2,4), (4,1), (3,1), (4,2)],
("P", "C") : [(1,3), (1,4), (2,3), (2,4), (3,1), (4,1), (3,2), (4,2)]
}
R1 = {
"F": [2,3],
"P": [2,3]
}
step = 0
s = solveBackTrack([None, None, None], [[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]], R2, R1, order)
print("solution: ", s)
|
# Sam Goodin 9/15/17
# Lab Assignment Week 4
# To be checked-off
# The use of min, max, sum, map, etc. functions that would be deemed shortcuts is prohibited
#
# Please call the function at the bottom of the code and print the result.
# None of the functions should call PRINT
#
# Created by Larry Gates
# Please commit to the repository
# Question 1
# Sums all the numbers in a list using a while-loop
def sumListWhile(aList):
result = 0
counter = 0
while counter < len(aList):
result += aList[counter]
counter += 1
return result
# Question 2
# Multiply the numbers in a list together using a for-loop
def multiplyListFor(aList):
result = 1
for i in aList:
result *= i
return result
# Question 3
# Return the factorial of n using a while-loop
def factorialWhileLoop(n):
result = 1
counter = 1
while counter < n+1:
result *= counter
counter += 1
return result
# Question 4 (Challenge Problem (Bonus))
# TODO: Write functions that perform the multiplication and division using for and while loops
# Part a: For loop - Multiplication
# Write a function taking in 2 arguments. Then use a for loop to multiply the numbers together.
# TODO: Write function
def forMultiplication(*args):
l = []
for a in args:
l.append(a)
result = 1
for i in l:
result *= i
return result
# Part b: For loop - Division
# Write a function taking in 2 arguments. Then use a for loop to divide the numbers.
# TODO: Write function
def forDivision(*args):
l = []
for a in args:
l.append(a)
result = l[0]
for i in l:
num = l.index(i)
result /= l[num+1]
if num + 1 == len(l):
break
else:
pass
return result
# Part c: While loop - Multiplication
# Write a function taking in 2 arguments. Then use a while loop to multiply the numbers together.
# TODO: Write function
def whileMultiplication(*args):
l = []
for a in args:
l.append(a)
result = 1
counter = 0
while counter < len(l):
result *= l[counter]
counter += 1
return result
# Part d: While loop - Division
# Write a function taking in 2 arguments. Then use a while loop to divide the numbers.
# TODO: Write function
def whileDivision(num1, num2):
pass
################ Print the Result of calling each of the functions ################
print(sumListWhile([1, 2, 3, 4]))
print(sumListWhile([5, 10, 15, 20]))
print(multiplyListFor([1, 2, 3, 4]))
print(multiplyListFor([5, 10, 15, 20]))
print(factorialWhileLoop(5))
print(factorialWhileLoop(10))
print(forMultiplication(2, 3))
print(forDivision(2, 3))
print(whileMultiplication(2, 3))
print(whileDivision(2, 3))
|
#Sam Goodin 9/15/17
#Sums all numbers in a list using a for-loop
def sumListFor(aList):
result = 0
for number in aList:
result += number
return result
aL = [1, 2, 3, 4]
result = sumListFor(aL)
print("Adding list: " + str(result))
# Multiply the numbers in a list together using a while-loop
def multiplyListWhile(aList):
result = 0
counter = 0
listLen = len(aList)
while counter < listLen:
result *= aList[counter]
counter += 1
return result
multList = multiplyListWhile(aL)
print("Multiply List: " + str(multList))
def factorialForLoop(n):
result = 1
for number in range(1, n+1):
result *= number
return result
fact = factorialForLoop(5)
print("Factorial of 5: " + str(fact))
|
while 0 < 1:
bloodType = (input("What is your blood type? ")).lower()
if bloodType == "a+":
print("You can donate to A+ or AB+!")
elif bloodType == "a-":
print("You can donate to A+, A-, AB+, and AB-!")
elif bloodType == "b+":
print("You can donate to B+ or AB+!")
elif bloodType == "b-":
print("You can donate to B+, B-, AB+, and AB-!")
elif bloodType == "ab+":
print("You can donate to AB+!")
elif bloodType == "ab-":
print("You can donate to AB+ and AB-!")
elif bloodType == "o+":
print("You can donate to O+, A+, B+, and AB+!")
elif bloodType == "o-":
print("You can donate to anyone!")
else:
print("That isn't a blood type.")
|
class Car:
"""
Class to represent the make, model, and year of a car
"""
def __init__(self, theMake, theModel, theYear):
"""
Takes in a string for the make, the model, and int representing the year
"""
self.make = theMake
self.model = theModel
self.year = theYear
def getMake(self):
#Returns make of the car
return self.make
def getModel(self):
#Returns the model of the car
return self.model
def getYear(self):
#Returns the year of the car
return self.year
def setYear(self, year):
#Given a year, update the year of the car
self.year = year
def olderCar(self, otherCar):
#Given a different car, return the instance of the older car
if self.year < otherCar.year:
return self
else:
return otherCar
def stringRep(self):
#Returns the string representation of the car class
return "Make: {0}\nModel: {1}\nYear: {2}\n".format(self.make, self.model, self.year)
def __repr__(self):
return self.stringRep()
|
date = 15
if date == 1:
print("start your new month")
elif date == 30:
print("end your month")
else:
print("enjoy your day")
#ternary
mydate = 15
myword = "start or end of your month" if mydate == 1 or mydate == 30 else "enjoy your day"
print(myword)
a = 3
a = 7 if 3**2 > 9 else 14
print(a)
|
def Reverse(head):
q = p = head
while p != None:
q = p
p = p.next
q.next = q.prev
q.prev = p
return q
|
"""
You are given a list of size N, initialized with zeroes.
You have to perform M operations on the list and output the maximum of final values of all the elements in the list.
For every operation, you are given three integers a, b and k and you have to add value k to all the elements ranging from index a to b(both inclusive).
Input Format
First line will contain two integers N and M separated by a single space.
Next lines will contain three integers a, b and k separated by a single space.
Numbers in list are numbered from 1 to N.
Output Format
A single line containing maximum value in the updated list.
Sample Input
5 3
1 2 100
2 5 100
3 4 100
Sample Output
200
"""
import sys
nm = sys.stdin.readline()
nm = nm.split(' ')
n = int(nm[0])
m = int(nm[1])
data = [0] * (n + 1)
max = 0
weight = 0
for i in range(m):
line = sys.stdin.readline()
line= line.split(' ')
a = int(line[0])
b = int(line[1])
k = int(line[2])
data[a-1] += k
data[b] -= k
for j in data:
weight += j
if weight > max:
max = weight
print(max)
|
from tkinter import *
import LTAT
window = Tk()
window.title("Lets Take A Trip")
window.geometry('350x300')
lbl = Label(window, text="Starting Location")
lbl.grid(column=0, row=0)
start = Entry(window,width=30)
start.grid(column=1, row=0)
lbl = Label(window, text="Ending Location")
lbl.grid(column=0, row=1)
end = Entry(window,width=30)
end.grid(column=1, row=1)
img = PhotoImage(file = r"accuweather.png")
img = img.subsample(10, 10)
label = Label(image=img)
label.place(x=40, y=100, relwidth=1, relheight=1)
def clicked():
startLoc = start.get()
endLoc = end.get()
lbl = Label(window, text="\n\n")
lbl.grid(column=1, row=3)
lblP = Label(window, text=" When should you leave? \n ")
lblP.grid(column=1, row=4)
if(startLoc!="" and endLoc !=""):
startLoc.rstrip()
startLoc.lstrip()
endLoc.rstrip()
endLoc.lstrip()
lbl = Label(window, text="Finding safest time to depart...")
lbl.grid(column=1, row=2)
window.update()
waitTime = LTAT.main(startLoc,endLoc)
if(waitTime==0):
pText = ("The best time for you to leave for\n " +str(endLoc)+" would be NOW.")
else:
pText = "The best time for you to leave for\n " +str(endLoc)+" would be in "+str(waitTime)+" HOUR"+ ("S"if waitTime>1 else "")
lblP.configure(text = pText)
btn = Button(window, text="Search", command=clicked)
btn.grid(column=2, row=1)
window.mainloop()
|
# Iterable protocol: can be called by iter() to get an iterator
# Iterator protocol: can be called by next() to fetch the next item
my_iterable = [1, 2, 3, 4]
my_iterator = iter(my_iterable)
print(my_iterator.__next__())
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
# print(next(my_iterator)) # <- raises exception (StopIteration) when it reaches the end
def is_empty(iterable):
i = iter(iterable)
try:
i.__next__()
return False
except StopIteration:
return True
print(is_empty({}))
|
# strings are homogeneous immutable sequence of unicode chars
# the common usage with the other languages:
print("len('English'):", len('English'))
# Strings are immutable so += re-binds variables reference to a new var. This may cause performance degradation
print("'Eng' + 'lish':", 'Eng' + 'lish')
print("names = ', '.join(['John', 'Bill', 'Anna']):", ', '.join(['John', 'Bill', 'Anna']))
names = ', '.join(['John', 'Bill', 'Anna'])
print("names.split(','): ", names.split(","))
# python idiomatic string concatenation:
print("''.join(['concatenated', ' ', 'string']):", ''.join(['concatenated', ' ', 'string']))
# use partition() together with tuple unpacking to destruct string into sub-strings
departure, separator, destination = "Montreal->Toronto".partition('->')
print("\ndeparture, separator, destination:", departure, separator, destination)
# _ usually represents unused variables
departure, _, destination = "Montreal->Toronto".partition('->')
print("departure, destination:", departure, destination)
# use string.format function to print values easily
input_t = (1, 2)
print("Elements are {input_tuple[0]}, {input_tuple[1]}".format(input_tuple=input_t))
|
from pprint import pprint
letters = ['a', 'b', 'c']
numbers = [1, 2, 3]
combined = [letters, numbers]
print("combined:")
pprint(combined, width=20)
print("----zipped_with_index----")
zipped_with_index = zip(combined[0], combined[1]) # manually select the inner lists with index
for item in zipped_with_index:
print(item)
print("----zipped_with_star----")
zipped_with_star = zip(*combined) # instead of suing indexes, we can just unpack the 2d array
for item in zipped_with_star:
print(item)
print("---------")
pprint(list(zip(*combined)), width=20)
|
from typing import Callable
def first_name(name):
""" Normal function statement """
return name.split()[0]
# Lambdas are actually of type Callable
func1: Callable[[str, int], str] = lambda name, age, : name.split()[-1]
func2: Callable[[], None] = lambda: print("I take no arguments and products no returns")
# No return keyword is allowed in lambda expressions
func3: Callable[[], int] = lambda: 1 # returns 1
# the built-in callable() function can be used for determining if an object can be called
print("callable(first_name)", callable(first_name))
print("callable(func1)", callable(func1))
print("callable(func2)", callable(func2))
print("callable(3)", callable(3))
|
class Point1D:
def __init__(self, x):
self.x = x
class Point2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
"""
Supports str(object) method
str() produces a readable, human-friendly representation of an object (not programmer orientated)
By default, str() simply calls repr()
str() is for clients
"""
return "({}, {}) __str__".format(self.x, self.y)
def __repr__(self):
"""
Supports repr(object) method
repr() produces and unambiguous string representation of an object
the result of repr() should contain more information than the result of str()
always write a repr() for your classes (The default implementation is not useful)
repr() is used when showing elements of a collection
repr() is for developers
"""
return "Point2D(x={}, y={}) __repr__".format(self.x, self.y)
def __format__(self, format_spec):
"""
Supports "{}".format(Point2D(1, 2))
By default, __format__() calls __str__
:param format_spec:
:return:
"""
return "[Formatted point: {}, {}, {}]".format(self.x, self.y, format_spec)
if __name__ == "__main__":
p1 = Point1D(26)
print("repr(p1):", repr(p1))
print("str(p1):", str(p1))
print("\n")
p2 = Point2D(26, 28)
print("repr(p2):", repr(p2))
print("str(p2):", str(p2))
print("\n")
print("This is a point: {}".format(p2))
|
class ShippingContainer:
next_serial = 100
def __init__(self, owner_code, content):
self.owner_code = owner_code
self.content = content
self.serial = ShippingContainer._get_next_serial()
@classmethod
def _get_next_serial(cls):
result = cls.next_serial
cls.next_serial += 1
return result
@classmethod
def create_empty(cls, owner_code, *args, **kwargs):
return cls(owner_code, None, *args, **kwargs)
@classmethod
def create_with_item(cls, owner_code, items, *args, **kwargs):
return cls(owner_code, items, *args, **kwargs)
class FridgeContainer(ShippingContainer):
MAX_CELSIUS = 4
def __init__(self, owner_code, content, celsius):
""" The initializer of parent classes are not called implicitly by Python """
super().__init__(owner_code, content)
if celsius > FridgeContainer.MAX_CELSIUS:
raise ValueError("Too hot!")
self._celsius = celsius
@property # https://stackoverflow.com/a/17330273/3363541
def celsius(self):
"""
High level:
@property converts celsius method into something that, when accessed, works like an attribute: instance.celsius
Under the hood:
* A new property object is created and bond to the name of "celsius"
* A reference to the original definition of method "celsius" is in the property object (how decorator works)
* A set of property method is already declared by this time, e.g. fget, fset. However, they = None (see doc)
* Getter, setter, deleter methods can be then created by using decorators under this property
"""
print("property (getter) method called")
return self._celsius
@celsius.setter
def celsius(self, value):
"""
The setter method is registered under the "celsius" property object
Setter method name must match the property name ("celsius", in this case)
"""
print("property (setter) setter method called")
self._celsius = value
if __name__ == "__main__":
child_instance = FridgeContainer.create_with_item("ABC Corp.", [1, 2, 3, 4], -16)
print("--- object created ---")
print("child_instance.celsius: ", child_instance.celsius) # "celsius" getter method is accessed like an attribute
child_instance.celsius = -100 # no ending (), "celsius" setter method is accessed as if is is an attribute
print("--- object property updated ---")
print("child_instance.celsius: ", child_instance.celsius)
|
x=raw_input("Enter the number: ")
x=int(x)
try:
x != 0
y= 10 / (x*1.0)
print y
except:
print '0 is not accepted'
|
def strange_algo(x, y):
z = 0
step = 0
while x != 0:
step += 1
some = (x % 2)*" not"
print(f"x={x} y{some}={y} z={z}")
if x % 2 == 1:
z = z + y
x = x // 2
y = y * 2
some = (x % 2)*" not"
print(f"x={x} y{some}={y} z={z}")
print(f"Z={z}")
print(f"steps = {step}")
def strange_algo_2(x, y):
power = 1
z = 0
while x // power > 0:
if x % power == 1:
print(z)
z += y * power
power *= 2
print(f"Z={z}")
strange_algo_2(17, 3)
|
import random as rand
from error import Error
import card as cardManager
class Player:
def __init__(self,socket):
"""Constructor for player"""
self.playerid = 0 # player id for attack/defend
self.currentHand = [] # store current cards in hand
self.AI = False # future implementations of AI Control
self.conn = socket
self.trump = 0
def addHand(self,newCard):
"""Adds a card into players hand - used for the drawing functions"""
"""newCard currently accepted as int, will change to card class"""
if type(newCard) == int:
if newCard < 0 or newCard > 51:
Error("Attempt to add card out of range")
self.currentHand.append(newCard)
else:
Error("newCard incorrect type")
def attack(self): # need to check defenders handcount
"""Select a card from player's current hand and returns it"""
"""Always returns a list of values"""
if self.AI:
# return rand.randint(0,len(self.currentHand))
Error("AI not yet implemented for Attacking")
else:
print("Select card from... ")
cardManager.printHand(self.currentHand)
card = int(input("to your attack: "))
while card not in self.currentHand: # error checking
print("Please select a valid card from...", end = " ")
cardManager.printHand(self.currentHand)
card = int(input())
self.currentHand.remove(card)
card = self.checkDoubles(card)
return card
def checkDoubles(self,card): # need to check defenders handcount...
"""Attack helper function if attacker's hand contains multiple of same rank"""
multipleCards = [card]
for i in range(4): # checking all other possible cards of same rank
card_plus = card + 13 * i # checking higher values
card_minus = card - 13 * i # checking lower values
if card_plus in self.currentHand and card_plus < 51 and card_plus != card and card_plus not in multipleCards:
print("Do you wish to add:")
cardManager.printHand([card_plus])
prompt= input("to your attack? (y/n):")
while prompt != 'y' and prompt != 'n': # input checking
print("Do you wish to add:")
cardManager.printHand([card_plus])
prompt = input("to your attack? (y/n):")
if prompt == 'y':
print("added")
multipleCards.append(card_plus)
self.currentHand.remove(card_plus)
else:
print("Did not add")
if card_minus in self.currentHand and card_minus > 0 and card_plus != card and card_minus not in multipleCards:
print("Do you wish to add:")
cardManager.printHand([card_minus])
prompt = input("to your attack? (y/n):")
while prompt != 'y' and prompt != 'n': # input checking
print("Do you wish to add:")
cardManager.printHand([card_minus])
prompt = input("to your attack? (y/n):")
if prompt == 'y':
print("added")
multipleCards.append(card_minus)
self.currentHand.remove(card_minus)
else:
print("Did not add")
return multipleCards
def followUpAttack(self, validCards):
"""Attack was successfully blocked and attack wishes to attack more"""
print("Select card from... ")
cardManager.printHand(validCards)
card = int(input("to your attack: "))
while card not in validCards: # error checking
print(card)
print("Please select a valid card from...")
cardManager.printHand(validCards)
card = int(input("to your attack: "))
self.currentHand.remove(card)
card = self.checkDoubles(card)
return card
def followUpDefend(self,targets,discardPile): # need to add defending with same ranking card
"""Will handle the entire players defend phase, inputs is all the cards being attacked with
and the defender must handle all of them"""
"""Accept targets as a list"""
"""Return list - discardCards (if 0 means defender accepts all the cards)"""
if len(self.currentHand) < len(targets): #Goes against the rules of the game
Error("Incorrect amount of targets")
discardCards = discardPile
forfeit = False
if self.AI:
Error("AI not yet implemented for defending")
else:
print("Cards that are currently attacking P" + str(self.playerid) + ":")
cardManager.printNon(targets)
print("Cards in P" + str(self.playerid) + " hand to defend with:")
cardManager.printHand(self.currentHand)
for attackCard in targets: # iterate thru all attackers
validDefend = False
defendCard = 0
while validDefend == False and forfeit == False:
print("which card do you want to defend with from:" , end=" ")
cardManager.printNon([attackCard])
defendCard = int(input())
while defendCard not in self.currentHand: # input checking
defendCard = int(input("which card do you want to defend with?"))
# check if defenderCard is larger/ choose new card or give up
validDefend = cardManager.compare(defendCard,attackCard)
if validDefend == False:
print("Failed defense...")
prompt = input("Do you wish to give up defense? (y/n)")
while prompt != "y" and prompt != 'n': # input checking
prompt = input("Do you wish to give up defense? (y/n)")
if prompt == 'y':
forfeit = True
break
else:
print("valid defend!")
self.currentHand.remove(defendCard)
discardCards.append(defendCard)
discardCards.append(attackCard)
if forfeit:
break
#results handling:
if forfeit:
for card in discardCards:
self.currentHand.append(card)
for card in targets:
if card not in self.currentHand:
self.currentHand.append(card)
discardCards.clear()
return discardCards
def defend(self,targets): # need to add defending with same ranking card
"""Will handle the entire players defend phase, inputs is all the cards being attacked with
and the defender must handle all of them"""
"""Accept targets as a list"""
"""Return list - discardCards (if 0 means defender accepts all the cards)"""
if len(self.currentHand) < len(targets): #Goes against the rules of the game
Error("Incorrect amount of targets")
discardCards = []
forfeit = False
if self.AI:
Error("AI not yet implemented for defending")
else:
print("Cards that are currently attacking P" + str(self.playerid) + ":")
cardManager.printNon(targets)
print("Cards in P" + str(self.playerid) + " hand to defend with:")
cardManager.printHand(self.currentHand)
for attackCard in targets: # iterate thru all attackers
validDefend = False
defendCard = 0
while validDefend == False and forfeit == False:
print("which card do you want to defend with from:" , end=" ")
cardManager.printNon([attackCard])
defendCard = int(input())
while defendCard not in self.currentHand: # input checking
defendCard = int(input("which card do you want to defend with?"))
# check if defenderCard is larger/ choose new card or give up
validDefend = cardManager.compare(defendCard,attackCard)
if validDefend == 'evaded':
print("Perfect block")
self.currentHand.remove(defendCard)
return (['evaded',defendCard] + targets)
if validDefend == False:
print("Failed defense...")
prompt = input("Do you wish to give up defense? (y/n)")
while prompt != "y" and prompt != 'n': # input checking
prompt = input("Do you wish to give up defense? (y/n)")
if prompt == 'y':
forfeit = True
break
else:
print("valid defend!")
self.currentHand.remove(defendCard)
discardCards.append(defendCard)
discardCards.append(attackCard)
if forfeit:
break
#results handling:
if forfeit:
for card in discardCards:
self.currentHand.append(card)
for card in targets:
if card not in self.currentHand:
self.currentHand.append(card)
discardCards.clear()
return discardCards
|
class MatrixFunctions(self):
def __init__(self, a, b):
self.a=a
self.b=b
def matrixaddf(self):
c=[[],[],[]]
for i in range(0,3):
for j in range(0,3):
z=self.a[i][j]+self.b[i][j]
c[i].append(z)
return c
def matrixsubf(self):
c=[[],[],[]]
for i in range(0,3):
for j in range(0,3):
z=self.a[i][j]-self.b[i][j]
c[i].append(z)
return c
def matrixequalf(self):
c = [[],[],[]]
z=0
for i in range(0, 3):
for j in range(0, 3):
x = self.a[i][j] - self.b[i][j]
z+=x
if z== 0:
return("matrix are equal")
else:
return("matrix not equal")
if __name__ == "__main__":
a=[]
b=[]
for i in range(0,3):
print("matrix enter:a",i+1,sep="")
x=list(map(int,input().split()))
a.append(x)
for i in range(0,3):
print("matrix enter b.",i+1,sep="")
x = list(map(int, input().split()))
b.append(x)
m = MatrixFunctions(a, b)
ops=input("1.Addition 2.Subtraction 3.equal ")
if (ops=="1" or ops=="addition"):
print(m.matrixaddf())
elif(ops=="2" or ops=="Subtraction"):
print(m.matrixsubf())
elif(ops=="3" or ops=="equal"):
print(m.matrixequalf())
|
class Gizmo:
def __init__(self):
print('Gizmo is: %d' %id(self))
x = Gizmo()
def ct(name):
print(name)
cx = ct
print(id(cx), id(ct))
print(cx is ct, cx == ct)
print(dir(Gizmo))
|
# List: []
# Dictionary: {}
# Tuple: ()
# Tuple: immutable
# List: mutable
post = ('Python Basics', 'Intro guide to python', 'Some cool python content')
# Tuple unpacking
title, sub_heading, content = post
# Equivalent to Tuple unpacking
# title = post[0]
# sub_heading = post[1]
# content = post[2]
print(title)
print(sub_heading)
print(content)
# adding elements to tuple
post = ('Python Basics', 'Intro guide to python', 'Some cool python content')
print(id(post))
print(id(post))
post += ('published',)# you cant change a tuple - we are reasigning the name post to a new tuple
print(id(post)) # id changes
title, sub_heading, content, status = post
print(title)
print(sub_heading)
print(content)
print(status)
# nesting lists into tuples
post = ('Python Basics', 'Intro guide to Python', 'Some cool python content')
tags = ['python', 'coding', 'tutorial']
post += (tags,)
print(post[-1][1]) # how to grab items in tuple and lists
# slicing tuples
post = ('Python Basics', 'Intro guide to Python', 'Some cool python content', 'published')
print(post[1::2])
# removing elements in tuple
post = ('Python Basics', 'Intro guide to Python', 'Some cool python content', 'published')
# Removing elements from end
post = post[:-1]
# Removing elements from beginning
post = post[1:]
# Removing specific element (messy/not recommended)
post = list(post)
post.remove('published')
post = tuple(post)
print(post)
# using tuples as keys
priority_index = {
(1, 'premier'): [1, 34, 12],
(1, 'mvp'): [84, 22, 24],
(2, 'standard'): [93, 81, 3],
}
# call as a list otherwise it would just be a view object
print(list(priority_index.keys()))
# zip() 2 lists into a tuple
positions = ['2b', '3b', 'ss', 'dh']
players = ['Altuve', 'Bregman', 'Correa', 'Gattis']
scoreboard = zip(positions, players)
print(list(scoreboard))
|
"""
Assignment: Names
Write the following function.
Part I
Given the following list:
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
Copy
Create a program that outputs:
Michael Jordan
John Rosales
Mark Guillen
KB Tonel
Copy
Part II
Now, given the following dictionary:
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name' : 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
Copy
Create a program that prints the following format (including number of characters in each combined name):
Students
1 - MICHAEL JORDAN - 13
2 - JOHN ROSALES - 11
3 - MARK GUILLEN - 11
4 - KB TONEL - 7
Instructors
1 - MICHAEL CHOI - 11
2 - MARTIN PURYEAR - 13
"""
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name' : 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
def show_students(arr):
for student in students:
print student['first_name'], student['last_name']
def show_all(users):
for role in users:
counter = 0
print role
for person in users[role]:
counter += 1
first_name = person['first_name'].upper()
last_name = person['last_name'].upper()
length = len(first_name) + len(last_name)
print "{} - {} {} - {}".format(counter, first_name, last_name, length)
show_students(students)
show_all(users)
|
def fizzbuzz():
# loop from 0 to 100
for i in range(101):
#as we loop, check if number is evenly divisible by 3
if i % 3 == 0 and i % 5 == 0:
print "fizzbuzz"
elif i % 3 == 0:
print "fizz"
elif i % 5 == 0:
print "buzz"
else:
print i
fizzbuzz()
|
""" Creates an index of all the files contained in the path's folder and subfolders.
The module creates an list of dicts representing all the files in the folder and subfolders
of the path provided. That index can then be filtered and dumped in a csv file.
Typical usage:
index = Indexer("../")
index.create_index(min_size="1 GB")
index.write_to_file()
"""
import os
import json
import re
import csv
from time import ctime
class Indexer:
""" Creates an index of all the files contained in the provided path's folder and subfolders.
Attributes:
path (str): represents the absolute or relative path of the folder to index.
files (list): list of dicts representing the indexed files. Filled by the create_index method.
types (dict): represents the type of files according to their extension. Loaded from a json file by default.
__uniques(list): lisgt of dicts representing all the unique files.
__duplicates(list): list of dicts representing all the duplicate files.
Public Methods:
create_index: Creates dict for each file contained in the path attribute's folder and subfolders.
filter_duplicates: Filters a list of dicts representing files to only keep files that have the same name and
size.
filter_by_min_size: Filters a list of dict representing files to keep files that are at least as big as the
provided argument.
write_to_file: Creates or overwrite a csv file representing all the files.
"""
def __init__(self, path):
"""Inits the Indexer class with path, files, __uniques, __duplicates and types atrtibutes."""
self.path = path
self.files = []
self.__uniques = []
self.__duplicates = []
self.__found_duplicate = False
with open("./types.json", "r") as types_file:
self.types = json.loads(types_file.read())
def __is_exception(self, path_function, file_path, dirpath):
"""Returns True if the os.path function passed raises an exception."""
try:
path_function(dirpath, file_path) if dirpath else path_function(file_path)
return False
except Exception as exception:
print("Parsing File Error:", exception)
return True
def __get_file_info_str(self, path_function, file_path, dirpath=""):
"""Returns a default value if the path function raised an exception or the value returned
by that function"""
if self.__is_exception(path_function, file_path, dirpath):
return "Parsing Error"
return path_function(dirpath, file_path) if dirpath else path_function(file_path)
def __get_file_info_int(self, path_function, file_path, dirpath=""):
"""Returns a default value if the path function raised an exception or the value returned
by that function"""
if self.__is_exception(path_function, file_path, dirpath):
return 0
return path_function(dirpath, file_path) if dirpath else path_function(file_path)
def __get_type(self, file_extension, types=None):
"""Returns a string representing the type of a file based on its extension."""
if types is None:
types = self.types
file_type = "other"
for key in types:
if file_extension in types[key]:
file_type = key
return file_type
def __parse_size(self, size):
"""Turns a string representing the size of a file into an integer of the size of the file.
The function assumes that each size unit is 1024 times bigger than the previous one.
Args:
size (str): a string representing a size in B, KB, MB, GB or TB (e.g.: 123 KB).
Returns:
int: the size of the file in Bytes
Raises:
ValueError: Invalid argument string for the size.
"""
valid = re.search(r"^\d+\.*\d*\s*[KMGT]*B$", size.upper())
if valid is None:
raise ValueError("Invalid argument string")
valid_str = valid.group(0)
value = float(re.search(r"^\d+\.*\d*", valid_str).group(0))
unit = re.search(r"[KMGT]*B$", valid_str).group(0)
exponent = {"B": 0, "KB": 10, "MB": 20, "GB": 30, "TB": 40}
return value * 2 ** exponent[unit]
def __filter_by_min_size(self, size, file):
"""Checks if the input file matches the input minimum size."""
return file["File Size"] >= self.__parse_size(size)
def __filter_by_max_size(self, size, file):
"""Checks if the input file matches the input maximum size."""
return file["File Size"] <= self.__parse_size(size)
def __is_duplicate(self, file_one, file_two):
"""Checks if two files are duplicates based on their name and size."""
if file_one["File Name"] == file_two["File Name"] and file_one["File Size"] == file_two["File Size"]:
return True
return False
def __set_found_duplicate(self, ):
pass
def create_index(self, duplicates=False, **filters):
"""Creates dict for each file contained in the path attribute's folder and subfolders
and apply provided filters.
Returns:
list: a list of dicts representing each file.
"""
print("Creating index...")
for dirpath, _, filenames in os.walk(self.path):
for filename in filenames:
file_path = self.__get_file_info_str(os.path.join, filename, dirpath)
file_item = {
"Absolute Path": self.__get_file_info_str(os.path.abspath, file_path),
"File Name": self.__get_file_info_str(os.path.basename, file_path),
"File Size": self.__get_file_info_int(os.path.getsize, file_path),
"Last Access": ctime(self.__get_file_info_int(os.path.getatime, file_path)),
"Creation": ctime(self.__get_file_info_int(os.path.getctime, file_path)),
"File Extension": self.__get_file_info_str(os.path.splitext, file_path)[1].lower(),
"File Type": self.__get_type(self.__get_file_info_str(os.path.splitext, file_path)[1].lower())
}
filter_methods = {
"min_size": self.__filter_by_min_size,
"max_size": self.__filter_by_max_size,
}
filtered_out = False
if filters:
for name, value in filters.items():
if not filter_methods[name](value, file_item):
filtered_out = True
if not filtered_out:
if duplicates:
for unique in self.__uniques:
if self.__is_duplicate(file_item, unique):
self.__uniques.remove(unique)
self.__duplicates += [unique, file_item]
self.__found_duplicate = True
break
if not self.__found_duplicate:
for duplicate in self.__duplicates:
if self.__is_duplicate(file_item, duplicate):
self.__duplicates.append(file_item)
self.__found_duplicate = True
break
if not self.__found_duplicate:
self.__uniques.append(file_item)
else:
self.files.append(file_item)
if not filters:
self.files.append(file_item)
if duplicates:
self.files = self.__duplicates[:]
print("Index created.")
return self.files[:]
def write_to_file(self, file_name=None, files=None):
""" Creates or overwrite a csv file representing all the files.
Args:
files (list): optional, a list of fict representing files, defaults to the files attribute.
file_name (str): optional, the name of the output file, defaults to 'index'.
"""
if files is None:
files = self.files
if file_name is None:
file_name = "index"
with open(f"{file_name}.csv", "w", newline="", encoding="utf-8") as csvfile:
fieldnames = ["Absolute Path", "File Name", "File Size", "Last Access", "Creation", "File Extension", "File Type"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for file_name in files:
print("Writing:", file_name["File Name"])
writer.writerow(file_name)
print("Done writing.")
|
strings = input().split(' ')
search_word = input()
palindrome_list = []
for word in strings:
if word == word[::-1]:
palindrome_list.append(word)
print(f'{palindrome_list}\nFound palindrome {palindrome_list.count(search_word)} times')
'''
wow father mom wow shirt stats
wow
#['wow', 'mom', 'wow', 'stats']
#Found palindrome 2 times
'''
|
grade = float(input())
print('Excellent!' if grade >= 5.5 else '')
|
row, col = input().split(', ')
matrix = [[int(col) for col in input().split(', ')] for _ in range(int(row))]
print(sum([sum(row) for row in matrix]))
print(matrix)
'''
3, 6
7, 1, 3, 3, 2, 1
1, 3, 9, 8, 5, 6
4, 6, 7, 9, 1, 0
'''
|
loop = int(input())
num_list = [int(input()) for _ in range(loop)]
print(f'Max number: {max(num_list)}\nMin number: {min(num_list)}')
'''
5
10
20
304
0
50
#Max number: 304
#Min number: 0
'''
|
#! /usr/bin/env python3
from __future__ import annotations
import Matrix2
import typing
class Vector2:
def __init__(self, x: float = 0, y: float = 0):
self.x = x
self.y = y
def __add__(self, other: Vector2) -> Vector2:
return Vector2(self.x + other.x, self.y + other.y)
def __sub__(self, other: Vector2) -> Vector2:
return Vector2(self.x - other.x, self.y - other.y)
def __mul__(self, other):
''' Scalar product and product by a constant'''
if type(other) == Vector2:
return self.x * other.x + self.y * other.y
elif type(other) == Matrix2.Matrix2:
xx = self.x * other.a + self.y * other.c
yy = self.x * other.b + self.y * other.d
return Vector2(xx, yy)
else:
try: return Vector2(self.x * other, self.y * other)
except TypeError:
return None
def __rmul__(self, other):
if type(other) != Vector2 and type(other) != Matrix2.Matrix2:
return Vector2(self.x * other, self.y * other)
def __or__(self, other: Vector2) -> Matrix2.Matrix2:
''' Outer product '''
mat = [[self.x ** 2, self.x * self.y],
[self.y * self.x, self.y ** 2]]
return Matrix2.Matrix2(mat)
def __list__(self) -> typing.List[float]:
return [self.x, self.y]
def norm2(self) -> float:
''' Square norm '''
return self.x ** 2 + self.y ** 2
def __str__(self):
return " ({0}, {1}) ".format(self.x, self.y)
def copy(self) -> Vector2:
''' Returns a copy of the current vector '''
return Vector2(self.x, self.y)
|
first = input('Enter first number ')
second = input('Enter second number ')
if first > second:
print(first)
else:
print(second)
|
"""
Use a function to find the determinants of any size matrix.
Uses raw python.
The same functionality is available in numpy.linalg.det
"""
from itertools import repeat
from typing import List
def find_determinant(matrix: List[List[int]], expansion_row: int=None) -> int:
"""
Find the determinant of an n x n matrix.
expansion_row parameter will not change answer; it is available as proof
that the choice of expansion_row will not change the answer.
"""
rows, columns = len(matrix), len(matrix[0])
if rows != columns:
raise ValueError(f"Matrix mismatch: {columns} does not equal {rows}")
if expansion_row is None:
expansion_row = 0
else:
expansion_row -= 1
if expansion_row > rows:
raise ValueError("Invalid expansion_row argument")
if rows == 1 and columns == 1:
return matrix[0][0]
if rows == 2 and columns == 2:
return base_determinant(matrix)
cofactors = find_row_cofactors(matrix, expansion_row)
return sum(cofactor * expansion for cofactor, expansion in zip(cofactors,
matrix[expansion_row]))
def base_determinant(matrix: List[List[int]]) -> int:
"""
Find determinant of a 2 x 2 matrix.
"""
if (len(matrix[0]), len(matrix)) != (2, 2):
raise ValueError(f"Matrix mismatch: Not 2 x 2 matrix.")
return (matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0])
def find_row_cofactors(matrix: List[List[int]], expansion_row: int) -> List[int]:
"""
Find the cofactors of the given expansion row of a matrix.
"""
rows, columns = len(matrix), len(matrix[0])
minors = []
for skip in range(rows):
new_matrix = []
for i, row in enumerate(matrix):
if i != expansion_row:
new_matrix_row = []
for idx, num in enumerate(row):
if idx != skip:
new_matrix_row.append(num)
new_matrix.append(new_matrix_row)
minor = find_determinant(new_matrix)
minors.append(minor)
signs = ((-1)**(row + col) for row, col in zip(repeat(expansion_row),
range(columns)))
cofactors = [sign * minor for sign, minor in zip(signs, minors)]
return cofactors
|
# L8 PROBLEM 5
def dToB(n, numDigits):
"""requires: n is a natural number less then 2**numDigits
returns a binary string of length numDigits representing the
decimal number n."""
assert type(n) == int and type(numDigits)==int and n >= 0 and n < 2**numDigits
bStr = ''
while n > 0:
n = n//2
while numDigits - len(bStr) > 0:
bStr = '0' + bStr
return bStr
def genPset(Items):
"""Generate a list of lists representing the power set of items"""
numSubsets = 2**len(Items)
templates = []
for i in range(numSubsets):
templates.append(dtoB(i, len(Items)))
pset = []
for t in templates:
elem = []
for j in range(len(t)):
if t[j] == '1':
elem.append(Items[j])
pset.append(elem)
return pset
###############
from itertools import chain, combinations
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
for result in powerset([1, 2, 3]):
print(result)
results = list(powerset([1, 2, 3]))
print(results)
###
i = set([1, 2, 3])
def powerset_generator(i):
for subset in chain.from_iterable(combinations(i, r) for r in range(len(i)+1)):
yield set(subset)
for i in powerset_generator(i):
print i
|
#!/usr/bin/env python
"""
@author: jstrick
"""
import argparse
parser = argparse.ArgumentParser("A Celsius-to-Fahrenheit converter")
parser.add_argument('ctemp',type=float, metavar='CELSIUS-TEMPERATURE')
args = parser.parse_args()
ftemp = ((9 * args.ctemp) / 5 ) + 32
print("{0:.1f} C is {1:.1f} F".format(args.ctemp,ftemp))
|
#!/usr/bin/env python
"""
@author: jstrick
Created on Wed Mar 20 07:55:25 2013
"""
from datetime import datetime as DateTime
event = DateTime(2012,7,4,11,15)
print(event)
print()
print('{0:%A, %B %d, %Y}'.format(event))
print('{0:%m/%d/%y %I:%M %p}'.format(event))
|
#!/usr/bin/env python
# (c)2015 John Strickler
import re
alice_text = '''
of getting up and picking the daisies, when suddenly a White
Rabbit with pink eyes ran close by her.
There was nothing so VERY remarkable in that; nor did Alice
think it so VERY much out of the way to hear the Rabbit say to
itself, `Oh dear! Oh dear! I shall be late!' (when she thought
it over afterwards, it occurred to her that she ought to have
wondered at this, but at the time it all seemed quite natural);
but when the Rabbit actually TOOK A WATCH OUT OF ITS WAISTCOAT-
POCKET, and looked at it, and then hurried on, Alice started to
her feet, for it flashed across her mind that she had never
before seen a rabbit with either a waistcoat-pocket, or a watch to
take out of it, and burning with curiosity, she ran across the
field after it, and fortunately was just in time to see it pop
down a large rabbit-hole under the hedge.
'''
rx_rabbit = re.compile(r"\brabbit\b", re.I)
replacement = 'badger'
new_text = rx_rabbit.sub(replacement, alice_text)
print(new_text)
|
#!/usr/bin/env python
class UnknownKnightError(Exception):
pass
class Knight(object):
def __init__(self,name):
self._name = name
try:
with open('../DATA/knights.txt') as K:
for line in K:
(name,title,color,quest,cmt) = line[:-1].split(":")
if name == self._name:
self._title = title
self._color = color
self._quest = quest
self._comment = cmt
found = True
break
else:
raise UnknownKnightError('''No such knight as "{0}"'''.format(self._name))
except IOError as err:
print(err)
@property
def name(self):
return self._name
@property
def title(self):
return self._title
@property
def favorite_color(self):
return self._color
@property
def quest(self):
return self._quest
@property
def comment(self):
return self._comment
if __name__== "__main__":
k1 = Knight("Arthur")
print(k1. name, k1.favorite_color, k1.comment, k1.title)
k2 = Knight("Bedevere")
print(k2.name, k2.favorite_color, k2.comment, k2.title)
try:
k3 = Knight("Hillary")
except UnknownKnightError as err:
print(err)
|
#!/usr/bin/env python
from random import randint
for i in range(10):
num = randint(1,15)
print('*' * num)
|
#!/usr/bin/env python
class Animal(object):
def __init__(self,species,name,sound):
self._species = species
self._name = name
self._sound = sound
@property
def species(self):
return self._species
@property
def name(self):
return self._name
def make_sound(self):
print(self._sound)
if __name__ == "__main__":
leo = Animal("African lion","Leo","Roarrrrrrr")
garfield = Animal("cat","Garfield","Meowwwww")
felix = Animal("cat","Felix","Meowwwww")
print(leo.name,"is a",leo.species,"--", end=' ')
leo.make_sound()
print(garfield.name,"is a",garfield.species,"--", end=' ')
garfield.make_sound()
print(felix.name,"is a",felix.species,"--", end=' ')
felix.make_sound()
|
#!/usr/bin/env python
# (c)2015 John Strickler
import re
# text from www.pigeon.org
pigeon_racing = '''
You can seek out your own comfort level with the birds. If you desire a lower-key approach,
with only a handful of homing pigeons for the family to enjoy, that's certainly an
attractive approach for many. The spectrum also includes those who are deeply committed to
racing. Races range in distance from 100 miles to 600 miles, with 300 miles being among the
most popular distances.
'''
rx_number = re.compile(r'\d+')
# Does it match?
if rx_number.search(pigeon_racing):
print('It matches\n')
# get the first match
m = rx_number.search(pigeon_racing)
if m:
print('First match:', m.group(0), '\n') # 0 is default, and can be omitted
else:
print('No match', '\n')
# iterate over all matches
for m in rx_number.finditer(pigeon_racing):
print(m.group()) # 0 not needed
print()
# just get all matches
all_matches = rx_number.findall(pigeon_racing)
print(all_matches, '\n')
|
# Comprehension is a compact way of creating a python data structure from iterators
# List comprehension is a way to build a new list by applying an expression to each item in an iterable
# common way
name = "MadhuSudhanaRaju"
new_list = []
for item in name:
new_list.append(item)
print(new_list)
# pythonic way
new_list = [item for item in name]
print("using comprehension is {} ".format(new_list))
# common way to add items to a list
L = []
L.append(1)
L.append(4)
L.append(9)
L.append(16)
L.append(25)
print(L)
# another approach to add items to a list
L = []
for item in range(1, 6):
L.append(item ** 2)
print(L)
# using list comprehension
l = [1, 2, 3, 4, 5]
pyth_way = [item ** 2 for item in range(1, 6)]
print(pyth_way)
# range(start,end(n-1 item),step)
# print each letter in a string three times and print in a list
s = 'MAD'
new_list = []
for item in s:
new_list.append(item * 3)
print(new_list)
# using list comprehension
str_list = [item * 3 for item in s]
print(str_list)
#
whole_numbers = [-2, -4, -5, 0, 7, 9]
oput = [2, 4, 5, 0, 7, 9]
# convert negative numbers to absolute numbers
L = [abs(x) for x in whole_numbers]
print(L)
# get only numerics
n_str = "Hello 123456 Madhu"
new_ll = [x for x in n_str if x.isdigit()]
print(new_ll)
# using list comprehension convert list items to lower
caps_items = ["A", "M", "C", "D"]
small_items = [item.lower() for item in caps_items]
print(small_items)
# using list comprehension convert list items to upper
small_letters = ['a', 'b', 'c']
caps = [item.upper() for item in small_letters]
print(caps)
# [(1,1),(2,4),(3,9)] # using list comprehension , return output in tuple format
squares_list = [(x, x ** 2) for x in range(1, 4)]
print(squares_list)
# using list comprehension print only first index of each element
words = ["Hello", "Iam", "Madhu", "Python"]
op = ['H', 'I', 'M', 'P']
output = [item[0].lower() for item in words]
print(output)
# using list comprehension print numbers which are greater than 0
whole_numbers = [-2, -4, -5, 0, 7, 9]
L = []
for number in whole_numbers:
if number >= 0:
L.append(number)
print(L)
n = [number for number in whole_numbers if number >= 0]
print(n)
# using list comprehension remove non-aqua animal
aqua_animals = ("fish", "whale", "dolphin", "Human")
non_aqua = [item for item in aqua_animals if item != "Human"]
print(non_aqua)
# 1 to 100 which are divisible by 3 and 5
numbers_div = [number for number in range(1, 100) if number % 3 == 0 and number % 5 == 0]
print(numbers_div)
#
# # 1 to 20 even,odd
obj = [(i, "Even") if i % 2 == 0 else (i, "Odd") for i in range(1, 21)]
print(obj)
normal_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
new_list = []
for outer_list in normal_list:
for inner_list in outer_list:
new_list.append(inner_list)
print(new_list)
# example of nested list comprehension
flat_list_compre = [inner_list_item ** 2 for outer_list in normal_list for inner_list_item in outer_list]
print(flat_list_compre)
|
# -----------
# User Instructions:
#
# Modify the the search function so that it returns
# a shortest path as follows:
#
# [['>', 'v', ' ', ' ', ' ', ' '],
# [' ', '>', '>', '>', '>', 'v'],
# [' ', ' ', ' ', ' ', ' ', 'v'],
# [' ', ' ', ' ', ' ', ' ', 'v'],
# [' ', ' ', ' ', ' ', ' ', '*']]
#
# Where '>', '<', '^', and 'v' refer to right, left,
# up, and down motions. Note that the 'v' should be
# lowercase. '*' should mark the goal cell.
#
# You may assume that all test cases for this function
# will have a path from init to goal.
# ----------
#
# grid = [[0, 0, 1, 0, 0, 0],
# [0, 0, 0, 0, 0, 0],
# [0, 0, 1, 0, 1, 0],
# [0, 0, 1, 0, 1, 0],
# [0, 0, 1, 0, 1, 0]]
grid = [[0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0],
[0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 0]]
init = [0, 0]
goal = [len(grid)-1, len(grid[0])-1]
cost = 1
delta = [[-1, 0 ], # go up
[ 0, -1], # go left
[ 1, 0 ], # go down
[ 0, 1 ]] # go right
delta_name = ['^', '<', 'v', '>']
def find_next_point(init,grid_state) :
#####print('\n\n----- funtion find_next_gen')
obstacle = 1
navigable_space = 0
closed_space = -1
occupied_space = 2
available_position = []
x1 , y1 = init[0] , init[1]
#####print('pop = g , y, x = %s, %s, %s' % (g_val , y, x))
for [dx,dy] in delta :
y2 , x2 = y1 + dy , x1 + dx
#####print('ny, nx = %s, %s ' % (ny, nx), end ='')
if x2>=0 and x2<=len(grid_state)-1 and y2>=0 and y2<=len(grid_state[0])-1:
#####print('search point is INSIDE',end=' ')
if grid_state[x2][y2] == navigable_space :
available_position.append([x2,y2])
grid_state[x2][y2] = occupied_space
#####print('ADDED in next_gen ,', end='')
#####print('available_position =',end=' ' )
#####print(available_position)
###else :
#####print('NO navigable_space')
###else :
#####print('search point is OUTSIDE')
grid_state[x1][y1] = closed_space
#####print('next_gen = ',end='')
#####print(next_gen)
return available_position , grid_state
def find_path(init,goal,grid,directions):
##print('--------- Func find_path')
import copy
grid_state = copy.deepcopy(grid)
path = [[init[0],init[1]]]
p1 = init
for d in directions :
##print('p1 = ',end='')
##print(p1)
##print('d = ',end='')
##print(d)
p2 = [0,0]
p2[0] = p1[0] + delta[d][0]
p2[1] = p1[1] + delta[d][1]
##print('p2 = ',end='')
##print(p2)
available_position , grid_state = find_next_point(p1,grid_state)
##print('available_position = ',end='')
##print(available_position)
if p2 in available_position :
path.append(p2)
p1 = p2
##print('path = ',end='')
##print(path)
else :
break
return path
def show_path(path,grid):
row , col = len(grid) , len(grid[0])
import copy
expand = copy.deepcopy(grid)
for row in range(len(expand)):
for col in range(len(expand[0])):
expand[row][col] = ' '
p1 = path[0]
for p2 in path[1:] :
d = [0,0]
d[0] = p2[0] - p1[0]
d[1] = p2[1] - p1[1]
if d == delta[0] : expand[p1[0]][p1[1]] = delta_name[0]
if d == delta[1] : expand[p1[0]][p1[1]] = delta_name[1]
if d == delta[2] : expand[p1[0]][p1[1]] = delta_name[2]
if d == delta[3] : expand[p1[0]][p1[1]] = delta_name[3]
p1=p2
return expand
def search(grid,init,goal,cost):
# ----------------------------------------
# modify code below
# ----------------------------------------
closed = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
closed[init[0]][init[1]] = 1
x = init[0]
y = init[1]
g = 0
open = [[g, x, y]]
found = False # flag that is set when search is complete
resign = False # flag set if we can't find expand
while not found and not resign:
if len(open) == 0:
resign = True
return 'fail'
else:
open.sort()
open.reverse()
next = open.pop()
x = next[1]
y = next[2]
g = next[0]
if x == goal[0] and y == goal[1]:
found = True
else:
for i in range(len(delta)):
x2 = x + delta[i][0]
y2 = y + delta[i][1]
if x2 >= 0 and x2 < len(grid) and y2 >=0 and y2 < len(grid[0]):
if closed[x2][y2] == 0 and grid[x2][y2] == 0:
g2 = g + cost
open.append([g2, x2, y2])
closed[x2][y2] = 1
##print('g-value = %s' % g )
import itertools as it
for j in it.product((3,2,1,0),repeat = g):
##print('directions = ' , j)
directions = list(j)
path = find_path(init,goal,grid,directions)
##print('Path = ' , path)
if len(path) == g+1 :
if path[-1] == goal :
break
# ### test
# directions = list((3, 2, 3, 3, 3, 3, 2, 2, 2))
# path = find_path(init,goal,grid,directions)
# ##print('-------- Solution Path = ' , path)
# ### test
expand = show_path(path,grid)
expand[goal[0]][goal[1]] = '*'
return expand # make sure you return the shortest path
for row in search(grid,init,goal,cost) :
print(row)
|
# 파이썬과 같은 몇몇 프로그래밍 언어는 Pothole_case 를 더 선호하는 언어라고 합니다.
#
# Example:
#
# codingDojang --> coding_dojang
#
# numGoat30 --> num_goat_3_0
#
# 위 보기와 같이 CameleCase를 Pothole_case 로 바꾸는 함수를 만들어요!
def CameleCase_to_Pothole_case(cc):
pc=''
for c in cc:
if c.isupper():c='_'+c.lower()
elif c.isdigit():c='_'+c
pc+=c
return pc
print(CameleCase_to_Pothole_case('codingDojang'))
print(CameleCase_to_Pothole_case('numGoat30'))
|
# def facto(n):
# if n==1: return 1
# return n*facto(n-1)
#
# print(facto(6))
# def arr_gen(n):
# arr=[]
# for i in range(n):
# arr.append(i)
# yield(arr)
#
# for x in arr_gen(10):
# print(x)
# def fibonacci(n):
# """Ein Fibonacci-Zahlen-Generator"""
# a, b, counter = 0, 1, 0
# while True:
# if (counter > n):
# return
# print(a,end=" ")
# a, b = b, a + b
# counter += 1
# fibonacci(5)
# f = fibonacci(5)
# for x in f:
# # no linefeed is enforced by end="":
# print(x, " ", end="") #
# print()
# def permutations(items):
# n = len(items)
# if n==0: yield []
# else:
# for i in range(len(items)):
# for cc in permutations(items[:i]+items[i+1:]):
# yield [items[i]]+cc
#
# for p in permutations(['r','e','d']): print(''.join(p))
# for p in permutations(list("game")): print(''.join(p) + ", ", end="")
def k_permutations(items, n):
if n==0: yield []
else:
for i in range(len(items)):
for ss in k_permutations(items, n-1):
if (not items[i] in ss):
yield [items[i]]+ss
for p in k_permutations(['r','e','d'],3): print(''.join(p))
|
def insertion_sort(A,n):
for i in range(1,n):
print(i)
key=A[i]
j=i-1
while j>=0 and A[j]>key:
A[j+1]= A[j]
j=j-1
A[j+1]=key
|
def recursive_linear_search(A,n,i,x):
if i>=n:
return "NOT FOUND"
elif A[i]==x:
return i
else:
return recursive_linear_search(A,n,i+1,x)
A=[1,2,3,4,5]
print(recursive_linear_search(A,len(A),0,6))
|
class Phone:
def __init__(self, brand, price):
self.brand = brand
self.price = price
def __call__(self, phoneNumber):
print(f"{self.brand} is calling")
def __str__(self) -> str:
return f"Brand{self.brand}Price = {self.price}"
iphone = Phone("Iphone 7+", 300)
samsung = Phone("Samsung s20", 300)
print(iphone.brand)
print(samsung.price)
|
#Naive approach
def max_prod_naive(arr):
product = 0
for i in range(len(arr)):
for j in range(i+1,len(arr)):
product = max(product,arr[i]*arr[j])
return product
#Fast approach
def max_prod_fast(arr):
p1 = max(arr)
arr.remove(p1)
p2 = max(arr)
return p1*p2
#Stress test
from random import randint
def max_prod_stress(N,M):
while True:
n = randint(2,N)
A = [None]*n
for i in range(n):
A[i] = randint(0,M)
print(A)
result1 = max_prod_naive(A)
result2 = max_prod_fast(A)
if result1==result2:
print('OK')
else:
print('Wrong answer:',result1,result2)
return
max_prod_stress(5,100)
|
num1 = int(input(" Informe un numero qualquer:"))
num2 = int(input(" Informe outro numero qualquer:"))
escolha = 0
while escolha != 5:
print('-'*20)
print(' [1] soma\n',
'[2] multiplicação\n',
'[3] maior\n',
'[4] novos numeros\n',
'[5] sair\n')
print('-'*20)
escolha = int(input('Informe qual sua escolha:'))
if escolha ==1:
resultado = num1 + num2
print(' A soma dos valores escolhidos é : {}'.format(resultado))
elif escolha ==2:
resultado = num1 * num2
print(' A multiplicação dos valores escolhidos são: {}'.format(resultado))
elif escolha ==3:
if num1 > num2:
print('O maior numero é {}'.format(num1))
else:
print(' O maior numero escolhido é {}'.format(num2))
elif escolha == 4:
num1 = int(input(" Informe un numero qualquer:"))
num2 = int(input(" Informe outro numero qualquer:"))
print('Fim do programa')
|
from random import randint
lista = (randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10))
print('Os numeros sortiados foram:', end=" ")
for c in lista:
print(f'{c}',end=" ")
print(f'\nO maior numero sorteado foi {max(lista)}')
print(f'O menor numero sorteado foi {min(lista)}')
|
print('\033[0;33;40m*-\033[m'*20)
print(' Analisador de frase ')
print (' ------PALINDROMO-------')
print('\033[0;33;40m*-\033[m'*20)
frase = str(input(' Digite uma frase \n')).strip().upper()
separar = frase.split()
junto = ''.join(separar)
inverso = ''
for letra in range(len(junto) -1,-1,-1):
inverso += junto[letra]
if inverso == junto:
print(" A frase \033[1;32m {} \033[m \n lida de trás para frente:\033[1;32m {}\033[m, \n é um PALINDROMO".format(junto,inverso))
else:
print(" A frase \033[1;32m {} \033[m \n lida de trás para frente:\033[1;32m {}\033[m, \n \033[1;31m NÃO \033[m é um PALINDROMO".format(junto, inverso))
|
lista = []
impar = []
par = []
while True:
num = int(input('Informe um numero inteiro:'))
lista.append(num)
if num%2 ==0:
par.append(num)
else:
impar.append(num)
stop = str(input('Deseja continuar inserindo numeros em sua lista?[S/N]')).upper().strip()[0]
while stop not in 'SN':
stop = str(input('Opção invalida, Digite novamente[S/N]')).upper().strip()[0]
if stop in 'N':
break
print(f'Os numeros da sua lista são {lista}')
print(f'Os numeros pares digitador foram {par}')
print(f'Os numeros impares digitador foram {impar}')
|
numero = int(input('Digite um numero de 0 a 9999: \n'))
unid = numero // 1 % 10
dez = numero // 10 % 10
cen = numero // 100 % 10
mil = numero // 1000 % 10
print(' Analisando o numero {} '.format(numero))
print(' Unidade : {}'.format(unid))
print(' Dezena : {}'.format(dez))
print(' Centena : {}'.format(cen))
print(' Milhar : {}'.format(mil))
|
num1 = int(input('Informe um numero inteiro \n'))
num2 = int(input('Informe outro numero inteiro \n'))
if num1 > num2:
print(' O primeiro numero {} é maior que o segundo numero {}'.format(num1,num2))
elif num2 > num1:
print(' O segundo numero {} é maior que o primeiro numero {}'.format(num2,num1))
else:
print('Os numeros {} e {} são iguais'.format(num1,num2))
|
from datetime import date
ano = int(input('Informe o ano em que você nasceu: \n'))
idade = (date.today().year )-ano
tempo = idade - 18
tempo1 = 18 - idade
if idade == 18:
print('Parabens! Você esta no periodo de alistamento')
elif idade > 18:
print('Você já passssou do periodo de alistamento a {} anos'.format(tempo))
elif idade < 18:
print('Você esta quase no periodo de alistamento, falta apenas {} anos'.format(tempo1))
print('*'*20)
print(' Patria ama Brasil')
print('*'*20)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
# 数据
x = [1, 2, 3]
y = [7, 2, 9]
x2 = [1, 2, 3]
y2 = [10, 20,2]
# 定义数据标签
plt.plot(x, y, label = "First one")
plt.plot(x2, y2, label = "Second one")
# 定义图标横竖轴标签,图标名称
plt.xlabel('Plot number')
plt.ylabel('Important var')
plt.title('Interestinng Graph\ncheck it out')
# 用于显示数据标签名称
plt.legend()
plt.show()
|
# Sum of Array Element
def sumArrayElement(arry, n):
s = 0 # Variable
for i in range(0, n): # Loop for array summation
s = s + arry[i] # Sum the current array element with right element
print("%d " % s) # Print the results
arry = [9, 3, 5, 2, 6, 8] # Given Array
n = 6 # Given Frequency for Looping
sumArrayElement(arry, n) # Call Function
|
""" Program to read data from file, process it
and draw graphs using matplotlib
Appropriate titles should be given
and axis should be labeled
Author: Varun Aggarwal
Username: aggarw82
Github: https://github.com/Environmental-Informatics/08-time-series-analysis-with-pandas-aggarw82
"""
import pandas as pd
import numpy as np
from pandas import Series, DataFrame, Panel
import matplotlib.pyplot as plt
'''read file. Specify date column in parse_dates'''
inFile = "WabashRiver_DailyDischarge_20150317-20160324.txt"
data = pd.read_csv(inFile,
sep='\t',
parse_dates=['datetime'],
index_col=['datetime'],
header=24,
skiprows=[25],
warn_bad_lines=True)
# print(data.head())
'''convert to time series'''
data = Series(data['01_00060'])
# print(data.head())
'''re-sample for daily average'''
daily_avg = data.resample("D").mean()
daily_avg.plot(title = 'Daily Avg Discharge')
plt.xlabel('Date')
plt.ylabel('Discharge (cu ft/s)')
plt.savefig('Daily Avg Discharge.pdf')
plt.show()
'''10 highest discharge days'''
highest = daily_avg.sort_values(ascending=False)[:10]
highest.plot(title = 'Top 10 Highest Discharge', style='--o')
plt.xlabel('Date')
plt.ylabel('Discharge (cu ft/s)')
plt.savefig('Top 10 Discharge.pdf')
plt.show()
'''re-sample for monthly average'''
monthly_avg = data.resample("M").mean()
monthly_avg.plot(title = 'Monthly Avg Discharge', style='--o')
plt.xlabel('Date')
plt.ylabel('Discharge (cu ft/s)')
plt.savefig('Monthly Avg Discharge.pdf')
plt.show()
|
age = int(input("Please enter your age:"))
if age>= 21:
print('yes,you can.')
else:
print('No,you can\'t. Idiot.')
|
#Give the absolute Value of X
def my_abs(x):
print(abs(x))
#Try it, fill in the blank!
my_abs(-3)
#Solve for x in 0 = ax**2+by+c
def quadratic(a, b, c):
X1 = ((-1*b + ((b**2)-4*a*c))**.5)/(2*a)
X2 = ((-1*b + ((b**2)-4*a*c))**.5)/(2*a)
if X1 ==complex:
print ('no solution')
else:
print('X1 = %d,', format(round(X1,3),round(X2,3)))
if X2 ==complex:
print('noX2')
else:
print('X2 = %d', format(round(X2,3)))
#Try it
quadratic(1,3,-4)
|
class City:
def __init__(self, passing_name = "Unknown", pop = 0, gdp = 0):
self.name = passing_name
self.population = pop
self.gdp_per_capita = gdp
def __str__(self):
return "{} has {} people, with gdp per capita of ${}.".format(self.name, self.population,self.gdp_per_capita)
def __gt__(self, other):
if self.gdp_per_capita > other.gdp_per_capita:
return True
elif self.gdp_per_capita == other.gdp_per_capita:
if self.population > other.population:
return True
else:
return False
def __add__(self, other):
total_city = City("{} and {} together".format(self.name, other.name), self.population+other.population, self.gdp_per_capita+other.gdp_per_capita)
return total_city
def __eq__ (self, other):
return self.population == other.population and self.gdp_per_capita == other.gdp_per_capita
city1 = City("New York", 8537000, 50000000)
print(city1)
print(city1.name)
print()
Boston = City("Boston", 300000, 50000000)
print (city1 > Boston)
print(city1+Boston)
print(city1==Boston)
|
def sed(pattern, replace, source, dest):
"""Reads a source file and writes the destination file.
In each line, replaces pattern with replace.
pattern: string
replace: string
source: string filename
dest: string filename
"""
f1 = open(source)
f2 = open(source, 'w')
for line in f1:
new_line = line.replace(pattern, replace)
f2.write(new_line)
f1.close()
f2.close()
pattern = 'Hey Jude'
replace = 'Hi Donald'
source = 'sed_tester.txt'
dest = 'new_' + source
sed(pattern, replace, source, dest)
|
def factor(n):
#Housekeeping--> Make sure the numbers entered are integers and above zero.
if not int(n)==n and n>=0:
print("Positive and whole number please.")
#Run a loop that stops at the number divided by any number up to itself.
#If the remainder of dividing the original number by the tested number, print that number.
for i in range(1, n + 1):
if n % i == 0:
print(i)
|
from threading import Lock
class FileFifo:
def __init__(self, filename):
self.filename = filename
self.lock = Lock()
try:
f = open(filename,'w')
f.close()
except:
print("impossibile aprire o creare il file")
raise
def append(self, line):
self.lock.acquire()
try:
with open(self.filename, "a+") as f: # Apre il file di testo
f.write(line + "\r\n")
finally:
self.lock.release()
def popleft(self):
self.lock.acquire()
try:
with open(self.filename, "r") as f: # Apre il file di testo
lines = f.readlines()
if len(lines) > 0:
line = lines.pop(0).strip()
else:
line = None
filestring = "".join(lines)
with open(self.filename, "w") as f: # Apre il file di testo
f.write(filestring)
finally:
self.lock.release()
return line
def peekleft(self):
self.lock.acquire()
try:
with open(self.filename, "r") as f: # Apre il file di testo
line = f.readline()
finally:
self.lock.release()
if line == "":
line = None
return line
def appendleft(self, line):
self.lock.acquire()
try:
with open(self.filename, "r") as f: # Apre il file di testo
lines = f.readlines()
lines.insert(0, line+"\r\n")
filestring = "".join(lines)
with open(self.filename, "w") as f: # Apre il file di testo
f.write(filestring)
finally:
self.lock.release()
def test():
tau = 0.5
import threading
import random
import time
ff = FileFifo("prova.txt")
random.seed()
def prod():
while True:
x = random.random()
time.sleep(x * 2 * tau)
ff.append("x = " + str(x))
def cons():
while True:
time.sleep(tau)
value = ff.popleft()
if value is None:
print("ran out of lines")
else:
coin = random.random() - 0.5
if coin > 0:
ff.appendleft(value)
print("putting back: " + value)
else:
print("I got: " + value)
p = threading.Thread(target = prod)
p.daemon = True
c = threading.Thread(target = cons)
c.daemon = True
p.start()
c.start()
while True:
pass
if __name__ == "__main__":
test()
|
# Crie um programa que pergunte o nome de um funcionário, seu salário atual e uma alíquota de aumento
# em seguida este programa deve retornar o novo salário com o reajuste solicitado
print('=' * 40)
print('{:^40}'.format('Reajuste salarial'))
print('=' * 40)
nome = str(input('Informe o nome do funcionário: '))
salario = float(input('Informe o salário atual do funcionário: '))
aumento = float(input('Informe o percentual de aumento pretendido: '))
salfinal = (salario / 100) * (100 + aumento)
print('\n{} recebe atualmente R$ {:.2f}, com o aumento de {:.2f}%'.format(nome, salario, aumento))
print('passará a receber R$ {:.2f}'.format(salfinal))
|
#!/usr/bin/python3
N = 15
# The main routine of AI.
# input: str[N][N] field : state of the field.
# output: int[2] : where to put a stone in this turn.
def Think(field):
CENTER = (int(N / 2), int(N / 2))
flg=0
flg2=0
best_position = (0, 0)
#best_position2 = nul
for i in range(N):
for j in range(N):
if field[i][j] != '.':
continue
position = (i, j)
#Assume to put a stone on (i,j) as opponent 対戦相手
field[i][j]='X'
# Assume to put a stone on (i, j).
field[i][j] = 'O'
if DoHaveNStones(field, position,5,'O'):
DebugPrint('I have a winning choice at (%d, %d)' % (i, j))
return position
if DoHaveNStones(field,position,4,'O'):
DebugPrint('I have a three stones at (%d, %d)' % (i,j))
best_position=position
flg=1
if DoHaveNStones(field,position,4,'X'):
DebugPrint('I need to stop at (%d, %d)' % (i,j))
flg2=1
#if GetDistance(best_position2, CENTER) > GetDistance(position, CENTER):
# best_position2=position
# Revert the assumption.
field[i][j] = '.'
if flg!=1 and flg2!=1 and GetDistance(best_position, CENTER) > GetDistance(position, CENTER):
best_position = position
return best_position
#returns truee if you have a three-stones line from |position|.Returns false otherwise.
def DoHaveNStones(field,position,N,player):
if(player=='X'):
return (CountStonesOnLineX(field, position, (1, 1)) >= N or
CountStonesOnLineX(field, position, (1, 0)) >= N or
CountStonesOnLineX(field, position, (1, -1)) >= N or
CountStonesOnLineX(field, position, (0, 1)) >= N)
else:
return (CountStonesOnLine(field, position, (1, 1)) >= N or
CountStonesOnLine(field, position, (1, 0)) >= N or
CountStonesOnLine(field, position, (1, -1)) >= N or
CountStonesOnLine(field, position, (0, 1)) >= N)
# Returns true if you have a five-stones line from |position|. Returns false otherwise.
def DoHaveFiveStones(field, position):
return (CountStonesOnLine(field, position, (1, 1)) >= 5 or
CountStonesOnLine(field, position, (1, 0)) >= 5 or
CountStonesOnLine(field, position, (1, -1)) >= 5 or
CountStonesOnLine(field, position, (0, 1)) >= 5)
# Returns the number of stones on the line segment on the direction of |diff| from |position|.
def CountStonesOnLine(field, position, diff):
count = 0
row = position[0]
col = position[1]
while True:
if row < 0 or col < 0 or row >= N or col >= N or field[row][col] != 'O':
break
row += diff[0]
col += diff[1]
count += 1
row = position[0] - diff[0]
col = position[1] - diff[1]
while True:
if row < 0 or col < 0 or row >= N or col >= N or field[row][col] != 'O':
break
row -= diff[0]
col -= diff[1]
count += 1
return count
# Returns the number of stones on the line segment on the direction of |diff| from |position|.
def CountStonesOnLineX(field, position, diff):
count = 0
row = position[0]
col = position[1]
while True:
if row < 0 or col < 0 or row >= N or col >= N or field[row][col] != 'X':
break
row += diff[0]
col += diff[1]
count += 1
row = position[0] - diff[0]
col = position[1] - diff[1]
while True:
if row < 0 or col < 0 or row >= N or col >= N or field[row][col] != 'X':
break
row -= diff[0]
col -= diff[1]
count += 1
return count
# Returns the Manhattan distance from |a| to |b|.
def GetDistance(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
# Outputs |msg| to stderr; This is actually a thin wrapper of print().
def DebugPrint(msg):
import sys
print(msg, file=sys.stderr)
# =============================================================================
# DO NOT EDIT FOLLOWING FUNCTIONS
# =============================================================================
def main():
field = Input()
position = Think(field)
Output(position)
def Input():
field = [list(input()) for i in range(N)]
return field
def Output(position):
print(position[0], position[1])
if __name__ == '__main__':
main()
|
# coding: utf-8
# # Chapter 1: Computing with Python
# ### Overview: a typical Python-based scientific computing stack.
# 
#
# * Resources:
# - [SciPy](http://www.scipy.org)
# - [Python Numeric & Scientific topics](http://wiki.python.org/moin/NumericAndScientific)
# ## Interpreter
# - The easist way to execute Python code: run the program directly.
# - Use Jupyter magic command to write Python source file to disk:
# In[1]:
get_ipython().run_cell_magic('writefile', 'hello.py', 'print("Hello from Python!")')
# * Use the ! system shell command (included in the Python Jupyter kernel) to interactively run Python with hello.py as its argument.
# In[2]:
get_ipython().system('python hello.py')
# In[3]:
get_ipython().system('python --version')
# ## Input and output caching
#
# * Input & output history can be accessed using __In__ (a list) & __Out__ (a dictionary). Both can be indexed with a cell number.
# In[4]:
3 * 3
# In[5]:
In[1]
# * A single underscore = the most recent output;
# * A double underscore = the _next_ most recent output.
# In[6]:
1+1
# In[7]:
2+2
# In[8]:
_, __
# In[9]:
# In = a list
In
# In[10]:
# Out = a dictionary
Out
# In[11]:
# Suppress output results by ending statement with a semicolon
1+2;
# ## Autocompletion
#
# * The __Tab__ key activates autocompletion (displays list of symbol names that are valid completions of what has been typed thus far.)
# In[12]:
import os
# * Results of typing "os.w", followed by \t:
#
# 
# ## Documentation
#
# * "Docstrings" provide a built-in reference manual for most Python modules. Display the docstring by appending a Python object with "?".
# In[13]:
import math
# In[14]:
get_ipython().run_line_magic('pinfo', 'math.cos')
# ## Interaction with System Shell
#
# * Anything after ! is evaluated using the system shell, such as bash.
# * (I use Ubuntu Linux as my laptop OS. Your Windows equivalents will vary.)
# In[15]:
get_ipython().system('touch file1.py file2.py file3.py')
# In[16]:
get_ipython().system('ls file*')
# In[17]:
# output of a system shell command
# can be captured in a Python variable
files = get_ipython().getoutput('ls file*')
# In[18]:
len(files)
# In[19]:
files
# In[20]:
# pass Python variable values to shell commands
# by prefixing the variable name with $.
file = "file1.py"
# In[21]:
get_ipython().system('ls -l $file')
# ## IPython Extensions
#
# * Commands start with one or two "%" characters. A single % is used for single-line commands; dual %% is used for cells (multiple lines).
#
# * %lsmagic returns a list of available commands.
# In[23]:
get_ipython().run_line_magic('pinfo', '%lsmagic')
# ## Running scripts
# In[24]:
get_ipython().run_cell_magic('writefile', 'fib.py', '\ndef fib(N): \n """ \n Return a list of the first N Fibonacci numbers.\n """ \n f0, f1 = 0, 1\n f = [1] * N\n for n in range(1, N):\n f[n] = f0 + f1\n f0, f1 = f1, f[n]\n\n return f\n\nprint(fib(10))')
# In[25]:
get_ipython().system('python fib.py')
# In[26]:
get_ipython().run_line_magic('run', 'fib.py')
# In[27]:
fib(6)
# ## Listing all defined symbols
#
# * __%who__ lists all defined symbols
# * __%whos__ provides more detailed info.
# In[28]:
get_ipython().run_line_magic('who', '')
# In[29]:
get_ipython().run_line_magic('whos', '')
# ## Debugger
#
# * Use __%debug__ to step directly into the Python debugger.
# In[30]:
# fib function fails - can't use floating point numbers.
fib(1.0)
# In[32]:
get_ipython().run_line_magic('debug', '')
# ## Resetting the Python namespace
# In[34]:
get_ipython().run_line_magic('reset', '')
# ## Timing and profiling code
#
# * __%timeit__ and __%time__ provide simple benchmarking utilities.
# In[35]:
# first, re-define fibonacci code used above.
def fib(N):
"""
Return a list of the first N Fibonacci numbers.
"""
f0, f1 = 0, 1
f = [1] * N
for n in range(1, N):
f[n] = f0 + f1
f0, f1 = f1, f[n]
return f
# In[36]:
get_ipython().run_line_magic('timeit', 'fib(50)')
# In[37]:
# %time only runs once. less accurate estimate.
result = get_ipython().run_line_magic('time', 'fib(100)')
# In[38]:
len(result)
# * The __cProfile__ module provides __%prun__ (for statements) and __%run__ (for external scripts) profiling commands.
# In[39]:
import numpy as np
def random_walker_max_distance(M, N):
"""
Simulate N random walkers taking M steps
Return the largest distance from the starting point.
"""
trajectories = [np.random.randn(M).cumsum()
for _ in range(N)]
return np.max(np.abs(trajectories))
# In[40]:
# returns call counts, runtime & cume runtime for
# each function.
get_ipython().run_line_magic('prun', 'random_walker_max_distance(400, 10000)')
# ### Jupyter: External image rendering
# In[41]:
from IPython.display import display, Image, HTML, Math
# In[42]:
Image(url='http://python.org/images/python-logo.gif')
# ### Jupyter: HTML rendering
# In[47]:
import scipy, numpy, matplotlib
modules = [numpy, matplotlib, scipy]
row = "<tr><td>%s</td><td>%s</td></tr>"
rows = "\n".join(
[row %
(module.__name__, module.__version__)
for module in modules])
table = "<table><tr><th>Library</th><th>Version</th></tr> %s </table>" % rows
# In[48]:
HTML(table)
# In[50]:
# another method
class HTMLdisplayer(object):
def __init__(self,code):
self.code = code
def _repr_html_(self):
return self.code
HTMLdisplayer(table)
# ### Jupyter: Formula rendering using Latex
# In[53]:
Math(r'\hat{H} = -\frac{1}{2}\epsilon \hat{\sigma}_z-\frac{1}{2}\delta \hat{\sigma}_x')
# ### Jupyter: UI Widgets
#
# ** Needs debugging: slider widget doesn't appear. **
# In[54]:
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
def f(mu):
X = stats.norm(loc=mu, scale=np.sqrt(mu))
N = stats.poisson(mu)
x = np.linspace(0, X.ppf(0.999))
n = np.arange(0, x[-1])
fig, ax = plt.subplots()
ax.plot(x, X.pdf(x), color='black', lw=2, label="Normal($\mu=%d, \sigma^2=%d$)" % (mu,mu))
ax.bar(n, N.pmf(n), align='edge', label=r"Poisson($\lambda=%d$)" % mu)
ax.set_ylim(0, X.pdf(x).max() * 1.25)
ax.legend(loc=2, ncol=2)
plt.close(fig)
return fig
# In[55]:
from ipywidgets import interact
import ipywidgets as widgets
# In[58]:
interact(f, mu=widgets.FloatSlider(min=1.0, max=20.0, step=1.0));
# ## nbconvert to HTML file
# In[59]:
get_ipython().system('jupyter nbconvert --to html ch01-intro.ipynb')
# ## nbconvert to PDF file
# * [Requires a LaTeX environment](https://nbconvert.readthedocs.io/en/latest/install.html#installing-tex) to be installed.
# * On this system (Ubuntu Linux): ```sudo apt-get install texlive-xetex```
# In[60]:
get_ipython().system('jupyter nbconvert --to pdf ch01-intro.ipynb;')
# ## nbconvert to pure Python source code
# In[4]:
get_ipython().system('jupyter nbconvert ch01-intro.ipynb --to python')
# In[5]:
get_ipython().system('ls ch01*')
|
#Import the modules we need
import turtle
import random
#Create a screen
win = turtle.Screen()
#Draw a finish line
naychelle = turtle.Turtle()
naychelle.color("red")
naychelle.penup()
naychelle.goto(150,300)
naychelle.pendown()
naychelle.right(90)
naychelle.forward(500)
#Create two turtles and give them colors and turtle shape
peter = turtle.Turtle()
grace = turtle.Turtle()
peter.color("purple")
grace.color("lightblue")
peter.shape("turtle")
grace.shape("turtle")
#Move the turtles to their starting positions
peter.penup()
grace.penup()
peter.goto(-200,-10)
grace.goto(-200, 10)
peter.pendown()
grace.pendown()
#Send them racing across the screen
x_grace = grace.xcor()
x_peter = peter.xcor()
while x_grace and x_peter < 150:
speed0 = random.randrange(1,10)#random speed--new each time
speed1 = random.randrange(1,10)
peter.speed(speed0)
grace.speed(speed1)
distance0 = random.randrange (-1,70)#random distance each time
distance1 = random.randrange (-1,70)
peter.forward(distance0)
x_peter = peter.xcor() #Update how far Peter went
if x_peter >= 150: #stop running if someone crosses the finish line
break
grace.forward(distance1)
x_grace = grace.xcor() #Update how far Grace went
if x_grace >= 150: #stop running if someone crosses the finish line
break
win.exitonclick()
|
# On a pour depart, un chiffre aleatoire qui est choisi
# apres, le jeu nous demande de taper un nombre entre 0 et 100
# si la reponse est inerieur au nombre aleatoir
# il doit afficher "le nombre est plus grand"
# si la reponse est superieur au nombre aleatoire
# il doit afficher "le nombre est plus petit"
# et sinon, vous avez gane.
# Ici on importe une librairie qui contient des fonctions aleatoire.
import random
# intialise nos variables nbaleatoire et trouver nbaleatoire sera genere par l'odrinateur.
# Trouver est un boonlean qui est egale a Faux.
nbAleatoire = random.randrange(0,100)
trouver = False
# Tant que trouver est egale a Faux on continue.
while trouver == False:
print("tape un nombre entre 0 et 100")
# On converti le nombre tape au clavier en int
reponse = int(input() )
# On compare notre reponse avec le nbaleatoire.
if reponse < nbAleatoire:
print("le nombre est plus grand")
elif reponse > nbAleatoire:
print("le nombre est plus petit")
else:
print("vous avez gagne")
# On passe trouver a Vrai pour arreter la boucle.
trouver = True
|
#!/bin/python3
import os
import sys
#
# Complete the diagonalDifference function below.
#
def diagonalDifference(a):
#
# Write your code here.
#
#n = int(input())
total1 = 0
total2 = 0
for i in range(n):
total1 += a[i][i]
total2 += a[i][n-i-1]
return abs(total1 - total2)
if __name__ == '__main__':
f = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
a = []
for _ in range(n):
a.append(list(map(int, input().rstrip().split())))
result = diagonalDifference(a)
f.write(str(result) + '\n')
f.close()
|
from typing import List
class A:
x: int
def __init__(self, x):
print('creating A')
self.x = x
def foo(self):
self.x += 1
class B(A):
y: int
def __init__(self, y):
super().__init__(2 * y)
self.y = y
def goo(self):
self.foo()
def foo(self):
self.x -= 1
a = A(1)
b = B(1)
w: List[A] = [a, b]
b.goo()
print(b.x)
# print(b.c)
#
# print(b.x)
# for r in w:
# print(r.x)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.