blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
660848ae5488cb9326331d9aa4ac4aab71d73632
|
Kpsmile/Learn-Python
|
/Basic_Programming/ListsComprehension_basics.py
| 951
| 4.125
| 4
|
sentence='My Name is Kp Singh'
def eg_lc(sentence):
vowel='a,e,i,o,u'
return''.join(l for l in sentence if l not in vowel)
print"List comprehension is" + eg_lc(sentence)
"""square of only even numbers in the list
def square_map(arr):
return map(lambda x: x**2, arr)
print ["List comprehension is" ]+ square_map(range(1,11))"""
"""square of only even numbers in the list"""
def even_fil(arr):
return str(filter(lambda x:x is not None ,map(lambda x:x**2 if x%2==0 else None, arr)))
print "square of only even numbers in the list is :" + even_fil(range(1,11))
#Method 3: List comprehension:
def square_even_lc(arr):
return str([i**2 for i in arr if i%2==0])
print "square of only even numbers in the list is :"+square_even_lc(range(1,11))
"""
Counting the occurrences of one item in a list
"""
l=['q','a','q', 1,3,1,2,3]
res=[[x,l.count(x)] for x in set(l)]
res_1=[[x,l.count(x)] for x in (l)]
print res
print res_1
| false
|
832de19c8b9ab75f412d3f0ebc57f6791bc0d15f
|
Kpsmile/Learn-Python
|
/Basic_Programming/Collections.py
| 1,580
| 4.53125
| 5
|
a = [3, 6, 8, 2, 78, 1, 23, 45, 9]
print(sorted(a))
"""
Sorting a List of Lists or Tuples
This is a little more complicated, but still pretty easy, so don't fret!
Both the sorted function and the sort function take in a keyword argument called key.
What key does is it provides a way to specify a function that returns what you would like your items
sorted by. The function gets an "invisible" argument passed to it that represents an item in the list,
and returns
a value that you would like to be the item's "key" for sorting.
So, taking a new list, let's test it out by sorting by the first item in each sub-list
"""
def getkey(item):
return item[1]
l=[[1,30],[4,21],[3,7]]
res=sorted(l, key=getkey)
print(res)
"""
Sorting a List (or Tuple) of Custom Python Objects
"""
class Custom(object):
def __init__(self, name, number):
self.name=name
self.number=number
def __repr__(self):
"""
the __repr__ function tells Python how we want the object to be represented as.
it tells the interpreter how to display the object when it is printed to the screen.
"""
return'{}: {} {}'.format(self.__class__.__name__,
self.name,
self.number)
Customlist=[Custom('abc',10),Custom('xyz',10),Custom('jklm',10),Custom('qrs',10)]
def getkey(item):
return item.name
results=sorted(Customlist, key=getkey)
result_rev=sorted(Customlist, key=getkey,reverse=True)
print(results)
print(result_rev)
| true
|
50febd52f27da540cc858944a37969ed932090c6
|
surya-lights/Python_Cracks
|
/math.py
| 293
| 4.15625
| 4
|
# To find the highest or lowest value in an iteration
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
# To get the positive value of specified number using abs() function
x = abs(-98.3)
print(x)
# Return the value of 5 to the power of 4 is (same as 5*5*5*5):
x = pow(5, 4)
print(x)
| true
|
f8bbfd6363010700b233934b7392629138d29e66
|
sanazjamloo/algorithms
|
/mergeSort.py
| 1,395
| 4.4375
| 4
|
def merge_sort(list):
"""
Sorts a list in ascending order
Returns a new sorted List
Divide: Find the midpoint of the list and divide into sublists
Conquer: Recursively sort the sublists created in previous step
Combine: Merge the sorted sublists created in previous step
Takes O(n log n) time and O(n) space
"""
#Stopping condition of the recursion
if len(list) <= 1:
return List
left_half, right_half = split(list)
left = merge_sort(left_half)
right = merge_sort(right_half)
return merge(left, right)
def split(list):
"""
Divide the unsorted list at midpoint into sublists
Returns two sublists - left and right_half
Takes overal O(log n) time
"""
# // for floor operation
mid = len(list) //2
left = list[:mid]
right = list[mid:]
return left, right
def merge (left, right):
"""
Merges two lists (left and right), sorting them in the process
Returns a new merged list
Runs in overall O(n) time
"""
l = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
l.append(left[i])
i+ = 1
else:
l.append(right[j])
j+ = 1
return l
| true
|
73631147ca4cc0322de2a68a36290502ee230907
|
ytgeng99/algorithms
|
/Pythonfundamentals/FooAndBar.py
| 1,040
| 4.25
| 4
|
'''Write a program that prints all the prime numbers and all the perfect squares for all numbers between 100 and 100000.
For all numbers between 100 and 100000 test that number for whether it is prime or a perfect square. If it is a prime number print "Foo". If it is a perfect square print "Bar". If it is neither print "FooBar". Do not use the python math library for this exercise. For example, if the number you are evaluating is 25, you will have to figure out if it is a perfect square. It is, so print "Bar".'''
for i in range(100, 100001):
if i == 1:
prime = False
perfect_square = True
else:
prime = True
perfect_square = False
for j in range(2, i):
if i%j == 0:
prime = False
if j**2 == i:
perfect_square = True
if j*2 > i or j**2 > i:
break
if not prime and not perfect_square:
print i, 'FooBar'
elif prime:
print i, 'Foo'
elif perfect_square:
print i, 'Bar'
| true
|
44a002f5ed28792f31033331f79f49b24d6bc3ef
|
ytgeng99/algorithms
|
/Pythonfundamentals/TypeList.py
| 1,320
| 4.375
| 4
|
'''Write a program that takes a list and prints a message for each element in the list, based on that element's data type.
Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the array contains. If it contains only one type, print that type, otherwise, print 'mixed'.'''
l = ['magical unicorns',19,'hello',98.98,'world']
'''l = [2,3,1,7,4,12]
l = ['magical','unicorns']
l = []'''
new_str_list = []
sum = 0
str_items = 0
num_items = 0
for item in l:
if type(item) == str:
new_str_list.append(item)
str_items += 1
elif type(item) == int or type(item) == float:
sum += item
num_items += 1
if (str_items == 0 and num_items == 0):
print 'The array you entered is empty'
elif (str_items > 0 and num_items > 0):
print 'The array you entered is of mixed type'
elif (str_items != 0 and num_items == 0):
print 'The array you entered is of string type'
elif (str_items == 0 and num_items != 0):
print 'The array you entered is of number type'
if (str_items != 0):
print 'String:', ' '.join(new_str_list)
if (num_items != 0):
print 'Sum:', sum
| true
|
c8bc084cc06c30404dbb8d5cd6653dd74d007405
|
KatePavlovska/python-laboratory
|
/laboratory1&2update/Lab2_Task2_calculation_pavlovska_km_93.py
| 640
| 4.25
| 4
|
print("Павловська Катерина. КМ-93. Варіант 14. ")
print("Task2: Given an integer N (> 0), which is a degree of 2: N = 2K. Finding an integer K is an exponent of this degree.")
print()
import re
re_integer = re.compile("^[-+]?\d+$")
def validator(pattern, promt):
text = input(promt)
while not bool(pattern.match(text)):
text = input(promt)
return text
number = int( validator( re_integer, "Input number: "))
counter = 0
while number % 2 == 0:
number /= 2
counter += 1
if number != 1:
print("This number is not a power of 2!")
else:
print("This number is", counter, " power")
| true
|
21a2fbe709284990b8d486f7aabd79ddc269d4bf
|
AlexChesser/CIT590
|
/04-travellingsalesman/cities.py
| 2,041
| 4.28125
| 4
|
def read_cities(file_name)
"""Read in the cities from the given file_name, and return them as a list
of four-tuples: [(state, city, latitude, longitude), ...] Use this as your
initial road_map, that is, the cycle Alabama → Alaska → Arizona → ... → Wyoming → Alabama."""
pass
def print_cities(road_map)
"""Prints a list of cities, along with their locations. Print only one or
two digits after the decimal point."""
pass
def compute_total_distance(road_map)
"""Returns, as a floating point number, the sum of the distances of all
the connections in the road_map. Remember that it's a cycle, so that (for example)
in the initial road_map, Wyoming connects to Alabama.."""
pass
def swap_adjacent_cities(road_map, index)
"""Take the city at location index in the road_map, and the city at location
index+1 (or at 0, if index refers to the last element in the list), swap their
positions in the road_map, compute the new total distance, and return the tuple
(new_road_map, new_total_distance)."""
pass
def swap_cities(road_map, index1, index2)
"""Take the city at location index in the road_map, and the city at location
index2, swap their positions in the road_map, compute the new total distance, and
return the tuple (new_road_map, new_total_distance). Allow the possibility that index1=index2,
and handle this case correctly."""
pass
def find_best_cycle(road_map)
"""Using a combination of swap_cities and swap_adjacent_cities, try 10000 swaps,
and each time keep the best cycle found so far. After 10000 swaps, return the best cycle found
so far."""
pass
def print_map(road_map)
"""Prints, in an easily understandable format, the cities and their connections,
along with the cost for each connection and the total cost."""
pass
def main()
"""Reads in and prints out the city data, then creates the "best"
cycle and prints it out."""
pass
if __name__ == '__main__':
main()
| true
|
40db83e086d8857643c10447811873e55740797b
|
kajalubale/PythonTutorial
|
/While loop in python.py
| 535
| 4.34375
| 4
|
############## While loop Tutorial #########
i = 0
# While Condition is true
# Inside code of while keep runs
# This will keep printing 0
# while(i<45):
# print(i)
# To stop while loop
# update i to break the condition
while(i<8):
print(i)
i = i + 1
# Output :
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# Assuming code inside for and while loop is same
# Both While and for loop takes almost equal time
# As both converted into same machine code
# So you can use any thing which is convenient
| true
|
a991a9d07955fe00dad9a2b46fd32503121249e8
|
kajalubale/PythonTutorial
|
/For loop in python.py
| 1,891
| 4.71875
| 5
|
################### For Loop Tutorial ###############
# A List
list1 = ['Vivek', 'Larry', 'Carry', 'Marie']
# To print all elements in list
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[3])
# Output :
# Vivek
# Larry
# Carry
# Marie
# We can do same thing easily using for loop
# for loop runs len(list1) times
# each time item is equal to one elemrnt of list from starting
for item in list1:
print(item)
# Output :
# Vivek
# Larry
# Carry
# Marie
# We can iterate tuple, list of lists, dictionary,
# and many more containers using for loop
# Examples :
# Iterating tuple
list1 = ('Vivek', 'Larry', 'Carry', 'Marie')
for item in list1:
print(item)
# Output :
# Vivek
# Larry
# Carry
# Marie
# Iterating a list of lists
list1 = [["Vivek", 1], ["Larry", 2],
["Carry", 6], ["Marie", 250]]
for item in list1:
print(item)
# Output :
# ['Vivek', 1]
# ['Larry', 2]
# ['Carry', 6]
# ['Marie', 250]
# Iterating a dictionary
dict1 = dict(list1)
print(dict1)
# Output :
# {'Vivek': 1, 'Larry': 2, 'Carry': 6, 'Marie': 250}
for item in dict1:
print(item) # It will print only keys
# Output :
# Vivek
# Larry
# Carry
# Marie
# to print both key and value while iterating dictionary
for item, lollypop in dict1.items():
print(item, "and lolly is ", lollypop)
# Output :
# Vivek and lolly is 1
# Larry and lolly is 2
# Carry and lolly is 6
# Marie and lolly is 250
# Quiz time :
# Ques : Create a list if item in list is numerical
# and number is greater than 6
# Solution
items = [int, float, "HaERRY", 5, 3, 3, 22, 21, 64, 23, 233, 23, 6]
for item in items:
if str(item).isnumeric() and item >= 6:
print(item)
# Remember str(item).isnumeric() is correct
# item.isnumeric() is wrong
# Output :
# 22
# 21
# 64
# 23
# 233
# 23
# 6
| true
|
2a3ca27dd93b4c29a43526fa2894f79f38280b82
|
kajalubale/PythonTutorial
|
/41.join function.py
| 971
| 4.34375
| 4
|
# What is the join method in Python?
# "Join is a function in Python, that returns a string by joining the elements of an iterable,
# using a string or character of our choice."
# In the case of join function, the iterable can be a list, dictionary, set, tuple, or even a string itself.
# The string that separates the iterations could be anything.
# It could just be a comma or a full-length string.
# We can even use a blank space or newline character (/n ) instead of a string.
lis = ["john","cena","khali","randy","ortan","sheamus","jinder mahal"]
# suppose i want to write like john and cena and khali and so no , then we write it as
# for item in lis:
# print(item,"and", end="")# end it used to ignore new line
# simply we can use join method
a = " and ".join(lis)
print(a)
b = " , ".join(lis)
print(b)
#output :
# john and cena and khali and randy and ortan and sheamus and jinder mahal
# john , cena , khali , randy , ortan , sheamus , jinder mahal
| true
|
767fc168ca7b5c78be91f3aa94302fc009d73e49
|
kajalubale/PythonTutorial
|
/35.Recursion.py
| 1,457
| 4.5625
| 5
|
# Recursion: Using Function inside the function, is known as recursion
def print_2(str):
print("This is",str)
print_2("kajal")
# output: This is kajal
# but if i used print_2("str") inside the function it shows Recursion error.
# def print_2(str):
# print_2(str)
# print("This is",str)
# print_2("kajal")
# output : [Previous line repeated 996 more times]
# RecursionError: maximum recursion depth exceeded
# Factorial program using Recursive and iterative
# n!= n*n-1*n-2*n-3......1
# n!=n*(n-1)!
def factorial_iterative(n):
'''
:param n: integer
:return: n * n-1 * n-2.....1
'''
fac=1
for i in range(n):
fac=fac*(i+1)
return fac
def factorial_Recursion(n):
'''
:param n: Integer
:return: n * n-1 *n-2.....1
'''
if n==1:
return 1;
else:
return n * factorial_Recursion(n-1)
# 5 * factorial_Recursion(4)
# 5 * 4 * factorial_Recursion(3)
# 5 * 4 * 3 * factorial_Recursion(2)
# 5 * 4 * 3 * 2 * factorial_Recursion(1)
# 0 1 1 2 3 5 8 13
def fibonacci(n):
if n==1:
return 0
elif n==2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
number=int(input("Enter the number:"))
print("Factorial using iterative : ",factorial_iterative(number))
print("Factorial using Recursion : ",factorial_Recursion(number))
print("Fibonacci of number : ",fibonacci(number))
| false
|
060eb25956088487b27ab6fe31077f73b6691857
|
mondler/leetcode
|
/codes_python/0006_ZigZag_Conversion.py
| 1,866
| 4.15625
| 4
|
# 6. ZigZag Conversion
# Medium
#
# 2362
#
# 5830
#
# Add to List
#
# Share
# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
#
# P A H N
# A P L S I I G
# Y I R
# And then read line by line: "PAHNAPLSIIGYIR"
#
# Write the code that will take a string and make this conversion given a number of rows:
#
# string convert(string s, int numRows);
#
#
# Example 1:
#
# Input: s = "PAYPALISHIRING", numRows = 3
# Output: "PAHNAPLSIIGYIR"
# Example 2:
#
# Input: s = "PAYPALISHIRING", numRows = 4
# Output: "PINALSIGYAHRPI"
# Explanation:
# P I N
# A L S I G
# Y A H R
# P I
# Example 3:
#
# Input: s = "A", numRows = 1
# Output: "A"
#
#
# Constraints:
#
# 1 <= s.length <= 1000
# s consists of English letters (lower-case and upper-case), ',' and '.'.
# 1 <= numRows <= 1000
class Solution:
def convert(self, s: str, numRows: int) -> str:
if (numRows == 1) or (numRows > len(s)):
return s
rows = [''] * numRows
row = 0
increment = 1
for c in s:
rows[row] += c
row += increment
if (row == (numRows - 1)) or (row == 0):
increment *= -1
return ''.join(rows)
def convert2(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
rows = [[] for i in range(numRows)]
n = len(s)
for i in range(n):
j = i % (2 * numRows - 2)
if j < numRows:
rows[j].append(s[i])
else:
rows[2 * numRows - 2 - j].append(s[i])
sNew = [row[i] for row in rows for i in range(len(row))]
return ''.join(sNew)
# s = "PAYPALISHIRING"
s = "ABCDEFG"
numRows = 3
Solution().convert(s, numRows)
| true
|
4decf52cae21f429395dbb079c3bada56f7bf326
|
basu-sanjana1619/python_projects
|
/gender_predictor.py
| 683
| 4.21875
| 4
|
#It is a fun program which will tell a user whether she is having a girl or a boy.
test1 = input("Are you craving spicy food? (Y/N) :")
test2 = input("Are you craving sweets? (Y/N) :")
test3 = input("Are you suffering from extreme morning sickeness or hyperemesis (Y/N) :")
test4 = input("Is the baby's heart rate above 150 beats per minute? (Y/N) :")
if test1.upper() == "N" and test2.upper() == "N" and test3.upper() == "Y" and test4.upper() == "Y":
print("CONGRATS!..Its a GIRL!..YAYYY")
elif test1.upper() == "Y" and test2.upper() == "Y" and test3.upper() == "Y" and test4.upper() == "Y":
print("CONGRATS!..Its a GIRL!..YAYYY")
else:
print("CONGRATS!..Its a BOY!..YAYYY")
| true
|
9d77a0ee4b5f9d90d48c67fcc19a686f6cb3b508
|
cookcodeblog/python_work
|
/ch07/visit_poll.py
| 543
| 4.125
| 4
|
# 7-10 Visit Poll
visit_places = {}
poll_active = True
while poll_active:
name = input("What is your name? ")
place = input("If you could visit one place in the world, where would you go? ")
visit_places[name] = place # It is like map.put(key, value)
repeat = input("Would you like to let another person respond? (yes / no)")
if repeat.lower() == "no":
poll_active = False
print("\n---Poll Result---\n")
for name, place in visit_places.items():
print(name.title() + " likes to visie " + place.title() + ".")
| true
|
2e1679facc189bf53edfc0c74160c0cecaa5b194
|
cookcodeblog/python_work
|
/ch06/river.py
| 316
| 4.25
| 4
|
# 6-5 River
rivers = {
'Nile': 'Egypt',
'Changjiang': 'China',
'Ganges River': 'India'
}
for river, location in rivers.items():
print("The " + river + " runs through " + location + ".\n")
for river in rivers.keys():
print(river)
print()
for location in rivers.values():
print(location)
| false
|
bdeab6a046d4236f6dd006dd5c44bdcdf62bf029
|
amigojapan/amigojapan.github.io
|
/8_basics_of_programming/fruits.py
| 580
| 4.71875
| 5
|
fruits=["banana","apple","peach","pear"] # create a list
print(fruits[0]) # print first element of list
print(fruits[3]) # print last element
print("now reprinting all fruits")
for fruit in fruits: # loops thru the fruits list and assigns each values to th>
print(fruit) # prints current "iteration" of the fruit
print("now reprinting all fruits in reverse")
fruits.reverse() # reverses the list
for fruit in fruits:
print(fruit)
print("now printing fruits in alphabetical order")
fruits.sort() # sorts the list in alphabetical order
for fruit in fruits:
print(fruit)
| true
|
c087789647cad25fc983acd3bfceee19ab0a507f
|
Narfin/test_push
|
/controlFlows.py
| 636
| 4.28125
| 4
|
# if, elif, else
def pos_neg(n):
"""Prints whether int n is positive, negative, or zero."""
if n < 0:
print("Your number is Negative... But you already knew that.")
elif n > 0:
print("Your number is super positive! How nice.")
else:
print("Zero? Really? How boring.")
my_num = int(input("Enter a number: "))
pos_neg(my_num)
# for
def reverse_str(word):
"""Prints word in reverse"""
print(word[::-1], " lol") # [begin:end:step], in this case reversing word.
my_word = input("Enter a word to flip: ")
reverse_str(my_word)
# while
x = 8
while (x != 0):
print(x)
x -= 1
| true
|
e80688442c643ed05976d0b872cffb33b1c3c054
|
Minashi/COP2510
|
/Chapter 5/howMuchInsurance.py
| 301
| 4.15625
| 4
|
insurance_Factor = 0.80
def insurance_Calculator(cost):
insuranceCost = cost * insurance_Factor
return insuranceCost
print("What is the replacement cost of the building?")
replacementCost = float(input())
print("Minimum amount of insurance to buy:", insurance_Calculator(replacementCost))
| true
|
0c404764a7b2a2921d926824e0a89883b560ab49
|
cajimon04/Primer-Proyecto
|
/comer_helado.py
| 1,403
| 4.28125
| 4
|
apetece_helado_input = input("¿Te apetece un helado? ¿Si/No?: ").upper()
if apetece_helado_input == "SI":
apetece_helado = True
elif apetece_helado_input == "NO":
apetece_helado = False
else:
print("Te he dicho que me digas si o no. Como no te entiendo pondre no")
apetece_helado = False
tienes_dinero_input = input("¿Tienes dinero para un helado? ¿Si/No?: ").upper()
if tienes_dinero_input == "SI":
tienes_dinero = True
elif tienes_dinero_input == "NO":
tienes_dinero = False
else:
print("Te he dicho que me digas si o no. Como no te entiendo pondre no")
tienes_dinero = False
hay_helados_input = input("¿Hay helados? ¿Si/No?: ").upper()
if hay_helados_input == "SI":
hay_helados = True
elif hay_helados_input == "NO":
hay_helados = False
else:
print("Te he dicho que me digas si o no. Como no te entiendo pondre no")
hay_helados = False
esta_tu_tia_input = input("¿Estas con tu tia? ¿Si/No?: ").upper()
if esta_tu_tia_input == "SI":
esta_tu_tia = True
elif esta_tu_tia_input == "NO":
esta_tu_tia = False
else:
print("Te he dicho que me digas si o no. Como no te entiendo pondre no")
esta_tu_tia = False
puedes_permitirtelo = tienes_dinero_input == "SI" or esta_tu_tia_input == "SI"
if apetece_helado == True and puedes_permitirtelo == True and hay_helados == True:
print("Pues cometelo")
else:
print("Pues na")
| false
|
039b84d58b8410e1017b71395ac44082e19323ec
|
milolou/pyscript
|
/stripMethod.py
| 1,756
| 4.65625
| 5
|
# Strip function.
'''import re
print('You can strip some characters by strip method,\n
just put the characters you want to strip in the parenthese\n
followed function strip')
print('Please input the text you wanna strip.')
text = input()
print('Please use the strip function.')
def strip(string):
preWhiteSpace = re.compile(r'^\s+')
epiWhiteSpace = re.compile(r'\s+$')
specificPattern = re.compile(r'%s'%string)
if string == None:
textOne = preWhiteSpace.sub('',text)
textTwo = epiWhiteSpace.sub('',text)
print('The stripped text is:\n' + textTwo)
return textTwo
else:
textThree = specificPattern.sub('',text)
print('The stripped text is:\n' + textThree)
return textThree
# start the program.
functionCall = input()
n = len(functionCall)
if n > 7:
stripString = functionCall[6:(n-1)]
elif n == 7:
stripString = None
else:
print('The input is not valid.')
strip(stripString)'''
import re
# Another version.
def strip(text,characters):
preWhiteSpace = re.compile(r'^\s+')
epiWhiteSpace = re.compile(r'\s+$')
specificPattern = re.compile(r'%s'%characters)
if characters == None:
textOne = preWhiteSpace.sub('',text)
textTwo = epiWhiteSpace.sub('',text)
print('The stripped text is:\n' + textTwo)
return textTwo
else:
textThree = specificPattern.sub('',text)
print('The stripped text is:\n' + textThree)
return textThree
# start the program.
print('please use the strip function.')
functionCall = input()
n = len(functionCall)
coreString = functionCall[7:(n-2)]
variableList = coreString.split("','")
newText = variableList[0]
newCharacters = variableList[1]
strip(newText,newCharacters)
| true
|
3a9572bd678ccbb324d12d945f3d19f4ae64619b
|
BenjiKCF/Codewars
|
/day197.py
| 403
| 4.15625
| 4
|
def valid_parentheses(string):
new_bracket = []
for i in string:
if i.isalpha():
pass
else:
new_bracket.append(i)
new_bracket = ''.join(new_bracket)
while '()' in new_bracket:
new_bracket = new_bracket.replace('()', '')
return new_bracket==''
print valid_parentheses("hi(hi)()")# ,True)
# while '{}' in s or '()' in s or '[]' in s:
| false
|
d00c5dd8c996aaed2784a30a925122bee2a4ac9d
|
rafaeljordaojardim/python-
|
/basics/exceptions.py
| 1,891
| 4.25
| 4
|
# try / Except / Else / Finally
for i in range(5):
try:
print(i / 0)
except ZeroDivisionError as e:
print(e, "---> division by 0 is not allowed")
for i in range(5):
try:
print(i / 0)
except NameError: # it doesn't handle ZeroDivisionError
print("---> division by 0 is not allowed")
for i in range(5):
try:
print(i / 1)
except ZeroDivisionError: # it doesn't handle ZeroDivisionError
print("---> division by 0 is not allowed")
except NameError:
print("---> division by 0 is not allowed")
except ValueError:
print("---> division by 0 is not allowed")
# if it doesn't raise any exception
try:
print(4 / 2)
except NameError: # it doesn't handle ZeroDivisionError
print("---> division by 0 is not allowed")
else:
print("if it doesn't raise any exception")
try:
print(4 / 2)
except NameError: # it doesn't handle ZeroDivisionError
print("---> division by 0 is not allowed")
finally:
print("it executes anyway if it raises error or not")
#Try / Except / Else / Finally - handling an exception when it occurs and telling Python to keep executing the rest of the lines of code in the program
try:
print(4/0) #in the "try" clause you insert the code that you think might generate an exception at some point
except ZeroDivisionError:
print("Division Error!") #specifying what exception types Python should expect as a consequence of running the code inside the "try" block and how to handle them
else:
print("No exceptions raised by the try block!") #executed if the code inside the "try" block raises NO exceptions
finally:
print("I don't care if an exception was raised or not!") #executed whether the code inside the "try" block raises an exception or not
#result of the above block
# Division Error!
# I don't care if an exception was raised or not!
| true
|
7521cbf4b76c785fe8d0b78e837fba5cdf41cce1
|
evanlihou/msu-cse231
|
/clock.py
| 1,436
| 4.4375
| 4
|
"""
A clock class.
"""
class Time():
"""
A class to represent time
"""
def __init__(self, __hour=0, __min=0, __sec=0):
"""Constructs the time class.
Keyword Arguments:
__hour {int} -- hours of the time (default: {0})
__min {int} -- minutes of the time (default: {0})
__sec {int} -- seconds of the time (default: {0})
"""
self.hour = __hour
self.min = __min
self.sec = __sec
def __repr__(self):
"""Creates the shell representation of a time with proper formatting
Returns:
string -- the representation of the time
"""
outstr = "Class Time: {:0>2d}:{:0>2d}:{:0>2d}"
return outstr.format(self.hour, self.min, self.sec)
def __str__(self):
"""Creates the string representation of a time with proper formatting
Returns:
string -- the representation of the time
"""
outstr = "{:0>2d}:{:0>2d}:{:0>2d}"
return outstr.format(self.hour, self.min, self.sec)
def from_str(self, time_str):
"""Updates the Time in place with a given str
Arguments:
time_str {str} -- Time to convert with format hh:mm:ss
"""
time_lst = time_str.split(":")
self.hour = int(time_lst[0])
self.min = int(time_lst[1])
self.sec = int(time_lst[2])
| true
|
f5d77a708522b6febacc4c1e43704d1c63a2d07d
|
evanlihou/msu-cse231
|
/proj01.py
| 1,123
| 4.3125
| 4
|
###########################################################
# Project #1
#
# Algorithm
# Prompt for rods (float)
# Run conversions to other units
# Print those conversions
###########################################################
# Constants
ROD = 5.0292 # meters
FURLONG = 40 # rods
MILE = 1609.34 # meters
FOOT = 0.3048 # meters
WALKING_SPEED = 3.1 # miles per hour
# Take input and convert to float inline, then print
rods = float(input("Input rods: "))
print("You input", rods, "rods.\n")
# Run conversions, but don't round yet for accuracy
meters = rods * ROD
feet = meters / FOOT
miles = meters / MILE
furlongs = rods / FURLONG
walking_hours = miles / WALKING_SPEED
walking = walking_hours * 60 # Converts hours to minutes of walking
# Round all floats for prettier printing
meters = round(meters, 3)
feet = round(feet, 3)
miles = round(miles, 3)
furlongs = round(furlongs, 3)
walking = round(walking, 3)
# Print conversions
print("Conversions")
print("Meters:", meters)
print("Feet:", feet)
print("Miles:", miles)
print("Furlongs:", furlongs)
print("Minutes to walk", rods, "rods:", walking)
| true
|
4fc1e7a055c830baa4ea154de82a4568a60b3bdf
|
alicevillar/python-lab-challenges
|
/conditionals/conditionals_exercise1.py
| 1,058
| 4.46875
| 4
|
#######################################################################################################
# Conditionals - Lab Exercise 1
#
# Use the variable x as you write this program. x will represent a positive integer.
# Write a program that determines if x is between 0 and 25 or between 75 and 100.
# If yes, print the message:_ is between 0 and 25 or 75 and 100, where the blank would be the value of x.
# The program should do nothing if the value of x does not fit into either range.
#
#Expected Output
# If x is 8, then the output would be: 8 is between 0 and 25 or 75 and 100.
# If x is 80, then the output would be: 80 is between 0 and 25 or 75 and 100.
# If x is 50, then the output would be blank (your program does not print anything).
#######################################################################################################
x = 8
if x <= 25:
print(str(x) + " is between 0 and 25")
elif x > 75 and x < 100:
print(str(x) + " is between 75 and 100")
# Output => 8 is between 0 and 25
| true
|
56870e9f3f322e09042d9e10312ed054fa033fa2
|
rghosh96/projecteuler
|
/evenfib.py
| 527
| 4.15625
| 4
|
#Define set of numbers to perform calculations on
userRange = input("Hello, how many numbers would you like to enter? ")
numbers = [0] * int(userRange)
#print(numbers)
numbers[0] = 0
numbers[1] = 1
x = numbers[0]
y = numbers[1]
i = 0
range = int(userRange)
#perform fibonacci, & use only even values; add sums
sum = 0
while x < int(userRange):
if x % 2 == 0:
#print (x, end=", ")
sum = sum + x
z = x + y
x = y
y = z
#i = i + 1
print("The total sum of the even-valued terms is:", sum)
| true
|
f87bafd4dbf5b69b9eda0f1baa5a87543b881998
|
biniama/python-tutorial
|
/lesson4_list_tuple_dictionary/dictionary.py
| 953
| 4.375
| 4
|
def main():
# dictionary has a key and a value and use colon (:) in between
# this is a very powerful and useful data type
dictionary = {"Book": "is something to read"}
print(dictionary)
biniam_data = {
"name": "Biniam",
"age": 32,
"profession": "Senior Software Engineer",
"spouse": {
"name": "Kidan",
"age": 29
}
}
print(biniam_data)
hareg_data = {
"name": "Hareg",
"age": "26",
"profession": "Junior Programmer and Business Manager"
}
print(hareg_data)
# Using for loop to iterate/repeat over a dictionary
# Exercise: print Hareg's data in capital letter and as a statement
for key in hareg_data:
#print(key.upper() + ' IS ' + hareg_data.get(key).upper())
# alternative way of writing
print(f'{key.upper()} IS {hareg_data.get(key).upper()}')
if __name__ == '__main__':
main()
| false
|
3c21bd12834e39d8fd1c53bb5d9885c2cc75a360
|
biniama/python-tutorial
|
/lesson6_empty_checks_and_logical_operators/logical_operators.py
| 490
| 4.1875
| 4
|
def main():
students = ["Kidu", "Hareg"]
name = input("What is your name? ")
if name not in students:
print("You are not a student")
else:
print("You are a student")
# if name in students:
# print("You are a student")
# else:
# print("You are not a student")
# Second example
value = False
if not value:
print("Value is false")
else:
print("Value is true")
if __name__ == '__main__':
main()
| true
|
bac2a9c57de523788893acc83ddfb37a2e10ce0d
|
biniama/python-tutorial
|
/lesson2_comment_and_conditional_statements/conditional_if_example.py
| 1,186
| 4.34375
| 4
|
def main():
# Conditional Statements( if)
# Example:
# if kidu picks up her phone, then talk to her
# otherwise( else ) send her text message
# Can be written in Python as:
# if username is ‘kiduhareg’ and password is 123456, then go to home screen.
# else show error message
# Conditional statement example
# Assumption
# child is someone who is less than 10 years old
# young is someone who is between 10 - 30 years old
# adult is someone who is between 30 - 50 years old
# accepting input from the user
ageString = input('Please enter your age ')
age = int(ageString) # converts string to integer
if age < 10:
print('child')
elif age >= 10 and age < 30: # T and F = F, T and T = T
print('young')
elif age > 30 and age <= 50:
print('adult')
else:
print('old - sheba')
# another example with ‘if’ only
# TODO: Un comment it to execute
# if age < 10:
# print('child')
# if age >= 10 and age <= 30: # T and F = F, T and T = T
# print('young')
# if age > 30:
# print('adult')
if __name__ == "__main__":
main()
| true
|
62ac86c00c6afcbb16dcc58a1a12bc426070001a
|
aiperi2021/pythonProject
|
/day_4/if_statement.py
| 860
| 4.5
| 4
|
# Using true vs false
is_Tuesday = True
is_Friday = True
is_Monday = False
is_Evening = True
is_Morning = False
if is_Monday:
print("I have python class")
else:
print("I dont have python class")
# try multiple condition
if is_Friday or is_Monday:
print("I have python class")
else:
print("I dont have python class")
if is_Friday and is_Evening:
print("I have python class")
else:
print("I dont have python class")
if is_Friday and is_Morning:
print("I have python class")
else:
print("I dont have python class")
if is_Friday and not is_Morning:
print("I have python class")
else:
print("I dont have python class")
if is_Friday and is_Morning:
print("I dont have python class")
elif is_Monday and is_Evening:
print("I have python class")
else:
print("I dont have python class in any of this time ")
| true
|
f6c60e2110d21c44f230ec710f3b74631b772195
|
aiperi2021/pythonProject
|
/day_7/dictionar.py
| 298
| 4.3125
| 4
|
# Mapping type
## Can build up a dict by starting with the the empty dict {}
## and storing key/value pairs into the dict like this:
## dict[key] = value-for-that-key
#create dict
dict = {}
dict['a'] = 'alpha'
dict['g'] = 'gamma'
dict['o'] = 'omega'
for key in dict:
print(key, '->', dict[key])
| true
|
00e3304a1b6216c18d5cd8fc9ea5c266ed72149e
|
Vaspe/Coursera_Python_3_Programming_Michigan
|
/Python_Project_pillow_tesseract_and_opencv_Mod5/Week2_Tesseract/ipywidgets_stuff.py
| 2,172
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 19:49:51 2020
@author: Vasilis
"""
# In this brief lecture I want to introduce you to one of the more advanced features of the
# Jupyter notebook development environment called widgets. Sometimes you want
# to interact with a function you have created and call it multiple times with different
# parameters. For instance, if we wanted to draw a red box around a portion of an
# image to try and fine tune the crop location. Widgets are one way to do this quickly
# in the browser without having to learn how to write a large desktop application.
#
# Lets check it out. First we want to import the Image and ImageDraw classes from the
# PILLOW package
from PIL import Image, ImageDraw
# Then we want to import the interact class from the widgets package
from ipywidgets import interact
# We will use interact to annotate a function. Lets bring in an image that we know we
# are interested in, like the storefront image from a previous lecture
image=Image.open('readonly/storefront.png')
# Ok, our setup is done. Now we're going to use the interact decorator to indicate
# that we want to wrap the python function. We do this using the @ sign. This will
# take a set of parameters which are identical to the function to be called. Then Jupyter
# will draw some sliders on the screen to let us manipulate these values. Decorators,
# which is what the @ sign is describing, are standard python statements and just a
# short hand for functions which wrap other functions. They are a bit advanced though, so
# we haven't talked about them in this course, and you might just have to have some faith
@interact(left=100, top=100, right=200, bottom=200)
# Now we just write the function we had before
def draw_border(left, top, right, bottom):
img=image.copy()
drawing_object=ImageDraw.Draw(img)
drawing_object.rectangle((left,top,right,bottom), fill = None, outline ='red')
display(img)
# Jupyter widgets is certainly advanced territory, but if you would like
# to explore more you can read about what is available here:
# https://ipywidgets.readthedocs.io/en/stable/examples/Using%20Interact.html
| true
|
0229eae841f5fec0563ad643a508650a3b1b235c
|
nadiiia/cs-python
|
/extracting data with regex.py
| 863
| 4.15625
| 4
|
#Finding Numbers in a Haystack
#In this assignment you will read through and parse a file with text and numbers.
#You will extract all the numbers in the file and compute the sum of the numbers.
#Data Format
#The file contains much of the text from the introduction of the textbook except that random numbers are inserted throughout the text.
#Handling The Data
#The basic outline of this problem is to read the file, look for integers using the re.findall(), looking for a regular expression of '[0-9]+' and then converting the extracted strings to integers and summing up the integers.
import re
name = raw_input("Enter file:")
if len(name) < 1 : name = "regex_sum_212308.txt"
handle = open(name)
sum=0
for line in handle:
stuff=re.findall('[0-9]+',line) #list of strings
for str in stuff:
num=int(str)
sum=sum+num
print 'Summ', sum
| true
|
59bb55684bffde3abd337b0617af2117a9e4abb4
|
jinwei15/java-PythonSyntax-Leetcode
|
/LeetCode/src/FindAllAnagramsinaString.py
| 2,464
| 4.1875
| 4
|
# 438. Find All Anagrams in a String
# Easy
# 1221
# 90
# Favorite
# Share
# Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
# Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
# The order of output does not matter.
# Example 1:
# Input:
# s: "cbaebabacd" p: "abc"
# Output:
# [0, 6]
# Explanation:
# The substring with start index = 0 is "cba", which is an anagram of "abc".
# The substring with start index = 6 is "bac", which is an anagram of "abc".
# Example 2:
# Input:
# s: "abab" p: "ab"
# Output:
# [0, 1, 2]
# Explanation:
# The substring with start index = 0 is "ab", which is an anagram of "ab".
# The substring with start index = 1 is "ba", which is an anagram of "ab".
# The substring with start index = 2 is "ab", which is an anagram of "ab".
# Accepted
# 94,870
# Submissions
# 268,450
# my first idea is that to remain a hashtable window and keep looping the the long string form 0 to len(long string) - len(short string)
class Solution:
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
block = dict()
winBlock = dict()
returnList = list()
for ch in p:
block[ch] = block.get(ch, 0) + 1
for i in range(0, len(s)):
if i - len(p) >= 0:
occur = winBlock.get(s[i - len(p)]) - 1
if occur == 0:
del winBlock[s[i - len(p)]]
else:
winBlock[s[i - len(p)]] = occur
winBlock[s[i]] = winBlock.get(s[i], 0) + 1
# print(winBlock)
# print(i+1-len(p))
if winBlock == block:
returnList.append(i + 1 - len(p))
return returnList
# def findAnagrams(self, s, p):
# """
# :type s: str
# :type p: str
# :rtype: List[int]
# """
# block = dict()
# returnList = list()
# for ch in p:
# block[ch] = block.get(ch,0)+1
# for i in range(0,len(s)-len(p) + 1):
# winBlock = dict() # window of length len(p)
# for ch in s[i:i+len(p)]:
# winBlock[ch] = winBlock.get(ch,0)+1
# if winBlock == block:
# returnList.append(i)
# return returnList
| true
|
795cbf40f98ad3a775af177e11913ce831752854
|
MenacingManatee/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/5-text_indentation.py
| 504
| 4.21875
| 4
|
#!/usr/bin/python3
'''Prints a string, adding two newlines after each of the following:
'.', '?', and ':'
Text must be a string'''
def text_indentation(text):
'''Usage: text_indentation(text)'''
if not isinstance(text, str):
raise TypeError('text must be a string')
flag = 0
for char in text:
if flag is 1 and char is ' ':
continue
print(char, end="")
flag = 0
if char in ['.', ':', '?']:
print('\n')
flag = 1
| true
|
1ee074079729475b25368a84a39006e5306aec28
|
MenacingManatee/holbertonschool-higher_level_programming
|
/0x07-python-test_driven_development/0-add_integer.py
| 571
| 4.375
| 4
|
#!/usr/bin/python3
'''Adds two integers
If floats are sent, casts to int before adding'''
def add_integer(a, b=98):
'''Usage: add_integer(a, b=98)'''
if (a == float("inf") or (not isinstance(a, int) and not
isinstance(a, float)) or a != a):
raise TypeError('a must be an integer')
elif (b == float("inf") or (not isinstance(b, int) and not
isinstance(b, float)) or b != b or
b is float("inf")):
raise TypeError('b must be an integer')
return (int(a) + int(b))
| false
|
d5d557f24d2e74375e95cf22f7df5d2ed5587e8c
|
MenacingManatee/holbertonschool-higher_level_programming
|
/0x0B-python-input_output/4-append_write.py
| 321
| 4.3125
| 4
|
#!/usr/bin/python3
'''Defines a function that appends a string to a text file (UTF8)
and returns the number of characters written:'''
def append_write(filename="", text=""):
'''Usage: append_write(filename="", text="")'''
with open(filename, "a") as f:
f.write(text)
f.close()
return len(text)
| true
|
d91f8e862b939ab0131fab2bf97c96681fba005a
|
MenacingManatee/holbertonschool-higher_level_programming
|
/0x0B-python-input_output/100-append_after.py
| 595
| 4.1875
| 4
|
#!/usr/bin/python3
'''Defines a function that inserts a line of text to a file,
after each line containing a specific string'''
def append_after(filename="", search_string="", new_string=""):
'''Usage: append_after(filename="", search_string="", new_string="")'''
with open(filename, "r") as f:
res = []
s = f.readline()
while (s != ""):
res.append(s)
if search_string in s:
res.append(new_string)
s = f.readline()
f.close()
with open(filename, "w") as f:
f.write("".join(res))
f.close()
| true
|
faefe53c66424e822ce06109fc4d095f013e64c0
|
MenacingManatee/holbertonschool-higher_level_programming
|
/0x06-python-classes/102-square.py
| 1,442
| 4.40625
| 4
|
#!/usr/bin/python3
'''Square class'''
class Square:
'''Defines a square class with logical operators available based on area,
as well as size and area'''
__size = 0
def area(self):
'''area getter'''
return (self.__size ** 2)
def __init__(self, size=0):
'''Initializes size'''
self.__size = size
@property
def size(self):
'''size getter'''
return (self.__size)
@size.setter
def size(self, value):
'''size setter'''
if (type(value) is int):
if (value >= 0):
self.__size = value
else:
raise ValueError('size must be >= 0')
else:
raise TypeError('size must be an integer')
def __eq__(self, other):
'''Sets __eq__ to check area'''
return (self.area() == other.area())
def __lt__(self, other):
'''Sets __lt__ to check area'''
return (self.area() < other.area())
def __gt__(self, other):
'''Sets __gt__ to check area'''
return (self.area() > other.area())
def __ne__(self, other):
'''Sets __ne__ to check area'''
return (not (self.area() == other.area()))
def __le__(self, other):
'''Sets __le__ to check area'''
return (self.area() <= other.area())
def __ge__(self, other):
'''Sets __ge__ to check area'''
return (self.area() >= other.area())
| true
|
61a293256dff4c87004e8627f0afadd9a9d202ca
|
shea7073/More_Algorithm_Practice
|
/2stack_queue.py
| 1,658
| 4.15625
| 4
|
# Create queue using 2 stacks
class Stack(object):
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def size(self):
return len(self.items)
def pop(self):
return self.items.pop()
def push(self, item):
self.items.append(item)
# Works only if entire set is passed during enqueue before any dequeueing
class Queue2Stacks(object):
def __init__(self):
self.stack1 = Stack()
self.stack2 = Stack()
def enqueue(self, element):
for item in element:
self.stack1.push(item)
while not self.stack1.isEmpty():
current = self.stack1.pop()
self.stack2.push(current)
return self.stack2
def dequeue(self):
return self.stack2.pop()
# Works better if enqueueing is happening randomly
# instead of all at once at the beginning
class Queue2Stacks2(object):
def __init__(self):
self.stack1 = Stack()
self.stack2 = Stack()
def enqueue(self, element):
self.stack1.push(element)
def dequeue(self):
while not self.stack1.isEmpty():
current = self.stack1.pop()
self.stack2.push(current)
answer = self.stack2.pop()
while not self.stack2.isEmpty():
current = self.stack2.pop()
self.stack1.push(current)
return answer
queue = Queue2Stacks2()
queue.enqueue(1)
queue.enqueue(2)
print(queue.dequeue())
queue.enqueue(5)
queue.enqueue(6)
print(queue.dequeue())
print(queue.dequeue())
print(queue.dequeue())
| true
|
29436d6802295d6eb8992d2f510427219d29f35b
|
Mark9Mbugua/Genesis
|
/chatapp/server.py
| 1,892
| 4.125
| 4
|
import socket #helps us do stuff related to networking
import sys
import time
#end of imports ###
#initialization section
s = socket.socket()
host = socket.gethostname() #gets the local hostname of the device
print("Server will start on host:", host) #gets the name of my desktop/host of the whole connection(when I run the program)
port = 8080 #make sure the port is on my local host(my computer)
s.bind((host,port)) #binds the socket with the host and the port
print("")
print("Server done binding to host and port successfully")
print("")
print("Server is waiting for incoming connections")
print("")
#we can now start listening to incoming connections
s.listen(1) #we accept only one connection
conn,addr = s.accept()
print("")
#conn is assigned to the socket itself which is the physical socket (s?) coming from the client
#addr is assigned to the IP address of the client that we'll be connecting
print(addr, "Has connected to the server and is now online...") #prints the IP Address/Hostname of the client that is connected to us
print("")
#now move on to the client side.
#we're back!
while 1:
message = input(str(">>"))#for a decoded message
message = message.encode()#to change this message into bytes since s/w interface only supports bytes
conn.send(message)#conn is the client that is connected to us
print("message has been sent..")
print("")
#piece of code that will accept the message and display it
incoming_message = conn.recv(1024) #when you type a message and press enter, it is going to be stored here.
#we need to decode the message since we had encoded it
incoming_message = incoming_message.decode()
print("Server: ", incoming_message)
print("")
#so far we have a one-sided chat
#we need to therefore put it in a loop
| true
|
80192a8c2357a805072936ccb99b9dabc8e27778
|
GANESH0080/Python-WorkPlace
|
/ReadFilePractice/ReadDataOne.py
| 291
| 4.25
| 4
|
# Created an File
file = open("ReadFile.txt" ,"w+")
# Enter string into the file and stored into variable
file.write("Ganesh Salunkhe")
# Open the for for reading
file = open("ReadFile.txt" ,"r")
# Reading the file and store file date into variable
re= file.read()
# Printing file data
print(re)
| true
|
de3cf5eec6681b391cddf58e4f48676b8e84e727
|
KapsonLabs/CorePythonPlayGround
|
/Decorators/instances_as_decorators.py
| 660
| 4.28125
| 4
|
"""
1. Python calls an instance's __call__()
when it's used as a decorator
2. __call__()'s return value is used as the
new function
3. Creates groups of callables that you can
dynamically control as a group
"""
class Trace:
def __init__(self):
self.enabled = True
def __call__(self, f):
def wrap(*args, **kwargs):
if self.enabled:
print('Calling {}'.format(f))
return f(*args, **kwargs)
return wrap
tracer = Trace()
@tracer
def rotate_list(l):
return l[1:] + [l[0]]
l = [1,2,3]
t = rotate_list(l)
print(t)
#disable the tracer
tracer.enabled = False
t = rotate_list(l)
print(t)
| true
|
ee9cf22dae8560c6ee899431805231a107b8f0e6
|
smalbec/CSE115
|
/conditionals.py
| 1,110
| 4.4375
| 4
|
# a and b is true if both a is true and b is true. Otherwise, it is false.
# a or b is true if either a is true or b is true. Otherwise, it is false.
#
# if morning and workday:
# wakeup()
#
# elif is when you need another conditional inside an if statement
def higher_lower(x):
if x<24:
return("higher")
elif x>24:
return("lower")
else:
return("correct u dumb")
print(higher_lower(24))
def categorize(x):
if x<20:
return("low")
elif x>=20 and x<36:
return("medium")
else:
return("high")
#or the more optimal one
def categorize2(x):
if x<15:
return("low")
elif 15<=x<=24:
return("medium")
else:
return("high")
print(categorize2(60))
def categorizelen(x):
if len(x)<5:
return("short")
elif 5<=len(x)<=14:
return("medium")
else:
return("long")
def compute_xp(x,y):
if y==False:
return(92884)
else:
return(92884 + x)
def replacement(x):
x = x.replace("a", "j")
return(x)
print(replacement("alalala"))
| true
|
4c403bd4174b1b71461812f9926e6dac87df2610
|
JasmanPall/Python-Projects
|
/lrgest of 3.py
| 376
| 4.46875
| 4
|
# This program finds the largest of 3 numbers
num1 = float(input(" ENTER NUMBER 1: "))
num2 = float(input(" ENTER NUMBER 2: "))
num3 = float(input(" ENTER NUMBER 3: "))
if num1>num2 and num1>num3:
print(" NUMBER 1 is the greatest")
elif num2>num1 and num2>num3:
print(" NUMBER 2 is the greatest")
else:
print(" NUMBER 3 is the greatest")
| true
|
c8b69c1728f104b4f308647cc72791e49d84e472
|
JasmanPall/Python-Projects
|
/factors.py
| 370
| 4.21875
| 4
|
# This program prints the factors of user input number
num = int(input(" ENTER NUMBER: "))
print(" The factors of",num,"are: ")
def factors(num):
if num == 0:
print(" Zero has no factors")
else:
for loop in range(1,num+1):
if num % loop == 0:
factor = loop
print(factor)
factors(num)
| true
|
9718066d59cdbd0df8e277d5256fd4d7bb10d90c
|
JasmanPall/Python-Projects
|
/Swap variables.py
| 290
| 4.25
| 4
|
# This program swaps values of variables.
a=0
b=1
a=int(input("Enter a: "))
print(" Value of a is: ",a)
b=int(input("Enter b: "))
print(" Value of b is: ",b)
# Swap variable without temp variable
a,b=b,a
print(" \n Now Value of a is:",a)
print(" and Now Value of b is:",b)
| true
|
87dfe7f1d78920760c7e1b7131f1dd941e284e5a
|
JasmanPall/Python-Projects
|
/odd even + - 0.py
| 557
| 4.375
| 4
|
# This program checks whether number is positive or negative or zero
number=float(input(" Enter the variable u wanna check: "))
if number < 0:
print("THIS IS A NEGATIVE NUMBER")
elif number == 0:
print(" THE NUMBER IS ZERO")
else:
print(" THIS IS A POSITIVE NUMBER")
if number%2 == 0:
print("The number %i is even number" %number)
else:
print("The Number %i is odd" % number)
#loop=float(input(" DO U WISH TO CONTINUE: "))
#if loop == "Y" or "y":
#elif loop == "N" or "n":
# break:
| true
|
17739c9ef743a4eea06fc2de43261bfc72c21678
|
elijahwigmore/professional-workshop-project-include
|
/python/session-2/stringfunct.py
| 1,612
| 4.21875
| 4
|
string = "Hello World!"
#can extract individual characters using dereferencing (string[index])
#prints "H"
print string[0]
#prints "e"
print string[1]
#print string[2]
#Slicing
#of form foo[num1:num2] - extract all elements from and including num1, up to num2 (but not including element at num2)
#all of the below prints World
print string[-6:-1]
print string[6:-1]
print string[6:11]
#print everything before the space: prints Hello
print string[:5]
#print everything after the space: World!
print string[6:]
sentence = "I am a teapot!"
print sentence.split(" ")
#***LISTS***
myList = ["a word", 3, 3, 4.6, "end"]
print myList
print myList[0]
print myList[1:]
print myList + [5, 4, 5, 67]
myList.append([1, 2, 3, 4])
print myList
myList.remove('end')
print myList
print len(myList)
myList[1] = 'one'
print myList
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in nums:
if ((i % 2) == 1):
nums.remove(i)
print nums
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in nums:
if ((i % 2) == 1):
nums = nums[0:i-1] + nums[i+1:]
print nums
#***DICTIONARIES***
myDict = {'one':1, 'two':2, 'three':3, 'four':4}
print myDict['two']
myDict['five'] = 5
print myDict
for i in myDict:
print myDict[i]
months = {'jan':1, 'feb':2, 'mar':3, 'apr':4, 'may':5, 'jun':6, 'jul':7, 'aug':8, 'sep':9, 'oct':10, 'nov':11, 'dec':12}
print ('apr' in months)
#PRACTICE:
#Input: "A man a plan a canal Panama" -> {'A':1, 'a':2, 'man':1, 'plan':1, 'Panama':1, 'canal':1}
| true
|
2244fcdea5ed252a02782ef5fb873fbb5c91b411
|
lohitbadiger/interview_questions_python
|
/3_prime_number.py
| 403
| 4.25
| 4
|
# given number is prime or not
def prime_num_or_not(n):
if n>1:
for i in range(2,n):
if (n%i)==0:
print('given number is not prime')
print(i,"times",n//i,"is",n)
break
else:
print('given number is prime')
else:
print('given number is not prime')
# n=input('enter the number')
n=3
prime_num_or_not(n)
| false
|
84f0b4335f058c440ac748f165fd7e87ef1e08b2
|
lohitbadiger/interview_questions_python
|
/6_letter_reverse.py
| 724
| 4.1875
| 4
|
#letters reverse in strings
def reverse_letters(string):
if len(string)==1:
return string
return reverse_letters(string[1:]) + (string[0])
# string=input('enter string')
string='lohit badiger'
print(reverse_letters(string))
print('----------------------------')
def reverse_letter2(string):
string = "".join(reversed(string))
print(string)
string='lohit badiger'
reverse_letter2(string)
print('----------------------------')
def reverse_letetr(string):
string=string[::-1]
print(string)
string='lohit badigers'
reverse_letetr(string)
print('----------------------------')
def reverse_string(string):
ss=''
for s in string:
s=s+ss
print(ss)
reverse_string('im going')
| false
|
50a3e1da1482569c0831227e0e4b5ead75433d43
|
PatrickKalkman/pirplepython
|
/homework01/main.py
| 1,872
| 4.59375
| 5
|
"""
Python Is Easy course @Pirple.com
Homework Assignment #1: Variables
Patrick Kalkman / patrick@simpletechture.nl
Details:
What's your favorite song?
Think of all the attributes that you could use to describe that song. That is:
all of it's details or "meta-data". These are attributes like "Artist",
"Year Released", "Genre", "Duration", etc. Think of as many different
characteristics as you can. In your text editor, create an empty file and name
it main.py.
Now, within that file, list all of the attributes of the song, one after
another, by creating variables for each attribute, and giving each variable
a value.
"""
# Favorite Song: Tennessee Whiskey by Chris Stapleton
Artist = "Chris Stapleton"
ArtistGender = "Male"
Title = "Tenessee Whiskey"
Album = "Traveller"
NumberOfSongsOnAlbum = 14
Year = 2015
Genre = "Country"
DurationInSeconds = 293
OriginalAutor = "David Allan Coe"
Country = "United States"
TimesPlayedOnSpotify = 287881875
PriceInDollars = 2.75
Bio = "Christopher Alvin Stapleton is an American singer-songwriter, " + \
"guitarist, and record producer.x He was born in Lexington, Kentucky," + \
" and grew up in Staffordsville, Kentucky, until moving to Nashville, " + \
"Tennessee, in 2001 to pursue a career in music writing songs. " + \
" Subsequently, Stapleton signed a contract with Sea Gayle Music to " + \
"write and publish his music."
WikipediaLink = "https://en.wikipedia.org/wiki/Chris_Stapleton"
print(f"Title: {Title}")
print(f"Artist: {Artist}")
print(f"Gender: {ArtistGender}")
print(f"Album: {Album}")
print(f"Number of songs on album: {NumberOfSongsOnAlbum}")
print(f"Year: {Year}")
print(f"Genre: {Genre}")
print(f"Country: {Country}")
print(f"Duration: {DurationInSeconds} s")
print(f"Original autor: {OriginalAutor}")
print(f"Number of plays on Spotify: {TimesPlayedOnSpotify}")
print(f"Price: ${PriceInDollars}")
print(f"Bio: {Bio}")
print(f"Wikipedia link: {WikipediaLink}")
| true
|
b884cc6e8e590ef59a9c3d69cad3b5d574368916
|
Ardrake/PlayingWithPython
|
/string_revisited.py
| 1,674
| 4.21875
| 4
|
str1 = 'this is a sample string.'
print('original string>>', str1,'\n\n')
print('atfer usig capitalising>>',str1.capitalize())
#this prints two instances of 'is' because is in this as well
print('using count method for "is" in the given string>>', str1.count('is'))
print('\n\n')
print('looking fo specfic string literal with spaces>>', str1.count(' is '),'\n')
print('using find method for "amp" in the string>>', str1.find('amp'),'\n')
print('checkin if sring.isupper()>>',str1.isupper(),'\n')
print(bin(255)) #prints in binary
stru = str1.upper()
print('making string upper case>>',stru,'\n\n')
print('now testing new string.isupper()>>', stru.isupper(),'\n\n')
print(str1.upper().isupper())
print('lower string "',stru.lower(),'"')
print('\n\nTitle method', str1.title())
##working with spaces in the string
str2 = ' five taps of the SPACEBAR '
print('\n\n',str2)
print('using s.lstrip() to remove all the whitespaces from the left\n\
', str2.lstrip(),'\n')
print('now on the right\n', str2.rstrip(),'next letter \n')
print('this is about removing whitespaces from both sides\n',str2.strip())
# replacing text in a string
print(str1.replace('sample', 'testing')) #replaces the first instance in the string
#splitting string into a list
str3 = str1.split(' ')
print(str3)
#joining it back together
str4 = ' '.join(str3) #because lists don't have join() method quoted string is necessary
print(str4)
##formatting a string
## there are two ways to do that
s = '%s is %d years old' % ('Harry', 29) #old c style still supported by python3
print(s)
t= '{0} is {1} years old and can pass {2} string data'.format('Harry', 29, 'third')
print(t)
| true
|
93f34502472cddeb27d9d3404fb0f4f5269bb920
|
ladipoore/PythonClass
|
/hass4.py
| 1,239
| 4.34375
| 4
|
""" I won the grant for being the most awesome. This is how my reward is calculated.
My earnings start at $1 and can be doubled or tripled every month.
Doubling the amount can be applied every month and tripling the amount can be applied every other month.
Write a program to maximize payments given the number of months by user. """
#Introducing the program
Welcome = "Congratulations!"
Welcome2 = "If you are using this program, that means you won the You-Are-Awesome award!"
print (100*"*")
print(format(Welcome,'^100s'))
print(format(Welcome2,'^100s'))
print (100*"*")
print("\n")
print("I am sure you are dying to know how much you won, let's compute!")
print("\n")
#Calculating and printing out the results.
amount = 1
months = int(input("For how many months did they say you will receive payments? "))
print("\n")
print("Here are the monthly installment amounts:")
print("\n")
for strategy in range(1,months+1,1):
if strategy == 1:
payment = "$"+str(amount)
print("Month ",strategy, ":", payment.rjust(50))
elif strategy %2 == 0:
amount *= 2
payment = "$"+str(amount)
print("Month ",strategy, ":", payment.rjust(50))
else:
amount *= 3
payment = "$"+str(amount)
print("Month ",strategy, ":", payment.rjust(50))
| true
|
0f7c3ae3ca9f584cdeb424c04b1f6b2a9a8317d5
|
gitStudyToY/PythonStudy
|
/ name_cases.py
| 736
| 4.21875
| 4
|
message = "Eric"
print("Hello " + message + ", would you like to learn some Python today?" )
print(message.title())
print(message.upper())
print(message.lower())
message = "Albert Einstein once said, 'A person who never made a mistake never tried anything new.'"
print(message)
famous_person = "Albert Einstein"
famous_person_said = " once said, 'A person who never made a mistake never tried anything new.'"
message = famous_person + famous_person_said
print(message)
message = " Eric "
print(message.lstrip())
print(message.rstrip())
print(message.strip())
famous_person = "\t\nAlbert Einstein"
famous_person_said = " once said, 'A person who never made a mistake never tried anything new.'"
message = famous_person + famous_person_said
print(message)
| false
|
aaf077c666e7c6d687e953d9b3e7d35596e7f430
|
dxab/SOWP
|
/ex2_9.py
| 427
| 4.5
| 4
|
#Write a program that converts Celsius temperatures to Fahrenheit temp.
#The formula is as follows: f = 9 / 5 * C + 32
#This program should ask the user to enter a temp in Celsius and then
#display the temp converted to Fahrenheit
celsius = float(input('Please enter todays temperature (in celsius): '))
fahr = 9 / 5 * celsius + 32
print("Today's temperature in degrees fahrenheit is", format(fahr, '.0f'), 'degrees.')
| true
|
fe0ed51cf0cdab74d7d87b9f8317e18776d0c27d
|
ostanleigh/csvSwissArmyTools
|
/dynamicDictionariesFromCSV.py
| 2,363
| 4.25
| 4
|
import csv
import json
from os import path
print("This script is designed to create a list of dictionaries from a CSV File.")
print("This script assumes you can meet the following requirements to run:")
print(" 1) The file you are working with has clearly defined headers.")
print(" 2) You can review the headers ('.head') ")
print(" 3) You wish to leverage the headers as keys, create a dict per row, and use the row values as Dict vals.")
while True:
userFileVal = input("\n Dynamic Dictionaries from CSV file,"
"\n \n What is the name of the csv file you would like to work with? (Don't enter the file extension.): ")
try:
filename = path.exists(userFileVal+'.csv')
except FileNotFoundError:
print("Wrong file or file path")
else:
break
#filename = input("What is the name of the csv file you would like to work with? (Don't enter the file extension.) ? ")
userEvalIn = input("Do you want to remove any columns or characters from the left of the header? Y or N?: ")
userEval = str.lower(userEvalIn)
if userEval == 'y':
startIndex = int(input("How many fields should be trimmed from left margin? Enter an integer: "))
# If file corruption introduces characters, or redundant file based index is in place
# Can add lines to support further indexing / slicing as needed
else:
startIndex = 0
outFileName = input("What do you want to name your output file? Please enter a valid csv file name: ")
with open (userFileVal+'.csv', 'r') as csvInputFile:
filereader = csv.reader(csvInputFile)
headerRaw = next(filereader)
header = headerRaw
header = headerRaw[startIndex:]
print(f"header is: {header}")
with open (outFileName+'.json','w',newline='') as jsonOutputFile:
filereader = csv.reader(csvInputFile)
outDicts = [ ]
for line in filereader:
keyValsRaw = next(filereader)
keyVals = keyValsRaw[ startIndex: ]
# If file corruption introduces characters, or redundant index is in place
# keyVals = keyValsRaw[1:]
# use further indexing / slicing as needed
headerKeys = dict.fromkeys(header)
zipObj = zip(headerKeys, keyVals)
dictObj = dict(zipObj)
outDicts.append(dictObj)
filewriter = json.dump(outDicts,jsonOutputFile)
print("Close")
| true
|
89ec0897f99163edb014c185425b3054332f6dbe
|
RamyaRaj14/assignment5
|
/max1.py
| 258
| 4.25
| 4
|
#function to find max of 2 numbers
def maximum(num1, num2):
if num1 >= num2:
return num1
else:
return num2
n1 = int(input("Enter the number:"))
n2 = int(input("Enter the number:"))
print(maximum(n1,n2))
| true
|
f8ec2566b82d611fe6e8ae0ecff036978de9a002
|
ayaabdraboh/python
|
/lap1/shapearea.py
| 454
| 4.125
| 4
|
def calculate(a,c,b=0):
if c=='t':
area=0.5*a*b
elif c=='c':
area=3.14*a*a
elif c=='s':
area=a*a
elif c=='r':
area=a*b
return area
if __name__ == '__main__':
print("if you want to calculate area of shape input char from below")
c = input("enter char between t,s,c,r : ")
a=int(input("enter num1"))
b=int(input("enter num2"))
print(calculate(a,c,b))
| true
|
ef3f6373867dbacee7aae3af141d9fcd1edbd311
|
PabloG6/COMSCI00
|
/Lab4/get_next_date_extra_credit.py
| 884
| 4.28125
| 4
|
from datetime import datetime
from datetime import timedelta
'''the formatting on the lab is off GetNextDate(day, month, year, num_days_forward)
would not return 9/17/2016 if GetNextDate(2, 28, 2004) is passed because
28 is not a month.
'''
def GetNextDate(day, month, year, num_days_forward):
num_days_forward = int(num_days_forward) if (type(num_days_forward) == str) else num_days_forward
day = str(day).zfill(2)
month = str(month).zfill(2)
year = str(year).zfill(2)
date = '{0}/{1}/{2}'.format(day, month, year)
new_date = datetime.strptime(date, '%d/%m/%Y')
new_date += timedelta(days=num_days_forward)
new_date = new_date.strftime('%m/%d/%Y')
return new_date
print(GetNextDate(input("Please enter the day: "), input("Please enter the month: "),
input("Please enter the year: "), input("Enter number of days forward: ")))
| true
|
af817ff14fbc1b00968c49da3f427ddb3d75622d
|
PabloG6/COMSCI00
|
/Lab2/moon_earths_moon.py
| 279
| 4.125
| 4
|
first_name = input("What is your first name?")
last_name = input("What is your last name?")
weight = int(input("What is your weight?"))
moon_gravity= 0.17
moon_weight = weight*moon_gravity
print("My name is", first_name, last_name+".", "And I weigh", moon_weight, "on the moon")
| true
|
683ce144348dbb8d1f15f38ada690d70e9b1a22f
|
joeschweitzer/board-game-buddy
|
/src/python/bgb/move/move.py
| 827
| 4.3125
| 4
|
class Move:
"""A single move in a game
Attributes:
player -- Player making the move
piece -- Piece being moved
space -- Space to which piece is being moved
"""
def __init__(self, player, piece, space):
self.player = player
self.piece = piece
self.space = space
class MoveHistory:
"""Records a move that was made
Attributes:
move -- Move that was made
time -- Time move was made
"""
def __init__(self, move, time):
self.move = move
self.time = time
class InvalidMoveError(Exception):
"""Error thrown for invalid move
Attributes:
value -- Error string
"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
| true
|
2b0293a0bd0452e9e94a7c6aea0d13a803cc9dbd
|
Demesaikiran/MyCaptainAI
|
/Fibonacci.py
| 480
| 4.21875
| 4
|
def fibonacci(r, a, b):
if r == 0:
return
else:
print("{0} {1}".format(a, b), end = ' ')
r -= 1
fibonacci(r, a+b, a+ 2*b)
return
if __name__ == "__main__":
num = int(input("Enter the number of fibonacci series you want: "))
if num == 0 or num < 0:
print("Incorrect choice")
elif num == 1:
print("0")
else:
fibonacci(num//2, 0, 1)
| true
|
bb50b8feabc4e027222ed347042d5cefdf0e64da
|
abtripathi/data_structures_and_algorithms
|
/problems_and_solutions/arrays/Duplicate-Number_solution.py
| 1,449
| 4.15625
| 4
|
# Solution
'''
Notice carefully that
1. All the elements of the array are always non-negative
2. If array length = n, then elements would start from 0 to (n-2), i.e. Natural numbers 0,1,2,3,4,5...(n-2)
3. There is only SINGLE element which is present twice.
Therefore let's find the sum of all elements (current_sum) of the original array, and
find the sum of first (n-2) Natural numbers (expected_sum).
Trick:
The second occurance of a particular number (say `x`) is actually occupying the space
that would have been utilized by the number (n-1). This leads to:
current_sum = 0 + 1 + 2 + 3 + .... + (n-2) + x
expected_sum = 0 + 1 + 2 + 3 + .... + (n-2)
current_sum - expected_sum = x
Tada!!! :)
'''
def duplicate_number(arr):
current_sum = 0
expected_sum = 0
# Traverse the original array in the forward direction
for num in arr:
current_sum += num
# Traverse from 0 to (length of array-1) to get the expected_sum
# Alternatively, you can use the formula for sum of an Arithmetic Progression to get the expected_sum
# The argument of range() functions are:
# starting index [OPTIONAL], ending index (non exclusive), and the increment/decrement size [OPTIONAL]
# It means that if the array length = n, loop will run form 0 to (n-2)
for i in range(len(arr) - 1):
expected_sum += i
# The difference between the
return current_sum - expected_sum
| true
|
26d6e211c524aae3668176e7f54638f589b9226c
|
nicholasrokosz/python-crash-course
|
/Ch. 15/random_walk.py
| 945
| 4.25
| 4
|
from random import choice
class RandomWalk:
"""Generates random walks."""
def __init__(self, num_points=5000):
"""Initializes walk attributes."""
self.num_points = num_points
# Walks start at (0, 0).
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""Calculate all the points in a walk."""
# Keep calculating random steps until number of steps is reached.
while len(self.x_values) < self.num_points:
# Randomly decide which direction and how far to step.
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4])
y_step = y_direction * y_distance
# Reject non-steps.
if x_step == 0 and y_step == 0:
continue
# Calculate the new position.
x = self.x_values[-1] + x_step
y = self.y_values[-1] + y_step
self.x_values.append(x)
self.y_values.append(y)
| true
|
6405fb18f932d4ef96807f2dc65b04401f32e5be
|
nicholasrokosz/python-crash-course
|
/Ch. 10/favorite_number.py
| 467
| 4.125
| 4
|
import json
def get_fav_num():
"""Asks a user for their favorite number and stores the value in a .json file."""
fav_num = input("What is your favorite number? ")
filename = 'fav_num.json'
with open(filename, 'w') as f:
json.dump(fav_num, f)
def print_fav_num():
"""Retrieves user's favoite number and prints it."""
filename = 'fav_num.json'
with open(filename) as f:
fav_num = json.load(f)
print(f"I know your favorite number! It's {fav_num}.")
| true
|
da5a646c0a2caecadb60485bf3d02d8c0661960b
|
nicholasrokosz/python-crash-course
|
/Ch. 8/user_albums.py
| 572
| 4.25
| 4
|
def make_album(artist, album, no_of_songs=None):
album_info = {'artist': artist, 'album': album}
if no_of_songs:
album_info['no_of_songs'] = no_of_songs
return album_info
while True:
artist_name = input("Enter the artist's name: ")
album_title = input("Enter the album title: ")
no_of_songs = input("Enter the number of songs (optional): ")
album_info = make_album(artist_name, album_title, no_of_songs)
print(album_info)
repeat = input("\nWould you like to enter another album? Enter Y or N: ")
if repeat == 'Y' or repeat == 'y':
continue
else:
break
| true
|
af5ab9aad7b047b9e9d061e22ab7afe7e64a4b01
|
mumarkhan999/UdacityPythonCoursePracticeFiles
|
/9_exponestial.py
| 347
| 4.5
| 4
|
#claculating power of a number
#this can be done easily by using ** operator
#for example 2 ** 3 = 8
print("Assuming that both number and power will be +ve\n")
num = int(input("Enter a number:\n"))
power = int(input("Enter power:\n"))
result = num
for i in range(1,power):
result = result * num
print(result)
input("Press any key to quit...")
| true
|
a6fc7a95a15f7c98ff59850c70a05fdb028a784f
|
mumarkhan999/UdacityPythonCoursePracticeFiles
|
/8_multi_mulTable.py
| 208
| 4.25
| 4
|
#printing multiple multiplication table
num = int(input("Enter a number:\n"))
for i in range (1, (num+1)):
print("Multiplication Table of",i)
for j in range(1,11):
print(i,"x",j,"=",i*j)
| true
|
162b0739cda0d6fba65049b474bc72fecf547f3d
|
dodgeviper/coursera_algorithms_ucsandeigo
|
/course1_algorithmic_toolbox/week4/assignment/problem_4.py
| 2,492
| 4.21875
| 4
|
# Uses python3
"""How close a data is to being sorted
An inversion of sequence a0, a1, .. an-1 is a pair of indices 0<= i < j< n
such that ai < aj. The number of inversion of a sequence in some sense measures
how close the sequence is to being sorted. For example, a sorted (in non-decreasing
order) sequence contains no inversions at all, while in a sequence sorted in descending
order any two elements constitute an inversion (for a total of n(n - 1)/ 2 inversions)
Task: the goal is to count the number of inversions of a given sequence.
Input format: First line contains an integer n, the next one contains a sequence of
integers a0, a1.. an-1
Constraints:
1<= n < 10^5, 1 <= ai <= 10^9 for all 0 <= i < n
Output:
The number of inversions of the sequence.
"""
inversion_count = [0]
def merge(a, b):
d = list()
index_a, index_b = 0, 0
len_a = len(a)
while index_a < len(a) and index_b < len(b):
el_a = a[index_a]
el_b = b[index_b]
if el_a <= el_b:
d.append(el_a)
index_a += 1
else:
d.append(el_b)
index_b += 1
inversion_count[0] += (len_a - index_a)
d.extend(a[index_a:])
d.extend(b[index_b:])
return d
def merge_sort(n):
if len(n) == 1:
return n
mid = int(len(n) / 2)
left_half = merge_sort(n[:mid])
right_half = merge_sort(n[mid:])
return merge(left_half, right_half)
#
# def counting_inversions_naive(input_list):
# count = 0
# for i in range(len(input_list)):
# for j in range(i+1, len(input_list)):
# if input_list[i] > input_list[j]:
# count += 1
# return count
#
# import random
# def stress_testing():
# while True:
# n = random.randint(1, 3)
# input_list = [random.randint(1, 100) for _ in range(n)]
# count_naive = counting_inversions_naive(input_list)
# inversion_count[0] = 0
# merge_sort(input_list)
# count_eff = inversion_count[0]
# if count_naive != count_eff:
# print('Failed')
# print(n)
# print(input_list)
# print('count naive; ', count_naive)
# print('optimized: ', count_eff)
# break
#
#
#
# stress_testing()
#
n = input()
input_list = list(map(int, input().split()))
# # inversions = []
# # n = 6
# # input_list = [9, 8, 7, 3, 2, 1]
merge_sort(input_list)
print(inversion_count[0])
# print(counting_inversions_naive(input_list))
| true
|
8c41e6813d5e137bf3acbe883b08d269d9cb7d7b
|
Smellly/weighted_training
|
/BinaryTree.py
| 1,813
| 4.25
| 4
|
# simple binary tree
# in this implementation, a node is inserted between an existing node and the root
import sys
class BinaryTree():
def __init__(self,rootid):
self.left = None
self.right = None
self.rootid = rootid
def getLeftChild(self):
return self.left
def getRightChild(self):
return self.right
def setNodeValue(self,value):
self.rootid = value
def getNodeValue(self):
return self.rootid
def insertRight(self,newNode):
if self.right == None:
self.right = BinaryTree(newNode)
else:
tree = BinaryTree(newNode)
tree.right = self.right
self.right = tree
def insertLeft(self,newNode):
if self.left == None:
self.left = BinaryTree(newNode)
else:
tree = BinaryTree(newNode)
self.left = tree
tree.left = self.left
def printTree(tree):
if tree != None:
# sys.stdout.write('<')
tmp = ''
tmp += printTree(tree.getLeftChild())
#print(tree.getNodeValue())
tmp += ' ' + tree.getNodeValue()
tmp += ' ' + printTree(tree.getRightChild())
#sys.stdout.write('>')
return tmp
else:
return ''
def getAllLeaves(tree):
leaves = set()
if tree != None:
if tree.getLeftChild() is None and tree.getRightChild() is None:
leaves.add(tree.getNodeValue())
else:
if tree.getLeftChild() is not None:
leaves = leaves.union(getAllLeaves(tree.getLeftChild()))
if tree.getRightChild() is not None:
leaves = leaves.union(getAllLeaves(tree.getRightChild()))
return leaves
# else:
# return None
| true
|
a5f8cf2de38a252d3e9c9510368419e5a763cf74
|
TheFibonacciEffect/interviewer-hell
|
/squares/odds.py
| 1,215
| 4.28125
| 4
|
"""
Determines whether a given integer is a perfect square, without using
sqrt() or multiplication.
This works because the square of a natural number, n, is the sum of
the first n consecutive odd natural numbers. Various itertools
functions are used to generate a lazy iterable of odd numbers and a
running sum of them, until either the given input is found as a sum
or the sum has exceeded n.
"""
from itertools import accumulate, count, takewhile
import sys
import unittest
is_square = lambda n: n > 0 and n in takewhile(lambda x: x <= n, accumulate(filter(lambda n: n & 1, count())))
class SquareTests(unittest.TestCase):
def test_squares(self):
for i in range(1, 101):
if i in (1, 4, 9, 16, 25, 36, 49, 64, 81, 100):
assert is_square(i)
else:
assert not is_square(i)
if __name__ == '__main__':
if len(sys.argv) != 2:
sys.exit(unittest.main())
value = None
try:
value = int(sys.argv[1])
except TypeError:
sys.exit("Please provide a numeric argument.")
if is_square(value):
print("{} is a square.".format(value))
else:
print("{} is not a square.".format(value))
| true
|
959fc6191262d8026e7825e50d80eddb08d6a609
|
OliValur/Forritunar-fangi-1
|
/20agust.py
| 2,173
| 4.28125
| 4
|
import math
# m_str = input('Input m: ') # do not change this line
# # change m_str to a float
# # remember you need c
# # e =
# m_float = float(m_str)
# c = 300000000**2
# e = m_float*c
# print("e =", e) # do not change this line)
# Einstein's famous equation states that the energy in an object at rest equals its mass times the square of the speed of light. (The speed of light is 300,000,000 m/s.)
# Complete the skeleton code below so that it:
# * Accepts the mass of an object (remember to convert the input string to a number, in this case, a float).
# * Calculate the energy, e
# * Prints e
# import math
# x1_str = input("Input x1: ") # do not change this line
# y1_str = input("Input y1: ") # do not change this line
# x2_str = input("Input x2: ") # do not change this line
# y2_str = input("Input y2: ") # do not change this line
# x1_int = int(x1_str)
# y1_int = int(y1_str)
# x2_int = int(x2_str)
# y2_int = int(y2_str)
# formula =(y1_int-y2_int)**2+(x1_int-x2_int)**2
# d = math.sqrt(formula)
# print(formula)
# print("d =",d) # do not change this line
# weight_str = input("Weight (kg): ") # do not change this line
# height_str = input("Height (cm): ") # do not change this line
# # weight_int = int(weight_str)
# # height_int = int(height_str)
# weight_float = float(weight_str)
# height_float = float(height_str)
# bmi = weight_float / (height_float**2)
# print("BMI is: ", bmi) # do not change this line75,290.6
n_str = input("Input n: ")
# remember to convert to an int
n_int = int(n_str)
first_three = n_int//100
last_two =n_int % 100
print("first_three:", first_three)
print("last_two:", last_two)
# Write a Python program that:
# Accepts a five-digit integer as input
# Assign the variable first_three (int) to be the first three digits.
# Assign the variable last_two (int) to be the last two digits.
# Prints out the two computed values.
# Hint: use quotient (//) and remainder (%)
# For example, if the input is 12345, the output should be:
# first_three: 123
# last_two: 45
# If the fourth digit is a zero, like 12305, the output should be:
# first_three: 123
# last_two: 5
# (even though that is not strictly correct).
| true
|
0837151d119a5496b00d63ae431b891e405d11cb
|
Shubham1744/Python_Basics_To_Advance
|
/Divide/Prog1.py
| 249
| 4.15625
| 4
|
#Program to divide two numbers
def Divide(No1,No2):
if No2 == 0 :
return -1
return No1/No2;
No1 = float(input("Enter First Number :"))
No2 = float(input("Enter Second Number :"))
iAns = Divide(No1,No2)
print("Division is :",iAns);
| true
|
b57b724347cc8429c3178723de6182e741940b16
|
DarioDistaso/senai
|
/logica_de_programação/sa4etapa1.py
| 1,614
| 4.15625
| 4
|
#Disciplina: [Logica de Programacao]
#Professor: Lucas Naspolini Ribeiro
#Descricao: SA 4 - Etapa 1: PILHA
#Autor: Dario Distaso
#Data atual: 06/03/2021
pilha = []
def empilhar(): # opção 1
if len(pilha) < 20:
produto = str(input("Digite o produto: ")).strip()
pilha.append(produto)
print(f'O produto inserido foi: {produto}')
elif len(pilha) == 20:
print("A pilha já está cheia!")
def desempilhar(): # opção 2
if len(pilha) == 0:
print("A pilha está vazia!")
else:
topo = pilha.pop()
print(f'O produto removido foi: {topo}')
def limpar(): # opção 3
if len(pilha) == 0:
print("A pilha já está vazia!")
else:
pilha.clear()
print("A pilha foi limpa!")
def listar(): # opção 4
if len(pilha) == 0:
print("A pilha está vazia!")
else:
print(f'\nA pilha atual é {pilha}')
def vazia(): # opção 5
if len(pilha) == 0:
print("A pilha está vazia!")
else:
print("A pilha não está vazia!")
while True:
print("""\n\t1 - Empilhar
\t2 - Desempilhar
\t3 - Limpar
\t4 - Listar
\t5 - A pilha está vazia?
\t6 - Encerrar""")
opcao = int(input("\nDigite uma opção: "))
if opcao == 1:
empilhar()
elif opcao == 2:
desempilhar()
elif opcao == 3:
limpar()
elif opcao == 4:
listar()
elif opcao == 5:
vazia()
elif opcao == 6:
print("\nVocê encerrou o programa!\n")
break
else:
print("Opção inválida!")
| false
|
c35d93f5359f710db0bb6d3db7f4c8af1724b1e9
|
umberahmed/hangman-
|
/index.py
| 586
| 4.25
| 4
|
# This program will run the game hangman
# random module will be used to generate random word from words list
import random
# list of words to use in game
list_of_words = ["chicken", "apple", "juice", "carrot", "hangman", "program", "success", "hackbright"]
# display dashes for player to see how many letters are in the word to guess
print random.choice(list_of_words)
def greet_user():
"""greets user to hangman"""
print "Welcome to Hangman!"
greet_user()
def player():
"""stores player's name"""
name = input("What's your name? ")
return name
player()
| true
|
191b74137d4b0636cbf401c865279f8c33ef69b0
|
zyavuz610/learnPython_inKTU
|
/python-100/104_numbers_casting.py
| 1,147
| 4.46875
| 4
|
"""
Seri: Örneklerle Python Programlama ve Algoritma
Python 100 - Python ile programlamaya giriş
Python 101 - Python ile Ekrana Çıktı Yazmak, print() fonksiyonu
Python 102 - Değişkenler ve Veri Türleri
Python 103 - Aritmetik operatörler ve not ortalaması bulma örneği
Python 104 - Sayılar, bool ifadeler ve tür dönüşümü
Sayılar
x = -11 # int
y = 1.8 # float
z = 2+3j # complex
tipini öğrenme
print(type(x))
uç örnekler
a = 35656222554887711
x = 35e3 = 35* (10**3)
y = 12E4
z = -87.7e100
x = 3+5j
y = 5j
z = -5j
boolean
print(10 > 9)
print(10 == 9)
print(10 < 9)
Tür Dönüşümü
int, str, float, complex, bool
True değerli ifadeler, içinde değer olan
bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])
False değerli ifadeler, içerisinde değer olmayan
bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})
Tip Dönüşümleri
x = int(1) # x = 1
y = int(2.8) # y = 2
z = int("3") # z = 3
x = float(1) # x = 1.0
y = float(2.8) # y = 2.8
z = float("3") # z = 3.0
w = float("4.2") # w = 4.2
x = str("s1") # x = 's1'
y = str(2) # y = '2'
z = str(3.0) # z = '3.0'
"""
| false
|
d9dd950f5a7dd35e1def63114c2f65ad6c2fb3da
|
zyavuz610/learnPython_inKTU
|
/python-100/113_while-loop.py
| 1,322
| 4.28125
| 4
|
"""
Seri: Örneklerle Python Programlama ve Algoritma
python-113: while döngüsü, 1-10 arası çift sayılar, döngü içinde console programı yazmak
Döngüler, programlamada tekrarlı ifadeleri oluşturmak için kullanılır.
türleri
for
while
döngülerin bileşenleri: 4 adet döngü bileşeni
1. başlangıç
2. bitiş (döngüye devam etme şartı bitişe ulaşmamak)
3. her tekrardan sonra yapılacak artış miktarı
4. dönünün gövdesi, tekrar edilecek ifade
for i in range(1,10):
print(i)
# for döngüsü analizi
# 1. başlangıç:0
# 2. bitiş: 10, 10 dahil değil değil, döngüye devam etmek için i<10 olmalı
# 3. artış miktarı:1
# 4. gövde: print() fonksiyonu (basit kodlar olabileceği gibi karmaşık kodlar da gövde kısmına yazılabilir. gövde kodları girintili bir şekilde döngü içine yazılır)
i = 1
while (i<10):
if(i%2==0):
print(i)
i +=1
"""
# console programı
lst = []
cond = True
while (cond):
s = input("İsim giriniz:")
if (s == "q"):
cond = False
else:
lst.append(s)
print(lst)
"""
cond while? s if? lst
True evet zafer hayır ['zafer']
True evet ali hayır ['zafer','ali']
True evet q evet, cond=False, .....
False hayır
"""
| false
|
db985b8f58b3c1ba64a29f48c8b1c1620a22629f
|
zyavuz610/learnPython_inKTU
|
/python-100/131_set-intro.py
| 1,266
| 4.21875
| 4
|
"""
Seri: Örneklerle Python Programlama ve Algoritma
Önceki dersler:
değişkenler ve operatörler
koşul ifadeleri: if,else
döngüler: for, while, iç içe döngüler
fonksiyonlar, modüller
veri yapıları:
string,
list,
tuple
...
set *
dict
Python - 131 : Set (Küme) Veri Yapısı
Set(s) - Küme(ler)
Matematikteki kümeler gibi verileri saklayan bir yapıdır
st = {"ali",1,True}
Özellikleri
. Birden çok değer içerir ancak her değer bir kere saklanır (tekrar yok)
. İndis ile erişim yoktur
. İçerik değiştirilemez, ancak eleman çıkarılıp başka bir eleman eklenebilir.
. { } parantezleri ile tanımlanır
. Küme elemanları sıralı değildir, elemanlar herhangi bir sırada olabilir.
. len() ile uzunluk bulunur
. küme elemanları herhangi bir türde olabilir (bool,int,str)
. set() yapıcı fonksiyonu vardır
. st = set(("python", "html", "java"))
"""
# bilinen programlama dilleri
ali_set = {'html','css','java','C','python','css'}
print(ali_set,len(ali_set))
veli_set = {'C','C++','java','python','java'}
print(veli_set,len(veli_set))
for e in ali_set:
print(e)
elm = 'C++'
if elm in ali_set:
print("Ali",elm,"biliyor")
else:
print("Ali",elm,"bilmiyor")
| false
|
a462d5adc2feb9f2658701a8c2035c231595f81e
|
kristinejosami/first-git-project
|
/python/numberguessing_challenge.py
| 911
| 4.3125
| 4
|
'''
Create a program that:
Chooses a number between 1 to 100
Takes a users guess and tells them if they are correct or not
Bonus: Tell the user if their guess was lower or higher than the computer's number
'''
print('Number Guessing Challenge')
guess=int(input('This is a number guessing Challenge. Please enter your guess number:'))
from random import randint
number=int(randint(1,100))
# number=3
if number==guess:
print('Congratulations! Your guess is correct. The number is {} and your guess is {}.'.format(number, guess))
elif number<guess:
print("Sorry, your number is incorrect. The number is {} and your guess is {}."
" Your guess is greater than the number. Please try again.".format(number,guess))
else:
print("Sorry, your number is incorrect. The number is {} and your guess is {}. "
"Your guess is lesser than the number. Please try again.".format(number, guess))
| true
|
c1fe260237f4a694c49c6191271a3d5870241e6f
|
pawan9489/PythonTraining
|
/Chapter-3/3.Scopes_1.py
| 1,353
| 4.625
| 5
|
# Local and Global Scope
# Global variable - Variables declared outside of Every Function
# Local variable - Variables declared inside of a Function
g = 0 # Global Variable
def func():
i = 30 # Local Variable
print("From Inside Func() - i = ", i)
print("From Inside Func() - g = ", g)
print('---- Global Variables ---')
func()
# print(i) # NameError: name 'i' is not defined
print("From Outside Func() - g = ", g)
print()
# Modify Global Variables
g = 0
def func1():
g = 10
print("From Inside Func1() - g = ", g)
print('---- Modify Global Variables ---')
func1()
print("From Outside Func1() - g = ", g)
print()
g = 0
def func2():
global g
g = 10
print("From Inside Func2() - g = ", g)
print('---- Modify Global Variables ---')
func2()
print("From Outside Func2() - g = ", g)
print()
# g = 0
# def outer():
# o = 2
# def inner():
# i = 10
# print("Inner - g", g, id(g))
# print("Inner - i", i, id(i))
# print("Inner - o", o, id(o))
# # Below Code Creates new 'o' variable
# # o = 20 # will loose the outer 'o'
# # print("Inner - o", o, id(o))
# print("Outer - g", g, id(g))
# print("Outer - o", o, id(o))
# inner()
# print("Outer - o", o, id(o))
# print(x)
# # Comment x and see failure
# x = 'Python'
# outer()
# # x = 'Python'
| false
|
b9310befbc4a399a8c239f22a1bc06f7286fedee
|
pawan9489/PythonTraining
|
/Chapter-2/4.Sets.py
| 1,504
| 4.375
| 4
|
# Set is a collection which is unordered and unindexed. No duplicate members.
fruits = {'apple', 'banana', 'apple', 'cherry'}
print(type(fruits))
print(fruits)
print()
# Set Constructor
# set() - empty set
# set(iterable) - New set initialized with iterable items
s = set([1,2,3,2,1])
print(s)
print()
# No Indexing - Since no ordering but we can Loop
for fruit in fruits:
print(fruit)
print()
# Membership
print("'cherry' in fruits = {0}".format('cherry' in fruits))
print()
# Only appending No Updating Items - Since no Indexing
# Add items
print("Before adding = {0}".format(fruits))
fruits.add('mango')
print("fruits.add('mango') = {0}".format(fruits))
print()
# Add Multiple items
print("Before Multiple adding = {0}".format(fruits))
fruits.update(['orange', 'grapes'])
print("fruits.update(['orange', 'grapes']) = {0}".format(fruits))
print()
# Length of Set
print("len(fruits) = {0}".format(len(fruits)))
print()
# Remove Item
# remove(item) - will throw error if item dont exist
# discard(item) - will not throw error if item dont exist
print("Before removing = {0}".format(fruits))
fruits.remove('grapes')
print("fruits.remove('grapes') = {0}".format(fruits))
print()
# pop - remove some random element - Since no Indexing
# only pop(), not pop(index) - Since no Indexing
print("Before pop = {0}".format(fruits))
print("fruits.pop() = {0}".format(fruits.pop()))
print()
# clear()
print("Before clear = {0}".format(fruits))
fruits.clear()
print("fruits.clear() = {0}".format(fruits))
| true
|
ea4f3b0a569bcc2fd312286f4d44383a2ef6729a
|
pawan9489/PythonTraining
|
/Chapter-4/1.Classes_Objects.py
| 1,641
| 4.21875
| 4
|
'''
Class Like Structures in Functional Style:
Tuple
Dictionary
Named Tuple
Classes
'''
d = dict(
name = 'John',
age = 29
)
print('- Normal Dictionary -')
print(d)
# Class Analogy
def createPerson(_name, _age):
return dict(
name = _name,
age = _age
)
print()
print('- Factory Function to Create Dictionaries -')
print(createPerson('John', 19))
print(createPerson('Mary', 45))
# What is the Difference between Dictionary or Named Tuple and a Class?
class Person:
'Person Class with Name and Age as Properties'
def __init__(self, _name, _age):
self.name = _name
self.age = _age
def __str__(self):
return "Name - {0}, Age - {1}".format(self.name, self.age)
# return ", ".join(map(lambda t: t[0].capitalize() + ' - ' + str(t[1])
# , self.__dict__.items()))
print()
print('- Using Classes -')
p = Person('John', 30)
print("p - {0}".format(p))
print(p.name, p.age)
print(p.__dict__)
# To Prove the Classes are Dictionaries
print()
print('After Adding a Key')
p.job = 'Manager'
print("p - {0}".format(p))
print(p.__dict__)
del p.job
print(p.__dict__)
# Getters and Setters
print()
print(' Getters and Setters ')
print(p.age) # Getter
p.age = 99 # Setter
print(p.age)
print()
# Generic Getters and Setters
# getattr(object, property_name)
# setattr(object, property_name, value)
print(getattr(p, 'age'))
setattr(p, 'age', 70)
print(getattr(p, 'age'))
# Get all avaliable functions on an Object
print()
print(dir(p))
print('----')
for key in dir(p):
print("{0:20} - {1}".format(key, getattr(p, key)))
print('----')
| false
|
ca7b96d6389b50e8637507cce32274991e792144
|
SK7here/learning-challenge-season-2
|
/Kailash_Work/Other_Programs/Sets.py
| 1,360
| 4.25
| 4
|
#Sets remove duplicates
Text = input("Enter a statement(with some redundant words of same case)")
#Splitting the statement into individual words and removing redundant words
Text = (set(Text.split()))
print(Text)
#Creating 2 sets
print("\nCreating 2 sets")
a = set(["Jake", "John", "Eric"])
print("Set 1 is {}" .format(a))
b = set(["John", "Jill"])
print("Set 2 is {}" .format(b))
#Adding elements
print("\nAdding 'SK7' item to both sets")
a.add("SK7")
b.add("SK7")
print("Set 1 after adding 'SK7' : ")
print(a)
print("Set 2 after adding 'SK7' : ")
print(b)
#Removing elements
del_index = (input("\nEnter the element to be removed in set 1: "))
a.remove(del_index)
print("After removing specified element")
print(a)
#Finding intersection
print("\nIntersection between set 1 and set 2 gives : ")
print(a.intersection(b))
#Finding items present in only one of the sets
print("\nItems present in only one of the 2 sets : ")
print(a.symmetric_difference(b))
print("\nItems present only in set a : ")
print(a.difference(b))
print("\nItems present only in set b : ")
print(b.difference(a))
#Finding union of 2 sets
print("\nUnion of 2 sets : ")
print(a.union(b))
#Clearing sets
print("\nClearing sets 1 and 2")
print("Set 1 is {}" .format(a.clear()))
print("Set 2 is {}" .format(b.clear()))
| true
|
0164661e3480ce4df1f2140c07034b3bb75a6c3b
|
SK7here/learning-challenge-season-2
|
/Kailash_Work/Arithmetic/Calculator.py
| 1,779
| 4.125
| 4
|
#This function adds two numbers
def add(x , y):
return x + y
#This function subtracts two numbers
def sub(x , y):
return x - y
#This function multiplies two numbers
def mul(x , y):
return x * y
#This function divides two numbers
def div(x , y):
return x / y
#Flag variable used for calculator termination purpose
#Initially flag is set to 0
flag = 0
#Until the user chooses option 5(Stop), calculator keeps on working
while(flag == 0):
#Choices displayed
print("\n\n\nSelect operation")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
print("5.Stop")
#Take input from the user
choice = input("\nEnter choice : ")
if(choice == '5'):
#If user wishes to stop calculator(choice 5), flag is set to 1
flag = 1
#If user has chosen choice 5(stop), control comes out of loop here, failing to satisfy the condition
if(flag == 0):
num1 = int(input("\nEnter first input : "))
num2 = int(input("Enter second input : "))
#Performing corresponding arithmetic operation
if choice == '1':
print("\nSum of {} and {} is {}" .format(num1 , num2 , add(num1,num2)))
elif choice == '2':
print("\nDifference between {} and {} is {}" .format(num1 , num2 , sub(num1,num2)))
elif choice == '3':
print("\nProduct of {} and {} is {}" .format(num1 , num2 , mul(num1,num2)))
elif choice == '4':
print("\nDivision of {} and {} is {}" .format(num1 , num2 , div(num1,num2)))
else:
print("Invalid operation")
#Comes out of the loop, if user chooses choice 5(flag is set to '1')
print("\nCalculator service terminated")
| true
|
7337c033becfb2c6c22daa18f54df4141ff804ac
|
kittytian/learningfishcpy3
|
/33.3.py
| 1,904
| 4.5
| 4
|
'''
2. 尝试一个新的函数 int_input(),当用户输入整数的时候正常返回,否则提示出错并要求重新输入。%
程序实现如图:
请教1:
int_input("请输入一个整数:") 这一句括号里的即是一个形参又是一个输入?为什么?
这一句的括号里不是形参,是实参,传递给了int_input函数
它并不是一个输入,能够作为输入是因为int_input函数中调用了input函数,才有了输入的功能
请教2:
def int_input(prompt=''): 这里的我用(prompt)和(prompt='')的结果是一样的,他们有区别吗?如果是(prompt='')的话是什么意思?
第一种(prompt)并没有指定形参的默认值,这样在调用int_input函数时必须带参数,将该参数赋值给了prompt
第二种(prompt='')指定了形参的默认值为空'',这种情况下在调用int_input函数时可以不写参数,比如
a = int_input(),
设置默认参数可以避免调用函数时没有给指定参数传值而引发的错误。
你可以尝试把def int_input(prompt='')和def int_input(prompt)两种情况下调用:
x=int_input()
如果没有设置默认参数,程序会报错。
def int_input(prompt=''):
这个就是定义一个函数,名字是int_input,调用这个函数的时候要传入一个参数,这个参数有个名字是prompt,而且规定了默认值为“空”
int(input(prompt))
里面的prompt就是刚才函数定义时传入的变量,然后对这个变量转换成int类型,如果是数字就直接跳出循环了,如果不是数字,会报一个ValueError,然后打印“出错,您输入的不是整数!”
'''
def int_input(prompt = ''):
while True:
try:
int(input(prompt))
break
except ValueError:
print('出错!您输入的不是整数')
int_input('请输入一个整数:')
| false
|
bb253f977f19bc69c71741e10e2d9f6be1191eea
|
kittytian/learningfishcpy3
|
/16.4.py
| 642
| 4.21875
| 4
|
'''
哎呀呀,现在的小屁孩太调皮了,邻居家的孩子淘气,把小甲鱼刚写好的代码画了个图案,
麻烦各位鱼油恢复下啊,另外这家伙画的是神马吗?怎么那么眼熟啊!??
自己写的时候注意点 循环 还有判断!!一定要细心 会写
'''
name = input('请输入待查找的用户名:')
score = [['米兔', 85], ['黑夜', 80], ['小布丁', 65], ['娃娃', 95], ['意境', 90]]
flag = False
for each in score:#遍历
if name in each:
print(name + '的得分是:', each[1])
flag = True
break
if flag == False:
print('查找的用户不存在')
| false
|
33d0681848619697f3236def10951be9751c43ce
|
kittytian/learningfishcpy3
|
/17.0.py
| 498
| 4.53125
| 5
|
'''
编写一个函数power()模拟内建函数pow(),即power(x, y)为计算并返回x的y次幂的值
递归(22课课后题0))和非递归法
def power(x, y):
return x ** y
print(power(2,3))
看了答案发现 人家的意思是不用**幂函数
'''
'''
def power(x, y):
result = 1
for i in range(y):
result *= x
return result
print(power(2, 3))
'''
def power(x,y):
if y:
return x * power(x,y-1)
else:
return 1
print(power(2,3))
| false
|
4e8b2c18ebf0d7793c7be7dc2830842f26535ab1
|
githubfun/LPTHW
|
/PythonTheHardWay/ex14-ec.py
| 1,061
| 4.25
| 4
|
# Modified for Exercise 14 Extra Credit:
# - Change the 'prompt' to something else.
# - Add another argument and use it.
from sys import argv
script, user_name, company_name = argv
prompt = 'Please answer: '
print "Hi %s from %s! I'm the %s script." % (user_name, company_name, script)
print "I'd like to ask you a few questions."
print "Do you like me, %s from %s?" % (user_name, company_name)
likes = raw_input(prompt)
print "Where do you live, %s?" % user_name
lives = raw_input(prompt)
print "Where is %s located?" % company_name
company_location = raw_input(prompt)
print "What kind of computer do you have?"
computer = raw_input(prompt)
print "Did %s give you your %s computer?" % (company_name, computer)
company_gave_computer = raw_input(prompt)
print """
OK... so you said %r about liking me.
You live in %s. Yes, I think I know the area.
%s is in %s. You must have to fly to get there. That's a shame; there are closer companies, I'm sure.
Your %s computer? Meh. I've seen better.
""" % (likes, lives, company_name, company_location, computer)
| true
|
c8176ae9af68ecc082863620472e9fe440300668
|
githubfun/LPTHW
|
/PythonTheHardWay/ex03.py
| 1,688
| 4.1875
| 4
|
# The first line of executable code prints a statment (the stuff contained between the quotes) to the screen.
print "I will now count my chickens:"
# Next we print the word "Hens" followed by a space, then the result of the formula, which is analyzed 25 + (30 / 6)
print "Hens", 25 + 30 / 6
# Line 7 prints right below the above output the word "Roosters" then the result of the formula 100 - (( 25 * 3) % 4)
print "Roosters", 100 - 25 * 3 % 4
# 10 prints the statement about counting the eggs.
print "Now I will count the eggs:"
# 12 puts the result of the formula on the next line below the statement about counting eggs.
# This formula is calculated ( 3 + 2 + 1 - 5 ) + ( 4 % 2 ) - ( 1 / 4 ) + 6
# What tripped me up was ( 1 / 4 ) = 0, since we're doing integer math, not FP.
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
# 19 prints a whole statement, including the whole formula, since everything
# is between the quotes.
print "Is it true that 3 + 2 < 5 - 7?"
# 22 prints the results of the formula, which is analyzed "Is ( 3 + 2 ) < ( 5 - 7 )"?
print 3 + 2 < 5 - 7
# 25 and 26 analyze the "halves" of the above question and formula, printing the "halves" first, then the result of the calculation.
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7", 5 - 7
# vvv----I noticed a typo here while working on Extra Credit 5
# 29 is an "Aha" from the above two analyses.
print "Oh, that's why it's False."
print "How about some more." # print the statement to the screen
# The final three lines print a question, then the answer to a formula.
print "Is it greater?", 5 > -2
print "Is it greater or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
| true
|
e12728b653a685aba01bf66f0b89f2d31f8b0c6d
|
Flor91/Data-Science
|
/Code/3-numpy/np_vectorizacion.py
| 1,143
| 4.25
| 4
|
"""
1) Generemos un array de 1 dimension con 1000 elementos con distribución normal de media 5 y desvío 2, inicialicemos la semilla en el valor 4703.
2) Usando algunas de las funciones de Numpy listadas en Métodos matemáticos y estadísticos, calculemos la media y el desvío de los elementos del array que construimos en el punto 1.
3) Generemos otro array de dimensiones 100 filas, 20 columnas con distribución normal de media 5 y desvío 2.
4) Usando las mismas funciones que en 2) calculemos la media y el desvío de cada fila del resultado de 3.
5) Usando las mismas funciones que en 2) calculemos la media y el desvío de cada columna del resultado de 3.
"""
import numpy as np
from random_distribuciones import random_binomial
def print_stats(a, axis):
print(f"Media: {a.mean(axis=axis)}")
print(f"Desvio: {a.std(axis=axis)}")
array_normal_1 = random_binomial(seed=4703, size=1000, n=5, p=2)
print(array_normal_1[:5])
print_stats(array_normal_1, 0)
array_normal_2 = random_binomial(seed=4703, size=(100, 20), n=5, p=2)
print(array_normal_2[:5, :2])
print_stats(array_normal_2, 0)
print_stats(array_normal_2, 1)
| false
|
b549c9db156fd82a945a101f713d0c66a14c64f8
|
abrosen/classroom
|
/itp/spring2020/roman.py
| 1,147
| 4.125
| 4
|
roman = input("Enter a Roman Numeral:\n")
value = {"I" :1, "V":5, "X":10, "L":50,"C":100,"D":500,"M":1000}
def validate(roman):
count = {"I" :0, "V":0, "X":0, "L":0,"C":0,"D":0,"M":0}
for letter in roman:
if letter not in count:
return False
for letter in roman:
count[letter] += 1
if count["I"] > 3 or count["X"] > 3 or count["C"] > 3 or count["M"] > 3:
return False
if count["V"] > 1 or count["L"] > 1 or count["D"] > 1:
return False
for i in range(len(roman) - 1):
current = roman[i]
nextNum = roman[i+1]
if value[current] < value[nextNum]:
if not (5*value[current] == value[nextNum] or 10*value[current] == value[nextNum]):
return False
return True
def convert(roman):
arabic = 0
for i in range(len(roman) - 1):
current = roman[i]
nextNum = roman[i+1]
if value[current] >= value[nextNum]:
arabic += value[current]
else:
arabic -= value[current]
return arabic + value[roman[-1]]
print(validate(roman.upper()))
print(convert(roman.upper()))
| false
|
6db17e91e654e5229ccad28166264478673839d9
|
abrosen/classroom
|
/itp/spring2020/booleanExpressions.py
| 427
| 4.1875
| 4
|
print(3 > 7)
print(6 == 6)
print(6 != 6)
weather = "sunny"
temperature = 91
haveBoots = False
goingToTheBeach = True
if weather == "raining":
print("Bring an umbrella")
print(weather == "raining" and temperature < 60)
if weather == "raining" and temperature < 60:
print("Bring a raincoat")
if (weather == "raining" and temperature > 90 and not haveBoots) or goingToTheBeach:
print("Looks like sandals for today")
| true
|
0c9567b722911116f27ed17fbc1129e8d900342f
|
berkercaner/pythonTraining
|
/Chap08/dict.py
| 1,565
| 4.25
| 4
|
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# it's like hash map in C
# each pair seperated by ',' and left of the pair is 'key'
# right of the pair is 'value'
def main():
#one way of creating dictionary
animals = { 'kitten': 'meow', 'puppy': 'ruff!', 'lion': 'grrr',
'giraffe': 'I am a giraffe!', 'dragon': 'rawr' }
#other way of creating dictionary and it's more readable
animals_2 = dict(kitten = 'meow', puppy = 'ruff!', lion = 'grrr',
giraffe = 'I am a giraffe!', dragon = 'rawr')
print_dict(animals)
print()
print_dict(animals_2)
#changing a key's value
print()
animals_2['lion'] = "i am a lion"
print_dict(animals_2),
#adding an elemet
print()
animals_2['monkey'] = "lol!"
print_dict(animals_2)
#using dict methods
print()
for k in animals_2.keys(): # in sequence of keys
print(k)
print()
for v in animals_2.values(): #in sequence of values
print(v)
print()
for z,y in animals_2.items(): #in sequene of items
print("{} says {}".format(z,y))
print()
print('lion' in animals_2) #returns true or false
print('found!' if 'lion' in animals_2 else 'nope!') #basic conditional expression with print
print()
#getting value from the key if key is not exists returns none
print(animals_2.get('lion'))
print(animals_2.get('levy'))
def print_dict(o):
for x in o: print('{}: {}'.format(x,o[x]))
if __name__ == '__main__': main()
| false
|
8f4b21a601c7e3a2da6c26971c7c7bb982d4a242
|
hashncrash/IS211_Assignment13
|
/recursion.py
| 2,230
| 4.625
| 5
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Week 14 Assignment - Recursion"""
def fibonnaci(n):
"""Returns the nth element in the Fibonnaci sequence.
Args:
n (int): Number representing the nth element in a sequence.
Returns:
int: The number that is the given nth element in the fibonnaci sequence.
Examples:
>>> fibonnaci(1)
1
>>> fibonnaci(10)
55
"""
if n == 1 or n == 2:
return 1
else:
return fibonnaci(n - 1) + fibonnaci(n - 2)
def gcd(a, b):
"""Returns the greatest common divisor of two numbers.
Args:
a (int): an integer to find the greatest common divisor with b
b (int): an integer to find the greatest common divosor with a
Returns:
int: An integer representing the largest number that divides both given
integers a and b without leaving a remainder.
Examples:
>>> gcd(252, 105)
21
>>> gcd(100, 27)
1
"""
if b == 0:
return a
else:
return gcd(b, a % b)
def compareTo(s1, s2):
"""Compares two strings and returns a value depending on the comparison of
the two strings.
Args:
s1(str): a string to be compared to another given string in the second
argument.
s2(str): a string to be compared to the first given argument (s1).
Returns:
int: A value corresponding with the comparison of two strings; A
positive value if s1 > s2, a negative value if s1 < s2, and 0 if they
are the same.
Examples:
>>> compareTo("abracadabra", "poof")
-112
>>> compareTo("lmno", "hijkl")
108
>>> compareTo("", "")
0
>>> compareTo("boo", "book")
-111
"""
if s1 == '' and s2 == '':
return 0
elif ord(s1[0]) > ord(s2[0]):
return 0 + ord(s1[0])
elif ord(s1[0]) < ord(s2[0]):
return 0 - ord(s2[0])
elif s1[1:2] == '' and not s2[1:2] == '':
return 0 - ord(s2[0])
elif s2[1:2] == '' and not s1[1:2] == '':
return 0 + ord(s1[0])
elif s1[1:2] == '' and s2[1:2] == '':
return 0
else:
return compareTo(s1[1:], s2[1:])
| true
|
7e50120d6e273dc64b440c847a7bfb4b2f8599da
|
PyladiesSthlm/study-group
|
/string_processing/elisabeth_anna.py
| 1,377
| 4.34375
| 4
|
#!/usr/bin/env python
import sys
import argparse
def palindrome_check(string_to_check):
letters_to_check = len(string_to_check)
if letters_to_check % 2 == 0:
letters_to_check = letters_to_check/2
else:
letters_to_check = (letters_to_check -1)/2
print letters_to_check
samma = 0
for i in range(letters_to_check):
if string_to_check[i] == string_to_check[len(string_to_check)-1-i]:
samma = samma +1
if letters_to_check == samma:
print "True"
return True
else:
print "False"
return False
def encrypt(number, string_to_encrypt):
new_string = ""
for i in range(len(string_to_encrypt)):
new_char = ord(string_to_encrypt[i]) + int(number)
new_letter = chr(new_char)
new_string = new_string + new_letter
print new_string
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Different string handling functions')
parser.add_argument("-e", "--encrypt", nargs = "+", help="use the encrypt function")
parser.add_argument("-p", "--palindrome", help="use the palindrome function")
args = parser.parse_args()
if args.encrypt:
encrypt(args.encrypt[1], args.encrypt[0])
elif args.palindrome:
palindrome_check(args.palindrome)
else:
print "no arguments"
| false
|
8d1de591706470db3bbcf26374ff958f393e85f7
|
tungnc2012/learning-python
|
/if-else-elif.py
| 275
| 4.21875
| 4
|
name = input("Please enter your username ")
if len(name) <= 5:
print("Your name is too short.")
elif len(name) == 8:
# print("Your name is 8 characters.")
pass
elif len(name) >= 8:
print("Your name is 8 or more characters.")
else:
print("Your name is short.")
| true
|
7de4e99e276c3e0ba73fc82112b55f7ee8190d5c
|
ayazzy/Plotter
|
/searches.py
| 1,673
| 4.1875
| 4
|
'''
This module has two functions.
Linear Search --> does a linear search when given a collection and a target.
Binary Search --> does a binary search when given a collection and a target.
output for both functions are two element tuples.
Written by: Ayaz Vural
Student Number: 20105817
Date: March 22nd 2019
'''
def linearSearch(collection,target):
count = 0
for item in collection:
count +=1
if target== item:
return target,count
return None, count
def binarySearch(collection,target):
low = 0
high = len(collection) - 1
count = 0
while high >= low:
count = count + 1
mid = (high + low) // 2
if target == collection[mid]:
return target, count
if target < collection[mid]:
high = mid - 1
else:
low = mid + 1
return None, count
if __name__ == "__main__":
print("~~TESTING~~")
aList = [1,2,3,4,5,6,7,8,9]
print(aList)
print("\n")
print("Testing the binarySearch function")
print("input is aList and target is 9. Expected output is 9 and 4 in a tuple")
print(binarySearch(aList,9 ))
print("\n")
print("input is the aList and target is 12. Since 12 is not in the list expected output is None and 4")
print(binarySearch(aList,12 ))
print("\n")
print("Testing the linearSearch function")
print("input is aList and target is 9. Expected output is 9 and 9 in a tuple")
print(linearSearch(aList,9))
print("\n")
print("input is aList and target is 11. Expected output is none and 9 in a tuple")
print(linearSearch(aList,11))
| true
|
a4b22a4a32ffa1afb1508d232388d6bc759e0485
|
avi651/PythonBasics
|
/ProgrammeWorkFlow/Tabs.py
| 233
| 4.125
| 4
|
name = input("Please enter your name: ")
age = int(input("Hi old are you, {0}? ".format(name))) #Adding type cast
print(age)
if age > 18:
print("You are old enough to vote")
else:
print("Please come back in {0}".format(18 - age))
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.