blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
df13a154e79b15d5a9b58e510c72513f8f8e2fa0
|
dipak-pawar131199/pythonlabAssignment
|
/Conditional Construct And Looping/SetB/Fibonacci.py
| 550
| 4.1875
| 4
|
'''4) Each new term in the Fibonacci sequence is generated by adding the previous two terms.
By starting with 1 and 2, the first 10 terms will be:
a. 0, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
b. By considering the terms in the Fibonacci sequence whose values do not exceed
four hundred, find the sum of the even-valued terms.
'''
num=int(input("enter how many fibonacci series number is display:"))
f0=1
f1=1
print("Terms of fibonaccie series is:")
print(f0,f1)
i=2
while i < num:
f=f0+f1
f0=f1
f1=f
print(f)
i=i+1
| true
|
10e021531d1b56e1375e898e7599422de0ce5c9a
|
RobStepanyan/OOP
|
/Random Exercises/ex5.py
| 776
| 4.15625
| 4
|
'''
An iterator
'''
class Iterator:
def __init__(self, start, end, step=1):
self.index = start
self.start = start
self.end = end
self.step = step
def __iter__(self):
# __iter__ is called before __next__ once
print(self) # <__main__.Iterator object at 0x000001465A203DC8>
return self
def __next__(self):
if not (self.index + self.step) in range(self.start, self.end+self.step):
raise StopIteration
else:
self.index += self.step
return self.index - self.step
iteratable = Iterator(0, 10, 2)
while True:
try:
print(iteratable.__next__())
# or print(next(iterable))
except StopIteration:
break
'''
Result:
0
2
4
6
8
'''
| true
|
9de5002aa797d635547bb7ca1989a435d4a97256
|
altvec/lpthw
|
/ex32_1.py
| 571
| 4.46875
| 4
|
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 {0}".format(number)
# same as above
for fruit in fruits:
print "A fruit of type: {0}".format(fruit)
# also we can go through mixed lists too
for i in change:
print "I got {0}".format(i)
# we can also build lists
elements = xrange(0, 6)
# now we can print then out too
for i in elements:
print "Element was: {0}".format(i)
| true
|
08087cefea1ebcb767e8cec2e4bcd3f4535b60de
|
PacktPublishing/Software-Architecture-with-Python
|
/Chapter04/rotate.py
| 417
| 4.1875
| 4
|
# Code Listing #6
"""
Example with collections.deque for rotating sequences
"""
from collections import deque
def rotate_seq1(seq1, n):
""" Rotate a sequence left by n """
# E.g: rotate([1,2,3,4,5], 2) => [4,5,1,2,3]
k = len(seq1) - n
return seq1[k:] + seq1[:k]
def rotate_seq2(seq1, n):
""" Rotate a sequence left by n using deque """
d = deque(seq1)
d.rotate(n)
return d
| false
|
b8e6af4affac0d2ae50f36296cc55f52c6b44af3
|
PacktPublishing/Software-Architecture-with-Python
|
/Chapter04/defaultdict_example.py
| 1,374
| 4.1875
| 4
|
# Code Listing #7
"""
Examples of using defaultdict
"""
from collections import defaultdict
counts = {}
text="""Python is an interpreted language. Python is an object-oriented language.
Python is easy to learn. Python is an open source language. """
word="Python"
# Implementations with simple dictionary
for word in text.split():
word = word.lower().strip()
try:
counts[word] += 1
except KeyError:
counts[word] = 1
print("Counts of word",word,'=>',counts[word])
cities = ['Jakarta','Delhi','Newyork','Bonn','Kolkata','Bangalore','Seoul']
cities_len = {}
for city in cities:
clen = len(city)
# First create entry
if clen not in cities_len:
cities_len[clen] = []
cities_len[clen].append(city)
print('Cities grouped by length=>',cities_len)
# Implementation using default dict
# 1. Counts
counts = defaultdict(int)
for word in text.split():
word = word.lower().strip()
# Value is set to 0 and incremented by 1 in one go
counts[word] += 1
print("Counts of word",word,'=>',counts[word])
# 2. Cities grouped by length
cities = ['Jakarta','Delhi','Newyork','Bonn','Kolkata','Bangalore','Seoul']
cities_len = defaultdict(list)
for city in cities:
# Empty list is created as value and appended to in one go
cities_len[len(city)].append(city)
print('Cities grouped by length=>',cities_len)
| true
|
97b15762af24ba6fb59fc4f11320e99ffcec6cf4
|
rxxxxxxb/PracticeOnRepeat
|
/Python Statement/practice1.py
| 540
| 4.125
| 4
|
# Use for, .split(), and if to create a Statement that will print out words that start with 's'
st = 'Print only the words that start with s in this sentence'
for word in st.split():
if word[0] == 's':
print(word)
# even number using range
li = list(range(1,15,2))
print(li)
#List comprehension to create a list of number devisible by 3
div3 = [x for x in range(1,50) if x%3 == 0 ]
print(div3)
#using list comprehension for 1st letter in every word
firstLetter = [word[0] for word in st.split()]
print(firstLetter)
| true
|
70c96ccdda8fec43e4dc2d85ba761bae2c4de876
|
heyimbarathy/py_is_easy_assignments
|
/pirple_functions.py
| 978
| 4.15625
| 4
|
# -----------------------------------------------------------------------------------
# HOMEWORK #2: FUNCTIONS
# -----------------------------------------------------------------------------------
'''create 3 functions (with the same name as those attributes),
which should return the corresponding value for the attribute.
extra: create a function that returns a boolean'''
year_recorded = 2003
artist = 'Snow Patrol'
def show_favorite_band(artist):
return artist
#function with default
def return_recording_year(year = 1900):
return year
# function without parameters
def echo_best_song():
return 'Run'
def search_artist(s):
'''tests if a substring is part of the artist name'''
return s in artist
# test functions through print statements
print(f"{echo_best_song()} ({return_recording_year(year_recorded)}) – {show_favorite_band(artist)}")
print("There were no songs released in:", return_recording_year())
print(search_artist('Snow'))
print(search_artist('Sun'))
| true
|
910185af5c3818d848aa569d6e57de868c9cb790
|
heyimbarathy/py_is_easy_assignments
|
/pirple_lists.py
| 1,311
| 4.15625
| 4
|
# -----------------------------------------------------------------------------------
# HOMEWORK #4: LISTS
# -----------------------------------------------------------------------------------
'''Create a function that allows you to add things to a list.
Anything that's passed to this function should get added to myUniqueList,
unless its value already exists in myUniqueList.
(If the value doesn't exist already, it should be added and the function should return True.
If the value does exist, it should not be added, and the function should return False)
Add some code below that tests the function, showcasing the different scenarios,
and then finally print the value of myUniqueList
extra: Add another function that pushes all the rejected inputs into a separate global array
called myLeftovers.
'''
myUniqueList = []
myLeftovers = []
def compile_unique_list(item):
'''depending on uniqueness, allocate item to myUniqueList or myLeftovers'''
if item not in myUniqueList:
myUniqueList.append(item)
return True
else:
myLeftovers.append(item)
return False
# test entries
compile_unique_list('dog')
compile_unique_list(4)
compile_unique_list(True)
compile_unique_list(4)
compile_unique_list('lucky')
# print both lists
print('Unique list:', myUniqueList)
print('Left-overs:', myLeftovers)
| true
|
29cc26a015801f4d1fe5e4c5ab103118b98e47bf
|
Segoka/python_learning
|
/colacao.py
| 650
| 4.125
| 4
|
print("*****Preparación de Colacao******")
leche = input("Primero de todo.... tienes leche? [s/n] ")
colacao = input("Y... tienes colacao? [s/n] ")
if leche == "s" and colacao == "s":
print("Perfecto!! Pon la leche en un vaso luego el colacao y a disfrutar :)")
elif leche != "s" and colacao == "s":
print("Te falta la leche para poder hacerlo :(")
print("Te lo apunto en la lista de la compra ")
elif leche == "s" and colacao != "s":
print("Te falta colacao :(")
print("Te lo apunto en la lista de la compra ")
else:
print("¡¡¡¡¡¡No tienes nada!!!!!")
print("No puedes hacer el colacao")
| false
|
5045f39041869fd81a8c406159a1bec39e4b7372
|
abdelilah-web/games
|
/Game.py
| 2,707
| 4.15625
| 4
|
class Game:
## Constractor for the main game
def __init__(self):
print('Welcome to our Games')
print('choose a game : ')
print('press [1] to play the Even-odd game')
print('Press [2] to play the Average game')
print('Press [3] to play the Multiplication')
self.choose()
##################################################
##Availabale choises
def choose(self):
while True:
select = input('your choise : ')
try:
select = int(select)
if select == 1:
print()
print()
self.Even_odd()
elif select == 2 :
print()
print()
self.Average()
elif select == 3 :
print()
print()
self.Multiplication()
else :
print('Please choose between 1, 2 or 3 ')
except ValueError:
print('Please Enter a valid number')
##################################################
##Even Odd code
def Even_odd(self) :
print('Welcome to the Even Odd game')
while True:
number = input('Enter your number : ')
if number == 'x':
print('End Of the game')
print('...')
break
try :
number = int(number)
if number % 2 == 0:
print('Even number')
else:
print('Odd number')
except ValueError :
print('Please enter a valid number')
##################################################
##Average Code
def Average(self) :
print('Welcome to the Average game')
how_number = int(input('how many number do you want to summ : '))
zero = 0
summ = 0
while how_number > zero :
numbers = int(input('your number : '))
zero += 1
summ += numbers
print(summ/how_number)
###################################################
##Multiplication Table game code
def Multiplication(self) :
print('Welcome to the Multiplication')
start = int(input('Enter the first number : '))
end = int(input('Enter the final number : '))
for x in range(start,end+1):
for y in range(1,13):
print(x,' X ',y ,' = ' ,x*y)
print('__________________________________')
## Create Object from the Class
play = Game()
| true
|
b9b5e983017845ef38400a7d8ad8c9e35333d405
|
bghoang/coding-challenge-me
|
/leetcode/Other (not caterogize yet)/maxProductThreeNumbers.py
| 1,411
| 4.25
| 4
|
'''
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example 1:
Input: [1,2,3]
Output: 6
Example 2:
Input: [1,2,3,4]
Output: 24
'''
'''
First solution: O(nlogn) runtime/ O(logn) space caus of sortings
Sort the array,
Find the product of the last 3 numbers
Find the product of the first 2 numbers and the last number
Return max of those 2 product
Optimal solution: O(n) runtime/ O(1) space
Find the 3 biggest numbers and 2 smallest numbers
Loop through the list, update these numbers
Find the product of the 3 biggest numbers
Find the product of the 2 smallest numbers and the biggest number
Return max of the these 2 products
'''
def maximumProduct(nums):
# First solution
'''
nums.sort()
l = len(nums)
if l < 3:
return
product1 = nums[l-1] * nums[l-2] * nums[l-3]
product2 = nums[l-1] * nums[0] * nums[1]
return max(product1, product2)
'''
max1, max2, max3 = float('-inf'), float('-inf'), float('-inf')
min1, min2 = float('inf'), float('inf')
for num in nums:
if num >= max1:
max3, max2, max1 = max2, max1, num
elif num >= max2:
max3, max2 = max2, num
elif num > max3:
max3 = num
if num <= min1:
min2, min1 = min1, num
elif num < min2:
min2 = num
return max(max1*max2*max3, min1*min2*max1)
| true
|
17756e03f8022ead554e7ec67add12ea22a45cb5
|
lj015625/CodeSnippet
|
/src/main/python/stack/minMaxStack.py
| 1,932
| 4.125
| 4
|
"""
Write a class for Min Max Stack.
Pushing and Popping value from the stack;
Peeking value at top of the stack;
Getting both minimum and maximum value in the stack at any time.
"""
from collections import deque
class MinMaxStack:
def __init__(self):
# doubly linked list deque is more efficient to implement large sized stack
self.minMaxStack = deque()
# O(1) time O(1) space
def peek(self):
return self.minMaxStack[-1]['number']
# O(1) time O(1) space
def pop(self):
return self.minMaxStack.pop()['number']
# O(1) time O(1) space
def push(self, number):
# default min and max to current number when stack is empty
currMinMax = {'min': number, 'max': number, 'number': number}
if len(self.minMaxStack) > 0:
lastMinMax = self.minMaxStack[-1]
currMin = min(number, lastMinMax['min'])
currMax = max(number, lastMinMax['max'])
currMinMax = {'min': currMin, 'max': currMax, 'number': number}
self.minMaxStack.append(currMinMax)
# O(1) time O(1) space
def getMin(self):
lastItem = self.minMaxStack[-1]
return lastItem['min']
# O(1) time O(1) space
def getMax(self):
lastItem = self.minMaxStack[-1]
return lastItem['max']
import unittest
def testMinMaxPeek(self, min, max, peek, stack):
self.assertEqual(stack.getMin(), min)
self.assertEqual(stack.getMax(), max)
self.assertEqual(stack.peek(), peek)
class TestProgram(unittest.TestCase):
def test_case_1(self):
stack = MinMaxStack()
stack.push(5)
testMinMaxPeek(self, 5, 5, 5, stack)
stack.push(7)
testMinMaxPeek(self, 5, 7, 7, stack)
stack.push(2)
testMinMaxPeek(self, 2, 7, 2, stack)
self.assertEqual(stack.pop(), 2)
self.assertEqual(stack.pop(), 7)
testMinMaxPeek(self, 5, 5, 5, stack)
| true
|
f2e670471bfa9bcac1e5f983ecdb0240eeaaf1f2
|
lj015625/CodeSnippet
|
/src/main/python/array/sumOfTwoNum.py
| 1,598
| 4.125
| 4
|
"""Given an array and a target integer, write a function sum_pair_indices that returns the indices of two integers
in the array that add up to the target integer if not found such just return empty list.
Note: even though there could be many solutions, only one needs to be returned."""
def sum_pair_indices(array, target):
index_holder = {}
for i in range(len(array)):
current_number = array[i]
complement = target - current_number
if complement in index_holder:
return [index_holder[complement], i]
else:
index_holder[current_number] = i
return []
array = [1, 2, 3, 4]
target = 5
print(sum_pair_indices(array, target))
def twoNumberSum(array, targetSum):
# use hashset O(n) time O(n) space
saved = {}
for current_num in array:
complement = targetSum - current_num
if complement in saved:
return [current_num, complement]
else:
# use dict as a hashset not a hashmap
saved[current_num] = complement
return []
array = [3,5,-4,8,11,1,-1,6]
target = 10
print(twoNumberSum(array, target))
def twoNumberSum2(array, targetSum):
# use sorting O(nlogn) time O(1) space
array.sort()
left = 0
right = len(array) - 1
while left < right:
currentSum = array[left] + array[right]
if currentSum == targetSum:
return [array[left], array[right]]
elif currentSum < targetSum:
left += 1
elif currentSum > targetSum:
right -= 1
return []
print(twoNumberSum2(array, target))
| true
|
153468d2ee32d18c1fe7cd6ee705d0f2e38c6ac2
|
lj015625/CodeSnippet
|
/src/main/python/string/anagram.py
| 626
| 4.28125
| 4
|
"""Given two strings, write a function to return True if the strings are anagrams of each other and False if they are not.
A word is not an anagram of itself.
"""
def is_anagram(string1, string2):
if string1 == string2 or len(string1) != len(string2):
return False
string1_list = sorted(string1)
string2_list = sorted(string2)
return string1_list == string2_list
string_1 = "listen"
string_2 = "silent"
print(is_anagram(string_1, string_2))
string_1 = "banana"
string_2 = "bandana"
print(is_anagram(string_1, string_2))
string_1 = "banana"
string_2 = "banana"
print(is_anagram(string_1, string_2))
| true
|
ce33d6bb0f0db42a8a0b28543f1ea6895da0d00c
|
lj015625/CodeSnippet
|
/src/main/python/tree/binarySearch.py
| 1,055
| 4.1875
| 4
|
def binary_search_iterative(array, target):
if not array:
return -1
left = 0
right = len(array)-1
while left <= right:
mid = (left + right) // 2
# found the target
if array[mid] == target:
return mid
# if target is in first half then search from the start to mid
elif target < array[mid]:
right = mid - 1
# search from the mid to end
else:
left = mid + 1
return -1
arr = [0, 1, 21, 33, 45, 45, 61, 71, 72, 73]
target = 33
print(binary_search_iterative(arr, target))
def binarySearch(array, target):
return binarySearchHelper(array, target, 0, len(array) - 1)
def binarySearchHelper(array, target, left, right):
while left <= right:
mid = (left + right) // 2
if target == array[mid]:
return mid
elif target < array[mid]:
right = mid - 1
else:
left = mid + 1
return -1
# Test array
arr = [ 2, 3, 4, 10, 40]
target = 10
print(binarySearch(arr, target))
| true
|
0ecfc8d40c1d7eba616676d03f04bb9bf187dc09
|
xamuel98/The-internship
|
/aliceAndBob.py
| 414
| 4.4375
| 4
|
# Prompt user to enter a string
username = str(input("Enter your username, username should be alice or bob: "))
''' Convert the username to lowercase letters and compare
if the what the user entered correlates with accepted string '''
if username.lower() == "alice" or username.lower() == "bob":
print("Welcome to programming with python " + username)
else:
print("Invalid username...")
| true
|
ed4ebe2d41a2da81d843004f32223f0662e59053
|
ParulProgrammingHub/assignment-1-kheniparth1998
|
/prog10.py
| 308
| 4.125
| 4
|
principle=input("enter principle amount : ")
time=input("enter time in years : ")
rate=input("enter the interest rate per year in percentage : ")
def simple_interest(principle,time,rate):
s=(principle*rate*time)/100
return s
print "simple interest is : ",simple_interest(principle,rate,time)
| true
|
3993689551ceed1cf1878340872846df0863556e
|
WangDongDong1234/python_code
|
/高级算法复习/ppt复习/2-2冒泡排序.py
| 268
| 4.1875
| 4
|
"""
冒泡排序
"""
def bubbleSort(array):
for i in range(len(array)-1):
for j in range(0,len(array)-1-i):
if array[j]>array[j+1]:
array[j],array[j+1]=array[j+1],array[j]
array=[2,1,5,6,3,4,9,8,7]
bubbleSort(array)
print(array)
| false
|
8e73474a9ac03600fee353f5f64259dae9840592
|
Sachey-25/TimeMachine
|
/Python_variables.py
| 1,234
| 4.21875
| 4
|
#Practice : Python Variables
#Tool : Pycharm Community Edition
#Platform : WINDOWS 10
#Author : Sachin A
#Script starts here
'''Greet'='This is a variable statement'
print(Greet)'''
#Commentning in python
# -- Single line comment
#''' ''' or """ """ multiline comment
print('We are learning python scripting and practice the same in pycharm And Varibales ')
'''[A-Za-z _]
[AnyEnlishWords and _]'''
variable = 1000
_another = 2000
CONSDATA=3.14
#Mulitple assignemnt
a,b,c,d=10,20,30,40
print("Value of c is : ",c)
print(a,b,c,d)
#first number
number_one=10
#second number
number_two=20
#addition of two numbers
print("Addition of two numbes :" ,number_one+number_two)
#Dynamical allocation
'''name = input("What is your name ?")
print(name)'''
number_third=input("Enter a number: ")
number_fourth=input("Enter another number: ")
print("Additon of entered number is :" , number_third+number_fourth)
#By default input prompt recives inputs as strings
#Implicit conversion --
#Explicit conversion
number_third=int(input("Enter a number: "))
number_fourth=int(input("Enter another number: "))
print("Additon of entered number is :" , number_third+number_fourth)
#Script Ends here
| true
|
1e8e3b23f03923e87e1910f676cda91e93bc02c8
|
skyesyesyo/AllDojo
|
/python/typelist.py
| 929
| 4.25
| 4
|
#input
one = ['magical unicorns',19,'hello',98.98,'world']
#output
"The array you entered is of mixed type"
"String: magical unicorns hello world"
"Sum: 117.98"
# input
two = [2,3,1,7,4,12]
#output
"The array you entered is of integer type"
"Sum: 29"
# input
three = ['magical','unicorns']
#output
"The array you entered is of string type"
"String: magical unicorns"
def typelist(somelist):
sum = 0
string = ""
for value in somelist:
if type(value) is int or type(value) is float:
sum = sum + value
elif type(value) is str:
string = string+value+" "
if(sum>0 and string != ""):
print "The array you entered is mixed type"
elif(sum>0 and string == ""):
print "The array you entered is of integer type"
elif(sum==0 and string !=""):
print "The array you entered is of string type"
print "String: {}".format(string)
if sum != 0:
print "Sum: {}".format(sum)
typelist(one)
typelist(two)
typelist(three)
| true
|
10c76b6c1e3466af784504b55e09bb4580f8303e
|
linth/learn-python
|
/function/base/2_closures_fun.py
| 1,679
| 4.15625
| 4
|
'''
Closure(閉包)
- 寫法特殊請注意
- 在 A 函式中再定義一個 B 函式。
- B 函式使用了 A 函式中的變量。
- A 函式返回 B 函式名。
閉包的使用時機
- 閉包避免了全域變數的使用,並可將資料隱藏起來。
- 當你有一些變數想要定義一個類別封裝起來時,若這個類別內只有一個方法時,使用閉包更為優雅
Reference:
- https://medium.com/@zhoumax/python-%E9%96%89%E5%8C%85-closure-c98c24e52770
- https://www.pythontutorial.net/advanced-python/python-closures/
'''
# 使用 class 方式
from tkinter import N
class Animal:
def __init__(self, name):
self.name = name
# 當使用 function 方式,就可以用閉包方式來處理
def animal(name):
def inner():
return name
return inner
def say():
# closure
##########################
greeting = 'hello'
def display():
print(greeting)
##########################
return display
# def compare(m, n):
# return m if m > n else n
if __name__ == '__main__':
# # assign function 物件給 fun
# fun = compare
# print(compare) # <function compare at 0x00000210C126F1F0>
# print(fun) # <function compare at 0x00000210C126F1F0>
# print(fun(1,2))
# print(compare(1, 2))
res = say()
res() # hello
# 使用 class 方式
a1 = Animal('dog')
a2 = Animal('cat')
print(a1.name)
print(a2.name)
# 當使用 function 方式,就可以用閉包方式來處理
a3 = animal('frog')
print(a3())
a4 = animal('lion')
print(a4())
| false
|
b73586058504c9ac8246fec05a91b091961be353
|
linth/learn-python
|
/data_structure/dict/dict_and_list_example.py
| 326
| 4.21875
| 4
|
'''
dict + list 範例
Reference:
- https://www.geeksforgeeks.org/python-ways-to-create-a-dictionary-of-lists/?ref=gcse
'''
d = dict((val, range(int(val), int(val) + 2)) for val in ['1', '2', '3'])
print([dict(id=v) for v in range(4)]) # [{'a': 0}, {'a': 1}, {'a': 2}, {'a': 3}]
# d2 = dict(a=[1, 2, 3])
# print(d2)
| false
|
95a0c7d5fd0cf60f7782f94f3dff469b636c519b
|
linth/learn-python
|
/async_IO/coroutines/base/1_multiple_process.py
| 928
| 4.125
| 4
|
'''
使用 multiple-processing 範例
Reference:
- https://medium.com/velotio-perspectives/an-introduction-to-asynchronous-programming-in-python-af0189a88bbb
'''
from multiprocessing import Process
def print_country(country='Asia'):
print('The name of country is: ', country)
# 如果不輸入引數情況下
def not_args():
p = Process(target=print_country)
p.start()
# 如果有輸入引數情況下
def has_args():
countries = ['America', 'Europe', 'Africa']
for c in countries:
p = Process(target=print_country, args=(c, ))
p.start()
p.join()
if __name__ == '__main__':
# 如果不輸入引數情況下
not_args()
# 如果有輸入引數情況下
has_args()
'''
The name of country is: Asia
The name of country is: America
The name of country is: Europe
The name of country is: Africa
'''
| false
|
886377b8aa15d2883936779974d51aad0e87916e
|
linth/learn-python
|
/algorithm/sorting/sort_base.py
| 943
| 4.25
| 4
|
"""
List sorting.
- sorted: 原本的 list 則不受影響
- sort: 改變原本的 list 內容
- sorted(x, revere=True) 反向排序
- itemgetter(), attrgetter()
Reference:
- https://officeguide.cc/python-sort-sorted-tutorial-examples/
"""
from operator import itemgetter, attrgetter
scores = [
('Jane', 'B', 12),
('John', 'A', 15),
('Dave', 'B', 11)
]
if __name__ == '__main__':
x = [4, 2, 5, 3, 1]
# sorted: 原本的 list 則不受影響
y = sorted(x)
print(y)
# sort: 改變原本的 list 內容
print(x)
x.sort()
print(x)
# 反向排序
y = sorted(x, reverse=True)
print(y)
# 依照第三個數字元素排序
print(sorted(scores, key=lambda s : s[2])) # [('Dave', 'B', 11), ('Jane', 'B', 12), ('John', 'A', 15)]
# 以第二個元素排序,若相同則以第三個元素排序
print(sorted(scores, key=itemgetter(1, 2)))
| false
|
8750cd8ce01b9521305987bd142f4815f4a0629d
|
linth/learn-python
|
/function/lambda/filter/filter.py
| 1,070
| 4.125
| 4
|
"""
References:
- https://www.runoob.com/python/python-func-filter.html
- https://www.liaoxuefeng.com/wiki/1016959663602400/1017323698112640
- https://wiki.jikexueyuan.com/project/explore-python/Advanced-Features/iterator.html
"""
import math
from collections import Iterable
# Iterator 判斷一個object是不是可迭代的
def is_iterator(lst):
return hasattr(lst, '__iter__')
# hasattr(l{}, '__iter__')
# hasattr(l'abc '__iter__')
def is_odd(n):
return n % 2 == 1
def is_even(n):
return n % 2 == 0
def get_odd_from_list(lst):
# filter(function, iterable)
res = filter(is_odd, lst)
return list(res)
def is_sqr(x):
return math.sqrt(x) % 1 == 0
# 過濾出1-100中平方根是整數的數
def filter_sqr():
res = filter(is_sqr, range(1, 101))
return list(res)
if __name__ == '__main__':
print(is_even(10))
arr = [1, 2, 3, 2, 8, 9, 4, 5]
res = get_odd_from_list(arr)
print(res, type(res))
print(is_iterator(123))
print(isinstance('abc', Iterable))
print(filter_sqr())
| false
|
8e018e0b2149ca6dab654c12849004e44761b8ba
|
linth/learn-python
|
/class/classAttr_instanceAttr/instance-method/1_InstanceMethod.py
| 479
| 4.21875
| 4
|
'''
實體方法(Instance Method)
- 至少要有一個self參數
- 實體方法(Instance Method) 透過self參數可以自由的存取物件 (Object)的屬性 (Attribute)及其他方法(Method)
Reference:
- https://www.learncodewithmike.com/2020/01/python-method.html
'''
class Cars:
# 實體方法(Instance Method)
def drive(self):
print('Drive is instance method.')
c = Cars()
c.drive()
'''Results:
Drive is instance method.
'''
| false
|
8b4a7475433936941c7f9794ec67783a4be5cadf
|
linth/learn-python
|
/function/anonymous_function/anonymous_filter.py
| 1,392
| 4.34375
| 4
|
"""
Anonymous function. (匿名函數)
- map
- filter
- reduce
lambda程式撰寫方式:
- lambda arguments: expression
map程式撰寫方式:
- map(function, iterable(s))
- 抓取符合的元素。
filter程式撰寫方式:
- filter(function, iterable(s))
- 用來過濾序列,過濾掉不符合的元素。
reduce程式撰寫方式:
- reduce(function, sequence[, initial])
- 對序列中元素進行累加
Reference:
- https://stackabuse.com/map-filter-and-reduce-in-python-with-examples/
- https://www.runoob.com/python/python-func-filter.html
"""
fruit = ["Apple", "Banana", "Pear", "Apricot", "Orange"]
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def is_even(l):
if l % 2 == 0:
return True
else:
return False
def is_larger_then_five(l):
if l > 5:
return True
else:
return False
# ##################
# 過濾掉不符合的元素
# ##################
res = filter(is_even, a)
print(list(res)) # [2, 4, 6, 8]
res2 = filter(is_larger_then_five, a)
print(list(res2)) # [6, 7, 8, 9]
# ###################################
# 使用 lambda function + filter 方式
# ###################################
res3 = filter(lambda l : True if l % 2 == 0 else False, a)
print(list(res3)) # [2, 4, 6, 8]
res4 = filter(lambda l : True if l > 5 else False, a)
print(list(res4)) # [6, 7, 8, 9]
| false
|
d09451cfc1aae0949562891a2b0d78a385a4eee2
|
linth/learn-python
|
/algorithm/sorting/merge_sort.py
| 1,809
| 4.53125
| 5
|
"""
Merge sorting (合併排序法)
- 把一個 list 開始逐步拆成兩兩一組
- 合併時候再逐步根據大小先後加入到新的 list裡面
- Merge Sort屬於Divide and Conquer演算法
- 把問題先拆解(divide)成子問題,並在逐一處理子問題後,將子問題的結果合併(conquer),如此便解決了原先的問題。
Reference:
- https://www.tutorialspoint.com/python_data_structure/python_sorting_algorithms.htm#
- https://www.youtube.com/watch?v=C9Xes8wH6Co&t=125s
- https://www.geeksforgeeks.org/python-program-for-merge-sort/
"""
def merge_sort(unsorted_list):
""" 前半部分都是將 list 拆成多個小的 list. """
if len(unsorted_list) <= 1:
return unsorted_list
# 找出中間值
middle_idx = len(unsorted_list) // 2
# 拆分兩個左右 list
left_list = unsorted_list[:middle_idx]
right_list = unsorted_list[middle_idx:]
left_list = merge_sort(left_list)
right_list = merge_sort(right_list)
return list(merge(left_list, right_list))
def merge(left_half, right_half):
res = []
# 如果兩個 list 都尚未結束,則逐步將 left_half/right_half 刪除並增加到 res
while len(left_half) != 0 and len(right_half) != 0:
if left_half[0] < right_half[0]:
res.append(left_half[0])
left_half.remove(left_half[0])
else:
res.append(right_half[0])
right_half.remove(right_half[0])
# 如果其中一個 list 已經排完
if len(left_half) == 0:
res = res + right_half
else:
res = res + left_half
return res
if __name__ == '__main__':
unsorted_list = [64, 34, 25, 12, 22, 11, 90]
print(merge_sort(unsorted_list))
| false
|
139447d3a6786a3fe0312574c48924ab83f7c709
|
linth/learn-python
|
/async_IO/multithreading/base/5_queue_threads.py
| 976
| 4.1875
| 4
|
'''
學習如何使用 queue + threads
Reference:
- https://blog.gtwang.org/programming/python-threading-multithreaded-programming-tutorial/
'''
from threading import Thread
import time
import queue
class Worker(Thread):
def __init__(self, queue, num):
Thread.__init__(self)
self.queue = queue
self.num = num
def run(self):
while self.queue.qsize() > 0:
# 取得新的資料
msg = self.queue.get()
# 處理資料
print('worker:', self.num, msg)
time.sleep(1)
if __name__ == '__main__':
# 建立佇列
q = queue.Queue()
# 將資料放入佇列
for i in range(10):
q.put(f'Data {i}')
# 建立 worker
w1 = Worker(q, 1)
w2 = Worker(q, 2)
# worker 處理資料
w1.start()
w2.start()
# 等待 worker 結束
w1.join()
w2.join()
print('finished !!!')
| false
|
584c4e36f9801a63fd17adae4c750647d0afeec8
|
linth/learn-python
|
/class/specificMethod-3.py
| 606
| 4.3125
| 4
|
'''
specific method
- __str__() and __repr__()
- __repr__() magic method returns a printable representation of the object.
- The __str__() magic method returns the string
Reference:
- https://www.geeksforgeeks.org/python-__repr__-magic-method/?ref=rp
'''
class GFG:
def __init__(self, name):
self.name = name
def __str__(self) -> str:
return f'Name is {self.name}'
def __repr__(self) -> str:
return f'GFG(name={self.name})'
if __name__ == '__main__':
obj = GFG('george')
print(obj.__str__())
print(obj.__repr__())
| true
|
a7ab0d16e3266d89e3119cfe59447d30062a9140
|
kelly4strength/intCakes
|
/intCake3.py
| 2,264
| 4.40625
| 4
|
# Given a list_of_ints,
# find the highest_product you can get from three of the integers.
# The input list_of_ints will always have at least three integers.
# find max, pop, add popped to a new list_of_ints
# add those ints bam!
# lst = [11,9,4,7,13, 21, 55, 17]
# returns [55, 21, 17]
# 93
# lst = [0, 9, 7]
# returns append three highest [9, 7]
# None
# if there are only 3 numbers in the list I need an if statement
# to add them before going through the loop
# if len(lst) == 3 then return three items added
# lst = [2, 2, 2]
# same issue as above
# returns None
# lst = [-1, 9, 8, -11]
# append three highest [9, 8]
# returns None
# lst = [-1, -9, -8, -11]
# returns
# append three highest [-1, -8]
# None
# lst = [-1, -9, -8, -11, -2]
# append three highest [-1, -2, -8]
# [-1, -2, -8]
# -11
def find_highest_product(lst):
"""function to find the highest product of three integers in a list, list will always have at least 3 integers"""
# list for the three highest numbers
three_highest = []
# product of three highest numbers
product = None
# if len(lst) == 3:
# product_of_three_highest = reduce(lambda x, y: x+y, lst)
# three_highest.append(product_of_three_highest)
# print "lst only three"
# return product_of_three_highest
while len(three_highest) < 3:
# else:
# for num in lst:
highest_num = max(lst)
print "max", highest_num
three_highest.append(highest_num)
print "append three highest", three_highest
lst.remove(highest_num)
# lst.append(0) - only added this to keep the original list the same length...
if len(three_highest) == 3:
# multiply the remaining items in the list
product_of_three_highest = reduce(lambda x, y: x+y, three_highest)
print three_highest
return product_of_three_highest
print find_highest_product([-1, -9, -8, -11, -2])
# lst.remove(product_of_three)
# for num in lst:
# two = max(lst)
# lst.remove(two)
# for num in lst:
# three = max(lst)
# lst.remove(three)
# # >>> lst = [3,7,2,9,11]
# # >>> for num in lst:
# add_top_three = 0
# # ... one = max(lst)
# # ... lst.remove(one)
# add_top_three += one
# # ... print one
# ... print lst
# ...
# 11
# [3, 7, 2, 9]
# 9
# [3, 7, 2]
# 7
# [3, 2]
# >>>
| true
|
0a3ab7aeeb12e47a41360f067099808b99eeac08
|
ChoSooMin/Web_practice
|
/python_pratice/command.py
| 1,230
| 4.1875
| 4
|
# list type : [str, int, float, boolean, list] [[1, 2, 3], [1, 2]] list 안의 list가 들어갈 경우, 안에 있는 list의 각 길이가 꼭 같을 필요는 없다.
list_a = [1, 2, 3]
list_b = [4, 5, 6]
print(list_a + list_b, " + 연산 후 list_a : ", list_a) # list_a 값을 변하게 하려면 list_a에 할당을 다시 해줘야 한다.
# 할당했을 경우
# list_a = list_a + list_b
# print("list_a 할당", list_a)
# 함수
# append(), insert(), del, pop()
print(list_a.append(4), "append 후 list_a", list_a) # list_a의 마지막 index+1에 4라는 원소를 넣어라
print(list_a.insert(1, 5), "insert 후 list_a", list_a) # list_a의 1번 인덱스에 5라는 값을 넣어라
print(list_a.pop(1), "pop(1) 삭제 후 list_a", list_a) # list_a의 1번 인덱스 원소 삭제
print(list_a.remove(1), "remove(1) 삭제 후 list_a", list_a) # 첫번째 만나는 값 1을 삭제해라
# for 반복자 in 반복할 수 있는 데이터(list, dictionary, string) :
# 실행문
index = 0 # index 같이 출력하기 위해
for data in list_a :
# print(index, data)
print("list_a[{0}] : {1}".format(index, data)) # list_a[0] : 2, list_a[1] : 3, list_a[2] : 4의 형식으로 출력된다.
index += 1
| false
|
f4c64fc63ebd9097cc450cc546586f504d385028
|
MariaAga/Codewars
|
/Python/triangle_type.py
| 335
| 4.125
| 4
|
# Should return triangle type:
# 0 : if triangle cannot be made with given sides
# 1 : acute triangle
# 2 : right triangle
# 3 : obtuse triangle
def triangle_type(a, b, c):
x,y,z = sorted([a,b,c])
if (x+y)<=z:
return 0
if (x*x+y*y==z*z):
return 2
if z*z > (x*x + y*y):
return 3
return 1
| false
|
d0434e4c42c139b85ec28c175749bb189d2a19bf
|
Francisco-LT/trybe-exercices
|
/bloco36/dia2/reverse.py
| 377
| 4.25
| 4
|
# def reverse(list):
# reversed_list = []
# for item in list:
# reversed_list.insert(0, item)
# print(reversed_list)
# return reversed_list
def reverse(list):
if len(list) < 2:
return list
else:
print(f"list{list[1:]}, {list[0]}")
return reverse(list[1:]) + [list[0]]
teste = reverse([1, 2, 3, 4, 5])
print(teste)
| true
|
d2d8f309a900c4642f0e7c66b3d33e26cabaf4e9
|
synaplasticity/py_kata
|
/ProductOfFibNumbers/product_fib_num.py
| 597
| 4.34375
| 4
|
def fibonacci(number):
if number == 0 or number == 1:
return number*number
else:
return fibonacci(number - 1) + fibonacci(number - 2)
def product_fib_num(product):
"""
Returns a list of the two consecutive fibonacci numbers
that give the provided product and a boolean indcating if
those two consecutive numbers where found.
"""
for n in range(1, product):
f1 = fibonacci(n)
f2 = fibonacci(n + 1)
if f1 * f2 == product or f1 * f2 > product:
break
return [f1, f2, f1 * f2 == product]
# return list[0]
| true
|
1687b77c4b2d3c44b6871e653a974153db7d3f96
|
ntuthukojr/holbertonschool-higher_level_programming-6
|
/0x07-python-test_driven_development/0-add_integer.py
| 578
| 4.125
| 4
|
#!/usr/bin/python3
"""Add integer module."""
def add_integer(a, b=98):
"""
Add integer function.
@a: integer or float to be added.
@b: integer or float to be added (default set to 98).
Returns the result of the sum.
"""
if not isinstance(a, int) and not isinstance(a, float):
raise TypeError('a must be an integer')
if not isinstance(b, int) and not isinstance(b, float):
raise TypeError('b must be an integer')
if isinstance(a, float):
a = int(a)
if isinstance(b, float):
b = int(b)
return (a + b)
| true
|
87ee73accac83e33eb0bf032d403ca1fa16c3b63
|
evnewlund9/repo-evnewlund
|
/PythonCode/reverse_string.py
| 414
| 4.28125
| 4
|
def reverse(string):
list = [character for character in string]
x = 0
n = -1
while x <= ((len(list))/2)-1:
a = list[x]
b = list[n]
list[x] = b
list[n] = a
x = x + 1
n = n - 1
stringFinal = ""
for letter in list:
stringFinal += letter
return stringFinal
def main():
reverse_string(string)
if __name__=="__main__":
main()
| false
|
394bc8e14a370f22d39fc84f176275c58d1ac349
|
evnewlund9/repo-evnewlund
|
/PythonCode/alternating_sum.py
| 414
| 4.125
| 4
|
def altSum(values):
sum = 0
for i in range(1,(len(values) + 1),2):
sum = sum + (int(values[i]) - int(values[(i - 1)]))
return sum
def main():
values = []
num = "0"
while num != "":
values.append(num)
num = input("Enter a floating point value: ")
answer = str(altSum(values))
print("The alternating sum is: " + answer)
if __name__ == "__main__":
main()
| false
|
7294ac7e6fa9a8e9d9b17cc661f639f7a04c289f
|
vdubrovskiy/Python
|
/new.py
| 738
| 4.21875
| 4
|
# -------------------------------------------------------
# import library
import math
# -------------------------------------------------------
# calculate rect. square
height = 10
width = 20
rectangle_square = height * width
print("Площадь прямоугольника:", rectangle_square)
# -------------------------------------------------------
# calculate circle square
radius = 5
circle_square = math.pi * (radius**2)
print("Площадь круга:", round(circle_square, 2))
print(type(circle_square))
# -------------------------------------------------------
# calculate hypotenuse
catheter1 = 5
catheter2 = 6
hypotenuse = math.sqrt(catheter1**2 + catheter2**2)
print("Гипотенуза:", round(hypotenuse, 2))
| false
|
b0cd7324e8b0835b40f9c1efbb48ff372ce54386
|
adyrmishi/100daysofcode
|
/rock_paper_scissors.py
| 843
| 4.15625
| 4
|
rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
import random
choices = [rock, paper, scissors]
player_choice = choices[int(input("Choose 0 for rock, 1 for paper and 2 for scissors.\n"))]
computers_choice = choices[random.randint(0,2)]
print(player_choice)
print(computers_choice)
if player_choice == computers_choice:
print("You drew!")
elif (player_choice == rock and computers_choice == scissors) or (player_choice == paper and computers_choice == rock) or (player_choice == scissors and computers_choice == paper):
print("You won!")
else:
print("You lost!")
| false
|
53bf0300d334909355777fa043e37beb823bd7d2
|
NixonRosario/Encryption-and-Decryption
|
/main.py
| 2,772
| 4.1875
| 4
|
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
# The Encryption Function
def cipher_encrypt(plain_text, key): # key is used has an swifting value
encrypted = ""
for c in plain_text:
if c.isupper(): # check if it's an uppercase character
c_index = ord(c) - ord('A') # ord('A') used because A is the first value in the alphabet
# shift the current character by key positions
c_shifted = (c_index + key) % 26 + ord('A')
c_new = chr(c_shifted)
encrypted += c_new
elif c.islower(): # check if its a lowercase character
# subtract the unicode of 'a' to get index in [0-25] range
c_index = ord(c) - ord('a')
c_shifted = (c_index + key) % 26 + ord('a')
c_new = chr(c_shifted)
encrypted += c_new
elif c.isdigit():
# if it's a number,shift its actual value
c_new = (int(c) + key) % 10
encrypted += str(c_new)
else:
# if its neither alphabetical nor a number, just leave it like that
encrypted += c
return encrypted
# The Decryption Function
def cipher_decrypt(ciphertext, key):
decrypted = ""
for c in ciphertext:
if c.isupper():
c_index = ord(c) - ord('A')
# shift the current character to left by key positions to get its original position
c_og_pos = (c_index - key) % 26 + ord('A')
c_og = chr(c_og_pos)
decrypted += c_og
elif c.islower():
c_index = ord(c) - ord('a')
c_og_pos = (c_index - key) % 26 + ord('a')
c_og = chr(c_og_pos)
decrypted += c_og
elif c.isdigit():
# if it's a number,shift its actual value
c_og = (int(c) - key) % 10
decrypted += str(c_og)
else:
# if its neither alphabetical nor a number, just leave it like that
decrypted += c
return decrypted
plain_text = input("Enter the message:- ")
ciphertext1 = cipher_encrypt(plain_text, 4) # function calling is made
print("Your text message:\n", plain_text)
print("Encrypted ciphertext:\n", ciphertext1)
n = input("If you want to decrypt any text press y else n: ")
if n == "y":
ciphertext = input("Enter the Encrypted text:- ")
decrypted_msg = cipher_decrypt(ciphertext, 4)
print("The decrypted message is:\n", decrypted_msg)
else:
print("Thank You!!")
| true
|
29d0f0a5b83dbbcee5f053a2455f9c8722b6cb51
|
MrYsLab/pseudo-microbit
|
/neopixel.py
| 2,943
| 4.21875
| 4
|
"""
The neopixel module lets you use Neopixel (WS2812) individually
addressable RGB LED strips with the Microbit.
Note to use the neopixel module, you need to import it separately with:
import neopixel
Note
From our tests, the Microbit Neopixel module can drive up to around 256
Neopixels. Anything above that and you may experience weird bugs and issues.
NeoPixels are fun strips of multi-coloured programmable LEDs.
This module contains everything to plug them into a micro:bit
and create funky displays, art and games
Warning
Do not use the 3v connector on the Microbit to power any more than
8 Neopixels at a time.
If you wish to use more than 8 Neopixels, you must use a separate
3v-5v power supply for the Neopixel power pin.
Operations
Writing the colour doesn’t update the display (use show() for that).
np[0] = (255, 0, 128) # first element
np[-1] = (0, 255, 0) # last element
np.show() # only now will the updated value be shown
To read the colour of a specific pixel just reference it.
print(np[0])
Using Neopixels
Interact with Neopixels as if they were a list of tuples.
Each tuple represents the RGB (red, green and blue) mix of colours
for a specific pixel. The RGB values can range between 0 to 255.
For example, initialise a strip of 8 neopixels on a strip connected
to pin0 like this:
import neopixel
np = neopixel.NeoPixel(pin0, 8)
Set pixels by indexing them (like with a Python list). For instance,
to set the first pixel to full brightness red, you would use:
np[0] = (255, 0, 0)
Or the final pixel to purple:
np[-1] = (255, 0, 255)
Get the current colour value of a pixel by indexing it. For example,
to print the first pixel’s RGB value use:
print(np[0])
Finally, to push the new colour data to your Neopixel strip, use the .show() function:
np.show()
If nothing is happening, it’s probably because you’ve forgotten this final step..!
Note
If you’re not seeing anything change on your Neopixel strip,
make sure you have show() at least somewhere otherwise your updates won’t be shown.
"""
from typing import Tuple, List, Union
from microbit import MicroBitDigitalPin
class NeoPixel:
def __init__(self, pin: MicroBitDigitalPin, n: int):
"""
Initialise a new strip of n number of neopixel LEDs controlled via pin pin.
Each pixel is addressed by a position (starting from 0).
Neopixels are given RGB (red, green, blue) values between 0-255 as a tuple.
For example, (255,255,255) is white.
"""
def clear(self) -> None:
"""
Clear all the pixels.
"""
def show(self) -> None:
"""
Show the pixels. Must be called for any updates to become visible.
"""
def __len__(self) -> int:
pass
def __getitem__(self, key) -> Tuple[int, int, int]:
pass
def __setitem__(self, key: int, value: Union[Tuple[int, int, int], List[int]]):
pass
| true
|
9d7df65d3a7a46a8c762c189d76bdebc04db78a9
|
Baude04/Translation-tool-for-Pirates-Gold
|
/fonctions.py
| 299
| 4.1875
| 4
|
def without_accent(string):
result = ""
for i in range(0,len(string)):
if string[i] in ["é","è","ê"]:
letter = "e"
elif string[i] in ["à", "â"]:
letter = "a"
else:
letter = string[i]
result += letter
return result
| false
|
638715d691110084c104bba50daefd5675aea398
|
baif666/ROSALIND_problem
|
/find_all_substring.py
| 501
| 4.25
| 4
|
def find_all(string, substr):
'''Find all the indexs of substring in string.'''
#Initialize start index
i = -1
#Creat a empty list to store result
result = []
while True:
i = string.find(substr, i+1)
if i < 0:
break
result.append(i)
return result
if __name__ == '__main__':
string = input('Please input your string : ')
substr = input("Please input your substring : ")
print('Result : ', find_all(string, substr))
| true
|
b0cad0b1e60d45bc598647fa74cb1c584f23eeaa
|
JGMEYER/py-traffic-sim
|
/src/physics/pathing.py
| 1,939
| 4.1875
| 4
|
from abc import ABC, abstractmethod
from typing import Tuple
import numpy as np
class Trajectory(ABC):
@abstractmethod
def move(self, max_move_dist) -> (Tuple[float, float], float):
"""Move the point along the trajectory towards its target by the
specified distance.
If the point would reach the target in less than the provided move
distance, move the point only to the target destination.
max_move_dist - maximum distance point can move towards target
returns: (new_x, new_y), distance_moved
"""
pass
class LinearTrajectory(Trajectory):
"""Trajectory that moves a point linearly towards a target point."""
def __init__(self, start_x, start_y, end_x, end_y):
self._cur_x, self._cur_y = start_x, start_y
self._end_x, self._end_y = end_x, end_y
def move(self, max_move_dist) -> (Tuple[float, float], float):
"""See parent method for desc."""
dx = self._end_x - self._cur_x
dy = self._end_y - self._cur_y
# Optimization
if dx == 0 or dy == 0:
norm = max(abs(dx), abs(dy))
# Target reached
if max_move_dist >= norm:
return (self._end_x, self._end_y), max_move_dist - norm
self._cur_x += np.sign(dx) * max_move_dist
self._cur_y += np.sign(dy) * max_move_dist
return (self._cur_x, self._cur_y), max_move_dist
else:
vector = np.array([dx, dy])
norm = np.linalg.norm(vector)
# Target reached
if max_move_dist >= norm:
return (self._end_x, self._end_y), max_move_dist - norm
unit = vector / norm
self._cur_x, self._cur_y = tuple(
np.array([self._cur_x, self._cur_y])
+ max_move_dist * np.array(unit)
)
return (self._cur_x, self._cur_y), max_move_dist
| true
|
d45df8bc1090aee92d3b02bb4e1d42fc93c402a0
|
dheerajkjha/PythonBasics_Udemy
|
/programmingchallenge_addition_whileloop.py
| 285
| 4.25
| 4
|
number = int(input("Please enter an Integer number."))
number_sum = 0
print("Entered number by the user is: " + str(number))
while number > 0:
number_sum = number_sum + number
number = number - 1
print("Sum of the numbers from the entered number and 1 is: " + str(number_sum))
| true
|
e96f81fc4967ca2dbb9993097f2653632b08a613
|
dheerajkjha/PythonBasics_Udemy
|
/programmingchallenge_numberofcharacters_forloop.py
| 258
| 4.34375
| 4
|
user_string = input("Please enter a String.")
number_of_characters = 0
for letter in user_string:
number_of_characters = number_of_characters + 1
print(user_string)
print("The number of characters in the input string is: " + str(number_of_characters))
| true
|
5e865b5a2ac4f087c4fe118e0423ef05908a4a09
|
reedless/dailyinterviewpro_answers
|
/2019_08/daily_question_20190827.py
| 528
| 4.5
| 4
|
'''
You are given an array of integers. Return the largest product that
can be made by multiplying any 3 integers in the array.
Example:
[-4, -4, 2, 8] should return 128 as the largest product can be made by multiplying -4 * -4 * 8 = 128.
'''
def maximum_product_of_three(lst):
lst.sort()
cand1 = lst[0] * lst[1] * lst[-1]
cand2 = lst[-3] * lst[-2] * lst[-1]
if (cand1 > cand2):
return cand1
else:
return cand2
print (maximum_product_of_three([-4, -4, 2, 8]))
# 128
| true
|
5e9bb62185611666f43897fd2033bae28d91ee18
|
reedless/dailyinterviewpro_answers
|
/2019_08/daily_question_20190830.py
| 806
| 4.21875
| 4
|
'''
Implement a queue class using two stacks.
A queue is a data structure that supports the FIFO protocol (First in = first out).
Your class should support the enqueue and dequeue methods like a standard queue.
'''
class Queue:
def __init__(self):
self.head = []
self.stack = []
def enqueue(self, val):
self.stack.append(val)
def dequeue(self):
while (self.stack):
elem = self.stack.pop()
self.head.append(elem)
result = self.head.pop()
while (self.head):
elem = self.head.pop()
self.stack.append(elem)
return result
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
print (q.dequeue())
print (q.dequeue())
print (q.dequeue())
# 1 2 3
| true
|
f1d328556b13e5d99c75d43cd750585184d9d9fa
|
deltahedge1/decorators
|
/decorators2.py
| 1,008
| 4.28125
| 4
|
import functools
#decorator with no arguments
def my_decorator(func):
@functools.wraps(func)
def function_that_runs_func(*args, **kwargs): #need to add args and kwargs
print("in the decorator")
func(*args, **kwargs) #this is the original function, dont forget to add args and kwargs
print("after the decorator")
return function_that_runs_func
@my_decorator
def my_function(x,y):
print(x+y)
my_function("hello ", "Ish")
#decorators that can accepts arguments themselves
def decorator_with_arguments(number):
def my_decorator(func):
@functools.wraps(func)
def function_that_runs_func(*arg, **kwargs): #args and kwargs needed to pass in arguments to original function
print("in the decorator")
if number == 56:
print("Not running the function!")
else:
func(*args, **kwargs)
print("After the decorator")
return function_that_runs_func
return my_decorator
| true
|
0ac3a65fea58acea5bc8ae4b1bbf9a4fb45b9f87
|
Hilamatu/cse210-student-nim
|
/nim/game/board.py
| 1,548
| 4.25
| 4
|
import random
class Board:
"""A board is defined as a designated playing surface.
The responsibility of Board is to keep track of the pieces in play.
Stereotype: Information Holder
Attributes:
"""
def __init__(self):
self._piles_list = []
self._prepare()
def to_string(self):
"""converts the board data to its string representation and returns it to the caller."""
print("-" *10)
for count, value in enumerate(self._piles_list):
print(f"{count}: " + "O " * value)
print("-" *10)
def apply(self, move):
"""applies a move to the playing surface. In this case, that means removing a number of stones from a pile.
Accepts one argument, an instance of Move."""
pile = move.get_pile()
stone = move.get_stones()
reduce = self._piles_list[pile] - stone
self._piles_list[pile] = reduce
def is_empty(self):
"""determines if all the stones have been removed from the board.
It returns True if the board has no stones on it; false if otherwise."""
empty = [0] * len(self._piles_list)
return self._piles_list == empty
def _prepare(self):
"""sets up the board with a random number of piles (2 - 5)
containing a random number of stones (1 - 9)."""
piles = random.randint(2, 5)
for n in range(piles):
stones = random.randint(1, 9)
self._piles_list.append(stones)
| true
|
686e53872c553c6dedc03dac6cf19806cc10b19e
|
NenadPantelic/Cracking-the-coding-Interview
|
/LinkedList/Partition.py
| 1,985
| 4.375
| 4
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 3 16:45:16 2020
@author: nenad
"""
"""
Partition: Write code to partition a linked list around a value x, such that all nodes less than x come
before all nodes greater than or equal to x. If x is contained within the list, the values of x only need
to be after the elements less than x (see below). The partition element x can appear anywhere in the
"right partition"; it does not need to appear between the left and right partitions.
"""
class Node:
def __init__(self, data): # data -> value stored in node
self.data = data
self.next = None
def partition(head, x):
if head is None:
return None
# ll with elements less than x
less_ll_head = None
# ll with element greater than or equal to x
greater_ll_head = None
# last added nodes for both sublists
prev_sm_node = None
prev_gr_node = None
node = head
while node:
# add to left sublist
if node.data < x:
if less_ll_head is None:
less_ll_head = node
else:
prev_sm_node.next = node
prev_sm_node = node
#prev_sm_node.next = None
else:
if greater_ll_head is None:
greater_ll_head = node
else:
prev_gr_node.next = node
prev_gr_node = node
#prev_gr_node.next = None
node = node.next
# make tails
prev_sm_node.next = None
prev_gr_node.next = None
# concatenate lists
prev_sm_node.next = greater_ll_head
return less_ll_head
def print_list(head):
node = head
while node:
print(node.data, end=" ")
node = node.next
print()
n1 = Node(3)
n2 = Node(5)
n3 = Node(8)
n4 = Node(5)
n5 = Node(10)
n6 = Node(2)
n7 = Node(1)
n1.next = n2
n2.next = n3
n3.next = n4
n4.next = n5
n5.next = n6
n6.next = n7
x = 5
head = partition(n1, 5)
print_list(head)
| true
|
886195fb51ac965a88f3ad3c3d505548638cc6bd
|
JadsyHB/holbertonschool-python
|
/0x06-python-classes/102-square.py
| 2,010
| 4.59375
| 5
|
#!/usr/bin/python3
"""
Module 102-square
Defines Square class with private attribute, size validation and area
accessible with setters and getters
comparison with other squares
"""
class Square:
"""
class Square definition
Args:
size: size of side of square, default size is 0
Functions:
__init__self, size)
size(self)
size(self, value)
area(self)
"""
def __init__(self, size=0):
"""
Initilization of square
Attributes:
size: size of side of square, default value is 0
"""
self.size = size
@property
def size(self):
"""
Getter
Return: size
"""
return self.__size
@size.setter
def size(self, value):
"""
Setter
Args:
value: size is set to value when value is an int
"""
if type(value) is not int:
raise TypeError("size must be an integer")
elif value < 0:
raise ValueError("size must be >= 0")
else:
self.__size = value
def area(self):
"""
Calculates are of a square
Returns:
area
"""
return (self.__size)**2
def __eq__(self, other):
"""
Compares if equals
"""
return self.size == other.size
def __ne__(self, other):
"""
Compares if not equals
"""
return self.size != other.size
def __lt__(self, other):
"""
Compares if less than
"""
return self.size < other.size
def __le__(self, other):
"""
Compares if less than or equal
"""
return self.size <= other.size
def __gt__(self, other):
"""
Compares if greater than
"""
return self.size > other.size
def __ge__(self, other):
"""
Compares if greater than or equal
"""
return self.size >= other.size
| true
|
55ffa8c32622c42f6d3a314018a0adaf0e1c0d18
|
JadsyHB/holbertonschool-python
|
/0x06-python-classes/1-square.py
| 373
| 4.125
| 4
|
#!/usr/bin/python3
"""
Module 1-square
class Square defined with private attribute size
"""
class Square:
"""
class Square
Args:
size: size of a side in a square
"""
def __init__(self, size):
"""
Initialization of square
Attributes:
size: size of a side of a square
"""
self.__size = size
| true
|
4db4720f452b2db358234f9ce50735430fb6a938
|
Rouzip/Leetcode
|
/Search Insert Position.py
| 354
| 4.125
| 4
|
def searchInsert(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
if target <= nums[0]:
return 0
for i in range(1, len(nums)):
if nums[i - 1] <= target <= nums[i]:
return i
return len(nums)
print(searchInsert([1,3],3))
| false
|
4415ba37e475c1650da0d81b32f85b4a4ae7d45c
|
23o847519/Python-Crash-Course-2nd-edition
|
/chapter_02/full_name.py
| 492
| 4.125
| 4
|
first_name = "ada"
last_name = "lovelace"
# sử dụng f-string format để đổi các biến bên trong {} thành giá trị
# f-string có từ Python 3.6
full_name = f"{first_name} {last_name}"
print(full_name)
# thêm "Hello!," ở phía trước
print(f"Hello, {full_name.title()}!")
# gom lại cho gọn
message = f"Hello, {full_name.title()}!"
print(message)
# Python 3.5 trở về trước
full_name2 = "Hello, {} {}!".format(first_name, last_name)
print(full_name2.title())
| false
|
7bb73b9cd6ca812395b93b17f116abd8e7033311
|
23o847519/Python-Crash-Course-2nd-edition
|
/chapter_09/tryityourself913.py
| 796
| 4.1875
| 4
|
# Import randit function from random library
from random import randint
# Make a class named Die
class Die:
def __init__(self, sides=6):
# default value of 6
self.sides = sides
def describe_die(self):
print(f"\nYour die has: {self.sides} sides")
# Write a method called roll_die() that prints
# a random number between 1 and self.sides
def roll_die(self):
return randint(1, self.sides)
die1 = Die()
die2 = Die(10)
die3 = Die(20)
die1.describe_die()
for i in range(10):
# format :2d mean 2 digits
print(f"- turn {i+1 :2d}: {die1.roll_die()}")
die2.describe_die()
for i in range(10):
# format :2d mean 2 digits
print(f"- turn {i+1 :2d}: {die2.roll_die()}")
die3.describe_die()
for i in range(10):
# format :2d mean 2 digits
print(f"- turn {i+1 :2d}: {die3.roll_die()}")
| false
|
96384a26d49430e18697d080c49f3341e7b13834
|
23o847519/Python-Crash-Course-2nd-edition
|
/chapter_08/tryityourself814.py
| 874
| 4.4375
| 4
|
# 8-14. Cars: Write a function that stores information about
# a car in a dictionary. The function should always receive
# a manufacturer and a model name. It should then accept an
# arbitrary number of keyword arguments. Call the function
# with the required information and two other name-value
# pairs, such as a color or an optional feature. Your
# function should work for a call like this one:
# car = make_car('subaru', 'outback', color='blue',
# tow_package=True)
# Print the dictionary that’s returned to make sure all
# the information was stored correctly.
print("\nEx 8.14 Cars\n" + "-"*70)
def make_car(manufacturer, model, **car_info):
car_info['manufacturer'] = manufacturer
car_info['model'] = model
return car_info
car_profile = make_car(model = 'outback', manufacturer = 'subaru', color = 'blue', tow_package = True)
print(car_profile)
| true
|
e0f7b4c472500360a03266df6e35031cd4534dc4
|
23o847519/Python-Crash-Course-2nd-edition
|
/chapter_07/tryityourself7.1.py
| 334
| 4.15625
| 4
|
# Ex 7.1 Rental Car
# Write a program that asks the user what kind of rental car they
# would like. Print a message about that car, such as
# “Let me see if I can find you a Subaru.”
print("\nEx 7.1")
rental_car = input("What kind of rental car would you like?\n")
print(f"\nLet me see if I can find you a {rental_car.title()}.")
| true
|
9cca96cb78e6ae2772c76f81ccf6a2106ee0ac99
|
23o847519/Python-Crash-Course-2nd-edition
|
/chapter_03/cars.py
| 604
| 4.28125
| 4
|
#Sorting
print("\nSorting")
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.sort()
print(cars)
#Reverse sorting
print("\nReverse sorting")
cars.sort(reverse=True)
print(cars)
#Sort tạm thời
print("\n Sorted()")
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Original list:")
print(cars)
print("\nSorted list:")
print(sorted(cars))
print("\nCome back to Original list:")
print(cars)
#Reverse list
#Đảo ngược toàn bộ list
print("\nReverse list")
print(cars)
cars.reverse()
print(cars)
#Length of List
print("\nLength of List")
cars.reverse()
print(cars)
print(len(cars))
| true
|
44f55bae68ae6fa0fddd6628dea0c92e1f0d81fe
|
23o847519/Python-Crash-Course-2nd-edition
|
/chapter_10/tryityourself106.py
| 726
| 4.3125
| 4
|
# 10-6. Addition: One common problem when prompting for numerical input
# occurs when people provide text instead of numbers. When you try to
# convert the input to an int, you’ll get a ValueError. Write a program
# that prompts for two numbers. Add them together and print the result.
# Catch the ValueError if either input value is not a number, and print
# a friendly error message. Test your program by entering two numbers
# and then by entering some text instead of a number.
print("\nEx 10.6 Addition\n" + "-"*70)
print("Give me a number\n")
try:
num1 = input("First_number = ")
num1 = int(num1)
except ValueError:
print("Value Error!, Enter a number next time.")
else:
print(f"Your number: {num1}")
| true
|
6ba1d02a2025378d11c0cfbf8a11055e0593e3ca
|
radishmouse/06-2017-cohort-python
|
/104/n_to_m.py
| 629
| 4.375
| 4
|
n = int(raw_input("Start from: "))
m = int(raw_input("End on: "))
# Let's use a while loop.
# Every while loop requires three parts:
# - the while keyword
# - the condition that stops the loop
# - a body of code that moves closer to the "stop condition"
# our loop counts up to a value.
# let's declare a counter variable
# and set the counter to start at n
count = n
# only run if count is less than or equal to the value of m
while count <= m:
# remember, we have to indent the body of our loop
# print the current value of count
print count
# move us closer to the "stop condition"
count = count + 1
| true
|
50cbb178c40d42e83aed3f936feef223eca8a865
|
radishmouse/06-2017-cohort-python
|
/dictionaries/dictionary1.py
| 534
| 4.21875
| 4
|
phonebook_dict = {
'Alice': '703-493-1834',
'Bob': '857-384-1234',
'Elizabeth': '484-584-2923'
}
#Print Elizabeth's phone number.
print phonebook_dict['Elizabeth']
#Add a entry to the dictionary: Kareem's number is 938-489-1234.
phonebook_dict['Kareem'] = '938-489-1234'
#Delete Alice's phone entry.
del phonebook_dict['Alice']
#Change Bob's phone number to '968-345-2345'.
phonebook_dict['Bob'] = '968-345-2345'
#Print all the phone entries.
for person, phone in phonebook_dict.items():
print "%s: %s" % (person, phone)
| true
|
9858f021c037399c27be321b80a5111b8825e2db
|
BhushanTayade88/Core-Python
|
/Feb/day 12/Dynamic/oddeve.py
| 756
| 4.3125
| 4
|
#1.Program to create odd-even elements list from given list.
l=[]
eve=[]
odd=[]
n=int(input("How many no u wants add in list :"))
for i in range(n):
a=int(input("Enter Numbers :"))
l.append(a)
for i in l:
if i%2==0:
eve.append(i)
else:
odd.append(i)
print("----Statements----\n" \
"1.List elemets--\n" \
"2.Display Even no on list--\n" \
"3.Display Odd no on list--\n" \
"4.Exit--\n")
while True:
ch=int(input("Enter your choice :"))
if ch<=3:
pass
if ch==1:
print(l)
elif ch==2:
print(eve)
elif ch==3:
print(odd)
elif ch==4:
break
else:
print("wrong choiice")
| false
|
a10c31fc5c15b63e5fd895e1457282eafab1f10f
|
BhushanTayade88/Core-Python
|
/March/day 10 filefand/taskfilehand/2perticularline.py
| 419
| 4.125
| 4
|
'''
2.Program to display particular line taken by user.
'''
f=open("bhushan.txt","r")
##print(f.tell())
##print(f.readline())
##print(f.tell())
##print(f.readline())
##print(f.tell())
##print(f.readline())
##print(f.tell())
##print(f.readline())
b=f.readlines()
print(b)
a=int(input("which line no u want see :"))
print(b[a-1])
##for i in range(len(b)):
##
## if i+1==a:
## print(b[i])
##
f.close()
| false
|
ff01b3080817a8469c3aee2376c6c3abc76ebe8e
|
BhushanTayade88/Core-Python
|
/Feb/day 19 const,oper/task/callstudent.py
| 2,432
| 4.15625
| 4
|
from student import *
print("----Statements----\n" \
"1.Enter details--\n" \
"2.display--\n" \
"3.Exit--\n")
while True:
ch=int(input("Enter Your choice----:"))
if ch<=2:
pass
if ch==1:
l=[]
n=int(input("How many student details u want to insert :"))
for i in range(n):
s=Student(int(input("Enter Student Rollno:")),input("Student name :"),int(input("Student Marks:")))
l.append(s)
elif ch==2:
print("----Student record----\n" \
"1.display all record--\n" \
"2.perticular student record--\n" \
"3.Exit--\n")
while True:
ch=int(input("enter your choice :"))
if ch<=2:
pass
#sname=input("enter name")
if ch==1:
for stu in l:
print(stu)
elif ch==2:
print("----Search record by----\n" \
"1.Rollno--\n" \
"2.Name--\n" \
"3.Exit--\n")
while True:
ch1=int(input("your choice :"))
if ch1<=2:
pass
if ch1==1:
srollno=int(input("enter rollno :"))
for st in l:
if st.sturollno==srollno:
print("record found ",st)
break
else:
print("no record found")
elif ch1==2:
sname=input("Enter student name :")
for st in l:
if st.stuname==sname:
print("record found ",st)
break
else:
print("no record found")
elif ch1==3:
break
elif ch==3:
break
elif ch==3:
break
else:
print("***Wrong Choice***")
| false
|
a14253b6695c8ebbe913a05525d001fe46ddb66c
|
BhushanTayade88/Core-Python
|
/March/day 11 decorator/task2/class deco/factorial.py
| 271
| 4.21875
| 4
|
##num=int(input("Enter no :"))
##for i in range(num,0,-1):
## fact = 1
## if i==0:
## print("Factorial of 0 is :",'1')
## else:
## for j in range(i,0,-1):
## fact = fact * j
##
## print("Factorial of", i ,"is :",fact)
##
| false
|
6ebffaee162c491cc4f2289845a1bf7bbcd33604
|
flub78/python-tutorial
|
/examples/conditions.py
| 374
| 4.1875
| 4
|
#!/usr/bin/python
# -*- coding:utf8 -*
print ("Basic conditional instructions\n")
def even(a):
if ((a % 2) == 0):
print (a, "is even")
if (a == 0):
print (a, " == 0")
return True
else:
print (a, "is odd")
return False
even(5)
even(6)
even(0)
bln = even(6)
if bln:
print ("6 is even")
print ("bye")
| true
|
0e531d7c0b4da023818f02265ab9e009420eaec6
|
flub78/python-tutorial
|
/examples/test_random.py
| 1,395
| 4.1875
| 4
|
#!/usr/bin/python
# -*- coding:utf8 -*
"""
How to use unittest
execution:
python test_random.py
or
python -m unittest discover
"""
import random
import unittest
class RandomTest(unittest.TestCase):
""" Test case for random """
def test_choice(self):
"""
given: a list
when: selecting a random elt
then: it belongs ot the list
"""
lst = list(range(10))
# print lst
elt = random.choice(lst)
# print "random elt = ", elt
self.assertIn(elt, lst)
self.assertFalse(elt % 4 == 0, "True quite often")
def test_shuffle(self):
"""
given: a list
when: shuffled
then: it still contains the same elements
likely in different order
"""
lst = list(range(10))
shuffled = list(lst) # deep copy
random.shuffle(shuffled)
# print "lst =", lst
# print "shuffled= ", shuffled
sorted = list(shuffled)
sorted.sort()
# print "sorted = ", sorted
same_order = True
i = 0
while i < 10:
same_order = same_order and (lst[i] == shuffled[i])
i += 1
self.assertEqual(sorted, lst)
self.assertFalse(same_order, "list are not in the same order after shuffling")
if __name__ == '__main__':
unittest.main()
| true
|
38081fd73316e20f6361d835d710dd379e8c78ea
|
andremmfaria/exercises-coronapython
|
/chapter_06/chapter_6_6_4.py
| 823
| 4.375
| 4
|
# 6-4. Glossary 2: Now that you know how to loop through a dictionary, clean up the code from Exercise 6-3 (page 102) by replacing your series of print statements with ía loop that runs through the dictionary’s keys and values. When you’re sure that your loop works, add five more Python terms to your glossary. When you run your program again, these new words and meanings should automatically be included in the output.
valdict = {
"variable": "Elementar data type that stores values",
"loop": "Self repeating structure",
"dictionary": "Glossary structure",
"array": "List of elements",
"conditional": "Conditional test",
"word0": "Value0",
"word1": "Value1",
"word2": "Value2",
"word3": "Value3",
"word4": "Value4"
}
for key in valdict:
print(key + ", " + valdict[key])
| true
|
9634250371f02daea5f2200e7ef401237a660e6f
|
andremmfaria/exercises-coronapython
|
/chapter_08/chapter_8_8_10.py
| 765
| 4.40625
| 4
|
# 8-10. Great Magicians: Start with a copy of your program from Exercise 8-9. Write a function called make_great() that modifies the list of magicians by adding the phrase the Great to each magician’s name. Call show_magicians() to see that the list has actually been modified.
def show_magicians(great_magicians):
for magician in great_magicians:
print(magician)
def make_great(magicians_names,great_magicians):
while magicians_names:
g_magician = magicians_names.pop()
g_magician = 'Great ' + g_magician
great_magicians.append(g_magician)
magicians_names = ['houdini','david blane', 'chris angel']
great_magicians = []
show_magicians(magicians_names)
make_great(magicians_names,great_magicians)
show_magicians(great_magicians)
| false
|
8c5498b935164c457447729c6de1553b390664e5
|
andremmfaria/exercises-coronapython
|
/chapter_06/chapter_6_6_8.py
| 522
| 4.34375
| 4
|
# 6-8. Pets: Make several dictionaries, where the name of each dictionary is the name of a pet. In each dictionary, include the kind of animal and the owner’s name. Store these dictionaries in a list called pets. Next, loop through your list and as you do print everything you know about each pet.
pet_0 = {
'kind' : 'dog',
'owner' : 'Juliana'
}
pet_1 = {
'kind' : 'cat',
'owner' : 'Ana'
}
pet_2 = {
'kind' : 'fish',
'owner' : 'Joao'
}
pets = [pet_0, pet_1, pet_2]
for p in pets:
print(p)
| true
|
7bc98b1c9a50acb1e7ff7fe3ce2781ace3a56eb8
|
andremmfaria/exercises-coronapython
|
/chapter_07/chapter_7_7_1.py
| 257
| 4.21875
| 4
|
# 7-1. Rental Car: Write a program that asks the user what kind of rental car they would like. Print a message about that car, such as “Let me see if I can find you a Subaru.”
message = input("Let me see whether I can find you a Subaru")
print(message)
| true
|
1647b333db7c0d04a16dc37f794146cb9843561b
|
Khusniyarovmr/Python
|
/Lesson_1/4.py
| 991
| 4.3125
| 4
|
"""
4. Написать программу, которая генерирует в указанных пользователем границах
● случайное целое число,
● случайное вещественное число,
● случайный символ.
Для каждого из трех случаев пользователь задает свои границы диапазона.
Например, если надо получить случайный символ от 'a' до 'f',
то вводятся эти символы. Программа должна вывести на экран любой
символ алфавита от 'a' до 'f' включительно.
"""
import random
a = input('Начальный символ: ')
b = input('Конечный символ: ')
if str.isdigit(a):
print(random.randint(int(a), int(b)+1))
print(random.uniform(int(a), int(b)+1))
else:
print(chr(random.randint(ord(a), ord(b)+1)))
| false
|
5cb4a583ec8a49434d41500e142cb79879070d1a
|
mkccyro-7/Monday_test
|
/IF.py
| 226
| 4.15625
| 4
|
bis = int(input("enter number of biscuits "))
if bis == 3:
print("Not eaten")
elif 0 < bis < 3:
print("partly eaten")
elif bis == 0:
print("fully eaten")
else:
print("Enter 3 or any other number less than 3")
| true
|
f029326ea49aaa4f1157fd6da18d6847144c5e26
|
Fran0616/beetles
|
/beatles.py
| 821
| 4.1875
| 4
|
#The beatles line up
#empty list name beetles
beatles = []
beatles.append("John Lennon")
beatles.append("Paul McCartney")
beatles.append("George Harrison")
print("The beatles consist of ", beatles)
print("Both name must be enter as written below\n")
for i in beatles:
i = input("Enter the name \"Stu Sutcliffe\": ")
x = input("Enter the name \"Pete Best\": ")
if i == "Stu Sutcliffe" and x == "Pete Best" :
beatles.append(i)
beatles.append(x)
print("The beatles consist of ", beatles)
break
print("Will now remove Peter Best and Stu Sutcliffe from the group")
#Deleting Stu Sutcliffe
del beatles[3]
#Deleting Pete Best
del beatles[3]
print("The beatles consist of ", beatles)
print("Lets add Ringo Starr to the list ")
beatles.insert(0, "Ringo Starr")
print("The beatles now consist of: ", beatles)
| false
|
4ccb729ebdb80510424aa920666f6b4f0acb5a2a
|
ErenEla/PythonSearchEngine
|
/Unit_1/Unit1_Hw3.py
| 1,060
| 4.1875
| 4
|
# IMPORTANT BEFORE SUBMITTING:
# You should only have one print command in your function
# Given a variable, x, that stores the
# value of any decimal number, write Python
# code that prints out the nearest whole
# number to x.
# If x is exactly half way between two
# whole numbers, round up, so
# 3.5 rounds to 4 and 2.5 rounds to 3.
# You may assume x is not negative.
# Hint: The str function can convert any number into a string.
# eg str(89) converts the number 89 to the string '89'
# Along with the str function, this problem can be solved
# using just the information introduced in unit 1.
# x = 3.14159
# >>> 3 (not 3.0)
# x = 27.63
# >>> 28 (not 28.0)
# x = 3.5
# >>> 4 (not 4.0)
#ENTER CODE BELOW HERE
x = 3.14159
x_round = str(round(x))
x_point = x_round.find(".")
print(x_round[:x_point])
#Train Focus
s = "CidatyUcityda"
print('1',s[6]+s[-2:]+s[7:12])
print('2',s[6]+s[-2:]+s[7:11])
print('3',s[6]+s[2:4]+s[7:13])
print('4',s[-7]+s[2:4]+s[7:11])
print('5',s[6]+s[-2]+s[3]+s[:-2]+s[4:6])
print('6',s[6]+s[2]+s[3]+s[7:11])
| true
|
4ed0dc77c6784f2006ca437568f80a73a8d51438
|
ErenEla/PythonSearchEngine
|
/Unit_3/Unit3_Quiz1.py
| 504
| 4.15625
| 4
|
# Define a procedure, replace_spy,
# that takes as its input a list of
# three numbers, and modifies the
# value of the third element in the
# input list to be one more than its
# previous value.
spy = [1,2,2]
def replace_spy(x):
x[0] = x[0]
x[1] = x[1]
x[2] = x[2]+1
return x
# In the test below, the first line calls your
# procedure which will change spy, and the
# second checks you have changed it.
# Uncomment the top two lines below.
print(replace_spy(spy))
#>>> [0,0,8]
| true
|
c2d3e85a587c11b9bae19348149545584de22a49
|
Bower312/Tasks
|
/task4/4.py
| 791
| 4.28125
| 4
|
# 4) Напишите калькулятор с возможностью находить сумму, разницу, так
# же делить и умножать. (используйте функции).А так же добавьте
# проверку не собирается ли пользователь делить на ноль, если так, то
# укажите на ошибку.
def calc(a,b,z):
if z == "+":
print(a+b)
elif z == "-":
print(a-b)
elif z == "*": #например если ввели знак * то умножай))).
print(a*b)
elif z == '/':
print(a/b)
a=int(input("введите первое число: "))
b=int(input("введите второе число: "))
z=input("знак ")
calc(a,b,z)
| false
|
66c4d00e9ce49d8570cd7a703d04aef1b6b4d3f6
|
iSabbuGiri/Control-Structures-Python-
|
/qs_17.py
| 962
| 4.21875
| 4
|
#Python program that serves as a basic calculator
def add(x,y):
return x+y
def subtract(x,y):
return x-y
def multiply(x,y):
return x*y
def divide(x,y):
return x/y
print("Select operation:")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
choice = input("Enter a choice(1/2/3/4):")
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter the first number:"))
num2 = float(input("Enter the second number:"))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2) )
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2) )
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2) )
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2) )
break
else:
print("Invalid Input")
| true
|
8bd69d5c6077386a9e79557a3d1ff83ffe464c1b
|
iSabbuGiri/Control-Structures-Python-
|
/qs_2.py
| 341
| 4.15625
| 4
|
#Leap year is defined as year which is exactly divisible by 4 except for century year i.e years ending with 00.
#Century year is a year which is divisible by 400
year = int(input("Enter a leap year:"))
if (year%4 == 0 and year%100 !=0 or year%400==0 ):
print("The year is a leap year")
else:
print("The year is not a leap year")
| false
|
3ba2ea80dcc916bf8e245a2ab518042b9ee55e3e
|
richardrcw/python
|
/guess.py
| 270
| 4.1875
| 4
|
import random
highest = 10
num = random.randint(1, highest)
guess = -1
while guess != num:
guess = int(input("Guess number between 1 and {}: ".format(highest)))
if guess > num:
print("Lower...")
elif guess < num:
print("Higher....")
else:
print("Got it!")
| true
|
4c33a43d27dede9366a759d3a40bccffcba92d3a
|
justhonor/Data-Structures
|
/Sort/BubbleSort.py
| 532
| 4.15625
| 4
|
#!/usr/bin/python
# coding:utf-8
##
# Filename: BubbleSort.py
# Author : aiapple
# Date : 2017-07-05
# Describe:
##
#############################################
def BubbleSort(a):
length = len(a)
while(length):
for j in range(length-1):
if a[j] > a[j+1]:
temp = a[j]
a[j] = a[j+1]
a[j+1] = temp
length=length-1
print "output array:%s"%a
if __name__ == '__main__':
a = [2,14,17,9,8,16]
print "input array:%s"%a
BubbleSort(a)
| false
|
4d737f3cdff3065f1c11c03ed8ce14c8c70b9f74
|
CeciliaTPSCosta/atv-construdelas
|
/lista1/temperatura.py
| 220
| 4.15625
| 4
|
# Faça um Programa que peça a temperatura em graus Fahrenheit, transforme e mostre a temperatura em graus Celsius.
fahrenheit = float(input('Diga-me uma temperatura em F \n'))
print(f'{5 * ((fahrenheit-32) / 9)}°C')
| false
|
efabcf8f6f413c833a75c8cc5e57e556c2d12823
|
prathamarora10/guessingNumber
|
/GuessingNumber.py
| 561
| 4.21875
| 4
|
print('Number Guessing Game')
print('Guess a Number (between 1 and 9):')
import random
number = random.randint(1,9)
print(number)
for i in range(0,5,1):
userInput = int(input('Enter your Guess :- '))
if userInput < 3:
print('Your guess was too low: Guess a number higher than 3')
elif userInput < 5:
print('Your guess was too low: Guess a number higher than 5')
elif userInput < 7:
print('Your guess was too low: Guess a number higher than 7')
if userInput == number:
print('Congratulations !\nYou Won !!')
| true
|
39cebe0780b8532517dadf4fd04517b9ba79f207
|
Carterhuang/sql-transpiler
|
/util.py
| 922
| 4.375
| 4
|
def standardize_keyword(token):
""" In returned result, all keywords are in upper case."""
return token.upper()
def join_tokens(lst, token):
"""
While joining each element in 'lst' with token,
we want to make sure each word is separated
with space.
"""
_token = token.strip(' ')
if _token == '':
# token only has empty space(s) in it,
# we make standardize it to be one empty space.
_token = ' '
else:
# Paddle a space on the left and right side of the token,
# so that "AND" becomes " AND ".
_token = ''.join([' ', standardize_keyword(_token), ' '])
return _token.join(map(str, lst))
def normalize_keyword(input_str):
"""
During transpiling, all reserved keywords(operators,
macro/field headers, etc) are converted to lower case.
e.g. 'AND' -> 'and', 'OR' -> 'or', etc.
"""
return input_str.lower()
| true
|
8c9890c843a63d8b2fa90098b28594ba1e012d99
|
justinhohner/python_basics
|
/datatypes.py
| 1,042
| 4.34375
| 4
|
#!/usr/local/bin/python3
# https://www.tutorialsteacher.com/python/python-data-types
#
"""
Numeric
Integer: Positive or negative whole numbers (without a fractional part)
Float: Any real number with a floating point representation in which a fractional component is denoted by a decimal symbol or scientific notation
Complex number: A number with a real and imaginary component represented as x+yj. x and y are floats and j is -1(square root of -1 called an imaginary number)
"""
x = 1
print(x)
y = 1.1
print(y)
j = -1
print(j)
i = x+j*y
print(i)
# Boolean
a = True
b = False
print(a)
print(b)
# String
a = "This is a string"
print(a)
# List
a = ["This", "is", "a", "list"]
print(a)
# Tuple
a = ("This", "is", "a", "list", 0)
print(a)
# Dictionary
a = {1:"Steve", 2:"Bill", 3:"Ram", 4: "Farha"}
print(a)
a = {"Steve":1, "Bill":2, "Ram":3, "Farha":4}
print(a)
"""
Create a variable to store your name and set it's value to your name
Create a list of numbers from 1 to 10
add the first 3 values of the list of numbers
"""
| true
|
9acddfa9dc609fbb3aad91d19c4348dda1aee239
|
jsanon01/100-days-of-python
|
/resources/day4/area_circumference_circle.py
| 427
| 4.59375
| 5
|
"""
Fill out the functions to calculate the area and circumference of a circle.
Print the result to the user.
"""
import math
def area(r):
return math.pi * r ** 2
def circumference(r):
return math.pi * 2 * r
radius = float(input("Circle radius: "))
circle_area = area(radius)
circle_circumference = circumference(radius)
print('Area: ' + str(circle_area))
print('Circumference: ' + str(circle_circumference))
| true
|
e2ca488af3efc7e4d8f5bc72be4ac0a3f139edd9
|
saumyatiwari/Algorithm-of-the-day
|
/api/FirstAPI.py
| 790
| 4.125
| 4
|
import flask
app=flask.Flask(__name__) #function name is app
# use to create the flask app and intilize it
@app.route("/", methods =['GET']) #Defining route and calling methods. GET will be in caps intalized as an arrya
# if giving the giving any configuration then function name will proceed with @ else it will use name alone for example we are using @app name to updae the config of @app name
def helloworld():
return "Helloworld"
if __name__ == '__main__':
app.run()
# by default flask uses 5000 port and host as 0.0.0.0
# Run steps
#1. Run with python FirstAPI.py
#2. Flask will auto. create a server & start the flask app in dev mode
#3. U can call ur API with address http://0.0.0.0:5000/
#4. First install the flask by command "pip3 install flask" before running the code
| true
|
1544a910a16011cc302ba6bcb449c0c8887c05ee
|
msvrk/frequency_dict
|
/build/lib/frequency_dict/frequency_dict_from_collection.py
| 557
| 4.53125
| 5
|
def frequency_dict_from_collection(collection):
"""
This is a useful function to convert a collection of items into a dictionary depicting the frequency of each of
the items. :param collection: Takes a collection of items as input :return: dict
"""
assert len(collection) > 0, "Cannot perform the operation on an empty collection"
dictionary = {}
keys = []
for item in collection:
if item not in keys:
keys.append(item)
dictionary[item] = 0
dictionary[item] += 1
return dictionary
| true
|
660a467f0428f2564fdeec4da7f5dc171b7a2e65
|
DivijeshVarma/CoreySchafer
|
/Decorators2.py
| 2,922
| 4.46875
| 4
|
# first class functions allow us to treat functions like any other
# object, for example we can pass functions as arguments to another
# function, we can return functions and we can assign functions to
# variable. Closures-- it will take advantage of first class functions
# and return inner function that remembers and has access to variables
# local to scope in which they were created.
def outer_func(mg):
def inner_func():
print(mg)
return inner_func
hi_func = outer_func('hi')
hello_func = outer_func('hello')
hi_func()
hello_func()
# Decorator is function that takes another function as an argument
# add some functionality and returns another function, all of this
# without altering source code of original function you passed in.
# Decorating our functions allow us to easily add functionality to
# our existing functions, by adding functionality inside wrapper
# without modifying original display function in any way and add
# code in wrapper in any way
def decorator_func(original_func):
def wrapper_func(*args, **kwargs):
print(f"wrapper function executed {original_func.__name__}")
original_func(*args, **kwargs)
return wrapper_func
@decorator_func
def display():
print('display function')
@decorator_func
def display_info(name, age):
print(f"name:{name}, age:{age}")
display()
display_info('divi', 27)
print('--------------------------------')
##################################
class decorator_class(object):
def __init__(self, original_func):
self.original_func = original_func
def __call__(self, *args, **kwargs):
print(f"call method executed {self.original_func.__name__}")
return self.original_func(*args, **kwargs)
@decorator_class
def display():
print('display function')
@decorator_class
def display_info(name, age):
print(f"name:{name}, age:{age}")
display()
display_info('divi', 27)
print('--------------------------------')
##################################
def decorator_func(func):
def wrapper_func(*args, **kwargs):
print(f"wrapper executed before {func.__name__}")
func(*args, **kwargs)
print(f"wrapper executed after {func.__name__}")
return wrapper_func
@decorator_func
def display_info(name, age):
print(f"display function with {name} and {age}")
display_info('divijesh', 27)
print('--------------------------------')
####################################
def prefix_decorator(prefix):
def decorator_func(func):
def wrapper_func(*args, **kwargs):
print(f"{prefix} wrapper executed before {func.__name__}")
func(*args, **kwargs)
print(f"{prefix} wrapper executed after {func.__name__}")
return wrapper_func
return decorator_func
@prefix_decorator('LOG:')
def display_info(name, age):
print(f"display function with {name} and {age}")
display_info('divijesh', 27)
| true
|
b1ebc3eeeceebdf1eb6760c88d00be6b40d9e5cd
|
DivijeshVarma/CoreySchafer
|
/generators.py
| 809
| 4.28125
| 4
|
def square_nums(nums):
result = []
for i in nums:
result.append(i * i)
return result
sq_nums = square_nums([1, 2, 3, 4, 5])
print(sq_nums)
# square_nums function returns list , we could convert
# this to generator, we no longer get list
# Generators don't hold entire result in memory
# it yield 1 result at a time, waiting for us to ask
# next result
# when you convert generators to list you lose performance
# like list(sq_nums)
def square_nums(nums):
for i in nums:
yield (i * i)
sq_nums = square_nums([1, 2, 3, 4, 5])
print(sq_nums)
print(next(sq_nums))
for num in sq_nums:
print(num)
# list comprehensions
sqs = [x * x for x in [1, 2, 3, 4, 5]]
print(sqs)
# create generator
sqs = (x * x for x in [1, 2, 3, 4, 5])
print(sqs)
for num in sqs:
print(num)
| true
|
e328a29edf17fdeed4d8e6c620fc258d9ad28890
|
DivijeshVarma/CoreySchafer
|
/FirstclassFunctions.py
| 1,438
| 4.34375
| 4
|
# First class functions allow us to treat functions like
# any other object, i.e we can pass functions as argument
# to another function and returns functions, assign functions
# to variables.
def square(x):
return x * x
f1 = square(5)
# we assigned function to variable
f = square
print(f)
print(f(5))
print(f1)
# we can pass functions as arguments and returns function
# as result of other functions
# if function accepts other functions as arguments or
# return functions as a result i.e higher order function
# adding paranthesis will execute function.
# # we can pass functions as arguments:--
def square(x):
return x * x
def my_map(func, arg_list):
result = []
for i in arg_list:
result.append(func(i))
return result
squares = my_map(square, [1, 2, 3, 4])
print(squares)
# to return a function from another function, one of the
# aspects for first class function
# log variable is equal to log_message function, so we can
# run log variable as just like function, it remembers
# message from logger function
def logger(msg):
def log_message():
print(f"log: {msg}")
return log_message
log = logger('hi')
log()
# it remembers tag we passed earlier
def html_tag(tag):
def wrap_text(msg):
print(f"<{tag}>{msg}<{tag}>")
return wrap_text
p_h1 = html_tag('h1')
p_h1('Test headline')
p_h1('Another headline')
p_p1 = html_tag('p1')
p_p1('Test paragraph')
| true
|
560043e5d1c9d6e31f9b9f6d4b86c02ac5bff325
|
Kyeongrok/python_crawler
|
/lecture/lecture_gn5/week2/01_function.py
| 859
| 4.21875
| 4
|
# plus라는 이름의 함수를 만들어 보세요
# 파라메터는 val1, val2
# 두개의 입력받은 값을 더한 결과를 리턴하는 함수를 만들어서
# 10 + 20을 콘솔에 출력 해보세요.
def plus(val1, val2):
result = val1 + val2
return result
def minus(val1, val2):
return val1 - val2
def multiple(val1, val2):
return val1 * val2
def divide(val1, val2):
return val1 / val2
result = plus(10, 20)
print(result)
print(minus(10, 20))
# (10 + 20) * (30 - 40) / 20
result1 = plus(10, 20)
result2 = minus(30, 40)
result3 = multiple(result1, result2)
result4 = divide(result3, 20)
print("result4:", result4)
result5 = divide(multiple(plus(10, 20), minus(30, 40)), 20)
print("result5:", result5)
def something(v1, v2, v3, v4, v5):
return (v1 + v2) * (v3 - v4) / v5
print("sth:", something(10, 20, 30, 40, 20))
| false
|
4f9c1ddb562de274a644e6d41e73d70195929274
|
sairamprogramming/learn_python
|
/book4/chapter_1/display_output.py
| 279
| 4.125
| 4
|
# Program demonstrates print statement in python to display output.
print("Learning Python is fun and enjoy it.")
a = 2
print("The value of a is", a)
# Using keyword arguments in python.
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='+')
print(1, 2, 3, 4, sep='+', end='%')
print()
| true
|
64c62c53556f38d9783de543225b11be87304daf
|
sairamprogramming/learn_python
|
/pluralsight/core_python_getting_started/modularity/words.py
| 1,204
| 4.5625
| 5
|
# Program to read a txt file from internet and put the words in string format
# into a list.
# Getting the url from the command line.
"""Retrive and print words from a URL.
Usage:
python3 words.py <url>
"""
import sys
def fetch_words(url):
"""Fetch a list of words from a URL.
Args:
url: The url of UTF-8 text document.
Returns:
A list of strings containing the words from
the document.
"""
# Importing urlopen method.
from urllib.request import urlopen
# Getting the text from the url given.
story = urlopen(url)
story_words = []
for line in story:
line_words = line.decode('utf8').split()
for word in line_words:
story_words.append(word)
story.close()
return story_words
def print_items(items):
"""Prints items one per line.
Args:
An iterable series of printable items.
"""
for item in items:
print(item)
def main(url):
"""Prints each word from a text document from a URL.
Args:
url: The url of UTF-8 text document.
"""
words = fetch_words(url)
print_items(words)
if __name__ == '__main__':
main(sys.argv[1])
| true
|
99bd7e715f504ce64452c252ac93a026f426554d
|
gotdang/edabit-exercises
|
/python/factorial_iterative.py
| 414
| 4.375
| 4
|
"""
Return the Factorial
Create a function that takes an integer and returns
the factorial of that integer. That is, the integer
multiplied by all positive lower integers.
Examples:
factorial(3) ➞ 6
factorial(5) ➞ 120
factorial(13) ➞ 6227020800
Notes:
Assume all inputs are greater than or equal to 0.
"""
def factorial(n):
fact = 1
while n > 1:
fact *= n
n -= 1
return fact
| true
|
30d9fe50769150b3efcaa2a1628ef9c7c05984fa
|
gotdang/edabit-exercises
|
/python/index_multiplier.py
| 428
| 4.125
| 4
|
"""
Index Multiplier
Return the sum of all items in a list, where each
item is multiplied by its index (zero-based).
For empty lists, return 0.
Examples:
index_multiplier([1, 2, 3, 4, 5]) ➞ 40
# (1*0 + 2*1 + 3*2 + 4*3 + 5*4)
index_multiplier([-3, 0, 8, -6]) ➞ -2
# (-3*0 + 0*1 + 8*2 + -6*3)
Notes
All items in the list will be integers.
"""
def index_multiplier(lst):
return sum([i * v for i, v in enumerate(lst)])
| true
|
36f7db179bcc0339c7969dfa9f588dcd51c6d904
|
adarshsree11/basic_algorithms
|
/sorting algorithms/heap_sort.py
| 1,200
| 4.21875
| 4
|
def heapify(the_list, length, i):
largest = i # considering as root
left = 2*i+1 # index of left child
right = 2*i+2 # index of right child
#see if left child exist and greater than root
if left<length and the_list[i]<the_list[left]:
largest = left
#see if right child exist and greater than root
if right<length and the_list[largest]<the_list[right]:
largest = right
#change root if larger number caught as left or right child
if largest!=i:
the_list[i],the_list[largest]=the_list[largest],the_list[i]
# heapify the new root
heapify(the_list, length, largest)
def heapSort(the_list):
n = len(the_list)
#heapify the full list
for i in range(n//2-1, -1, -1):
#heapify from last element with child to top
heapify(unsorted_list, n, i)
#heapsort sxtracting elements one by one
for i in range(n-1, 0, -1):
#swapping the root element which is max to its position
the_list[i],the_list[0] = the_list[0],the_list[i]
#heapify from root again length reduced to 'i' to keep sorted elements unchanged
heapify(the_list, i, 0)
if __name__ == '__main__':
unsorted_list = [17,87,6,22,54,3,13,41]
print(unsorted_list)
heapSort(unsorted_list)
print(unsorted_list)
| true
|
88bf240c30c8373b3779a459698223ec3cb74e24
|
mliu31/codeinplace
|
/assn2/khansole_academy.py
| 836
| 4.1875
| 4
|
"""
File: khansole_academy.py
-------------------------
Add your comments here.
"""
import random
def main():
num_correct = 0
while num_correct != 3:
num1 = random.randint(10,99)
num2 = random.randint(10,99)
sum = num1 + num2
answer = int(input("what is " + str(num1) + " + " + str(num2) + "\n>>"))
if sum == answer:
num_correct += 1
print("Correct. You've gotten " + str(num_correct) + " problem(s) right in a row! ")
if num_correct == 3:
print("Congratulations! you've mastered addition")
else:
print("Incorrect. the expected answer is " + str(sum))
num_correct = 0
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == '__main__':
main()
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.