blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
37275d292fae16c77c1b10d231b25d273e4a5082 | YTLogos/my_python_learning | /multiplication_table.py | 571 | 4.21875 | 4 | #!/home/taoyan/anaconda3/bin/python3
# -*- coding: UTF-8 -*-
# filename:multiplication_table.py
# author by:taoyan
#九九乘法表十分简单
for i in range(1,10):
for j in range(1,i+1):
print("{}*{}={}\t".format(i,j,i*j), end="")
print()
'''
下面是参考别人的方法:
class multiplication_table():
def paint(self, n=9):
for i in range(1,n+1):
for j in range(1,i+1):
print("{1}*{0}={2}\t".format(i,j,i*j), end="")
print()
table=multiplication_table()
table.paint
''' | false |
43cad148e487746b571b248a876ffa908efcd399 | Rae420/python-wd1902 | /day2/chapter6/functions/more-functions.py | 502 | 4.1875 | 4 | def add_range(num1, num2):
total = 0
for num1 in range(num1, num2+1):
total += num1
print(total)
add_range(3, 20)
print('')
def even_numbers(num1, num2):
if num2 % 2 != 0:
print('please supply an even number')
else:
while num1 <= num2:
if num1 % 2 == 0:
print(num1)
num1 += 1
var1 = int(input('Enter start number : '))
var2 = int(input('Enter stop number : '))
even_numbers(var1, var2)
| false |
23604a6c43668ad273bbfb22c7196103369734df | adunk/python-practice | /Playground/practice_code/standard/_tempfile_lib.py | 479 | 4.21875 | 4 | import tempfile
# useful for storing data only useful for the execution of the program
# Create a temporary file
temp = tempfile.TemporaryFile()
# Write to a temporary file
# write() takes a bytes object. In order to convert a string to a bytes literal, we place b in front of the string
temp.write(b'Save this special number for me: 12349876')
# Reset seek pointer back to 0
temp.seek(0)
# Read the temporary file
print(temp.read())
# Close the temporary file
temp.close()
| true |
fcc9dfc361292c9f16dcbd2ad39535b4a27bc9e7 | adunk/python-practice | /Playground/practice_code/standard/_date_time.py | 1,085 | 4.3125 | 4 | import calendar
from datetime import datetime
from datetime import timedelta
now = datetime.now()
print(now)
print(now.date())
print(now.year)
print(now.month)
print(now.hour)
print(now.minute)
print(now.second)
print(now.time())
# date() and time() are methods as they combine several attributes
# Change the formatting of a time display. These change how days are formatted
print(now.strftime('%a (short) %A (long) %d (day of the month)'))
print(now.strftime('%b (short) %B (long) %m (number of the month)'))
print(now.strftime('%A %B %d'))
print(now.strftime('%A %B %d %H:%M:%S %p'))
print(now.strftime('%A %B %d %H:%M:%S %p, %Y'))
# Creating future and past date objects
future = now + timedelta(days=2)
past = now - timedelta(weeks=3)
print(future.date())
print(past.date())
if future > past:
print('Comparision of date objects works')
cal = calendar.month(2001, 10)
print(cal)
cal2 = calendar.weekday(2001, 10, 11)
# Index of the day of the week starting with 0 for Monday
# This prints 3 (Thursday)
print(cal2)
print(calendar.isleap(1999))
print(calendar.isleap(2000)) | true |
6df111c48708618cd09cf59e4d6a924693761f09 | PythonCoder8/python-174-exercises-wb | /Intro-to-Programming/exercise-1.py | 770 | 4.6875 | 5 | '''
Exercise 1: Mailing Address
Create a program that displays your name and complete mailing address formatted in
the manner that you would usually see it on the outside of an envelope. Your program
does not need to read any input from the user.
'''
recipentName = input('Enter your name: ')
homeAddress = input('Enter your home address: ')
streetName = input('Enter your street name: ')
city = input('Enter the name of the city that you live in: ')
province = input('Enter the name of the province/state that you live in: ')
postalCode = input('Enter your postal code/zip code: ')
country = input('Enter the country that you live in: ')
print(f'\nMailing address:\n\n{recipentName}\n{homeAddress}{streetName}\n{city} {province} {postalCode}\n{country}')
| true |
687b36241453acb14547356e338d4164adf8f0a8 | michealodwyer26/MPT-Senior | /Labs/Week 4/decompose.py | 635 | 4.1875 | 4 | '''
python program for prime number decomposition of n
Input: n - int
Output: primes with their power
How to?
repeat for each potential prime divisor
test if is divisor
extract its power and write them
'''
import math
def primeDecomp():
# read input
n = int(input("n = "))
# repeat for potential divisors
for d in range(2, n+1):
# test if d is a div of n
if n%d == 0:
# find the power of d
power = 0
while n%d == 0:
power = power + 1
n = n // d
# end while
# print d and power
print(d, "**", power)
# end if
# end for
# end def
primeDecomp()
| true |
f7ba87b71fe436891b00644f07254c5b9ae8aa9d | michealodwyer26/MPT-Senior | /Labs/Week 2/invest.py | 1,063 | 4.28125 | 4 | # import modules
import math
# function to calculate the investment over 3 years
def invest():
'''
Invest amount1 euro at rate interest
write the numbers for each year
'''
# Input amount1, rate
amount = float(input("initial amount = "))
rate = float(input("invest rate = "))
# calculate and print amount1, interst1, finalAmount1
amount1 = amount
interest1 = amount1 * rate
finalAmount1 = amount1 + interest1
print("Year 1 (amount, interest, final amount): ", amount1, interest1, finalAmount1)
# calculate and print amount2, interst2, finalAmount2
amount2 = finalAmount1
interest2 = amount2 * rate
finalAmount2 = amount2 + interest2
print("Year 1 (amount, interest, final amount): ", amount2, interest2, finalAmount2)
# calculate and print amount3, interst3, finalAmount3
amount3 = finalAmount2
interest3 = amount3 * rate
finalAmount3 = amount3 + interest1
print("Year 1 (amount, interest, final amount): ", amount3, interest3, finalAmount3)
# end def
invest()
| true |
be72e40218804c383e510bcbc277d0dc07acbfa3 | michealodwyer26/MPT-Senior | /Homework/Week 5/testGoldback.py | 660 | 4.25 | 4 | '''
python program to test the Goldback Conjecture for an even number n
'''
import math
def isPrime(n):
ans = True
if n == 0 or n == 1:
ans = False
return ans
if n != 0 and n % 2 == 0:
ans = False
return ans
for d in range(3, int(math.sqrt(n)) + 1, 2):
if n % d == 0:
ans = False
return ans
return ans
def testGoldback(n):
for p1 in range(1, n+1):
for p2 in range(1, n+1):
if isPrime(p1) and isPrime(p2):
if p1 + p2 == n:
return p1, p2
return "False Conjecture"
def main():
n = int(input("Please enter an even integer: "))
p1, p2 = testGoldback(n)
print(p1, "+", p2, "=", n)
main() | false |
8ec383e8220c535da9b7ebe146477415dbd06fb9 | michealodwyer26/MPT-Senior | /Homework/Week 2/solveTriangle.py | 937 | 4.28125 | 4 | '''
This program inputs the sides a, b, c and calculates
the angles, perimeter and the area of the triangle.
'''
# import modules
import math
# function to solve out a triangle
def solveTriangle():
# input float a, b, c
a = float(input("a = "))
b = float(input("b = "))
c = float(input("c = "))
# calculate and print the perimeter
perimeter = a + b + c
print("Perimeter = ", perimeter)
# calculate and print the area
p = (a + b + c) / 2
area = math.sqrt(p * (p - a) * (p - b) * (p -c))
print("Area = "area)
# calculate and print the angles A, B, C
cosA = (b*b + c*c - a*a) / (2 * b * c)
A = math.degrees(math.acos(cosA)) # math.acos() = cos**-1() or cos to the power of -1
print("A = ", A)
cosB = (a*a + c*c - b*b) / (2 * a * c)
B = math.degrees(math.acos(cosB))
print("B = ", B)
cosC = (a*a + b*b - c*c) / (2 * a * b)
C = math.degrees(math.acos(cosC))
print("C = ", C)
# end def
solveTriangle()
| true |
b4327743ca0f951cb21efee5fcd6a07eab03025c | hima-del/Learn_Python | /06_loops/01_if_else.py | 577 | 4.28125 | 4 | #The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition".
a=200
b=20
if b>a:
print("b is greater than a")
elif a==b:
print("a and b are equal")
else:
print("a is greater than b")
#and
x=200
y=33
z=500
if x>y and z>x:
print("both conditions are true")
if x>y or x>z:
print("atleast one condition is true")
#if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.
a=33
b=200
if b>a:
pass
| true |
c31bfd1e1e032e3074a94420446dab9d248092cf | dsnyder489/Python | /variables.py | 754 | 4.15625 | 4 | #!/usr/bin/env python2
hello_str = "Hello World"
hello_int = 21
hello_bool = True
hello_tuple = (21, 32)
hello_list = ["Hello,","this","is","a","list"]
hello_list = list()
hello_list.append("Hello,")
hello_list.append("this")
hello_list.append("is")
hello_list.append("a")
hello_list.append("list")
hello_dict = {"first_name":"Dave",
"last_name":"Snyder",
"eye_colour":"blue"}
print(hello_list)
hello_list[4]+="!"
hello_list[4] = hello_list[4] + "!"
print(hello_list[4])
print(str(hello_tuple[0]))
print(hello_dict["first_name"]+" "+hello_dict["last_name"]+" has "+
hello_dict["eye_colour"]+" eyes.")
print("{0}{1}has{2}eyes.".format(hello_dict["first_name"],hello_dict["last_name"],
hello_dict["eye_colour"]))
| false |
eaa809ece2f8aee8634b7f2b7566809245d86ec1 | michaelgagliardi/2019_2020_projects | /big_calculator.py | 1,915 | 4.15625 | 4 | '''------------------------------------------------------
Import Modules
---------------------------------------------------------'''
from BigNumber import BigNumber
'''------------------------------------------------------
Main program starts here
---------------------------------------------------------'''
print("\nWelcome to BigNumber Calculator")
print("================================")
# closed loop, keep executing until user select 0
while True:
command=input("\nChoose Operation (none,==,+,-,scale,*) or q for quit: ")
if command=="q": #exit program
print("Goodbye!")
break
# input error handling
if not(command in ["none","==","+","-","scale","*"]):
continue
# read and convert first input string to a BigNumber
big1=BigNumber(input("Enter first number: "))
print(big1) # display
if not(command in ["none","scale"]):
# read and convert second input string to a BigNumber
big2=BigNumber(input("Enter second number: "))
print(big2) # display
if command=="scale": # scale the big number and return a new big number
factor=int(input("Enter the scaling factor: "))
big3=big1.scale(factor)
print("Result: "+str(big3))
elif command=="==": # compare the two big numbers
c=big1.compare(big2)
print("first number %s second number"%c)
elif command=="+": # perform big number addition and display
big3=big1.add(big2)
print("Result: "+str(big3))
elif command=="-": # perform big number subtraction and display
big3=big1.subtract(big2)
print("Result: "+str(big3))
elif command=="*": # perform big number multiplication and display
big3=big1.multiply(big2)
print("Result: "+str(big3))
| true |
39a33d4f12d58329dc9da4bf6f894d7f69b7ec8f | ilee38/practice-python | /coding_problems/project_e/2_even_fibonacci_nums.py | 685 | 4.15625 | 4 | #!/usr/bin/env python3
"""Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the
first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the
even-valued terms.
"""
def even_fib_sum(limit):
table = {1: 1, 2: 2}
sum = 2
n = 3
while True:
table[n] = table[n-1] + table[n-2]
next = table[n]
if next > limit:
break
if next % 2 == 0:
sum += next
n += 1
return sum
def main():
sum = even_fib_sum(4000000)
print("sum is: ", sum)
if __name__ == "__main__":
main()
| true |
92dba2e586ad1cfc713cdf353d988dfcf2ef3630 | ilee38/practice-python | /binary_search/binary_search.py | 1,203 | 4.25 | 4 | """
# Implementation of a recursive binary search algorithm
# Returns the index of the target element in a sorted array,
# an index value of -1 indicates the target elemen was not found
"""
def binarySearch(arr, target, low, high):
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif low > high:
return -1
if arr[mid] > target:
return binarySearch(arr, target, low, mid-1)
else:
return binarySearch(arr, target, mid+1, high)
# Tests for the binarySearch function
if __name__ == '__main__':
myArr = [5, 6]
indexOfTarget = binarySearch(myArr, 5, 0, len(myArr)-1)
print("index of 5: ", indexOfTarget)
indexOfTarget = binarySearch(myArr, 6, 0, len(myArr)-1)
print("index of 6: ", indexOfTarget)
myArr2 = [1, 8, 11, 51, 78, 95, 132, 256, 389]
targetIndex = binarySearch(myArr2, 132, 0, len(myArr2)-1)
print("index of 132: ", targetIndex)
targetIndex = binarySearch(myArr2, 1, 0, len(myArr2)-1)
print("index of 1: ", targetIndex)
targetIndex = binarySearch(myArr2, 389, 0, len(myArr2)-1)
print("index of 389: ", targetIndex)
targetIndex = binarySearch(myArr2, 500, 0, len(myArr2)-1)
print("index of 500 (not in the array): ", targetIndex)
| true |
76eacc70e929ceb8a27bdc043a90f38155272923 | ilee38/practice-python | /coding_problems/project_e/16_power_digit_sum.py | 243 | 4.15625 | 4 | #!/usr/bin/env python3
def pow_digit_sum(power):
total_sum = 0
str_qty = str(2**power)
for digit in str_qty:
total_sum += int(digit)
return total_sum
def main():
print(pow_digit_sum(1000))
if __name__ == '__main__':
main() | false |
b53c2669597df2d82297c118b688a086f00b4e52 | ilee38/practice-python | /graphs/topological_sort.py | 2,062 | 4.21875 | 4 | #!/usr/bin/env python3
from directed_graph import *
def topological_sort(G):
""" Performs topological sort on a directed graph if no cycles exist.
Parameters:
G - directed graph represented with an adjacency list
Returns:
returns a dict containing the edges in the discovery path as:
{destination : source}
"""
if not has_cycles(G):
dfs_visit = G.DFS()
return dfs_visit
else:
print("Graph has cycles")
return None
def has_cycles(G):
""" Checks for cycles in a directed graph
parameters:
G - a directed graph represented with an adjacency list
returns:
boolean value indicating wether there was a cycle in the graph
"""
cycles = False
STARTED = 1
FINISHED = 2
for v in G.Adj:
visited = {}
to_finish = [v]
while to_finish and not cycles:
v = to_finish.pop()
if v in visited:
if visited[v] == STARTED:
visited[v] = FINISHED
else:
visited[v] = STARTED
to_finish.append(v) #v has been started, but not finished yet
for e in G.Adj[v]:
if e.opposite(v) in visited:
if visited[e.opposite(v)] == STARTED:
cycles = True
else:
to_finish.append(e.opposite(v))
if cycles:
break
return cycles
def main():
DG = DirectedGraph()
#Create vertices
U = DG.insert_vertex("u")
V = DG.insert_vertex("v")
W = DG.insert_vertex("w")
X = DG.insert_vertex("x")
Y = DG.insert_vertex("y")
Z = DG.insert_vertex("z")
#Create edges
U_V = DG.insert_edge(U, V, 0)
U_W = DG.insert_edge(U, W, 0)
U_X = DG.insert_edge(U, X, 0)
V_W = DG.insert_edge(V, W, 0)
#W_U = DG.insert_edge(W, U, 0)
W_X = DG.insert_edge(W, X, 0)
W_Y = DG.insert_edge(W, Y, 0)
W_Z = DG.insert_edge(W, Z, 0)
print("Number of vertices: ", DG.vertex_count())
print("Number of edges: ", DG.edge_count())
print("")
topological_order = topological_sort(DG)
print("Topological order:")
print(topological_order)
if __name__ == '__main__':
main() | true |
07d74a32b25ff613f67bac48fed73db109aedbfd | John-Witter/Udemy-Python-for-Data-Structures-Algorithms-and-Interviews- | /Section 12: Array Sequences/sentence-reversal-1st.py | 496 | 4.125 | 4 | def rev_word(s):
revS = s.split() # create a list from the s string
revS = revS[::-1] # reverse the list
return ' '.join(revS) # return the list as a string with a space b/t words
print(rev_word('Hi John, are you ready to go?'))
# OUTPUT: 'go? to ready you are John, Hi'
print(rev_word(' space before'))
# OUTPUT: 'before space'
print(rev_word('space after '))
# OUTPUT: 'after space'
print(rev_word(' Hello John how are you '))
# OUTPUT: 'you are how John Hello'
| true |
a087f2a392d5e5ae45352fc9470eb03d79270c91 | vikasdongare/python-for-everbody | /Python Data Structures/Assign8_4.py | 753 | 4.375 | 4 | #Open the file romeo.txt and read it line by line. For each line, split the line
#into a list of words using the split() method. The program should build a list
#of words. For each word on each line check to see if the word is already in the
#list and if not append it to the list. When the program completes, sort and
#print the resulting words in alphabetical order.
#You can download the sample data at http://www.py4e.com/code3/romeo.txt
#Date :- 27 April 2020
#Done By :- Vikas Dongare
fn = open("romeo.txt",'r')
words = list()
for line in fn:
line = line.rstrip()
line = line.split()
for word in line:
if word in words:
continue
else:
words.append(word)
words.sort()
print(words)
| true |
94b8215f1231cf510ee949a2ff9c51501b6f7c29 | imvivek71/Python-complete-solution | /Task8/ListReverse.py | 283 | 4.40625 | 4 | #Write a Python program to reverse the order of the items in the array
#Write a Python program to get the length in bytes of one array item in the internal representation
a = [str(x) for x in input("Enter the elements seperated by space").split()]
a.reverse()
print(a)
print(len(a))
| true |
8007c463c9c8ce5d853b98412155a65df1cf02cf | imvivek71/Python-complete-solution | /Task4ModerateLevel/elementSearch.py | 614 | 4.15625 | 4 | #elements search in a string using loop & if else
str = input("Enter any strng")
z = input("Enter the char to be searched")
counts = 0
if len(z)==1:
if len(z) > 0:
count = 0
for i in range(len(str)):
if z == str[i]:
print("The element is available in index {} the string".format(i))
counts=counts+1
else:
count = count + 1
if (count >= 1&counts==0):
print("The element is not available in the string")
else:
print("You did not enter anything")
else:
print("Enter only single element")
| true |
e4e3a3d3e4da802fc7770348f4a60521d1b72a8e | agasparo/boot2root_42 | /scripts/test.py | 842 | 4.1875 | 4 | #!/usr/bin/python3
import sys
import turtle
import os
if __name__ == '__main__':
turtle.setup()
turtle.position()
filename = "./turtle.txt"
# Open the file as f.
# The function readlines() reads the file.
with open(filename) as f:
content = f.readlines()
# Show the file contents line by line.
# We added the comma to print single newlines and not double newlines.
# This is because the lines contain the newline character '\n'.
for line in content:
lines = line.split(' ');
if (lines[0] == "Recule") :
turtle.backward(float(lines[1]));
if (lines[0] == "Tourne") :
if (lines[1] == "gauche") :
turtle.left(float(lines[3]));
if (lines[1] == "droite") :
turtle.right(float(lines[3]));
if (lines[0] == "Avance") :
turtle.forward(float(lines[1]));
turtle.exitonclick() | true |
eaab59b8dd086f4119bddcb8a5b91b422ec9773a | bharathtintitn/HackerRankProblems | /HackerRankProblems/recursive_digit_sum.py | 1,829 | 4.125 | 4 | '''
We define super digit of an integer using the following rules:
If has only digit, then its super digit is .
Otherwise, the super digit of is equal to the super digit of the digit-sum of . Here, digit-sum of a number is defined as the sum of its digits.
For example, super digit of will be calculated as:
super_digit(9875) = super_digit(9+8+7+5)
= super_digit(29)
= super_digit(2+9)
= super_digit(11)
= super_digit(1+1)
= super_digit(2)
= 2.
You are given two numbers and . You have to calculate the super digit of .
is created when number is concatenated times. That is, if and , then .
Input Format
The first line contains two space separated integers, and .
Constraints
Output Format
Output the super digit of , where is created as described above.
Sample Input 0
148 3
Sample Output 0
3
Explanation 0
Here and , so .
super_digit(P) = super_digit(148148148)
= super_digit(1+4+8+1+4+8+1+4+8)
= super_digit(39)
= super_digit(3+9)
= super_digit(12)
= super_digit(1+2)
= super_digit(3)
= 3. ;;
'''
def sum_str(number, length):
''' return sum of digiits, till you get a single digit.'''
#print "number ",number
zero = length - 1
if zero > 0:
divisor = int('1' + ('0'*zero))
else:
divisor = 10
d, r = divmod(number, divisor)
if d == 0:
return number
total = r
while d != 0:
d, r = divmod(d, 10)
total += r
return sum_str(total)
if __name__ == "__main__":
n, k = raw_input().strip().split()
#print n,k
conc_str = n*int(k)
length = len(conc_str)
#print conc_str
print sum_str(int(conc_str), length)
| true |
0af7fb61665bcfa144b0433bb8cb9bc0644f9d8f | bharathtintitn/HackerRankProblems | /HackerRankProblems/symmetric-difference.py | 775 | 4.3125 | 4 | '''
Task
Given sets of integers, and , print their symmetric difference in ascending order. The term
symmetric difference indicates those values that exist in either or but do not exist in both.
Input Format
The first line of input contains an integer, .
The second line contains space-separated integers.
The third line contains an integer, .
The fourth line contains space-separated integers.
Output Format
Output the symmetric difference integers in ascending order, one per line.
'''
na = int(raw_input().strip())
a = set(map(int, raw_input().strip().split()))
nb = int(raw_input().strip())
b = set(map(int, raw_input().strip().split()))
ar = list(a.difference(b))
br = list(b.difference(a))
print ar , br
ar += br
ar.sort()
for i in ar:
print i
| true |
98433116d7caab7f5c84d6e3edcd15803845f242 | bharathtintitn/HackerRankProblems | /HackerRankProblems/tries.py | 1,227 | 4.1875 | 4 | class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = {}
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: None
"""
curr = self.root
for c in word:
if not curr.get(c, False):
curr[c] = {}
curr = curr[c]
print "word: ", self.root
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
curr = self.root
print "Search:", word, " root:", self.root
for c in word:
print 'charac:', c
if curr.get(c, False):
curr = curr[c]
else:
return False
return True
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
self.search(prefix)
obj = Trie()
import pdb
pdb.set_trace()
obj.insert('apple')
param_2 = obj.search('apple')
param_3 = obj.startsWith(prefix)
| true |
ae7376bb56be79139334eb5c93d78f8e4ee5ec07 | bharathtintitn/HackerRankProblems | /HackerRankProblems/fibonacci-modified.py | 977 | 4.4375 | 4 | import sys
'''
We define a modified Fibonacci sequence using the following definition:
Given terms and where , term is computed using the following relation:
For example, if term t1 = 0 and t2=1, term t3 = 0+1^2 = 1, term t4 = 1 + 1^2 = 2, term
t5 = 1 + 2^2 = 5, and so on.
Given three integers, t1, t2, and n, compute and print term tn of a modified Fibonacci sequence.
Input Format
A single line of three space-separated integers describing the respective values of t1, t2, and n.
Constraints
tn may exceed the range of a 64-bit integer.
Output Format
Print a single integer denoting the value of term tn in the modified Fibonacci sequence where the first two
terms are t1 and t2.
'''
def fibonacci(t1, t2, n):
while n-2 > 0:
t1, t2 = t2, t2*t2 + t1
n -= 1
#print "t1: {}, t2: {}, n: {}".format(t1,t2,n)
return t2
def main():
assert fibonacci(0,1,5) == 5
assert fibonacci(0,1,10) == 84266613096281243382112
if __name__ == "__main__":
main()
| true |
098f8d188e2579e6d80c1fc62d56122a75f10e57 | EffectoftheMind/Python-A-Excersizes | /operations.py | 1,099 | 4.125 | 4 | #calc with exceptions
def add(a, b):
return(a + b)
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print()
while True:
try:
operation = int(input("Select Operation (1, 2, 3, 4): "))
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if operation == 1:
print(add(a, b))
elif operation == 2:
print(subtract(a, b))
elif operation == 3:
print(multiply(a, b))
elif operation == 4:
print(divide(a, b))
else:
print("Non-Valid Number")
except ZeroDivisionError:
print()
print("Impossible - Can't Divide by Zero")
break
except ValueError:
print()
print("Enter a Whole Number Please")
break
#Example
#while True:
#try:
#age = int(input('Enter your age: '))
#except ValueError:
#print('Enter a whole number!')
#else:
#if age < 21:
#print('Not Allowed!')
#break
#else:
#print('Welcome!')
#break
| true |
98b0c8c6a5a390a5f3f59d90b5b1ecbb3536a410 | EffectoftheMind/Python-A-Excersizes | /semesterfinal.py | 375 | 4.15625 | 4 | tri_input = input("Enter your numbers: ").split(" ")
print()
print()
tri_a = int(tri_input[0])
tri_b = int(tri_input[1])
tri_c = int(tri_input[2])
def tri_type():
if tri_c**2 < tri_a**2 + tri_b**2:
print("The triangle is acute!")
elif tri_c**2 == tri_a**2 + tri_b**2:
print("The triangle is right!")
else:
print("The triangle is obtuse!")
tri_type()
| false |
c8f50e663763b379597f86a71c8aa6c630600354 | Mihirkumar7/letsupgrade-assignment2 | /string is pangram or not.py | 519 | 4.4375 | 4 | # Write a program to check whether a string is a pangram or not.
# Pangram is a sentence or string which contains every letters of english alphabet.
def is_pangram(s): # This function takes string as an argument.
alphabets = 'abcdefghijklmnopqrstuvwxyz'
for ch in alphabets:
if ch not in s.lower():
return False
return True
string = input('Enter the string to check : ')
if is_pangram(string):
print('Yes it is pangram.')
else:
print('No it is not pangram.') | true |
4a4469148c1f690e7fd393ab55ebed4bd779b7d1 | zhangkai98/ProgrammingForThePuzzledBook | /Puzzle7/roots.py | 2,037 | 4.28125 | 4 | #Programming for the Puzzled -- Srini Devadas
#Hip To Be a Square Root
#Given a number, find the square root to within a given error
#Two strategies are shown: Iterative search and bisection search
##Find the square root of a perfect square using iterative search
def findSquareRoot(x):
if x < 0:
print ('Sorry, imaginary numbers are out of scope!')
return
ans = 0
while ans**2 < x:
ans = ans + 1
if ans**2 != x:
print (x, 'is not a perfect square')
print ('Square root of ' + str(x) +
' is close to ' + str(ans - 1))
else:
print ('Square root of ' + str(x) + ' is ' + str(ans))
return
##Find the square root to within a certain error using iterative search
def findSquareRootWithinError(x, epsilon, increment):
if x < 0:
print ('Sorry, imaginary numbers are out of scope!')
return
numGuesses = 0
ans = 0.0
while x - ans**2 > epsilon:
ans += increment
numGuesses += 1
print ('numGuesses =', numGuesses)
if abs(x - ans**2) > epsilon:
print ('Failed on square root of', x)
else:
print (ans, 'is close to square root of', x)
return
##Find the square root to within a certain error using bisection search
def bisectionSearchForSquareRoot(x, epsilon):
if x < 0:
print ('Sorry, imaginary numbers are out of scope!')
return
numGuesses = 0
low = 0.0
high = x
ans = (high + low)/2.0
while abs(ans**2 - x) >= epsilon:
if ans**2 < x:
low = ans
else:
high = ans
ans = (high + low)/2.0
numGuesses += 1
#print('low = ', low, 'high = ', high, 'guess = ', ans)
print ('numGuesses =', numGuesses)
print (ans, 'is close to square root of', x)
return
findSquareRoot(65536)
findSquareRootWithinError(65535, .01, .001)
findSquareRootWithinError(65535, .01, .0001)
findSquareRootWithinError(65535, .01, .00001)
bisectionSearchForSquareRoot(65535, .01)
| true |
e833e62d6b7515e6cabc70e1427cd52cbc3560e8 | rohit00001/Assignment-1-letsupgrade-Python-Essentials | /Assignment 1 letsupgrade/question3.py | 319 | 4.21875 | 4 | #Question 3
#Find sum of n numbers by using the while loop –
#Program
num= int(input("enter the number of terms : "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is", sum) | true |
6fdafdc64f04cd52aba89a3367da671db6e279ec | wissam0alqaisy/python_begin_1 | /begin_3/classes_2.py | 1,675 | 4.59375 | 5 | ###############################################
# #
# Created by Youssef Sully #
# Beginner python #
# classes 1.2 INSTANCE variables 2 #
# methods and __dict__ #
# #
###############################################
# INSTANCE variables 2
# instead of assigning variables to each INSTANCE (classes_1.py),
# we can def a INSTANCE variables inside the class
class StudentType2:
# Initializing INSTANCE variables: self (by convention) act like INSTANCE (student_1)
def __init__(self, f_name, l_name, courses):
self.f_name = f_name
self.l_name = l_name
self.courses = courses
# Functions inside the class called INSTANCE regular methods
# INSTANCE regular methods take an INSTANCE as an argument by default
def email(self):
return '{}.{}@aol.com'.format(self.f_name.lower(), self.l_name.lower())
# assigning self --> new_student_1 (assigned automatically), f_name --> 'Youssef', l_name --> 'Sully',
# courses --> ['CompSci', 'Telecom']
new_student_1 = StudentType2('Youssef', 'Sully', ['CompSci', 'Telecom'])
new_student_2 = StudentType2('Sully', 'Youssef', ['Telecom', 'CompSci'])
print(new_student_1.f_name, new_student_1.l_name, new_student_1.courses)
print(new_student_2.f_name, new_student_2.l_name, new_student_2.courses, "\n")
# __dict__ methods shows all the INSTANCES variables as dictionary
print(new_student_1.__dict__)
print(new_student_2.__dict__, "\n")
# to call the method inside the class
print(new_student_1.email())
print(new_student_2.email())
| true |
7c5868847603b67a03c73c830ea9be7fb0c982a0 | Podakov4/pyCharm | /module_8/lesson_5.py | 581 | 4.125 | 4 | # Задача 5. Антошка, пора копать картошку
performed = int(input('Сколько метров уже вскопали?: '))
space = int(input('Через сколько метров другт от друга растёт картофель?: '))
potato_tuber = 0
for meter in range(performed, 101, space):
potato_tuber += 3
print('Картофеля выкопано:', potato_tuber, 'на', str(meter) + '-м метре')
print()
print('Картофеля выкопано всего:', potato_tuber, 'клубней картофеля')
| false |
0eddfc9e0c7f8552bfa0c0342988a9a420cd3c40 | luisas/PythonCourse | /Python/block1_part1.py | 1,615 | 4.125 | 4 |
# coding: utf-8
# In[114]:
import math
# In[115]:
# First Exercise
def get_cone_volume(radius, height):
"""The function returns the volume of a cone given, in order, radius and height as input"""
return (height/3)*math.pi*(radius**2)
# In[69]:
# Calculate the factorial of a number n in a recursive way
def recursive_factorial(n):
"""The function calculates the factorial of a number n in a recursive way. It takes the number n as an input. """
if n == 0:
return 1
else:
return (n)* recursive_factorial(n-1)
# In[70]:
# Calculate the factorial of a number n in an iterative way
def factorial(n):
""" The function calculates the factorial of a number n in an iterative way. It takes the number n as an input. """
if n==0:
return 1
else:
calculated_factorial = 1
while n > 0:
calculated_factorial*=n
n-=1
return(calculated_factorial)
# In[124]:
def count_down(n, odd=False):
""" This function counts down the number by printing them, from the input n to 0. The compulsory input is the number from which to count down. There is an optional input, which is a boolean: if set to True the funciton will print only Odd numbers. """
while n >=0 :
if( odd == True):
if (n%2)!= 0:
print(n)
else:
print(n)
n-=1
# In[95]:
def get_final_price(price, discount_percentage=10):
"""Return the final price after applying the discount percentage"""
return price-( price* discount_percentage / 100)
| true |
75619da925967dcea3b32d2b922060c2ec48440e | VeeravelManivannan/Python_training | /python_veeravel/numpy_arrays/numpy_excercise.py | 784 | 4.1875 | 4 | weightlist = [89,98,78,101,171,76]
heightlist = [1.78,1.66,1.89,1.76,1.88,1.76]
#printing datatype
#print(type(weightlist))
import numpy
#converting array to numpy array
numpy_weightlist = numpy.array(weightlist)
numpy_heightlist = numpy.array(heightlist)
print("Printing a weight list , without numpy %s" % weightlist )
print("Printing a weight list , with numpy %s " % numpy_weightlist )
#print(numpy_weightlist)
print((numpy_heightlist /numpy_weightlist) **2)
# Print only heights greater than 180
print("printing only height list greater than 180 cm %s " % numpy_heightlist[numpy_heightlist>1.8])
#converting all the weights from kilograms to pounds
numpy_weightlist_inpounds = numpy_weightlist * 2.2
print("weight list in pounds %s " % numpy_weightlist_inpounds)
| true |
f6d61c73127c5d0d6a4de16881457cd05d942e3d | VeeravelManivannan/Python_training | /python_veeravel/closures/closures_trying_out.py | 1,440 | 4.34375 | 4 |
#Scenario1: inner function not returning anything , only using and printing
def outer_function(outer_function_variable_passed_as_arguement):
variable_defined_inside_outer_function = "I am a variable_defined_inside_outer_function "
def inner_function():
print("inside inner function , printing all variables of outer function")
print("values from outer function \n %s" % outer_function_variable_passed_as_arguement)
print("values defined n outer function \n %s" % variable_defined_inside_outer_function)
inner_function()
#Scenario2: inner function not returning anything , 1. innre function is returned as function object 2. innerfunction also retruns
def outer_function2(outer_function2_variable_passed_as_arguement):
variable_defined_inside_outer_function2 = "I am a variable_defined_inside_outer_function2 "
def inner_function2():
return (outer_function2_variable_passed_as_arguement + "---" + variable_defined_inside_outer_function2 )
#print(outer_function2_variable_passed_as_arguement + "---" + variable_defined_inside_outer_function2)
return inner_function2
#main code starts here
outer_function("arguement to outerfunction")
print("-----------------------------------------------------------------------------------------------------------------------------")
function_object1=outer_function2("arguement to outerfunction2")
print("calling the inner_function_2 object %s " % function_object1() )
| true |
b004db71cd2568e70234a4b55bc64f0ca9b621c9 | chelxx/Python | /python_OOP/bike.py | 878 | 4.21875 | 4 | # Bike Assignment
class Bike(object):
def __init__(self, name, speed, miles):
self.name = name
self.speed = speed
self.miles = miles
def information(self):
print (self.name, self.speed, self.miles)
return self
def ride(self):
self.miles += 10
if self.miles <= 0:
self.miles = 0
print(("Riding..."), self.miles)
return self
def reverse(self):
self.miles -= 5
if self.miles <= 0:
self.miles = 0
print(("Reversing..."), self.miles)
return self
def displayinfo():
bike1 = Bike("Harry", 25, 50).information().ride().ride().ride().reverse()
bike2 = Bike("Ron", 20, 60).information().ride().ride().reverse().reverse()
bike3 = Bike("Hermione", 30, 70).information().reverse().reverse().reverse()
displayinfo()
# END | false |
1fe0e1b74e36ff6acb5bb0aa7e90ef814ee09cb5 | OnsJannet/holbertonschool-higher_level_programming | /0x0B-python-input_output/0-read_file.py | 214 | 4.15625 | 4 | #!/usr/bin/python3
def read_file(filename=""):
"""
Reads a text file and prints it
filename: filename.
"""
with open(filename, encoding='UTF8') as my_file:
print(my_file.read(), end="")
| true |
f0a15181d6b37bcaf771c7f0657acd39a34c54bd | haijunXue/python_info_sytem_exercise | /student_info.py | 2,287 | 4.1875 | 4 | str_print = "name: {}\tmath: {}\tchinese: {},english: {}\ttotal: {}\t"
grade_list = []
while 1:
print("""
**************
1. create
2. show
3. search
4. delete
5. modify
**************
""")
action = input("input your operation:\n")
if action == '1':
"create student information"
name = input("please input name: ")
math = input("input math score: ")
chinese = input("input chinese score: ")
english = input("input chinese score: ")
total = int(math) + int(chinese) + int(english)
grade_list.append([name,math,chinese,english,total])
print(str_print.format(name,math,chinese,english,total))
pass
elif action == '2':
""" show all information"""
for info in grade_list:
print(str_print.format(*info))
elif action == '3':
""" searh student information"""
name = input("the search student name: ")
for info in grade_list:
if name in info:
print(str_print.format(*info))
break
else:
print("the student not exist")
pass
elif action == '4':
"""delete information"""
name = input("the delete name")
for info in grade_list:
if name in info:
info_ = grade_list.pop(grade_list.index(info))
print("the information delete\n",info)
break
else:
print("the student not exist")
pass
elif action == '5':
"modify information"
name = input("the modify name")
index = None
for info in grade_list:
if name in info:
index = grade_list.index(info)
break
else:
print("the student not exist")
continue
math = input("input math score: ")
chinese = input("input chinese score: ")
english = input("input chinese score: ")
total = int(math) + int(chinese) + int(english)
grade_list[index][1:] = [math,chinese,english,total]
print("change the name",grade_list[index])
pass
elif action == '0':
"quite the system"
pass
else:
print("information error") | false |
def56b6491b279a5616ecb5bd18246a85275ef4f | maokuntao/python-study | /src/the_if.py | 726 | 4.25 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Created on 2017年11月16日
@author: taomk
'''
from math import pow
height = input("Your height (m) : ")
weight = input("Your weight (kg) : ")
# input()返回的数据类型是str,必须先把str转换成float
bmi = float(weight)/pow(float(height), 2)
# 只要bmi是非零数值、非空字符串、非空list等,就判断为True,否则为False
if bmi:
print("Your BMI :", bmi)
# 条件判断从上向下匹配,当满足条件时执行对应的块内语句,后续的elif和else都不再执行
if bmi<18.5:
print("过轻")
elif bmi<25:
print("正常")
elif bmi<28:
print("过重")
elif bmi<32:
print("肥胖")
else:
print("过于肥胖") | false |
b780b1c0a22652ef191e7303727d3ac2d26be3ed | aarbigs/python_labs | /06_classes_objects_methods/06_02_shapes.py | 1,241 | 4.5 | 4 | '''
Create two classes that model a rectangle and a circle. The rectangle class should
be constructed by length and width while the circle class should be constructed by
radius.
Write methods in the appropriate class so that you can calculate the area (of the rectangle and circle),
perimeter (of the rectangle) and circumference of the circle.
'''
from math import pi
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
self.area = self.length * self.width
print(f"The area of your rectangle is {self.area}")
def perimeter(self):
self.perimeter = (self.length * 2) + (self.width * 2)
print(f"The perimeter of your rectange is {self.perimeter}")
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
self.area = pi * (self.radius**2)
print(f"The area of your circle is {self.area}")
def circumference(self):
self.circumference = (2*pi*(self.radius))
print(f"The circumference of your circle is {self.circumference}")
new_rec = Rectangle(2, 4)
new_rec.area()
new_rec.perimeter()
new_circ = Circle(5)
new_circ.area()
new_circ.circumference() | true |
2c760dce41a71fc860f8b9af3d452e9ceb1bd1c0 | aarbigs/python_labs | /02_basic_datatypes/02_06_invest.py | 392 | 4.25 | 4 | '''
Take in the following three values from the user:
- investment amount
- interest rate in percentage
- number of years to invest
Print the future values to the console.
'''
invest = int(input("enter investment amount: "))
interest = int(input("enter interest rate: "))
num_years = int(input("enter number of years: "))
fv = invest * ((1+(interest/100))**num_years)
print(fv) | true |
d400d8f6bd33d30ba3d7d3d350ce90ca9b0ae672 | aarbigs/python_labs | /15_variable_arguments/15_01_args.py | 344 | 4.1875 | 4 | '''
Write a script with a function that demonstrates the use of *args.
'''
def arg_function(*args):
# for i in args:
# print(i*i)
a,b,c = args
print(a, b, c)
arg_function(1, 2, 3)
new_list = []
def arg_function2(*args):
for arg in args:
new_list.append(arg)
print(new_list)
arg_function2(1, 2, 3, 4, 5) | true |
a267f13054cd7b67170aa04a7ad4582bcc3fdc70 | aarbigs/python_labs | /06_classes_objects_methods/06_04_inheritance.py | 1,358 | 4.1875 | 4 | '''
Build on the previous exercise.
Create subclasses of two of the existing classes. Create a subclass of
one of those so that the hierarchy is at least three levels.
Build these classes out like we did in the previous exercise.
If you cannot think of a way to build on your previous exercise,
you can start from scratch here.
We encourage you to be creative and try to think of an example of
your own for this exercise but if you are stuck, some ideas include:
- A Vehicle superclass, with Truck and Motorcycle subclasses.
- A Restaurant superclass, with Gourmet and FastFood subclasses.
'''
import django
class Vehicle:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def __str__(self):
return f"Your {self.make} {self.model} is from {self.year}"
class Car(Vehicle):
def __init__(self, make="Honda", model="civic", year="2016"):
self.make = make
self.model = model
self.year = year
class Toyota(Car):
def __init__(self, make="Toyota", model="camry", year="2018"):
self.make = make
self.model = model
self.year = year
my_vehicle = Vehicle("bicycle", 'red', 2000)
print(my_vehicle)
my_honda = Car()
print(my_honda)
my_car = Car("toyota", "4runner", 2009)
print(my_car)
my_toyota = Toyota()
print(my_toyota) | true |
ce4189a60d6f35d025a0662243d839d83e7bfe2f | Giorc93/Python-Int | /datatype.py | 608 | 4.34375 | 4 | # Strings
print("Hello World")
print('Hello World') # Prints the sting on the console
print("""Hello Word""")
print('''Hello World''')
print(type('''Hello World''')) # Gets the data type and prints the value
print("Bye"+"World") # + links the strings
# Numbers
print(30) # integer
print(30.5) # float
# Boolean
False #
True
# List
[10, 20, 30, 40]
['Hello', 'Bye', 'World']
[10, 'Hello', False]
# Tuples
(10, 20, 30, 55) # Tuples are lists that can't be modified
# Dictionaries
{
'name': 'Ryan',
'lastname': 'Smith'
}
print(type({
'name': 'Ryan',
'lastname': 'Smith'
}))
| true |
dc557c4f23cdcc92ce1f526ed7da471477f9b861 | Lina-Pawar/Devops | /sum_digits.py | 310 | 4.15625 | 4 | def Digits(n):
sum = 0
for digit in str(n):
sum += int(digit) #uses shorthand operator += for adding sum like sum=sum+int(digit)
return sum
n= int(input(print("Enter an integer number: "))) #inputs an integer number
print("Sum of digits is",Digits(n)) #prints the sum | true |
6d8a96fb1870197e366cca12db202ea58e134eac | gitter-badger/Erin-Hunter-Book-Chooser | /Erin Hunter Book Chooser Main Window.py | 1,645 | 4.125 | 4 | from tkinter import *
import tkinter.messagebox as box
window = Tk()
window.title("Erin Hunter Book Chooser")
label = Label( window, font = ("architects daughter", 11, "normal"), text = "Welcome to the Erin Hunter Book Chooser.\nPlease select your favorite animal below and the app will select your favorite Erin Hunter authored book.\n You can visit the website link displayed to learn more afterwards.\n")
label.pack( padx = 200, pady = 25 )
frame = Frame(window)
book = StringVar()
radio_1 = Radiobutton( frame, font = ("architects daughter", 10, "normal"), text='Cats', \
variable = book, value = ' Warriors by Erin Hunter.\nVisit warriorscats.com for more information.')
radio_2 = Radiobutton( frame, font = ("architects daughter", 10, "normal"), text='Bears', \
variable = book, value = ' Seekers by Erin Hunter.\nVisit seekrsbears.com for more information.')
radio_3 = Radiobutton(frame, font = ("architects daughter", 10, "normal"), text='Dogs', \
variable = book, value = ' Survivors by Erin Huter.\nVisit survivorsdogs.com for more information.')
radio_1.select()
def dialog():
box.showinfo('Erin Hunter Book Selection', \
'Your Erin Hunter Book selection is:' + book.get() )
btn = Button( frame, font = ("architects daughter", 10, "normal"), text = 'Choose', command = dialog)
btn.pack(side = RIGHT, padx = 5)
radio_1.pack(side = LEFT)
radio_2.pack(side = LEFT)
radio_3.pack(side = LEFT)
frame.pack( padx = 30, pady = 15 )
window.mainloop()
window.mainloop()
| true |
396d6ad0f092eda6e3404d7b8fd4c53b8ecd3c58 | jdamerow/gdi-python-intro | /exercises/game2.py | 961 | 4.125 | 4 | from random import randint
items = {
'sword':'ogre',
'cake':'wolf',
'balloons':'bees',
'kitty':'troll',
}
def does_item_protect(obstacle, item):
# Your code goes here.
# Your code should do something with the obstacle and item variables and assign the value to a variable for returning
# You could use two dictionaries to assign what happens when a certain item does or does not protect agains an obstacle.
return items[item] == obstacle
input_obstacle = raw_input("You encounter: ")
while input_obstacle not in items.values():
input_obstacle = raw_input("That's not real. What do you really encounter? ")
input_item = raw_input("You have a: ")
while input_item not in items.keys():
input_item = raw_input("That doesn't exist. What do you defend yourself with? ")
protected = does_item_protect(input_obstacle, input_item)
# Display the answer in some meaningful way
print("you are protected is " + str(protected))
| true |
5c8c9c8d0c4ebe55a7d5ce857fefd416500ad486 | MrGallo/classroom-examples | /11-algorithms/03b_bubble_sort_solution.py | 1,009 | 4.28125 | 4 | from typing import List
import random
def bubble_sort(numbers: List[int]) -> List[int]:
# optimization 1: if gone through without swapping, its sorted, stop looping
is_sorted = False
# optimization 2: each pass, the last element is always sorted, don't loop to it anymore.
times_through = 0
while not is_sorted:
is_sorted = True # optimization 1
# loop through and compare two elements at a time
for i in range(len(numbers) - 1 - times_through): # with optimization 2
a = numbers[i]
b = numbers[i+1]
# if the two elements are out of order, swap them
if a > b:
numbers[i] = b
numbers[i+1] = a
is_sorted = False # optimization 1
times_through += 1 # optimization 2
# return the sorted list
return numbers
print(bubble_sort([1, 2, 3, 4, 5]))
print(bubble_sort([5, 4, 3, 2, 1, 0]))
print(bubble_sort([random.randrange(100) for _ in range(10)]))
| true |
a2d6f7b306f5dd41a3d994b218f7bfcbc8b28857 | ayushi424/PyAlgo-Tree | /Dynamic Programming/Gold Mine Problem/gold_mine_problem.py | 2,708 | 4.34375 | 4 | # Python program to solve
# Gold Mine problem
# Problem Statement : Returns maximum amount of
# gold that can be collected
# when journey started from
# first column and moves
# allowed are right, right-up
# and right-down
# -----------------------------------------------------------------
# Approach : Brute Force Method
# Abhishek S, 2021
# -----------------------------------------------------------------
MAX = 100
def getMaxGold(gold, m, n):
# Create a table for storing
# intermediate results
# and initialize all cells to 0.
# The first row of
# goldMineTable gives the
# maximum gold that the miner
# can collect when starts that row
goldTable = [[0 for i in range(n)]
for j in range(m)]
for col in range(n-1, -1, -1):
for row in range(m):
# Gold collected on going to
# the cell on the rigth(->)
if (col == n-1):
right = 0
else:
right = goldTable[row][col+1]
# Gold collected on going to
# the cell to right up (/)
if (row == 0 or col == n-1):
right_up = 0
else:
right_up = goldTable[row-1][col+1]
# Gold collected on going to
# the cell to right down (\)
if (row == m-1 or col == n-1):
right_down = 0
else:
right_down = goldTable[row+1][col+1]
# Max gold collected from taking
# either of the above 3 paths
goldTable[row][col] = gold[row][col] + max(right, right_up, right_down)
# The max amount of gold
# collected will be the max
# value in first column of all rows
res = goldTable[0][0]
for i in range(1, m):
res = max(res, goldTable[i][0])
return res
# Driver code
gold = [[1, 3, 3],
[2, 1, 4],
[0, 6, 4]]
m = 3
n = 3
print ("- Gold Mine Problem using Dynamic Programming -")
print ("-----------------------------------------------")
print ()
print ("Output : ")
print ("The maximum amount of Gold can be collected : ")
print(getMaxGold(gold, m, n))
# -------------------------------------------------------------------------
# Output
# - Gold Mine Problem using Dynamic Programming -
# -----------------------------------------------
# Output :
# The maximum amount of Gold can be collected :
# 12
# -------------------------------------------------------------------------
# Code contributed by, Abhishek S, 2021
| true |
611ae37b5820df62f36eaa2c9ef7ca03af4a30b0 | AozzyA/homeCode | /ch2.py | 987 | 4.15625 | 4 | # Ask first name.
nameFirst = input('what is your first name: ').strip()
# Ask if you have a midle name.
midleAsk = input('do you have a midle name yes or no: ').strip()
# Seting nameMidle to nothing.
nameMidle = ''
# What happens if you type yes to do you have a midle name.
if midleAsk.lower() in ['y', 'yes']:
# Asking what your midle name is.
nameMidle = input ("what is your midle name: ").strip()
# Ask last name
nameLast = input('what is your last name: ').strip()
# Printing hello.
# First name.
# Midle name and last name.
print ('Hello ' + nameFirst.title() + ' ' + nameMidle.title() + ' ' + nameLast.title())
# Ask if you have a nickname
nickName = input ('do you have a nickname yes or no: ').strip()
# What happens if you type yes to do you have a nickname.
if nickName.lower() in ['y', 'yes']:
# Ask what is your nickname.
name4 = input ("what is your nickname: ").strip()
# Printing hi and your nickname.
print ('hi '.title() + name4.title())
| true |
3178d5bcf5b8d59815f94c62df17d874ac05579e | AozzyA/homeCode | /ch6project.py | 598 | 4.28125 | 4 | numbers = {'anthony':[9, 10, 1], 'coleman':[26, 5], 'milan':[5, 10], 'jake':[8, 14]}# a dictionary is used when one wants to get a vaule from a spesific key
#lists are used when one wants a ordird culectshun of vaules
for name, favNumbers in numbers.items():
#print('\n')
print(name + ' favorite numbers: ')
#print('\t' + str(favNumbers))
print('',end='')
for an in favNumbers:
print(an, end=' ')
for a in favNumbers:
print()
abc = [1, 2, 3]
jake = abc[0:2]
print(abc)
print(jake)
xyz = ['hi', 'bye', 'hey']
xyz[0:1]
print(8888)
print(xyz[0:3])
| false |
7b451e89f8f43c8894999220bd538319e27d4f35 | xiangormirko/python_work | /list2.py | 481 | 4.28125 | 4 | # List exercise 2
# Mirko (xiang@bu.edu)
def main():
animals=["cow","sheep","pig"]
print animals
for animal in animals:
print "the %s says..." % animal
animals.append("goat")
print animals
animals.append("cow")
animals.append("pig")
print animals
print animals.count("cow")
print animals.count("dinosaur")
animals.sort()
print animals
animals.reverse()
print animals
animals.remove("goat")
print animals
main()
| false |
490c7ef960b63be0a91b233cce81a98050255b7b | xiangormirko/python_work | /clock.py | 541 | 4.15625 | 4 | # File: clock.py
# Author: Mirko (xiang@bu.edu)
# Description: Definite Loop Exercise
# Assignment: A03
# Date: 09/10/13
def main():
print "enter time in 24h format"
StartHour=input("enter the start hour:")
EndHour=input("enter the end hour:")
IncrementMinutes=input("enter the increment in minutes:")
for hour in range (StartHour,EndHour,1):
for minutes in range (0,60,IncrementMinutes):
print hour, ":", minutes
print "time is up!"
main()
| true |
1e5612fc4db365103732c4fb4532e9a6324c9fd0 | xiangormirko/python_work | /savings03.py | 1,528 | 4.40625 | 4 | # File: savings01.py
# Author: Mirko (xiang@bu.edu)
# Description:accumulating monthly interest
# Assignment: A05
# Date: 09/17/13
def main():
goal= input("Enter your savings goal in dollars:")
YearRatepercent= input("Enter the expected annual rate of return in percent:")
yearRate=YearRatepercent/100
Time=input("Enter time until goal in year:")
MonthRate= yearRate/12
nominatore=MonthRate*goal
denominatore=((1+MonthRate)**(Time*12))-1
MonthSavings= nominatore/denominatore
interest=0
balance=0
print
print "Saving goal: $", goal
print "Annual rate of return:", yearRate,"(",YearRatepercent,"%)"
print
for i in range(1,Time+1,1):
print "Saving Schedule for year",i
pastinterest=interest
for num in range (1,13,1):
interestearned= balance*MonthRate
interest=interest+interestearned
balance=balance+MonthSavings+interestearned
print "month interest amount balance"
print num," ",round(interestearned,2),"20 ",round(MonthSavings,2)," ",round(balance,2)
print
print "Savings summary for year", i
print "Total amount saved:", round(MonthSavings*12,2)
print "Total interest earned:", round(interest-pastinterest,2)
print "End of your balance:", round(balance,2)
print
print "***************************************************************************"
print
main()
| true |
364d86b7854d608eaa1caa0415ba465640cbbc62 | majomendozam/semanaTec | /cannon.py | 2,046 | 4.28125 | 4 | """Cannon, hitting targets with projectiles.
María José Mendoza Muñiz
06/05/2021
Exercises
1. Keep score by counting target hits.
2. Vary the effect of gravity.
3. Apply gravity to the targets.
4. Change the speed of the ball.
"""
from random import randrange
from turtle import *
from freegames import vector
ball = vector(-200, -200)
speed = vector(0, 0)
targets = []
title('Cannon Game')
count = 0
def tap(x, y):
"Respond to screen tap."
if not inside(ball):
ball.x = -199
ball.y = -199
speed.x = (x + 500) / 25
speed.y = (y + 500) / 25
def inside(xy):
"Return True if xy within screen."
return -200 < xy.x < 200 and -200 < xy.y < 200
def draw():
"Draw ball and targets."
clear()
for target in targets:
goto(target.x, target.y)
dot(50, 'blue')
if inside(ball):
goto(ball.x, ball.y)
dot(6, 'red')
update()
def move():
"Move ball and targets."
# Generate a new target at random times
global count
if randrange(40) == 0:
y = randrange(-150, 150)
target = vector(200, y)
targets.append(target)
# Move the existing targets
for target in targets:
target.x -= 0.9
# Move the cannon shot
if inside(ball):
speed.y -= 0.35
ball.move(speed)
# Make a copy of the existing target list before redrawing
dupe = targets.copy()
targets.clear()
# Detect if the bullet hits a target
for target in dupe:
if abs(target - ball) > 13:
targets.append(target)
else: count+=1
draw()
# Detect when a target reaches the left side
for target in targets:
if not inside(target):
#targets.remove(target)
return
ontimer(move, 50)
setup(420, 420, 370, 0)
hideturtle()
up()
tracer(False)
onscreenclick(tap)
move()
listen()
style = ('Arial', 30, 'bold')
onkey(lambda: write('SCORE: ', font = style, align = 'right'), 'w')
onkey(lambda: write(count, font = style, align = 'left'), 'e')
done()
| true |
8206c5bc4b39ed16d03fc3972b45aabd17dc1293 | Hazem-Atya/learning_python | /firstProject/tuples.py | 405 | 4.34375 | 4 | x = ('Hazem', 'Atya', 21)
print(x)
for i in x:
print(i)
# Unlike lists , we can't change tuples
(x, y) = ('Safa', 18)
print(x)
d = {'x': 10, 'b': 1, 'c': 22}
tri = sorted(d.items())
print(tri)
# ----------------sort a dictionary by value---------------
tmp = list()
for k, v in d.items():
tmp.append((v, k))
print(tmp)
tmp = sorted(tmp)
print(tmp)
rev = sorted(tmp, reverse=True)
print(rev)
| false |
5fb3409b2814f96c093b312aa7c51e8c07d763bd | bambergerz/optimization_for_deep_learning | /bisection.py | 1,155 | 4.1875 | 4 | import numpy as np
def bisection(func, deriv, iters, lhs, rhs):
"""
:param func: Our original function (which takes in a single argument)
that we are trying to minimize. Argument is an integer.
:param deriv: The derivative of our initial function (see above).
Argument is an integer.
:param iters: An integer representing the number of steps we will take
towards finding the minima
:param lhs: the smallest value of x we are considering as the potential minima
:param rhs: the largest value of x we are considering as the potential minima
:return: The integer x which yields the minimum output from func, and that supposed
minimum value.
"""
for k in range(iters):
if lhs == rhs:
return lhs, func(lhs)
t = (lhs + rhs) / 2
if deriv(t) > 0:
rhs = t
else:
lhs = t
loc = (lhs + rhs) / 2
val = func(loc)
return "x* = " + str(loc),\
"f(x*) = " + str(val)
if __name__ == "__main__":
func = lambda x: x**2
deriv = lambda x: 2*x
lhs = -10
rhs = 10
print(bisection(func, deriv, 20, lhs, rhs))
| true |
55527d6aa9a17804a2aadae86b7e78b9f6e559d8 | bwasmith/smash-cs | /final-project/main.py | 2,358 | 4.125 | 4 | import pandas as pd
# Read dataset
data = pd.read_csv("CSY1Data.csv")
# Get the Calculus AB test scores from dataset
calculus_scores = data.loc[2]
# Prepare variables for the sums I need
males_passing_sum = 0
females_passing_sum = 0
another_passing_sum = 0
males_failing_sum = 0
females_failing_sum = 0
another_failing_sum = 0
# *index* is the column race, gender, score. Such as: AMERICAN INDIAN/ALASKA NATIVE MALES 5
# *value* is the number of tests with that race, gender, score
#for each race, gender, score combination
for index, value in calculus_scores.items():
# if the column is female
if "FEMALES" in index:
# if the column is a passing test
if "5" in index or "4" in index or "3" in index:
#add to the female passing sum
females_passing_sum += value
else:
# add to the female failing sum
females_failing_sum += value
elif "MALES" in index:
if "5" in index or "4" in index or "3" in index:
males_passing_sum += value
else:
males_failing_sum += value
elif "ANOTHER" in index:
if "5" in index or "4" in index or "3" in index:
another_passing_sum += value
else:
another_failing_sum += value
print("For the AP Calculus AB Test")
print("___________________________")
print("Pass/Fail Totals:")
print("Total Males Passing: ", str(males_passing_sum))
print("Total Males Failing: ", str(males_failing_sum))
print("Total Females Passing: ", str(females_passing_sum))
print("Total Females Failing: ", str(females_failing_sum))
print("Total Anothers Passing: ", str(another_passing_sum))
print("Total Anothers Failing: ", str(another_failing_sum))
# Calculate pass rate for each gender
male_pass_rate = males_passing_sum / (males_passing_sum + males_failing_sum)
female_pass_rate = females_passing_sum / (females_passing_sum + females_failing_sum)
another_pass_rate = another_passing_sum / (another_passing_sum + another_failing_sum)
# Round to make it more readable
male_pass_rate = round(male_pass_rate, 4)
female_pass_rate = round(female_pass_rate, 4)
another_pass_rate = round(another_pass_rate, 4)
print()
print("Pass Rates:")
print("Male Pass Rate: ", str(male_pass_rate))
print("Female Pass Rate: ", str(female_pass_rate))
print("Another Pass Rate: ", str(another_pass_rate))
| true |
73c5fe6272768f4a30a38ba50a53afc38adb8318 | SwetaSinha9/Basic-Python | /sum_prime.py | 410 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 13 15:46:02 2019
@author: sweta
"""
# WAP to add all prime numbers from 1 to n and n is given by user.
n = int(input("Enter a No: "))
p=0
for j in range(2, n+1):
f=0
for i in range(2, int(j/2) + 1):
if j % i == 0:
f=1
break
if f==0:
p=p+j
print("Sum of all prime numbers are:",p) | true |
c0ae49719eda3526da5a6a6471a9be1f9eb9f65e | Louvani/holbertonschool-higher_level_programming | /0x06-python-classes/6-square.py | 1,713 | 4.5 | 4 | #!/usr/bin/python3
""" definition of a square class """
class Square:
""" defines a square with a private instance attribute"""
def __init__(self, size=0, position=(0, 0)):
"""size: Square size"""
self.size = size
self.position = position
def area(self):
return self.__size ** 2
def my_print(self):
if self.__size == 0:
print("")
else:
if self.__position[1] > 0:
for i in range(0, self.__position[1]):
print("")
for i in range(0, self.__size):
for k in range(0, self.__position[0]):
print(" ", end="")
for j in range(0, self.__size):
print("#", end="")
print("")
@property
def size(self):
return self.__size
@property
def position(self):
return self.__position
@size.setter
def size(self, value):
if type(value) is not int:
raise TypeError("size must be an integer")
elif value < 0:
raise ValueError("size must be >= 0")
else:
self.__size = value
@position.setter
def position(self, value):
if type(value) is not tuple or len(value) != 2:
raise TypeError("position must be a tuple of 2 positive integers")
else:
is_int = True
for i in value:
if not isinstance(i, int) or i < 0:
is_int = False
break
if is_int:
self.__position = value
else:
raise TypeError("position must be a tuple \
of 2 positive integers")
| true |
137ed6bab151a47d13909834b92829b170cfb18c | Louvani/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/2-matrix_divided.py | 1,214 | 4.125 | 4 | #!/usr/bin/python3
"""Module that divides all element of a matrix"""
def matrix_divided(matrix, div):
"""Function that divides all element of a matrix"""
if div == 0:
raise ZeroDivisionError('division by zero')
if not isinstance(div, (int, float)):
raise TypeError('div must be a number')
if not isinstance(matrix, list):
raise TypeError('matrix must be a matrix (list of lists) \
of integers/floats')
if all(not isinstance(row, list) for row in matrix):
raise TypeError('matrix must be a matrix (list of lists) \
of integers/floats')
if not all(len(matrix[0]) == len(row) for row in matrix):
raise TypeError('Each row of the matrix must have the same size')
else:
new_matrix = []
for idx in range(len(matrix)):
num_list = []
temp = 0
for num in range(len(matrix[idx])):
if isinstance(matrix[idx][num], (int, float)):
num_list.append(round(matrix[idx][num] / div, 2))
else:
raise TypeError('matrix must be a matrix (list of lists) \
of integers/floats')
new_matrix.append(num_list)
return new_matrix
| true |
968809686894aeddacb5ab1cb46dcc091fe44162 | cannium/leetcode | /design-snake-game.py | 2,308 | 4.125 | 4 | class SnakeGame(object):
def __init__(self, width, height, food):
"""
Initialize your data structure here.
@param width - screen width
@param height - screen height
@param food - A list of food positions
E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].
:type width: int
:type height: int
:type food: List[List[int]]
"""
self.w = width
self.h = height
self.food = food
self.food_i = 0
self.snake = [(0,0)]
self.delta = {
'U': (-1, 0),
'L': (0, -1),
'R': (0, 1),
'D': (1, 0),
}
self.gameover = False
def mv(self, loc, delta):
return (loc[0]+delta[0], loc[1]+delta[1])
def move(self, direction):
"""
Moves the snake.
@param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down
@return The game's score after the move. Return -1 if game over.
Game over when snake crosses the screen boundary or bites its body.
:type direction: str
:rtype: int
"""
if self.gameover:
return -1
head = self.snake[0]
next_head = self.mv(head, self.delta[direction])
#print head, next_head
if next_head[0] < 0 or next_head[0] >= self.h:
self.gameover = True
return -1
if next_head[1] < 0 or next_head[1] >= self.w:
self.gameover = True
return -1
if next_head in self.snake[:-1]:
self.gameover = True
return -1
food = None
if self.food_i < len(self.food):
food = tuple(self.food[self.food_i])
#print direction, head, next_head, food, self.snake
if next_head == food:
if next_head == self.snake[-1]:
self.gameover = True
return -1
self.snake.insert(0, next_head)
self.food_i += 1
else:
self.snake.insert(0, next_head)
self.snake.pop(-1)
return len(self.snake) - 1
# Your SnakeGame object will be instantiated and called as such:
# obj = SnakeGame(width, height, food)
# param_1 = obj.move(direction)
| true |
674c488e5fca6c4b88f1192e8807516a15dca2cd | guhaigg/python | /month01/day13/demo07.py | 1,493 | 4.40625 | 4 | """
增加新功能:
飞机
"""
# 缺点:违反了面向对象设计原则--开闭原则
# 允许增加新功能,但是不能修改客户端代码.
"""
class Person:
def __init__(self, name=""):
self.name = name
def go_to(self, position, vehicle):
print("去" + position)
if type(vehicle) == Car:
vehicle.run()
elif type(vehicle) == Airplane:
vehicle.fly()
class Car:
def run(self):
print("汽车在行驶")
class Airplane:
def fly(self):
print("飞机在飞行")
# 在使用时创建
zl = Person("老张")
car = Car()
air = Airplane()
zl.go_to("东北", car)
zl.go_to("东北", air)
"""
# ------------------架构师--------------------
# 客户端代码
class Person:
def __init__(self, name=""):
self.name = name
def go_to(self, position, vehicle):
print("去" + position)
# 编码时,调用父类交通工具
# 运行时,执行子类汽车/飞机
vehicle.transport()
#
# 父类(规范)
class Vehicle:
def transport(self):
pass
# ------------------程序员--------------------
# 子类(功能)
class Car(Vehicle):
def transport(self):
print("汽车在行驶")
class Airplane(Vehicle):
# 重写快捷键
# ctrl + o
def transport(self):
print("飞机在飞行")
# 在使用时创建
zl = Person("老张")
car = Car()
air = Airplane()
zl.go_to("东北", car)
zl.go_to("东北", air)
| false |
456e03fc7bf5d2d0d74bb7fd956589cfc9b35b37 | guhaigg/python | /month01/day16/exercise05.py | 698 | 4.125 | 4 | """
练习1:定义函数,在列表中找出所有偶数
[43,43,54,56,76,87,98]
练习2:定义函数,在列表中找出所有数字
[43,"悟空",True,56,"八戒",87.5,98]
"""
# 练习1:
list01 = [43, 43, 54, 56, 76, 87, 98]
def find_all_even():
for item in list01:
if item % 2 == 0:
yield item
result = find_all_even()
for number in result:
print(number)
# 练习2:
list02 = [43, "悟空", True, 56, "八戒", 87.5, 98]
def find_all_number():
for item in list02:
# if type(item) == int or type(item) == float:
if type(item) in (int, float):
yield item
for number in find_all_number():
print(number)
| false |
ad1844e5285584c9e7afc884c6532b0d6ab8373e | guhaigg/python | /month01/day02/exercise11.py | 547 | 4.40625 | 4 | """
练习1:写出下列代码表达的命题含义
print(666 == "666") 整数666 等于 字符串666
print(input("你爱我吗? ") == "爱") 你爱我
print(float(input("请输入你的身高:")) > 170) 你的身高大于170
练习2: 根据命题写出代码
输入的是正数
输入的是月份
输入的不是偶数(奇数)
"""
print(666 == "666")
print(float(input("请输入数字:")) > 0)
print(1 <= int(input("请输入月份:")) <= 12)
print(int(input("请输入整数:")) % 2 != 0)
| false |
79fb7c32367eed6951ebd21ebfa4ca265f5b6697 | guhaigg/python | /month01/day10/demo01.py | 1,486 | 4.65625 | 5 | """
实例成员
实例变量:表达不同个体的不同数据
语法:对象.变量名
实例方法:操作实例变量
语法:
def 方法名(self,参数):
方法体
对象.方法名(数据)
"""
# [一个]全局变量,只能表达一个人的姓名,
# 不能表达不同人的姓名.
name = "双儿"
name = "建宁"
# dict01 = {"name":"双儿"}
# dict01["name"] = "双双"
class Wife:
def __init__(self, name=""):
# 创建实例变量
self.name = name
# 实例方法
def work(self):
print(self.name + "在工作")
shuang_er = Wife("双儿")
# 修改实例变量
shuang_er.name = "双双"
# 读取实例变量
print(shuang_er.name)
# __dict__ 存储所有实例变量
print(shuang_er.__dict__) # {'name': '双双'}
# 通过对象访问实例方法
shuang_er.work() # work(shuang_er)
# dict01 = {}
# dict01["name"] = "双双"
"""
# 不建议在类外创建实例变量
class Wife:
pass
shuang_er = Wife()
# 创建实例变量
shuang_er.name = "双双"
# 读取实例变量
print(shuang_er.name)
# __dict__ 存储所有实例变量
print(shuang_er.__dict__) # {'name': '双双'}
"""
# 不建议在__init__外创建实例变量
"""
class Wife:
def set_name(self, name):
# 创建实例变量
self.name = name
shuang_er = Wife()
shuang_er.set_name("双双")
print(shuang_er.name)
print(shuang_er.__dict__)
"""
| false |
948fde0e876992046160d717e9477aa671270810 | guhaigg/python | /month01/day06/demo02.py | 1,478 | 4.625 | 5 | """
元组:由一系列变量组成的不可变序列容器。
面试题:Python语言都有那些数据类型?
答: 可变类型:预留空间+自动扩容
例如:list...
优点:操作数据方便(增删改)
缺点:占用空间较多
适用性:存储的数据需要发生改变
不可变类型:按需分配
例如:int float str bool tuple ...
优点:占用空间较少
缺点:操作数据不方便
适用性:优先,存储的数据不会改变
"""
# tuple基础操作
# 创建
# -- 根据元素
tuple01 = (10, 20, 30)
# -- 根据可迭代对象
# 使用列表存储计算过程中的数据
list_name = ["朱礼军", "周天奇", "陈永杰"]
# 使用元组存储计算结果
tuple02 = tuple(list_name)
# 定位(只读)
print(tuple01[0])
print(tuple01[-2:])
# 遍历
for item in tuple01:
print(item)
for i in range(len(tuple01) - 1, -1, -1):
print(tuple01[i])
# 注意1:在没有歧义的情况下,创建元组可以省略小括号
tuple03 = "a", "b", "c"
# 注意2:如果元组只有一个元素,必须添加逗号
tuple04 = ("a",)
print(type(tuple04))
# 注意3:序列拆包
data01, data02, data03 = tuple01
data01, data02, data03 = list_name
data01, data02, data03 = "孙悟空"
print(data01)
print(data02)
print(data03)
# 应用:
a = 1
b = 2
# b, a --> 构建元组,省略小括号
# a, b --> 序列拆包
a, b = b, a
| false |
e3bee95a8de7cbf1c47685155f759c7bf6cd604c | guhaigg/python | /month01/day13/demo06.py | 860 | 4.375 | 4 | """
运算符重载(重写)
比较运算符
"""
class Vector2:
def __init__(self, x, y):
self.x = x
self.y = y
# 相同的依据
def __eq__(self, other):
# return self.x == other.x and self.y == other.y
return self.__dict__ == other.__dict__
# 大小的依据
def __gt__(self, other):
return self.x ** 2 + self.y ** 2 > other.x ** 2 + other.y ** 2
# 1. 需要重写__eq__
pos01 = Vector2(3, 2)
pos02 = Vector2(3, 2)
print(pos01 == pos02) # True
list_data = [
Vector2(1, 1),
Vector2(3, 3),
Vector2(2, 2),
Vector2(5, 5),
Vector2(4, 4),
]
print(Vector2(1, 1) in list_data)
list_data.remove(Vector2(3, 3))
print(list_data)
value = max(list_data)
print(value.__dict__)
list_data.sort() # 升序排列
list_data.sort(reverse=True) # 降序排列
print(list_data)
| false |
3d831665556fabfd20ad21a2464af0201b6ccbf0 | guhaigg/python | /month01/day08/demo04.py | 514 | 4.15625 | 4 | """
函数内存分布
结论:
函数内部修改传入的可变数据
不用通过return返回结果
"""
# 将函数代码存储内存,不执行函数体.
def func01():
a = 10
# 调用函数时,开辟内存空间(栈帧),存储在函数内部创建的变量
func01()
# 函数调用结束,该空间立即释放
def func02(p1,p2):
p1 = 200
p2[0] = 200 # 修改传入的可变数据
data01 = 100
data02 = [100]
func02(data01,data02)
print(data01) # 100
print(data02) # 200
| false |
6ad51d5f5c7c4d7c72ce87ffa803c2c984338e3b | guhaigg/python | /month01/day06/demo06.py | 696 | 4.34375 | 4 | """
字典dict:由一系列键值对组成的可变散列容器。
"""
dict_szl = {"name": "孙子凌", "age": 28, "sex": "女"}
# 遍历
# -- 获取所有key
for key in dict_szl:
print(key)
# -- 获取所有value
for value in dict_szl.values():
print(value)
# -- 获取所有key和value
# 得到的是元组(键,值)
# for item in dict_szl.items():
# print(item[0])
# print(item[1])
for k, v in dict_szl.items():
print(k)
print(v)
# list -注意格式-> dict
# dict --> list
print(list(dict_szl)) # ['name', 'age', 'sex']
print(list(dict_szl.values())) # ['孙子凌', 28, '女']
print(list(dict_szl.items())) # [('name', '孙子凌'), ('age', 28), ('sex', '女')] | false |
0e8550f950b5b6eace74bde56e6d1057ba147326 | guhaigg/python | /month01/day14/demo02.py | 2,361 | 4.21875 | 4 | """
需求:一家公司有如下几种岗位:
程序员:底薪 + 项目分红
测试员:底薪 + Bug数*5
创建员工管理器,实现下列要求:
(1)存储多个员工
(2)打印所有员工姓名
(3)计算所有员薪资
练习1:写出下列代码的面向对象三大特征思想
封装: 创建EmployeeController/Programmer/Tester
继承: 创建父类Employee
统一Programmer/Tester类型的calculate_salary方法
隔离EmployeeController与Programmer/Tester
多态:对于Employee的calculate_salary方法,在Programmer/Tester类中有不同实现
Programmer/Tester重写calculate_salary方法的内容
"""
class EmployeeController:
"""
员工管理器
"""
def __init__(self):
self.__list_employee = []
@property
def list_employee(self):
return self.__list_employee
def add_employee(self, emp):
if isinstance(emp, Employee):
self.__list_employee.append(emp)
def get_total_salary(self):
total_salary = 0
for item in self.__list_employee:
# 体会多态:编码时调用父
# 运行时执行子
total_salary += item.calculate_salary()
return total_salary
class Employee:
def __init__(self, name="", base_salary=0):
self.name = name
self.base_salary = base_salary
def calculate_salary(self):
pass
class Programmer(Employee):
def __init__(self, name, base_salary, bonus):
super().__init__(name, base_salary)
self.bonus = bonus
def calculate_salary(self):
# 底薪 + 项目分红
salary = self.base_salary + self.bonus
return salary
class Tester(Employee):
def __init__(self, name, base_salary, bug_count):
super().__init__(name, base_salary)
self.bug_count = bug_count
def calculate_salary(self):
# 底薪 + Bug数*5
salary = self.base_salary + self.bug_count * 5
return salary
controller = EmployeeController()
controller.add_employee(Programmer("张三", 10000, 1000000))
controller.add_employee(Tester("李四", 8000, 300))
controller.add_employee("大爷")
print(controller.get_total_salary())
for item in controller.list_employee:
print(item.name)
| false |
770a6e6b9e78a16c3148f3669379014f49518ddb | alandegenhart/python | /prog_ex/08_rock_paper_scissors.py | 2,410 | 4.65625 | 5 | # Practice Python Exercise 08 -- Rock, paper, scissors
#
# This script allows the user to play rock, paper, scissors. The user is prompted for one of three possible inputs,
# randomly chooses an input for the computer, and displays the result.
import random as rnd
def choose_winner(sel):
# Function to determine the winner. This function implements a if/elif chain that is generally fragile and
# inefficient.
if sel[0] == sel[1]:
result = 0
elif sel == ('rock', 'paper'):
result = 2
elif sel == ('rock', 'scissors'):
result = 1
elif sel == ('paper', 'rock'):
result = 1
elif sel == ('paper', 'scissors'):
result = 2
elif sel == ('scissors', 'rock'):
result = 2
elif sel == ('scissors', 'paper'):
result = 1
else:
result = None
return result
def choose_winner_2(sel):
# Function to choose the winner. This implements a more elegant solution where the selection is used as the key
# into a dictionary of possible options.
if sel[0] == sel[1]:
result = 0
else:
all_outcomes = {
('rock', 'paper'): 2,
('rock', 'scissors'): 1,
('paper', 'rock'): 1,
('paper', 'scissors'): 2,
('scissors', 'rock'): 2,
('scissors', 'paper'): 1}
result = all_outcomes[sel]
return result
# Define result strings
output_str = ['You and the computer tied.',
'You win!',
'The computer wins.']
# Continuously loop until the user decides to exit
while True:
# Get input from the user
s = input('Enter an input (rock, paper, or scissors). Type "exit" to quit: ')
# Convert input to lower case, define valid options
s = s.lower() # Note: the 'lower' function does not chance the input object
valid_options = ['rock', 'paper', 'scissors']
if s in valid_options:
# Choose a random input for the computer player
idx = rnd.sample(range(len(valid_options)), 1)[0]
print('The computer choose {}.'.format(valid_options[idx]))
# Determine the winner
r = choose_winner_2((s, valid_options[idx]))
# Display the result
print(output_str[r])
elif s == 'exit':
# Break out of loop
break
else:
# Inform the user that the input was invalid
print('Invalid input.')
| true |
c36d93f8567325f35afb52ffcd258aef6cd1cf16 | alandegenhart/python | /prog_ex/04_divisors.py | 684 | 4.375 | 4 | # Practice Python Exercise 4 -- Divisors
#
# This script asks the user for a number and returns all of the divisors of that number.
# Get user input and convert to a number
x = input('Enter a number: ')
# Verify that input number is an integer
try:
x = float(x)
except ValueError:
print('The provided in put must be a number.\n')
exit(1)
# Convert input number to an integer in case it was a float
x = int(x)
if x < 1:
print('The provided input must be greater than 0.')
exit(1)
# Iterate over values and get those which the input is divisible by
a = [i for i in range(1, x+1) if x % i == 0]
print('The provided input ({}) is divisible by {}.'.format(x, a)) | true |
ba38bb24213f0f36bdd424ed8431cad198c1d03b | o-ndr/LPTHW-OP | /ex25.py | 2,572 | 4.28125 | 4 | # I add the 'sentence' variable in Python (run python -i in git bash)
# then assign the sentence with a few words to the variable
# words = ex25.break_words(sentence) means:
# 1: create variable 'words'
# 2: run function 'break_words' with argument 'sentence' on 'ex25'.
# 3: This function breaks words (using .split method/function on the values of the arguments.
# The argument was 'stuff', in Python I created sentence variable,
# it's value was then used as argument for the break_words function
# so the function used its own variable 'words' did the .split,
# and returned the broken words as 'words'
# When I type 'words' in Python, I get this:
# >>> words
# ['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']
def break_words(stuff):
"""This function will break up words for us."""
words = stuff.split(' ')
return words
def sort_words(words):
"""Sorts the words"""
return sorted(words)
def print_first_word(words):
"""Prints the first word after popping it off"""
word = words.pop(0)
print word
# How can the words.pop function change the words variable?
# That's a complicated question, but in this case words is a list,
# and because of that you can give it commands
# and it'll retain the results of those commands.
def print_last_word(words):
"""Prints the last word after popping it off."""
word = words.pop(-1)
print word
# After I run 2 previous functions (ex25.print(first_word(words) &
# ex25.print_last_word(words))
# the 1st and last words are popped, and variable words will contain
# less 1st and last element of the array words:
# >>> words
# 'good', 'things', 'come', 'to', 'those', 'who']
def sort_sentence(sentence):
"""Takes in a full sentence and returns the sorted words."""
words = break_words(sentence)
return sort_words(words)
def print_first_and_last(sentence):
"""Prints the first and last words of the sentence."""
words = break_words(sentence)
print_first_word(words)
print_last_word(words)
def print_first_and_last_sorted(sentence):
"""Sorts the words then prints the first and last one."""
words = sort_sentence(sentence)
print_first_word(words)
print_last_word(words)
# when this function is run with argument sentence, the value of 'sentence'
# is changed by function 'sort_sentence"
# (sentence gets sorted alphabetically, result is 'words')
# then 'words' is used as argument with which the 2 functions are run
# and they return the popped 1st and last items of the words array
# and they are printed out (because last line in each of those functions is "print word")
| true |
689f14426fe2ed97bc1023164f2ce89dbd44e501 | o-ndr/LPTHW-OP | /ex20.py | 1,773 | 4.46875 | 4 | from sys import argv
script, input_file = argv
# Function that takes one argument which will be a file.
# When the function is called, it will read the contents of the file
# and print it all out
def print_all(f):
print f.read()
# when called with argument (file name), the method seek
# will take us back to position zero within the file
def rewind(f):
f.seek(0)
# for the object f, do this method/function seek
# when called, the function takes 2 arguments -
# line count and file name (see below, current_line and current_file)
def print_a_line(line_count, f):
print line_count, f.readline()
# Inside readline() is code that scans each byte of the file
# until it finds a \n character, then stops reading the file
# to return what it found so far.
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
# variable current line is defined as 1
# the variable is passed into function print_a_line as 1st argument "line_count"
# the function runs with 2 arguments - 1 and file name,
# and prints line_count, then method readline is run on a file
# (which apparently reads and stores in memory the content of that line)
# and then that corresponding line is printed out
current_line = 1
print_a_line(current_line, current_file)
# below is where variable current_line becomes 2 (1 + 1)
# Function print_a_line takes 2 arguments: 2 and file.
# Function returns (prints out) 2 + the line that has been
# read from the file, as specified in the function - print line_count, f.readline()
current_line += 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line (current_line, current_file)
| true |
d4e61a0accbaaaea34ab6a4ae2a870d26ff17d36 | shiyin-li/demo | /闭包/闭包.py | 764 | 4.15625 | 4 | # 闭包的作用:可以保存外部函数的变量
# 闭包的形成条件:
# 1.函数嵌套
# 2.内部函数使用了外部函数的变量或者参数
# 3.外部函数返回内部函数,这个使用了外部函数变量的内部函数成为闭包
#1.函数嵌套
def func_out():
# 外部函数
num1=10
def func_inner(num2):
# 内部函数
# 2.内部函数必须使用外部函数的变量或参数
result=num1+num2
print("结果:",result)
# 3.外部函数返回内部函数,这个使用了外部函数变量的内部函数成为闭包
return func_inner
# 获取闭包对象
# 这里的new_func就是闭包
# 这里的new_func=func_inner
new_func=func_out()
# 执行闭包
new_func(2)
new_func(10)
| false |
7e59344f37d63ff2fba1c0f8ccc59c80a2921703 | seshadribpl/seshadri_scripts | /python/class-employee-1.py | 1,380 | 4.125 | 4 | class employee:
raise_amt = 1.3
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
print 'the name is: %s %s' %(self.first, self.last)
print 'the email ID is: %s' %self.email
print 'the pay is: %s' %self.pay
print 'the new pay is %s x' %employee.raise_amt
# employee.num_of_emps += 1
# print 'the total number of employees: %s' %employee.emp_count
def fullname(self):
return '{} {}'.format(self.first, self.last)
def income(self):
print 'the current pay is %s' %self.pay
# return self.pay
def email(self):
print 'Email ID is: %s' %self.email
# return self.email
def apply_raise(self):
new_pay = int(self.pay) * self.raise_amt
print 'the new pay is %s ' %self.new_pay
return '{}'.format(self.pay)
@classmethod
def from_string(cls, emp_str):
first, last, pay = emp_str.split('-')
return cls(first,last,pay)
# emp1 = employee('raju', 'gentleman', 50000)
# emp2 = employee('munna', 'bhai', 40000)
# print emp1.fullname()
# print emp1.income()
# print emp1.apply_raise()
# print(employee.num_of_emps)
# print emp2.fullname()
# print emp2.income()
# print emp2.apply_raise()
emp3_str = 'John-Doe-90000'
first, last, pay = emp3_str.split('-')
emp3 = employee(first,last,pay)
# print emp3.apply_raise()
print emp3.fullname()
print emp3.apply_raise() | false |
058d4f1f7a556c9e77c73bc65c8350bff741fcb7 | xiaoming2333ca/wave_1 | /Volume of Cylinder.py | 249 | 4.125 | 4 | import math
base_radius = int(input("please enter the base radius of cylinder: "))
height = int(input("please enter the height of cylinder: "))
base_area = math.pi * pow(base_radius, 2)
cylinder_volume = base_area * height
print(cylinder_volume)
| true |
5d09a51e7546466a39fae991deb3cd33c2b29205 | heangly/AlgoExpert-Problem-Solutions | /solutions-in-python/29. Node Depths.py | 1,542 | 4.15625 | 4 | """
*** Node Depths ***
The distance between a node in a Binary Tree and the tree's root is called the node's depth. Write a function that takes in a Binary
Tree and returns the sum of its nodes'depths. Each Binary Tree node has an integer value, a left child node, and a right child node.
Children nodes can either be Binary Tree nodes themselves or None / Null.
Sample Input:
tree =
1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
Sample Output:
16
//The depth of the node with value 2 is 1.
//The depth of the node with value 3 is 1.
//The depth of the node with value 4 is 2.
//Summing all of these depths yields 16.
"""
class BinaryTree:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# recursive approach
#O(n) time | O(h) space
def nodeDepths(root, depth=0):
#handle base case of recursion
if root is None:
return 0
return depth + nodeDepths(root.left, depth + 1) + nodeDepths(root.right, depth + 1)
# iterative approach
# O(n) time | O(h) space
# def nodeDepths(root):
# sumOfDepths = 0
# stack = [{"node": root, "depth":0}]
# while len(stack) > 0:
# nodeInfo = stack.pop()
# node, depth = nodeInfo["node"], nodeInfo["depth"]
# if node is None:
# continue
# sumOfDepths += depth
# stack.append({"node": node.left, "depth": depth + 1})
# stack.append({"node": node.right, "depth": depth + 1})
| true |
a653abd7d830dd1f1ae67f0422b934eb39da7037 | heangly/AlgoExpert-Problem-Solutions | /solutions-in-python/7. Product Sum.py | 950 | 4.46875 | 4 | """
*** Product Sum ***
Write a function that takes in a 'special' array and returns its product sum. A 'special' array is a non-empty array that
contains either integers or other 'special' arrays. The product sum of a 'special' array is the sum of its elements, where
'special' arrays inside it are summed themselves and then multiplied by their level of depth.
For example, the product sum of [x, y] is x + y; the product sum of [x, [y,z]] is x + 2y + 2z
Sample Input:
array = [5, 2, [7, -1], 3, [6, [-13, 8], 4]]
Sample Output:
12 // calculated as 5 + 2 + 2 * (7 - 1) + 3 + 2 * (6 + 3 * (-13 +8) + 4)
"""
#O(n) time | O(d) time
def productSum(array, multiplier=1):
sum = 0
for element in array:
if type(element) is list:
sum += productSum(element, multiplier + 1)
else:
sum += element
return sum * multiplier
# testing
array = [5, 2, [7, -1], 3, [6, [-13, 8], 4]]
productSum(array)
| true |
3e1b09130f09ef3517c3722e0c01a59bf80489c6 | heangly/AlgoExpert-Problem-Solutions | /solutions-in-python/1.TwoSum.py | 1,797 | 4.25 | 4 | """
*** Two Number Sum ***
Write a function that takes in a non-empty of distinct integers and an integers representing a target sum.
If any two numbers in the input array sum up to the target sum, the function should return them in an array.
If no two numbers sum up to the target sum. the function should return an empty array. Assume that there
will be at most one pair of numbers summing up to the target sum.
Sample input: [3, 5, -4, 8, 11, 1, -1, 6], 10
Sample output: [-1, 11]
"""
#Using 2 ForLoops
#Time: O(n^2) | Space: O(1)
def twoNumberSum1(array, target_sum):
for outer in range(len(array)-1):
for inner in range(outer+1, len(array)):
if array[outer] + array[inner] is target_sum:
return [array[outer], array[inner]]
return []
#Using hash_table
#Time: 0(n) | Space: 0(n)
def twoNumberSum2(array, target_sum):
hash_map = dict()
for num in array:
compliment = target_sum - num
if compliment in hash_map:
return [compliment, num]
else:
#store the num (not the compliment) in the hash_map
hash_map[num] = True #the true value is optional. You can put whatever you want.
return []
#Preferred!!!
#Using 2 pointers
#Time: 0(nlog(n)) | Space: 0(1)
def twoNumberSum3(array, target_sum):
array.sort()
left = 0
right = len(array)-1
#while left pointer and right pointer don't overlap to each other
while left < right:
current_sum = array[left] + array[right]
if current_sum is target_sum:
return [array[left], array[right]]
elif current_sum < target_sum:
left += 1
else:
right -= 1
return []
#testing
arr = [3, 5, -4, 8, 11, 1, -1, 6]
target = 10
print(twoNumberSum3(arr, target))
| true |
77c26c1d933feefed022b1b9f86c263e207ddde0 | heangly/AlgoExpert-Problem-Solutions | /solutions-in-python/17. Move Element To End.py | 822 | 4.15625 | 4 | """
Move Element To End
You're given an array of integers and an integer. Write a function that moves all instances of that integer in the array
to the end of the array and returns the array.
The function should perform this in place(i.e., it should mutate the input array) and doesn't need to maintain the order
of the other integers.
Sample Input:
array = [2, 1, 2, 2, 2, 3, 4, 2]
toMove = 2
Sample Output:
[1, 3, 4, 2, 2, 2, 2, 2]
"""
#O(n) time | O(n) space
def moveElementToEnd(array, toMove):
i = 0
j = len(array) - 1
while i < j:
while array[j] == toMove and i < j:
j -= 1
if array[i] == toMove:
array[i], array[j] = array[j], array[i]
i += 1
return array
#test
array = [2, 1, 2, 2, 2, 3, 4, 2]
toMove = 2
print(moveElementToEnd(array, toMove)) | true |
016db88baf1a04abbdcca909d55117ee9e799f0c | wyfkwok/CompletePythonBootcamp | /00-PythonObjectAndDataStructureBasics/07-SetsAndBooleans.py | 666 | 4.21875 | 4 | # Sets are unordered collections of unique elements
my_set = set()
my_set.add(1)
print(my_set)
my_set.add(2)
print(my_set)
# Sets only accept unique values. Will not add 2 again.
my_set.add(2)
print(my_set)
my_set.add('2')
print(my_set)
my_list = [4, 4, 1, 1, 1, 1, 1, 2, 2, 3, 3, 3]
# Cast the list as a set.
# It may look like they are in order, but sets really have no order.
x = set(my_list)
print(x)
# Turn the string into a set of unique letters
print(set('Mississippi'))
# Booleans bitches!
print(type(True))
print(type(False))
# We can use None as a placeholder for an object that we don't want to reassign yet
b = None
print(b)
print(type(b))
| true |
208676754f5a4f7ef1c1d6550d6e8a1a67352dda | vkaplarevic/MyCodeEvalSolutions | /python/interrupted_bubble_sort.py | 680 | 4.25 | 4 | #! /usr/bin/env python
import sys
def bubble_sort_iteration(array, iteration):
size = len(array)
for i in range(size):
for j in range(1, size - i):
if array[j - 1] > array[j]:
array[j - 1], array[j] = array[j], array[j - 1]
if i == iteration - 1:
return
def main():
test_cases = open(sys.argv[1], 'r')
for line in test_cases:
tmp = line.split(' | ')
iteration = int(tmp[1])
array = [int(x) for x in tmp[0].split(' ')]
bubble_sort_iteration(array, iteration)
print(' '.join([str(x) for x in array]))
test_cases.close()
if __name__ == '__main__':
main()
| false |
808208864d5a57f123a0600335a09aef010e5e4f | daking0/b_Python | /_2019_05_16/_03_string_indexing.py | 1,923 | 4.34375 | 4 | # 문자열 인덱싱
a = "Life is too short, Youd need Python"
print(a[3]) # e
print(a[12]) # s
print(a[-1]) # n
print(a[-2]) # o
# 문자열 슬라이싱
# 앞은 포함, 뒤는 이전
print(a[0:4]) # 0부터 3까지 Life
print(a[0:3]) # Lif
print(a[8:11]) # too
print(a[19:]) # 19부터 ~ 끝
print(a[:17]) # 처음부터 ~ 17 이전
print(a[:]) # 전체 문자열
a = '20190516Sunny'
print("date: " + a[:8]) # 20190516
print("weather: " +a[8:]) # Sunny
year = a[:4]
day = a[4:8]
weather = a[8:]
print("year: " + year)
print("day: " + day) # 20190516
print("weather: " + weather) # Sunny
# 문자열 포맷팅
s = "I eat %s apples." % 3 # s는 모든걸 다 받는다
print(s)
number = 10
day = 'three'
s = """
I ate %s apples.
so I was sick for %s days.
""" % (number, day)
print(s)
s = """
I ate {0} apples.
so I was sick for {1} days.
""" .format(number, day)
print(s)
# 문자열 함수
s = "Hello Python"
print(s, type(s))
# 문자 개수 세기
print(s, type(s))
# 문자 개수 세기
print(s.count('l')) # l이라는 문자 몇 개야
print(s.count('e'))
# 문자 위치 알려주기
print(s.find('P'))
print(s.find('k')) # 없는 건 -1
print(s.index('P')) #
#print(s.index('k')) # 예외 발생
# 문자 삽입
a = ","
b = a.join('abcd')
print(b)
# 대소문자 바꾸기
a = 'hi'
b = 'HI'
print(a.upper())
print(b.lower())
# 왼쪽 공백 지우기
a = ' hi'
print('Hi' + a)
print('Hi' + a.lstrip())
# 오른쪽 공백 지우기
a = 'hi '
print(a + "Fine Thank You")
print(a.rstrip() + "Fine Thank You")
# 양쪽 공백지우기
a = " hi "
print('***' + a + '***')
print('***' + a.strip() + '***')
# 문자열 바꾸기
a = "Life is too short"
b = a.replace("short","long")
print(b)
# 문자열 나누기
a = "Life is too short"
b = a.split()
print(b)
a = 'a:b:c:d'
b = a.split(':')
print(b) | false |
0a051ad0bc6311b79039fdb153e06030d79d3bea | diecamdia/python-programming | /listas/listas.py | 701 | 4.1875 | 4 | #declaracin de lista
invitados = ['Manolo','Carmen','Pedro', 'Jorge']
#acceso a elementos
print (invitados[0])
#borrar elementos
invitados.remove('Carmen')
del invitados[0]
print (invitados[0])
#agregar elementos
invitados.append('Maria')
#acceder al ltimo elemento
print('El ultimo invitado es', invitados[-1])
#encontrar la posicin de un valor
print (invitados.index('Pedro'))
#la siguiente instruccin da error porque no existe en la lista
#print (invitados.index('Manolo'))
longitud = len(invitados)
print('La lista tiene %d elementos' % longitud)
for indice in range(longitud):
print(invitados[indice])
print('Lista de invitados')
for invitado in invitados:
print(invitado)
| false |
a37fe440410322552ccb20429c2b1e4e08c18086 | luowanqian/DSA | /python/dsa/queue/linked_queue.py | 1,809 | 4.25 | 4 | """A Queue using a Linked List like structure
"""
from .node import Node
class QueueIterator:
def __init__(self, queue):
self._queue = queue
self._pointer = queue.first
def __next__(self):
if self._pointer is None:
raise StopIteration()
node = self._pointer
self._pointer = node.next
return node.item
class Queue:
"""Linked List Queue
Examples
--------
>>> queue = Queue()
>>> nums = [1, 2, 3]
>>> for n in nums:
... queue.enqueue(n)
...
>>> queue.is_empty()
False
>>> len(queue)
3
>>> for elem in queue:
... print(elem)
...
1
2
3
>>> queue.dequeue()
1
>>> queue.dequeue()
2
>>> queue.dequeue()
3
>>> queue.is_empty()
True
"""
def __init__(self):
# number of items on the queue
self._num_items = 0
# link to least recently added node
self._first = None
# link to most recently added node
self._last = None
def enqueue(self, item):
old_last = self._last
last = Node()
last.item = item
self._last = last
if self.is_empty():
self._first = self._last
else:
old_last.next = self._last
self._num_items = self._num_items + 1
def dequeue(self):
item = self._first.item
self._first = self._first.next
if self.is_empty():
self._last = None
self._num_items = self._num_items - 1
return item
def is_empty(self):
return self._first is None
def __len__(self):
return self._num_items
def __iter__(self):
return QueueIterator(self)
@property
def first(self):
return self._first
| true |
80cec8f840f5672b75f9c20a7d8df5bf5b07bbf5 | easyawslearn/Python-Tutorial | /#2_Python_Basic_Operators.py | 1,683 | 4.46875 | 4 | # Assume variable a = 10 and variable b = 20
# Operator Description Example
# + Addition Adds values on either side of the operator. a + b = 30
# - Subtraction Subtracts right hand operand from left hand operand. a – b = -10
# * Multiplication Multiplies values on either side of the operator a * b = 200
# / Division Divides left hand operand by right hand operand b / a = 2
# % Modulus Divides left hand operand by right hand operand and returns remainder b % a = 0
# ** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20
# //Floor Division The division of operands where the result is the quotient in which the digits after the decimal point are removed.
#Number Format in Hex octa and Binary & Arithmetic Operator Example
a=0b100
print (a)
#Output is
#4
a=0xa
print (a)
#Output is
#10
a=0o100
print (a)
#Output is
#64
print ("Arithmetic Operator Example")
# Arithmetic Operator Example
a=10
b=20
#Addition Operator
print (a+b)
#Output is
#30
#Subscraction Operator
print (b-a)
#Output is
#10
#Division Operator
print (b/a)
#Output is
#2.0
#Multipication Operator
print (a*b)
#Output is
#200
#Power hsm_operation
c=2
d=2
print (c**d)
#Output is
#4
#Floor Division - The division of operands where the result is the quotient in which the digits after the decimal point are removed.
e=9
f=2
print (e//f)
#Output is
#4
#percentage Operation
print (e%f)
#Output is
#1
a=100
example = ---a
print (example)
a=100
example = --a
print (example)
a=100
example = +a
print (example)
a=100
example = ++a
print (example)
| true |
0cbb47f532d59ef007f011a648909e93106fb3f7 | easyawslearn/Python-Tutorial | /Python-String-Basics/String-Formating.py | 1,427 | 4.71875 | 5 | # Python String Formating Demostration
# Python program to demonstrate the
# use of capitalize() function
# capitalize() first letter of
# string.
example = "Python LEARNINF"
print ("String make to capitalize\n")
print(example.capitalize())
# demonstration of individual words
# capitalization to generate camel case
name1 = "hello"
name2 = "world"
print ("2 String make to capitalize\n")
print(name1.capitalize() + name2.capitalize())
# Python code for implementation of isupper()
# checking for uppercase characters
string = 'PYTHON LEARNING'
print (string)
print ("\nChecking String is upper case\n")
print(string.isupper())
print ("\nChanging string upper case to lower\n")
#change staring case using lower function
print (string.lower())
string = 'python learning'
# Python code for implementation of isupper()
# checking for uppercase characters
print (string)
print ("\nChecking String is upper case\n")
print(string.isupper())
#change staring case using lower function
print ("\nChanging string lower case to upper\n")
print (string.upper())
string = "Python Learning"
# Python code for implementation of swapcase()
print (string)
print ("\nChanging string case using swapcase function\n")
print (string.swapcase())
string = "python learning"
# Python code for implementation of title()
print (string)
print ("\n make title of string\n")
print (string.title())
| true |
7ef7ba9614417fe6c3ee643540da3bbc181916c5 | easyawslearn/Python-Tutorial | /#3_Python_Comparison_Operators.py | 1,138 | 4.375 | 4 | # Operator Description Example
# == If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
# != If values of two operands are not equal, then condition becomes true. (a != b) is true.
# > If the value of left operand is greater than the value of right operand, then condition becomes true. (a > b) is not true.
# < If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is true.
# >= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is not true.
# <= If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is true.a=9
a=9
b=2
#Comparison Operation retus only boolen value (True/False)
print (a==b)
#output would be
#False
print (a!=b)
#output would be
#True
print (a>b)
#output would be
#True
print (a<b)
#output would be
#False
print (a>=b)
#output would be
#True
print (a<=b)
#output would be
#False
print (a and b)
| true |
862d56aa6f34b506b1496af2c959ec0d6727cb31 | easyawslearn/Python-Tutorial | /#6_Python_Type_Conversion.py | 1,601 | 4.65625 | 5 | # Python code to demonstrate Type conversion
# int(a,base) : This function converts any data type to integer. ‘Base’ specifies the base in which string is if data type is string.
# float() : This function is used to convert any data type to a floating point number
# complex(): This function is used to convert any data type to complex data type
# bool(): This function is used to identify the value is 0 or not it return True or False
a=1
b="101010"
print ("Convert Value in integer data type",int(b,2),)
print ("Convert value in float data type",float(a),)
print ("convert value in complex data type",complex(a),)
print ("validiate value as boolen datatype",bool(a),)
# using ord(), hex(), oct()
# initializing integer
example = '4'
# printing character converting to integer
output = ord(example)
print ("After converting character to integer : ",end="")
print (output)
# printing integer converting to hexadecimal string
output = hex(50)
print ("After converting 56 to hexadecimal string : ",end="")
print (output)
# printing integer converting to octal string
output = oct(60)
print ("After converting 56 to octal string : ",end="")
print (output)
example=0
output = (bool(example))
print ("validating example value is 0 or not using bool function: ", end="")
print (output)
example=1
output = (bool(example))
print ("validating example value is 0 or not using bool function: ", end="")
print (output)
example=-1
output = (bool(example))
print ("validating example value is 0 or not using bool function: ", end="")
print (output)
| true |
f20ef33b1667e3c56708ce5a47b3095fec9560dc | easyawslearn/Python-Tutorial | /String-escape/string-repr.py | 745 | 4.25 | 4 | # Python code to demonstrate printing
# escape characters from repr()
# initializing target string
example = "I\nLove\tworld"
print ("The string without repr() is : ")
print (example)
print ("\r")
print ("The string after using repr() is : ")
print (repr(example))
# Python code to demonstrate printing
# escape characters from "r" or "R"
# initializing target string
ch = "I\nLove\tWorld"
print ("The string without r / R is : ")
print (ch)
#print ("\r")
# using "r" to prevent resolution
ch1 = r"I\nLove\tWorld"
print ("The string after using r is : ")
print (ch1)
#print ("\r")
# using "R" to prevent resolution
ch2 = R"I\nLove\tWorld"
print ("The string after using R is : ")
print (ch2)
| false |
29b4b6025cdb4f00a6206db5fd3cb681556f76f8 | nyu-compphys-2017/section-1-smfarzaneh | /riemann.py | 882 | 4.5 | 4 | # This is a python file! The '#' character indicates that the following line is a comment.
import numpy as np
# The following is an example for how to define a function in Python
# def tells the compiler that hello_world is the name of a function
# this implementation of hello_world takes a string as an argument,
# which has default value of the empty string. If the user calls
# hello_world() without an argument, then the compiler uses ''
# as the default value of the argument.
def hello_world(name=''):
print 'hello world!'
print name
return
#Implement the Riemann Sum approximation for integrals.
def int_riemann(a, b, N, func):
width = (b - a + 0.0)/N
print str(width)
x_vals = np.arange(a + width, b + width, width) # right biased points
print str(x_vals)
func_vals = func(x_vals)
int_reimann = np.sum(func_vals)*width
return int_reimann
| true |
3e60af1c7caf77153f0d0f75ff0a224a86ab0d07 | id3at/practicepython.org | /stringlist.py | 439 | 4.125 | 4 | """
Autor id3at
"""
#https://www.practicepython.org/exercise/2014/03/12/06-string-lists.html
#Exercise 6
#Ask the user for a string and print out whether this string is
#a palindrome or not. (A palindrome is a string that reads
# the same forwards and backwards.)
NAZWA = input('Podaj słowo a sprawdzimy czy to Palindrom: ')
if NAZWA == NAZWA[::-1]:
print('To jest Palindrom')
else:
print('To nie jest Palindrom')
| false |
9ec12ffcfb7d1014dfac3260b18a0f3b0f8ea919 | bai3/python-demo | /part1/1.2.py | 1,701 | 4.1875 | 4 | # coding:utf-8
'''
python支持三种不同的数值类型
- 整型(int)
- 浮点型(float)
- 复数(complex)
'''
number = 0xA0F
#十六进制
print(number)
# => 2575
number = 0o37
#八进制
print(number)
# => 31
#python的数字类型的转换
'''
- int(x)将x转换一个整数
- float(x)将x转换一个浮点数
- complex(x)将x转换一个复数,实数部分为x,虚数部分为0
- complex(x,y)将x和y转换到一个复数,实数部分为x,虚数部分为y
'''
a = 1.0
print(int(a))
# => 1
print(8/5)
# => 1.6
print(8//5)
# => 1
print(8%5)
# => 3
print(8**2)
# 进行平方运算 => 64
# print((8***2))
# 测试 => error 并不是三次方
# 不同类型的数混合运算时会将整数转换为浮点数
print(3*3.75/1.5)
# =>7.5
# 常用的数学函数
print(abs(-5))
# 绝对值 =>5
import math
print(math.ceil(4.1))
# 向上取整 => 5
print(math.fabs(-5))
# 绝对值 => 5.0
print(math.floor(4.1))
# 向下取整 => 4
print(max(-5,2,3,100,10))
# 取最大值 => 100
print(min(-5, -2 ,-100 ,1))
# 取最小值 =>-100
print(pow(2,3))
# 2^3
# 随机数函数
'''
随机数可以用于数学,游戏,安全领域中,还经常
被嵌入算法中,用以提高算法效率,并提高程序的
安全性
'''
import random
# choice 从序列的元素中随机挑选一个元素,比如random.choice(range(10)),从0到9随机挑选一个整数
print('随机数:'+str(random.choice(range(10))))
# random()随机在[0,1)中随机生成一个数
print(random.random())
# shuffle(list)将序列中的所有元素随机排列
# uniform(x.y)随机生成一个实数,它在[x,y]范围内。
# 数学常量
print(math.pi);
# 圆周率
print(math.e);
# 自然常数
| false |
01791bda3d20bae50bc99ca53c710eddf4d752b5 | pranaymate/Python_3_Deep_Dive_Part_1 | /Section 7 Scopes, Closures and Decorators/97. Global and Local Scopes - Lecture.py | 2,046 | 4.625 | 5 | a = 10
# def my_func(n):
# c = n ** 2
# return c
#
#
# def my_func(n):
# print('global:', a)
# c = a ** n
# return print(c)
#
# my_func(2)
# my_func(3)
print('#' * 52 + ' ')
print('# But remember that the scope of a variable is determined by where it is assigned. In particular, any variable'
' defined (i.e. assigned a value) inside a function is local to that function, even if the variable name'
' happens to be global too! ')
def my_func(n):
a = 2
c = a ** 2
return c
print(a)
print(my_func(8))
print(a)
print('#' * 52 + ' In order to change the value of a global variable within an inner scope, we can use the **global**'
' keyword as follows: ')
def my_func(n):
global a
a = 2
c = a ** 2
return c
print(a)
print(my_func(3))
print(a)
print('#' * 52 + ' ')
print()
def my_func(n):
global var
var = 'hello world'
return n ** 2
# print(var) # NameError: name 'var' is not defined
print(my_func(2))
print(var)
print('#' * 52 + ' Remember that whenever you assign a value to a variable without having specified the variable'
' as **global**, it is **local** in the current scope. **Moreover**, it does not matter **where**'
' the assignment in the code takes place, the variable is considered local in the **entire** '
' scope - Python determines the scope of objects at compile-time, not at run-time.')
a = 10
b = 100
def my_func():
print(a)
print(b)
my_func()
print('#' * 52 + ' ')
a = 10
b = 100
# def my_func():
# print(a)
# print(b)
# b = 1000 # UnboundLocalError: local variable 'b' referenced before assignment
#
#
# my_func()
print('#' * 52 + ' Of course, functions are also objects, and scoping applies equally to function objects too. '
' For example, we can "mask" the built-in `print` Python function:')
print = lambda x: 'hello {0}!'.format(x)
def my_func(name):
return print(name)
my_func('world')
del print
| true |
f9d34e423be9b07780ee4b6898d015917736db71 | pranaymate/Python_3_Deep_Dive_Part_1 | /Section 5 Function Parameters/69. args - Coding.py | 2,357 | 4.625 | 5 |
print('#' * 52 + ' Recall from iterable unpacking:')
a, b, *c = 10, 20, 'a', 'b'
print(a, b)
print(c)
print('#' * 52 + ' We can use a similar concept in function definitions to allow for arbitrary'
' numbers of positional parameters/arguments:')
def func1(a, b, *args):
print(a)
print(b)
print(args)
func1(1, 2, 'a', 'b')
print('#' * 52 + ' Unlike iterable unpacking, *args will be a tuple, not a list.')
print('#' * 52 + ' The name of the parameter args can be anything you prefer')
print('#' * 52 + ' You cannot specify positional arguments after the *args parameter - '
' this does something different that we will cover in the next lecture.')
def func1(a, b, *my_vars):
print(a)
print(b)
print(my_vars)
func1(10, 20, 'a', 'b', 'c')
def func1(a, b, *c, d):
print(a)
print(b)
print(c)
print(d)
# func1(10, 20, 'a', 'b', 100) # TypeError: func1() missing 1 required keyword-only argument: 'd'
print('#' * 52 + ' Lets see how we might use this to calculate the average of an arbitrary number of parameters.')
def avg(*args):
count = len(args)
total = sum(args)
return total/count
print(avg(2, 2, 4, 4))
def avg(*args):
count = len(args)
total = sum(args)
if count == 0:
return 0
else:
return total/count
print(avg(2, 2, 4, 4))
print(avg())
print('#' * 52 + ' But we may not want to allow specifying zero arguments, '
' in which case we can split our parameters into a required (non-defaulted) positional argument, '
' and the rest:')
def avg(a, *args):
count = len(args) + 1
total = a + sum(args)
return total/count
print(avg(2, 2, 4, 4))
print('#' * 52 + ' Unpacking an iterable into positional arguments')
def func1(a, b, c):
print(a)
print(b)
print(c)
l = [10, 20, 30]
# func1(l) # TypeError: func1() missing 2 required positional arguments: 'b' and 'c'
print('#' * 52 + ' But we could unpack the list, and then pass it to as the function arguments:')
print(*l,)
func1(*l)
print('#' * 52 + ' What about mixing positional and keyword arguments with this?')
def func1(a, b, c, *d):
print(a)
print(b)
print(c)
print(d)
# func1(10, c=20, b=10, 'a', 'b') # SyntaxError: positional argument follows keyword argument
| true |
f5161cb4e51dc2d68c63ce944ed3b4e381094a77 | pranaymate/Python_3_Deep_Dive_Part_1 | /Section 7 Scopes, Closures and Decorators/103. Closure Applications - Part 1.py | 2,457 | 4.40625 | 4 | print('#' * 52 + ' In this example we are going to build an averager function that can average multiple values.')
print('#' * 52 + ' The twist is that we want to simply be able to feed numbers to that function and get a running'
' average over time, not average a list which requires performing the same calculations'
' (sum and count) over and over again.')
class Averager:
def __init__(self):
self.numbers = []
def add(self, number):
self.numbers.append(number)
total = sum(self.numbers)
count = len(self.numbers)
return total / count
a = Averager()
print(a.add(10))
print(a.add(20))
print(a.add(30))
print('#' * 52 + ' We can do this using a closure as follows:')
def averager():
numbers = []
def add(number):
numbers.append(number)
total = sum(numbers)
count = len(numbers)
return total / count
return add
a = averager()
print(a(10))
print(a(20))
print(a(30))
print('#' * 52 + ' ')
class Averager:
def __init__(self):
self._count = 0
self._total = 0
def add(self, value):
self._total += value
self._count += 1
return self._total / self._count
a = Averager()
print(a.add(10))
print(a.add(20))
print(a.add(30))
print('#' * 52 + ' Now, lets see how we might use a closure to achieve the same thing.')
def averager():
total = 0
count = 0
def add(value):
nonlocal total, count
total += value
count += 1
return 0 if count == 0 else total / count
return add
a = averager()
print(a(10))
print(a(20))
print(a(30))
print('#' * 52 + ' Suppose we want something that can keep track of the running elapsed time in seconds.')
from time import perf_counter
class Timer:
def __init__(self):
self._start = perf_counter()
def __call__(self):
return (perf_counter() - self._start)
a = Timer()
print(a())
print('#' * 52 + ' Lets start another "timer":')
b = Timer()
print(a())
print(b())
print('#' * 52 + ' Now lets rewrite this using a closure instead:')
def timer():
start = perf_counter()
def elapsed():
# we don't even need to make start nonlocal
# since we are only reading it
return perf_counter() - start
return elapsed
x = timer()
print(x)
print(x())
y = timer()
print(y)
print(y())
print(a())
print(b())
print(x())
print(y())
| true |
c544784f9d91764d713fd742b9ca7efccbf3b244 | pranaymate/Python_3_Deep_Dive_Part_1 | /Section 5 Function Parameters/75. Application A Simple Function Timer.py | 2,061 | 4.375 | 4 |
import time
def time_it(fn, *args, rep=5, **kwargs):
print(args, rep, kwargs)
time_it(print, 1, 2, 3, sep='-')
print('#' * 52 + ' Lets modify our function to actually run the print function with any positional'
' and keyword args (except for rep) passed to it: ')
def time_it(fn, *args, rep=5, **kwargs):
for i in range(rep):
fn(*args, **kwargs)
time_it(print, 1, 2, 3, sep='-')
print('#' * 52 + ' We can even add more arguments: ')
time_it(print, 1, 2, 3, sep='-', end=' *** ', rep=3)
print()
print('#' * 52 + ' Now all that iss really left for us to do is to time the function and return the average time: ')
def time_it(fn, *args, rep=5, **kwargs):
start = time.perf_counter()
for i in range(rep):
fn(*args, **kwargs)
end = time.perf_counter()
return (end - start) / rep
print('#' * 52 + ' Lets write a few functions we might want to time:')
print('#' * 52 + ' We will create three functions that all do the same thing:'
' calculate powers of n**k for k in some range of integer values ')
def compute_powers_1(n, *, start=1, end):
# using a for loop
results = []
for i in range(start, end):
results.append(n**i)
return results
def compute_powers_2(n, *, start=1, end):
# using a list comprehension
return [n**i for i in range(start, end)]
def compute_powers_3(n, *, start=1, end):
# using a generator expression
return (n**i for i in range(start, end))
print('#' * 52 + ' Lets run these functions and see the results:')
print(compute_powers_1(2, end=5))
print(compute_powers_2(2, end=5))
print(list(compute_powers_3(2, end=5)))
print('#' * 52 + ' Finally lets run these functions through our time_it function and see the results:')
print(time_it(compute_powers_1, n=2, end=20000, rep=4))
print(time_it(compute_powers_2, 2, end=20000, rep=4))
print(time_it(compute_powers_3, 2, end=20000, rep=4))
print('#' * 52 + ' ')
print('#' * 52 + ' ')
print('#' * 52 + ' ')
print('#' * 52 + ' ')
print('#' * 52 + ' ')
| true |
e4228a035cd1f4ff6911742ed258485154621495 | lalchand-rajak/Python-Learn | /Basics/comparison.py | 253 | 4.28125 | 4 | x = True # boolean data type true or false
y = False
print(x and y)
print(x or y)
z = False
print( x and y and z)
print((x and y) or z)
print(not x)
print(not y)
print(not(x and y)) # not will reverse the output like true to false or false to true | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.