blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
5031ef63a8e97b9b55df8c872002e5a03fff41e2 | Magical-Man/Python | /Learning Python/practice/listprc.py | 1,269 | 4.25 | 4 | ##Here what we are doing is just declaring a variable, and then printing some stuff
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait, there are not 10 things in that list. Let's fix that.")
##Here we declare a variable assigned to the ten_things var, but split
##Then we make a list called more_stuff
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
##Here we make a loop that is adding to more_stuff from stuff
while len(stuff) != 10:
next_one = more_stuff.pop() #Because there is nothing specified in .pop() the default is the last item
print("Adding: ", next_one)
stuff.append(next_one)
print("There are %d items now." % len(stuff))
print("There we go: ", stuff)
print("Let's do some things with stuff.")
print(stuff[1]) #Here we just say to grab the second item, this is becuase of cardinal nums
print(stuff[-1]) #Here we are grabbing the last item cause integers nad negativces
print(' '.join(stuff)) #Here we say to make everything in stuff back into one string
print("#".join(stuff)) #Same but sperate w/ #
print("#".join(stuff[3:5])) #Here we say print eveything between item 4 and 6
| true |
07e495cda7220ffa3299cb09e7ee082ba57210e2 | Magical-Man/Python | /Learning Python/functions/functions.py | 994 | 4.75 | 5 | #Functions let you make our own mini-scripts or tiny commands.
#We create functions by using th word def in python
#This function is like argv scripts
#So here we create a function named print_two, and we call *args on it, just
#Like argv
def print_two(*args):
arg1, arg2 = args
print("arg1: %r, arg2: %r" %(arg1, arg2))
#Okay, so the *args is actallty pointless there lets just do
def print_two_again(arg1, arg2):
print("arg1: %r, arg2: %r" %(arg1, arg2))
#Now here is one that just takes one argument
def print_one(arg1):
print("arg1: %r" % arg1)
#This one takes no arguments
def print_none():
print("I got nothin'.")
print_two("Charlie", "Odulio")
print_two_again("Charlie", "Odulio")
print_one("First Place!")
print_none()
'''
Some more notes
Always as a colin after the function parenthesis, ;
Always indent
No duplicate arguments in parenthesis
Print, execpt, len, all that is bassiclaly a function
To run, call, or use a function all use the same thing
'''
| true |
fb20e6839f882a85e11b7275a54458dc1c3046a7 | kalensr/pygrader | /prog_test_dir/Debug2.py | 1,407 | 4.15625 | 4 | # Debug Exercise 2
# Create a change-counting game that gets the user to enter the number of
# coins required to make exactly one dollar. The program should prompt
# the user to enter the number of pennies, nickels, dimes, and quarters.
# If the total value of the coins entered is equal to one dollar, the
# program should congratulate the user for winning the game. Otherwise,
# the program should display a message indicating whether the amount
# entered was more than or less than one dollar.
numPennies = int(input('Enter the number of pennies: '))
numNickels = int(input('Enter the number of nickels: '))
numDimes = int(input('Enter the number of dimes: '))
numQuarters = int(input('Enter the number of quarters: '))
# need to convert the above to floats
totalCentValue = numPennies + (numNickels * 5) + (numDimes * 10) + (numQuarters * 25)
# convert count of coins to cents - above
totalDollars = totalCentValue / 100
if totalDollars > 1:
# correct spelling with variable above, lower case 'd', changed to uppercase 'D'
print('Sorry, the amount you entered was more than one dollar.')
elif totalDollars < 1:
# corrected syntax above with else/if statement
print('Sorry, the amount you entered was less than one dollar.')
else:
print('Congratulations!')
print('The amount you entered was exactly one dollar!')
print('You win the game!')
| true |
d4af8a596aed03f073999cf901a4d130875b8807 | DWaze/CreateDB | /checkdb.py | 230 | 4.15625 | 4 | import sqlite3
conn = sqlite3.connect("contacts.sqlite")
name = input("Please enter your name : ")
sql_query = "SELECT * FROM contacts WHERE name LIKE ?"
for row in conn.execute(sql_query, (name,)):
print(row)
conn.close()
| true |
e3a318a9cadbfc7d82b3ca5885c80c1bad4e1b36 | VanessaTan/LPTHW | /EX03/ex3.py | 1,178 | 4.375 | 4 | #Subject introduction
print "I will now count my chickens:"
#Calculation of how many Hens. 30.0 divided by 6.0 + 25.0.
print "Hens", 25.0 + 30.0 / 6.0
#Calculation of how many Roosters. (25.0x3.0 = 75.0) Take 75.0 ÷ 4.0 = 18 with remainder 3.0. Therefore: 100.0 - 3.0 = 97
print "Roosters", 100.0 - 25.0 * 3.0 % 4.0
#New subject introduction
print "Now I will count eggs:"
#Calculation of eggs. 3.0 + 2.0 + 1.0 - 5.0 + (4.0÷2.0= 0 remainders) - (0.25) + 6.0
print 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0
#Questioning statement
print "Is it true that 3.0 + 2.0 < 5.0 - 7.0?"
#True/False answer to statement
print 3.0 + 2.0 < 5.0 - 7.0
#Questioning statement and answer to question in orange calculation
print "What is 3.0 + 2.0?", 3.0 + 2.0
#Questioning statement and answer to question in orange calculation
print "What is 5.0 - 7.0?", 5.0 - 7.0
#Comment
print "Oh, that's why it's False."
#Comment
print "How about some more."
#Question and answer in True/False
print "Is it greater?", 5.0 > -2.0
#Question and answer in True/False
print "Is it greater or equal?", 5.0 >= -2.0
#Question and answer in True/False
print "Is it less or equal?", 5.0 <= -2.0
| true |
4e72c4f48e96103d758a6c766d0b2aa76aed1822 | anandkrthakur/AlgorithmsEveryProgrammerShouldKnow | /01a. BinarySearch_Iterative.py | 1,206 | 4.15625 | 4 | # Find out if a key x exists in the sorted list A
# or not using binary search algorithm
def binarySearch(A, x):
# search space is A[left..right]
(left, right) = (0, len(A) - 1)
# till search space consists of at-least one element
while left <= right:
# we find the mid value in the search space and
# compares it with key value
mid = (left + right) // 2
# overflow can happen. Use:
# mid = left + (right - left) / 2
# mid = right - (right - left) // 2
# key value is found
if x == A[mid]:
return mid
# discard all elements in the right search space
# including the mid element
elif x < A[mid]:
right = mid - 1
# discard all elements in the left search space
# including the mid element
else:
left = mid + 1
# x doesn't exist in the list
return -1
if __name__ == '__main__':
A = [2, 5, 6, 8, 9, 10]
key = 5
index = binarySearch(A, key)
if index != -1:
print("Element found at index", index)
else:
print("Element found not in the list")
| true |
0dccf3b276606b24679a1fc520dc963f8f32600d | TsunamiMonsoon/InternetProgramming | /Homework3/Homework3.py | 1,124 | 4.1875 | 4 | import sqlite3
from os.path import join, split
conn = sqlite3.connect("Courses.sq")
# create a query
cmd = "select * from Courses"
# create a cursor
crs = conn.cursor()
# send a query and receive query result
crs.execute(cmd)
Courses = crs.fetchall()
for row in Courses:
print(row)
cmd2 = """
select Courses.department,
Courses.course_num,
Courses.course_name,
PreReqs.prereq1,
PreReqs.prereq2
from Courses, PreReqs
where PreReqs.course_id = Courses.course_id
"""
crs.execute(cmd2)
Courses2 = crs.fetchall()
#prereqIds = set()
for row in Courses2:
print(row[0] + " " + str(row[1]) + " " + str(row[2]) + " " + str(row[3]) + " " + str(row[4]))
year = input("Enter the year: ")
sem = input("Enter the semester: ")
if year is Courses.years:
print(Courses)
if sem is Courses.semester:
print(Courses)
grade = input("Enter a letter grade: ")
if grade is Courses.grade:
print(Courses)
courseIid = input("Enter the course id: ")
if id is Courses.courseId:
print(Courses) | true |
59924003253bf6eaf850df9876ceef651c38f84f | KuldeepJagrotiya/python | /function/isPalindrome.py | 254 | 4.21875 | 4 | ## Q3 take the input from user and check if number is palindrome
inp = (input("enter the number : "))
out = str()
for i in range(len(inp)-1,-1,-1):
out+=inp[i]
if out==inp:
print(inp,"is a palindrome")
else:
print(inp,"is not a palindrome") | true |
46734740a355dcfab21ca9ed817eda423b106c51 | mohitKhanna1411/COMP9020_19T3_UNSW | /Assignment_3/count_full_nodes.py | 1,250 | 4.34375 | 4 | # Python program to count full
# nodes in a Binary Tree
class newNode():
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Function to get the count of
# full Nodes in a binary tree
def getfullCount(root):
if (root == None):
return -1
if (root.left == None and root.right == None):
return 0
else:
return 1 + (getfullCount(root.left) + getfullCount(root.right))
# def BST_size(root):
# if root is None:
# return -1
# if root is not None:
# count = 1
# if root.left is not None:
# return count += BST_size(root.left)
# if root.right is not None:
# return count += BST_size(root.right)
# Driver code
if __name__ == '__main__':
""" 2
/ \
7 5
\ \
6 9
/ \ /
1 11 4
Let us create Binary Tree as shown
"""
root = newNode(2)
root.left = newNode(7)
root.right = newNode(5)
root.left.right = newNode(6)
root.left.right.left = newNode(1)
root.left.right.right = newNode(11)
root.right.right = newNode(9)
root.right.right.left = newNode(4)
root.right.right.right = newNode(14)
print(getfullCount(root))
# This code is contributed by SHUBHAMSINGH10
| true |
cf326c3bd46d29e86cfa3574178dc2857a1d1a84 | natanonsilver/General-Knowledge-City-Quiz- | /version 3.py | 2,036 | 4.125 | 4 | # In version 3 of my quiz i will doing my 10 question quiz that is a multichoice quiz.
#asking user for name
try:
name=str(input("enter your name:"))
if name == "1234":
raise Exception
except:
input("Please try again, enter your name \n")
#ask the user to enter there age.
try:
age=int(input("Please enter your age?:"))
except:
print("not valid")
else:
print("Please continue")
#asking the user if they are ready to take the quiz
ready=input("are you ready for the quiz?: press y to continue or x to exit:")
if ready=="y" or "yes" :
print("lets continue")
elif ready== "x" or "no":
print("Thank you come again")
#Preparing the dictionary
Captialcitesquiz=(
'1. What is the captial for Nigeria': 'Abuja',
'2. What is the captial for Spain': 'Madrid',
'3. What is the captial for Canada': 'Ottawa',
'4. What is the captial for New Zealand': 'Wellington',
'5. What is the captial for Italy': 'Rome',
'6. What is the captial for Peru': 'Lima',
'7. What is the captial for San Marino': 'San Marino',
'8. What is the captial for Mexico': 'Mexico City',
'9. What is the captial for United States Of America': 'Washington DC',
'10. What is the captial for Syria': 'Damascus',
}
#preparing the multi choice
optlist=['Abuja:11:12:13',
'11:12:18:20',
'Jumping:Swimming:Cycling:Running',
'Speaking:Kicking:Dribbling:Jogging',
'No running with the ball: No speaking with the ball:No passing of the ball:',
'Ants:Coakroaches:Unicorns:Butterfly:',
'3 seconds:50 seconds:10 seconds:100 seconds',
'30 mins:1 hour:1 min:2 mins',
'2 times: 1 time: 3 times: 4 times',
'Running:Passing:Throwing:Breathing techniques',]
| true |
d2af3f9c481bf5d868e446c186eb9c48efd75157 | rdoherty2019/Computer_Programming | /forwards_backwards.py | 1,024 | 4.1875 | 4 | #setting accumulator
num = 0
print("Using while loops")
#Iterations
while num <31:
#If number is divisably by 4 and 3
if num % 4 == 0 and num % 3 == 0:
#accumalte
num += 3
#continue to next iterations
continue
#IF number is divisable by 3 print
if num % 3 == 0 :
print(num)
#accumulate
num += 3
#Setting condition
nu = 30
while nu > 1:
# If number is divisably by 4 and 3
if nu % 4 == 0 and nu % 3 == 0:
#reduce
nu -= 3
#conitune to next itteration
continue
# IF number is divisable by 3 print
if nu % 3 == 0:
print(nu)
#reduce
nu -= 3
print("Using for loops")
#setting range, making sure 30 is included
for n in range(3,31,3):
if n % 4 == 0 and n % 3 == 0:
continue
if n % 3 == 0:
print(n)
#setting range
#making sure 3 is included
#counting backwards
for n in range(30,2,-3):
if n % 4 == 0 and n % 3 == 0:
continue
if n % 3 == 0 :
print(n) | true |
780e01cf0530b9f534adb390d52365ea99ca36aa | jc23729/day-1-3-exercise-1 | /main.py | 220 | 4.3125 | 4 | #Write your code below this line 👇
#This code prints the number of characters in a user's name.
print( len( input("What is your name? ") ) )
#Notes
#If input was "Jack"
#1st: print(len("Jack"))
#2nd: print(4)
| true |
841bfb0cf506bdd439d2aa0f5b54814dfda31ebf | ani17/data-structures-algorithms | /merge-sort.py | 906 | 4.15625 | 4 | import math
def mergeSort(A):
# If no more divison possible through mergeSort return to "merge" logic
# for merging subarrays back into same array by repacing values
# accordingly
if len(A) < 2:
return
# Keep Dividing Array in to Left & Right Sub Arrays
mid = int(math.floor(len(A) / 2))
L = A[0 : mid]
R = A[mid : ]
mergeSort(L)
mergeSort(R)
merge(L,R,A)
return A
def merge(L,R,A):
# iterators for L, R and A
i = 0
l = 0
r = 0
# If iterators of both L & R have not reached the end
# compare values in both arrays and put the smaller value
# back into the existing array
while l < len(L) and r < len(R):
if L[l] <= R[r]:
A[i] = L[l]
l += 1
else:
A[i] = R[r]
r += 1
i +=1
# leftovers in L
while l < len(L):
A[i] = L[l]
l += 1
i += 1
# leftovers in R
while r < len(R):
A[i] = R[r]
r += 1
i += 1
A = [5,4,3,2,1]
S = mergeSort(A)
print(S)
| true |
891262eabe5174b820a8b43673c21e222e8bad85 | LeonVillanueva/Projects | /Daily Exercises/daily_17.py | 473 | 4.15625 | 4 | '''
The ancient Egyptians used to express fractions as a sum of several terms where each numerator is one.
For example, 4 / 13 can be represented as 1 / 4 + 1 / 18 + 1 / 468.
Create an algorithm to turn an ordinary fraction a / b, where a < b, into an Egyptian fraction.
'''
import numpy as np
def e_frac (n, d):
d_list = []
while n != 0:
x = np.ceil(d/n)
d_list.append (x)
n = x*n - d
d *= x
return d_list
| true |
bfc8e8f9574f6cdbe394ebeabee29b2b3a12f80e | aliabbas-s/tathastu_week_of_code | /day3/3.py | 246 | 4.1875 | 4 | #Day-3
#Program 3
string = input("Enter a Word")
length = len(string)
duplicate_string = ""
for i in range(0,length):
if string[i] in duplicate_string:
continue
else:
duplicate_string += string[i]
print(duplicate_string)
| true |
d0b6cc898aca8d016713caf44b36612a9f662fa1 | SteeveJose/luminarpython | /languagefundamentals/largestamong2.py | 243 | 4.125 | 4 | num1=float(input("enter the first number:"))
num2=float(input("enter the second number:"))
if (num1>num2):
print(num1,"is greater than",num2)
elif (num2>num1):
print(num2,"greater than",num1)
else:
print("the two numbers are equal") | true |
0aee0120683e267da353a0af63e518cefebdd7da | TheodoreAI/puzzle | /algorithm.py | 2,753 | 4.125 | 4 | # Mateo Estrada
# CS325
# 03/01/2020
# Description: This algorithm checks to see if the input solution to the 8-puzzle (also known as the sliding puzzle) is solvable.
# Step 1: I choose my favorite puzzle: the 8-puzzle (puzzle number 12 from the list).
# Step 2: The following rules were taken from: file:///Users/mateog.estrada/Downloads/A_Survey_of_NP-Complete_puzzles.pdf
# I. Played on an mxm
# II. m^2 - 1 = n
# III. There is a blank tile that has a possible number of 2, 3, 4 adjacent tiles depending on the location of the blank tile.
# IV. Standard size is a 3x3 and a move of the blank tile will mean the adjacent tile will move to the blank.
# V. 181,440 possible variations that are solvable.
# Step 4: I will use the idea of counting the number of inversions between nodes. Given a board of size N where the size N is an odd integer,
# each legal move changes the number of inversions by an even number.
# If a board has an odd number of inversions, then it cannot lead to the goal board by a sequence of legal moves because the goal board has an even number of inversions.
# I will show my proof by example:
def getInversions(arr):
"""This function was taken from: https://www.geeksforgeeks.org/check-instance-8-puzzle-solvable/#:~:text=What%20is%208%20puzzle%3F,tiles%20into%20the%20empty%20space."""
# we initially the count at 0
countOfInversions = 0
for i in range(0, len(arr)):
for j in range(i + 1, len(arr)):
# value 0 will be used to indicate the "blank"
if arr[i] > arr[j] != 0:
countOfInversions += 1
return countOfInversions
class Solution:
def __init__(self, puzzle):
self.puzzle = puzzle
def hasSolution(self):
# count inversions in 8 puzzle
invertCount = getInversions(self.puzzle)
return invertCount % 2 == 0
def checkSolution(self):
if self.hasSolution():
print("Solvable!")
else:
print("Can't solve that! (Remember, for an 8-puzzle there must be an even number of inversions for the puzzle to have a solution! Please see pdf for more details!")
# The testing:
# this one you should be able to solve because it has an even number of inversions aka 1,3,4,2,5,7,8,6 inversions (3-2, 4-5, 7-6, 8-6) and four inversions is even!
# p1 = [0, 1, 3, 4, 2, 5, 7, 8, 6]
# s1 = Solution(p1)
# s1.checkSolution()
#
# # this one you shouldn't because it has an odd number of inversions aka 8 - 7 is one inversion and one is odd!
# p2 = [1, 2, 3, 4, 5, 6, 8, 7, 0]
# s2 = Solution(p2)
# s2.checkSolution()
# Step 5: The proof is explained using some of the logic from this resource: https://www.cs.princeton.edu/courses/archive/spring13/cos226/assignments/8puzzle.html
| true |
fd3a67b45acba3593efdd159ba41e1aa57b3c256 | SushanShakya/pypractice | /Functions/14.py | 298 | 4.21875 | 4 | # Write a Python program to sort a list of dictionaries using Lambda
nameSort = lambda x: x['name']
sample = [
{
"name" : "Sushan"
},
{
"name" : "Aladin"
},
{
"name" : "Sebastian"
},
]
sorted_list = sorted(sample,key=nameSort)
print(sorted_list) | true |
34dd81b6d4c5480951d6be4595848f0f4da63cdc | morisasy/data-analysis-with-python | /week1/multiplication.py | 580 | 4.21875 | 4 | #!/usr/bin/env python3
"""
Make a program that gives the following output.
You should use a for loop in your solution.
4 multiplied by 0 is 0
4 multiplied by 1 is 4
4 multiplied by 2 is 8
4 multiplied by 3 is 12
4 multiplied by 4 is 16
4 multiplied by 5 is 20
4 multiplied by 6 is 24
4 multiplied by 7 is 28
4 multiplied by 8 is 32
4 multiplied by 9 is 36
4 multiplied by 10 is 40
"""
def main():
# Enter your solution here
x = int(input("Input a number: "))
for i in range(11):
print(f"{x} multiplied by {i} is {x*i}")
if __name__ == "__main__":
main()
| true |
cb6eb22fff86e8a80974c2a21bbe88c2e53af786 | PetersonZou/astr-119-session-4 | /operators.py | 724 | 4.1875 | 4 | x=9
y=3 #integers
#arithmetic operators
print(x+y) #addition
print(x-y) #subtraction
print(x*y) #multiplication
print(x/y) #division
print(x%y) #modulus
print(x**y) #exponentiation
x=9.1918123
print(x//y) #floor division
#Assignment operators
x=9 #sets x to equal 9
x+=3 #x=x+3
print(x)
x=9
x-=3 #x=x-3
print(x)
x*=3 #x=x*3
print(x)
x/=3 #x=x/3
print(x)
x**=3 #x=x**3
print(x)
#Comparison operators
x=9
y=3
print(x==y) #True if x equals to y, False otherwise
print(x!=y) #True if x does not eq y, False otherwise
print(x>y) #True if x is greater than y, False otherwise
print(x<y) #True if x is less than y, False otherwise
print(x>=y) #True if x is greater or eq y, False otherwiseß
print(x<=y) | true |
09164664fb940298ad2dfa5fefa78c52121ab04d | carlavieira/code-study | /algorithms/sorting_searching/sparse_search.py | 1,250 | 4.125 | 4 | def sparse_search(arr, string):
if not arr or not string: return -1
return recursive_binary_search(arr, string, 0, len(arr)-1)
def recursive_binary_search(arr, string, first, last):
if first > last: return -1
mid = (first + last) // 2
#that is not midd, find the closest nonempty value
if not arr[mid]:
# set pointers do mid side
left = mid - 1
right = mid + 1
while True:
# if gets to the point that the pointers exceed the perimeters, that is not a valid value
if left < first and right > last:
return -1
elif arr[right] and right <= last:
mid = right
break
elif arr[left] and left >= first:
mid = left
break
left -= 1
right += 1
if arr[mid] == string: return mid
elif arr[mid] > string: return recursive_binary_search(arr, string, first, mid-1)
elif arr[mid] < string: return recursive_binary_search(arr, string, mid + 1, last)
arr=['at', '', '', '', 'ball', '', '', 'car', '', '', 'dad', '', '']
print(sparse_search(arr, "ball"))
print(sparse_search(arr, "at"))
print(sparse_search(arr, "dad")) | true |
edd7c8fb9a385d76702d906104eb9ccde836fa1e | vishnu2981997/Programming_Ques | /PROG QUES/1.py | 2,902 | 4.1875 | 4 | """
ID: 437
Given an array of n numbers. sort the array in ascending order based on given conditions:
---convert the elements of array to filesize formats
---convert the file sizes to corresponding binary representations
---sort the actual array based on number of 1's present in the binary representation of their
file sizes.
Note: File sizes should be in integer format
Consider file size till YB (B, KB, MB, GB, TB, PB, EB, ZB, YB)
Input:
---The first line of the input contains a single integer T denoting the number of test cases.
The description of T test cases follows.
---First line of each test case consists of a single integer n denoting the size of the
array.
---The second line of each test case contains n space separated integers.
Output:
---For each test case, print a single line containing the sorted array.
Sample Input:
3
10
1 2 3 4 5 6 7 8 9 10
10
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
3
2048 1024 3072
Sample Output:
1 2 4 8 3 5 6 9 10 7
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
1024 2048 3072
Explanation:
Example case 1: In the array 1 2 3 4 5 6 7 8 9 10
file sizes are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
1's count in their binary representation are 1, 1, 2, 1, 2, 2, 3, 1, 2, 2
So sorted array is 1 2 4 8 3 5 6 9 10 7
"""
import math as m
from sys import stdin, stdout
def convert_to_file_size(arr):
"""
:param arr: Array input given by the user
:return: An integer array consisting of file sizes corresponding to arr
"""
arr1 = []
for num in arr:
if num == 0:
arr.append(0)
else:
i = int(m.floor(m.log(num, 1024)))
power = m.pow(1024, i)
size = int(num / power)
arr1.append(size)
return arr1
def count_of_binary_1s(arr):
"""
:param arr: Array returned by convert_to_file_size()
:return: An integer array consisting of count of no.of 1's in array's binary representation
"""
arr1 = []
for num in arr:
if num == 0:
arr1.append(0)
else:
binary = bin(int(num))
arr1.append(binary[2:len(binary)].count("1"))
return arr1
def main():
"""
:return: None
"""
for _ in range(int(stdin.readline())):
#size_name = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
arr_size = int(stdin.readline().strip())
array = [int(i) for i in stdin.readline().strip().split()]
arr = convert_to_file_size(array)
arr1 = count_of_binary_1s(arr)
sorted_arr = [x for i, x in sorted(zip(arr1, array))]
for i in range(arr_size):
stdout.write(str(sorted_arr[i])+" ")
stdout.write("\n")
if __name__ == "__main__":
main()
| true |
74e106cda0e7a685124ea86603fe61faf9c2fa7f | Rich43/rog | /albums/3/challenge145_easy/code.py | 1,818 | 4.34375 | 4 | '''
Your goal is to draw a tree given the base-width of the tree (the number of characters
on the bottom-most row of the triangle section). This "tree" must be drawn through
ASCII art-style graphics on standard console output. It will consist of a 1x3 trunk on
the bottom, and a triangle shape on the top. The tree must be centered, with the leaves
growing from a base of N-characters, up to a top-layer of 1 character. Each layer
reduces by 2 character, so the bottom might be 7, while shrinks to 5, 3, and 1 on top
layers. See example output.
Originally submitted by u/Onkel_Wackelflugel
Formal Inputs & Outputs
Input Description
You will be given one line of text on standard-console input: an integer and two
characters, all space-delimited. The integer, N, will range inclusively from
3 to 21 and always be odd. The next character will be your trunk character. The next
character will be your leaves character. Draw the trunk and leaves components with
these characters, respectively.
Output Description
Given the three input arguments, draw a centered-tree. It should follow this pattern:
(this is the smallest tree possible, with a base of 3)
*
***
###
Here's a much larger tree, of base 7:
*
***
*****
*******
###
Sample Inputs & Outputs
Sample Input 1
3 # *
Sample Output 1
*
***
###
Sample Input 2
13 = +
Sample Output 2
+
+++
+++++
+++++++
+++++++++
+++++++++++
+++++++++++++
===
'''
def tree(a, b, c, d):
x = 1
while x <= c:
print((a * x).center(c, ' '))
x += 2
print((b * d).center(c, ' '))
if __name__ == '__main__':
N = 3
leaf = '*'
trunk = '#'
trunk_width = 3
ans = tree(leaf, trunk, N, trunk_width)
N = 13
leaf = '+'
trunk = '='
ans = tree(leaf, trunk, N, trunk_width) | true |
c8305d2dcb7962c7f460d4e44851d4a24c495e6e | Rich43/rog | /albums/3/challenge160_easy/code.py | 2,037 | 4.25 | 4 | '''
(Easy): Trigonometric Triangle Trouble, pt. 1
A triangle on a flat plane is described by its angles and side lengths,
and you don't need to be given all of the angles and side lengths to work
out the rest. In this challenge, you'll be working with right-angled triangles only.
Here's a representation of how this challenge will describe a triangle.
Each side-length is a lower-case letter, and the angle opposite each side
is an upper-case letter. For the purposes of this challenge, the angle C
will always be the right-angle. Your challenge is, using basic trigonometry
and given an appropriate number of values for the angles or side lengths, to
find the rest of the values.
Formal Inputs and Outputs
Input Description
On the console, you will be given a number N. You will then be given N lines,
expressing some details of a triangle in the format below, where all angles are
in degrees; the input data will always give enough information and will describe
a valid triangle. Note that, depending on your language of choice, a conversion
from degrees to radians may be needed to use trigonometric functions such as
sin, cos and tan.
Output Description
You must print out all of the details of the triangle in the same format as above.
Sample Inputs & Outputs
Sample Input
3
a=3
b=4
C=90
Sample Output
a=3
b=4
c=5
A=36.87
B=53.13
C=90
Tips & Notes
There are 4 useful trigonometric identities you may find very useful.
Pythagoreas' Theorem, where h is the side length opposite the
right-angle and r and s are any 2 other sides.
3 Trigonometric Ratios
'''
import math
def sine(b, c):
''' Compute the sine of the
right-angled triangle'''
return (round(math.degrees(math.acos(b/c)), 2))
def cosine():
''' Cosine can be found to be
180 - (sine + 90)'''
return round(180 - (sine(b, c) + 90), 2)
if __name__ == '__main__':
a = 3
b = 4
c = 5
A = sine(b, c)
B = cosine()
C = 90
print('a={0}\nb={1}\nc={2}\nA={3}\nB={4}\nC={5}'.format(a, b, c, A, B, C)) | true |
f2a5494dea131dd5bacd09931c98aa04a4fb6e43 | Rich43/rog | /albums/3/challenge87_easy/code.py | 1,235 | 4.15625 | 4 | '''
Write a function that calculates the intersection of two rectangles,
returning either a new rectangle or some kind of null value.
You're free to represent these rectangles in any way you want:
tuples of numbers, class objects, new datatypes, anything goes. For
this challenge, you'll probably want to represent your rectangles
as the x and y values of the top-left and bottom-right points.
(Rect(3, 3, 10, 10) would be a rectangle from (3, 3) (top-left) to
(10, 10) (bottom-right).)
As an example, rectIntersection(Rect(3, 3, 10 10), Rect(6, 6, 12, 12))
would return Rect(6, 6, 10, 10), while rectIntersection
(Rect(4, 4, 5, 5), Rect(6, 6, 10 10)) would return null.
'''
'''
Based on:
A.X1 < B.X2: true
A.X2 > B.X1: false
A.Y1 < B.Y2: true
A.Y2 > B.Y1: true
Intersect: false'''
def intersect(rect1, rect2):
if (rect1[0] < rect2[2]) and rect1[2] > rect2[0] and \
rect1[1] < rect2[3] and rect1[3] > rect2[1]:
rectangle = (rect2[0], rect2[1], rect1[2], rect1[3])
return 'rectangle ' + str(rectangle)
else:
return 'no intersect!'
if __name__ == '__main__':
rect_one = (3, 3, 10, 10)
rect_two = (6, 6, 12, 12)
ans = intersect(rect_one, rect_two)
print(ans) | true |
401ec919e87f936bd9e31a9d4e413da50bddb44e | Rich43/rog | /albums/3/challenge23_easy/code.py | 524 | 4.125 | 4 | ''' Input: a list
Output: Return the two halves as different lists.
If the input list has an odd number, the middle item can go to any of the list.
Your task is to write the function that splits a list in two halves.
'''
lst = [1, 2, 3, 4, 5]
half_lst = len(lst) // 2
first_lst = []
second_lst = []
for x in range(0, half_lst):
candidate = lst[x]
first_lst.append(candidate)
for y in range(0, len(lst)):
if lst[y] not in first_lst:
second_lst.append(lst[y])
print(first_lst)
print(second_lst) | true |
d758ed97ea2aea49f6e70a9253952f6ba271e398 | Rich43/rog | /albums/3/challenge168_easy/code.py | 2,067 | 4.46875 | 4 | '''
So my originally planned [Hard] has issues. So it is not ready for posting.
I don't have another [Hard] so we are gonna do a nice [Easy] one for Friday
for all of us to enjoy.
Description:
We know arrays. We index into them to get a value. What if we could apply
this to a string? But the index finds a "word". Imagine being able to parse
the words in a string by giving an index. This can be useful for many reasons.
Example:
Say you have the String "The lazy cat slept in the sunlight."
If you asked for the Word at index 3 you would get "cat" back. If you asked
for the Word at index 0 you get back an empty string "". Why an empty
string at 0? Because we will not use a 0 index but our index begins at 1. If
you ask for word at index 8 you will get back an empty string as the string
only has 7 words. Any negative index makes no sense and return an empty string "".
Rules to parse:
Words is defined as [a-zA-Z0-9]+ so at least one of these and many more
in a row defines a word.
Any other character is just a buffer between words."
Index can be any integer (this oddly enough includes negative value).
If the index into the string does not make sense because the word does not
exist then return an empty string.
Challenge Input:
Your string: "...You...!!!@!3124131212 Hello have this is a --- string Solved !
!...? to test @\n\n\n#!#@#@%$**#$@ Congratz this!!!!!!!!!!!!!!!!one ---Problem\n\n"
Find the words at these indexes and display them with a " " between them:
12 -1 1 -100 4 1000 9 -1000 16 13 17 15
'''
import re
the_string = "...You...!!!@!3124131212 Hello have this is a --- string Solved ! \
!...? to test @\n\n\n#!#@#@%$**#$@ Congratz this!!!!!!!!!!!!!!!!one ---Problem\n\n"
the_string = re.findall('\w+', the_string)
indexes = ' 12 -1 1 -100 4 1000 9 -1000 16 13 17 15'
indexes = indexes.split()
output = ''
for num in indexes:
num = int(num) - 1
if num <= -1:
continue
try:
output += the_string[num] + ' '
except IndexError:
continue
print(the_string)
print(output) | true |
12f29461a004ea1e8264153d5cfb473973ee153f | Rich43/rog | /albums/4/problem18.py/code.py | 418 | 4.15625 | 4 | def panagram(strng):
'''(str) -> bool
return whether the string is a panagram
'''
sett = set()
strng = strng.lower()
for letter in strng:
if letter.isalpha():
sett.add(letter)
return len(sett) == 26
strng = 'The quick brown fox jumps over the lazy dog'
ans = panagram(strng)
print(ans) | true |
16652e2897466142fd0b285578018c150e0a5a5e | Rich43/rog | /albums/3/challenge126_easy/code.py | 2,287 | 4.15625 | 4 | '''
Imagine you are an engineer working on some legacy code that has some odd constraints:
you're being asked to implement a new function, which basically merges and sorts one
list of integers into another list of integers, where you cannot allocate any other
structures apart from simple temporary variables (such as an index or counter variable).
You will be given two lists, list A and B, where the elements are positive integers
from 1 to 2147483647; the integer '0' is reserved as "buffer space". List A will not
be pre-sorted, though list B will be pre-sorted and will start with a series of '0'
values. These '0' values are simply reserved space in list B which is the same number
of elements that list A has. You cannot modify list A in any way, though list B is
fair game. Your goal is to return a merged and sorted list of elements of list A into
list B, where you cannot allocate any extra space other than simple / trivial local
variables for your function.
Author: nint22
Formal Inputs & Outputs
Input Description
You will be given two lists, list A and B, of integers from 1 to 2147483647. List A
will be unsorted, while list B will be sorted. List B has extra elements in the start
of the list that are all '0' value: this is buffered space for you to work with when
merging and sorting list A into B. These two lists will be space-delimited and on
separate lines.
Output Description
Simply print the contents of list B, after it has had the contents of A merged &
sorted within it.
Sample Inputs & Outputs
Sample Input
692 1 32
0 0 0 14 15 123 2431
Sample Output
1 14 15 32 123 692 2431
Note
Please note that the real challenge here is respecting the premise of the challenge:
you must implement your sort / merge function inline into list B! If you do not
understand the premise, please do ask questions and we will gladly answer. Good luck,
and have fun!
'''
l1 = [692, 1, 32] # unsorted
l2 = [0, 0, 0, 14, 15, 123, 2431] # sorted
def merge(l1, l2):
i = 0
while len(l1) > 0:
i = 0
temp = l1.pop(0)
trim = l2.pop(0)
for item in l2:
while item < temp:
i += 1
break
l2.insert(i, temp)
return l2
if __name__ == '__main__':
ans = merge(l1, l2)
print(ans) | true |
5bcf6fd1c5bb4eb598aca0a9c70d0ee65d883a7a | Rich43/rog | /albums/3/challenge171_easy/code.py | 1,983 | 4.125 | 4 | '''
Description:
Today we will be making some simple 8x8 bitmap pictures. You will be given 8 hex values
that can be 0-255 in decimal value (so 1 byte). Each value represents a row. So 8 rows
of 8 bits so a 8x8 bitmap picture.
Input:
8 Hex values.
example:
18 3C 7E 7E 18 18 18 18
Output:
A 8x8 picture that represents the values you read in.
For example say you got the hex value FF. This is 1111 1111 . "1" means the bitmap at that
location is on and print something. "0" means nothing is printed so put a space. 1111 1111
would output this row:
xxxxxxxx
if the next hex value is 81 it would be 1000 0001 in binary and so the 2nd row would output
(with the first row)
xxxxxxxx
x x
Example output based on example input:
xx
xxxx
xxxxxx
xxxxxx
xx
xx
xx
xx
Challenge input:
Here are 4 pictures to process and display:
FF 81 BD A5 A5 BD 81 FF
AA 55 AA 55 AA 55 AA 55
3E 7F FC F8 F8 FC 7F 3E
93 93 93 F3 F3 93 93 93
Output Character:
I used "x" but feel free to use any ASCII value you want. Heck if you want to display
it using graphics, feel free to be creative here.
'''
import re
def hex_to_str(base16):
scale = 16
num_of_bits = 8
my_hexdata = base16
strng = ''
bin_out = bin(int(my_hexdata, scale))[2:].zfill(num_of_bits)
for digit in bin_out:
if digit == '1':
strng += '='
else:
strng += ' '
return strng
if __name__ == '__main__':
base16 = '18 3C 7E 7E 18 18 18 18'
base16 = re.findall('\d[A-Z]|[A-Z]\d|\d+|[A-Z]+', base16)
for num in base16:
ans = hex_to_str(num)
print(ans)
print()
hex_matrix = '''FF 81 BD A5 A5 BD 81 FF
AA 55 AA 55 AA 55 AA 55
3E 7F FC F8 F8 FC 7F 3E
93 93 93 F3 F3 93 93 93'''
hex_matrix = hex_matrix.splitlines()
for line in hex_matrix:
base16 = re.findall('\d[A-Z]|[A-Z]\d|\d+|[A-Z]+', line)
for num in base16:
ans = hex_to_str(num)
print(ans) | true |
469bcb352f966ce525cc49271d3c707085ce1e17 | Rich43/rog | /albums/3/challenge10_easy/code.py | 866 | 4.53125 | 5 | '' The exercise today asks you to validate a telephone number, as if written on an input form. Telephone numbers
can be written as ten digits, or with dashes, spaces, or dots between the three segments, or with the area code
parenthesized; both the area code and any white space between segments are optional.
Thus, all of the following are valid telephone numbers: 1234567890, 123-456-7890, 123.456.7890, (123)456-7890, (123)
456-7890 (note the white space following the area code), and 456-7890.
The following are not valid telephone numbers: 123-45-6789, 123:4567890, and 123/456-7890.
'''
# Note: no '/' or ':' or nine digits.
#call = input('Enter telephone number: ')
call = '345 6 6789'
lst = []
for x in call:
if str.isnumeric(x):
lst.append(x)
if '/' in call or ':' in call or len(lst) < 10:
print('False')
else:
print('Number OK!') | true |
458fcbc5b06298bd4fc084465f91f1a86bae2e17 | Rich43/rog | /albums/3/challenge149_easy/code.py | 1,838 | 4.25 | 4 | '''
Disemvoweling means removing the vowels from text. (For this challenge, the letters a, e, i, o, and u
are considered vowels, and the letter y is not.) The idea is to make text difficult but not
impossible to read, for when somebody posts something so idiotic you want people who are reading it
to get extra frustrated.
To make things even harder to read, we'll remove spaces too. For example, this string:
two drums and a cymbal fall off a cliff
can be disemvoweled to get:
twdrmsndcymblfllffclff
We also want to keep the vowels we removed around (in their original order), which in this case is:
ouaaaaoai
Formal Inputs & Outputs
Input description
A string consisting of a series of words to disemvowel. It will be all lowercase (letters a-z)
and without punctuation. The only special character you need to handle is spaces.
Output description
Two strings, one of the disemvoweled text (spaces removed), and one of all the removed vowels.
Sample Inputs & Outputs
Sample Input 1
all those who believe in psychokinesis raise my hand
Sample Output 1
llthswhblvnpsychknssrsmyhnd
aoeoeieeioieiaiea
Sample Input 2
did you hear about the excellent farmer who was outstanding in his field
Sample Output 2
ddyhrbtthxcllntfrmrwhwststndngnhsfld
ioueaaoueeeeaeoaouaiiiie
Notes
'''
vowels = 'aeiou'
consononts = ''
vowel_output = ''
samples = '''all those who believe in psychokinesis raise my hand
did you hear about the excellent farmer who was outstanding in his field'''
for line in samples.splitlines():
line = line.strip('\n')
line = line.replace(' ', '')
vowel_string = ''
for x in range(0, len(line)):
if line[x] in vowels:
vowel_output += line[x]
else:
consononts += line[x]
print(consononts)
print(vowel_output)
consononts = ''
vowel_output = '' | true |
d702030522318f0d1aa5c9c134e670bf2dd23db5 | Rich43/rog | /albums/3/challenge41_easy/code.py | 967 | 4.15625 | 4 | ''' Write a program that will accept a sentence as input and then output that sentence surrounded by some type of an ASCII decoratoin banner.
Sample run:
Enter a sentence: So long and thanks for all the fish
Output
*****************************************
* *
* So long and thanks for all the fish *
* *
*****************************************
Bonus: If the sentence is too long, move words to the next line.
'''
def outer():
global leng
return ('x' * (leng +6))
def inner():
global leng
return ('x' + (' ' * (leng + 4)) + 'x')
def string():
global quote
return ('x' + ' ' * 2 + quote + ' ' * 2 + 'x')
if __name__ == '__main__':
#quote = input("Let's have a quote...: ")
quote = 'I am a python'
leng = len(quote)
out = outer()
inn = inner()
txt = string()
print(out + "\n" + inn + "\n" + txt + "\n" + inn + "\n" + out) | true |
dc507cd0c38636a157f79882827f66505af93ee2 | Rich43/rog | /albums/3/challenge193_easy/code.py | 1,657 | 4.4375 | 4 | ''' An international shipping company is trying to figure out
how to manufacture various types of containers. Given a volume
they want to figure out the dimensions of various shapes that
would all hold the same volume.
Input:
A volume in cubic meters.
Output:
Dimensions of containers of various types that would hold the volume.
The following containers are possible.
Cube
Ball (Sphere)
Cylinder
Cone
Example Input:
27
Example Output:
Cube: 3.00m width, 3.00m, high, 3.00m tall
Cylinder: 3.00m tall, Diameter of 3.38m
Sphere: 1.86m Radius
Cone: 9.00m tall, 1.69m Radius
Some Inputs to test.
27, 42, 1000, 2197
'''
import math
def cube(vol):
r = vol / 3
return r
def sphere(vol):
r = ((3 * vol) / (4 * math.pi)) ** (1 / 3)
r = round(r, 2)
return r
def cylinder(vol):
r = (vol / (math.pi * h)) ** 0.5
r = round(r, 2)
return r
def cone(vol):
r = (3 * (vol / (math.pi * h))) ** 0.5
r = round(r, 2)
return r
def display(volume, h):
print('A cube of {0} metres cubed will have sides of {1} metres'.format(volume, h))
print('A sphere of volume {0} cubic metres will have a radius of {1} metres.'.format(volume, sphere(volume)))
print('A cylinder of {0} cubic metres with a height of {1} will have a radius of {2} metres.'.format(volume, h, cylinder(volume)))
print('A cone of {0} cubic metres and height of {1} metres will have a radius of {2} metres'.format(volume, h, cone(volume)))
if __name__ == '__main__':
lst = [27, 42, 1000, 2197]
for num in lst:
h = round((num / 9), 2)
ans = display(num, h)
print(ans)
print()
# 193 | true |
93ea951e7c2eb9c49eab5ecaefba68570832a79a | Rich43/rog | /albums/3/challenge191_easy/code.py | 1,995 | 4.25 | 4 | '''
You've recently taken an internship at an up and coming lingustic and natural language centre.
Unfortunately, as with real life, the professors have allocated you the mundane task of
counting every single word in a book and finding out how many occurences of each word there
are.
To them, this task would take hours but they are unaware of your programming background (They
really didn't assess the candidates much). Impress them with that word count by the end of the
day and you're surely in for more smooth sailing.
Description
Given a text file, count how many occurences of each word are present in that text file. To
make it more interesting we'll be analyzing the free books offered by Project Gutenberg
The book I'm giving to you in this challenge is an illustrated monthly on birds. You're free
to choose other books if you wish.
Inputs and Outputs
Input
Pass your book through for processing
Output
Output should consist of a key-value pair of the word and its word count.
Example
{'the' : 56,
'example' : 16,
'blue-tit' : 4,
'wings' : 75}
Clarifications
For the sake of ease, you don't have to begin the word count when the book starts, you can just count
all the words in that text file (including the boilerplate legal stuff put in by Gutenberg).
Bonus
As a bonus, only extract the book's contents and nothing else.
'''
import re
word_dict = {}
with open('gutenburg.txt', 'r') as f:
for line in f:
line = re.findall('[a-zA-Z]+', line)
for word in line:
word_dict[word] = word_dict.setdefault(word, 0) + 1
print(word_dict)
#-- Bonus --------------------------------------------
text_string = ''
word_dict = {}
with open('gutenburg.txt') as f:
for line in f:
line = line.rstrip()
text_string += line + ' '
txt = re.findall('Title:.*Patagonia.', text_string)
txt = txt[0]
txt = re.findall('[a-zA-Z]+', txt)
for word in txt:
word_dict[word] = word_dict.setdefault(word, 0) + 1
print(word_dict) | true |
83e038b449f0db56788edf9ac5a8d41898141dd9 | Rich43/rog | /albums/3/challenge199_easy/code.py | 2,042 | 4.15625 | 4 | '''
You work for a bank, which has recently purchased an ingenious machine
to assist in reading letters and faxes sent in by branch offices.
The machine scans the paper documents, and produces a file with a
number of entries which each look like this:
_ _ _ _ _ _ _
| _| _||_||_ |_ ||_||_|
||_ _| | _||_| ||_| _|
Each entry is 4 lines long, and each line has 27 characters. The first
3 lines of each entry contain an account number written using pipes and
underscores, and the fourth line is blank. Each account number should
have 9 digits, all of which should be in the range 0-9.
Right now you're working in the print shop and you have to take account
numbers and produce those paper documents.
Input
You'll be given a series of numbers and you have to parse them into the
previously mentioned banner format. This input...
000000000
111111111
490067715
Output
...would reveal an output that looks like this
_ _ _ _ _ _ _ _ _
| || || || || || || || || |
|_||_||_||_||_||_||_||_||_|
| | | | | | | | |
| | | | | | | | |
_ _ _ _ _ _ _
|_||_|| || ||_ | | ||_
'''
import itertools
one = '''
|
|
'''
two = ''' _
_|
|_
'''
three = '''_
_!
_!
'''
four = '''
!_!
!
'''
five = ''' _
!_
_!
'''
six = '''_
!_
!_!
'''
seven = '''_
!
!
'''
eight = '''_
!_!
!_!
'''
nine = ''' _
!_!
_!
'''
zero = ''' _
! !
!_!
'''
strings = list(itertools.repeat(zero, 9))
string2 = list(itertools.repeat(one, 9))
string3 = (four, nine, zero, zero, six, seven, seven, one, five)
print(*[''.join(x) for x in zip(*[[x.ljust(len(max(s.split('\n'), key=len)))
for x in s.split('\n')] for s in strings])], sep='\n')
print(*[''.join(x) for x in zip(*[[x.ljust(len(max(s.split('\n'), key=len)))
for x in s.split('\n')] for s in string2])], sep='\n')
print(*[''.join(x) for x in zip(*[[x.ljust(len(max(s.split('\n'), key=len)))
for x in s.split('\n')] for s in string3])], sep='\n') | true |
7634f458818e574f22aee33c9c64e0263bc51312 | Rich43/rog | /albums/3/challenge194_easy/code.py | 2,678 | 4.25 | 4 | '''
Most programming languages understand the concept of escaping strings. For example,
if you wanted to put a double-quote " into a string that is delimited by double
quotes, you can't just do this:
"this string contains " a quote."
That would end the string after the word contains, causing a syntax error. To remedy
this, you can prefix the quote with a backslash \ to escape the character.
"this string really does \" contain a quote."
However, what if you wanted to type a backslash instead? For example:
"the end of this string contains a backslash. \"
The parser would think the string never ends, as that last quote is escaped! The
obvious fix is to also escape the back-slashes, like so.
"lorem ipsum dolor sit amet \\\\"
The same goes for putting newlines in strings. To make a string that spans two
lines, you cannot put a line break in the string literal:
"this string...
...spans two lines!"
The parser would reach the end of the first line and panic! This is fixed by
replacing the newline with a special escape code, such as \n:
"a new line \n hath begun."
Your task is, given an escaped string, un-escape it to produce what the parser
would understand.
Input Description
You will accept a string literal, surrounded by quotes, like the following:
"A random\nstring\\\""
If the string is valid, un-escape it. If it's not (like if the string doesn't
end), throw an error!
Output Description
Expand it into its true form, for example:
A random
string\"
Sample Inputs and Outputs
1. Sample Input
"hello,\nworld!"
Sample Output
hello,
world!
2. Sample Input
"\"\\\""
Sample Output
"\"
3. Sample Input
"an invalid\nstring\"
Sample Output
Invalid string! (Doesn't end)
4. Sample Input
"another invalid string \q"
Sample Output
Invalid string! (Bad escape code, \q)
'''
import re
import codecs
escape_chars = ['\\newline',
'\\',
"\\'",
'\\"',
'\\a',
'\\b',
'\\f',
'\\n',
'\r',
'\t',
'\\v',
'\\ooo',
'\\uxxxxx',
'\\Uxxxxx']
file = '194.txt'
with open(file, 'r') as f:
for line in f:
line = line.strip('\n')
end_of = re.findall('\\\$', line)
extract = re.findall(r'\\\w|\\', line)
temp = extract
first = temp[0]
if len(end_of) > 0:
print('Invalid string (Doesn\'t end)')
elif first in escape_chars:
print(codecs.escape_decode(bytes(line, "utf-8"))[0].decode("utf-8"))
else:
print('Invalid string' + ' (bad escape code ' + first + ')') | true |
b22a560b7c2cdfae02f5a0e47cfc9a9714f5986f | Rich43/rog | /albums/3/challenge33_easy/code.py | 885 | 4.125 | 4 | ''' This would be a good study tool too. I made one myself and I thought it would also be a good challenge.
Write a program that prints a string from a list at random, expects input, checks for a right or wrong answer,
and keeps doing it until the user types "exit". If given the right answer for the string printed,
it will print another and continue on. If the answer is wrong, the correct answer is printed and
the program continues.
Bonus: Instead of defining the values in the program, the questions/answers is in a file,
formatted for easy parsing.
Example file:s
Translate: hola,hello
'''
dikt = {'4 times 8 = ': 32, '6 divided by 3 = ': 2, 'Square root of nine? ': 3}
for key in dikt:
question = key
ans = input(question)
ans1 = str(dikt[question])
if ans == ans1:
print('Correct')
else:
print('Wrong! Answer is: ', dikt[question]) | true |
84e5a596be210ab77c029504c094f3328162aba2 | Rich43/rog | /albums/3/challenge34_easy/code.py | 373 | 4.25 | 4 | ''' A very basic challenge:
In this challenge, the
input is are : 3 numbers as arguments
output: the sum of the squares of the two larger numbers.
Your task is to write the indicated challenge.
'''
#nums = input('Input three numbers in the form 1/2/3 : ')
nums = '5/8/4'
nums = sorted(nums.split('/'))
ans = (float(nums[1]) ** 2) + (float(nums[2]) ** 2)
print(ans) | true |
3fda92e3ae36967245d8366a30d54987ef9f3694 | kaczifant/Elements-of-Programming-Interviews-in-Python-Exercises | /string_integer_interconversion.py | 1,767 | 4.25 | 4 | # 6.1 INTERCONVERT STRINGS AND INTEGERS
# Implement an integer to string conversion function, and a string to integer conversison function.
# Your code should handle negative integers. You cannot use library functions like int in Python.
from test_framework import generic_test
from test_framework.test_failure import TestFailure
def int_to_string(x):
minus = False
chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
string = ''
if x < 0:
minus = True
x = x * -1
if x == 0:
return '0'
else:
while x != 0:
mod_10 = x % 10
x = (x - mod_10)//10
string += chars[mod_10]
if minus:
return '-' + string[::-1]
return string[::-1]
def string_to_int(s):
num = 0
num_dict = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}
if '-' in s:
tens = len(s) - 2
for char in s:
if char in num_dict:
num += num_dict[char] * (10 ** tens)
tens -= 1
return num * -1
else:
tens = len(s) - 1
for char in s:
if char in num_dict:
num += num_dict[char] * (10 ** tens)
tens -= 1
return num
def wrapper(x, s):
if int_to_string(x) != s:
raise TestFailure("Int to string conversion failed")
if string_to_int(s) != x:
raise TestFailure("String to int conversion failed")
if __name__ == '__main__':
exit(
generic_test.generic_test_main("string_integer_interconversion.py",
'string_integer_interconversion.tsv',
wrapper))
| true |
57f902e278e495aa66de4b3cc1408aaebfbda91e | cory-schneider/random-article-generator | /writer.py | 2,873 | 4.21875 | 4 | #!/usr/bin/python3
#Pulls from a word list, creates "paragraphs" of random length, occasionally entering a blank line.
#User Inputs:
# word list file path
# test file, exit if bad path
# print word count
# file name for output
# number of paragraphs
# min words per paragraph (prompt user not to use zero, random blank functionality is separate)
# max words per paragraphs
import random
#User input for the input file:
def q1():
x = input("Enter word list full file path/name: ")
return x
input_file = q1()
#Check for correct file path. Exit if no such file
try:
wordlist = open(input_file, "r")
except IOError:
print("An error was found. Either path incorrect or file doesn't exist!"
+ '\n' + "Exiting program!")
exit()
source_count = len(open(input_file).readlines())
print("There are {} words in '{}'".format(source_count,input_file))
#Implement output file check. If exists, overwrite?
#User input for the output file:
def q2():
x = input("Enter desired output path/name: ")
return x
output_query = q2()
output = open(output_query, "a+")
#User input for number of paragraphs per article:
def q3():
x = input("How many paragraphs shall we print? ")
return x
try:
art_length = int(q3())
except:
print("Integers only!")
exit()
#User input for min words per paragraph:
def q4():
x = input("Minimum number of words per paragraph? ")
return x
try:
min_w = int(q4())
except:
print("Integers only!")
exit()
#User input for max words per paragraph:
def q5():
x = input("Maximum number of words per paragraph? ")
return x
try:
max_w = int(q5())
except:
print("Integers only!")
exit()
answers = (
'\n' + "Wordlist File: {}" + '\n' + "Words in list: {}" + '\n' + "Output File: {}" + '\n'
+ "Paragraph count: {}" + '\n' + "Min words/paragraph: {}" + '\n'
+ "Max words/paragraph: {}" + '\n' + '------------------------------------------' + '\n'
)
output.write(answers.format(input_file, source_count, output_query, art_length, min_w, max_w))
#Opens the input file, strips out the entries into a list, closes input file.
textBlock = wordlist.readlines()
master_list = []
for line in textBlock:
master_list.append(line.strip())
wordlist.close()
#Creates num_list which will be used to pull from the master_list
def para_list():
w_para = random.randint(min_w, max_w)
x = []
for _ in range(w_para):
x.append(random.randint(1,source_count))
return x
def para_mesh():
num_list = para_list()
paragraph = []
for i in num_list:
paragraph.append(master_list[i])
#alphabetize, otherwise manipulate the list:
# paragraph.sort()
paragraph = ' '.join(paragraph).lower()
print(paragraph + '\n')
output.write(paragraph + '\n')
for _ in range(art_length):
para_mesh()
output.close()
| true |
dc282841394adaf3cd83d97bf55e1e7bedfbab15 | saarco777/Centos-REpo | /User age - Pub.py | 672 | 4.21875 | 4 | # define your age
name = input('Hi there, whats your name?') # user defines their name
age = input('How old are you?') # user gets asked whats their age
if int(age) > 20:
print('Hi', name, 'Welcome in, Please have a Drink!') # if age is bigger than 20, user gets inside and HAS a drink
elif int(age) < 20 and int(age) > 18:
print('Welcome in', name, 'But your age is below 20, Sorry but you CANNOT have a drink') # if age is bigger than 18 but lower than 20, user can get inside but cannot have a drinl
elif int(age) < 18:
print('Sorry', name, 'Your too young. You cannot come inside') # if age is below 20, user is too young and cannot come inside | true |
dacafce3f5455a01d105f0f3e017dc17d5f3efde | dark-glich/data-types | /Tuple.py | 874 | 4.59375 | 5 | # tuple : immutable - ordered
tuple_1 = (1, 2, 3, 4, 2, 5, 2, )
print(f"original name : {tuple_1}")
# tuple[index] is used to access a single item from the tuple.
print(f"tuple[2] : {tuple_1[2]}")
# tuple.index[value] is used to get the index of a value.
x = tuple_1.index(3)
print(f"tuple.index : {x}")
# tuple[:index] is used to get the value to the certain index.
print(f"tuple[:2] : {tuple_1[:2]}")
# tuple[index :] is used to get the value from the certain index.
print(f"tuple[2:] : {tuple_1[2 :]}")
# tuple[::num] is used to display the tuple with the jump of num.
print(f"tuple[::2] : {tuple_1[::2]}")
# tuple.count(value) is used to get no. of repetition of a certain value.
print(f"tuple.count(2) : {tuple_1.count(2)}")
# converting tuple to list and set.
print(f"tuple to list : {list(tuple_1)}")
print(f"tuple to set : {set(tuple_1)}") | true |
cecd850e5ac271d9cf8f27faf059188ecf53f8c6 | xiaojias/python | /development/script.py | 1,383 | 4.28125 | 4 | my_name = "Codecademy"
print("Hello and welcome " + my_name + " !")
# Operators
message = "First Name"
message += ", Sure Name"
print(message)
# Comment on a single line
user = "Jdoe" # Comment after code
# Arithmetic operators
result = 10 + 20
result = 40 - 30
result = 20 * 2
result = 16 / 4
result = 25 % 2
result = 5 ** 3
# Plus-equal operator
counter = 0
counter += 10
# This is equalent to
counter = 0
counter = counter + 10
# This operator will also perform string contactenation
message = "Part 1 of message"
message += "Part 2 of message"
# There are all valid variable and assignment
user_name = "codey"
user_id = 100
verified = False
# A variable can be changed after assignment
points = 100
points = 120
# Modulo operation
zero = 8 % 4
nozero = 12 % 5
# Exact integer number
chairs = 4
tables = 1
broken_chairs = -2
sofas = 0
# Non-integer numbers
lights = 2.5
left_overs = 0.0
# String concatenation
first = "Hello"
second = "World"
result = first + second
long_reslut = first + second + "!"
# Floating point number
pi = 3.1415926
meal_cost = 12.98
tip_percent = 0.20
# Print function
print("Hello World !")
print(100)
pi = 3.1415926
print(pi)
# Idendity
a = "Hello"
b = a
id(a)
# An interger
id(a) == id(b)
# True
b = 'Hell' + 'o'
id(a) == id(b)
# True
# Type
type(a)
# Type conversion
x = '145'
y = int(x)
type(x)
# Str
type(y)
# Int
| true |
b5694e5bb2c3d591d886a5f21f63f5ef0f1dcadc | gururajh/python-standard-programs | /Fibonacci.py | 1,995 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 29 14:27:50 2022
@author: Gururaja Hegde V'
"""
"""Write a program to generate Fibonnaci numbers.
The Fibonnaci seqence is a sequence of numbers where the next number in the sequence
is the sum of the previous two numbers in the sequence.
The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)"""
def gen_fib1():
count=int(input("Gen_fib_1- How many fibonacci numbers would you like to generate?:"))
i=1
if count==0:
fib=[]
elif count==1:
fib=[1]
elif count==2:
fib=[1,1]
elif count>2:
fib=[1,1]
while i<(count-1):
fib.append(fib[i]+fib[i-1])
i+=1
return fib
def gen_fib2():
num=int(input("Gen_fib_2- How many fibonacci numbers would you like to generate:"))
i=1
if num==0:
fib=[]
elif num==1:
fib=[1]
elif num==2:
fib=[1,1]
elif num>2:
fib=[1,1]
while i<(num-1):
fib.append(fib[i]+fib[i-1])
i+=1
return fib
def gen_fib3():
n =int(input("Gen_fib_3- How many fibonacci numbers would you like to generate:"))
f=[]
f.append(1)
f.append(1)
for i in range(2,n):
f.append(f[i-1]+f[i-2])
print(f)
""" Type 4 """
# 1. Take the number of terms from the user and store it in a variable.
# 2. Pass the number as an argument to a recursive function named fibonacci.
# 3. Define the base condition as the number to be lesser than or equal to 1.
# 4. Otherwise call the function recursively with the argument as the number minus
# 1 added to the function called recursively with the argument as the number minus 2.
# 5. Use a for loop and print the returned value which is the fibonacci series.
# 6. Exit.
def gen_fib4(n):
if(n <= 1):
return n
else:
return(gen_fib4(n-1) + gen_fib4(n-2))
n = int(input("Enter number of terms for fibon:"))
print("Fibonacci sequence:")
for i in range(n):
print(gen_fib4(i))
print(gen_fib1())
print(gen_fib2())
print(gen_fib3())
| true |
1382f8c14d706cf5c5a089821a0e0211b5d5c8f4 | AmGhGitHub/SAGA_Python | /py_lesson8.py | 1,164 | 4.40625 | 4 | # Arithmetic operators
x = 10.0
y = 3.1415
exponent = 3
print("sum:", x + y) # addition
print("subtraction:", x - y) # addition
print("multiplication:", x * y) # multiplication
print("float division:", x / y) # float division
print("floor division:", int(x) // int(y)) # floor division
print("modulus:", int(x) % int(y)) # modulus: the remainder when first operand is divided by the second
print("exponent:", x ** exponent) # exponent
# the result of a mathematical expression can be assigned to a new variable
z = x + y
# Use mathematical operation to modify the value of a variable in place
print("before modify: x=", x)
x = x / 2
print("after modify: x=", x)
# each arithmetic operator has an augmented operator equivalent
#y = y + 2
y += 2 # this is equivalent to y = y + 2
y **= 2
print("y=", y)
sw = 0.2
so = 0.45
# un-equality
print(sw != 0.2)
# less than
print(sw < so)
# returns True if both statements are true
print(sw > 0.1 and so < 0.3)
# returns True if one of the statements is true
print(sw > 0.15 or so > 0.60)
# negate the result, returns False if the result is true
print(not sw <= 0.1)
| true |
9ec395003a967ab68c644c01cd3a792fc27a0d67 | AmGhGitHub/SAGA_Python | /py_lesson17.py | 1,657 | 4.1875 | 4 | class Well:
"""
Well class for modelling vertical well
performance
"""
def __init__(self, radius, length):
"""
Initialize well attributes
:param radius (float): radius of the well
in ft
:param length (float): productive length
of the well in ft
"""
self.radius = radius
self.length = length
def get_wellbore_volume(self, correction_factor=1.0):
"""
:param correction_factor (float): a correction-factor
to be applied to volume
:return (float): storage volume of the
well is returned
"""
PI = 3.1415 # by convention, we use all CAPITAL LETTERS name for constant value in Python
well_volume = PI * self.radius ** 2.0 * self.length * correction_factor
return well_volume
# create an instance of the class or create an well object
oil_well = Well(0.30, 551) # please note that init() method requires 3 parameters, but we only provide two parameters
water_well = Well(0.25, 1001.4)
## objects are working independently from each other
print(oil_well.radius > water_well.radius) # you see the application of "dot" notation with objects
print(f"Internal volume:{oil_well.get_wellbore_volume(0.9):.2f} ft3")
## use the object method
oil_well_internal_vol = oil_well.get_wellbore_volume(0.95) # again, we don't need to pass any value for the self parameter
water_well_internal_vol = water_well.get_wellbore_volume(0.81)
print(f"Oil-well internal volume:{oil_well_internal_vol}")
print(f"Water-well internal volume:{water_well_internal_vol:.2f}")
| true |
6e21a23abb976fbfd248c0e107ad86250bed9c12 | raberin/Sorting | /src/recursive_sorting/recursive_sorting.py | 2,749 | 4.25 | 4 | # TO-DO: complete the helpe function below to merge 2 sorted arrays
def merge(arrA, arrB):
merged_arr = []
arrA_index = 0
arrB_index = 0
# Until the merged_arr is as big as both arrays combined
while len(merged_arr) < len(arrA) + len(arrB):
print(
f"arrA_index = {arrA_index}, arrB_index = {arrB_index}\n {merged_arr}")
# If arrB is empty add arrA elements and vice versa
if len(arrB) <= arrB_index:
merged_arr.append(arrA[arrA_index])
arrA_index += 1
elif len(arrA) <= arrA_index:
merged_arr.append(arrB[arrB_index])
arrB_index += 1
# Compare which element is smaller and push to merged
elif arrA[arrA_index] <= arrB[arrB_index]:
merged_arr.append(arrA[arrA_index])
arrA_index += 1
else:
merged_arr.append(arrB[arrB_index])
arrB_index += 1
return merged_arr
# arr1 = [1, 3, 5, 6, 7]
# arr2 = [2, 4, 8, 9]
# print(merge(arr1, arr2))
# # TO-DO: implement the Merge Sort function below USING RECURSION
def merge_sort(arr):
# Base Case
if len(arr) < 2:
return arr
# Make midpt variable
middlePoint = len(arr) // 2
# Recurse the left and right sides of the array
sortLeft = merge_sort(arr[0:middlePoint])
sortRight = merge_sort(arr[middlePoint:len(arr)])
# Merge the arrays
return merge(sortLeft, sortRight)
arr1 = [1, 3, 5, 6, 7, 2, 4, 8, 9]
print(merge_sort(arr1))
def quick_sort(arr):
# Base case
if len(arr) == 0:
return arr
# Set pivot point last number in arr
pivot = arr[len(arr) - 1]
# Create left and right arrays
left_arr = []
right_arr = []
# Loop until right before last element
for i in range(len(arr) - 1):
# if pivot < arr[i] push to rightArr
if pivot < arr[i]:
right_arr.append(arr[i])
# if pivot > arr[i] push to leftArr
else:
left_arr.append(arr[i])
# recurse left + right
left_arr_sorted = quick_sort(left_arr)
right_arr_sorted = quick_sort(right_arr)
print(
f"left_arr_sorted {left_arr_sorted} + right_arr_sorted {right_arr_sorted}")
# return left + pivot + right
return left_arr_sorted + [pivot] + right_arr_sorted
arr1 = [1, 3, 5, 6, 7, 2, 4, 8, 9]
print(quick_sort(arr1))
# STRETCH: implement an in-place merge sort algorithm
# def merge_in_place(arr, start, mid, end):
# # TO-DO
# return arr
# def merge_sort_in_place(arr, l, r):
# # TO-DO
# return arr
# # STRETCH: implement the Timsort function below
# # hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt
# def timsort(arr):
# return arr
| true |
26c5201471d8948cfe707093710a05820f85e72b | CatLava/oop_practice | /car.py | 697 | 4.28125 | 4 | class Car:
def __init__(self, color, mileage):
self.color = color
self.mileage = mileage
# This is a built in function for only car
# Put a repr on any defined class, this helps to understand it
def __repr__(self):
return 'Car({self.mileage})'.format(self=self)
# Python built in method for string
def __str__(self):
return "a {self.color} car".format(self=self)
myc = Car("red", 12000)
myc
# when this is printed, all we get is a memory address, no information
print(myc)
# To help print readable information, we will use the __str__ and __repr__ methods
# __str__ is supposed to be easy to read function and be explicit as possible
| true |
de853c093fd83515f4a98a5f4c453272a6b5579c | sethifur/cs3030-seth_johns_hw5 | /seth_johns_hw5.py | 918 | 4.25 | 4 | #!/usr/bin/env python3
import sys
def GetInput():
"""
Function:
asks for a pin input <9876>
validates the size, type, and number.
returns pin if correct
if incorrect 3 times exits program
"""
for index in range(3):
try:
pin = int(input('Enter your pin: '))
if (pin >= 1000 and pin < 10000):
if pin == 1234:
return pin
else:
print('Your PIN is incorrect')
else:
print('Invalid PIN lenth. Correct format is: <9876>')
except ValueError:
print('Invalid PIN character. Correct format is: <9876>')
print('Your bank card is blocked.')
exit(1)
# Main Function
def main():
validation = GetInput()
print('Your PIN is correct.')
return
if __name__ == '__main__':
#Call Main
main()
exit(0)
| true |
cdcdb23d6ac63da1b095a1ee68be9b97e4643c20 | niko-vulic/sampleAPI | /leetcodeTester/q35.py | 1,744 | 4.1875 | 4 | # 35. Search Insert Position
# Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
# You must write an algorithm with O(log n) runtime complexity.
from typing import List
class Solution:
def __init__(self):
self.testCases = []
self.funcName = "searchInsert"
def defineTestCases(self):
self.testCases.append([[2, 3, 4], 3])
self.testCases.append([[1, 4, 7, 8], 5])
self.testCases.append([[-1, 0, 4, 7], 4])
self.testCases.append([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 12])
def runTests(self):
for case in self.testCases:
print("Test case:" + str(case) + ", answer is:" + str(getattr(self, self.funcName)(case[0], case[1])))
def searchInsert(self, nums: List[int], target: int) -> int:
# When the last element is reached, return recursively, adding any halfway counters on the return
if len(nums) == 1:
if target <= nums[0]:
return 0
else:
return 1
# fullsize = len(nums)
halfway = int(len(nums)/2)
# print("Size of current array" + str(fullsize))
# print("left half:" + str(nums[:halfway]))
# print("right half:" + str(nums[halfway:]))
# As the requirement is O(log n) time, we perform binary search on the array.
if target < nums[halfway]:
return self.searchInsert(nums[:halfway], target)
else:
return halfway + self.searchInsert(nums[halfway:], target)
if __name__ == '__main__':
soln = Solution()
soln.defineTestCases()
soln.runTests() | true |
7fff33692bf4f4aad318681b76b177bb021f6637 | niko-vulic/sampleAPI | /leetcodeTester/q121.py | 1,311 | 4.125 | 4 | # 121. Best Time to Buy and Sell Stock
# You are given an array prices where prices[i] is the price of a given stock on the ith day.
# You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
# Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
from typing import List
class Solution:
def __init__(self):
self.testCases = []
self.funcName = "maxProfit"
def defineTestCases(self):
self.testCases.append([0, 1, 2])
self.testCases.append([4, 1, 3, 5, 2, 7])
self.testCases.append([3, 2, 1])
def runTests(self):
for case in self.testCases:
print("Test case:" + str(case) + ", answer is:" + str(getattr(self, self.funcName)(case)))
def maxProfit(self, prices: List[int]) -> int:
minBuy = [0] * len(prices)
minBuy[0] = prices[0]
maxDiff = 0
for i in range(1, len(prices)):
minBuy[i] = min(prices[i], minBuy[i-1])
currDiff = prices[i] - minBuy[i]
if currDiff > maxDiff: maxDiff = currDiff
return maxDiff
if __name__ == '__main__':
soln = Solution()
soln.defineTestCases()
soln.runTests() | true |
1aca8af29f7519569145abfe34d3cd2efa535327 | enderceylan/Projects | /Solutions/FibonacciSequence.py | 390 | 4.3125 | 4 | # Fibonacci Sequence - Enter a number and have the program generate the Fibonacci
# sequence to that number or to the Nth number.
# Solution by Ender Ceylan
x = 1
y = 1
num = int(input("Enter the amount of Fibonacci values to be viewed: "))
while num <= 0:
num = int(input("Input must be above 0: "))
for i in range(num):
print(str(x)+" ")
y = (x-y)
if i != 0:
x = x + y
| true |
08eb776f982387f55fe513b09a624472c158dc5f | dhrvdwvd/practice | /python_programs/34_pr_04.py | 206 | 4.1875 | 4 | names = ["dhruv", "ratnesh", "abhinav", "jaskaran"]
name = input("Enter a name to search: ")
if name in names:
print(name+" is present in the list.")
else:
print("Name entered is not in the list.") | true |
3ff3ba9cd497c199e24a8683e59595802bedc4f2 | dhrvdwvd/practice | /python_programs/06_operators.py | 238 | 4.3125 | 4 | a = 3
b = 4
# Arithmetic Operators
print("a + b = ", a+b)
print("a - b = ", a-b)
print("a * b = ", a*b)
print("a / b = ", a/b)
# Python gives float when two ints are divided.
# Assignment operators.
a = 12
a+=22
a-=12
a*=2
a/=4
print(a) | true |
06ead9d50bb8b9eaad3a0c1bf43434331bcda7cb | dhrvdwvd/practice | /python_programs/66_try.py | 425 | 4.21875 | 4 | while(True):
print("Press q to quit")
a = input("Enter a number: ")
if(a == 'q'): break
try:
a = int(a)
if(a>6): print("Entered number is greater than 6.")
except Exception as e:
print(e) # This breaks the loop as well.
print("Thanks for playing the game.")
# The try-except do not let the programs to crash when an error
# occurs, this is useful when making GUI applications. | true |
bdec843924ca0e0e4e45ccd6bd315245098bf6ec | dhrvdwvd/practice | /python_programs/12_strings_slicing.py | 331 | 4.15625 | 4 | greeting = "Hello, "
name = "DhruvisGood"
#print(greeting + name)
#print(name[0])
#name[3] = 'd' --> does not work
# String can be accessed but not changed.
print(name[0:3]) # is same as below
print(name[:3])
print(name[1:]) # will print from index 1 to last index
print(name[1:8:2]) # will start printing index 1, 1+2, 5, 7 ... | true |
0137946f7a9ea9bbdae58fc8d79266575689cf32 | dhrvdwvd/practice | /python_programs/50b_genrators.py | 1,590 | 4.78125 | 5 | """
Iterables are those objects for which __iter__() and __getitem__()
methods are defined. These methods are used to generate an iterator.
Iterators are those objects for __next__() method is defined.
Iterations are process through which the above are accessed.
If I wish to traverse in a python object (string, list, tuple) moving
from one element to other, then that object should be an iterable.
If an object is iterable, then it generates an iterator through
__iter__(). The iterator obtained uses __next__() method to provide
items in the iterable.
Generators are iterators. These iterators can only be traversed once at
a time
"""
# To obtain a generator, yield keyword is used. yield gives a generator
# object:
def gen(n):
for i in range(n):
yield 10*i
def fib_nth_term(n):
if(n==1 or n==2):
return 1
else:
return fib_nth_term(n-1)+fib_nth_term(n-2)
def fib_gen(n):
for i in range(1,n):
yield fib_nth_term(i)
print(gen(2))
for i in range(8):
print(i)
# The above for loop generates values 'on the fly'. It does not store
# all the values from 0 to 77 in RAM, but it generates them one by one.
# So, range is a generator.
for i in gen(4):
print(i)
g = gen(5)
print("Printing using __next__()")
print("g(0): {}".format(g.__next__()))
print("g(1): {}".format(g.__next__()))
print("g(2): {}".format(g.__next__()))
print("g(3): {}".format(g.__next__()))
print("g(4): {}".format(g.__next__()))
print("\nGenerating fibonnaci series through a generator:")
for i in fib_gen(8):
print(i) | true |
6769020adb8b369e75113cf4f75cc06060dc5214 | ma-henderson/python_projects | /05_rock_paper_scissors.py | 2,297 | 4.34375 | 4 | import random
message_welcome = "Welcome to the Rock Paper Scissors Game!"
message_name = "Please input your name!"
message_choice = "Select one of the following:\n- R or Rock\n- P or Paper\n- S or Scissors"
message_win = "You WON!"
message_loss = "You LOST :("
message_end = "If you'd like to quit, enter 'q' or 'quit'"
message_quit = "quitting..."
choice_alternatives = ['r', 'rock', 'p', 'paper', 's', 'scissors']
# Functions:
def choice_checker(choice, alternatives):
"""Checks if the user's input is OK, does not stop until OK"""
while True:
for num in range(0, len(alternatives)):
if choice == alternatives[num]:
return choice
print("Incorrect input, please select one of the following:" + str(alternatives))
choice = input("Your choice (lowercase only): ")
#new_choice = choice_checker(choice_player, choice_alternatives)
# Player starts game, is welcomed
print(message_welcome)
print(message_name)
# Player inputs name
name = input("Your name: ")
while True:
# Player is asked what choice he would like to make
print(message_choice)
# Input is Checked and stored
choice_player = input("Your choice: ")
if choice_player == 'q' or choice_player == 'quit':
print(message_quit)
break
choice_player_ok = choice_checker(choice_player, choice_alternatives)
# Player choice is converted to number
if choice_player_ok == 'r' or choice_player_ok == 'rock':
choice_player_num = 0
elif choice_player_ok == 'p' or choice_player_ok == 'paper':
choice_player_num = 1
elif choice_player_ok == 's' or choice_player_ok == 'scissors':
choice_player_num = 2
# Computer randomizes its choice
choice_comp = random.randrange(3)
# Comparison is made
if choice_comp == 2 and choice_player_num == 1:
decision = 0
elif choice_comp == 1 and choice_player_num == 0:
decision = 0
elif choice_comp == 0 and choice_player_num == 2:
decision = 0
else:
decision = 1
# winner declared and printed
if decision == 1:
print(message_win)
else:
print(message_loss)
# score is recorded and printed
# player decides if he continues playing (q or quit)
print("\n" + message_end)
#BONUS: if player's name is "Tom" or "Tomas", Player always loses
# Note, if extra time use REGEXP to detect variations of tom | true |
1184cff6fc360e4a0bfd5754ed1312be4cf624f1 | ivanjankovic16/pajton-vjezbe | /Exercise 9.py | 885 | 4.125 | 4 | import random
def Guessing_Game_One():
try:
userInput = int(input('Guess the number between 1 and 9: '))
random_number = random.randint(1, 9)
if userInput == random_number:
print('Congratulations! You guessed correct!')
elif userInput < random_number:
print(f'You guessed to low! The correct answer is {random_number}')
elif userInput > random_number:
print(f'You guessed to high! The correct answer is {random_number}')
elif userInput > 9:
print('Error! You should enter a number between 1 and 9!')
except:
print('Error! You must enter a number between 1 and 9.')
Guessing_Game_One()
Guessing_Game_One()
while True:
answer = input('Dou you want to play again? (yes/exit): ')
if answer == 'yes':
Guessing_Game_One()
elif answer != 'exit':
print('Enter: yes or exit')
elif answer == 'exit':
#print(f'You took {guesses} guesses!')
break | true |
4b3d8f8ce9432d488a4ee4ebdc2bec1256939dbe | ivanjankovic16/pajton-vjezbe | /Exercise 16 - Password generator solutions.py | 675 | 4.21875 | 4 | # Exercise 16 - Password generator solutions
# Write a password generator in Python. Be creative with how you generate
# passwords - strong passwords have a mix of lowercase letters, uppercase
# letters, numbers, and symbols. The passwords should be random, generating
# a new password every time the user asks for a new password. Include your
# run-time code in a main method.
#Njihovo rješenje
import string
import random
def pw_gen(size = input, chars=string.ascii_letters + string.digits + string.punctuation):
return ''.join(random.choice(chars) for _ in range(size))
print(pw_gen(int(input('How many characters in your password?'))))
input('Press<enter>')
| true |
4713b2790c09b0f5f98e8f544c0a961ef87c2ea5 | ivanjankovic16/pajton-vjezbe | /Exercise 13 - Fibonacci.py | 1,204 | 4.625 | 5 | # Write a program that asks the user how many Fibonnaci numbers
# to generate and then generates them. Take this opportunity to
# think about how you can use functions. Make sure to ask the user
# to enter the number of numbers in the sequence to generate.(Hint:
# The Fibonnaci seqence is a sequence of numbers where the next number
# in the sequence is the sum of the previous two numbers in the
# sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)
def gen_fib():
nnums = int(input("How many numbers in a Fibonacci sequence do you want? "))
n1, n2 = 0, 1
count = 0
if nnums <= 0:
print("Please enter a positive integer")
#elif nterms == 1:
# print("Fibonacci sequence upto",nnums,":")
# print(n1)
else:
print("Fibonacci sequence:")
while count < nnums:
print(n1)
n3 = n1 + n2
# update values
n1 = n2
n2 = n3
count += 1 # is the same as count = count + 1. That keeps the index moving forward
gen_fib()
while True:
answer = input('Do you want to generate another sequence? (yes/no): ')
if answer == 'yes':
gen_fib()
elif answer == 'no':
break
else:
print('Enter yes or no')
#input('Press<enter>') | true |
e1d4247baca7c6291bd0fa90b51d920c86adb81b | csdaniel17/python-classwork | /string_split.py | 1,387 | 4.125 | 4 | ## String split
# Implement the string split function: split(string, delimiter).
# Examples:
# split('abc,defg,hijk', ',') => ['abc', 'defg', 'hijk']
# split('JavaScript', 'a') => ['J', 'v', 'Script']
# split('JaaScript', 'a') => ['J', '', 'Script']
# split('JaaaScript', 'aa') => ['J', 'aScript']
def str_split(str, delim):
result = []
start_idx = 0
end_idx = str.index(delim)
while end_idx != -1:
# find to the end_idx (until delim)
part = str[:end_idx]
# append to array
result.append(part)
# set start index to next point after delim
start_idx = end_idx + len(delim)
# now string is cut from start_idx to leave remainder so you can find next delim
str = str[start_idx:]
# if there is no delim in the rest of string
if delim not in str:
# put remaining str in array
result.append(str)
# terminate loop
break
# end_idx is now delim in leftover string
end_idx = str.index(delim)
print result
## test before adding input functionality
# str_split('abc,defg,hijk', ',')
# str_split('JavaScript', 'a')
# str_split('JaaScript', 'a')
# str_split('JaaaScript', 'aa')
print "Give string and a delimiter to split the string on."
str = raw_input("Enter a string: ")
delim = raw_input("Enter a delim: ")
str_split(str, delim)
| true |
cf6b1e2e097358113767dc766af9ebd853d52933 | Audodido/IS211_Assignment1 | /assignment1_part2.py | 716 | 4.28125 | 4 | class Book:
"""
A class to represent a book
Attributes:
author (string): Name of the author
title (string): Title of the book
"""
def __init__(self, author, title):
"""
Constructs all the necessary attributes for the Book object.
"""
self.author = author
self.title = title
def display(self):
"""
Returns:
(string) message containing the book's author and title
"""
print(self.title + ", written by " + self.author)
book1 = Book("John Steinbeck", "Of Mice and Men")
book2 = Book("Harper Lee", "To Kill a Mockingbird")
if __name__ == "__main__":
book1.display()
book2.display() | true |
9f020702dc8684050f12bca0a0610309033c7bc3 | saradcd77/python_examples | /abstract_base_class.py | 1,120 | 4.40625 | 4 | # This example shows a simple use case of Abstract base class, Inheritance and Polymorphism
# The base class that inherits abstract base class in python needs to override it's method signature
# In this case read method is overriden in methods of classes that inherits Electric_Device
# Importing in-built abstract base class
from abc import ABC, abstractmethod
# Custom Exception
class InvalidOperationError(Exception):
pass
# Inherits ABC class
class Electric_Device(ABC):
def __init__(self):
self.open = False
def turn_on_device(self):
if self.open:
raise InvalidOperationError("Electric_Device is already ON!")
self.open = True
def turn_off_device(self):
if not self.open:
raise InvalidOperationError("Electric_Device is OFF")
self.open = False
@abstractmethod
def charge(self):
pass
class Heater(Electric_Device):
def charge(self):
print("Charging Electric Heater!")
class Kettle(Electric_Device):
def charge(self):
print("Charging Electric Kettle! ")
device1 = Kettle()
device1.charge()
device2 = Heater()
device2.charge()
device2.turn_on_device()
print(device2.open)
| true |
22e801ed46b26007bbd7880dce3197fbc3e04a7c | simonzahn/Python_Notes | /Useful_Code_Snippets/DirectorySize.py | 522 | 4.375 | 4 | #! python3
import os
def dirSize(pth = '.'):
'''
Prints the size in bytes of a directory.
This function takes the current directory by default, or the path specified
and prints the size (in bypes) of the directory.
'''
totSize = 0
for filename in os.listdir(pth):
totSize += os.path.getsize(os.path.join(pth, filename))
return totSize
print('Your current directory is ' + os.getcwd())
print('What is the file path you want to look at?')
foo = str(input())
print(dirSize(foo))
| true |
1672167ecd1302e8bfff3da2f790d69ff6889be4 | KatGoodwin/LearnPython | /python_beginners/sessions/strings-basic/examples/.svn/text-base/string_concatenation.py.svn-base | 734 | 4.125 | 4 | # concatenating strings
newstring = "I am a " "concatenated string"
print newstring
concat = "I am another " + "concatenated string"
print concat
print "Our string is : " + newstring
# The above works, but if doing a lot of processing would be inefficient.
# Then a better way would be to use the string join() method, which joins
# string elements from a list.
lst = [ 'a', 'bunch', 'of', 'words', 'which', 'together', 'make', 'a',
'sentence', 'and', 'which', 'have', 'been', 'collected', 'in',
'a', 'list', 'by', 'some', 'previous', 'process.',
]
print ' '.join( lst )
# another way to construct strings is to use a format
s1 = "I am a"
s2 = "concatenated string"
print '%s formatted %s' % ( s1, s2, )
| true |
54415d27cdec4ce01ede31c8a87f330bb703ce59 | tomgarcia/Blabber | /markov.py | 2,284 | 4.21875 | 4 | #extra libraries used
import queue
import tools
import random
"""
markov_chain class is a class that creates a(n) markov chain statistical
model on an inputted list of objects.
The class is then able to generate randomly a new list of objects based
on the analysis model of the inputted list.
"""
class markov_chain:
"""
Class constructor, at the very minium, the class needs an inputted list of
objects the level parameter is extra to specify the level of the markov
chain
"""
def __init__(self, obj_list: list, level:int = 1):
self.level = level #level class variable
self.obj_list = obj_list #list of objects
self.transitions = {}
self.generate_prob_table()
"""
generate_prob_table goes through the list of objects and generates a probability
table of current object to the previous object that can be used to look up again.
NOTE: you might not need to keeptrack of a probability, just the count of one
object appearing after another
"""
def generate_prob_table(self):
for i in range(len(self.obj_list) - self.level):
state = self.obj_list[i:i+self.level]
next = self.obj_list[i+self.level]
if tuple(state) not in self.transitions:
self.transitions[tuple(state)] = {}
if next not in self.transitions[tuple(state)]:
self.transitions[tuple(state)][next] = 0
self.transitions[tuple(state)][next] += 1
"""
generate_random_list uses the probability table and returns a list of
objects that adheres to the probability table generated in the previous
method
NOTE: the first object has to be selected randomly(the seed)
NOTE: the count parameter is just to specify the length of the generated
list
"""
def generate_obj_list(self, count:int = 10):
start = random.randrange(len(self.obj_list)-self.level)
output = self.obj_list[start:start+self.level]
state = self.obj_list[start:start+self.level]
for i in range(count-self.level):
choice = tools.weighted_choice(self.transitions[tuple(state)])
output.append(choice)
state.append(choice)
state.pop(0)
return output
| true |
e52255d28a1e9c0d55ce5a296e384e1d7746b87d | mediter/Learn-Python-the-Hard-Way-notes-and-practices | /ex7.py | 1,138 | 4.46875 | 4 | # -*- coding: utf-8 -*-
# Exercise 7: More Printing
print "Mary had a little lamb."
print "Its fleece was white as %s." % 'snow'
print "And everywhere that Mary went."
print "." * 12 # what would that do?
end1 = 'C'
end2 = 'h'
end3 = 'e'
end4 = 'e'
end5 = 's'
end6 = 'e'
end7 = 'B'
end8 = 'u'
end9 = 'r'
end10 = 'g'
end11 = 'e'
end12 = 'r'
# watch that comma at the end.
# try removing it to see what happens
print end1 + end2 + end3 + end4 + end5 + end6,
print end7 + end8 + end9 + end10 + end11 + end12
# Shorthand for printing a string multiple times
# string * number [the number can only be an integer]
print "*" + "." * 12 + "*"
print "*", "." * 12, "*"
# Use the comma inline in print would also add a
# space between the elements.
# Now without the comma in the middle
print end1 + end2 + end3 + end4 + end5 + end6
print end7 + end8 + end9 + end10 + end11 + end12
print "Summary"
print "1. When using a comma at EOL after a print statement,",
print "the result of the next print statement will follow in",
print "the same line with a space added in between them."
print "2. Otherwise, it would print on separate lines."
| true |
660472dd3ec4d4ab685c784ea85dc540e6eb45c9 | mediter/Learn-Python-the-Hard-Way-notes-and-practices | /ex9.py | 923 | 4.28125 | 4 | # -*- coding: utf-8 -*-
# Exercise 9: Printing, Printing, Printing
# Here's some new strange stuff, remember to type it exactly
days = "Mon Tue Wed Thu Fri Sat Sun"
# \n would make the stuff after it begin on a new line
months = "\nJan\nFeb\nMar\nApr\nMay\nJun"
# if a comma is added to the above statement, it would cause
# TypeError: can only concatenate tuple (not "str") to tuple
months = months + "\nJul\nAug\nSep\nOct\nNov\nDec"
print "Here are the days: ", days
print "Here are the months: ", months
flowers = "rose\nnarcissus",
flowers = flowers + ("tuplip", "gardenia")
print flowers
# Output -> ('rose\nnarcissus', 'tuplip', 'gardenia')
# Why "\n" does not behave as an escaped char?
# Use triple double-quotes to enclose paragraphs to be printed
print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
| true |
10dc31cc92bc284cb08fde0fda5cdb312da06025 | Sayed-Tasif/my-programming-practice | /math function.py | 256 | 4.34375 | 4 | Num = 10
Num1 = 5
Num2 = 3
print(Num / Num1) # used to divide
print(Num % Num2) # used to see remainder
print(Num2 ** 2) # indicates something to the power {like ( "number" ** "the power number")}
print(Num2 * Num1) # used to multiply the number | true |
c781089190d266c5c3649f4ff96736fc1dfe8b1d | YanSongSong/learngit | /Desktop/python-workplace/homework.py | 217 | 4.1875 | 4 | one=int(input('Enter the first number:'))
two=int(input('Enter the second number:'))
three=int(input('Enter the third number:'))
if(one!=two and one!=three and two!=three):
a=max(one,two,three)
print(a)
| true |
95cafd3e875061426d39fd673bbf6327c5eb7c14 | krwinzer/web-caesar | /caesar.py | 489 | 4.25 | 4 | from helpers import alphabet_position, rotate_character
def encrypt(text, rot):
code = ''
for char in text:
if char.isalpha():
char = rotate_character(char, rot)
code = code + char
else:
code = code + char
return (code)
def main():
text = input("Please enter your text to be coded:")
rot = int(input("Please enter your desired rotation:"))
print(encrypt(text, rot))
if __name__ == "__main__":
main()
| true |
a337618daafddfb9224eda521e2e03644f204a0e | Seun1609/APWEN-Python | /Lesson2/quadratic.py | 1,141 | 4.21875 | 4 | # Get inputs a, b and c
# The coefficients, in general, can be floating-point numbers
# Hence cast to floats using the float() function
a = float(input("Enter a: "))
b = float(input("Enter b: "))
c = float(input("Enter c: "))
# Compute discriminant
D = b*b - 4*a*c
if D >= 0: # There are real roots
# x1 and x2 could be equal
# In that case, we would have real repeated roots
# This happens when the discriminant, D = 0
# Otherwise, there are real and distinct roots
x1 = (-b + D**0.5) / (2*a) # first solution
x2 = (-b - D**0.5) / (2*a) # second solution
# Print solutions
print("x1 = " + str(x1))
print("x2 = " + str(x2))
else: # Complex conjugate roots
# Get the real and imaginary parts
# In finding the imaginary part, we find the square root of -D
# This is because D itself is a negative number already
re = -b / (2*a) # real part
im = ((-D)**0.5) / (2*a) # imaginary part
# Print solutions
# x1 = re + j(im)
# x2 = re - j(im)
print("x1 = " + str(re) + " + j" + str(im))
print("x2 = " + str(re) + " - j" + str(im))
| true |
30115c3de0f19d9878f2b00c1abf998b7b36a9fb | stansibande/Python-Week-Assignments | /Functions.py | 2,048 | 4.25 | 4 | #name and age printing function
def nameAge(x,y):
print ("My name is {} and i am {} Years old.".format(x,y))
#take two numbers and multiply them
def multiply(x,y):
result=x*y
print("{} X {} = {}.".format(x,y,result))
#take two numbers and check if a number x is a multiple of a number Y
def multiples(x,y):
if x%y==0:
print("The number {} is a multiple of the number {}".format(x,y))
print
else:
print("The number {} is not a multiple of the number {}.".format(x,y))
print()
#out of three numbers determine biggest and smallest
def checker(num1,num2,num3):
if num1>num2:
largest=num1
else:
largest=num2
if num2>num3:
largest=num2
else:
largest=num3
if num3>largest:
largest=num3
else:
largest=largest
if largest>num1:
largest=largest
else:
largest=num1
print("The largest number between {},{} and {} is {}.".format(num1,num2,num3,largest))
print()
#Example 1
print ("Enter Your Name and Age To Be Printed:")
name=input("Enter Your Full Name:")
try:
age =int (input("Enter Your Age :"))
except:
print ("Age can only be a number")
else:
nameAge(name,age)
print()
#Example 2
print ("Enter 2 numbers to be Submitted to a fuction for Multiplication:")
num1=int(input("Enter your First number: "))
num2=int (input("Enter your second Number: "))
multiply(num1,num2)
print()
#Example 3
print ("Enter 2 numbers to be Submitted to a fuction To Determine if the First number is a Multiple of the Second Number:")
mult1=int(input("Enter your First number: "))
mult2=int (input("Enter your second Number: "))
multiples(mult1,mult2)
#Example 4
print ("Enter 3 numbers to be Submitted to a fuction To Determine Which one is the largest:")
n1=int(input("Enter your First number: "))
n2=int (input("Enter your second Number: "))
n3=int (input("Enter your third Number: "))
checker(n1,n2,n3)
| true |
1f07e8a2872c37d2a6a74c0ef5a6e9c997d3d6ea | UCSD-CSE-SPIS-2021/spis21-lab03-Vikram-Marlyn | /lab03Warmup_Vikram.py | 928 | 4.40625 | 4 | # Vikram - A program to draw the first letter of your name
import turtle
def draw_picture(the_turtle):
''' Draw a simple picture using a turtle '''
the_turtle.speed(1)
the_turtle.forward(100)
the_turtle.left(90)
the_turtle.forward(100)
the_turtle.left(90)
the_turtle.forward(100)
the_turtle.left(90)
the_turtle.forward(100)
the_turtle.left(90)
my_turtle = turtle.Turtle() # Create a new Turtle object
draw_picture(my_turtle) # make the new Turtle draw the shape
turtle1 = turtle.Turtle()
turtle2 = turtle.Turtle()
turtle1.speed(1)
turtle2.speed(2)
turtle1.setpos(-50, -50)
turtle2.setpos(200, 100)
turtle1.forward(100)
turtle2.left(90)
turtle2.forward(100)
#turtle.forward(distance)
#turtle.fd(distance)
#Parameters: distance – a number (integer or float)
#Move the turtle forward by the specified distance, in the direction the turtle is headed. | true |
9a7ed39510c516c2e7da84be43a8f8c2a488a337 | v-stickykeys/bitbit | /python/mining_simplified.py | 2,043 | 4.1875 | 4 | import hashlib
# The hash puzzle includes 3 pieces of data:
# A nonce, the hash of the previous block, and a set of transactions
def concatenate(nonce, prev_hash, transactions):
# We have to stringify it in order to get a concatenated value
nonce_str = str(nonce)
transactions_str = ''.join(transactions)
return ''.join([nonce_str, prev_hash, transactions_str])
# Now we want to hash this concatenated value.
def hash_sha256(concatenated):
# Bitcoin uses the SHA256 hash algorithm for mining
return hashlib.sha256(str(concatenated).encode('utf-8')).hexdigest()
# If we get a hash value inside of our defined target space we have found a
# solution to the puzzle. In this case, we will print the hash solution (which
# will be this block's hash) and return true.
def solve_hash_puzzle(nonce, prev_hash, transactions):
concatenated = concatenate(nonce, prev_hash, transactions)
proposed_solution = hash_sha256(concatenated)
# For the sake of example, we will define our target space as any hash
# output with 2 leading zeros. In Bitcoin it is actually 32 leading zeros.
if (proposed_solution[0:2] == '00'):
print(f'Solution found: {proposed_solution}')
return True
return False
# Now let's mine!
def mine_simple(max_nonce, prev_hash, transactions):
print('\nMining...')
# Note: max_nonce is just used for demonstration purposes to avoid an endless
# loop
nonce = 0 # Initalized to zero -- Is this true in Bitcoin?
while (solve_hash_puzzle(nonce, prev_hash, transactions) == False
and nonce < max_nonce):
nonce += 1
print(f'Nonce that produced solution: {nonce}')
# Uncomment the code below to see the program run
"""
_max_nonce = 100000
prev_hash = hashlib.sha256('Satoshi Nakamoto'.encode('utf-8')).hexdigest()
transactions = ["tx1", "tx2", "tx3"]
mine_simple(_max_nonce, prev_hash, transactions)
"""
# Notice the nonce value tells us how many attempts were required to find a
# solution. This is also an approximation for difficulty.
| true |
63c362549cdfdeeea249d6d31df11e8fca7748e3 | herr0092/python-lab3 | /exercise8.py | 400 | 4.34375 | 4 | # Write a program that will compute the area of a circle.
# Prompt the user to enter the radius and
# print a nice message back to the user with the answer.
import math
print('===================')
print(' Area of a Circle ')
print('===================')
r = int(input('Enter radius: '))
area = math.pi * ( r * r)
print('The area of a circle with a radius of ', r , 'is: ' , round(area,2) )
| true |
02096c3d2fcff25f2a680e34586a56d8d7ca1f89 | evb-gh/exercism | /python/guidos-gorgeous-lasagna/lasagna.py | 1,299 | 4.1875 | 4 | """Functions used in preparing Guido's gorgeous lasagna.
Learn about Guido, the creator of the Python language: https://en.wikipedia.org/wiki/Guido_van_Rossum
"""
EXPECTED_BAKE_TIME = 40
PREPARATION_TIME = 2
def bake_time_remaining(minutes):
"""Calculate the bake time remaining.
:param elapsed_bake_time: int - baking time already elapsed.
:return: int - remaining bake time derived from 'EXPECTED_BAKE_TIME'.
Function that takes the actual minutes the lasagna has been in the oven as
an argument and returns how many minutes the lasagna still needs to bake
based on the `EXPECTED_BAKE_TIME`.
"""
return EXPECTED_BAKE_TIME - minutes
def preparation_time_in_minutes(layers):
"""
Return prep time.
This function takes an int param representing the number of layers
multiplies it by the PREPARATION_TIME constant and returns an int
representing the prep time in minutes
"""
return PREPARATION_TIME * layers
def elapsed_time_in_minutes(prep, bake):
"""
Return elapsed cooking time.
This function takes two int params representing the number of layers &
the time already spent baking and returns the total elapsed minutes
spent cooking the lasagna.
"""
return preparation_time_in_minutes(prep) + bake
| true |
80df60b4c750e3e98e1c00c0d083e3582cbd4093 | zee7han/algorithms | /sorting/insertion_sort.py | 504 | 4.28125 | 4 | def insertion_sort(arr):
for i in range(1,len(arr)):
position = i
current_value = arr[i]
print("position and current_value before", position, current_value)
while position > 0 and arr[position-1] > current_value:
arr[position] = arr[position-1]
position = position-1
print("position and current_value after change -----------", position)
arr[position] = current_value
arr = [1,4,2,3,7,86,9]
insertion_sort(arr)
print(arr)
| true |
027a6c2e0251e68ff32feef6b1b1710692c7e8f2 | Sem31/Data_Science | /2_Numpy-practice/19_sorting_functions.py | 1,376 | 4.125 | 4 | #Sorting Functions
import numpy as np
#np.sort() --> return sorted values of the input array
#np.sort(array,axis,order)
print('Array :')
a = np.array([[3,7],[9,1]])
print(a)
print('\nafter applying sort function : ')
print(np.sort(a))
print('\nSorting along axis 0:')
print(np.sort(a,0))
#order parameter in sort function
dt = np.dtype([('name','S10'),('age',int)])
x = np.array([('Ram',23),('Robert',25),('Rahim',27)], dtype = dt)
print('\nArray :')
print(x)
print('dtype : ',dt)
print('Order by name : ')
print(np.sort(x, order = 'name'))
#np.nonzero() --> returns the indices of the non-zero elements
b = np.array([[30,40,0],[0,20,10],[50,0,60]])
print('\narray b is :\n',b)
print('\nafter applying nonzero() function :')
print(np.nonzero(b))
#np.Where() --> returns the indices of elements when the condition is satisfied
x = np.arange(12).reshape(3,4)
print('\nArray is :')
print(x)
print('Indices of elements >3 :')
y = np.where(x>3) #its just work like a sql query
print(y)
print('Use these indices to get elements statisfying the condition :')
print(x[y])
#np.extract() --> returns the elements satisfying any condition
x = np.arange(9).reshape(3,3)
print('\nArray : ')
print(x)
#define conditions
condition = np.mod(x,2) == 0
print('\nelement-wise value of condition :\n',condition)
print('\nextract elements using condition :\n',np.extract(condition, x))
| true |
e6c02fe3a07681cc415d9aa0e0257705aca65492 | Rishivendra/Turtle_Race_Game | /3.Turtle_race.py | 1,281 | 4.25 | 4 | from turtle import Turtle, Screen
import random
is_race_on = False
screen = Screen()
screen.setup(width=500, height=400) # sets the width and height of the main window
user_bet = screen.textinput(title="Make your bet",
prompt="Which turtle will win the race? Enter color:") # Pop up a dialog window for input of a string
colours = ["red", "orange", "yellow", "green", "blue", "purple"]
y_positions = [-70, -40, -10, 20, 50, 80]
all_turtle = []
for turtle_index in range(0, 6):
new_turtle = Turtle(shape="turtle")
new_turtle.penup()
new_turtle.goto(x=-230, y=y_positions[turtle_index])
new_turtle.color(colours[turtle_index])
all_turtle.append(new_turtle)
if user_bet:
is_race_on = True
while is_race_on:
for turtle in all_turtle:
if turtle.xcor() > 230:
is_race_on = False # stop race
winning_color = turtle.pencolor()
if winning_color == user_bet:
print(f"You have Won! The {winning_color} is the turtle winner!")
else:
print(f"You have Lost! The {winning_color} is the turtle winner!")
rand_distance = random.randint(0, 10)
turtle.fd(rand_distance)
screen.exitonclick()
| true |
6206eb9dc2cb71a50b5f75a1e9c8ffd11ba8e15c | Polaricicle/practical03 | /q3_find_gcd.py | 1,231 | 4.40625 | 4 | #Filename: q3_find_gcd.py
#Author: Tan Di Sheng
#Created: 20130218
#Modified: 20130218
#Description: This program writes a function that returns the greatest common
#divisor between two positive integers
print("""This program displays a the greatest common divisor between
two positive integers.""")
#Creates a loop so that the user can keep using the application
#without having to keep restarting the application
while True:
def gcd(m, n):
min = m
if (min > n):
min = n
m = int(m)
n = int(n)
min = int(min)
while not (min == 1):
if (m % min == 0) and (n % min == 0):
break
min = min - 1
print("\nThe greatest common divisor of {0} and {1} is {2}".format(m, n, min))
while True:
m = input("\nEnter the first integer: ")
n = input("Enter the second integer: ")
try:
int(m) and int(n)
except:
print("\nPlease input integer values.")
else:
break
gcd(m, n)
#gives the user an option to quit the application
contorquit = input("\nContinue? Type no to quit: ")
if contorquit == "no":
quit()
else:
continue
| true |
5a734d271228ba71cd34021f260885193bba923d | abbyto/QUALIFIER | /main.py | 495 | 4.125 | 4 | import difflib
words= ['i','have','want','a','test','like','am','cheese','coding','sleeping','sandwich','burger']
def word_check(s):
for word in s.casefold().split():
if word not in words:
suggestion= difflib.get_close_matches(word, words)
print(f'Did you mean {",".join(str(x)for x in suggestion)} instead of {word}?')
s = input('Input a string: ')
word_check(s)
# mod from python.org, https://docs.python.org/3/library/difflib.html
print("lol")
| true |
7ed458e350f78585fc568c5ad7fc9913077b7890 | BethMwangi/DataStructuresAndAlgorithms | /Arrays/operations.py | 1,693 | 4.34375 | 4 |
# Accessing an element in an array
array = [9,4,5,7,0]
print (array[3])
# output = 7
# print (array[9])---> This will print "list index out of range" since the index at 9 is not available.
# Insertion operation in an array
# One can add one or more element in an array at the end, beginning or any given index
# Insertion takes two arguments, the index to insert the element and the element , i,e insert(i, element)
array = [9,4,5,7,0]
array.insert(0,3) # the zero(0) is the first index and 3 is the element
print (array) # output --> [3, 9, 4, 5, 7, 0]
array.insert(4,8)
print (array) # output --> [3, 9, 4, 5, 8, 7, 0]
# Deletion operation in an array
# Remove an exixting element in an array with the python inbult function remove()
array = [9,4,5,7,0]
array.remove(7)
print(array) # removes the number 7 specified in the function and re-organizes the array
# Search operation in an array
# the search operation searches an element based on the index given or its value
# It uses in-built python function index()
array = [9,4,5,7,0]
print (array.index(4)) # output ---> this returns 1 since index of 4 is 1
# print (array.index(3)) # output ---> this returns an ValueError since 3 is not in the array list
# Update operation in an array
# this operation updates an exixting element in the array by re-assigning a new value to an element by index.
array = [9,4,5,7,0]
array[0] = 3
print (array) # output --->[3, 4, 5, 7, 0] upadates value at index 0 to 3 and removes 9
array = [9,4,5,7,0]
# array[5] = 3 This will return an error since the index at 5 is out of range...index goes upto 4
# print (array) - IndexError: list assignment index out of range | true |
b2ecec901924b48a30b420c2b87c3f9087872bd5 | alabiansolution/python-wd1902 | /day4/chapter7/mypackage/code1.py | 755 | 4.4375 | 4 | states = {
"Imo" : "Owerri",
"Lagos" : "Ikeja",
"Oyo" : "Ibadan",
"Rivers" : "Port Harcourt",
"Taraba" : "Yalingo",
"Bornu": "Maidugri"
}
def my_avg(total_avg):
'''
This function takes a list of numbers as
an argument and returns the average
of that list
'''
sum = 0
for x in total_avg:
sum += x
return sum/len(total_avg)
def multiplication(multiply_by, start=1, stop=12):
'''
This function takes three argument
the first one is the multiplication number
and it is required. The second is the start value
and is optional while the third on is stop value
and it is also optional
'''
while start <= stop:
print(multiply_by, " X ", start, " = ", multiply_by * start)
start += 1
| true |
d9b7c5980339a47d34694780934f8828440ff379 | 666176-HEX/codewars_python | /Find_The_Parity_Outlier.py | 524 | 4.5 | 4 | """
You are given an array (which will have a length of at least 3, but could be very large)
containing integers. The array is either entirely comprised of odd integers or entirely
comprised of even integers except for a single integer N. Write a method that takes the
array as an argument and returns this "outlier" N."""
def find_outlier(integers):
odd = sum(map(lambda x: x%2 != 0,integers[:3])) >= 2
return list(filter(lambda x: x%2 != odd, integers))[0]
print(find_outlier([160, 3, 1719, 19, 11, 13, -21])) | true |
053d6552e18849fe13c14f0e4d229624f1f19076 | mohitsoni7/oops_concepts | /oops5_dunder_methods.py | 2,300 | 4.40625 | 4 | """
Dunder methods / Magic methods / Special methods
================================================
These are special methods which are responsible for the certain types of behaviour of
objects of every class.
Also, these methods are responsible for the concept of "Operator overloading".
Operator overloading
--------------------
It means we can make operators to work for User defined classes.
For ex. "+" operator works differently for Integers and Strings.
Similarly, we can make it work in our way for our User defined Class.
__repr__ method
---------------
It gives the "Unambiguous" representation of an instance of a class.
Usually, helps and is used in debugging, logging etc.
Used by developers!
__str__ method
---------------
It gives the "End user readable" representation of an instance of a class.
Note: If __str__ method is not there then a call to __str__ method, fallback to __repr__ method.
i.e. str(emp_1) and repr(emp_1) will give the same output.
"""
class Employee:
raise_amt = 1.04
def __init__(self, firstname, lastname, pay):
self.firstname = firstname
self.lastname = lastname
self.pay = pay
self.email = firstname.lower() + '.' + lastname.lower() + '@yopmail.com'
def fullname(self):
return '{} {}'.format(self.firstname, self.lastname)
def apply_raise(self):
self.pay = (self.pay * self.raise_amt)
def __repr__(self):
return "Employee({}, {}, {})".format(self.firstname, self.lastname, self.pay)
# def __str__(self):
# return 'Employee: {}'.format(self.fullname())
# Operator overloading
# Here, we are overloading the "+" operator
# We are making it work such that if 2 instances of class Employee are added,
# there salaries are added.
def __add__(self, other):
return int(self.pay + other.pay)
def __len__(self):
return len(self.fullname())
emp_1 = Employee('Mohit', 'Soni', 70000)
print(emp_1)
print(emp_1.__repr__())
print(Employee.__repr__(emp_1))
# print(emp_1.__str__())
print(repr(emp_1))
print(str(emp_1))
emp_2 = Employee('Udit', 'Soni', 80000)
print(emp_1 + emp_2)
print(Employee.__add__(emp_1, emp_2))
print(len(emp_1)) | true |
a47be7352926ddacb098ca2fd795af56e691c137 | mickyaero/Practice | /read.py | 951 | 4.71875 | 5 | """
#It imports the thing argv from the library already in the computer "sys"
from sys import argv
#Script here means that i will have to type the filename with the python command and passes this argument to the "filename"
script, filename = argv
#OPen the file and stores it in text variable
text = open(filename)
#prints the file
print "This is the file %r" %filename
#text.read(), reads the data in the file and it is then directly printed
print text.read()
#just another print statement
"""
print " Type filename again:"
#the "> " is just what you would like to show to the user to add an input, its just a bullet !!!!!!input is taken from the user in the running of the code and that is used further in the code, so basically the code halts here and takes the input, nice!!!
file_again = raw_input("> ")
#same stores the data in "text_again"
text_again = open(file_again)
#prints it
print text_again.read()
#closes the file
text_again.close()
| true |
535282c6449efc953b8fc171d0ca08e95fb79ac2 | DonalMcGahon/Problems---Python | /Smallest&Largest.Q6/Smallest&Largest.py | 515 | 4.4375 | 4 | # Create an empty list
lst = []
# Ask user how many numbers they would like in the list
num = int(input('How many numbers: '))
# For the amount of numbers the user wants in the list, ask them to enter a number for each digit in the list
for n in range(num):
numbers = int(input('Enter number '))
# .append adds the numbers to the list
lst.append(numbers)
# Print out the Lagest and Smallest numbers
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst)) | true |
10781a10fa8cbac266fb58bcd1b87a033d2e842b | DonalMcGahon/Problems---Python | /Palindrome.Q7/Palindrome.py | 349 | 4.59375 | 5 | # Ask user to input a string
user_string = str(input('Enter a string to see if it is palindrome or not: '))
# This is used to reverse the string
string_rev = reversed(user_string)
# Check to see if the string is equal to itself in reverse
if list(user_string) == list(string_rev):
print("It is palindrome")
else:
print("It is not palindrome") | true |
df5d470412dbee029d29972f1dc66b8fe4af7912 | bernardukiii/Basic-Python-Scripts | /YourPay.py | 611 | 4.28125 | 4 | # Write a program to prompt the user for hours and rate per hour using input to compute gross pay.
# Use 35 hours and a rate of 2.75 per hour to test the program (the pay should be 96.25).
# You should use input to read a string and float() to convert the string to a number.
# Do not worry about error checking or bad user data.
print("Hi there, let´s calculate how much you earn per day!")
hours = int(input("How many hours do you work per day?: "))
wage = float(input("I know this is sensitive, but I need to know how much you get paid per hour: "))
print("Your pay: " + str(hours*wage))
| true |
1f85c84c848524dd0056d74fa6cb6ca3e4bbe3f2 | pratikmahajan2/My-Python-Projects | /Guess The Number Game/06 GuessTheNumber.py | 536 | 4.15625 | 4 | import random
my_number = random.randint(0,100)
print("Please guess my number - between 0 and 100: ")
while True:
your_number = int(input(""))
if your_number > 100 or your_number < 0:
print("Ohhoo! You need to enter number between 0 and 100. Try again")
elif (your_number > my_number):
print("Your guess is greater than my number. Try again")
elif (your_number < my_number):
print("Your number is less than my number. Try again" )
else:
print("Your won. My number is: ", my_number)
break
| true |
924fde1d0ded0a114f314cfe2560672f7736a629 | Theodora17/TileTraveller | /tile_traveller.py | 1,911 | 4.46875 | 4 | # Functions for each movement - North, South, East and West
# Function that updates the position
# Function that checks if the movement wanted is possible
def north(first,second) :
if second < 3 :
second += 1
return first, second
def south(first,second) :
if second > 1 :
second -= 1
return first, second
def west(first,second) :
if first > 1 :
first -= 1
return first, second
def east(first,second) :
if first < 3 :
first += 1
return first, second
def read_choice():
choice = input("Direction: ").lower()
return choice
def get_valid_direction(first, second):
if first == 1 and second == 1:
print("You can travel: (N)orth")
elif first == 2 and second == 1:
print("You can travel: (N)orth")
elif first == 1 and second == 2:
print("You can travel: (N)orth or (E)ast or (S)outh")
elif first == 1 and second == 3:
print("You can travel: (E)ast or (S)outh")
elif first == 2 and second == 3:
print("You can travel: (W)est or (E)ast")
elif first == 2 and second == 2:
print("You can travel: (W)est or (S)outh")
elif first == 3 and second == 3:
print("You can travel: (W)est or (S)outh")
elif first == 3 and second == 2:
print("You can travel: (N)orth or (S)outh")
elif first == 3 and second == 1:
print("Victory!")
else:
print("Not a valid direction!")
return first, second
def main():
first = 1
second = 1
victory = False
while victory == False:
valid_direction = get_valid_direction(first, second)
choice = read_choice()
if choice == "n":
north(first, second)
elif choice == "s":
south(first, second)
elif choice == "w":
west(first, second)
elif choice == "e":
east(first, second)
main() | true |
58872f4d3554c2849ffeb4c978451bfbf415cfb3 | mparker24/EvensAndOdds-Program | /main.py | 622 | 4.25 | 4 | #This asks the user how many numbers they are going to input
question = int(input("How many numbers do you need to check? "))
odd_count = 0
even_count = 0
#This asks for a number and outputs whether its even or odd
for i in range(question):
num = int(input("Enter number: "))
if (num % 2) == 0:
print(f"{num} is an even number")
even_count = even_count + 1
else:
print(f"{num} is an odd number")
odd_count = odd_count + 1
#This outputs how many even numbers and how many odd numbers you've inputted
print(f"You entered {even_count} even number(s)")
print(f"You entered {odd_count} odd number(s)")
| true |
50934c184a7b7248bfae0bdcfba6c6a002d38f59 | erikseyti/Udemy-Learn-Python-By-Doing | /Section 2 - Python Fundamentals/list_comprehension.py | 766 | 4.46875 | 4 | # create a new list with multiples by 2.
numbers = [0,1,2,3,4]
doubled_numbers = []
# a more simple way with a for loop
# for number in numbers:
# doubled_numbers.append(number *2)
# print(doubled_numbers)
# with list comprehension:
doubled_numbers = [number *2 for number in numbers]
print(doubled_numbers)
# using range of numbers:
doubled_numbers = [number *2 for number in range(5)]
print(doubled_numbers)
# You can use any number on the parameter that will be in the for loop of the list comprehension
# obviously the word number is not used, in this context
doubled_numbers = [5 for number in range(5)]
# In cases like this you can see programmers using a _ on the name of the variable
# doubled_numbers = [5 for _ in range(5)]
print(doubled_numbers) | true |
f3b0cd25318048ca749c91aecd7ee53e36327221 | sloaneluckiewicz/CSCE204 | /CSCE204/exercises/mar9/functions3.py | 1,190 | 4.28125 | 4 | def factorial():
num = int(input("Enter number: "))
answer = 1
# error invalid input return = takes you out of the function
if num < 1:
print("Invalid number")
return
for i in range(1, num+1):
answer *= i
print(f"{num}! = {answer}")
def power():
base = int(input("Enter number for base: "))
exponent = int(input("Enter number for exponent: "))
answer = 1
if base < 1 or exponent <1:
print("invalid input")
return
# loop through and caluculate answer, then display it
for i in range(exponent):
answer *= base
print(f"{base}^{exponent} = {answer}")
def sum():
number = int(input("Enter number to sum: "))
ans = 0
for i in range(1, number+1):
ans += i
print(f"The sum of {number} = {ans}")
# program
print("Welcome to Math!")
while True:
command = input("Compute (F)actotial, (S)um, (P)ower, or (Q)uit: ").strip() .lower()
if command == "q":
break
elif command == "f":
factorial()
elif command == "s":
sum()
elif command == "p":
power()
else:
print("Invalid input")
print("Goodbye!")
| true |
e8ba520b71bcb4af787d39ad3bca0521c806c433 | sloaneluckiewicz/CSCE204 | /CSCE204/exercises/feb23/mult_tables.py | 449 | 4.125 | 4 | # multiplication table
"""
1 2 3 4 5
1 4 6 8 10
"""
tableSize = int(input("Enter size of table: "))
for row in range(1, tableSize+1): # loop through rows
for col in range(1, tableSize+1): # for every row loop their cols
ans = row * col
# if there is just one digit in the number
if len(str(ans)) == 1:
print(f" {ans}", end= " ")
else:
print(ans, end = " ")
print() | true |
09c598aa5bfd2a7489b5e30d6723ae6a39cdc04a | ceeblet/OST_PythonCertificationTrack | /Python1/python1/space_finder.py | 287 | 4.15625 | 4 | #!/usr/local/bin/python3
"""Program to locate the first space in the input string."""
s = input("Please enter a string: ")
pos = 0
for c in s:
if c == " ":
print("First space occurred at position", pos)
break
pos += 1
else:
print("No spaces in that string.") | true |
5bbd0ab39d4112ccac8775b398c37f8f13f42345 | ceeblet/OST_PythonCertificationTrack | /Python1/python1/return_value.py | 1,259 | 4.375 | 4 | #!/usr/local/bin/python3
def structure_list(text):
"""Returns a list of punctuation and the location of the word 'Python' in a text"""
punctuation_marks = "!?.,:;"
punctuation = []
for mark in punctuation_marks:
if mark in text:
punctuation.append(mark)
return punctuation, text.find('Python')
text_block = """\
Python is used everywhere nowadays.
Major users include Google, Yahoo!, CERN and NASA (a team of 40 scientists and engineers
is using Python to test the systems supporting the Mars Space Lander project).
ITA, the company that produces the route search engine used by Orbitz, CheapTickets,
travel agents and many international and national airlines, uses Python extensively.
The YouTube video presentation system uses Python almost exclusively, despite their
application requiring high network bandwidth and responsiveness.
This snippet of text taken from chapter 1"""
for line in text_block.splitlines():
print(line)
p, l = structure_list(line)
if p:
print("Contains:", p)
else:
print("No punctuation in this line of text")
if ',' in p:
print("This line contains a comma")
if l >= 0:
print("Python is first used at {0}".format(l))
print('-'*80)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.