blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
59d4865c48cf12bac99b751cec480b1aa52b59c5 | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/simplify-path.py | 2,163 | 4.5 | 4 | """
# SIMPLIFY PATH
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period '.' refers to the current directory. Furthermore, a double period '..' moves the directory up a level.
Note that the returned canonical path must always begin with a slash '/', and there must be only a single slash '/' between two directory names. The last directory name (if it exists) must not end with a trailing '/'. Also, the canonical path must be the shortest string representing the absolute path.
Example 1:
Input: path = "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: path = "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: path = "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Example 4:
Input: path = "/a/./b/../../c/"
Output: "/c"
Constraints:
1 <= path.length <= 3000
path consists of English letters, digits, period '.', slash '/' or '_'.
path is a valid Unix path.
"""
def simplifyPath(path: str) -> str:
if len(path) == 1:
return "/"
res = "/"
path = path[1:]
if path[-1] != "/":
path += "/"
temp = ""
for x in path:
if x != "/":
temp += x
continue
else:
if temp == "" or temp == ".":
pass
elif temp == "..":
if res == "/":
pass
else:
t = len(res) - 2
while True:
if res[t] != "/":
res = res[:t]
t -= 1
else:
t -= 1
break
else:
res += temp + "/"
temp = ""
if len(res) > 2 and res[-1] == "/":
res = res[:len(res) - 1]
return res | true |
7028074d72039afc722149007fbae5fda2bba392 | SPARSHAGGARWAL17/DSA | /Linked List/linked_ques_4.py | 1,325 | 4.28125 | 4 | # reverse of a linked list
class Node():
def __init__(self,data):
self.data = data
self.nextNode = None
class LinkedList():
def __init__(self):
self.head = None
self.size = 0
def insertAtStart(self,data):
self.size += 1
node = Node(data)
currentNode = self.head
if self.head is None:
self.head = node
return
node.nextNode = currentNode
self.head = node
return
def display(self):
currentNode = self.head
if self.head is None:
print('List is Empty')
return
while currentNode is not None:
print('Data : ',currentNode.data)
currentNode = currentNode.nextNode
def reverse(self):
if self.head is None:
print('List is empty')
return
current = self.head
prev = None
while current is not None:
nextNode = current.nextNode
current.nextNode = prev
prev = current
current = nextNode
self.head = prev
link = LinkedList()
link.insertAtStart(4)
link.insertAtStart(3)
link.insertAtStart(2)
link.insertAtStart(1)
link.display()
link.reverse()
link.display() | true |
d9402c751d352b002fff94a55c3d4f322e231e8d | Unknown-Flyin-Wayfarer/pycodes | /9/testFor.py | 307 | 4.15625 | 4 | # i starts from 0, will increment by +1 stop at the range
for i in range(3):
print("My name is Amit, value of i = ",i)
for j in range(6,10):
print ("Value of j = ",j)
for z in range(10,50,5):
print("Value of z = ",z)
for y in range(100,10,-10):
print("value of y = ",y)
| false |
50dfd4b377425832e0a75179c16433e00d68ffda | Unknown-Flyin-Wayfarer/pycodes | /7/test_if4.py | 658 | 4.25 | 4 | a = int(input("enter first number"))
b = int(input("Enter second number"))
if a > b:
print("a is larger")
if a > 100:
print("a is also greater than 100")
if a > 1000:
print ("a is greater than 1000 also")
print("a is only greater than and not 1000")
print ("Thats enough")
if a > b and a > 100 and a > 1000:
print ("a is larger than b and 100 and 1000")
if b > a or b > 100 or b > 50:
print ("b has something to print")
print("Code exiting")
#input 3 numbers from user and find the largest
# input 6 numbers from the user and find the largest and smallest
| true |
7bfc463f05d5555ea2df2b2ca7d36a5a3e5d1d64 | aaroncymor/python-data-structures-and-algorithms | /Search and Sort/sort_implementation.py | 1,094 | 4.125 | 4 | # Hello World program in Python
def bubblesort(arr):
for i in range(len(arr)-1,0,-1):
for j in range(i):
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
return arr
def insertionsort(arr):
for i in range(1,len(arr)):
position = i
currentvalue = arr[position]
while position > 0 and arr[position-1] > currentvalue:
arr[position] = arr[position-1]
position = position - 1
arr[position] = currentvalue
return arr
def selectionsort(arr):
for i in range(len(arr),0,-1):
positionOfMax = 0
for j in range(1,i):
if arr[j] > arr[positionOfMax]:
positionOfMax = j
temp = arr[i-1]
arr[i-1] = arr[positionOfMax]
arr[positionOfMax] = temp
return arr
print "Bubble Sort", bubblesort([3,2,13,4,6,5,7,8,1,20])
print "Insertion Sort", insertionsort([3,2,13,4,6,5,7,8,1,20])
print "Selection Sort", selectionsort([3,2,13,4,6,5,7,8,1,20]) | false |
e0622163402f580a65518211eb3378994a15bec2 | rajeshpillai/learnpythonhardway | /ex9.py | 717 | 4.1875 | 4 | # Exercise 9: Printing, Printing, Printing
# By now you should realize the pattern for this book is to use more than one
# exercise to teach you something new. I start with code that you might not
# understand, then more exercises explain the concept. If you don't understand something now,
# you will later as you complete more exercises. Write down what you don't understand, and keep going.
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the days: ", days
print "here are the months: ", months
print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
| true |
e4288c0c6d4b3d2decad9a22a96a79fe8b9502b7 | rajeshpillai/learnpythonhardway | /ex31.py | 2,038 | 4.59375 | 5 | # Exercise 32: Loops and Lists
# You should now be able to do some programs that are much more interesting. If you have been keeping up, you should realize that now you can combine all the other things you have learned with if-statements and boolean expressions to make your programs do smart things.
# However, programs also need to do repetitive things very quickly. We are going to use a for-loop in this exercise to build and print various lists. When you do the exercise, you will start to figure out what they are. I won't tell you right now. You have to figure it out.
# Before you can use a for-loop, you need a way to store the results of loops somewhere. The best way to do this is with lists. Lists are exactly what their name says: a container of things that are organized in order from first to last. It's not complicated; you just have to learn a new syntax. First, there's how you make lists:
# hairs = ['brown', 'blond', 'red']
# eyes = ['brown', 'blue', 'green']
# weights = [1, 2, 3, 4]
# You start the list with the [ (left bracket) which "opens" the list. Then you put each item you want in the list separated by commas, similar to function arguments. Lastly, end the list with a ] (right bracket) to indicate that it's over. Python then takes this list and all its contents and assigns them to the variable.
the_count = [1,2,3,4,5]
fruits = ['apples', 'oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
# also we can go through mixed lists too
# notice we have use %r since we don't know what's in it
for i in change:
print "I got %r" % i
# we can also build lists, first start with an empty oranges
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print "Adding %d to the list." % i
# append is a function that lists understand
elements.append(i)
# now we can print them out too
for i in elements:
print "Element was : %d" % i
| true |
b6350d9fb8134ecb5fa0d840315140af1c905978 | mauriceLC92/LeetCode-solutions | /Arrays/Selection-sort.py | 607 | 4.125 | 4 | def find_smallest(arr):
smallestIndex = 0
smallestValue = arr[smallestIndex]
index = 1
while index < len(arr):
if arr[index] < smallestValue:
smallestValue = arr[index]
smallestIndex = index
index += 1
return smallestIndex
def selection_sort(arr):
sorted_array = []
arr_len = len(arr)
for i in range(arr_len):
smallest_value_position = find_smallest(arr)
sorted_array.append(arr.pop(smallest_value_position))
print(sorted_array)
return sorted_array
testArr = [5, 3, 6, 2, 10]
selection_sort(testArr)
| true |
a11dae4297dd98f1a75943a3a4e5143e8d716922 | prathamesh-collab/python_tutorials-pratham- | /inheritance.py | 603 | 4.21875 | 4 | #!/usr/bin/env python3.7
#for inheritance
class person:
def __init__(myo,fname,lname):
myo.fname=fname
myo.lname=lname
def printname(myo):
print("hello,my name is " + myo.fname,myo.lname)
#child class ,parent is person class
class student(person):
def __init__(self,fname,lname,year):
person.__init__(self,fname,lname)
self.graduationyear=year
def welcome(self):
print("welcome",self.fname,self.lname, "to the class of " , self.graduationyear)
x=student("pratham","sawant",2019)
x.printname()
print(x.graduationyear)
x.welcome()
| false |
6f5e1666083599d3d40180ba5a488f7dc4512c24 | prathamesh-collab/python_tutorials-pratham- | /practice.py/cal_2020-14.py | 961 | 4.125 | 4 | #!/usr/bin/env python3.7
def menu():
print("welcome")
print(" " )
print("1:- addition")
print("2: subtraction")
print("3:- multiplication")
print("4:- division")
print("5:- quit")
print(" " )
return int(input("chose your option "))
def add():
a = int(input("enter 1st value : "))
b = int(input("enter 2nd value : " ))
print(a + b )
def sub():
a = int(input("enter value :"))
b = int(input("enter value :"))
print(a - b )
def mul():
a = int(input("enter value : "))
b = int(input("enter value : "))
print(a * b )
def div():
a = int(input("enter value :"))
b = int(input("enter value : "))
print(a / b )
loop = 1
choice = 0
while loop == 1:
choice = menu()
if choice == 1:
add()
elif choice == 2:
sub()
elif choice == 3:
mul()
elif choice == 4:
div()
elif choice == 5:
loop = 0
print("thanks for using")
| false |
c6fb497553306801c5ee4c71ef33e19a832dd6f0 | has-g/HR | /fb_1_TestQuestions.py | 1,551 | 4.1875 | 4 | '''
In order to win the prize for most cookies sold, my friend Alice and
I are going to merge our Girl Scout Cookies orders and enter as one unit.
Each order is represented by an "order id" (an integer).
We have our lists of orders sorted numerically already, in lists.
Write a function to merge our lists of orders into one sorted list.
For example:
my_list = [3, 4, 6, 10, 11, 15]
alices_list = [1, 5, 8, 12, 14, 19]
# Prints [1, 3, 4, 5, 6, 8, 10, 11, 12, 14, 15, 19]
print merge_lists(my_list, alices_list)
Solution:
def merge_sorted_lists(arr1, arr2):
return sorted(arr1 + arr2)
'''
def merge_sorted_lists(arr1, arr2):
sorted_arr = []
idx1 = 0
idx2 = 0
if len(arr1) == 0: return arr2
if len(arr2) == 0: return arr1
count = 0
while count < len(arr2) + len(arr1):
print('count = ' + str(count) + ', idx1 = ' + str(idx1) + ', idx2 = ' + str(idx2) + ', sorted_arr = ' + str(sorted_arr))
if idx2 >= len(arr2):
# idx2 is exhausted
sorted_arr.append(arr1[idx1])
idx1 += 1
elif idx1 >= len(arr1):
# idx1 is exhausted
sorted_arr.append(arr2[idx2])
idx2 += 1
elif arr2[idx2] < arr1[idx1]:
sorted_arr.append(arr2[idx2])
idx2 += 1
else:
sorted_arr.append(arr1[idx1])
idx1 += 1
count += 1
return sorted_arr
print(merge_sorted_lists([2, 4, 6, 8], [1, 7]))
#print(merge_sorted_lists([], [1, 7]))
#print(merge_sorted_lists([2, 4, 6], [1, 3, 7]))
| true |
77d6e6cd9187f8c0b5dc63059a37a717873f3717 | OSUrobotics/me499 | /plotting/basic.py | 1,617 | 4.5 | 4 | #!/usr/bin/env python3
# Import the basic plotting package
# plt has all of the plotting commands - all of your plotting will begin with ply.[blah]
# To have this behave more like MatLab, do
# import matplotlib.pyplot
# in which case the plt scoping isn't needed
import matplotlib.pyplot as plt
# Get some things from numpy. The numpy sin function allows us to apply sin to an array of numbers all at once,
# rather than one at a time. Don't worry much about this for now, since we'll talk about it more when we cover
# numpy in more detail.
from numpy import arange, sin, pi
if __name__ == '__main__':
# This shows the basic plotting functionality. plot() can take an iterable, and will plot the values in it.
# It will assume that the x-values are 0, 1, 2, and so on. In this example, we're plotting a sine function
# from 0 to 2 * pi, in increments of 0.01. The x-axis, however, (since you didn't specify it) will go from
# 0 to the number of points (around 500). See better.py to specify both x and y
plt.plot(sin(arange(0, 2 * pi, 0.01)))
# Note that functionality differs depending on if you're running in the debugger and what operating system you're
# using. In debug/interactive mode, the window may show up when you do the plot command. In non-interactive
# mode it won't show up until you do show
# We'll only see the graph when you run show(). The program will stop here, until you kill the plot window.
# If you want the window to stay up when you step over this line in the debugger, use this instead:
# plt.show(block=True)
plt.show()
| true |
744b7479288431296863e7d8d2254c0cd58c1ea4 | OSUrobotics/me499 | /files/basics.py | 760 | 4.40625 | 4 | #!/usr/bin/env python3
if __name__ == '__main__':
# Open a file. The second argument means we're opening the file to write to it.
f = open('example_file', 'w')
# Write something to the file. You have to explicitly add the end of lines.
f.write('This is a string\n')
f.write('So is this\n')
# You can't guarantee that things are written to the file until you close it.
f.close()
# You open for reading like this
f = open('example_file', 'r')
# You can read with f.read(), f.readline(), or use the more convenient for loop approach. The end of line
# character is included in the string that gets assigned to the line variable.
for line in f:
print(line)
# Close the file again
f.close()
| true |
84eb498c2dc5b63eb5942e3bd057b1d2602c0348 | OSUrobotics/me499 | /control/while_loops.py | 613 | 4.3125 | 4 | #!/usr/bin/env python3
if __name__ == '__main__':
# This is the basic form a while statement. This particular example is better suited to a for loop, though, since
# you know how many times round the loop you're going to go.
n = 0
while n < 5:
print(n)
n += 1
# This is a better example of using a while loop, since we don't know how many times round the loop we need to go.
numbers = [1, 4, 3, 6, 7]
i = 0
while numbers[i] != 3:
i += 1
if i == len(numbers):
print('Did not find number')
else:
print('Number is in position', i)
| true |
23b5df5c6836f5759b1b820eb7d57fc51d9d70ff | OSUrobotics/me499 | /containers/list_comprehensions.py | 870 | 4.3125 | 4 | #!/usr/bin/env python3
from random import random
if __name__ == '__main__':
# Instead of enumerating all of the items in a list, you can use a for loop to build one. Start with an empty
# list.
a = []
# This will build a list of the first 10 even numbers.
for i in range(10):
a.append(i * 2)
print(a)
# There's a more compact syntax for this, called a list comprehension.
a = [2 * i for i in range(10)]
print(a)
# Here's a list of 5 random numbers, using the random() function
a = [random() for _ in range(5)]
print(a)
# Same code as below but with if and for written out
a = []
for i in range(10):
if i % 2 == 0:
a.append(i)
# You can put conditions on the list elements. This builds a list of even numbers.
a = [i for i in range(10) if i % 2 == 0]
print(a)
| true |
7730f652b4b1bb37f4e2b33533317aca526af6c0 | Mksourav/Python-Data-Structures | /stringlibraryfunction.py | 819 | 4.15625 | 4 | greet=input("Enter the string on which you want to perform the operation::")
# zap=greet.lower()
# print("lower case of the inputted value:",zap)
#
# search=input("Enter the substring you want the find:")
# pos=greet.find(search)
# if pos=='-1':
# print("substring not found!")
# else:
# print("substring spotted!")
# print("So, the position of the substring is ", pos)
#
# old=input("Enter the old substring you want to remove:")
# new=input("Enter the new substring you want to replace on old one:")
# nstr=greet.replace(old,new)
# print("Your new string is ", nstr)
lws=greet.lstrip()
print("String after removing the left whitespace:", lws)
rws=greet.rstrip()
print("String after removing the right whitespace:", rws)
ras=greet.strip()
print("String after removing both left & right whitespace:",ras)
| true |
78345b42e8ff3dc48545a9d4d3bd1aeac5b74eef | HighPriestJonko/Anger-Bird | /Task1.py | 1,366 | 4.15625 | 4 | import math
v = int(input('Enter a velocity in m/s:')) # With which bird was flung
a = int(input('Enter an angle in degrees:')) # With respect to the horizontal
d = int(input('Enter distance to structure in m:'))
h = int(input('Enter a height in m:')) # Height of structure
g = -9.8 # m/s^2
degC = math.pi / 180
ar = a * degC # Degrees into radians for computational purposes
# Tips to you, you should use meaningful name for variables,
# instead of using x,y,z and it is a bad thing.
horizontal_speed = v * math.cos(ar)
vertical_speed = v * math.sin(ar)
t = d / horizontal_speed # Time to reach structure
vf_vertical = vertical_speed + g*t # Final vertical velocity
dy = (vertical_speed * t) + ((1/2) * g * (t ** 2)) # Vertical position
dx = horizontal_speed * t # Horizontal position
v_co_speed = math.sqrt(vf_vertical * vf_vertical + horizontal_speed * horizontal_speed)
degrees = math.acos(horizontal_speed / v_co_speed) * 180 / math.pi
print('Did the Red Bird hit the structure? Let\'s review the results:\n')
print('Your Red Bird reached the structure in ', t, 's')
print('and was traveling at a velocity of ', v_co_speed, 'm/s')
print(' at an angle of ', degrees, "below the horizontal")
print('The Red Bird was at a height of', dy + h, 'm from the ground')
print('when it reached your intended structure, so your Red Bird', '', 'the structure.')
| true |
8b11e8566191510812c33c50c77a9c4610904130 | ajakaiye33/pythonic_daily_capsules | /apythonicworkout_book/pig_latin.py | 1,814 | 4.21875 | 4 |
def pig_latin():
"""
The program should asks the user to enter an english word. your program should
then print the word, translated into Pig Latin.
If the word begins with a vowel(a,e,i,o,u), then add way to the end of the word e.g
so "air" becomes "airway" eat becomes "eatway"
if the word begin with any other letter, put it on the end of the word and then add "ay"
so python becomes "ythonpay"
"""
your_word = input("type a word > ")
vowel = "aeiou"
if your_word[0] in vowel:
wayword = your_word[1:] + "way"
else:
frst_word = your_word[0]
wayword = your_word[1:] + frst_word + "ay"
return wayword
print(pig_latin())
Bonus
def pig_latin2():
"""
if the word contains two different vowels "way" should added at its end but if
it contain one vowel the first word should placed at it end and subsequently add "ay"
"""
the_vow = "aeiou"
counter = []
ask_word = input("Give us a word > ")
for i in the_vow:
if i in ask_word:
counter.append(i)
if len(counter) == 2:
res = f"{ask_word}way"
else:
res = f"{ask_word[1:]}{ask_word[0]}ay"
return res
print(pig_latin2())
def pig_latin3():
fly = []
vow_the = "aeiou"
the_sentence = input("Lets have your sentence > ")
for word in the_sentence.split():
if word[0] in vow_the:
fly.append(f"{word}way")
else:
fly.append(f"{word[1:]}{word[0]}ay")
return " ".join(fly)
print(pig_latin3())
# Morsels python problem
def unique_only(lst):
return [i for i in set(lst)]
print(unique_only([1, 2, 2, 1, 1, 3, 2, 1]))
# print(unique_only())
nums = [1, -3, 2, 3, -1]
sqr = [i**2for i in nums]
print(unique_only(sqr))
| true |
25223ab1874f7cf1e492040faba073faba3881a4 | ajakaiye33/pythonic_daily_capsules | /make_car_drive.py | 469 | 4.125 | 4 |
class Car(object):
"""
make a car that drive
"""
def __init__(self, electric):
"""
receives a madatory argument: electric
"""
self. electric = electric
def drive(self):
if not self.electric:
return "VROOOOM"
else:
return "WHIRRRRRRRR"
car1 = Car(electric=False)
print(car1.electric)
print(car1.drive())
car2 = Car(electric=True)
print(car2.electric)
print(car2.drive())
| true |
44be8c3c7f6920bdb8329af683afa045634d682e | ajakaiye33/pythonic_daily_capsules | /concatenate_string.py | 602 | 4.34375 | 4 |
def concatenate_string(stringy1, stringy2):
"""
A function that receives two strings and returns a new one containing both
strings cocatenated
"""
return "{} {}".format(stringy1, stringy2)
print(concatenate_string("Hello", "World"))
print(concatenate_string("Hello", ""))
# some other way...
def concatenate_string(string1, stringy2):
"""
A function that receives two strings and returns a new one containing both
strings cocatenated
"""
return string1 + " " + stringy2
print(concatenate_string("Hello", "World"))
print(concatenate_string("Hello", ""))
| true |
7ba818effcd4db9905ca6814f4679184224e9d27 | ajakaiye33/pythonic_daily_capsules | /color_mixer.py | 970 | 4.25 | 4 |
def color_mixer(color1, color2):
"""
Receives two colors and returns the color resulting from mixing them in
EITHER ORDER. The colors received are either "red", "blue", or "yellow" and
should return:
"Magenta" if the colors mixed are "red" and "blue"
"Green" if the colors mixed are "blue" and "yellow"
"Orange" if the color mixed are "yellow" and "red"
"""
if (color1 == "red" and color2 == "blue") | (color2 == "red" and color1 == "blue"):
res = "Magenta"
elif (color1 == "blue" and color2 == "yellow") | (color2 == "blue" and color1 == "yellow"):
res = "Green"
elif (color1 == "yellow" and color2 == "red") | (color2 == "yellow" and color1 == "red"):
res = "Orange"
return res
print(color_mixer("red", "blue"))
print(color_mixer("blue", "red"))
print(color_mixer("blue", "yellow"))
print(color_mixer("yellow", "red"))
print(color_mixer("red", "yellow"))
print(color_mixer("yellow", "blue"))
| true |
195b3d1288769e60d0aa6d0023f308a6e0675523 | ajakaiye33/pythonic_daily_capsules | /make_number_odd.py | 288 | 4.25 | 4 |
def make_number_odd(num):
"""
Receives a number, adds 1 to that number if it's even and returns the number
if the original number passed is odd, just return it
"""
if num % 2 == 0:
num += 1
return num
print(make_number_odd(2))
print(make_number_odd(5))
| true |
d46bd897ee359b69d2f3fc29d7d6803883590c23 | rhydermike/PythonPrimes | /primes.py | 1,641 | 4.40625 | 4 | #Prime number sieve in Python
MAXNUMBER = 1000 #Total number of numbers to test
results = [] #Create list to store the results
for x in range (1,MAXNUMBER): #Begin outer for loop to test all numbers between 1 and MAXNUMBER
isprime = True #Set boolean variable isprime to True
for y in range (2, x - 1): #Begin inner for loop. The divisiors shall be every number between (but not including) 1 and the number itself
if x % y == 0: #Check to see if the remainder of x divided by y is 0. If so, carry out next bit of code.
isprime = False #If so, set isprime to False. It's not a prime, in other words.
break #Break out of the loop if the number isn't prime. There's no point of continuing to test this number.
if isprime == True: #Following the tests, if x/y was never found to have a remainder of 0, set isprime to True
results.append(x) #If so, add the prime number to the list
message = str(x) + " is a prime"; #Create notification string that current number is prime
print (message) #Print notification that current number is prime
def show_results(): #Define a funtion to show the results
print ("The complete list of primes between 1 and "+str(MAXNUMBER)) # Print text explaining what the list is
for x in results: #Begin a for loop that visits every result in the list
print (x), #Print current entry in the list
show_results() #Call the function that shows the results that are stored in the list
| true |
4221e1c6df47872d910c462da5e3aff516755f86 | doctor-blue/python-series | /Intermediate/strings.py | 503 | 4.15625 | 4 | # a = "Hello\nWorld"
# a = '''Lorem ipsum dolor sit amet,
# consectetur adipiscing elit,
# sed do eiusmod tempor incididunt
# ut labore et dolore magna aliqua.'''
# print(a)
# a = 'Hello'
# print(a[-5])
# print(len("banana"))
# for x in "banana":
# print(len(x))
# print("ca" not in "banana")
a = "Hello, world"
# print(a[2:])
# print(a.lower())
# print(a.strip())
# print(a.replace("ll",'a'))
# print(a.split(','))
age = 21
text = 'My name is Tan, and I am {} '
print(text.format(age))
| false |
3b25e59cd8ef2f769e36aca0497e4dd7b9db38ad | SamJ2018/LeetCode | /python/python语法/pyexercise/Exercise04_39.py | 744 | 4.21875 | 4 | import turtle
x1, y1, r1 = eval(input("Enter circle1's center x-, y-coordinates, and radius: "))
x2, y2, r2 = eval(input("Enter circle2's center x-, y-coordinates, and radius: "))
# Draw circle 1
turtle.penup()
turtle.goto(x1, y1 - r1)
turtle.pendown()
turtle.circle(r1)
# Draw circle 2
turtle.penup()
turtle.goto(x2, y2 - r2)
turtle.pendown()
turtle.circle(r2)
turtle.penup()
turtle.goto(x1 - r1, y1 - r1 - 30)
turtle.pendown()
distance = ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) ** 0.5
if distance + r2 <= r1:
turtle.write("circle2 is inside circle1")
elif distance <= r1 + r2:
turtle.write("circle2 overlaps circle1")
else:
turtle.write("circle2 does not overlap circle1")
turtle.hideturtle()
turtle.done()
| false |
7a02905d8b244c6e96eb871ff8099d6c0db26e03 | SamJ2018/LeetCode | /python/python语法/pyexercise/Exercise04_11.py | 1,309 | 4.125 | 4 | # Prompt the user to enter input
month = eval(input("Enter a month in the year (e.g., 1 for Jan): "))
year = eval(input("Enter a year: "))
numberOfDaysInMonth = 0;
if month == 1:
print("January", year, end = "")
numberOfDaysInMonth = 31;
elif month == 2:
print("February", year, end = "")
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
numberOfDaysInMonth = 29;
else:
numberOfDaysInMonth = 28;
elif month == 3:
print("March", year, end = "")
numberOfDaysInMonth = 31;
elif month == 4:
print("April", year, end = "")
numberOfDaysInMonth = 30;
elif month == 5:
print("May", year, end = "")
numberOfDaysInMonth = 31;
elif month == 6:
print("June", year, end = "")
numberOfDaysInMonth = 30;
elif month == 7:
print("July", year, end = "")
numberOfDaysInMonth = 31;
elif month == 8:
print("August", year, end = "")
numberOfDaysInMonth = 31;
elif month == 9:
print("September", year, end = "")
numberOfDaysInMonth = 30;
elif month == 10:
print("October", year, end = "")
numberOfDaysInMonth = 31;
elif month == 11:
print("November", year, end = "")
numberOfDaysInMonth = 30;
else:
print("December", year, end = "")
numberOfDaysInMonth = 31;
print(" has", numberOfDaysInMonth, "days")
| true |
8eed6f99e34f720e1b6a2c0e7d406e938fbc11ff | SamJ2018/LeetCode | /python/python语法/pyexercise/Exercise11_27.py | 738 | 4.1875 | 4 | def main():
SIZE = 3
print("Enter a 3 by 3 matrix row by row: ")
m = []
for i in range(SIZE):
line = input().split()
m.append([eval(x) for x in line])
print("The column-sorted list is ")
printMatrix(sortColumns(m))
def reverse(m):
for i in range(len(m)):
for j in range(i, len(m[i])):
m[i][j], m[j][i] = m[j][i], m[i][j]
def printMatrix(m):
for i in range(len(m)):
for j in range(len(m[i])):
print(m[i][j], end = " ")
print()
def sortColumns(m):
result = []
for row in m:
result.append(row)
reverse(result)
for row in result:
row.sort()
reverse(result)
return result
main()
| false |
be6bed1c6c15377c1bd5d78c321d8413fcb85bf5 | SamJ2018/LeetCode | /python/python语法/pyexercise/Exercise06_17.py | 643 | 4.28125 | 4 | import math
def main():
edge1, edge2, edge3 = eval(input("Enter three sides in double: "))
if isValid(edge1, edge2, edge3):
print("The area of the triangle is", area(edge1, edge2, edge3))
else:
print("Input is invalid")
# Returns true if the sum of any two sides is
# greater than the third side.
def isValid(side1, side2, side3):
return (side1 + side2 > side3) and \
(side1 + side3 > side2) and (side2 + side3 > side1)
# Returns the area of the triangle.
def area(side1, side2, side3):
s = (side1 + side2 + side3) / 2
return math.sqrt(s * (s - side1) * (s - side2) * (s - side3))
main()
| true |
2608df1e9d7d7a7dabfc23600cc0ab47b70883a3 | EvgenyTyurin/Dictionary-demo | /dict.py | 571 | 4.34375 | 4 | # Bill Lubanovich "Introducing Python"
# Chapter 3, Exercises 10-14: Dictionary demo
# English/French dictionary
e2f = {
"dog": "chien",
"cat": "chat",
"walrus": "morse"}
print("English/French dictionary: " + str(e2f))
# Walrus in french?
print("walrus in french = " + e2f["walrus"])
# Make French/English dictionary from English/French dictionary
f2e = {}
word_list = list(e2f.items())
for pare in word_list:
f2e[pare[1]] = pare[0];
print("French\English dictionary: " + str(f2e))
# Chien?
print("chien means = " + f2e["chien"])
| false |
0a685439e88369e8b563d1960fa8fc846e9fe2d5 | Renatabfv/T-cnicas-de-Programa-o | /projeto_2.py | 1,332 | 4.15625 | 4 | #cadastrar novos usuários pelo seu nome completo e e-mail
#exibir todos os usuários cadastrados, listando-os por ordem de cadastro.
#exibir todos os usuários cadastros, listando-os por ordem alfabética.
#um usuário faz parte da lista de participantes, buscando-o pelo seu nome.
#remover um usuário cadastrado, buscando-o por seu e-mail.
#poder alterar o nome de um usuário cadastrado no sistema, buscando-o por seu e-mail.
def criarEstudante():
estudanteTemp = {}
estudanteTemp["nome"] = input("Digite o nome do estudante: ")
estudanteTemp["email"] = input("Digite o email do estudante: ")
return estudanteTemp
def mostrarNomesEstudante(listaEstudante):
for estudante in listaEstudante:
print(estudante["nome"])
def main():
listaEstudante = [ ]
qtdEstudante = int(input("Informe quantos estudantes você deseja salvar na lista: "))
ordemAlfabetica = (input("Deseja ordernar os usuarios por ordem alfabetica ?"))
contador = 0
while(contador < qtdEstudante):
estudanteTemp = criarEstudante()
listaEstudante.append(estudanteTemp)
contador = contador + 1
if (ordemAlfabetica) == ("sim" or "Sim"):
mostrarNomesEstudante(listaEstudante.sort())
else:
mostrarNomesEstudante(listaEstudante)
if (__name__) == ("__main__"):
main()
| false |
5a326e8c133c4fb3fc2d0581f1c8d6c7feb72376 | Ayman-M-Ali/Mastering-Python | /Assignment_015.py | 2,725 | 4.15625 | 4 | #--------------------------------------------------------
# Assignment (1):
# Write the following code to test yourself and do not run it
# After the last line in the code write a comment containing the Output that will come out from your point of view
# Then run Run to see your result sound or not
# Make a comment before each of the lines in the code to explain how this result appeared
#--------------------------------------------------------
# var => Type of value is Tuple
values = (0, 1, 2)
# if statement : any of values is True:
if any(values):
# Create new var => give value => Zero
my_var = 0
# Create List That contains True Type Element
my_list = [True, 1, 1, ["A", "B"], 10.5, my_var]
# If All values into List (with Index) Is True :
if all(my_list[:4]) or all(my_list[:6]) or all(my_list[:]):
# Give Result "Good"
print("Good")
else:
# Give Result "Bad"
print("Bad")
# The result is Good
print("##### End Assignment (1) #####")
#-------------------------------------------------------
# Assignment (2):
# What is the value of v that causes the print to output the number 820
#-------------------------------------------------------
v = 40
my_range = list(range(v))
print(sum(my_range, v) + pow(v, v, v)) # 820
print("##### End Assignment (2) #####")
#-------------------------------------------------------
# Assignment (3):
# What is the value of the variable n
#-------------------------------------------------------
n = 20
l = list(range(n))
if round(sum(l) / n) == max(0, 3, 10, 2, -100, -23, 9):
print("Good")
print("##### End Assignment (3) #####")
#-------------------------------------------------------
# Assignment (4):
# Create a function that does the same thing as all and call it my_all
# Create a function that does the same as any and call it my_any
# Create a function that does the same as the min and call it my_min
# Create a function that does the same as the max and call it my_max
# Make sure my_min + my_max accepts List or Tuple
#-------------------------------------------------------
# func all()
def my_all(nums):
for n in nums :
if not n :
return False
return True
print(my_all([1, 2, 3]))
print(my_all([1, 2, 3, []]))
# func any()
def my_any(nums):
for n in nums :
if n :
return True
return False
print(my_any([1, 2, 3]))
print(my_any([0, (), False, []]))
# func min()
def my_min(nums):
for n in nums :
if n == min(nums):
return n
print(my_min([1, 2, 3, -10, -100]))
print(my_min((1, 2, 3, -10, -100)))
# func max()
def my_max(nums) :
for n in nums :
if n == max(nums) :
return n
print(my_max([10, 20, -50, 700]))
print(my_max((10, 20, -50, 700)))
| true |
073cb8b4c68463b903c6b033228e849ca8a1136f | Athithya6/Python-Programs | /trial4.py | 901 | 4.25 | 4 | # List comprehensions and while loop
# Celsius to fahrenheit using ordinary for loop
'''
celsius = [12.5, 36.6, 37, 43, 49]
fahrenheit = []
for i in celsius:
caltemp = (((9 / 5) * i) + 32)
fahrenheit.append(caltemp)
print("Input Celsius tempertures in fahrenheit: ", fahrenheit)
'''
'''
# Celsius to fahrenheit using list comprehension
c = [12.5, 36, 6, 37, 43, 49]
f = [((9 / 5) * i) + 32 for i in c]
print(f)
'''
'''
result = ["MULTIPLE OF 3" if x % 3 == 0 else "NON-MULTIPLE OF 3" for x in range(1, 20)]
print(result)
x = [i*j for i in range(1, 10) for j in range(1, 6)]
print (x)
'''
# while loop
'''
k=5
while(k>0):
print(k)
k-=1
if(k==2):
continue
print("while loop execution complete")
'''
k=10
while(k>1):
if(k==8):
k-=1
continue
if(k==1):
break
print(k)
k-=1
| false |
694a06ab8f7ca681fb5b16f273cb2be1f725abbd | Lydia-Li725/python-basic-code | /排序.py | 369 | 4.1875 | 4 | def insertion_sort(array):
for index in range(1,len(array)):
position = index
temp_value = array[index]
while position > 0 and array[position - 1] > temp_value:
array[position] = array[position-1]
position -= 1
array[position] = temp_value
return array
a = [1,7,6,3,2,4]
print(insertion_sort(a)) | true |
027ddb1b8268b0d843d0c987d8c31eda833b9bbf | mxmaria/coursera_python_course | /week5/Ближайшее число.py | 562 | 4.125 | 4 | # Напишите программу, которая находит в массиве элемент, самый близкий по величине к данному числу.
n = int(input())
mass_elems = list(map(int, input().split()))
diff_from_number = int(input())
min_diff_elem = mass_elems[0]
min_diff = abs(min_diff_elem - diff_from_number)
for elem in mass_elems:
current_diff = abs(diff_from_number - elem)
if current_diff < min_diff:
min_diff = current_diff
min_diff_elem = elem
print(min_diff_elem)
| false |
b1f37d0a9a5d003672c1c3d17a2c72b0a9094b57 | mxmaria/coursera_python_course | /week4/Быстрое возведение в степень.py | 709 | 4.375 | 4 | # Возводить в степень можно гораздо быстрее, чем за n умножений!
# Для этого нужно воспользоваться следующими рекуррентными соотношениями: aⁿ = (a²)ⁿ/² при четном n, aⁿ=a⋅aⁿ⁻¹ при нечетном n.
# Реализуйте алгоритм быстрого возведения в степень.
def power(a, n):
if n == 0:
return 1
elif n == 1:
return a
elif n % 2 != 0:
return a * power(a, n - 1)
elif n % 2 == 0:
return power(a * a, n / 2)
a = float(input())
n = int(input())
print(power(a, n))
| false |
b79fe6a6d388f0bc02d2ac304582ad39a54811c5 | mxmaria/coursera_python_course | /week3/Цена товара.py | 745 | 4.125 | 4 | # Цена товара обозначена в рублях с точностью до копеек, то есть действительным числом с двумя цифрами после десятичной точки.
# Запишите в две целочисленные переменные стоимость товара в виде целого числа рублей и целого числа копеек и выведите их на экран.
# При решении этой задачи нельзя пользоваться условными инструкциями и циклами.
import math
price = float(input())
rub = math.floor(price)
kop = round((price - rub) * 100)
print(rub, kop, sep=' ')
| false |
26dafe823f7870dd47096c8e4bb4cb809cb95a0b | mxmaria/coursera_python_course | /week2/Узник замка Иф.py | 985 | 4.1875 | 4 | # За многие годы заточения узник замка Иф проделал в стене прямоугольное отверстие размером D×E.
# Замок Иф сложен из кирпичей, размером A×B×C. Определите, сможет ли узник выбрасывать кирпичи в море через это отверстие (очевидно, стороны кирпича должны быть параллельны сторонам отверстия).
# Программа получает на вход числа A, B, C, D, E.
# Программа должна вывести слово YES или NO.
A, B, C = int(input()), int(input()), int(input())
D, E = int(input()), int(input())
if A <= D and B <= E or A <= E and B <= D:
print('YES')
elif B <= D and C <= E or B <= E and C <= D:
print('YES')
elif A <= D and C <= E or A <= E and C <= D:
print('YES')
else:
print('NO')
| false |
acbf854d06bfa1e458cf65cca8af844fb40cd094 | swavaldez/python_basic | /01_type_and_statements/04_loops.py | 620 | 4.21875 | 4 | # student_names = []
student_names = ["Mark", "Katarina", "Jessica", "Sherwin"]
print(len(student_names))
# for loops
for name in student_names:
print("Student name is {0}".format(name))
# for range
x = 0
for index in range(10):
x += 10
print("The value of x is {0}".format(x))
# start in 5 and ends in 9
for index in range(5, 9):
x += 10
print("The value of x is {0}".format(x))
# index increase by 2
for index in range(5, 9, 2):
x += 10
print("The value of x is {0}".format(x))
for index in range(len(student_names)):
print("Student name is {0}".format(student_names[index]))
| true |
214f5b112c81efed5de997dd92b72e35383da87d | eMUQI/Python-study | /python_book/basics/chapter03_list/03-08.py | 352 | 4.125 | 4 | list_of_place = ['hangzhou','shanghai','meizhou','xian','beijing']
#1
print(list_of_place)
print(sorted(list_of_place))
print(list_of_place)
print(sorted(list_of_place,reverse = True))
print(list_of_place)
list_of_place.reverse()
print(list_of_place)
list_of_place.sort()
print(list_of_place)
list_of_place.sort(reverse = True)
print(list_of_place) | false |
a1ba2026687b109cdd7c72113cc222d4cffdd804 | cassandraingram/PythonBasics | /calculator.py | 1,427 | 4.1875 | 4 | # calculator.py
# Cassie Ingram (cji3)
# Jan 22, 2020
# add function adds two inputs
def add(x, y):
z = x + y
return z
#subtract function subtracts two inputs
def subtract(x, y):
z = x - y
return z
# multiply function multiplies two inputs
def multiply(x, y):
z = x * y
return z
# divide function divides two inputs
def divide(x, y):
z = x / y
return z
# modulee calls each function using the numbers 47 and 7 and
# then prints the results of each function
a = add(47, 7)
print("47 + 7 = {}" .format(a))
s = subtract(47, 7)
print("47 - 7 = {}" .format(s))
m = multiply(47, 7)
print("47 * 7 = {}" .format(m))
d = divide(47, 7)
print("47 / 7 = {}" .format(d))
###### additional practice
# prompt user to enter two numbers and the operation they
# want to perform
n1, n2, opp = input("Enter two integers and an operation, separated by a comma: ").split(", ")
# converet input numbers to integer type variables
n1 = int(n1)
n2 = int(n2)
# perform action based on what was entered
if opp == "add":
solution = add(n1, n2)
print("{} + {} = {}" .format(n1, n2, solution))
elif opp == "subtract":
solution = subtract(n1, n2)
print("{} - {} = {}" .format(n1, n2, solution))
elif opp == "multiply":
solution = multiply(n1, n2)
print("{} * {} = {}" .format(n1, n2, solution))
elif opp == "divide":
solution = divide(n1, n2)
print("{} / {} = {}" .format(n1, n2, solution))
else:
print("Not a valid operation.")
| true |
9527efcef31dba3ca25ec33f2115ebfc5ec1d53a | snowpuppy/linux_201 | /python_examples/example1/guessnum.py | 855 | 4.21875 | 4 | #!/usr/bin/env python
#Here we import the modules we need.
import random
random.seed() #We need to seed the randomizer
number = random.randint(0,100) #and pull a number from it.
trys = 10 #We're only giving them 10 tries.
guess = -1 #And we need a base guess.
while guess != number and trys != 0: #So, we need to let them guess if they haven't guessed and if they have tries left
guess = int(raw_input("Guess a number from 0 to 100: ")) #Get the input from them.
if guess < number: #Yell at them that they're wrong.
print "Guess Higher!"
elif guess > number:
print "Guess Lower!"
trys = trys - 1 #Decrease the number of tries.
if guess == number: #Once we break out of the while, if they were right, tell them so, otherwise tell them they were wrong.
print "Congratulations! You guessed correcty!"
else:
print "The answer was " + number
| true |
26f06216b4cf66c2bb236dccb89ae7cf0d7b2713 | rchristopfel/IntroToProg-Python-Mod07 | /Assignment07.py | 2,304 | 4.125 | 4 | # ------------------------------------------------------------------------ #
# Title: Assignment 07
# Description: using exception handling and Python’s pickling module
# ChangeLog (Who,When,What):
# Rebecca Christopfel, 11-18-19, test pickle module
# Rebecca CHristopfel, 11-20-19, create try/except block for script
# ------------------------------------------------------------------------ #
# Pickling Example
# To store user demographic data
import pickle
# create some data to be pickled
strFirstName = str(input("Enter your first name: "))
strLastName = str(input("Enter your last name: "))
strAge = str(input("Enter your age: "))
strNumber = str(input("Enter your phone number: "))
demoData = [strFirstName, strLastName, strAge, strNumber]
print(demoData)
# store the data with the pickle.dump method
file = open("Demo.dat", "ab")
pickle.dump(demoData, file)
file.close()
# read the data back with the pickle.load method
file = open("Demo.dat", "rb")
fileData = pickle.load(file)
file.close()
print(fileData)
# Exception Handling
# To show calculation of age in years (and fraction of years) based on user's birthday
print("\n_____________________________________\n")
print("Now we'll do the exception handling...\n")
print("_____________________________________\n")
import datetime
today = datetime.date.today()
userBirthMonth = 0
userBirthDay = 0
userBirthYear = 0
while 1 > userBirthMonth or 12 < userBirthMonth:
try:
userBirthMonth = int(input("\nEnter your birth month (1-12): "))
except ValueError:
print("Oops! That is not a valid number. Try 1-12...")
while 1 > userBirthDay or 31 < userBirthDay:
try:
userBirthDay = int(input("\nEnter your birth day (1-31): "))
except ValueError:
print("Oops! That is not a valid number. Try 1-31...")
while True:
try:
userBirthYear = int(input("\nEnter your birth year: "))
break
except ValueError:
print("Oops! That is not a valid number. Try format (yyyy) ...")
userBirthDate = datetime.date(userBirthYear, userBirthMonth, userBirthDay)
dateDiff = (today - userBirthDate)
userAge = round(float(dateDiff.days / 365.25), 2)
print("\n\tRounding to the nearest hundredth of a decimal, you are " + str(userAge) +" years old!")
| true |
919d4323cdb5dd99e5aff75710d00fe279bbf712 | XavierKoen/lecture_practice_code | /guessing_game.py | 254 | 4.125 | 4 | question = input("I'm thinking of a number between 1 and 10, what is it? ")
ANSWER = '7'
print(question)
while question != ANSWER:
question = input("Oh no, please try again. ")
print (question)
print("Congrtulations! You were correct, it was 7!") | true |
1a8f986972d5f0ec326aaeb3f901cc259bf47ecd | XavierKoen/lecture_practice_code | /name_vowel_reader.py | 786 | 4.125 | 4 | """
Asks user to input a name and checks the number of vowels and letters in the name.
"""
def main():
name = input("Name: ")
number_vowels = count_vowels(name)
number_letters = count_letters(name)
print("Out of {} letters, {}\nhas {} vowels".format(number_letters, name, number_vowels))
def count_vowels(string):
number_of_vowels = 0
vowels = "AaEeIiOoUu"
for char in string:
if char in vowels:
number_of_vowels = number_of_vowels + 1
return number_of_vowels
def count_letters(string):
number_of_letters = 0
letters = "abcdefghijklmnopqrstuvwxyz"
string = string.lower()
for char in string:
if char in letters:
number_of_letters = number_of_letters + 1
return number_of_letters
main()
| true |
04cb412cecc6d49bd15ebde03cc729f51d1e19aa | milanvarghese/Python-Programming | /Internshala/Internshala Assignments/W5 Assignment - Connecting to SQLite Database/insert_data.py | 1,124 | 4.28125 | 4 | #Importing Necessary Modules
import sqlite3
#Establishing a Connection
shelf=sqlite3.connect("bookshelf.db")
curshelf=shelf.cursor()
#Creating a table with error check
try:
curshelf.execute('''CREATE TABLE shelf(number INT PRIMARY KEY NOT NULL ,title TEXT NOT NULL, author TEXT STRING, price FLOAT NOT NULL);''')
shelf.commit()
print("Table Created SUCCESSFULLY!")
except:
print("ERROR in Creating a New Table!")
shelf.rollback()
cont="y"
#Accepting the variables from the USER
while cont=="y":
number=input("Enter Book Index: ")
title=str(input("Title: "))
author=str(input("Author: "))
price=int(input("Price: "))
#Inserting the values into the records
try:
curshelf.execute("INSERT INTO shelf(number,title,author,price) VALUES(?,?,?,?)",(number,title,author,price))
shelf.commit()
print("Record ADDED SUCCESSFULLY!")
except:
print("ERROR in INSERT query!")
shelf.rollback()
cont=input("Add More Records? Y/N: ")
if cont=="n" or cont=="N":
print("DATA Entry Complete")
break;
#Closing the Connection
shelf.close()
| true |
76f3fe078aebe4ede0b70767e19ba901e4a7d7b7 | CamiloBallen24/Python-PildorasInformaticas | /Script's/00 - Otros/Metodos de Cadenas.py | 1,029 | 4.4375 | 4 | #TEMA: METODOS DE CADENA
################################################################
print("Ejemplo #1")
miCadena = "Hola"
print(miCadena.upper()) #Pasa a mayusculas tooo
print()
print()
print()
################################################################
################################################################
print("Ejemplo #2")
miCadena = "Hola"
print(miCadena.lower()) #Pasa todo a minuscula
print()
print()
print()
################################################################
################################################################
print("Ejemplo #3")
miCadena = "hOlA cOmo ESTAS"
print(miCadena.capitalize()) #primera letra en mayuscula y resto en minuscula
print()
print()
print()
################################################################
################################################################
print("Ejemplo #4")
edad = "123"
print(edad.isdigit()) #Comprueba si es un digito
print()
print()
print()
################################################################
| false |
dc73601bced9a16c9b52abdb42a53b04df5da287 | Ktheara/learn-python-oop | /advaced-review/2.tuple.py | 959 | 4.5625 | 5 | # A tuple is a collection of objects which is ordered and immutable(unchangeable).
# https://www.python-engineer.com/courses/advancedpython/02-tuples/
# So similar to list but elements are protected
mytuple = ('a', 'p', 'p', 'l', 'e') #create a tuple
print(mytuple)
# number of elements
print(len(mytuple))
# number of x element
print(mytuple.count('p'))
# index of first item that equal to x
print(mytuple.index('p'))
# repetition
yourtuple = ('a', 'b') * 5
print('Your tuple is :', yourtuple)
# concatenation
ourtuple = mytuple + yourtuple
print('Our tuple is: ', ourtuple)
# convert list to tuple
mylist = ['a', 'b', 'c', 'd']
list2tuple = tuple(mylist)
print('Converted list to tuple: ', list2tuple)
# convert string to tuple
str2tuple = tuple("Hello")
print('Converted string to tuple: ', str2tuple)
# unpacke tuple
myinfo = ('Theara', 25, 'Mechatronics Engineer')
name, age, job = myinfo
print('Name: ', name, ' age: ', age, ' and job: ', job) | true |
d7948b4af779d68ed87af1d832c4cf6c558ec274 | cuongv/LeetCode-python | /BinaryTree/PopulatingNextRightPointersInEachNode.py | 2,802 | 4.21875 | 4 | #https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
"""
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Follow up:
You may only use constant extra space.
Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
Example 1:
Input: root = [1,2,3,4,5,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B.
The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Constraints:
The number of nodes in the given tree is less than 4096.
-1000 <= node.val <= 1000
#Solution 1: BFS travel tree by levels -> O(n)
#Solution 2:
We only move on to the level N+1 when we are done establishing the next pointers for the level N.
Since we have access to all the nodes on a particular level via the next pointers,
we can use these next pointers to establish the connections for the next level or the level containing their children.
# Definition for a Node.
class Node(object):
def __init__(self, val=0, left=None, right=None, next=None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
from collections import deque
class Solution(object):
#O(1) solution
def connect(self, root):
if not root:
return None
leftMost = root
node = leftMost
while leftMost.left:
node.left.next = node.right
if node.next:
node.right.next = node.next.left
node = node.next
else:
leftMost = leftMost.left
node = leftMost
return root
#My O(n) solution
"""
def connect(self, root):
if not root:
return None
q = deque([root])
while q:
prev = None
count = len(q)
for i in range(count):
node = q.popleft()
if prev:
prev.next = node
prev = node
if node.left:
q.append(node.left)
q.append(node.right)
prev = None
return root
"""
"""
:type root: Node
:rtype: Node
"""
| true |
1dfcc2fe5bcac12d235391d073b5991fca58960b | sudhamshu091/Daily-Dose-of-Python-Coding | /Qsn_21/string_punctuation.py | 232 | 4.25 | 4 | from string import punctuation
string = "/{Python @ is actually an > interesting //language@ "
replace = '#'
for char in punctuation:
string = string.replace(char, replace)
print("String after replacement is: ", string)
| true |
88fa596a897959b76862605be56a153b606f4555 | devil-cyber/Data-Structure-Algorithm | /tree/count_node_complete_tree.py | 643 | 4.125 | 4 | from tree import Tree
def height_left(root):
hgt = 0
node = root
while node:
hgt += 1
node = node.left
return hgt
def height_right(root):
hgt = 0
node = root
while node:
hgt += 1
node = node.right
return hgt
def count_node(root):
if root is None:
return 0
lh = height_left(root)
rh = height_right(root)
if rh==lh:
return (1 << rh) -1
return 1 + count_node(root.left) + count_node(root.right)
if __name__ == "__main__":
t = Tree()
root = t.create_tree()
print('the number of node in complete binary tree is:', count_node(root)) | true |
9179d31d9eeda1d0767924c0714b62e22875fb34 | MeeSeongIm/trees | /breadth_first_search_02.py | 611 | 4.1875 | 4 | # find the shortest path from 1 to 14.
# graph in list adjacent representation
graph = {
"1": ["2", "3"],
"2": ["4", "5"],
"4": ["8", "9"],
"9": ["12"],
"3": ["6", "7"],
"6": ["10", "11"],
"10": ["13", "14"]
}
def breadth_first_search(graph, start, end):
next_start = [(node, path + "," + node) for i, path in start if i in graph for node in graph[i]]
for node, path in next_start:
if node == end:
return path
else:
return breadth_first_search(graph, next_start, end)
print(breadth_first_search(graph, [("1", "1")], "14"))
| true |
21ef42736c7ef317b189da0dc033ad75615d3523 | LiloD/Algorithms_Described_by_Python | /insertion_sort.py | 1,505 | 4.1875 | 4 | import cProfile
import random
'''
this is the insertion sort Algorithm implemented by Python
Pay attention to the break condition of inner loop
if you've met the condition(the key value find a place to insert)
you must jump out of the loop right then
Quick Sort is Moderately fast for small input-size(<=30)
but weak for Large Input
by Zhizhuo Ding
'''
class InsertionSort:
"Algorithm---Insertion Sort"
@staticmethod
def execute(array):
array = list(array)
for i in xrange(1,len(array)):
key = array[i]
for j in range(0,i)[::-1]:
if key < array[j]:
array[j+1] = array[j]
if key >= array[j]:
array[j+1] = key
break
#return carefully at a right place
return array
@staticmethod
def execute_ver2(array):
'''donot use the additional key value,
all elements in array rearrange where they're
fairly effient in its usage of storage
'''
array = list(array)
for i in xrange(1,len(array)):
for j in range(0,i)[::-1]:
'''
here,because that we don't use additional varible to
keep the key(which is array[i] on the beginning)
the value will change in this case
so we can only compare array[j+1] with array[j]
not compare array[i] with [array[j]]
'''
if array[j+1] < array[j]:
array[j],array[j+1] = array[j+1],array[j]
return array
if __name__ == "__main__":
list1 = []
for i in xrange(0,10000):
list1.append(random.randint(0,10000))
cProfile.run("list1 = InsertionSort.execute_ver2(list1)", None, -1)
print list1
| true |
bedf86dafe10f5dc96b2ebd355040ab2fdfbd469 | jpacsai/MIT_IntroToCS | /Week5/ProblemSet_5/Problem1.py | 1,832 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 6 16:04:29 2018
@author: jpacsai
"""
def build_shift_dict(self, shift):
'''
Creates a dictionary that can be used to apply a cipher to a letter.
The dictionary maps every uppercase and lowercase letter to a
character shifted down the alphabet by the input shift. The dictionary
should have 52 keys of all the uppercase letters and all the lowercase
letters only.
shift (integer): the amount by which to shift every letter of the
alphabet. 0 <= shift < 26
Returns: a dictionary mapping a letter (string) to
another letter (string).
'''
newDict = {}
lower = string.ascii_lowercase
upper = string.ascii_uppercase
for char in lower:
shifted = ord(char)+shift
if shifted > 122:
shifted -= 26
newDict[char] = chr(shifted)
for char in upper:
shifted = ord(char)+shift
if shifted > 90:
shifted -= 26
newDict[char] = chr(shifted)
return newDict
def apply_shift(self, shift):
'''
Applies the Caesar Cipher to self.message_text with the input shift.
Creates a new string that is self.message_text shifted down the
alphabet by some number of characters determined by the input shift
shift (integer): the shift with which to encrypt the message.
0 <= shift < 26
Returns: the message text (string) in which every character is shifted
down the alphabet by the input shift
'''
newDict = self.build_shift_dict(shift)
newStr = ''
for char in self.message_text:
try:
newStr += newDict[char]
except KeyError:
newStr += char
return newStr | true |
5902f17e71a3630344ab79f9c22ee2985cb80d3e | GorTIm/DailyCoding | /2020-01-17-Medium-Google-DONE.py | 987 | 4.21875 | 4 | """
This problem was asked by Google.
You are given an array of nonnegative integers. Let's say you start at the beginning of the array
and are trying to advance to the end. You can advance at most, the number of steps that you're currently on.
Determine whether you can get to the end of the array.
For example, given the array [1, 3, 1, 2, 0, 1],
we can go from indices 0 -> 1 -> 3 -> 5, so return true.
Given the array [1, 2, 1, 0, 0], we can't reach the end, so return false.
"""
false_set=set()
def toTheEnd(L,start_index):
if start_index==len(L)-1:
return True
elif L[start_index]==0:
return False
elif start_index in false_set:
return False
else:
for steps in range(1,L[start_index]+1):
new_index=start_index+steps
if toTheEnd(L,new_index):
return True
false_set.add(new_index)
return False
if __name__=="__main__":
L=[1, 0, 1, 1, 0]
print(toTheEnd(L,0))
| true |
8e0f519ea8d1c1fb701a718929fb35e1319c2faf | pemburukoding/belajar_python | /part002.py | 2,128 | 4.40625 | 4 | # Get input from console
# inputString = input("Enter the sentence : ")
# print("The inputted string is :", inputString)
# Implicit Type
# num_int = 123
# num_flo = 1.23
# num_new = num_int + num_flo
# print("Value of num_new : ", num_new)
# print("datatype of num_new : ", type(num_new))
# num_int = 123
# num_str = "456"
# num_str = int(num_str)
# print(num_int+num_str)
# print(type(5))
# print(type(5.0))
# c = 5 + 3j
# print(type(c))
# Create List
# my_list = []
# my_list = [1, 2, 3]
# my_list = [1, "Hello", 3.4]
# language = ["French","German","English","Polish"]
# print(language[3])
# Create Tupple
# language = ("French","German","English","Polish")
# String Operator
# my_string = 'Hello'
# print(my_string)
# my_string = "Hello"
# print(my_string)
# my_string = '''Hello'''
# print(my_string)
# my_string = """Hello, welcome to the world of Python """
# print(my_string)
# str = "programiz"
# print('str = ', str)
# print('str[0] = ',str[0])
# print('str[-1] = ',str[-1])
# print('str[1:5] = ',str[1:5])
# print('str[5:-2] = ',str[5:-2])
# str1 = 'Hello'
# str2 = 'World!'
# print(str1 + str2)
# print(str1 * 3)
# Create Sets
# my_set = {1, 2, 3}
# print(my_set)
# my_set = {1.0, "Hello", (1,2,3)}
# print(my_set)
# my_set = {1,2,3}
# my_set.add(4)
# print(my_set)
# my_set.add(2)
# print(my_set)
# my_set.add([3, 4, 5])
# print(my_set)
# my_set.remove(4)
# print(my_set)
# A = {1, 2, 3}
# B = {2, 3, 4, 5}
# print(A | B)
# print(A & B)
# print(A - B)
# print(A ^ B)
# my_dict = {}
# my_dict = {1 : 'apple', 2: 'ball'}
# my_dict = {'name': 'John', 1 : [2, 4, 3]}
# person = {'name': 'Jack', 'age' : 26, 'salary' : 4534.2}
# person['age'] = 36
# print(person)
# person['salary'] = 100
# print(person)
# del person['age']
# print(person)
# del person
# Create Range
# numbers = range(1, 6)
# print(list(numbers))
# print(tuple(numbers))
# print(set(numbers))
# print(dict.fromkeys(numbers, 99))
numbers1 = range(1, 6, 1)
print(list(numbers1))
numbers2 = range(1, 6, 2)
print(list(numbers2))
numbers3 = range(5, 0, -1)
print(list(numbers3))
| true |
639934c70afa23f042371ce06b3ed89fdd6245ca | baluneboy/pims | /recipes/recipes_map_filter_reduce.py | 1,824 | 4.53125 | 5 | #!/usr/bin/env python
"""Consider map and filter methodology."""
import numpy as np
def area(r):
"""return area of circle with radius r"""
return np.pi * (r ** 2)
def demo_1(radii):
"""method 1 does not use map, it fully populates in a loop NOT AS GOOD FOR LARGER DATA SETS"""
areas = []
for r in radii:
a = area(r) # populate list one-by-one in for loop
areas.append(a)
print a
def demo_2(radii):
"""method 2 uses map to create iterator, which applies area function to each element of radii
it can sometimes be better to use iterator, esp. for large lists"""
area_iter = map(area, radii) # returns iterator over area applied to each radius
for a in area_iter:
print a
def demo_one_map():
"""compare with/out using map"""
radii = [2, 5, 7.1, 0.3, 10]
demo_1(radii)
demo_2(radii)
def demo_two_map():
"""use map to convert temps en masse"""
# example using map
temps_c = [("Berlin", 29), ("Cairo", 36), ("Buenos Aires", 19),
("Los Angeles", 26), ("Tokyo", 27), ("New York", 28),
("London", 22), ("Beijing", 32)]
# lambda to return tuple with calculated deg. F converted from deg. C
c2f = lambda city_tmp: (city_tmp[0], (9.0/5.0)*city_tmp[1] + 32)
print list(map(c2f, temps_c))
def demo_one_filter():
"""use filter to keep only data from list that are strictly above average"""
data = [1.3, 2.7, 0.8, 4.1, 4.3, -0.1]
avg = np.mean(data)
print "average value is:", avg
# create iterator that filters to keep only above average data
above_avg_iter = filter(lambda x: x > avg, data) # returns iterator for data above the avg
print "values strictly above average are:", list(above_avg_iter)
if __name__ == '__main__':
demo_one_filter()
| true |
1e6201d2f6f6df652f7ca66b1347c59c3121d067 | ThoPhD/vt | /question_1.py | 918 | 4.25 | 4 | # Question 1. Given an array of integer numbers, which are already sorted.
# E.g., A = [1,2,3,3,3,4,4,5,5,6]
# • Find the mode of the array
# • Provide the time complexity and space complexity of the array, and your reasoning
# • Note: write your own function using the basic data structure of your language,
# please avoid the provided available functions from external lib
from collections import Counter
def find_mode_of_array(input_array: list) -> list:
"""Find mode of the array."""
if not input_array:
raise Exception('Cannot compute mode on empty array!')
counter_set = Counter(input_array)
counter_max = max(counter_set.values())
mode = [k for k, v in counter_set.items() if v == counter_max]
return mode
# time complexity = O(n)
# space complexity = O(n)
if __name__ == "__main__":
n_num = [1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 6]
print(find_mode_of_array(n_num))
| true |
dc76d98797c421cf3ff6ca5de691aeec5ad29aa6 | VersionBeathon/Python_learning | /chapter_8/catch_exception.py | 1,648 | 4.28125 | 4 | # _*_ coding:utf-8 _*_
# 处理异常可以使用try/except语句来实现
try:
x = input('Enter the first number: ')
y = input("Enter the second number: ")
print x / y
except ZeroDivisionError:
print "The second number can`t be zero!"
# 不止一个except字句
try:
x = input('Enter the first number: ')
y = input("Enter the second number: ")
print x / y
except ZeroDivisionError:
print "The second number can`t be zero!"
except TypeError:
print "That wasn`t a number , was it ?"
# 用一个模块捕捉多个异常,可将他们作为元组列出
try:
x = input('Enter the first number: ')
y = input("Enter the second number: ")
print x / y
except (ZeroDivisionError, TypeError, NameError):
print "The second number can`t be zero!"
# 捕捉对象
try:
x = input('Enter the first number: ')
y = input("Enter the second number: ")
print x / y
except (ZeroDivisionError, TypeError), e:
print e
# 真正的全捕捉(用空的except语句)
try:
x = input('Enter the first number: ')
y = input("Enter the second number: ")
print x / y
except:
print "Something wrong happened..."
# 屏蔽 ZeroDivisionError,打印错误信息而不是让异常传播
class MuffledCalculator:
muffled = False
def calc(self, expr):
try:
return eval(expr)
except ZeroDivisionError:
if self.muffled:
print 'Division by zero is illegal'
else:
raise
calculator = MuffledCalculator()
print calculator.calc('10/2')
calculator.calc('10/0')
calculator.muffled = True
calculator.calc('10/0')
| false |
604be482da6a2aea20bf660763b23019eea9571f | cloudzfy/euler | /src/88.py | 1,356 | 4.1875 | 4 | # A natural number, N, that can be written as the sum and
# product of a given set of at least two natural numbers,
# {a1, a2, ... , ak} is called a product-sum number:
# N = a_1 + a_2 + ... + a_k = a_1 x a_2 x ... x a_k.
# For example, 6 = 1 + 2 + 3 = 1 x 2 x 3.
# For a given set of size, k, we shall call the smallest N
# with this property a minimal product-sum number. The
# minimal product-sum numbers for sets of size, k = 2, 3,
# 4, 5, and 6 are as follows.
# k = 2: 4 = 2 x 2 = 2 + 2
# k = 3: 6 = 1 x 2 x 3 = 1 + 2 + 3
# k = 4: 8 = 1 x 1 x 2 x 4 = 1 + 1 + 2 + 4
# k = 5: 8 = 1 x 1 x 2 x 2 x 2 = 1 + 1 + 2 + 2 + 2
# k = 6: 12 = 1 x 1 x 1 x 1 x 2 x 6 = 1 + 1 + 1 + 1 + 2 + 6
# Hence for 2 <= k <= 6, the sum of all the minimal product-sum
# numbers is 4 + 6 + 8 + 12 = 30; note that 8 is only counted
# once in the sum.
# In fact, as the complete set of minimal product-sum numbers
# for 2 <= k <= 12 is {4, 6, 8, 12, 15, 16}, the sum is 61.
# What is the sum of all the minimal product-sum numbers for
# 2 <= k <= 12000?
limit = 12000
ans = [2 * k for k in range(12001)]
def get_product_sum(num, nprod, nsum, start):
k = nprod - nsum + num
if k <= limit:
ans[k] = min(nprod, ans[k])
for i in range(start, limit / nprod * 2 + 1):
get_product_sum(num + 1, nprod * i, nsum + i, i)
get_product_sum(0, 1, 0, 2)
print sum(set(ans[2:]))
| true |
03f028686704d0b223621546b04893a844ef9148 | NathanJiangCS/Exploring-Python | /Higher Level Python Concepts/Closures.py | 2,029 | 4.6875 | 5 | #Closures
'''
Closures are a record storing a function together with an environment: a mapping
associating each free variable of the function with the value or storage location
to which the name was bound when the closure was created. A closure, unlike a plain
function, allows the function to access those captured variables through the closure's
reference to them, even when the function is invoked outside their scope.
'''
#Example 1
def outer_func():
message = 'Hi'
def inner_func():
print message #this message variable is a free variable because
#it is not actually defined within the scope of inner_func
#but it is still able to be accessed
return inner_func() # we are returning the executed inner function
outer_func() #the result is it prints Hi
#Example 2
def outer_func():
message = 'Hi'
def inner_func():
print message
return inner_func #This time, we will return inner_func without executing it
my_func = outer_func() #Now, instead of printing hi, we get that the value of
#my_func is the inner_func()
my_func() #We can execute the variable as a function and it prints hi
#This is interesting because we are done with the execution of the outer_func but it
#still is able to access the value of what the message is. This is what a closure is
'''
In simple terms, a closure is a function that has access to variables created in the local
scope even after the outer function is finished executing.
'''
#Example 3
#this time, let us give our functions parameters
def outer_func(msg):
message = msg
def inner_func():
print message
return inner_func
hi_func = outer_func('Hi') #This time, the hi and hello func are equal to inner_func
#which is ready to print the message
hello_func = outer_func('Hello')
hi_func() #Prints hi
hello_func() #Prints hello
#Notice that each of these functions remembers the values of their own msg variable
| true |
d3ea582ed28b3eaa9f7a0376c649bab202c94ffa | NathanJiangCS/Exploring-Python | /Higher Level Python Concepts/String Formatting.py | 2,862 | 4.125 | 4 | #String formatting
#Advanced operations for Dicts, Lists, and numbers
person = {'name':'Nathan', 'age':100}
#######################
#Sentence using string concatenation
sentence = "My name is " + person['name'] + ' and I am ' + str(person['age']) + ' years old.'
print sentence
#This is not readable as you have to open and close strings
#You also have to remember to place spaces
#######################
#Sentence using %s
sentence = "My name is %s and I am %s years old." % (person['name'], person['age'])
print sentence
#######################
#Sentence using .format
sentence = 'My name is {} and I am {} years old.'.format(person['name'], person['age'])
#You can also explicitly number your placeholders
#By doing this, your value at the specified index will replace that placeholder
sentence = 'My name is {0} and I am {1} years old.'.format(person['name'], person['age'])
#For example, we don't have to type the text value twice when using this formatting
tag = 'h1'
text = 'This is a headline'
sentence = '<{0}>{1}</{0}>'.format(tag, text)
print sentence
#We can also specify specific fields from the placeholders themselves
#Before we were doing this
sentence = 'My name is {0} and I am {1} years old.'.format(person['name'], person['age'])
#We can also do this. This method also works for a list or a tuple
sentence = 'My name is {0[name]} and I am {0[age]} years old.'.format(person)
print sentence
#We can also access attributes in a similar way
class Person():
def __init__(self,name,age):
self.name = name
self.age = age
p1 = Person('Jack',33)
sentence = 'My name is {0.name} and I am {0.age} years old.'.format(p1)
print sentence
#We can also pass in keyword arguments
sentence = 'My name is {name} and I am {age} years old.'.format(name='Jen',age=30)
#This means we can unpack a dictionary and format the sentence in a similar way
#By unpacking the dictionary, it fills in the keyword arguments for us
person = {'name':'Jen', 'age', 30}
sentence = 'My name is {name} and I am {age} years old.'.format(**person)
#By adding a colon in our placeholders, we can add formatting
#For example, lets say we wanted to make all of our values 2 digits by padding a zero
for i in range(1,11):
sentence = 'The value is {:02}'.format(i)
print sentence
#This gives us 01, 02, 03, 04 ... 10, 11. We can change {:02} to {:03} and it gives us
#001, 002, 003 .... 010, 011
#This is how we format decimal places
pi = 3.14152965
sentence = 'Pi is equal to {:.2f}'.format(pi)
#This rounds pi to 2 decimal places 3.14
#We can also chain formatting. For example, if we wanted to add commas to make a large
#number more readable but also have the large number rounded to 2 decimal places
sentence = '1MB is equal to {:,.2f} bytes'.format(1000**2)
#See how we chained , which inserts the commas to make it more readable with .2f
| true |
616e0af829a12d78b50fdf016704bb179d2a721c | RonakNandanwar26/Python_Programs | /zip_enumerate.py | 2,367 | 4.40625 | 4 | # zip
# zip returns iterator that combines multiple iterables into
# one sequence of tuples
# ('a',1),('b',2),('c',3)
# letters = ['a','b','c']
# nums = [1,2,3]
# lst = [4,5,6]
# print(zip(nums,letters,lst))
# # #
# for letters,nums,lst in zip(letters,nums,lst):
# print(letters,nums,lst)
# # unzip
# lst = [('a',1),('b',2),('c',3)]
# letter,num = zip(*lst)
# print(letter,num)
# print(num)
#
# for i in letter:
# print(i)
# Enumerate
# Enumerator is a built in function that returns an generator
# of tuples containing indices and value of list
# letters = ['a','b','c','d','e','f']
# print(enumerate(letters))
# for i,letter in enumerate(letters):
# print(i,letter)
# use zip to write for loop that creates string specifying the label and
# co-ordinates of each point and appends it to the list points.
# each string should be formatted as 'label:x,y,z'
# a:23,56,12
# x_coord = [23,4,5]
# y_coord = [56,3,4]
# z_coord = [12,5,6]
# labels = ['a','b','c']
# #
# points = []
# #
# for point in zip(labels,x_coord,y_coord,z_coord):
# print(point)
#
# for point in zip(labels,x_coord,y_coord,z_coord):
# print('{}:{},{},{}'.format(*point))
#
# # for making a list
# for point in zip(labels,x_coord,y_coord,z_coord):
# points.append('{}:{},{},{}'.format(*point))
#
# print(points)
# for i in points:
# print(i)
# # zip to create dictionary
# cast_names = ['barney','Robin','Ted']
# cast_heights = [72,68,90]
# cast = dict(zip(cast_names,cast_heights))
# print(cast)
# print(cast.items())
# for k,v in cast.items():
# print(k,v)
# # zip to create tuple
# cast_names = ['barney','Robin','Ted']
# cast_heights = [72,68,90]
# cast = tuple(zip(cast_names,cast_heights))
# print(cast)
# print(zip(cast_names,cast_heights))
# for i in cast:
# print(i)
# # # zip to create list
# cast_names = ['barney','Robin','Ted']
# cast_heights = [72,68,90]
# cast = list(zip(cast_names,cast_heights))
# print(cast)
# unzip cast tuple
# cast = [('barney', 72), ('Robin', 68), ('Ted', 90)]
# name,height = zip(*cast)
# print(name,height)
# names = ['barney','Robin','Ted']
# heights = [72,68,90]
#
# for i,name in enumerate(names):
# print(i,name)
#
# for i,name in enumerate(names):
# names[i] = name + " " + str(heights[i])
#
# print(names) | true |
39c6cf72d27d1444e7fcb21d611ee5673a32b9f1 | fsicardir/sorting-algorithms | /mergeSort.py | 624 | 4.125 | 4 |
# Time complexity: O(n*log(n))
# Space complexity: O(n)
# Stable
def merge_sort(arr):
def merge(list1, list2):
i, j = 0, 0
merge = []
while i < len(list1) and j < len(list2):
if list1[i] > list2[j]:
merge.append(list2[j])
j += 1
else:
merge.append(list1[i])
i += 1
merge += list1[i:]
merge += list2[j:]
return merge
if len(arr) < 2:
return arr
half = len(arr) // 2
left = merge_sort(arr[:half])
right = merge_sort(arr[half:])
return merge(left, right)
| false |
baa648fbc217616042bccd431787c762b2e8fc47 | wxhheian/lpthw | /ex41e.py | 2,047 | 4.59375 | 5 | ###继承####
#继承是一种创建新类的方式,在python中,新建的类可以继承一个或多个父类,父类又称为基类 或超类,新建的类称为派生类或子类
#继承分为单继承和多继承
# class ParentClass1: #定义父类
# pass
#
# class ParentClass2: #定义父类
# pass
#
# class SubClass1(ParentClass1): #单继承,基类是ParentClass1 派生类是SubClass1
# pass
#
# class SubClass2(ParentClass1,ParentClass2): #多继承
# pass
#
# print(SubClass1.__bases__) #__base__只查看从左到右第一个父类, __bases___查看全部的父类
# print(SubClass2.__bases__)
#
# ##如果没有指定基类,python的类会默认继承object类
# print(ParentClass1.__bases__)
# print(ParentClass2.__bases__)
#继承例子说明
#猫可以:吃、喝、爬树
#狗可以:吃、喝、看家
#若要分别为猫和狗创建一个类。
#class 猫:
# def 吃(self):
# pass
#
# def 喝(self):
# pass
#
# def 爬树(self):
# pass
#
#class 狗:
# def 吃(self):
# pass
#
# def 喝(self):
# pass
#
# def 看家(self):
# pass
# ##############但是猫和狗有共同的功能是吃和喝,则可以使用继承的功能
class Animal:
def eat(self):
print("%s 吃" %self.name)
def drink(self):
print("%s 喝" %self.name)
class Cat(Animal): #在类后面括号中写入另外一个类名,表示当前类继承另外一个类
def __init__(self,name):
self.name = name
self.breed = '猫'
def climb(self):
print('爬树')
class Dog(Animal): #在类后面括号中写入另外一个类名,表示当前类继承另外一个类
def __init__(self,name):
self.name = name
self.breed = '狗'
def look_after_house(self):
print('汪汪叫')
c1 = Cat('小白家的小黑猫')
c1.eat()
c2 = Cat('小黑家的小白猫')
c2.drink()
d1= Dog('胖子家的小瘦狗')
d1.look_after_house()
d1.eat()
| false |
a7d494c37a77ff4aec474502cff553348d9e5c17 | alexander-zou/pycheats | /pyps/use_random.py | 1,548 | 4.3125 | 4 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@File : use_random.py
@Author : alexander.here@gmail.com
@Date : 2020-07-10 16:55 CST(+0800)
@Brief : https://docs.python.org/zh-cn/3/library/random.html
'''
from __future__ import print_function
import random
print( 'random.random() generates 0 <= X < 1.0:')
print( [ random.random() for i in range( 8)])
print( '\nrandom.uniform( A, B) generates floats A <= X <= B:')
print( [ random.uniform( -5, 5) for i in range( 5)])
print( [ random.uniform( 5, -5) for i in range( 5)])
print( '\nrandom.choice():') # use choices( datas, weights) for weighting
print( random.choice( 'hello'), 'from', "'hello'")
print( random.choice( range( 10)), 'from', 'range( 10)')
print( '\nrandom.shuffle():') # scramble in-place:
l = list( range( 10))
random.shuffle( l)
print( l)
s = list( "python")
random.shuffle( s)
print( ''.join( s))
print( '\nrandom.sample() can be used as choice() or shuffle():')
print( random.sample( [ 1, 3, 5, 7], 2)) # choose 2 elements from container
print( random.sample( range( 10), 1)[ 0]) # as choice()
print( ''.join( random.sample( 'python', 6))) # as shuffle()
# random.randrange( start, stop[, step]) works just like:
# random.choice( range( start, stop, step)) without actually creating range() object.
# random.randint( a, b) is equivalent to random.randrange( a, b+1)
# set seed:
print( "\nfixed seed:")
random.seed( 1)
print( [ random.random() for i in range( 3)])
random.seed( 1)
print( [ random.random() for i in range( 3)])
# End of 'use_random.py'
| false |
9a84af3077b599c11231def2af09cb8ccf40141c | stavernatalia95/Lesson-5.3-Assignment | /Exercise #1.py | 448 | 4.5 | 4 | #Create a function that asks the user to enter 3 numbers and then prints on the screen their summary and average.
numbers=[]
for i in range(3):
numbers.append(int(input("Please enter a number:")))
def print_sum_avg(my_numbers):
result=0
for x in my_numbers:
result +=x
avg=result/len(my_numbers)
print("Total: ", result, "Average: ", avg)
total_of_numbers=numbers
(print_sum_avg(total_of_numbers))
| true |
bcacc85fdc2fde42a3f3636cedd1666adaa24378 | Chia-Network/chia-blockchain | /chia/util/significant_bits.py | 991 | 4.125 | 4 | from __future__ import annotations
def truncate_to_significant_bits(input_x: int, num_significant_bits: int) -> int:
"""
Truncates the number such that only the top num_significant_bits contain 1s.
and the rest of the number is 0s (in binary). Ignores decimals and leading
zeroes. For example, -0b011110101 and 2, returns -0b11000000.
"""
x = abs(input_x)
if num_significant_bits > x.bit_length():
return input_x
lower = x.bit_length() - num_significant_bits
mask = (1 << (x.bit_length())) - 1 - ((1 << lower) - 1)
if input_x < 0:
return -(x & mask)
else:
return x & mask
def count_significant_bits(input_x: int) -> int:
"""
Counts the number of significant bits of an integer, ignoring negative signs
and leading zeroes. For example, for -0b000110010000, returns 5.
"""
x = input_x
for i in range(x.bit_length()):
if x & (1 << i) > 0:
return x.bit_length() - i
return 0
| true |
f3d569ebc4192a0e60d95944b91ac33bac1f17aa | chimaihueze/The-Python-Workbook | /Chapter 2/44_faces_on_money.py | 1,118 | 4.1875 | 4 | """
Individual Amount
George Washington $1
Thomas Jefferson $2
Abraham Lincoln $5
Alexander Hamilton $10
Andrew Jackson $20
Ulysses S. Grant $50
Benjamin Franklin $100
Write a program that begins by reading the denomination of a banknote from the
user. Then your program should display the name of the individual that appears on the
banknote of the entered amount. An appropriate error message should be displayed
if no such note exists.
"""
amount = int(input("Enter the denomination: "))
notes = [1, 2, 5, 10, 20, 50, 100]
individual = {"George Washington": 1,
"Thomas Jefferson": 2,
"Abraham Lincoln": 5,
"Alexander Hamilton": 10,
"Andrew Jackson": 20,
"Ulysses S. Grant": 50,
"Benjamin Franklin": 100}
if amount in notes:
for k, v in individual.items():
if amount == v:
print("The face of {} is printed on ${} note.".format(k, v))
else:
print("This note does not exist! Please try again.")
| true |
87a475ae20b4dde09bc00f7ca8f0258ead316aa4 | chimaihueze/The-Python-Workbook | /Chapter 1/exercise24_units_of_time.py | 670 | 4.4375 | 4 | """
Create a program that reads a duration from the user as a number of days, hours,
minutes, and seconds. Compute and display the total number of seconds represented
by this duration.
"""
secs_per_day = 60 * 60 * 24
secs_per_hour = 60 * 60
secs_per_minute = 60
days = int(input("Enter the number of days: "))
hours = int(input("Enter the number of hours: "))
minutes = int(input("Enter the number of minutes: "))
seconds = int(input("Enter the number of seconds: "))
total_seconds = (days * secs_per_day) + (hours * secs_per_hour) + (minutes * secs_per_minute) + seconds
print("The total number of seconds represented by this duration is {}".format(total_seconds)) | true |
621e85bdd3efd63d3d3fccd18e6d77d83ef9d6f3 | chimaihueze/The-Python-Workbook | /Chapter 1/exercise29_wind_mill.py | 1,266 | 4.4375 | 4 | """
When the wind blows in cold weather, the air feels even colder than it actually is
because the movement of the air increases the rate of cooling for warm objects, like
people. This effect is known as wind chill.
In 2001, Canada, the United Kingdom and the United States adopted the following formula for computing the wind chill index. Within the formula Ta is the
air temperature in degrees Celsius and V is the wind speed in kilometers per hour.
A similar formula with different constant values can be used for temperatures in
degrees Fahrenheit and wind speeds in miles per hour.
Write a program that begins by reading the air temperature and wind speed from the
user. Once these values have been read your program should display the wind chill
index rounded to the closest integer.
The wind chill index is only considered valid for temperatures less than or
equal to 10 degrees Celsius and wind speeds exceeding 4.8 kilometers per
hour.
"""
air_temp = float(input("Enter the air temperature (in degrees Celsius): "))
wind_speed = float(input("Enter the wind speed (k/hr): "))
wind_chill = 13.12 + (0.6215 * air_temp) - (11.37 * (wind_speed ** 0.16)) + (0.3965 * (air_temp * (wind_speed ** 0.16)))
print("The wind chill is {}".format(round(wind_chill))) | true |
420c2501440b97e647d1eff05559561e5c5b3869 | chimaihueze/The-Python-Workbook | /Chapter 1/exercise23_area_of_a_regular-polygon.py | 531 | 4.46875 | 4 | """
Polygon is regular if its sides are all the same length and the angles between all of
the adjacent sides are equal.
Write a program that reads s and n from the user and then displays the area of a
regular polygon constructed from these values.
"""
# s is the length of a side and n is the number of sides:
import math
s = float(input("Enter the length (s): "))
n = int(input("Enter the number of sides (n): "))
area = (n * (s ** 2)) / (4 * (math.tan(math.pi / n)))
print("The area of the polygon os {:.2f}".format(area)) | true |
61628dc6e1c6d4ba2c8bdc112d25aa1b2d334f96 | cheikhtourad/MLND_TechnicalPractice | /question2.py | 1,628 | 4.125 | 4 | # Question 2
# Given a string a, find the longest palindromic substring contained in a.
# Your function definition should look like question2(a), and return a string.
# NOTE: For quetions 1 and 2 it might be useful to have a function that returns all substrings...
def question2(a):
longest_pal = ''
# Base Case: The initial string is a plindrome
if isPalindrome(a):
return a
end = len(a)
start = 0
# Get all the substrings and check if its a palindrome
# if it is a palindrome and it's longer than longest_pal
# make longest_pal the current substring
while start != end:
while end != start:
if isPalindrome( a[start:end] ) and len( a[start:end] ) >= len( longest_pal ):
longest_pal = a[start:end]
end -= 1
start += 1
end = len(a)
return longest_pal
# Helper function for question 2
# Determine if a string s is a palindrome
def isPalindrome(s):
# Base Case: if s empty
if not s:
return True
# Bsae Case: is s is a single character
#print (len(s) == 1)
if len(s) == 1:
return True
if s[0] == s[-1]:
return isPalindrome(s[1:-1])
return False
def test2():
print "Tests for Question 2: \n"
a = "racecar"
print "The longest palindrome in '" + a + "' is " + " "
print question2(a)
# Single character test
a = "a"
print "The longest palindrome in '" + a + "' is " + " "
print question2(a)
# Empty string test
a = ""
print "The longest palindrome in '" + a + "' is " + " "
print question2(a)
# Empty string test
a = "I have a racecar"
print "The longest palindrome in '" + a + "' is " + " "
print question2(a)
print "\n"
if __name__ == '__main__':
test2() | true |
3c6a3ffb396896360f45c373f871e4e15fafc181 | vivekinfo1986/PythonLearning | /Oops-Polymorphism_AbstractClass_Overwrite.py | 530 | 4.46875 | 4 | #Define a base class with abstract method and using inheritence overwrite it.
class Animal():
def __init__(self,name):
self.name = name
#Testing abstract class
def speak(self):
raise NotImplementedError('Subclass must implement this abstract method')
class Dog(Animal):
def speak(self):
return self.name + " Says woof!!"
class Cat(Animal):
def speak(self):
return self.name + " Says MeaW!!"
Pet1 = Dog('Tommy')
Pet2 = Cat('Catty')
print(Pet1.speak())
print(Pet2.speak())
| true |
649554a6af19f4c16562158e17a24a630a116fcd | arctan5x/jhu | /algorithms/sorting/insertion_sort.py | 609 | 4.1875 | 4 | def insertion_sort(lst):
if not lst:
return []
for i in range(1, len(lst)):
pivot_key = lst[i]
position = i - 1
while position > -1 and pivot_key < lst[position]:
lst[position + 1] = lst[position]
position -= 1
lst[position + 1] = pivot_key
return lst
if __name__ == "__main__":
# some tests
lst1 = [2, 1, 34, 3, 6, 2, 4, 7]
print insertion_sort(lst1) == [1, 2, 2, 3, 4, 6, 7, 34]
lst2 = []
print insertion_sort(lst2) == []
lst3 = [1]
print insertion_sort(lst3) == [1]
lst4 = [2, 1]
print insertion_sort(lst4) == [1, 2]
lst5 = [1, 2, 3]
print insertion_sort(lst5) == [1, 2, 3] | false |
9dd09c27fa88d56e88778df9bee7ddf4edaa98ca | ShiekhRazia29/Dictionary | /samp7.py | 542 | 4.5 | 4 | #To check whether a key exists in a dictiory or not
#For that we use a key word called "in"
key_word_exists={'name':"Razia",'Age':22,'Course':"Software Engineering",
'present':"Navgurkul Campus"}
if 'name' in key_word_exists:
print("Yes the keyword name exists:",key_word_exists['name'])
else:
print("No the keyword name doesnot exist in the dictionary")
#adding element to the dictionary
dic={'Name':"Razia",'age':22,'place':"Gulmarg"}
dic['organization']="NavGurkul"
dic['course']="Software Engineering"
print("dic",dic) | false |
3efc0fc73ac41af9ac77e905c7cf68b82a71a2d5 | brayan-mendoza/ejercicios_examen | /L-2.py | 357 | 4.21875 | 4 | # utlizando ciclos (loops) dinujar un triangulo de asteriscos
def triangulo(altura):
for numero_linea in range(altura):
espacios = altura - numero_linea - 1
print("", espacios)
asteriscos = 1 + numero_linea * 2
print (" " * espacios + "*" * asteriscos)
alt = int(input("introduce la altura: "))
triangulo(alt) | false |
cd4f7ca00ff3f3336e8899c75f10fc5d69fedc7e | AndyWheeler/project-euler-python | /project-euler/5 Smallest multiple/smallestMultiple.py | 1,105 | 4.15625 | 4 | import primeFactors
#primePower(num) returns True if num is a prime power, False otherwise
def primePower(num):
factors = primeFactors.primeFactorsOf(num)
#print "prime factors of " + str(num) + ": " + str(factors)
isPrimePower = not factors or factors.count(factors[0]) == len(factors)
return isPrimePower
def smallestMultiple(upperBound):
lim = upperBound
powers = []
for n in range(lim, 1, -1):
#check to see if it's a prime power, aka if its prime factors are all equal
#check to see if it evenly divides an element of the list. if not, add to list
isPower = primePower(n)
if isPower:
if powers:
for p in powers:
if p%n == 0:
break
else:
powers.append(n)
else:
powers.append(n)
print powers
#multiply all the prime powers
product = 1
for p in powers:
product *= p
return product
n = 16
#print primeFactors.primeFactorsOf(n)
#print primePower(n)
print smallestMultiple(14) | true |
4ca1429fa78294b81f05a18f22f23a5bad106c73 | jammilet/PycharmProjects | /Notes/Notes.py | 2,014 | 4.1875 | 4 | import random # imports should be at the top
print(random.randint(0, 6))
print('Hello World')
# jamilet
print(3 + 5)
print(5 - 3)
print(5 * 3)
print(6 / 2)
print(3 ** 2)
print() # creates a blank line
print('see if you can figure this out')
print(5 % 3)
# taking input
name = input('What is your name?')
print('Hello %s' % name)
# print(name)
age = input('What is your age?')
print('%s you are old' % age)
def print_hw():
print('Hello World')
print_hw()
def say_hi(name1):
print('Hello %s.' % name1)
print('I hope you have a fantastic day')
say_hi('jamilet')
def birthday(age1):
age1 += 1 # age = age + 1
say_hi('John')
print('John is 15. Next year:')
birthday(16)
# variables
car_name = 'jamilet mobile'
car_type = 'toyota'
car_cylinders = 8
car_mpg = 900.1
# inline printing
print('my car is the %s.' % car_name)
print('my car is the %s. it is a %s' % (car_name, car_type))
def birthday(age1):
age1 += 1 # age = age + 1
def f(x):
return x**5 + 4 * x ** 4 - 17*x**2 + 4
print(f(3))
print(f(3) + f(5))
# if statements
def grade_calc(percentage):
if percentage >= 90:
return "A"
elif percentage >= 80: # else if
return "B"
if percentage >= 70:
return "C"
elif percentage >= 60:
return "D"
elif percentage >= 50:
return "E"
elif percentage >= 40:
return "F"
# loops
# for num in range(5):
# print(num + 1)
# for letter in "Hello World":
# print(letter)
a = 1
while a < 10:
print(a)
a += 1
# response = ""
# while response != "Hello":
# response = input("Say \"Hello\"")
print("Hello \nWorld") # \n means newline
# comparisons
print(1 == 1) # two equal signs to compare
print(1 != 2) # one is not equal to two
print(not False)
print(1 == 1 and 4 <= 5)
# recasting
c = '1'
print(c == 1) # false - c is a string, 1 is an integer
print(int(c) == 1)
print(c == str(1))
num = input("give me a number")
# inputs are ALWAYS (!!!!!!!) of type string!!!
| true |
976d7a598201141e0a1b4ae033be763da80fd5b2 | Genyu-Song/LeetCode | /Algorithm/BinarySearch/Sqrt(x).py | 1,003 | 4.15625 | 4 | # -*- coding: UTF-8 -*-
'''
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
'''
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
def binarysearch(goal, start, end):
m = start + (end - start) // 2
if round(m ** 2) > goal:
if round((m-1)**2) < goal:
return m-1
return binarysearch(goal, start, m-1)
elif round(m ** 2) < goal:
if round((m+1)**2) > goal:
return m
return binarysearch(goal, m+1, end)
if round(m ** 2) == goal:
return m
if x < 2: return x
return binarysearch(x, 0, x)
if __name__ == '__main__':
print(Solution().mySqrt(2147395600)) | true |
d188291d13c688c3fd3404e49c785336f160a075 | Genyu-Song/LeetCode | /Algorithm/Sorting/SortColors.py | 1,598 | 4.15625 | 4 | # -*- coding: UTF-8 -*-
'''
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library's sort function for this problem.
'''
class Solution:
def sortColors(self, nums):
"""
Do not return anything, modify nums in-place instead.
"""
"""
TODO: ??
"""
map_dict = {}
for i in nums:
map_dict[i] = map_dict.get(i, 0) + 1
max_times = max(map_dict.values())
res = []
for color in range(max(set(nums))+1):
count = 0
while count < map_dict[color]:
res.append(color)
count += 1
return res
import random
class Solution2:
def sortColors(self, nums):
def swap(nums, index1, index2):
nums[index1], nums[index2] = nums[index2], nums[index1]
pivot = 1
lt, gt = 0, len(nums)-1
pointer = 0
while pointer <= gt:
if nums[pointer] < pivot:
swap(nums, pointer, lt)
lt += 1
pointer += 1
elif nums[pointer] > pivot:
swap(nums, gt, pointer)
gt -= 1
elif nums[pointer] == pivot:
pointer += 1;
return nums
if __name__ == '__main__':
print(Solution2().sortColors(nums=[2,0,2,1,1,0,1,0])) | true |
f13838e403245f0e5e00dd3db6d7cdd4a3425631 | driscollis/Python-101-Russian | /code/Chapter 2 - Strings/string_slicing.py | 248 | 4.25 | 4 | # string slicing
my_string = "I like Python!"
my_string[0:1]
my_string[:1]
my_string[0:12]
my_string[0:13]
my_string[0:14]
my_string[0:-5]
my_string[:]
my_string[2:]
# string indexing
print(my_string[0]) # prints the first character of the string | true |
b7bdff3a5a9043d42ec3dd26c63c67c239f1b3cf | traj1593/LINEAR-PREDICTION-PROGRAM | /linearPrediction-tRaj-00.py | 1,173 | 4.25 | 4 | '''
Program: LINEAR PREDICTION
Filename: linearPrediction-tRaj-00.py
Author: Tushar Raj
Description: The program accepts two integers from a user at the console and uses them to predict the next number in the linear sequence.
Revisions: No revisions made
'''
### Step 1: Announce, prompt and get response
#Announce
print("LINEAR PREDICTION");
print("predict the 3rd number in a sequence\n");
#Prompt user to get response
first_number = input("Enter the 1st number: ")
second_number = input("Enter the 2nd number: ")
###Step 2: Compute the next number in the linear sequence
#convert the string into integer data type
converted_first_number = int(first_number)
converted_second_number = int(second_number)
#Calculate the difference between the first number and second number and store in a variable
difference = converted_first_number - converted_second_number
#Subtract the difference from the second number to get the predicted number
predicted_number = converted_second_number - difference
###Step 3: Print the linear sequence along with the predicted number
print("The linear sequence is: ",first_number,second_number,predicted_number)
| true |
42fd723316a51442c22fb676a3ec9f12ae82056b | HeimerR/holbertonschool-higher_level_programming | /0x0B-python-input_output/7-save_to_json_file.py | 302 | 4.125 | 4 | #!/usr/bin/python3
"""module
writes an Object to a text file
"""
import json
def save_to_json_file(my_obj, filename):
""" writes an Object to a text file, using a JSON representation"""
with open(filename, encoding="utf-8", mode="w") as json_file:
json_file.write(json.dumps(my_obj))
| true |
e5666f5f6d68cc0fbc6d57012f6b9c3e740a09a8 | bmihovski/PythonFundamentials | /count_odd_numbers_list.py | 429 | 4.15625 | 4 | """
Write a program to read a list of integers and find how many odd items it holds.
Hints:
You can check if a number is odd if you divide it by 2 and check whether you get a remainder of 1.
Odd numbers, which are negative, have a remainder of -1.
"""
nums_odd = list()
nums_stdin = list(map(int, input().split(' ')))
[nums_odd.append(item) for item in nums_stdin if item % 2 == 1 or item % 2 == -1]
print(len(nums_odd))
| true |
d03229593c9e605f31320e0200b0b258e191acee | bmihovski/PythonFundamentials | /sign_of_int_number.py | 581 | 4.25 | 4 | """
Create a function that prints the sign of an integer number n.
"""
number_stdin = int(input())
def check_int_type(int_to_check):
"""
Check the type of input integer and notify the user
:param int_to_check: Int
:return: message_to_user: Str
"""
if int_to_check > 0:
msg_to_user = f'The number {int_to_check} is positive.'
elif int_to_check < 0:
msg_to_user = f'The number {int_to_check} is negative.'
else:
msg_to_user = f'The number {int_to_check} is zero.'
return msg_to_user
print(check_int_type(number_stdin))
| true |
f6a011b92ee7858403ea5676b01610ff962e1c0d | bmihovski/PythonFundamentials | /wardrobe.py | 2,079 | 4.21875 | 4 | """
On the first line of the input, you will receive n - the number of lines of clothes,
which came prepackaged for the wardrobe.
On the next n lines, you will receive the clothes for each color in the format:
" "{color} -> {item1},{item2},{item3}…"
If a color is added a second time, add all items from it and count the duplicates.
Finally, you will receive the color and item of the clothing, that you need to look for.
Output
Go through all the colors of the clothes and print them in the following format:
{color} clothes:
* {item1} - {count}
* {item2} - {count}
* {item3} - {count}
…
* {itemN} - {count}
If the color lines up with the clothing item, print "(found!)" alongside the item.
See the examples to better understand the output.
Input
4
Blue -> dress,jeans,hat
Gold -> dress,t-shirt,boxers
White -> briefs,tanktop
Blue -> gloves
Blue dress
Output
Blue clothes:
* dress - 1 (found!)
* jeans - 1
* hat - 1
* gloves - 1
Gold clothes:
* dress - 1
* t-shirt - 1
* boxers - 1
White clothes:
* briefs - 1
* tanktop - 1
"""
wardrobe = dict()
input_clothes = list()
input_checkouts = list()
items_wardrobe = int(input())
printed = []
def _items_wardrobe(color, cloth):
"""
Prints the content of wardrobe by color and matches
:param color: (Str) The color of clothes
:param cloth: (Str) The kind of cloth
:return: None
"""
print(f'{color} clothes:')
for cloth in wardrobe[color]:
if cloth in printed:
continue
print(f'* {cloth} - {wardrobe[color].count(cloth)}', end='')
if color == input_checkouts[0] and cloth == input_checkouts[1]:
print(f' (found!)', end='')
print()
printed.append(cloth)
for item in range(items_wardrobe):
input_clothes = input().split(' -> ')
clothes = input_clothes[1].split(',')
if input_clothes[0] in wardrobe:
wardrobe[input_clothes[0]].extend(clothes)
else:
wardrobe.update({input_clothes[0]: clothes})
input_checkouts = input().split()
{_items_wardrobe(key, input_checkouts[1]) for key in wardrobe.keys()}
| true |
d92a918b6cfb2f15386e235fdd3f2f2f3c7d8291 | heldaolima/MiniCursoIC | /PROVA/1) A.py | 584 | 4.15625 | 4 | print('''Questão1- Fazer um programa que peça uma quantidade de números e em seguida separar os números
que forem pares e colocar em um vetor e os que forem impares e colocar em outro vetor. Ao final printar
os vetores.''')
print('----------------')
pares = []
ímpares = []
quant = int(input('Quantos números deseja inserir? '))
for i in range(1, quant+1):
num = int(input(f'Insira o {i}º número: '))
if num % 2 == 0:
pares.append(num)
else:
ímpares.append(num)
print('----------------')
print(f'PARES: {pares}')
print(f'ÍMPARES: {ímpares}')
| false |
fa8b2f12b38257a7111d00aca216f0251c8238b4 | juso40/ALDA_SS2019 | /sheet1/sieve.py | 861 | 4.125 | 4 | from math import sqrt
def sieve(sieve_up_to):
sieve_up_to=int(sieve_up_to)
is_prime = [True] * sieve_up_to #jede zahl ist eine potentielle primzahl
is_prime[0],is_prime[1]=False,False #0 und 1 sind keine Primzahlen
for n in range(2, int(sqrt(sieve_up_to)+1)): #bei 2(der erstenprimzahl) fängt man an
if is_prime[n]: #wenn eine primzahl da ist, dann:
for l in range (n * n, sieve_up_to, n): #range(x,y, Schrittgröße)
is_prime[l]=False #jedes echt vielfache von n ist keine prime
#for i in range (len(is_prime)):
# print(i,"is prime",is_prime[i])
prime_numbers = []
for i in range(len(is_prime)):
if is_prime[i]:
prime_numbers.append(i)
return prime_numbers
#up_to = input("Please enter the number to search up to for primes using the sieve:")
#sieve(up_to)
| false |
b80cb0d8e3d127c6f859b761403cce0f9a9fcc0e | g423221138/chebei | /bs4_study.py | 1,766 | 4.21875 | 4 | #bs4官方文档学习
#例子文档
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
#实例编写
from bs4 import BeautifulSoup
import re
soup = BeautifulSoup(html_doc, 'html.parser')
#让数据按照标准格式输出
print(soup.prettify())
#几个简单地浏览结构化数据的方法
print(soup.title)
print(soup.title.name)
print(soup.title.string)
print(soup.title.parent.name)
print(soup.p)
print(soup.a)
print(soup.find_all('a'))
print(soup.find(id="link3"))
#从文档中获取所有文字内容:
print(soup.get_text())
#输出所有字符串
for string in soup.strings:
print(repr(string))
#去除多余空白字符串
for string in soup.stripped_strings:
print(repr(string))
#find_all用法举例
#从文档中找到所有<a>标签的链接:
for link in soup.find_all('a'):
print(link.get('href'))
#查找匹配标签及属性
print(soup.find_all("p", "title"))
#查找特定id属性
print(soup.find_all(id = "link2"))
#可正则查找href属性
print(soup.find_all(href = re.compile("elsie")))
#正则可模糊查找匹配字符串
print(soup.find_all(string = re.compile("sisters")))
#同时查找匹配多个字符串
print(soup.find_all(string = ["Tillie", "Elsie", "Lacie"]))
#limit参数,限制输出结果数量
print(soup.find_all("a", limit = 2)) | true |
c1279076e019dd32f1e2fd30c52d1831b9ffe504 | NicsonMartinez/The-Tech-Academy-Basic-Python-Projects | /For and while loop statements test code.py | 2,469 | 4.46875 | 4 |
mySentence = 'loves the color'
color_list = ['red','blue','green','pink','teal','black']
def color_function(name):
lst = []
for i in color_list:
msg = "{0} {1} {2}".format(name,mySentence,i)
lst.append(msg)
return lst
def get_name():
go = True
while go:
name = input('What is your name? ')
if name == '':
print('You need to provide you name!')
elif name == 'Sally':
print('Sally, you may not use this software.')
else:
go = False
lst = color_function(name)
for i in lst:
print(i)
get_name()
"""
**Notes by Nicson Martinez**
The way the above code works is:
1. get_name() gets called,
2. Since the while condition is true, the computer waits for an input from the user after
printing "What is your name? ". The While loop is used in a way to catch user input and if it
meets the specific condition in a conditional statement inside of the loop, print specific
message, else exit out of the loop and carry on with the rest of the instructions
(While loop keeps running until go = False).
3. Now that we have the string value that the user entered on the screen stored in variable 'name',
the function color_function(name) gets called and will eventually store what it returns to a local
variable 'lst' (local to get_name()).
4. In color_function(name), an empty list is stored in local variable 'lst' (local to color_function(name)).
the for loop iterates through global variable 'color_list' that contains a list of 6 color elements. So, a
string consisting of 'name' (what the user imputed),'mySentence' (global variable containing a string), and
'i' which is the current iteration of elements in list 'color_list' get stored in variable 'msg' (which is
a local variable to the for loop). Then lst.append(msg), adds each version of the 'msg' string to a the empty
list 'lst' that we created earlier. So at the end, the list 'lst' will have 6 elements containing 6 different
concatenation of strings differentiating in color because of the iteration of the 'color_list' using i. Lastly,
it returns that newly created list containing 6 elements made up of previously concatenated string values.
5. In get_name(), now that we have the returned list in variable 'lst', a for loop is used to iterate through
each of those 6 elements to print each of those elements (a string value made up of previously
concatenated string values) one at a time.
"""
| true |
6b42b0ca8302c2642bf2becbacf273c22f9281d2 | lufe089/lfrincon | /material/IntroProg/Ejercicios/6. Diccionarios/Nivel0- ejemploLLenarDiccionario.py | 1,586 | 4.3125 | 4 | # Escriba un programa en Python que le solicite al usuario por pantalla un listado de números (para finalizar debe ingresar 0). Cree un diccionario en donde se almacene la siguiente información a partir de los números ingresados:
# Cantidad de números pares
# Cantidad de números impares
# Número mayor
# Número menor
# Promedio
def main():
informacion = {}
listaUsuario = solicitarNumeros()
numerosPares = cantidadPares(listaUsuario)
numerosImpares = cantidadImpares(listaUsuario)
informacion["cantidadPares"] = numerosPares
informacion["cantidadImpares"] = numerosImpares
informacion["numeroMayor"] = max(listaUsuario)
informacion["numeroMenor"] = min(listaUsuario)
informacion["promedio"] = promedioLista(listaUsuario)
print(informacion)
def solicitarNumeros():
listaNumero = []
numeroUsuario = eval(input("Digite un número: "))
while numeroUsuario != 0:
listaNumero.append(numeroUsuario)
numeroUsuario = eval(input("Digite un número: "))
return listaNumero
def cantidadPares(lista):
contadorPares = 0
for elemento in lista:
if elemento % 2 == 0:
contadorPares += 1
return contadorPares
def cantidadImpares(lista):
contadorImpares = 0
for elemento in lista:
if elemento % 2 != 0:
contadorImpares += 1
return contadorImpares
def promedioLista(lista):
cantidadElementos = len(lista)
acumulador = 0
for elemento in lista:
acumulador += elemento
promedio = acumulador/cantidadElementos
return promedio
main() | false |
a59a8a3825c2b2d1c790e24f3fd2e7738b7b999d | veterinarian-5300/Genious-Python-Code-Generator | /Py_lab/Lab 1,2/plotting_a_line.py | 345 | 4.375 | 4 | # importing the module
import matplotlib.pyplot as plt
# x axis values
x = [1,2,3,4,5]
# corresponding y axis values
y = [2,4,1,3,5]
# plotting the points
plt.plot(x, y)
# naming the x axis
plt.xlabel('x - axis')
# naming the y axis
plt.ylabel('y - axis')
# Title to plot
plt.title('Plot')
# function to show the plot
plt.show() | true |
41da6593087fa6ce2e17fff89aa8179832563cfb | prmkbr/misc | /python/fizz_buzz.py | 536 | 4.125 | 4 | #!/usr/local/bin/python
"""
Prints the numbers from 1 to 100. But for multiples of three print 'Fizz'
instead of the number and for the multiples of five print 'Buzz'.
For numbers which are multiples of both three and five print 'FizzBuzz'.
"""
def main():
"""
Main body of the script.
"""
for i in xrange(1, 101):
if i % 5 == 0:
print "FizzBuzz" if (i % 3 == 0) else "Buzz"
elif i % 3 == 0:
print "Fizz"
else:
print i
if __name__ == "__main__":
main()
| true |
69936d76f0ecd2b3f640c6015389fbcbe8d14821 | yodifm/Hacktoberfest2020 | /round.py | 705 | 4.1875 | 4 | import turtle
print("1. Draw circle")
print("2. Draw Tangent Circles in Python Turtle")
print("3. Draw Spiral Circles in Python Turtle")
print("4. Draw Concentric Circles in Python Turtle")
num = int(input("Enter a number: "))
if num == 0:
t = turtle.Turtle()
t.circle(100)
print(num)
elif num == 1:
t = turtle.Turtle()
for i in range(10):
t.circle(10*i)
print(num)
elif num == 2:
t = turtle.Turtle()
for i in range(100):
t.circle(10+i, 45)
print(num)
elif num == 3:
t = turtle.Turtle()
for i in range(50):
t.circle(10*i)
t.up()
t.sety((10*i)*(-1))
t.down()
print(num)
| false |
5782fa59d65af071e8fb004f42c8321f17fb6fd3 | mljarman/Sorting | /src/iterative_sorting/iterative_sorting.py | 1,383 | 4.25 | 4 | # TO-DO: Complete the selection_sort() function below
arr = [5, 2, 1, 6, 8, 10]
def selection_sort(arr):
# loop through n-1 elements
for i in range(len(arr)-1):
cur_index = i
smallest_index = cur_index
# TO-DO: find next smallest element
# (hint, can do in 3 loc)
# iterate over list after initial loop:
for x in range(cur_index, len(arr)):
print(arr)
# if value at index is smaller, it becomes smallest_index
if arr[x] < arr[smallest_index]:
smallest_index = x
# swap index locations with smallest element:
arr[smallest_index], arr[cur_index] = arr[cur_index], arr[smallest_index]
return arr
selection_sort(arr)
# TO-DO: implement the Bubble Sort function below
def bubble_sort(arr):
# loop through array:
# first one will go through list once
for i in range(len(arr)-1):
# iterate over rest of list but don't
# need last index because know those are largest elements.
for x in range(len(arr)-i-1):
# compare each element to its neighbor:
# if element on the left is higher, switch places:
if arr[x] > arr[x + 1]:
arr[x], arr[x + 1] = arr[x +1], arr[x]
return arr
# STRETCH: implement the Count Sort function below
def count_sort( arr, maximum=-1 ):
return arr
| true |
de2c80883264b731c748c09d2a20c8c27995d03e | bjucps/cps110scope | /Lesson 2-3 String Processing/greeter.py | 481 | 4.21875 | 4 | # Demonstrates string processing
full_name = input('Enter your first and last name:')
if full_name == '':
print('You did not enter a name!')
else:
space_pos = full_name.find(' ')
if space_pos == -1:
print('You did not enter your first and last name!')
else:
first_name = full_name[0:space_pos]
print('Hello,' , first_name)
last_name = full_name[space_pos + 1:len(full_name)]
print('Or should I call you Mr.', last_name)
| true |
3d9018bea5f64544cb6abc8c06a27385262d73c3 | bjucps/cps110scope | /Lesson 2-4 Unit Testing/addnums.py | 409 | 4.1875 | 4 | def addNums(num: str) -> int:
"""Adds up all digits in `num`
Preconditions: `num` contains only digits
Postconditions: returns sum of digits in `num`
"""
sum = 0
for digit in num:
sum += int(digit)
return sum
def test_addNums():
assert addNums('123') == 6
if __name__ == "__main__":
# Add this to use debugger to step through unit test code
test_addNums()
| true |
25d71f955e65b7fd8bd67850c5cc694e8eb5b2ba | meera-ramesh19/sololearn-python | /displaycalenderofthemonth.py | 1,511 | 4.25 | 4 | # input from the user the month and the year of the calendar and displaythe
#calendar for the month or the year
yearuser=int(input("Enter the year:"))
print(yearuser)
#monthuser=int(input("\nEnter the month : "))
#print(monthuser)
startday=input("Enter the day of the week:")
print(startday)
calendar=[('January',range(1,31+1)),
('february',range(1,28+1)),
('March',range(1,31+1)),
('April',range(1,30+1)),
('May',range(1,31+1)),
('June',range(1,30+1)),
('July',range(1,31+1+1)),
('August',range(1,31+1)),
('September',range(1,30+1)),
('October',range(1,31+1)),
('November',range(1,30+1)),
('December',range(1,31+1)) ]
week=['Mo','Tu','We','Th','Fr','Sa','Su']
def leapyear(year):
if year % 4 ==0:
if year%100 != 0:
if year % 400 == 0:
return 1
else :
return 2
else:
return 1
else:
return 2
isyear=leapyear(yearuser)
if isyear == 1:
calendar[1] =('Febraury',range(1, 29 + 1))
startpoint=week.index(startday)
for month,days in calendar:
print('{0} {1}'.format(month,yearuser).center(20,' '))
print(''.join(['{0:<3}'.format(w) for w in week]))
print('{0:<3} '.format('') *startpoint,end=' ' )
for day in days:
print('{0:<3}'.format(day),end='')
startpoint = startpoint+ 1
if startpoint==7:
print()
startpoint=0
print('\n')
| false |
a8d363524dc77a216dbf6b331181ac9f05c7b4d8 | nong2013/Apple-to-Raspberry-Pi | /Early Lessons/python_strings_demo.py | 852 | 4.28125 | 4 | #python_Strings_demo
my_string ="and now for SOMEthing completely different"
my_silly_string ="silly walks"
pi_value= 3.1415926
integer_value = 123
print (my_string + ' -- The Ministry of ' + my_silly_string )
print (len(my_string))
print (my_string.capitalize())
print (my_string.upper())
print (my_string.lower())
print (my_string.title())
print (my_string.swapcase())
print (my_silly_string.center(30))
print (my_silly_string.center(30,'*'))
print (my_silly_string.rjust(30,'-'))
print (my_silly_string.ljust(30,'^'))
print (my_string.replace('different','penguin'))
print (my_string.partition('SOME'))
print (my_string.count('e'), " e's in our string")
print (my_string.find('e'))
print (
""" ANd now
for
something
completely
different""")
my_string ="Hello {0} {1} {2:5.4g}" .format("Nurse!",12,3.14159)
print(my_string)
| false |
09dcca918dee39291a7de4a3e15cbe89e3e7dfd6 | vinayakentc/BridgeLabz | /AlgorithmProg/VendingMachine.py | 1,042 | 4.3125 | 4 | # 10. Find the Fewest Notes to be returned for Vending Machine
# a. Desc > There is 1, 2, 5, 10, 50, 100, 500 and 1000 Rs Notes which can be
# returned by Vending Machine. Write a Program to calculate the minimum number
# of Notes as well as the Notes to be returned by the Vending Machine as a
# Change
# b. I/P > read the Change in Rs to be returned by the Vending Machine
# c. Logic > Use Recursion and check for largest value of the Note to return change
# to get to minimum number of Notes.
# ------------------------------------------------------------------------------------
def vendingmachine(money):
count2 = 0
for denomination in [1000, 500, 100, 50, 10, 5, 2, 1]:
count = 0
while money // denomination != 0:
count = count + 1
count2 = count2 + 1
money = money - denomination
print(denomination, " ", count)
return count2
if __name__ == '__main__':
money = int(input("Enter amount to withdraw:"))
print("No.of notes:", vendingmachine(money))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.