blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
8f4667338e761fca8b77a813d4f5ee957e0cbaa0
|
Akansha0211/Basics-of-try-except-revision
|
/Basics of try-except.py
| 1,461
| 4.1875
| 4
|
'''num1=input("Enter the first number \n")
num2=input("Enter the second number \n")
try:
print("the sum of twoi numbers is", int(num1) + int(num2))
except Exception as e:
print(e)
print("This line is very important")'''
#Will never come in except block
'''a=[1,2,3]
try:
print("second element",a[1])
except Exception as e:
print("Fourth element")
print(" An Error occured") '''
'''a=[1,2,3]
try:
print("Second element is",a[1])
print("Fourth element is",a[3])
except Exception as e:
print(e)'''
'''a=[1,2,3]
try:
print("Second element",a[1])
print("Fourth element is",a[3])
except IndexError:
print("An Error occured")'''
'''try:
a=3
if a<4:
b=a/(a-3)
print(b)
except Exception as e:
print(e)'''
'''try:
a=eval(input("Enter anumber between 3 and 4,inclusive"))
if a<4:
b=a/(a-3)
print("Value of b:",b)
print("Value of b",b)
except (ZeroDivisionError):
print("ZeroDivsionError occured")
except (NameError):
print("NameError occured")'''
'''def func(a,b):
try:
c=(a+b)/(a-b)
except (ZeroDivisionError):
print("Result is 0")
else:
print(c)
func(3,2)
func(2,2)'''
#Raise statement
#force a specific exception to occur.
# try:
# raise NameError("Hi there") #raise
# except NameError:
# print("An exception")
# raise
| true
|
9c511a9a74f9eccbed868ed190d3f58392157bed
|
asouzajr/algoritmosLogicaProgramacao
|
/lingProgPython/programasPython/testesCondicionais.py
| 479
| 4.375
| 4
|
x = -2
y = -3
if x == y:
print("números iguais")
elif x < y:
print ("x menor que y")
elif y > x:
print("y maior que x")
else:
print ("algo deu errado")
if x > y:
if x > 0:
print("x é maior que y e é positivo")
else:
print ("x é maior que y e é negativo")
else:
print ("y é menor que x")
if x == y:
print("x é igual que y")
elif x > y:
print("x é maior que y")
elif x > 0:
print ("x não é maior que y e é positivo")
else:
print ("y é maior que x")
| false
|
8c4d57da1267b058b76250618f25893a4114949f
|
jonesy212/Sorting
|
/src/iterative_sorting/iterative_sorting.py
| 1,277
| 4.15625
| 4
|
# TO-DO: Complete the selection_sort() function below
def selection_sort(arr):
def selection_sort(arr):
for i in range(0, len(arr)-1):
cur__index = i
smallest_index = cur_index
#find the next smallest element q
for x in range(cur_index, len(arr)):
if arr[x] < arr[smallest_index]:
#found new smallest thing!
smalles_index = x
# loop through everything but the last element
return arr
# Always pick first element as pivot.
# Always pick last element as pivot (implemented below)
# Pick a random element as pivot.
# Pick median as pivot.
# *compare first and last number
# *if second number is bigger than the
# one to the left, swap
# # TO-DO: implement the Bubble Sort function below
def bubble_sort(arr):
swap = True
while swap:
swap = False
for i range(0, len(arr)-1):
current_index = i
next_index = i + 1
if arr[i] > arr[next_index]:
arr[i], arr[next_index] = arr[next_index], arr[i]
swap = True
return arr
# print(arr.sort())
# # STRETCH: implement the Count Sort function below
# def count_sort( arr, maximum=-1 ):
# return arr
| true
|
be344fd136945a81eb038d99bbda7372fdba3c0b
|
anihakobyan98/group-2
|
/Exceptions/task4.py
| 274
| 4.5
| 4
|
''' Number that type is integer and it can be divided to 3 '''
try:
a = int(input("Enter a number: "))
except ValueError:
print("Entered value must be an integer type")
else:
if a % 3 != 0:
raise TypeError("Number must be divisible to 3")
else:
print("Excellent")
| true
|
b1119e6cb30d4b4a20dcc6a0f7065150fc080b32
|
ayushthesmarty/Simple-python-car-game
|
/main.py
| 1,336
| 4.25
| 4
|
help_ = """
The are the commands of the game
help - show the commands
start - start the car
stop - stop the car
exit - exit the game
"""
print(help_)
running = True
car_run = False
while running:
command = input("Your command: ").lower()
if command == "help":
print(help_)
elif command == "start":
if not car_run:
car_run = True
print("Starting car!!\n")
print("The car is started!!")
else:
print("Starting car!!\n")
print("The car is already started!!")
elif command == "stop":
if car_run:
car_run = False
print("Stopping car!!\n")
print("The car is stopped!!")
else:
print("Stopping car!!\n")
print("The car is already stopped!!")
elif command == "exit":
exit_run = True
while exit_run:
input_ = input("Do you want to exit the game? (y or n) ").lower()
if input_ == "y":
print("Bye, Bye!")
exit()
elif input_ == "n":
break
else:
print("I don't recognize this command!!!")
else:
print("I don't recognize this command!!!")
| true
|
1ff020d024ad2dd9d2e238125f6ec7402acac880
|
chanzer/leetcode
|
/575_distributeCandies.py
| 1,205
| 4.625
| 5
|
"""
Distribute Candies
题目描述:
Given an integer array with even length, where
different numbers in this array represent different kinds of
candies. Each number means one candy of the corresponding
kind. You need to distribute these candies equally in number
to brother and sister. Return the maximum number of kinds of
candies the sister could gain.
Example 1:
Input: candies = [1,1,2,2,3,3]
Output: 3
Explanation:
There are three different kinds of candies (1, 2 and 3),
and two candies for each kind.Optimal distribution: The
sister has candies [1,2,3] and the brother has candies
[1,2,3], too. The sister has three different kinds of candies.
Example 2:
Input: candies = [1,1,2,3]
Output: 2
Explanation:
For example, the sister has candies [2,3] and the brother
has candies [1,1]. The sister has two different kinds of
candies, the brother has only one kind of candies.
Note:
1.The length of the given array is in range [2, 10,000],
and will be even.
2.The number in given array is in range
[-100,000, 100,000].
"""
class Solution:
def distributeCandies(self,candies):
"""
:type candies:List[int]
:rtype : int
"""
return min(len(candies)//2,len(set(candies)))
| true
|
25b3275a82d546d5f17f9232ec4c363e2e85c402
|
chanzer/leetcode
|
/867_transpose.py
| 862
| 4.21875
| 4
|
"""
Transpose Matrix
题目描述:
Given a matrix A, return the transpose of A.
The transpose of a matrix is the matrix flipped over
it's main diagonal, switching the row and column indices of
the matrix.
Example 1:
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: [[1,4,7],[2,5,8],[3,6,9]]
Example 2:
Input: [[1,2,3],[4,5,6]]
Output: [[1,4],[2,5],[3,6]]
Note:
1. 1 <= A.length <= 1000
2. 1 <= A[0].length <= 1000
"""
# 方法一:
class Solution:
def transpose(self, A):
return list(zip(*A))
# 方法二:
class Solution:
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
R,C = len(A),len(A[0])
ans = [[None]*R for _ in range(C)]
for r,row in enumerate(A):
for c,val in enumerate(row):
ans[c][r] = val
return ans
| true
|
6d801ce1b4951d9b4b7fa1c7e39aa2d1dd69a1b4
|
chanzer/leetcode
|
/697_findShortestSubArray.py
| 1,269
| 4.21875
| 4
|
"""
Degree of an Array
题目描述:
Given a non-empty array of non-negative integers
nums, the degree of this array is defined as the maximum
frequency of any one of its elements.
Your task is to find the smallest possible length of a
(contiguous) subarray of nums, that has the same degree
as nums.
Example 1:
Input: [1, 2, 2, 3, 1]
Output: 2
Explanation:The input array has a degree of 2 because
both elements 1 and 2 appear twice.Of the subarrays that
have the same degree:[1, 2, 2, 3, 1], [1, 2, 2, 3],
[2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.
Example 2:
Input: [1,2,2,3,1,4,2]
Output: 6
Note:
nums.length will be between 1 and 50,000.
nums[i] will be an integer between 0 and 49,999.
"""
from collections import Counter
class Solution:
def findShortestSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
c = Counter(nums)
deg = max(c.values())
if deg == 1: return 1
candidates = [k for k in c if c[k] == deg]
n = len(nums)
minlen = 50000
for i in candidates:
l = nums.index(i)
r = n - nums[::-1].index(i) - 1
minlen = min(minlen, r - l + 1)
return minlen
| true
|
4eef3b2411dd7eaa18cd6ceb5224098379d4672c
|
chanzer/leetcode
|
/628_maximumProduct.py
| 669
| 4.5
| 4
|
"""
Maximum Product of Three Numbers
题目描述:
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
Note:
1.The length of the given array will be in range
[3,104] and all elements are in the range [-1000, 1000].
2.Multiplication of any three numbers in the input
won't exceed the range of 32-bit signed integer.
"""
class Solution:
def maximumProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
return max(nums[0]*nums[1]*nums[-1],nums[-1]*nums[-2]*nums[-3])
| true
|
0f8c88f4a60a4c9f26553c9903e7d6d111ca8ed1
|
chanzer/leetcode
|
/453_minMoves.py
| 842
| 4.15625
| 4
|
"""
Minimum Moves to Equal Array Elements
题目描述:
Given a non-empty integer array of size n, find the
minimum number of moves required to make all array elements
equal, where a move is incrementing n - 1 elements by 1.
Example:
Input:[1,2,3]
Output:3
Explanation:Only three moves are needed (remember each
move increments two elements):
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
"""
# 方法一
class Solution:
def minMoves(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum(nums) - len(nums) * min(nums)
# 方法二
class Solution(object):
def minMoves(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
minimum = min(nums)
res = 0
for n in nums:
res += n - minimum
return res
| true
|
6947cc6a019c3b232b432788a8ce9ed5729e8551
|
MichelGeorgesNajarian/randomscripts
|
/Python/recursive_rename.py
| 907
| 4.28125
| 4
|
# Python3 code to rename multiple
# files in a directory or folder
#give root directory as argument when executing program and all the file in root directory and subsequent folders will be renamed
#renaming parameter are to remove any '[xyz123]', '(xyz123)' and to replace '_' by ' '
# importing os module
import os
import re
import sys
# Function to rename multiple files
def main():
pathToDir = str(sys.argv[1])
for root, dirs, files in os.walk(pathToDir):
for filename in files:
newFile = re.sub(r'(\s)*\[(.*?)\](\s)*|(\s)*\((.*?)\)(\s)*', '', filename) #regex to match all patterns that are of the form striong inside square or normal brackets
newFile = re.sub(r'_', ' ', newFile) #replace _ by whitespace
if (newFile != filename):
os.rename(root + "\\" + filename, root + "\\" + newFile)
# Driver Code
if __name__ == '__main__':
# Calling main() function
main()
| true
|
0d1564abb38b41d58ce025ee1353e90e62d084be
|
wrgsRay/playground
|
/amz_label.py
| 2,181
| 4.21875
| 4
|
"""
Python 3.6
@Author: wrgsRay
"""
import time
class Shipment:
def __init__(self, last_page, total_pallet, pallet_list=[], current_pallet):
self.last_page = last_page
self.total_pallet = total_pallet
self.pallet_list = pallet_list
self.current_pallet = current_pallet
def get_pallet_input(self):
while True:
pallet_input = input(f'Please enter carton number for Pallet {self.current_pallet}, enter nothing to stop ')
if pallet_input == '':
break
else:
pallet_input = int(pallet_input)
self.pallet_list.append(pallet_input)
print(f'Pallet {self.current_pallet}: {pallet_input}')
self.current_pallet += 1
def amz():
shipment = Shipment(1, 10, [], 1)
shipment.get_pallet_input()
def main():
last_page = int(input('Please enter the last page number(eg. 1064) '))
pallet_total = int(input('Please enter the total number of pallets(eg. 24) '))
pallet_list = list()
current_pallet = 1
while True:
pallet_input = input(f'Please enter carton number for Pallet {current_pallet}, enter nothing to stop ')
if pallet_input == '':
break
else:
pallet_input = int(pallet_input)
pallet_list.append(pallet_input)
print(f'Pallet {current_pallet}: {pallet_input}')
current_pallet += 1
if len(pallet_list) != pallet_total:
print(f'Pallet Total mismatch: expected {pallet_total} pallets got {len(pallet_list)} pallets')
elif sum(pallet_list) != last_page:
print(f'Carton Total Mismatch expected {last_page} cartons got {sum(pallet_list)} cartons')
# pallet_list = [49, 49, 36, 36, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 48, 44, 30, 15, 35, 48, 56, 30]
else:
current = 1
print(len(pallet_list))
print(sum(pallet_list))
for pallet in pallet_list:
print(f'{current}-{current + pallet - 1}')
current += pallet
print('Window is closing in 30 seconds...')
time.sleep(30)
if __name__ == '__main__':
amz()
| true
|
d603602255347b138dfb7b6685222b2b03501986
|
SaraKenig/codewars-solutions
|
/python/7kyu/Unique string characters.py
| 598
| 4.34375
| 4
|
# In this Kata, you will be given two strings a and b and your task will be to return the characters that are not common in the two strings.
# For example:
# solve("xyab","xzca") = "ybzc"
# --The first string has 'yb' which is not in the second string.
# --The second string has 'zc' which is not in the first string.
# Notice also that you return the characters from the first string concatenated with those from the second string.
# More examples in the tests cases.
# Good luck!
def solve(a,b):
return f'{"".join([r for r in a if r not in b])}{"".join([r for r in b if r not in a])}'
| true
|
acbf417955c0e14618b09ab10a0952fc6e63d79a
|
SaraKenig/codewars-solutions
|
/python/7kyu/sort array by last character.py
| 539
| 4.34375
| 4
|
# Sort array by last character
# Write a function sortMe or sort_me to sort a given array or list by last character of elements.
# Element can be an integer or a string.
# Example:
# sortMe(['acvd','bcc']) => ['bcc','acvd']
# The last characters of the strings are d and c. As c comes before d, sorting by last character will give ['bcc', 'acvd'].
# If two elements don't differ in the last character, then they should be sorted by the order they come in the array.
def sort_me(arr):
return sorted(arr, key=lambda x: str(x)[-1])
| true
|
32b1fdce0553b30a13993a7f2d487af7187b4500
|
FrancoisCzarny/HackerRank
|
/Python/Python_weirdFunction.py
| 565
| 4.46875
| 4
|
#!/usr/bin/env python
#-*- coding : utf-8 -*-
"""
Given an integer, n, perform the following conditional actions:
If n is odd, print Weird
If n is even and in the inclusive range of 2 to 5, print Not Weird
If n is even and in the inclusive range of 6 to 20, print Weird
If n is even and greater than 20, print Not Weird
"""
def weird(n):
t = n%2
if (t != 0) | (t==0) & (6<=n<=20):
s = "Weird"
elif t==0 & (2<=n<=5) | t==0 & (n>20):
s = "Not Weird"
return s
if __name__ == '__main__':
n = int(raw_input())
print weird(n)
| false
|
b7f7a1ec2ec63e46c1162b3e5e6967048f222569
|
vidyakov/geek
|
/2lesson/2_task.py
| 572
| 4.28125
| 4
|
# Посчитать четные и нечетные цифры введенного натурального числа.
# Например, если введено число 34560, в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
a = input('Введите натуральное число: ')
even = 0
odd = 0
for i in a:
if int(i) % 2 == 0 or i == '0':
even += 1
else:
odd += 1
print(f'Количество четных чисел: {even}')
print(f'Количество нечетных чисел: {odd}')
| false
|
77637b2eaef358ad308de773a915caddab871f12
|
begogineni/cs-guided-project-python-basics
|
/src/demonstration_03.py
| 566
| 4.40625
| 4
|
"""
Challenge #3:
Create a function that takes a string and returns it as an integer.
Examples:
- string_int("6") ➞ 6
- string_int("1000") ➞ 1000
- string_int("12") ➞ 12
"""
import re
def string_int(txt):
'''
input: str
output: int
'''
# Your code here
#what to do if there is a letter in the given string - remove all but numbers - check other assignments
# only_nums = re.sub('[^a-zA-Z ]', '', txt) #replace
# return int(only_nums)
return int(txt)
# check
print(string_int("65"))
# print(string_int("65 tigers"))
| true
|
2bea7f84ca43f1bfde89b3590f7212edf469a5d9
|
tarushsinha/WireframePrograms
|
/3fizz5buzz.py
| 452
| 4.125
| 4
|
## program that returns multiples of 3 as fizz, multiples of 5 as buzz, and multiples of both as fizzbuzz within a range
def fizzBuzz(rng):
retList = []
for i in range(rng):
if i % 3 == 0 and i % 5 == 0:
retList.append("fizzbuzz")
elif i%3 == 0:
retList.append("fizz")
elif i%5 == 0:
retList.append("buzz")
else:
retList.append(i)
print(retList)
fizzBuzz(100)
| true
|
52f36317552e8eb0e533b61c0f4947b653e7d52d
|
saikirandulla/HW06
|
/HW06_ex09_04.py
| 1,337
| 4.40625
| 4
|
#!/usr/bin/env python
# HW06_ex09_04.py
# (1)
# Write a function named uses_only that takes a word and a string of letters,
# and that returns True if the word contains only letters in the list.
# - write uses_only
# (2)
# Can you make a sentence using only the letters acefhlo? Other than "Hoe
# alfalfa?"
# - write function to assist you
# - type favorite sentence(s) here:
# 1: Hello half leech face
# 2: cool cafe coffee
# 3: coach fell off hellhole
##############################################################################
# Imports
# Body
def uses_only(word, s):
flag = True
for letter in word:
if letter not in s:
return False
return True
# if word.find(s[i]) == -1:
# flag = False
# else:
# flag = True
# return True
# return False
def word_maker():
fin = open('words.txt')
words_file_list = []
for line in fin:
words_file_list.append(line.strip('\r\n'))
return words_file_list
def sentence_maker(words_file_list):
count = 0
for letter in words_file_list:
if uses_only(letter, 'acefhlo'):
count +=1
print letter
print count
##############################################################################
def main():
words_file_list = word_maker()
sentence_maker(words_file_list)
# print uses_only("Hello", "abcd")
if __name__ == '__main__':
main()
| true
|
31f3c7d5da418e3abbf4c44fced349ab7aac1fab
|
yotroz/white-blue-belt-modules
|
/17-exceptions/blue_belt.py
| 488
| 4.53125
| 5
|
#%%
#Create a function that reads through a file
#and prints all the lines in uppercase.
#
#
#
#be sure to control exceptions that may occur here,
#such as the file not existing
def print_file_uppercase(filename):
try:
file = open(filename)
for line in file:
print(line.upper().strip())
except Exception:
print("file doesnt exist")
print_file_uppercase("data.txt")
print_file_uppercase("other_file.txt")
| true
|
147ebca997008e894bd6b5f6f74d63c658643188
|
Umesh8Joshi/My-Python-Programs
|
/numbers/PItoNth.py
| 274
| 4.21875
| 4
|
'''
Enter a number to find the value of PI till that digit
'''
def nthPI(num):
'''
function to return nth digit value of PU
:param num: number provided by user
:return : PI value till that digit
'''
num = input('Enter the digit')
return "%.{num}f"(22/7).format(num)
| true
|
d05ea438611f9a1af279a4935c1c966047ae41d5
|
Chener-Zhang/HighSchoolProject
|
/Assembly/hw6pr5.py
| 2,447
| 4.15625
| 4
|
# hw6 problem 5
#
# date:
#
# Hmmm...
#
#
# For cs5gold, this is the Ex. Cr. recursive "Power" (Problem4)
# and recursive Fibonacci" (Problem5) program
# Here is the starter for gold's Problem4 (recursive power):
# This is the recursive factorial from class, to be changed to a recursive _power_ program:
Problem4 = """
00 read r1 # read input and put into r1.
01 setn r15 42 # 42 is the beginning of the stack, put that address in r15.
02 call r14 5 # begin function at line 5, but first put next address (03) into r14.
03 jumpn 21 # Let's defer final output to line 21...
04 nop # no operation -- but useful for squeezing in an extra input...
05 jnez r1 8 # BEGINNING OF FACTORIAL FUNCTION! Check if r1 is non-zero. If it is go to line 8 and do the real recursion!
06 setn r13 1 # otherwise, we are at the base case: load 1 into r13 and...
07 jumpr r14 # ... return to where we were called from (address is in r14)
08 storer r1 r15 # place r1 onto the stack
09 addn r15 1 # increment stack pointer
10 storer r14 r15 # place r14 onto the stack
11 addn r15 1 # increment stack pointer
12 addn r1 -1 # change r1 to r1-1 in preparation for recursive call
13 call r14 5 # recursive call to factorial, which begins at line 5 - but first store next memory address in r14
14 addn r15 -1 # we're back from the recursive call! Restore goods off the stack.
15 loadr r14 r15 # restoring r14 (return address) from stack
16 addn r15 -1 # decrement stack pointer
17 loadr r1 r15 # restoring r1 from stack
18 mul r13 r13 r1 # now for the multiplication
19 jumpr r14 # and return!
20 nop # nothing
21 write r13 # write the final output
22 halt
"""
#
# for the other extra credit, here's a placeholder... (named Problem5)
#
# This is a placeholder by that name whose code you'll replace:
Problem5 = """
00 read r1 # get # from user to r1
01 read r2 # ditto, for r2
02 mul r3 r1 r2 # r3 = r1 * r2
03 write r3 # print what's in r3
04 halt # stop.
"""
# This function runs the Hmmm program specified
#
def run():
""" runs a Hmmm program... """
import hmmmAssembler ; reload(hmmmAssembler) # import helpers
hmmmAssembler.main(Problem4) # this runs the code!
# change this name ^^^^^^^^ to run a different function!
| true
|
f8c33c98dc671fd597a5b40848d72e42f504fbc5
|
tsakallioglu/Random-Python-Challenges
|
/Weak_numbers.py
| 1,324
| 4.25
| 4
|
#We define the weakness of number x as the number of positive integers smaller than x that have more divisors than x.
#It follows that the weaker the number, the greater overall weakness it has. For the given integer n, you need to answer two questions:
#what is the weakness of the weakest numbers in the range [1, n]?
#how many numbers in the range [1, n] have this weakness?
#Return the answer as an array of two elements, where the first element is the answer to the first question,
#and the second element is the answer to the second question.
#Function that calculates the number of divisors for a given number
def num_of_div(n):
div=[]
result=1
if n!=1:
while (n!=1):
for i in range(2,n+1):
if n%i==0:
div.append(i)
n /= i
break
for x in set(div):
result *= div.count(x)+1
return result
#Main Function
def weakNumbers(n):
divisors=[]
weaknesses=[]
for i in range(1,n+1):
curr_div=num_of_div(i)
divisors.append(curr_div)
weakness=0
for j in range (1,i):
if divisors[j]>curr_div:
weakness += 1
weaknesses.append(weakness)
return [max(weaknesses),weaknesses.count(max(weaknesses))]
| true
|
3edca50ac0faee8c95d27f19232bd03202ab814c
|
shenlinli3/python_learn
|
/second_stage/day_11/demo_05_面向对象-多态和鸭子类型.py
| 1,449
| 4.40625
| 4
|
# -*- coding: utf-8 -*-
"""
@Time : 2021/5/22 16:08
@Author : zero
"""
# 多态:在面向对象中,一个类的实例可以是多种形态(向上转型)
# 鸭子类型:在python中,只要一个对象长的像鸭子,走路和鸭子差不多,我就认为它是一只鸭子
class Person: # 会默认继承自object类
def eat(self):
print("eat eat eat")
class Student(Person):
pass
class LowLevelStudent(Student):
pass
p1 = Person()
s1 = Student()
lls1 = LowLevelStudent()
# # isinstance 判断指定对象是否是指定类的实例
# print(isinstance(p1, Person)) # True
# print(isinstance(p1, Student)) # False
# print(isinstance(s1, Student)) # True
# print(isinstance(s1, Person)) # True
# print(isinstance(lls1, LowLevelStudent)) # True
# print(isinstance(lls1, Student)) # True
# print(isinstance(lls1, Person)) # True
print(type(lls1) == Student)
print(type(lls1) == LowLevelStudent)
# 通过上面的验证,我们可知:在面向对象中,一个类的实例可以是多种形态(向上转型)
# p1.eat()
# s1.eat()
# lls1.eat()
class Pig:
def eat(self):
print("eat eat eat")
def double_eat(obj: Person):
obj.eat()
obj.eat()
# double_eat(p1)
# double_eat(s1)
# double_eat(lls1)
pig1 = Pig()
double_eat(pig1)
# double_eat(Pig()) # 这里Pig的实例对象没有名字,一般我们称之为 匿名对象
| false
|
24ac42452a2c8d4a84d52447187451ea079d4b1d
|
shenlinli3/python_learn
|
/second_stage/day_03/demo_03_for循环.py
| 1,090
| 4.125
| 4
|
# -*- coding: utf-8 -*-
"""
@Time : 2021/5/12 16:06
@Author : zero
"""
# for循环
"""
for 变量名 in 可迭代对象:
print(变量名)
...
"""
# 遍历字符串
# str01 = "hello world!" # 12
# for i in str01:
# print(i)
# 遍历列表
# list01 = [1, 2, 3, 4, 5]
# for j in list01:
# print(j)
# 遍历元组
# tuple01 = (1, 2, 3, 4, 5)
# for x in tuple01:
# print(x)
# # 函数 range() 返回指定范围的生成器、懒序列
# # start, stop, step 左闭右开
# print(list(range(1, 11, 1)))
# print(list(range(1, 11, 2)))
# print(list(range(1, 11, 3)))
# # 如果只有一个参数,那么这个参数被认为是stop,start默认为0
# print(list(range(100))) # range(0, 100)
# 10000次循环
# for i in range(10000):
# print(i)
# 1~100求和
# sums = 0
# for i in range(1, 101):
# sums += i
# print(sums)
# for循环中的break、continue
for i in range(1, 101):
if i == 77:
break
print(i)
for i in range(1, 101):
if i == 77:
continue
print(i)
| false
|
7af6a875e8789ca9846521d0df9be2bd5eb2fa22
|
KhushiRana2003/Hacktoberfest2021-1
|
/Python/bubble_sort.py
| 319
| 4.21875
| 4
|
def bubbleSort(array):
for i in range(len(array)):
for j in range(len(array) - i - 1):
if array[j] > array[j + 1]:
swap(j, j + 1, array)
return array
def swap(i, j, array):
array[i], array[j] = array[j], array[i]
# Time Complexity: O(n^2)
# Space Complexity: O(1)
| false
|
71417cb49cb8704d54aa0f6f923e92bd37da5bd9
|
Niteshyadav0331/Zip-File-Extractor
|
/main.py
| 248
| 4.15625
| 4
|
from zipfile import ZipFile
file_name = input("Enter the name of file you want to file in .zip: ")
with ZipFile(file_name, 'r') as zip:
zip.printdir()
print('Extracting all the files...')
zip.extractall()
print("Done!")
| true
|
74d174d8878c2604daf720d755e6b156a6ec4881
|
netor27/codefights-solutions
|
/arcade/python/arcade-theCore/07_BookMarket/053_IsTandemRepeat.py
| 643
| 4.3125
| 4
|
def isTandemRepeat(inputString):
'''
Determine whether the given string can be obtained by one concatenation of some string to itself.
Example
For inputString = "tandemtandem", the output should be
isTandemRepeat(inputString) = true;
For inputString = "qqq", the output should be
isTandemRepeat(inputString) = false;
For inputString = "2w2ww", the output should be
isTandemRepeat(inputString) = false.
'''
middle = len(inputString) // 2
return inputString[:middle] == inputString[middle:]
print(isTandemRepeat("tandemtandem"))
print(isTandemRepeat("qqq"))
| true
|
e082ba713c0a0001a3c47dfb5b1e31719534600d
|
netor27/codefights-solutions
|
/arcade/python/arcade-theCore/07_BookMarket/054_IsCaseInsensitivePalindrome.py
| 339
| 4.1875
| 4
|
def isCaseInsensitivePalindrome(inputString):
'''
Given a string, check if it can become a palindrome through a case change of some (possibly, none) letters.
'''
lowerCase = inputString.lower()
return lowerCase == lowerCase[::-1]
print(isCaseInsensitivePalindrome("AaBaa"))
print(isCaseInsensitivePalindrome("aabbc"))
| true
|
c32f3501b32a4141e575abe2f57b9b8eb712b6e1
|
netor27/codefights-solutions
|
/arcade/python/arcade-intro/02_Edge of the Ocean/004_adjacentElementsProduct.py
| 522
| 4.15625
| 4
|
def adjacentElementsProduct(inputArray):
'''Given an array of integers, find the pair of adjacent elements
that has the largest product and return that product.
'''
n = len(inputArray)
if n < 2:
raise "inputArray must have at least 2 elements"
maxValue = inputArray[0] * inputArray[1]
for i in range(n - 1):
aux = inputArray[i] * inputArray[i + 1]
if aux > maxValue:
maxValue = aux
return maxValue
print(adjacentElementsProduct([3, 6, -2, -5, 7, 3]))
| true
|
62bbb74e43256f78b67050821d847af478d4669c
|
netor27/codefights-solutions
|
/arcade/python/arcade-intro/12_Land of Logic/052_longestWord.py
| 637
| 4.21875
| 4
|
def longestWord(text):
'''
Define a word as a sequence of consecutive English letters. Find the longest word from the given string.
'''
maxLen, maxStart, currStart, currLen = 0, 0, 0, 0
for i in range(len(text)):
if text[i].isalpha():
if currLen == 0:
currStart = i
currLen += 1
else:
if currLen > maxLen:
maxLen = currLen
maxStart = currStart
currLen = 0
if currLen > maxLen:
maxLen = currLen
maxStart = currStart
return text[maxStart:maxStart + maxLen]
| true
|
6cc342813a5cf0ab9e54f0ebb7bf05911b66e9b0
|
netor27/codefights-solutions
|
/arcade/python/arcade-theCore/05_ListForestEdge/040_IsSmooth.py
| 996
| 4.125
| 4
|
def isSmooth(arr):
'''
We define the middle of the array arr as follows:
if arr contains an odd number of elements, its middle is the element whose index number
is the same when counting from the beginning of the array and from its end;
if arr contains an even number of elements, its middle is the sum of the two elements
whose index numbers when counting from the beginning and from the end of the array differ by one.
An array is called smooth if its first and its last elements are equal to one another and to the middle.
Given an array arr, determine if it is smooth or not.
'''
length = len(arr)
if length % 2 == 1:
middle = arr[length//2]
else:
middle = arr[length//2] + arr[length//2 - 1]
return arr[0] == middle and arr[length-1] == middle
print(isSmooth([7, 2, 2, 5, 10, 7]))
print(isSmooth([-5, -5, 10]))
print(isSmooth([4, 2]))
print(isSmooth([45, 23, 12, 33, 12, 453, -234, -45]))
| true
|
df112813c067411853941f8455d31fed51a2c1fa
|
netor27/codefights-solutions
|
/arcade/python/arcade-theCore/01_IntroGates/005_MaxMultiple.py
| 349
| 4.21875
| 4
|
def maxMultiple(divisor, bound):
'''
Given a divisor and a bound, find the largest integer N such that:
N is divisible by divisor.
N is less than or equal to bound.
N is greater than 0.
It is guaranteed that such a number exists.
'''
num = bound - (bound % divisor)
return max(0, num)
print(maxMultiple(3, 10))
| true
|
4360bfb5399e8fc6a7d7453b8582063d04704139
|
netor27/codefights-solutions
|
/arcade/python/arcade-intro/02_Edge of the Ocean/008_matrixElementsSum.py
| 1,100
| 4.1875
| 4
|
def matrixElementsSum(matrix):
'''
After they became famous, the CodeBots all decided to move to a new building
and live together. The building is represented by a rectangular matrix of rooms.
Each cell in the matrix contains an integer that represents the price of the room.
Some rooms are free (their cost is 0), but that's probably because they are haunted,
so all the bots are afraid of them. That is why any room that is free or is located
anywhere below a free room in the same column is not considered suitable for the bots
to live in.
Help the bots calculate the total price of all the rooms that are suitable for them.
'''
maxX = len(matrix)
maxY = len(matrix[0])
total = 0
# Sum every colum until we found a 0, then move to the next column
for y in range(maxY):
for x in range(maxX):
if matrix[x][y] == 0:
break
total += matrix[x][y]
return total
print(matrixElementsSum([[0, 1, 1, 2],
[0, 5, 0, 0],
[2, 0, 3, 3]]))
| true
|
9ab6e5d04bdd7d278e9f6c1188160ff8ae892e14
|
netor27/codefights-solutions
|
/arcade/python/arcade-theCore/04_LoopTunnel/029_AdditionWithoutCarrying.py
| 763
| 4.375
| 4
|
def additionWithoutCarrying(param1, param2):
'''
A little boy is studying arithmetics.
He has just learned how to add two integers, written one below another, column by column.
But he always forgets about the important part - carrying.
Given two integers, find the result which the little boy will get.
'''
result = 0
currentDigit = 0
while(param1 != 0 or param2 != 0):
result = result + (param1 + param2) % 10 * 10 ** currentDigit
currentDigit += 1
param1 = param1 // 10
param2 = param2 // 10
return result
print(additionWithoutCarrying(456, 1734))
print(additionWithoutCarrying(99999, 0))
print(additionWithoutCarrying(999, 999))
print(additionWithoutCarrying(0, 0))
| true
|
cb03a35c7e74fc7ca73545dadc59c16bce5c6f7a
|
netor27/codefights-solutions
|
/arcade/python/arcade-theCore/08_MirrorLake/059_StringsConstruction.py
| 634
| 4.1875
| 4
|
def stringsConstruction(a, b):
'''
How many strings equal to a can be constructed using letters from the string b? Each letter can be used only once and in one string only.
Example
For a = "abc" and b = "abccba", the output should be
stringsConstruction(a, b) = 2.
We can construct 2 strings a with letters from b.
'''
continueSearching = True
r = 0
while continueSearching:
for i in a:
j = 0
while j < len(b) and i != b[j]:
j+=1
if j >= len(b):
return r
b = b[:j] + b[j+1:]
r += 1
return r
| true
|
5cf96612d1c9bdb7f2fd851e8a00b424c2da2b6f
|
mixelpixel/CS1-Code-Challenges
|
/cc69strings/strings.py
| 2,486
| 4.28125
| 4
|
# cc69 strings
# https://repl.it/student/submissions/1855286
# https://developers.google.com/edu/python/
# http://pythoncentral.io/cutting-and-slicing-strings-in-python/
'''
For this challenge, you'll be writing some basic string functions.
Simply follow along with each exercise's prompt.
You may find the following article helpful with regards to
how to perform string slicing in Python:
http://pythoncentral.io/cutting-and-slicing-strings-in-python/
'''
# 1. Donuts
# Given an int count of a number of donuts, return a string
# of the form 'Number of donuts: <count>', where <count> is the number
# passed in. However, if the count is 10 or more, then use the word 'many'
# instead of the actual count.
# So donuts(5) returns 'Number of donuts: 5'
# and donuts(23) returns 'Number of donuts: many'
def donuts(count):
# Your code here
if count < 10:
reply = str(count)
else:
reply = 'many'
# print("Number of donuts: ", count if count < 10 else 'many')
return "Number of donuts: " + reply
print(donuts(5))
print(donuts(23))
print(donuts(4))
# 2. both_ends
# Given a string s, return a string made of the first 2
# and the last 2 chars of the original string,
# so 'spring' yields 'spng'. However, if the string length
# is less than 2, return instead the empty string.
def both_ends(s):
# Your code here
if len(s) < 2:
return ''
return s[0:2] + s[-2:]
print(both_ends("Scooby Snacks"))
print(both_ends("Jesh doesn't share his candy"))
# 3. fix_start
# Given a string s, return a string
# where all occurences of its first char have
# been changed to '*', except do not change
# the first char itself.
# e.g. 'babble' yields 'ba**le'
# Assume that the string is length 1 or more.
# Hint: s.replace(stra, strb) returns a version of string s
# where all instances of stra have been replaced by strb.
def fix_start(s):
letter = s[0]
s = s.replace(letter, '*')
starring = letter + s[1:]
return starring
print(fix_start("well, why weren't we welcome?"))
print(fix_start("Scooby Snacks Sound Simply Scrumptuous!"))
# 4. mix_up
# Given strings a and b, return a single string with a and b separated
# by a space '<a> <b>', except swap the first 2 chars of each string.
# e.g.
# 'mix', pod' -> 'pox mid'
# 'dog', 'dinner' -> 'dig donner'
# Assume a and b are length 2 or more.
def mix_up(a, b):
new_a = b[:2] + a[2:]
new_b = a[:2] + b[2:]
return new_a + ' ' + new_b
print(mix_up("What", "the???"))
print(mix_up("Patrick", "Kennedy"))
| true
|
c2bad1043e0499dfcd0fed9d617d9200ebede882
|
lijerryjr/MONIAC
|
/textFunctions.py
| 1,637
| 4.21875
| 4
|
###################
# rightJustifyText
# This contains the text justifier code from HW3
###################
import string
def replaceWhiteSpace(text):
#replace white space in text with normal spaces
#inspired by recitation 3 video
inWhiteSpace=False
result=''
for c in text:
if not inWhiteSpace and c.isspace():
inWhiteSpace=True
elif inWhiteSpace and not c.isspace():
inWhiteSpace=False
result+=' '+c
elif not inWhiteSpace and not c.isspace():
result+=c
return result
def breakLines(text, width):
#break into lines of required width
newText=''
lineLen=0
for word in text.split(' '):
if lineLen+len(word) > width:
newText+='\n'+word+' '
lineLen=len(word)+1
else:
newText+=word+' '
lineLen+=len(word)+1
return newText
def removeTrailingSpaces(text):
#remove trailing white space in each line
newText=''
for line in text.splitlines():
newText+=line.strip()+'\n'
return newText
def createNewText(text, width):
#return clean lines of required width with above functions
text=text.strip()
text=replaceWhiteSpace(text)
text=breakLines(text, width)
text=removeTrailingSpaces(text)
return text
def rightJustifyText(text, width):
#return right-justified text
text=createNewText(text, width)
newText=''
#add white space before text to align right
for line in text.splitlines():
newText+=' '*(width-len(line))+line+'\n'
#remove '\n' at end
newText=newText[:-1]
return newText
| true
|
4c92c735e5966ba9de1cd9c0538c82040271139a
|
cloudsecuritylabs/pythonProject_1
|
/ch_01/19.comparisonoperators..py
| 812
| 4.125
| 4
|
'''
Let's learn about comparison operators
'''
age = 0
if age <= 100:
print("You are too young")
elif age >100:
print("You are a strong kid")
else:
print("We need to talk")
if True:
print("hey there")
# this does not print anything
if False:
print("Oh No!")
string = "he he"
if string:
print("dont smile")
if not string:
print("can't smile")
mylist = []
if mylist:
print("dont smile")
if not mylist:
print("can't smile")
myDict = {}
if myDict:
print("dont smile")
if not myDict:
print("can't smile")
list1 = [1,2,3]
list2 = [4,5,6]
if list1 == list2:
print("hello identical")
cat = "tom"
dog = 'jerry'
if cat == 'tom':
if dog == 'jerry':
print("Hi cartoon")
if cat == 'tom' and dog == 'jerry':
print("Hi cartoon")
# truth table
| true
|
c9e05c41ee43bd41fc57f5da76649fad20c261be
|
KingTom1/StudyBySelf
|
/视频学习练习/视频第二周学习_数据类型/列表类型.py
| 1,426
| 4.21875
| 4
|
# 列表(list)是有序的元素集合
# 列表元素可以通过索引访问单个元素
# 列表与元组不同的是: 列表的大小没有限制,可以随时修改
'''
<seq> + <seq> 连接两个序列
<seq> * <整数类型> 对序列进行整数次重复
<seq> [<整数类型>] 索引序列中的元素
Len(<seq>) 序列中元素个数
<seq>[<整数类型>:<整数类型>] 取序列的一个子序列
For<var> in <seq>: 对序列进行循环列举
<expr> in <seq> expr选项是否在序列中
'''
'''列表的操作'''
vlist = [0,1,2,3,4]
print(vlist*2) # 扩展列表 输出[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
print(len(vlist[2:])) # 取从2开始获取[2,3,4] 输出该列表长度 为 3
for i in vlist[:3]:
print(i)
# 遍历列表 输出
# 0
# 1
# 2
a = 2 in vlist
print(a)
# 判断值是否在列表内 输出true
'''方法:
<list>.append(x) 将元素x增加到列表的最后
<list>.sort() 将列表元素排序
<list>.reverse() 将列表元素反转
<list>.index() 返回第一次出现元素x的索引值
<list>.insert(i,x) 在i处插入新元素x
<list>.pop(i) 取出列表中位置为i的元素,并删除它
<list>.count(x) 返回元素x在列表中的数量
<list>.remove(x) 删除列表中第一个出现的元素x'''
list = "python is an excellent language".split()
print(list)
| false
|
75775de1bd44da7021fa2bcc7e2d9ebb9124e2e8
|
ahmad-atmeh/my_project
|
/CA07/Problem 3/triangle.py
| 2,036
| 4.1875
| 4
|
# Class Triangle
class Triangle():
# TODO: Implement __init__ for this class use a,b,c and for the length of the sides
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
def __str__(self):
tri = """
*
***
*****
******
********
"""
value = f"the length os the side area {self.a},{self.b},{self.c}"
sentens = f"the area is {self.find_area()} and the perimeter is {self.find_perimeter()}"
return sentens + tri + value
# TODO: Implement find_area() for this class
def find_area(self):
s = self.find_perimeter()
# s(s – a)(s – b)(s – c)
area = (s*(s-self.a)*(s-self.b)*(s-self.c)) ** 0.5
return(area)
# TODO: Implement find_perimeter() for this class
def find_perimeter(self):
return (self.a + self.b + self.c ) / 2
# TODO: Implement a print_triangle_type() method which prints
# the type of the triangle based on the length of the sides.
# Hint: You can use the Pythagorean Theorum to find the type of triangle.
# Hint: Read more https://www.geeksforgeeks.org/find-the-type-of-triangle-from-the-given-sides/
def print_triangle_type(self):
if self.a == self.b == self.c:
print("Equilateral Triangle")
elif self.a == self.b or self.a == self.c or self.b == self.c:
print("Isosceles Triangle")
else:
print("Scaline Triangle")
how_many = int (input = ("please enter how many "))
list_Triangle = []
print(f"Now I'll for the length of the {how_many} triangle.")
for i in range(how_many+1):
#tarnary operater
a , b , c =[ int(x) for x in input(f"please enter three length {i} like (1,2,3) ").split(',')]
print(a,b,c)
list_Triangle.append(Triangle(a,b,c))
for triangle in list_Triangle:
print(triangle)
triangle = Triangle(3,5,4)
print(triangle.find_area())
triangle.print_triangle_type()
| false
|
da2004b72fdf6dc722bd025c1c6580a9e9aaed8e
|
ahmad-atmeh/my_project
|
/CA10/3.py
| 592
| 4.34375
| 4
|
# 3.You are given a list of words. Write a function called find_frequencies(words) which returns a dictionary of the words along with their frequency.
# Input: find_frequencies(['cat', 'bat', 'cat'])
# Return: {'cat': 2, 'bat': 1}
# Creating an empty dictionary
def find_frequencies(word):
freq ={}
for item in word:
if (item in freq):
freq[item] += 1
else:
freq[item] = 1
for key, value in freq.items():
print ("% s : % s"%(key, value))
# Driver function
word =['cat', 'bat', 'cat']
find_frequencies(word)
| true
|
36cda705b3d2e83c671be0582bbaf1cb45b7484d
|
ahmad-atmeh/my_project
|
/CA10/4.py
| 384
| 4.125
| 4
|
#4. You are given a list of integers. Write a function cumulative_sum(numbers) which calculates the cumulative sum of the list. The cumulative sum of a list numbers = [a, b, c, ...] can be defined as [a, a+b, a+b+c, ...].
# Input: numbers = [1, 2, 3, 4]
# Return: cumulative_sum_list = [1, 3, 6, 10]
lis = [1, 2, 3, 4]
from itertools import accumulate
print(list(accumulate(lis)))
| true
|
2e2eccaa840f0fbf6bde633cf87834b7b4b62173
|
ahmad-atmeh/my_project
|
/CA07/Problem 3/circle.py
| 2,002
| 4.46875
| 4
|
# Class Circle
import math
class Circle:
# TODO: Define an instance attribute for PI
def __init__(self, radius=1.0):
# TODO: Define an instance attribute for the radius
self.PI=3.14
self.radius=radius
# TODO: Define the string representation method and print
# r = {self.radius} c = {self.get_circumference()} a = {self.get_area()}
def __str__(self):
return f"r = {self.radius} c = {self.get_circumference()} a = {self.get_area()}"
# TODO: Define a get_area() method and return the area
def get_area(self):
return self.PI * (self.radius ** 2)
# TODO: Define a get_circumference() method and return the circumference
def get_circumference(self):
return 2 * self.PI * self.radius
# TODO: Define a set_color(color) method which sets the object attribute
def set_color(self, color):
self.color = color
# TODO: Define a get_color() method which returns the object attribute
def get_color(self):
return self.color
# Playground
# TODO: Create two circles one with radius 3, and one with the default radius
c1=Circle(3)
c2=Circle()
# TODO: Set the colors of your circles using the setter method
c1.set_color('black')
c2.set_color('green')
# TODO: Print the colors of your circles using the getter method
print(f" the color of circles 1 is {c1.get_color()}")
print(f" the color of circles 2 is {c2.get_color()}")
# TODO: Print your circles. How does this work?
print(c1)
print(c2)
# TODO: Print the radius and areas of your cricles
print(f" the area of cricles is {c1.get_area()} and the radius is {c1.radius} ")
print(f" the area of cricles is {c2.get_area()} and the radius is {c2.radius} ")
# TODO: Print the circumference of your circles using the getter method
print(f" the area of circumference 1 is {c1.get_circumference()}")
print(f" the area of circumference 2 is {c2.get_circumference()}")
| true
|
eb954e96ab4f8a34e70891920d417a2d93822b44
|
Dipin-Adhikari/Python-From-Scratch
|
/Dictionary/dictionary.py
| 1,398
| 4.125
| 4
|
"""Dictionaries is collection of keyvalue pairs.it is ordered and changeable but it doesnot allow duplicates values.."""
dictionary = {
"python": "Python is an interpreted high-level general-purpose programming language.",
"django": "Django is a Python-based free and open-source web framework that follows the model–template–views architectural pattern",
"flask": "Flask is a micro web framework written in Python.",
}
for key, value in dictionary.items(): # .items() return a list of key & values tuples
print(key, ":", value)
print(
dictionary.keys()
) # .keys() will return and prints keys only from dictionary !
# .update() will update values in dictionary
dictionary.update(
{
"django": "Django is a python based webframework that follow MVT architectural pattern"
}
)
# value of django is updated now !
""".get() returns values of specifed keys but if given value is not present in dictionary it will return none
whereas | dictionary.["keyname"] | throws an error if key is not present in dictionary"""
# print(dictionary["notindict"]) #it will throw an error because key is not present in dictionary
print(dictionary.get("django")) # prints value of given keys name (django)
print(dictionary.get("flask")) # prints value of given keys name (flask)
print(dictionary.get("python")) # prints value of given keys name (python)
| true
|
07604d6d6910ff0efa994121dd13f8784568634e
|
Aadit017/code_sharing
|
/type of triangle.py
| 411
| 4.28125
| 4
|
while True:
f= float(input("Enter first side: "))
s= float(input("Enter second side: "))
t= float(input("Enter third side: "))
if(f==s and f==t):
print("THE TRIANGLE IS AN EQUILATERAL TRIANGLE")
elif(f==s or f==t or s==t):
print("THE TRIANGLE IS AN ISOSCELES TRIANGLE")
else :
print("THE TRIANGLE IS AN SCALENE TRIANGLE")
print()
| false
|
b578a4a9a57922b7b6a13472a074c1ad883b0421
|
Aadit017/code_sharing
|
/month to days.py
| 756
| 4.1875
| 4
|
while True:
name=input("Enter name of month: ")
name=name.lower()
if(name=="january"):
print("days=31")
elif(name=="february"):
print("days=28")
elif(name=="march"):
print("days=31")
elif(name=="april"):
print("days=30")
elif(name=="may"):
print("days=31")
elif(name=="june"):
print("days=30")
elif(name=="july"):
print("days=31")
elif(name=="august"):
print("days=31")
elif(name=="september"):
print("days=30")
elif(name=="october"):
print("days=31")
elif(name=="november"):
print("days=30")
elif(name=="december"):
print("days=31")
else:
print("INVALID input")
| true
|
a6759a0d5fb17142435d89d87ccbd4ce64629a39
|
Abhilash11Addanki/cspp1-assignments
|
/Module 22 Week Exam/Check Sudoku/check_sudoku.py
| 1,741
| 4.28125
| 4
|
'''
Sudoku is a logic-based, combinatorial number-placement puzzle.
The objective is to fill a 9×9 grid with digits so that
each column, each row, and each of the nine 3×3 subgrids that compose the grid
contains all of the digits from 1 to 9.
Complete the check_sudoku function to check if the given grid
satisfies all the sudoku rules given in the statement above.
'''
def check_row(sudoku):
'''function for checking the rules for row'''
for row in sudoku:
if sum([int(ele) for ele in row]) != 45:#Sum of numbers in a row should be equal to 45
return False
return True
def check_column(sudoku):
'''function for checking the rules for column'''
for row, list_ in enumerate(sudoku):
sum_res = 0
for column in range(len(list_)):
sum_res += int(sudoku[column][row])
if sum_res != 45:
return False
return True
def check_sudoku(sudoku):
'''
Your solution goes here. You may add other helper functions as needed.
The function has to return True for a valid sudoku grid and false otherwise
'''
if check_row(sudoku) and check_column(sudoku):
return True
return False
def main():
'''
main function to read input sudoku from console
call check_sudoku function and print the result to console
'''
# initialize empty list
sudoku = []
# loop to read 9 lines of input from console
for row in range(9):
# read a line, split it on SPACE and append row to list
row = input().split(' ')
sudoku.append(row)
# call solution function and print result to console
print(check_sudoku(sudoku))
if __name__ == '__main__':
main()
| true
|
174ca0fb814021e716969bcd6b681fca98d5fbb9
|
Abhilash11Addanki/cspp1-assignments
|
/Practice Problems/Code Camp matrix/matrix_operations.py
| 2,042
| 4.125
| 4
|
'''Matrix operations.'''
def mult_matrix(m_1, m_2):
'''
check if the matrix1 columns = matrix2 rows
mult the matrices and return the result matrix
print an error message if the matrix shapes are not valid for mult
and return None
error message should be "Error: Matrix shapes invalid for mult"
'''
if len(m_1[0]) != len(m_2):
print("Error: Matrix shapes invalid for mult")
return None
res_m = [[sum([m_1[i][k]*m_2[k][j] for k in range(len(m_2))])
for j in range(len(m_2[0]))] for i in range(len(m_1))]
return res_m
def add_matrix(m_1, m_2):
'''
check if the matrix shapes are similar
add the matrices and return the result matrix
print an error message if the matrix shapes are not valid for addition
and return None
error message should be "Error: Matrix shapes invalid for addition"
'''
if len(m_1) == len(m_2):
add_mat = [[i+j for i, j in zip(m_1[i], m_2[i])] for i in range(len(m_1))]
return add_mat
print("Error: Matrix shapes invalid for addition")
return None
def read_matrix():
'''
read the matrix dimensions from input
create a list of lists and read the numbers into it
in case there are not enough numbers given in the input
print an error message and return None
error message should be "Error: Invalid input for the matrix"
'''
rows_mat, cols_mat = input().split(",")
read_mat = [input().split(" ") for i in range(int(rows_mat))]
mat = [[int(j) for j in i] for i in read_mat]
if any([True if len(i) != int(cols_mat) else False for i in mat]):
print("Error: Invalid input for the matrix")
return None
return mat
def main():
'''Main Function.'''
matrix_1 = read_matrix()
matrix_2 = read_matrix()
if matrix_1 and matrix_2 is not None:
print(add_matrix(matrix_1, matrix_2))
print(mult_matrix(matrix_1, matrix_2))
if __name__ == '__main__':
main()
| true
|
6485a65aaf4ecbcdbf3e86c954a792aeaa5c8948
|
BabaYaga007/Second-1
|
/stone_paper_scissor.py
| 1,198
| 4.1875
| 4
|
from random import randint
def print_menu():
print('1 for Stone')
print('2 for Paper')
print('3 for Scissor')
print('Enter your choice')
def print_score(a,b):
print('---Score---')
print('Player =',a)
print('Computer =',b)
choice = ['stone','paper','scissor']
a=0
b=0
while(True):
print_menu()
ch = int(input())
if ch==1 :
player = 'stone'
elif ch==2 :
player = 'paper'
elif ch==3 :
player = 'scissor'
else :
print('Invalid Choice. Try Again')
continue
rand = randint(0,2)
computer = choice[rand]
print('You chose',player)
print('Computer chose',computer)
if player=='stone' and computer=='paper':
b += 1
elif player=='stone' and computer=='scissor':
a += 1
elif player=='paper' and computer=='stone':
a += 1
elif player=='paper' and computer=='scissor':
b += 1
elif player=='scissor' and computer=='stone':
b += 1
elif player=='scissor' and computer=='paper':
a += 1
else:
print("It's a Tie!!!")
print_score(a,b)
if a==5 or b==5:
break
| true
|
238f30f035a54ede9b8a3cae148c074bbd806ec3
|
ralsouza/python_data_structures
|
/section7_arrays/searching_an_element.py
| 440
| 4.1875
| 4
|
from array import *
arr1 = array("i", [1,2,3,4,5,6])
def search_array(array, value):
for i in array: # --------------------------------------> O(n)
if i == value:# ------------------------------------> O(1)
return array.index(value) # --------------------> O(1)
return "The element does not exist in this array." # ---> O(1)
print(search_array(arr1,3))
print(search_array(arr1,6))
print(search_array(arr1,7))
| true
|
3f9c04833a87be9b112078e462c08aa7369dc9bc
|
ralsouza/python_data_structures
|
/section8_lists/chal6_pairs.py
| 550
| 4.21875
| 4
|
# Pairs
# Write a function to find all pairs of an integer array whose sum is equal to a given number.
# Example: pair_sum([2,4,3,5,6,-2,4,7,8,9], 7)
# Output: ['2+5', '4+3', '3+4', '-2+9']
my_list = [2,4,3,5,6,-2,4,7,8,9]
def pair_sum(list, num_sum):
output = []
for i in range(len(list)):
for j in range(i+1, len(list)):
if list[i] + list[j] == num_sum:
# print(f"{list[i]} + {list[j]} = {num_sum}")
output.append(f"{list[i]}+{list[j]}")
return output
print(pair_sum(my_list, 7))
| true
|
49ab45268ba1099af5637316d5584e075a601dab
|
ralsouza/python_data_structures
|
/section28_sorting_algorithms/293_bubbles_sort.py
| 490
| 4.25
| 4
|
# Bubble Sort
# - Bubble sort is also referred as Sinking sort
# - We repeatedly compare each pair of adjacent items and swap them if
# they are in the wrong order
def bubble_sort(custom_list):
for i in range(len(custom_list)-1):
for j in range(len(custom_list)-i-1):
if custom_list[j] > custom_list[j+1]:
custom_list[j], custom_list[j+1] = custom_list[j+1], custom_list[j]
print(custom_list)
c_list = [2,1,7,6,5,3,4,9,8]
bubble_sort(c_list)
| true
|
6adcebfeff79bf2c97bf0587a49e658e71b7b503
|
ralsouza/python_data_structures
|
/section8_lists/proj3_finding_numer_in_array.py
| 399
| 4.15625
| 4
|
# Project 3 - Finding a number in a array
# Question 3 - How to check if an array contains a number in Python
import numpy as np
my_list = list(range(1,21))
my_array = np.array(my_list)
def find_number(array, number):
for i in range(len(array)):
if array[i] == number:
print(f"The number {number} exists at index {i}.")
find_number(my_array, 13)
find_number(my_array, 21)
| true
|
c22fbab5afe23a79783eeaa86b6d0041c5c01b7d
|
viratalbu1/Python-
|
/AccesingInstanceVariable.py
| 513
| 4.25
| 4
|
#This Example is used for understanding what is instance variable
class test:
def __init__(self,name,rollno):
self.name=name
self.rollno=rollno
def info(self):
print(self.name)
print(self.rollno)
#In Above Example state creation of constructor and object method
# For Accessing it just create Object
t=test("Virat",1)
t.info() #This method will print the value of instance variable
print(t.name)
#above and below method will also give yo the instance variable value
print(t.rollno)
| true
|
78e9924735898785f3963c59531b866f1f44138b
|
viratalbu1/Python-
|
/IteratorAndGeneratorExample.py
| 695
| 4.875
| 5
|
# Iterator is used for creating object for iteratable object such as string, list , tuple
itr_list=iter([1,2,3,4])
itr_tuple=iter((1,2,3,4))
itr_string=iter('String')
print('--------List ------')
for val in itr_list:
print(val)
print('-----Tuple----------')
for val in itr_tuple:
print(val)
print('------String---------')
for val in itr_string:
print(val)
print('Genertor Examples')
def GetCubes(a):
for num in range(a):
yield num**3
print(GetCubes(5))
print('This is Object so now we can call this object and get the result')
for val in GetCubes(5):
print(val)
print('Other Varient for Using Generator')
print(list(GetCubes(2)))
| true
|
ad96b449267f2c830b6ebc0f6f0d8f13a1300f0a
|
bongjour/effective_python
|
/part1/zip.py
| 672
| 4.15625
| 4
|
from itertools import zip_longest
names = ['dante', 'beerang', 'sonic']
letters = [len(each) for each in names]
longest_name = None
max_letter = 0
# for i, name in enumerate(names):
# count = letters[i]
#
# if count > max_letter:
# longest_name = name
# max_letter = count
for name, count in zip(names, letters):
if count > max_letter:
longest_name = name
max_letter = count
print(max_letter)
print(longest_name)
names.append('billy') # zip은 크기가 틀리면 이상하게 동작한다.
for name, count in zip(names, letters):
print(name)
for name, count in zip_longest(names, letters):
print(name, count)
| true
|
4f1ee7021d8707fcf351345b18d164ecc0ccd3db
|
aFuzzyBear/Python
|
/python/mystuff/ex24.py
| 1,953
| 4.28125
| 4
|
# Ex24- More Python Practicing
#Here we are using the escape \\ commands int eh print statement.
print "Let's practice everything."
print "You\'d need to know \'bout dealing with \\escape statements\\ that do \n newlines and \t tabs"
#Here we have made the poem a multilined print statement
poem = """
\tThe lovely world
with logic so firmly planted
cannot dicern \n the needs of love
nor comprehend passion from intuition
and requires and explanation
\n\t\twhere there is none.
"""
#Here we are outputing the varible poem as a call funtion to print
print "--------------------"
print poem
print "--------------------"
#Here a varible is calculating the math of the varible and calling it into the print statement
five = 10 - 2 + 3- 6
print "this should be five: %s" % five
#Here we are defining a function with variables set to return the values of their respective arguements.
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
#Here we are introducing values to the function
start_point = 1000 #tbh we could do a raw_input to get the user to enter the value here
beans, jars, crates = secret_formula(start_point) # beans and jelly_beans are synonomis with each other, the varible inside the function is temporary, when it is returned in the function it can be called assigned to a varible for later, here beans just holds the value for jelly_beans
print "With a starting point of: %d" % start_point
print "We'd have %d beans, %d jars, and %d crates" % secret_formula(start_point)
start_point = start_point /10
print "We can also do that this way: "
print "We'd have %d beans, %d Jars, and %d crates" % secret_formula(start_point)# I tried to use {} tuples to enter the arguements into the statement, however was given IndexError: tuple index out of range. This is probalby down to the fact the arguements being called is stored within the function. idk
| true
|
09f90dc3135c90b4e3a62d3ef3553f160c621f4a
|
aFuzzyBear/Python
|
/python/mystuff/ex33.py
| 1,228
| 4.375
| 4
|
#While Loops
"""A While loop will keep executing code if the boolean expression is True. It is a simple If-Statement but instead of running a block of code once if True, it would keep running through the block untill it reaches the first False expression.
The issue with while-loops is that they sometimes dont stop. They can keep going on forever.
To avoid this issue follow the following rules:
1) Make sure that you use While-loops sparingly. For loops are always better!
2) Review the while loops to make sure the logic behind it will produce a false expression at one point.
3)when in doubt print out a test varible at the top and bottom of the while-loop to see what it's doing
"""
i = 0
numbers = []
#This is saying while i equal to values less than 6 print keep doing the block of code.
while i < 6:
print "At the top i is %d" % i
numbers.append(i)#Here we are adding to the list for every iteratation
i = i + 1 #This is a strange one, telling to change the i varible by taking the current value and adding its new value for the iteration to itself. probably could be written as i += 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
print "The numbers: "
for num in numbers:
print num
| true
|
1766f40560f8a404a0c964a89198d185304c20c7
|
aFuzzyBear/Python
|
/python/mystuff/ex20.py
| 606
| 4.15625
| 4
|
#Functions and Files
from sys import argv
scrit, input_file = argv
def print_all(f):
print f.read()
def rewind (f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file: \n"
print_all(current_file)
print "Now let's rewind, kinda like a tape.\n"
rewind(current_file)
print "Lets print three lines.\n"
current_line = 1
current_line += current_line
print_a_line (current_line, current_file)
print_a_line (current_line, current_file)
print_a_line (current_line, current_file)
#I really dont get this!
| true
|
d37e27a702a74af02dce7b41c3a6a368f714ba2e
|
szhongren/leetcode
|
/129/main.py
| 1,697
| 4.15625
| 4
|
"""
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ \
2 3
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 = 25.
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def make_tree(ls):
"""
:type ls: List[int]
:rtype: TreeNode
"""
list_nodes = list(map(lambda x: TreeNode(x) if x != None else None, ls))
length = len(list_nodes)
for i in range(length // 2):
if list_nodes[i] != None:
if i * 2 + 1 < length:
list_nodes[i].left = list_nodes[i * 2 + 1]
if i * 2 + 2 < length:
list_nodes[i].right = list_nodes[i * 2 + 2]
return list_nodes[0]
def dfs(root, num, sum):
if root == None:
return sum
num = num * 10 + root.val
if root.left == None and root.right == None:
sum += num
return sum
sum = dfs(root.left, num, sum) + dfs(root.right, num, sum)
return sum
class Solution(object):
def sumNumbers(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
else:
return dfs(root, 0, 0)
ans = Solution()
print(ans.sumNumbers(make_tree([1, 1])))
print(ans.sumNumbers(make_tree([1, 2, 3])))
| true
|
1a1a9e775108be74c02d4e90c42bf1928f94ca4f
|
szhongren/leetcode
|
/337/main.py
| 2,378
| 4.15625
| 4
|
"""
The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.
Determine the maximum amount of money the thief can rob tonight without alerting the police.
Example 1:
3
/ \
2 3
\ \
3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3
/ \
4 5
/ \ \
1 3 1
Maximum amount of money the thief can rob = 4 + 5 = 9.
"""
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def make_tree(ls):
"""
:type ls: List[int]
:rtype: TreeNode
"""
if len(ls) == 0:
return None
list_nodes = list(map(lambda x: TreeNode(x) if x != None else None, ls))
length = len(list_nodes)
for i in range(length // 2):
if list_nodes[i] != None:
if i * 2 + 1 < length:
list_nodes[i].left = list_nodes[i * 2 + 1]
if i * 2 + 2 < length:
list_nodes[i].right = list_nodes[i * 2 + 2]
return list_nodes[0]
class Solution(object):
def rob(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def transformTree(node):
if node == None:
return TreeNode([0, 0])
node.left = transformTree(node.left)
node.right = transformTree(node.right)
curr_val = node.val
node.val = [None, None]
rob = 0
notrob = 1
node.val[notrob] = node.left.val[rob] + node.right.val[rob]
node.val[rob] = max(node.val[notrob], curr_val + node.left.val[notrob] + node.right.val[notrob])
return node
# only works when space between houses robbed can only be 1
return max(transformTree(root).val)
ans = Solution()
print(ans.rob(make_tree([3, 2, 3, None, 3, None, 1])))
print(ans.rob(make_tree([3, 4, 5, 1, 3, None, 1])))
print(ans.rob(make_tree([])))
| true
|
522b1b01a64b08202f162b7fae780dbf2219066e
|
szhongren/leetcode
|
/473/main.py
| 1,692
| 4.3125
| 4
|
"""
Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.
Example 1:
Input: [1,1,2,2,2]
Output: true
Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
Example 2:
Input: [3,3,3,3,4]
Output: false
Explanation: You cannot find a way to form a square with all the matchsticks.
Note:
The length sum of the given matchsticks is in the range of 0 to 10^9.
The length of the given matchstick array will not exceed 15.
"""
class Solution(object):
def makesquare(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
total = 0
max_match = 0
count = 0
for v in nums:
count += 1
total += v
max_match = max(v, max_match)
if count < 4 or max_match > total // 4 or total % 4 != 0:
return False
nums.sort()
side = total // 4
return self.makeSquareRecur(nums, [side for _ in range(4)], side)
def makeSquareRecur(self, nums, sides, side):
return True
ans = Solution()
print(ans.makesquare([1, 1, 2, 2, 2]))
print(ans.makesquare([3, 3, 3, 3, 4]))
| true
|
10c13ace9bc8e87cf08e9f5a4947808deb630506
|
AI-System/ai-learning-material-old
|
/Basic-Python/code/test_oop/2.py
| 814
| 4.125
| 4
|
### 类的构造方法 __init__
class A:
def __init__(self):
# 实例化时自动调用,一般用于初始化
print('init ...')
def fun(self):
print('class A...')
a = A() # 实例化 A 时, 如果内部有 __init__ 方法, 那么会调用该方法
print('✨' * 20)
class Person:
name=""
age=0
def __init__(self):
pass
def getInfo(self):
print(self.name, " : ", self.age)
p = Person()
# 初始化之后设置参数
p.name = 'lisi'
p.age = 20
p.getInfo()
print('✨' * 20)
class Dog:
name=""
age=0
def __init__(self, name, age):
self.name = name
self.age = age
def getName(self):
# 注意这里的第一个参数都是self
print('test dog : name %s; age %d'%(self.name, self.age))
d = Dog('Jack', 10) # test dog : name Jack; age 10
d.getName()
| false
|
4671c9f8d366e45e97a92920d6190e1d7c65d894
|
tdongsi/effective_python
|
/ep/item13b.py
| 1,973
| 4.15625
| 4
|
NUMBERS = [8, 3, 1, 2, 5, 4, 7, 6]
GROUP = {2, 3, 5, 7}
def sort_priority(numbers, group):
""" Sort the input numbers but put those in "group" first.
:param numbers: list of input numbers.
:param group: set of numbers in priority group.
:return: True if any number in priority is found.
"""
found = False
def helper(x):
if x in group:
found = True
return (0, x)
return (1, x)
numbers.sort(key=helper)
return found
def main_original():
numbers = NUMBERS[:]
print(sort_priority_solved(numbers, GROUP))
print(numbers)
def sort_priority_python_3(numbers, group):
""" Sort the input numbers but put those in "group" first.
:param numbers: list of input numbers.
:param group: set of numbers in priority group.
:return: True if any number in priority is found.
"""
found = False
def helper(x):
if x in group:
# nonlocal found
found = True
return (0, x)
return (1, x)
numbers.sort(key=helper)
return found
def sort_priority_python_2(numbers, group):
""" Sort the input numbers but put those in "group" first.
:param numbers: list of input numbers.
:param group: set of numbers in priority group.
:return: True if any number in priority is found.
"""
found = [False]
def helper(x):
if x in group:
found[0] = True
return (0, x)
return (1, x)
numbers.sort(key=helper)
return found[0]
class CheckSpecial(object):
def __init__(self, group):
self.group = group
self.found = False
def __call__(self, x):
if x in self.group:
self.found = True
return (0, x)
return (1, x)
def sort_priority_solved(numbers, group):
helper = CheckSpecial(GROUP)
numbers.sort(key=helper)
return helper.found
if __name__ == '__main__':
main_original()
| true
|
6c73b0dade33e1a6dfbd3bfc1bb9e43ec21dabbf
|
tdongsi/effective_python
|
/ep/item13.py
| 924
| 4.46875
| 4
|
meep = 23
def enclosing():
""" Variable reference in different scopes.
When referring to a variable not existing in the inner scope,
Python will try to look up in the outer scope.
"""
foo = 15
def my_func():
bar = 10
print(bar) # local scope
print(foo) # enclosing scope
print(meep) # global scope
print(str) # built-in scope
# print(does_not_exist)
my_func()
enclosing()
def enclosing_assignment():
""" Variable assignment in different scopes.
Different from variable reference.
When assigning to a variable not existing in the inner scope,
Python will create a new local variable.
"""
foo = 15
foo = 25
def my_func():
foo = 15
bar = 5
print(foo)
print(bar)
my_func()
print(foo)
# print(bar) # Does not exist
enclosing_assignment()
| true
|
3d8fa1d96a89e06299f099b1f4ccc88cf33b5d97
|
oigwe/learning_data_analyzing
|
/python/Step 1/2.Python Data Analysis Basics: Takeaways.py
| 1,229
| 4.1875
| 4
|
#Python Data Analysis Basics: Takeaways
#by Dataquest Labs, Inc. - All rights reserved © 2020
#Syntax
#STRING FORMATTING AND FORMAT SPECIFICATIONS
#Insert values into a string in order:
continents = "France is in {} and China is in {}".format("Europe", "Asia")
#Insert values into a string by position:
squares = "{0} times {0} equals {1}".format(3,9)
#Insert values into a string by name:
population = "{name}'s population is {pop} million".format(name="Brazil", pop=209)
#Format specification for precision of two decimal places:
two_decimal_places = "I own {:.2f}% of the company".format(32.5548651132)
#Format specification for comma separator:
india_pop = The approximate population of {} is {}".format("India",1324000000)
#Order for format specification when using precision and comma separator:
balance_string = "Your bank balance is {:,.2f}"].format(12345.678)
#Concepts
#The str.format() method allows you to insert values into strings without explicitly converting them.
#The str.format() method also accepts optional format specifications, which you can use to format values so they are easier to read.
#Resources
#Python Documentation: Format Specifications
#PyFormat: Python String Formatting Reference
| true
|
0a4042a5c22e529574bc1ccb8f1f6bbfad9c7894
|
oigwe/learning_data_analyzing
|
/python/Step 1/Lists and For Loops: Takeaways.py
| 1,567
| 4.375
| 4
|
#Lists and For Loops: Takeaways
#by Dataquest Labs, Inc. - All rights reserved © 2020
#Syntax
#Creating a list of data points:
row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5]
row_2 = ['Instagram', 0.0, 'USD', 2161558, 4.5]
#Creating a list of lists:
data = [row_1, row_2]
#Retrieving an element of a list:
first_row = data[0]
first_element_in_first_row = first_row[0]
first_element_in_first_row = data[0][0]
last_element_in_first_row = first_row[-1]
last_element_in_first_row = data[0][-1]
#Retrieving multiple list elements and creating a new list:
row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5]
rating_data_only = [row_1[3], row_1[4]]
#Performing list slicing:
row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5]
second_to_fourth_element = row_1[1:4]
#Opening a data set file and using it to create a list lists:
opened_file = open('AppleStore.csv')
from csv import reader #reader is a function that generates a reader object
read_file = reader(opened_file)
apps_data = list(read_file)
#Repeating a process using a for loop:
row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5]
for data_point in row_1:
print(data_point)
#Concepts
#A data point is a value that offers us some information.
#A set of data points make up a data set. A table is an example of a data set.
#Lists are data types which we can use to store data sets.
#Repetitive process can be automated using for loops.
#Resources
#Python Lists
#Python For Loops
#More on CSV files
#A list of keywords in Python — for and in are examples of keywords (we used for and in to write for loops)
| true
|
28d231a0a4e9f1a42c968643e77bd1598e0da992
|
jonag-code/python
|
/dictionary_list_tuples.py
| 1,675
| 4.25
| 4
|
List =[x**2 for x in range(5)]
Dictionary = {0:'zero', 1:'one', 2:'four', 3:'nine', 4:'sixteen'}
Tuple = tuple(List)
#The following doesn't work as with lists: Tuple2 =(x**2 for x in range(10)).
#Also the entries of tuples cannot be modified like in lists or dictionaries.
#This is useful when storing important information.
print("The following is a list followed by tuple: \n%s\n%s \n" %(List,Tuple))
print("This was the old dictionary: \n %s \n" %Dictionary)
for i in range(len(List)):
print("%s \t%s \t%s " % (List[i], Tuple[i], Dictionary[i]) )
print("\n")
#Note how all three types are referenced the same way, In a given
#dictionary only the "value" is printed, for instance,
# where the reference is the "key": Dictionary[key_0] = value_0.
Copy_Dictionary = dict(Dictionary)
#NOTE: Copy_Dictionary = Dictionary will not only copy, but both
#will change dynamically. Here unwanted. In for loop fine?
print("This is a copied dictionary: \n%s " %Copy_Dictionary)
#--------------------------------------------------------------------------------
#THE CODE BELOW HAS TWO BETTER VERSIONS IN: dictionaries_from_lists.py
#ACTUALLY REALLY BAD CODE HERE, AS THE FOR LOOP CRITICALLY DEPENDS ON
#THE FIRST "key" OF dictionary TO BE EQUAL TO 0.
dictionary = {0:'zero', 1:'one', 2:'four'}
copy_dictionary = dict(dictionary)
VALUES = list(dictionary.values())
for n in range(len(dictionary)):
#Copy_Dictionary[ VALUES[n] ] = Copy_Dictionary.pop(n)
copy_dictionary[ VALUES[n] ] = copy_dictionary[n]
del copy_dictionary[n]
print("\n \nThis is the old dictionary: \n %s" %dictionary)
print("This is the new dictionary: \n %s\n" %copy_dictionary)
| true
|
b831921bf3f540ef6e9a6a8957720757feda3e46
|
theparadogs/Python
|
/Calculator.py
| 780
| 4.125
| 4
|
print("===============================================")
#masukan input dari user
print("Selamat Datang di Program Kalkulator sederhana")
enter = input("klik enter untuk lanjut : ")
print("Program ini dibuat oleh Felix Rizky Lesmana")
enter = input("klik enter untuk lanjut : ")
print("===============================================")
a = float(input("Masukan nilai pertama: "))
aritmatika = input("pilih operator +, -, /, * : ")
b = int(input("Masukan nilai kedua: "))
if aritmatika == '+' :
print(a ,"+", b, "= ",(a + b))
elif aritmatika == '-' :
print(a ,"-", b, "= ",(a - b))
elif aritmatika == '*' :
print(a ,"*", b, "= ",(a * b))
elif aritmatika == '/' :
print(a ,"/", b, "= ",(a / b))
else :
print("Operator salah")
enter = input("klik enter untuk selesai : ")
| false
|
4e5a34a5a570d67a33a414124f62dd3b498e06a2
|
Robin-Andrews/Serious-Fun-with-Python-Turtle-Graphics
|
/Chapter 8 - The Classic Snake Game with Python Turtle Graphics/2. basic_snake_movement.py
| 1,362
| 4.25
| 4
|
# Import the Turtle Graphics module
import turtle
# Define program constants
WIDTH = 500
HEIGHT = 500
DELAY = 400 # Milliseconds between screen updates
def move_snake():
stamper.clearstamps() # Remove existing stamps made by stamper.
# Next position for head of snake.
new_head = snake[-1].copy()
new_head[0] += 20
# Add new head to snake body
snake.append(new_head)
# Remove last segment of snake
snake.pop(0)
# Draw snake
for segment in snake:
stamper.goto(segment[0], segment[1])
stamper.stamp()
# Refresh screen
screen.update()
# Rinse and repeat
turtle.ontimer(move_snake, DELAY)
# Create a window where we will do our drawing
screen = turtle.Screen()
screen.setup(WIDTH, HEIGHT) # Set the dimensions of the window
screen.title("Snake")
screen.bgcolor("pink")
screen.tracer(0) # Turn off automatic animation
# Stamper Turtle
# This Turtle is defined at the global level, so is available to move_snake()
stamper = turtle.Turtle("square")
stamper.penup()
# Create snake as a list of coordinate pairs. This variable is available globally.
snake = [[0, 0], [20, 0], [40, 0], [60, 0]]
# Draw snake for the first time
for segment in snake:
stamper.goto(segment[0], segment[1])
stamper.stamp()
# Set animation in motion
move_snake()
# Finish nicely
turtle.done()
| true
|
ec0af5bcde099c9a9695d6ec4d8f4f231b13ce7e
|
rizqo46/refactory-assignment
|
/logic_test/leapyear.py
| 695
| 4.15625
| 4
|
# In the Gregorian calendar, three conditions are used to identify leap years:
# - The year can be evenly divided by 4, is a leap year, unless:
# - * The year can be evenly divided by 100, it is NOT a leap year, unless:
# - - # The year is also evenly divisible by 400. Then it is a leap year.
def leapyear(a, b):
if a > b:
a, b = b, a
arr = []
for i in range(a, b + 1):
div4 = (i%4 == 0)
div100 = (i%100 == 0)
div400 = (i%400 == 0)
if div4 and div100 and div400:
arr.append(i)
elif div4 and not div100:
arr.append(i)
return arr
if __name__ == "__main__":
a, b = 2000, 1900
print(leapyear(a, b))
| false
|
501ca8c5a71b67cd7db14e7577be41fcd6646fd7
|
shantanusharma95/LearningPython
|
/DataStructures/priority_queue.py
| 2,988
| 4.25
| 4
|
import sys
class node:
def __init__(self,data,priority):
self.data=data
self.priority=priority
self.next=None
class queue:
def __init__(self):
self.Head=self.Tail=None
self.queueSize=0
#adds a new value to queue, based on priority of data
#this will make enqueue operation time complexity to O(n) against O(1) in normal queue
def enqueue(self,data,priority):
temp=node(data,priority)
if self.Head==None:
self.Head=temp
self.Tail=temp
else:
if(self.queueSize==1):
if(temp.priority>self.Head.priority):
temp.next=self.Head
self.Tail=temp
else:
self.Tail.next=temp
self.Head=temp
else:
temp2=self.Tail
temp3=self.Tail
while(temp2!=None and temp.priority<=temp2.priority):
temp3=temp2
temp2=temp2.next
if(temp2==temp3):
temp.next=temp3
self.Tail=temp
else:
temp3.next=temp
temp.next=temp2
self.queueSize+=1
#removes the most oldest inserted value
def dequeue(self):
if self.queueSize==0:
print("Queue is empty!\n")
return
temp=self.Tail
self.Tail=temp.next
del(temp)
self.queueSize-=1
def sizeCheck(self):
print("Size of queue is ",self.queueSize)
def display(self):
print("The queue contains...\n")
temp=self.Tail
while(temp!=None):
print(temp.data," ")
temp=temp.next
def main():
queueObj=queue()
while(True):
#add a new element at head of queue
print("1. Enqueue")
#remove element from tail of queue
print("2. Dequeue")
#display size of stack
print("3. Size Check")
#display size of stack
print("4. Display Queue")
print("5. Exit")
user_choice=input("Enter your Choice!\n")
user_choice=int(user_choice)
if user_choice == 1:
data=input("Enter data : ")
priority=int(input("Enter priority, lowest from 1 and onwards : "))
if(priority>0):
queueObj.enqueue(data,priority)
print("Updated Queue : \n")
queueObj.display()
else:
print("Enter valid priority!")
continue
elif user_choice == 2:
print("Removing from queue...")
queueObj.dequeue()
elif user_choice == 3:
queueObj.sizeCheck()
elif user_choice == 4:
queueObj.display()
elif user_choice == 5:
sys.exit(0)
else:
print("Please enter a valid choice!")
if __name__=='__main__':
main()
| true
|
08951c8a90dc3bffde4ce992e89a15ff0ba31acf
|
adudjandaniel/Fractions
|
/lib/fraction/fraction.py
| 2,313
| 4.1875
| 4
|
class Fraction():
'''A basic fraction data type in python'''
def __init__(self, a=0, b=1):
self.a = a
self.b = b if b else 1
def __str__(self):
'''Converts the instance to a string'''
return "{}/{}".format(self.a, self.b)
def __repr__(self):
'''View of the instance in console'''
return self.__str__()
def __add__(self, next_fraction):
'''Adds two instances (+)'''
new_numerator = self.a * next_fraction.b + self.b * next_fraction.a
new_denominator = self.b * next_fraction.b
return Fraction(new_numerator, new_denominator).simplified()
def __sub__(self, next_fraction):
'''Subtracts the second instance passed to the function from the first (-)'''
new_numerator = self.a * next_fraction.b - self.b * next_fraction.a
new_denominator = self.b * next_fraction.b
return Fraction(new_numerator, new_denominator).simplified()
def __eq__(self, next_fraction):
'''Test equality (==)'''
return self.simplified().__str__() == next_fraction.simplified().__str__()
def __mul__(self, next_fraction):
'''Multiply two instances (*)'''
new_numerator = self.a * next_fraction.a
new_denominator = self.b * next_fraction.b
return Fraction(new_numerator, new_denominator).simplified()
def __truediv__(self, next_fraction):
'''Divide the first instance by the second (/)'''
next_fraction = Fraction(next_fraction.b, next_fraction.a)
return self.__mul__(next_fraction)
def simplify(self):
'''Simplify the fraction. Return None.'''
a = self.a
b= self.b
if b > a:
a, b = b, a
while b != 0:
remainder = a % b
a, b = b, remainder
gcd = a
self.a = int(self.a / gcd)
self.b = int(self.b / gcd)
def simplified(self):
'''Simplify the fraction. Return the simplified fraction.'''
a = self.a
b= self.b
if b > a:
a, b = b, a
while b != 0:
remainder = a % b
a, b = b, remainder
gcd = a
a = int(self.a / gcd)
b = int(self.b / gcd)
return Fraction(a,b)
| true
|
41f9eaee34956ebf3e6688ebca4d55b095552448
|
yafiimo/python-practice
|
/lessons/11_ranges.py
| 992
| 4.21875
| 4
|
print('\nloops from n=0 to n=4, ie up to 5 non-inclusive of 5')
for n in range(5):
print(n)
print('\nloops from 1 to 6 non-inclusive of 6')
for n in range(1,6):
print(n)
print('\nloop from 0 to 20 in steps of 4')
for n in range(0, 21, 4):
print(n)
print('\nloop through list like a for loop')
food = ['chapatti', 'sambusa', 'katlesi', 'biryani', 'samaki']
for n in range(len(food)):
print(n, food[n])
print('\nloop through list backwards')
for n in range(len(food) - 1, -1, -1):
print(n, food[n])
# starting from n=4, loop in steps of -1 until n=-1 non-inclusive
# which covers all items in food array going backwards
# range(x, y, z)
# x is the starting point
# y is the end point non-inclusive
# z is the step size
# LOOPING BACKWARDS THROUGH A LIST
# using len(list)-1 as x makes the starting point the index of the last item in the list
# using -1 as z makes the loop go backwards
# using -1 as y (end point) loops through whole list including index 0
| true
|
842079f591bef1485312dad98a8d44ad0cbace44
|
yafiimo/python-practice
|
/lessons/27_writing_files.py
| 941
| 4.125
| 4
|
# must use 'w' as 2nd argument to write to a file, and file_name as first argument
with open('text_files/write_file.txt', 'w') as write_file:
text1 = 'Hello, I am writing my first line to a file using Python!'
print('Writing first line to file...')
write_file.write(text1)
# if you want to ammend a file, you must use the 'a' argument
with open('text_files/write_file.txt', 'a') as write_file:
text2 = '\nWriting a second line into the text file.'
print('Adding a second line to file...')
write_file.write(text2)
quotes = [
'\nI\'m so mean I make medicine sick'
'\nThe best preparation for tomorrow is doing your best today'
'\nI am always doing that which I cannot do, in order that I may learn how to do it'
]
# writing lines into a text file from list separated lines
with open('text_files/write_file.txt', 'a') as write_file:
print('Adding quotes to file...')
write_file.writelines(quotes)
| true
|
a40506eaf66ec0af19289816a30e8ff2039e5868
|
zerodayz/dailycoding
|
/Examples/Recursion.py
| 350
| 4.1875
| 4
|
def recursive(input):
print("recursive(%s)" %input)
if input <= 0:
print("returning 0 into output")
return input
else:
print("entering recursive(%s)" %( input -1 ))
output = recursive(input -1)
print("output = %s from recursive(%s)" %(output, input - 1))
return output
print(recursive(3))
| true
|
fd0494ab43d057e55d61d3a0b0c2797406da3e47
|
arpitsingh17/DataStructures
|
/binarysearch.py
| 697
| 4.125
| 4
|
# Binary Search
# Input list must be sorted in this search method.
def bin(alist,item):
aalist = alist
midterm = alist[(len(alist)//2)]
found = False
while True:
try:
if item < midterm:
#print (alist[:((alist.index(midterm)))])
return(bin(alist[:((alist.index(midterm)))],item))
elif item > midterm:
#print(alist.index(midterm))
return(bin(alist[(alist.index(midterm)+1):],item))
#print alist[(alist.index(midterm)+1):]
elif item==midterm:
return("Found")
break
except:
return "Not Found"
print (bin([1,2,3,4,5],42))
| true
|
68bb058fda2c703036d8bd76c1c57171db1608a0
|
ericwebsite/ericwebsite.github.io
|
/src/python/TheTemple(2).py
| 1,376
| 4.125
| 4
|
import random
print("Importable +")
import time
time.sleep(3)
print("You went in a temple. I dare you. ")
print(",,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,")
time.sleep(3)
print("You saw...")
print("()()()()()()()()()()()()")
time.sleep(3)
power = input("Choose a power. waterBreathing(w),fireProtection(fp),BlastProtection(bp),ScaryMask(sm)")
time.sleep(3)
print("T-rex-er comes")
c = random.randint(0,1)
time.sleep(3)
if c == 1:
if power == "fp":
print("You win!!!!!!!!!!!!!!!!")
else:
print("Fire killed you")
else:
d = input("Go left(l) or right(r)")
time.sleep(3)
if d == "l":
print ("TNT is active. BOOM!!!!!!!!!!!!")
time.sleep(3)
if power == "bp":
print("You win")
else:
print("TNT killed you")
else:
print("Another 2-choice intersect?")
time.sleep(3)
lor = input("Go left(l) or right(r)")
time.sleep(3)
if lor == "l":
print("water rises")
time.sleep(3)
if power == "w":
print("You win!!!!!!!!!")
else:
print("water killed you, you can't breath")
else:
print("There is evil girls")
time.sleep(3)
if power == "sm":
print("You win")
else:
print("evil wins")
| false
|
d5b0e6cae118c886d8ac206b3af3e16ca0b4edf5
|
j-thepac/Python_snippets
|
/SmallHighPow/smallhighpow.py
| 896
| 4.21875
| 4
|
"""
We have the number 12385. We want to know the value of the closest cube but higher than 12385. The answer will be 13824.
Now, another case. We have the number 1245678. We want to know the 5th power, closest and higher than that number. The value will be 1419857.
We need a function find_next_power ( findNextPower in JavaScript, CoffeeScript and Haskell), that receives two arguments, a value val, and the exponent of the power, pow_, and outputs the value that we want to find.
Let'see some cases:
find_next_power(12385, 3) == 13824
find_next_power(1245678, 5) == 1419857
The value, val will be always a positive integer.
The power, pow_, always higher than 1.
Happy coding!!
"""
def find_next_power(val, pow_):
n=2
while (n**pow_ < val):
n+=1
return n**pow_
assert find_next_power(12385, 3) == 13824
assert find_next_power(1245678, 5) == 1419857
print("done")
| true
|
08f2d5e5f13dcb98a8e419568b391b56439ae6cf
|
j-thepac/Python_snippets
|
/IntSeq/python/intseq.py
| 1,626
| 4.21875
| 4
|
"""
Description:
Complete function findSequences. It accepts a positive integer n. Your task is to find such integer sequences:
Continuous positive integer and their sum value equals to n
For example, n = 15
valid integer sequences:
[1,2,3,4,5] (1+2+3+4+5==15)
[4,5,6] (4+5+6==15)
[7,8] (7+8==15)
The result should be an array [sequence 1,sequence 2...sequence n], sorted by ascending order of the length of sequences; If no result found, return [].
Some examples:
findSequences(3) === [[1,2]]
findSequences(15) === [[7,8],[4,5,6],[1,2,3,4,5]]
findSequences(20) === [[2, 3, 4, 5, 6]]
findSequences(100) === [[18, 19, 20, 21, 22], [9, 10, 11, 12, 13, 14, 15, 16]]
findSequences(1) === []
"""
def find_sequences(n):
n1=n//2
res=[]
for i in range(0,n1):
tempRes=[]
while True:
i=i+1
tempRes.append(i)
if(sum(tempRes)==n):
res.append(tempRes)
break
elif (sum(tempRes)>n):break
return res[::-1]
def find_sequences2(n):
n1=n//2
res=[]
for i in range(1,n1+1):
tempRes=[]
for j in range(i,n-1):
tempRes.append(j)
if(sum(tempRes)>n):break
elif(sum(tempRes)==n):
res.append(tempRes)
break
print(n,res)
return res[::-1]
test_cases = [
# ( 3, [[1,2]]),
( 15, [[7,8], [4,5,6], [1,2,3,4,5]]),
( 20, [[2,3,4,5,6]]),
(100, [[18,19,20,21,22], [9,10,11,12,13,14,15,16]]),
( 1, []),
]
for n, expected in test_cases:
assert(find_sequences(n)== expected)
print("Done")
| true
|
c7dfc6b9bbf3f103a6c4a127119edc8f0e0df1bd
|
j-thepac/Python_snippets
|
/Brackets/brackets.py
| 1,423
| 4.21875
| 4
|
"""
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Every close bracket has a corresponding open bracket of the same type.
Example 1:
Input: s = "()"
Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]"
Output: false
"""
def isValid2(s: str) -> bool:
s=s.replace("()","").replace("[]","").replace("{}","")
if(len(s)%2!=0):return False
if(s.count("(")!=s.count(")") or s.count("[")!=s.count("]") or s.count("{") != s.count("}")):return False
l=list(s)
while(len(l)!=0):
m=(len(l)//2)
if(l[m-1]=='(' and l[m]==')' or l[m-1]=='[' and l[m]==']' or l[m-1]=="{" and l[m]=='}'):
del l[m]
del l[m-1]
else: return False
return True
def isValid(s: str) -> bool:
if(len(s)%2!=0):return False
if(s.count("(")!=s.count(")") or s.count("[")!=s.count("]") or s.count("{") != s.count("}")):return False
while (len(s)>0):
count=len(s)
s=s.replace("()","").replace("[]","").replace("{}","")
if(len(s)==count): return False
return True
assert (isValid("[([[]])]")==True)
assert (isValid("(([]){})")==True)
assert (isValid("()[]{}")==True)
# assert(isValid("(]")==False)
| true
|
ebf04b862009e61e6993d8216c0ffdb3db6cf5a2
|
j-thepac/Python_snippets
|
/SameCase/samecase.py
| 1,069
| 4.1875
| 4
|
"""
Write a function that will check if two given characters are the same case.
'a' and 'g' returns 1
'A' and 'C' returns 1
'b' and 'G' returns 0
'B' and 'g' returns 0
'0' and '?' returns -1
If any of characters is not a letter, return -1.
If both characters are the same case, return 1.
If both characters are letters and not the same case, return 0.
docker run -it --name samecase -p 5000:5000 -v $PWD:/home/app -w /home/app python:3.9-slim python samecase.py
"""
def same_case(a, b):
if(len(a)>1 or len(b) > 1) :return -1
elif(ord(a) not in range(65,91) and ord(a) not in range(97,123) ):return -1
elif(ord(b) not in range(65,91) and ord(b) not in range(97,123) ): return -1 # (ord(b) in range(97,123)
if( (a.isupper() and b.islower()) or (a.islower() and b.isupper()) ):return 0
else:return 1
assert(same_case('C', 'B')== 1)
assert(same_case('b', 'a')== 1)
assert(same_case('d', 'd')== 1)
assert(same_case('A', 's')== 0)
assert(same_case('c', 'B')== 0)
assert(same_case('b', 'Z')== 0)
assert(same_case('\t', 'Z')== -1)
print("done")
| true
|
14c7bf781e52c8f4eaa62b0d30dab3939d452180
|
j-thepac/Python_snippets
|
/Phoneno/phoneno.py
| 1,032
| 4.21875
| 4
|
"""
Write a function that accepts an array of 10 integers (between 0 and 9)== that returns a string of those numbers in the form of a phone number.
Example
create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) # => returns "(123) 456-7890"
The returned format must be correct in order to complete this challenge.
Don't forget the space after the closing parentheses!
docker run -it --name phoneno -v $PWD:/home/app -w /home/app -p 5000:5000 python:3.9-slim python phoneno.py
docker build -t phoneno:v1 .
"""
def create_phone_number(n):
n="".join(str(i) for i in n)
return "({}) {}-{}".format(n[0:3],n[3:6],n[6:])
assert(create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])== "(123) 456-7890")
assert(create_phone_number([1, 1, 1, 1, 1, 1, 1, 1, 1, 1])== "(111) 111-1111")
assert(create_phone_number([1, 2, 3, 4, 5, 6, 7, 8, 9, 0])== "(123) 456-7890")
assert(create_phone_number([0, 2, 3, 0, 5, 6, 0, 8, 9, 0])== "(023) 056-0890")
assert(create_phone_number([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])== "(000) 000-0000")
print("done")
| true
|
e362ff3a5d949f03cceb6f8de2602b06d1d2cac4
|
barthelemyleveque/Piscine_Python
|
/D00/ex06/recipe.py
| 2,559
| 4.125
| 4
|
import sys
import time
cookbook= {
'sandwich': {
'ingredients':['ham', 'bread', 'cheese', 'tomatoes'],
'meal':'lunch',
'prep_time':10,
},
'cake' : {
'ingredients':['flour', 'sugar', 'eggs'],
'meal':'dessert',
'prep_time':60
},
'salad':{
'ingredients':['avocado', 'arugula', 'tomatoes', 'spinach'],
'meal':'lunch',
'prep_time':15,
}
}
def print_recipe(name):
if name in cookbook:
recipe = cookbook[name]
print("Recipe for "+name+":")
print("Ingredients list:" + str(recipe['ingredients']))
print("To be eaten for: "+str(recipe["meal"]+"."))
print("Takes "+str(recipe["prep_time"])+" minutes of cooking.")
else:
print("Recipe doesn't exist")
def delete_recipe(name):
if name in cookbook:
del cookbook[name]
print(name + " recipe has been deleted\n")
else:
print("Cannot delete a recipe that doesn't exist")
def add_recipe(name, ingredients, meal, prep_time):
if name in cookbook:
print("Recipe already exists")
else:
cookbook[name] = {
'ingredients': ingredients,
'meal': meal,
'prep_time': prep_time,
}
print("\nRecipe has been added :\n")
print_recipe(name)
def print_all():
for key in cookbook:
print_recipe(key)
print("----")
i = input('Please select an option by typing the corresponding number:\n1: Add a recipe\n2: Delete a recipe\n3: Print a recipe\n4: Print the cookbook\n5: Quit\n')
while (i.isdigit() != 0 or int(i) > 5 or int(i) == 0):
if (int(i) == 1):
recipe = input('Please enter the recipe name to add:\n')
str_ingredients = input('Please enter the ingredients of the recipe, separated by commas and no spaces:\n')
ingredients = str_ingredients.split(",")
meal = input('Please enter which meal it is best for :\n')
prep_time = input('Please enter which prep time :\n')
add_recipe(recipe, ingredients, meal, prep_time)
if (int(i) == 2):
delete_recipe(input('Please enter the recipe name to delete:\n'))
if (int(i) == 3):
print_recipe(input('Please enter the recipe name to get details:\n'))
if (int(i) == 4):
print_all()
if (int(i) == 5):
sys.exit("Goodbye !\n")
time.sleep(4)
i = input('Please select an option by typing the corresponding number:\n1: Add a recipe\n2: Delete a recipe\n3: Print a recipe\n4: Print the cookbook\n5: Quit\n')
| true
|
ce499afe3bf4323bc35f81eda9cb02bbeb866f2b
|
anand13sethi/Data-Structures-with-Python
|
/Queue/QueueReverse.py
| 963
| 4.15625
| 4
|
# Reversing a Queue implemented using singly link list using stack.
from QueueUsingLinkList import Queue
class Stack:
def __init__(self):
self.stack = []
self.size = 0
def is_empty(self):
return self.size <= 0
def push(self, data):
self.stack.append(data)
self.size += 1
def pop(self):
if self.is_empty():
raise ValueError("Underflow!")
else:
self.size -= 1
return self.stack.pop()
def peek(self):
if self.is_empty():
raise ValueError("Peeking Into Empty Stack!")
else:
return self.stack[self.size]
def reverse_queue(que=Queue()):
aux_stack = Stack()
if que.is_empty():
raise ValueError("Empty Queue!")
else:
while not que.is_empty():
aux_stack.push(que.dequeue())
while not aux_stack.is_empty():
que.enqueue(aux_stack.pop())
return que
| true
|
1b6bc1d29ff40669e1d3f47d92f5675934c4c8c8
|
joeybtfsplk/projecteuler
|
/10.py
| 1,353
| 4.125
| 4
|
#!/usr/bin/env python
"""
file: 10.py
date: Thu Jul 31 09:25:11 EDT 2014
from: Project Euler: http://projecteuler.net
auth: tls
purp: The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of
all the primes below two million.
Ans: 142913828922 on Fri Aug 1 22:34:07 EDT 2014
"""
def prime_list(num):
"""
From: http://en.wikibooks.org/wiki/Efficient_Prime_Number_Generating_
Algorithms
Return primes up to but not including num.
Acts goofy below 20.
"""
from math import sqrt
pp=2
ep=[pp]
pp+=1
tp=[pp]
ss=[2]
#lim=raw_input("\nGenerate prime numbers up to what number? : ")
lim= int(num)
while pp<int(lim):
pp+=ss[0]
test=True
sqrtpp=sqrt(pp)
for a in tp:
if a>sqrtpp: break
if pp%a==0:
test=False
break
if test: tp.append(pp)
ep.reverse()
[tp.insert(0,a) for a in ep]
return tp
def main():
"""
"""
num= 2000000
ans= prime_list(num)
print("Sum of primes found between 2 and %d: %d" % (num, sum(ans)))
print("Found a total of %d primes." % len(ans))
if len(ans) <= 6:
print("Primes: %s" % str(ans))
else:
print("From %s... to ...%s" % (str(ans[:3]),ans[-3:]))
return 0
if __name__ == "__main__":
main()
| true
|
0cd3f80f80bed75176e9ca50eb0f928d73df4cc6
|
zw-999/learngit
|
/study_script/find_the_largest.py
| 481
| 4.21875
| 4
|
#!/usr/bin/env python
# coding=utf-8
import sys
def find_largest(file):
fi = open(file,"r")
for line in fi:
line = line.split()
print line
#fi.close()
#line = fi.readline()
largest = -1
for value in line.split():
v = int(value[:-1])
if v > largest:
largest = v
return largest
if __name__=='__main__':
file = '/home/ellen/learngit/aaa.txt'
test = find_largest(file)
print test
| true
|
1a2f875189437c1c09d34ece099de1858cdaa880
|
Kavitajagtap/Python3
|
/Day14.py
| 1,792
| 4.375
| 4
|
"""
1.Write a program to sort a list alphabetically in a dictionary
Enter dictionary = {1: ['B', 'C', 'A'], 2: ['D', 'B', 'A'], 3: ['V', 'A', 'K']}
Sorted list of dictionary = {1: ['A', 'B', 'C'], 2: ['A', 'B', 'D'], 3: ['A', 'K', 'V']}
"""
dict = {}
n = int(input("Enter elements: "))
for i in range(n):
k = int(input("key: "))
v = eval(input("value: "))
dict[k] = v
print("Dictionary =",dict)
new_dict = {k: sorted(v) for k, v in dict.items()}
print("Sorted list of dictionary =",new_dict)
------------------------------------------------------------------------------------------------------------
"""
2.Write a program to remove spaces from dictionary keys
Dictionary = {'a b c': 15, 'd e f': 30, 'g h i': 45}
new dictionary = {'abc': 15, 'def': 30, 'ghi': 45}
"""
dict = {}
n = int(input("Enter elements: "))
for i in range(n):
k = (input("key: "))
v = int(input("value: "))
dict[k] = v
print("Dictionary =",dict)
for key in dict:
k1 = key.replace(' ', '')
dict[k1] = dict.pop(key)
print("new dictionary =",dict)
--------------------------------------------------------------------------------------------------------------
"""
3.Write a program to get the key, value and item in a dictionary.
Dictionary = {'a': 10, 'b': 20, 'c': 30, 'd': 40}
key: a value: 10 item: ('a', 10)
key: b value: 20 item: ('b', 20)
key: c value: 30 item: ('c', 30)
key: d value: 40 item: ('d', 40)
"""
dict = {}
n = int(input("Enter elements: "))
for i in range(n):
k = (input("key: "))
v = int(input("value: "))
dict[k] = v
print("Dictionary =",dict)
for k, v in dict.items():
print('key:', k, 'value:', v, 'item:', (k, v))
----------------------------------------------------------------------------------------------------------------
| false
|
87424e37b3e029ddd8fcc1ccd752b23fc5864b33
|
Kavitajagtap/Python3
|
/Day8.py
| 1,852
| 4.59375
| 5
|
# 1.Write a program to create dictionary and access all elements with keys and values
dict = eval(input("Enter dictionary = "))
print("Accessing Elements from dictionary -->")
for key in dict:
print(key,dict[key])
'''
Output :
Enter dictionary = {'Apple':2017,'Microsoft':1985,'Facebook':2012,'Amazon':1997}
Accessing Elements from dictionary -->
Apple 2017
Microsoft 1985
Facebook 2012
Amazon 1997
'''
---------------------------------------------------------------------------------------------------
# 2.Write a Program to sort (ascending and descending) a dictionary by value.
dict = {}
n = int(input("Enter elements: "))
for i in range(n):
k = (input("key: "))
v = int(input("value: "))
dict[k] = v
print("dictionary =",dict)
print("sorted dictionary in ascending order =",sorted(dict.items(), key=lambda x: x[1]))
print("sorted dictionary in descending order =",sorted(dict.items(), key=lambda x: x[1],reverse = True))
'''
Output:
Enter elements: 4
key: a
value: 4
key: b
value: 1
key: c
value: 6
key: d
value: 3
dictionary = {'a': 4, 'b': 1, 'c': 6, 'd': 3}
sorted dictionary in ascending order = [('b', 1), ('d', 3), ('a', 4), ('c', 6)]
sorted dictionary in descending order = [('c', 6), ('a', 4), ('d', 3), ('b', 1)]
'''
------------------------------------------------------------------------------------------------------
# 3.Write a Program to add a key to a dictionary.
dict = eval(input("Enter dictionary:"))
key = input("key: ")
value = int(input("value: "))
dict.update({key:value})
print("updated dictionary =",dict)
'''
Output:
Enter dictionary:{'Apple':2017,'Microsoft':1985,'Facebook':2012}
key: Amazon
value: 1997
updated dictionary = {'Apple': 2017, 'Microsoft': 1985, 'Facebook': 2012, 'Amazon': 1997}
'''
-------------------------------------------------------------------------------------------------
| true
|
71432b142344cfa33686bf7bdcaeafb4f2d4b372
|
Kavitajagtap/Python3
|
/Day16.py
| 1,528
| 4.3125
| 4
|
"""
1. Write program to sort Counter by value.
Sample data : {'Math':81, 'Physics':83, 'Chemistry':87}
Expected data: [('Chemistry', 87), ('Physics', 83), ('Math', 81)]
"""
dict = {}
n = int(input("Enter elements: "))
for i in range(n):
k = (input("key: "))
v = int(input("value: "))
dict[k] = v
print("dictionary = ",dict)
print("Dictionary sorted by value = ")
print(sorted(dict.items(), key=lambda x: x[1], reverse=True))
------------------------------------------------------------------------------------------------------------
## 2. Write a program to create a dictionary from two lists without losing duplicate values.
l1 = []
num = int(input("First list\nlength of a list:"))
print("Enter elements of list:")
for i in range(num):
l1.append((input()))
l2 = []
num = int(input("Second list\nlength of a list:"))
print("Enter elements of list:")
for i in range(num):
l2.append(int(input()))
d = {l1[i]: l2[i] for i in range(len(l1))}
print("dictionary =",d)
------------------------------------------------------------------------------------------------------------
## 3. Write a program to replace dictionary values with their average.
dict = {}
n = int(input("Enter elements: "))
for i in range(n):
k = (input("key: "))
v = eval(input("value: "))
dict[k] = v
print("dictionary = ",dict)
d1 = {k:sum(v)/len(v) for k, v in dict.items()}
print("New dictionary =",d1)
------------------------------------------------------------------------------------------------------------
| true
|
b369a56787f0a1d15519d7e228ac7ef2ef6b849a
|
VolodymyrMeda/Twittmap
|
/json_navigator.py
| 1,646
| 4.1875
| 4
|
import json
def reading_json(file):
'''
str -> dict
Function reads json file
and returns dictionary
'''
with open(file, mode='r', encoding='utf-8') as rd:
json_read = json.load(rd)
return json_read
def json_navigation(json_read):
'''
Function navigates user in
json dictionary
'''
step_set = set()
for step in json_read:
step_set.add(step)
navigate = input('Enter one of the list words to go to the next '
'json step or enter 0 to go to the first stage '
'enter 1 to exit: \n' + str(step_set) + '\n')
if navigate == '1':
return quit()
elif navigate == '0':
return json_navigation(reading_json(file='json_api.json'))
elif navigate not in step_set:
print('You entered the wrong word! Try again')
return json_navigation(json_read)
elif navigate in step_set:
if type(json_read[navigate]) == dict:
print(str(json_read[navigate]) + ' - this is the result')
return json_navigation(json_read[navigate])
else:
print(str(json_read[navigate]) + ' - this is the final result')
stay = input('Enter 1 to quit or 0 to go to the first stage of json: ')
if stay == '1':
quit()
elif stay == '0':
return json_navigation(reading_json(file='json_api.json'))
else:
print('You entered the wrong word! Try again')
return json_navigation(json_read)
if __name__ == '__main__':
print(json_navigation(reading_json('json_api.json')))
| true
|
a75fa80c8412141fd7e8b28978b5a7f92643fbed
|
annmag/Student-manager
|
/generator_function.py
| 985
| 4.21875
| 4
|
# Generator function - a way of crating iterators (objects which you can iterate over)
# Creating generator - defining function with at least one yield statement (or more) instead of return statement
# Difference: return terminates a function entirely
# yield pauses the function saving all it's states and continues there on successive calls
# Once the function yields, the function is paused and the control is transferred to the caller
students = []
def read_students(file): # This is a generator function
for line in file: # For loop - to iterate over the file
yield line
def read_file():
try:
file = open("students.txt", "r")
for student in read_students(file): # For loop - to go through all the results from called function
students.append(student) # and add them to the list
file.close()
except Exception:
print("The file can't be read")
read_file()
print(students)
| true
|
0bd27accb7021db31fbfd540a9318d768adb366c
|
gokullogu/pylearn
|
/tutorial/list/add.py
| 550
| 4.25
| 4
|
#to add the the value to end of list use append
cars=["audi","bens","rolls royce"]
cars.append("bmw")
print(cars)
#['audi', 'bens', 'rolls royce', 'bmw']
#to append the list to the list use extend
fruit=["apple","mango","banana"]
veg=["carrot","beetroot","brinjal"]
fruit.extend(veg)
print(fruit)
#['apple', 'mango', 'banana', 'carrot', 'beetroot', 'brinjal']
#to append the set,tuples,dictionaries to list use extend
name=["john", "peter", "kenn"]
details=(18, "america")
name.extend(details)
print(name)
#['john', 'peter', 'kenn', 18, 'america']
| true
|
28080c6a55b1fc92494501d470c314beb176f11e
|
gokullogu/pylearn
|
/tutorial/tuple/access.py
| 1,044
| 4.4375
| 4
|
cars=("bmw","rolls royce","MG hector","tata tigor","audi","creta")
print(cars)
#('bmw', 'rolls royce', 'MG hector', 'tata tigor', 'audi', 'creta')
#second item
print(cars[1])
#rolls royce
#last item index -1
print(cars[-1])
#creta
print(cars[2:4])
#('MG hector', 'tata tigor')
print(cars[-5:-1])
#('rolls royce', 'MG hector', 'tata tigor', 'audi')
print(cars[-5:])
#('rolls royce', 'MG hector', 'tata tigor', 'audi', 'creta')
print(cars[4:5])
if "creta" in cars:
print("creta is in the tuple")
#we cannot directly add tuples
#they are immutable or unchangable
biketuple=("duke","shine","yamaha","apache")
print("\n","before change :",biketuple)
bikelist=list(biketuple)
bikelist[2]="fascino"
biketuple=tuple(bikelist)
print("after change :",biketuple)
#to delete item from tuple
mobiletuple=("lava","redmi","mi","samsung")
mobilelist=list(mobiletuple)
mobilelist.remove("lava")
mobiletuple=tuple(mobilelist)
print(mobiletuple)
#to delete the tuple
deltuple=("item1","item2","item3")
print(deltuple)
del deltuple
#print(deltuple)
| false
|
39f45bae07f632c715928a8237750ac70edafdef
|
gokullogu/pylearn
|
/tutorial/functions.py
| 1,287
| 4.21875
| 4
|
#creating functions
def my_fun():
print("hello world")
my_fun()
#hello world
#function with argument
def namefun(fname,lname):
print(fname+" "+lname)
namefun("gokul","L")
#gokul L
#namefun("gokul") will cause to error
#using argument tuple to get values
def namefun(*name):
print(name[2])
namefun("emil","john","britto")
#britto
#using keyword arguments child1,2,3
#if keyword arguments number known
#changing order will not change the value
def kname(child3,child1,child2):
print(child3)
kname(child1="emil",child2="tobias",child3="john")
#emil
#if number of keyword unknown
#uses dict of arguments
def kwname(**kid):
print("name is "+kid["fname"])
kwname(fname="tharun",lname="balaji")
#default parameter value
def country(countryname="India",state="Tamil Nadu"):
print("I am from ",state,",",countryname,".")
country("srilanka","kandy")
country()
#passing list as list
fruits=["apple","mango","pineapple"]
def my_fru(fruits):
for x in fruits:
print(x)
my_fru(fruits)
#function returns a statement
def my_ret(x):
return 5*x
print(my_ret(3))
#recursive function to print sum of 0 to 5
print("recursive function")
def rec_fun(k):
if(k>0):
x=k+rec_fun(k-1)
print(x)
else:
x=0
return x
rec_fun(5)
| false
|
50e3a4dbe8af7537d416e830a6882fcacf7fce1e
|
gokullogu/pylearn
|
/tutorial/list/remove.py
| 778
| 4.28125
| 4
|
#remove() removes item sepecified
fruit=["mango","orange","papaya"]
fruit.remove("mango")
print(fruit)
#['orange', 'papaya']
#pop() removes the list item at specified index
this_list=["john","19","poland"]
this_list.pop(1)
print(this_list)
#['john', 'poland']
#pop() removes the last item if unspecified
this_list1 = ["john", "19", "poland"]
this_list1.pop()
print(this_list1)
#['john', '19']
#del without index deletes the list completely
thislist2=["xenon","randon","zinc"]
del thislist2
#print(thislist2)
#NameError: name 'thislist2' is not defined
#del woth index delete the item at specified index
chem=["H2O","H2","OH"]
del chem[0]
print(chem)
#['H2', 'OH']
#clear method empties the list but do not delete it
lan=["c","cpp","java","python"]
lan.clear()
print(lan)
| true
|
33de33e1b694522a1ce35baf5777cab2ba132560
|
gokullogu/pylearn
|
/tutorial/tuple/loop.py
| 531
| 4.375
| 4
|
#loop through the tuple using for
fruit=("apple","banana","carrot","beetroot")
for x in fruit:
print(x)
#apple
#banana
#carrot
#beetroot
#loop through tuple using index numbers
print("for loop by index number:")
for i in range(len(fruit)):
print(i,"",fruit[i])
#for loop by index number:
#0 apple
#1 banana
#2 carrot
#while to loop through tuple using index
print("while loop by index number:")
i=0
while i <len(fruit):
print(i,"",fruit[i])
i+=1
#while loop by index number:
#0 apple
#1 banana
#2 carrot
| false
|
bff509e7057885d4a0c7e480c09a4605db36bcb8
|
ChadevPython/WeeklyChallenge
|
/2017/02-06-2017/EthanWalker/main.py
| 240
| 4.3125
| 4
|
#!/usr/bin/env python3
from reverse_str import reverse_line
import sys
#open file and get lines
with open(sys.argv[1], 'r') as in_file:
file = in_file.readlines()
# print reversed lines
for line in file:
print(reverse_line(line))
| true
|
9a63728319bc7a007e3edcc2acf916c0e32b988a
|
Arunken/PythonScripts
|
/2_Python Advanced/8_Pandas/10_Sorting.py
| 1,643
| 4.46875
| 4
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 21 14:30:07 2018
@author: SilverDoe
"""
'''
There are two kinds of sorting available in Pandas :
1. By Label
2. By Actual Value
'''
'''================== Sorting By Label ========================================'''
import pandas as pd
import numpy as np
unsorted_df = pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns = ['col2','col1'])
# based on row index
sorted_df=unsorted_df.sort_index(axis=0,ascending=True)# ascending order. # ascending is true by default,axis = 0 by default
print(sorted_df)
sorted_df = unsorted_df.sort_index(axis=0,ascending=False) # descending order
print(sorted_df)
#based on columns
sorted_df=unsorted_df.sort_index(axis=1,ascending=True)# ascending order
print(sorted_df)
sorted_df = unsorted_df.sort_index(axis=1,ascending=False) # descending order
print(sorted_df)
'''=================== Sorting By Value ======================================='''
'''
Like index sorting, sort_values() is the method for sorting by values. It accepts
a 'by' argument which will use the column name of the DataFrame with which the
values are to be sorted
'''
import pandas as pd
import numpy as np
unsorted_df = pd.DataFrame({'col1':[2,1,1,1],'col2':[1,3,2,4]})
# based on a specific column
sorted_df = unsorted_df.sort_values(by='col1')
print(sorted_df)
# based on multiple columns
sorted_df = unsorted_df.sort_values(by=['col1','col2'])
print(sorted_df)
# specifying sorting alorithm
sorted_df = unsorted_df.sort_values(by='col1' ,kind='mergesort') # mergesort, heapsort and quicksort
print(sorted_df)
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.