blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string | is_english
bool |
|---|---|---|---|---|---|---|---|
5d4fa6aaab3cc50ab1b67c9ab5add9ca49d2f25a
|
Ryandalion/Python
|
/Decision Structures and Boolean Logic/Roman Numeral Converter/Roman Numeral Converter/Roman_Numeral_Converter.py
| 1,269
| 4.21875
| 4
|
# Function converts a number to a roman numeral
userNum = int(input('Please enter a literal number between 1 ~ 10 you wish to convert to a Roman numeral: '));
if userNum < 0 or userNum > 10:
print('Please enter a number between 1 and 10');
else:
if userNum == 1:
print('I');
else:
if userNum == 2:
print('II');
else:
if userNum == 3:
print('III');
else:
if userNum == 4:
print('IV');
else:
if userNum == 5:
print('V');
else:
if userNum == 6:
print('VI');
else:
if userNum == 7:
print('VII');
else:
if userNum == 8:
print('VIII');
else:
if userNum == 9:
print('IX');
else:
if userNum == 10:
print('X');
| true
|
2b7ac8c5047791e80d7078a9f678b27c0c79d997
|
Ryandalion/Python
|
/Lists and Tuples/Larger than N/Larger than N/Larger_than_N.py
| 1,752
| 4.3125
| 4
|
# Program generates a list via random generation and compares it to a user input number n which will determine if the elements within the last are greater than the number
import random; # Import the random module to generate a random integer
def main():
randNum = [0] * 10; # Intialize list with 10 elements of zero
for x in range(10): # Loop 10 times
randNum[x] = random.randint(0,10); # Generate a random number between 0 and 10
x+=1; # Increment x by one
userNum = int(input("Please enter a number: ")); # Get the user's number they wish to compare to the elements of the list
print(randNum); # Print list for verification purposes
numGreater = compareNum(randNum, userNum); # Send the list and the user number to the numGreater function to be evaluated
print("There are",numGreater,"numbers greater than",userNum); # Print the results that were returned by the compare function
def compareNum(userList, userNum): # Function will compare the elements in the list to the user specified number. It will calculate the number of elements that are greater than the user number
numGreater = 0; # Create a numGreater variable to hold the number of elements that are greater than the user specified number
for x in range(len(userList)): # Loop through the length of the list
if userNum < userList[x]: # If list element is greater than user number execute
numGreater += 1; # Increase the numGreater variable by one
x += 1; # Increase the counter variable
else: # If userNum is greater than the list element
x +=1; # Increase x by one
return numGreater; # Return the results to the caller
print("Larger than N\n")
main(); # Execute main
| true
|
daee14c84fcbbe19529eae9f874083297fc67493
|
run-fourest-run/PythonDataStructures-Algos
|
/Chapter 3 - Python Data Types and Structures/Sets.py
| 2,216
| 4.125
| 4
|
'''
Sets are unordered collection of unique items. Sets are mutable, but the elements inside of them are immutable.
* Important distinctions is that the cannot contain duplicate keys
* Sets are typically used to perform mathmatical operations such as intersection, union, difference and complement.
Unlike sequence types, set types do not provide any indexing or slicing operations. There are also no keys associated with values.
'''
player_list = ['alex','spencer','don','don']
cod_players = set(player_list)
'''
Methods and operations:
'''
#len(s)
#length
length = len(cod_players)
#s.copy()
#copy
copy = cod_players.copy()
#s.add()
#add
copy.add('ryan')
#s.difference(t)
#difference --> returns all items in s but not in t
difference = cod_players.difference(copy)
#s.intersection(t)
#intersections --> returns a set of all items in both t and s
intersection = cod_players.intersection(copy)
#s.isdisjoint(t)
#is disjoint --> Returns True if S and t have no items in common
isdisjoint = cod_players.isdisjoint(copy)
#s.issubset(t)
# is subset --> Returns True if all items in s are also in t
subset = cod_players.issubset(copy)
#s.issuperset(t)
# is superset --> Returns True if all items in t are also in s
superset = cod_players.issuperset(copy)
#s.union(t)
# union --> returns a set of all items in s or t
union = cod_players.union(copy)
'''Mutable set object methods '''
#s.add(item)
#add
cod_players.add('doug')
#s.clear()
#clear
copy_cod_players = cod_players.copy()
copy_cod_players.clear()
#s.difference_update(t)
#difference update --? removes all items in s that are also in t
cod_players.difference_update(['spencer','alex'])
#s.discard(item)
#discard --> remove item from set
cod_players.discard('doug')
#s.intersection_update(t)
#intersection update --> removes all items from s that are not in the intersection of s and t
cod_players.intersection_update(['alex'])
#s.pop
#pop --> returns and removes
cod_players.pop('don')
#s.symetric_difference_updater
#symeteric difference updater --> removes all items from s that are not in the symettric difference of s and t (no idea what the fuck that means)
cod_players.symmetric_difference_update(['dontknow'])
| true
|
90e9a6e867b5601d2ce5fc2ed648d980eb904b17
|
PWalis/Intro-Python-I
|
/src/10_functions.py
| 495
| 4.28125
| 4
|
# Write a function is_even that will return true if the passed-in number is even.
# YOUR CODE HERE
def is_even(n):
if n % 2 == 0:
return True
else:
return False
print(is_even(6))
# Read a number from the keyboard
num = input("Your number here")
num = int(num)
# Print out "Even!" if the number is even. Otherwise print "Odd"
# YOUR CODE HERE
def even_odd():
global num
if num % 2 == 0:
return 'Even'
else:
return 'Odd'
print(even_odd())
| true
|
ad0017b73937ba9313620bfc23101a2502707321
|
Sumanthsjoshi/capstone-python-projects
|
/src/get_prime_number.py
| 728
| 4.125
| 4
|
# This program prints next prime number until user chooses to stop
# Problem statement: Have the program find prime numbers until the user chooses
# to stop asking for the next one.
# Define a generator function
def get_prime():
num = 3
yield 2
while True:
is_prime = True
for j in range(3, num, 2):
if num % j == 0:
is_prime = False
if is_prime:
yield num
num += 2
# Initialize a generator instance
g = get_prime()
# Get the user input
while True:
inp = input("Press enter to get next prime number(Enter any key to stop)")
if not inp:
print(next(g))
else:
print("Stopping the prime generator!!")
break
| true
|
8c99ba43d3481a6190df22b51b93d2d94358f68c
|
abhic55555/Python
|
/Assignments/Assignment2/Assignment2_3.py
| 440
| 4.15625
| 4
|
def factorial(value1):
if value1 > 0:
factorial = 1
for i in range(1,value1 + 1):
factorial = factorial*i
print("The factorial of {} is {}".format(value1,factorial))
elif value1==0:
print("The factorial of 0 is 1 ")
else:-
print("Invalid number")
def main():
value1 = int(input("Enter first number : "))
factorial(value1)
if __name__ == "__main__":
main()
| true
|
6b89934c7911e7f1c24db7c739b46eb26050297c
|
Tyler668/Code-Challenges
|
/twoSum.py
| 1,018
| 4.1875
| 4
|
# # Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
# # (i.e., [0, 1, 2, 4, 5, 6, 7] might become[4, 5, 6, 7, 0, 1, 2]).
# # You are given a target value to search. If found in the array return its index, otherwise return -1.
# # You may assume no duplicate exists in the array.
# # Your algorithm's runtime complexity must be in the order of O(log n).
# # Example 1:
# # Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 0
# # Output: 4
# # Example 2:
# # Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 3
# # Output: -1
# def search(nums, target):
# mid = len(nums) // 2
# # print(mid, nums[mid])
# if nums[mid] == target:
# return mid
# elif nums[mid] > target:
# lowerHalf
# nums = [4, 5, 6, 7, 0, 1, 2, 19]
# target = 0
# print(search(nums, target))
def double_char(txt):
solution = ''
for i in range(len(txt)):
double = 2 * txt[i]
solution += double
return solution
print(double_char("Hello"))
| true
|
15be302b0b417de9eb462b731ad20a0d78e448d8
|
SaiJyothiGudibandi/Python_CS5590-490-0001
|
/ICE/ICE1/2/Reverse.py
| 328
| 4.21875
| 4
|
num = int(input('Enter the number:')) #Taking nput from the user
Reverse = 0
while(num > 0): #loop to check whether the number is > 0
Reminder = num%10 # finding the reminder for number
Reverse = (Reverse * 10) + Reminder
num = num // 10
print('Reverse for the Entered number is:%d' %Reverse)
| true
|
684dba9a9265b5867782ca23dd12e646972bf8b8
|
lorinatsumi/lista3
|
/ex2.py
| 496
| 4.1875
| 4
|
#1 Escreva um algoritmo que permita a leitura das notas de uma turma de 5 alunos, armazenando os dados numa lista. Depois calcule a média da turma e conte quantos alunos obtiveram nota acima desta média calculada. Escrever a média da turma e o resultado da contagem.
notas = []
for i in range(5):
nota=int(input("Digite sua nota: "))
notas.append(nota)
print (notas)
soma = 0
for nota in notas:
soma = (soma + nota)
media = soma / 5
print ("A média da turma é: " + str(media))
| false
|
bb0b85fbe5e9fe5c3e05dfb28f35feba48e2d0d7
|
jarturomora/learningpython
|
/ex16bis.py
| 834
| 4.28125
| 4
|
from sys import argv
script, filename = argv
# Opening the file in "read-write" mode.
my_file = open(filename, "rw+")
# We show the current contents of the file passed in filename.
print "This is the current content of the file %r." % filename
print my_file.read()
print "Do you want to create new content for this file?"
raw_input("(hit CTRL-C if you don't or hit RETURN if you do) >")
# In order to truncate the file we move the pointer to the first line.
my_file.seek(0)
my_file.truncate()
print "\nThe file %r was deleted..." % filename
print "\nWrite three lines to store in the file %r" % filename
line1 = raw_input("Line 1: ")
line2 = raw_input("Line 2: ")
line3 = raw_input("Line 3: ")
my_file.write(line1 + "\n" + line2 + "\n" + line3 + "\n")
my_file.close()
print "The new contents for %r has been saved." % filename
| true
|
8e81b8f7d46c6257d8a6dbabfd677297149148be
|
jarturomora/learningpython
|
/ex44e.py
| 863
| 4.15625
| 4
|
class Other(object):
def override(self):
print "OTHER override()"
def implicit(self):
print "OTHER implicit()"
def altered(self):
print "OTHER altered()"
class Child(object):
def __init__(self):
self.other = Other() # The composition begins here
# where Child has-a other
def implicit(self):
self.other.implicit() # Call to the implicit() method of
# Child's 'other' instance.
def override(self):
print "CHILD override()"
def altered(self):
print "CHILD BEFORE OTHER altered()"
self.other.altered() # Call to the altered() method of 'other' object.
print "CHILD AFTER OTHER altered()"
son = Child()
son.implicit() # Call to the method "composed" from "Other" class.
son.override()
son.altered()
| true
|
01ce27d5d65b55566cccded488d1c99d2fd848b0
|
dablackwood/my_scripts_project_euler
|
/specific_solutions/project_euler_019.py
| 1,079
| 4.1875
| 4
|
"""
You are given the following information, but you may prefer to do some
research for yourself.
* 1 Jan 1900 was a Monday.
* Thirty days has September,
April, June and November.
All the rest have thirty-one,
Saving February alone,
Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
* A leap year occurs on any year evenly divisible by 4, but not on a
century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century
(1 Jan 1901 to 31 Dec 2000)?
"""
day = 2
tally = 0
months_common = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
months_leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for year in xrange(1901, 2001):
#print
print year,
if year % 4 == 0:
months_current = months_leap
else:
months_current = months_common
for month in xrange(0, 12):
#print day, day % 7,
if day % 7 == 0:
tally = tally + 1
day = day + months_current[month]
print tally
print "*", tally
| true
|
159b7422dc21ca5c01cec91b1c27ee3a88b08ca1
|
dablackwood/my_scripts_project_euler
|
/specific_solutions/project_euler_029a.py
| 759
| 4.15625
| 4
|
"""
Consider all integer combinations of a^(b) for 2<=a<=5 and 2<=b<=5:
2^(2)=4, 2^(3)=8, 2^(4)=16, 2^(5)=32
3^(2)=9, 3^(3)=27, 3^(4)=81, 3^(5)=243
4^(2)=16, 4^(3)=64, 4^(4)=256, 4^(5)=1024
5^(2)=25, 5^(3)=125, 5^(4)=625, 5^(5)=3125
If they are then placed in numerical order, with any repeats removed, we get
the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by a^(b) for 2<=a<=100
and 2<=b<=100?
"""
max_a_b = input("Max for 'a' and 'b': ")
big_list = []
for a in xrange(2, max_a_b + 1):
for b in xrange(2, max_a_b + 1):
if big_list.count(a ** b) == 0:
big_list.append(a ** b)
print len(big_list)
| true
|
627e26b857e77b466da042acef1737e3d0816d1e
|
shaziya21/PYTHON
|
/zip.py
| 349
| 4.25
| 4
|
# if we want to join two list or tuple or set or dict we'll use zip
names = ('shaz','naaz','chiku')
comps = ('apple','hp','asus')
zipped = list(zip(names,comps))
print(zipped)
# or we can use loop to iterate like
names = ('shaz','naaz','chiku')
comps = ('apple','hp','asus')
zipped = list(zip(names,comps))
for (a,b) in zipped:
print(a,b)
| false
|
73980da3c813213a81f11db877458ff72c0a47b7
|
shaziya21/PYTHON
|
/constructor_in_inheritance.py
| 732
| 4.1875
| 4
|
class A: # Parent class / Super class
def __init__(self): # Constructor of parent class A
print("in A init")
def feature1(self):
print("feature1 is working")
def feature2(self):
print("feature2 is working")
class B(A):
def __init__(self):
super().__init__() # jump up to super class A executes it thn jump back to B and thn execute it.
print("in B init")
def feature3(self):
print("feature3 is working")
def feature4(self):
print("feature4 is working")
a1 = B()
# when you create object of sub class it will call init of sub class first.
# if you have ccall super then it will first call init of super class thn call init of sub class.
| true
|
6ffafcc1da316699df44275889ffab8ba957265f
|
shaziya21/PYTHON
|
/MRO.py
| 1,004
| 4.4375
| 4
|
class A: # Parent class / Super class
def __init__(self): # Constructor of parent class A
print("in A init")
def feature1(self):
print("feature 1-A is working")
def feature2(self):
print("feature2 is working")
class B:
def __init__(self): # Constructor of class B
print("in B init")
def feature1(self):
print("feature 1-B is working")
def feature4(self):
print("feature4 is working")
class C(A,B): # C is inheriting both from A & B
def __init__(self):
super().__init__() # Constructor of parent class A
print("in C init")
def feature5(self):
print("feature5 is working")
def feat(self):
super().feature2() # super method is used to call other method as well not just init
a1 = C() # it will give output for C & A only coz in multiple inheritance
a1.feature1() # it starts from left to right
a1.feat() # to represent super class we use super method.
| true
|
1e870f6429ff8f0b0cde4f40b7d0f3e148242257
|
JoshiDivya/PythonExam
|
/Pelindrome.py
| 354
| 4.3125
| 4
|
def is_pelindrome(word):
word=word.lower()
word1=word
new_str=''
while len(word1)>0:
new_str=new_str+ word1[-1]
word1=word1[:-1]
print(new_str)
if (new_str== word):
return True
else:
return False
if is_pelindrome(input("Enter String >>>")):
print("yes,this is pelindrome")
else:
print("Sorry,this is not pelindrome")
| true
|
2dd93300d7ede7b2fd78a925eeea3d912ae55c51
|
dhaffner/pycon-africa
|
/example1.py
| 408
| 4.53125
| 5
|
# Example #1: Currying with inner functions
# Given a function, f(x, y)...
def f(x, y):
return x ** 2 + y ** 2
# ...currying constructs a new function, h(x), that takes an argument
# from X and returns a function that maps Y to Z.
#
# f(x, y) = h(x)(y)
#
def h(x):
def curried(y):
return f(x, y)
return curried
fix10 = h(10)
for y in range(10):
print(f'fix10({y}) = {fix10(y)}')
| true
|
b86300067afe20ac6d3661a4d8a6b85446b57512
|
Yaambs18/python-bootcamp
|
/Day3/Ineheritance.py
| 1,251
| 4.15625
| 4
|
#Multilevel Inheritance
class Base():
def __init__(self, name):
self.name = name
def getName(self):
return self.name
class Child(Base):
def __init__(self, name, age):
Base.__init__(self, name)
self.age = age
def getAge(self):
return self.age
class GrandChild(Child):
def __init__(self, name, age, address):
Child.__init__(self, name, age)
self.address = address
def getAddress(self):
return self.address
m = GrandChild("Yansh", 1, "Aligarh")
print(m.getName(), m.getAge(), m.getAddress())
#Mutiple inheritance
class Addition():
def __init__(self):
print("addition")
def Addition(self,a,b):
return a+b;
def func(self):
print("this method is of addition class")
class Mulultiplication():
def __init__(self):
print("multiplication")
def Multiplication(self,a,b):
return a*b
def m1(self):
print("this method is of multipication class")
class Division(Addition, Mulultiplication):
def __init__(self):
print("divide")
def Divide(self,a,b):
return a/b;
divide_ = Division()
print(divide_.Addition(10,20))
print(divide_.Multiplication(10,20))
print(divide_.Divide(10,20))
divide_.m1()
| false
|
a93f8e9ac02ba81adbd2b0ead5aa0a2af11d6011
|
egill12/pythongrogramming
|
/P3_question4.py
| 842
| 4.625
| 5
|
'''
Write a program that asks the user for a long string containing multiple words.
Echo back to the user the same string, except with the words in backwards order.
For example, say we type the string:
My name is Michele
Then we would expect to see the string:
Michele is name My
'''
def reverse_str(string):
'''
Write a program that asks the user for a long string containing multiple words.
Echo back to the user the same string, except with the words in backwards order.
:param string:
:return:
'''
broken_string = string.split()
reversed_string = []
for element in reversed(broken_string):
reversed_string.append(element)
return reversed_string
string = str(input("please give str:"))
reversed_string = reverse_str(string)
for element in reversed_string:
print(element, end = " " )
| true
|
fc044bef4295e8e85313366be4a89689938756c2
|
BjornChrisnach/Basics_of_Computing_and_Programming
|
/days_traveled.py
| 233
| 4.125
| 4
|
print("Please enter the number of days you traveled")
days_traveled = int(input())
full_weeks = days_traveled // 7
remaining_days = days_traveled % 7
print(days_traveled, "days are", full_weeks, "weeks and",\
remaining_days,"days")
| true
|
386917245b7e7130aa3a96abccf9ca35842e1904
|
getachew67/UW-Python-AI-Coursework-Projects
|
/Advanced Data Programming/hw2/hw2_pandas.py
| 2,159
| 4.1875
| 4
|
"""
Khoa Tran
CSE 163 AB
This program performs analysis on a given Pokemon data file,
giving various information like average attack levels for a particular type
or number of species and much more. This program immplements the panda
library in order to compute the statistics.
"""
def species_count(data):
"""
Returns the number of unique species in the
given file
"""
result = data['name'].unique()
return len(result)
def max_level(data):
"""
Returns a tuple with the name and level of the Pokemon
that has the highest level
"""
index = data['level'].idxmax()
result = (data.loc[index, 'name'], data.loc[index, 'level'])
return result
def filter_range(data, low, high):
"""
Returns a list of Pokemon names having a level that is
larger or equal to the lower given range and less than
the higher given range
"""
temp = data[(data['level'] >= low) & (data['level'] < high)]
return list(temp['name'])
def mean_attack_for_type(data, type):
"""
Returns the average attack for all Pokemon
in dataset with the given type
Special Case: If the dataset does not contain the given type,
returns 'None'
"""
temp = data.groupby('type')['atk'].mean()
if type not in temp.index:
return None
else:
return temp[type]
def count_types(data):
"""
Returns a dictionary of Pokemon with the types
as the keys and the values as the corresponding
number of times that the type appears in the dataset
"""
temp = data.groupby('type')['type'].count()
return dict(temp)
def highest_stage_per_type(data):
"""
Returns a dictionary with the key as the type of
Pokemon and the value as the highest stage reached for
the corresponding type in the dataset
"""
temp = data.groupby('type')['stage'].max()
return dict(temp)
def mean_attack_per_type(data):
"""
Returns a dictionary with the key as the type of Pokemon
and the value as the average attack for
the corresponding Pokemon type in the dataset
"""
temp = data.groupby('type')['atk'].mean()
return dict(temp)
| true
|
5d01d82bfd16634be636cce2cf2e1d31ea7208b1
|
Razorro/Leetcode
|
/88. Merge Sorted Array.py
| 1,353
| 4.28125
| 4
|
"""
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
No other tricks, just observation.
执行用时: 68 ms, 在Merge Sorted Array的Python3提交中击败了8.11% 的用户
内存消耗: 13.1 MB, 在Merge Sorted Array的Python3提交中击败了0.51% 的用户
Although the result is not so well, but I think there is no big difference with other solutions.
"""
class Solution:
def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
"""
Do not return anything, modify nums1 in-place instead.
"""
idx1, idx2 = m - 1, n - 1
fillIdx = len(nums1) - 1
while idx1 >= 0 and idx2 >= 0:
if nums1[idx1] > nums2[idx2]:
nums1[fillIdx] = nums1[idx1]
idx1 -= 1
else:
nums1[fillIdx] = nums2[idx2]
idx2 -= 1
fillIdx -= 1
while idx2 >= 0:
nums1[fillIdx] = nums2[idx2]
idx2 -= 1
fillIdx -= 1
| true
|
2cd13056f72eaf8f16e342bacde6c9b17bd43d3b
|
Razorro/Leetcode
|
/49. Group Anagrams.py
| 863
| 4.125
| 4
|
"""
Description:
Given an array of strings, group anagrams together.
Example:
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
["ate","eat","tea"],
["nat","tan"],
["bat"]
]
Note:
All inputs will be in lowercase.
The order of your output does not matter.
Runtime: 152 ms, faster than 39.32% of Python3 online submissions for Group Anagrams.
Memory Usage: 15.5 MB, less than 100.00% of Python3 online submissions for Group Anagrams.
Not very fast, but I guess all the answer comply the rule:
Make unique hash value of those same anagrams.
"""
class Solution:
def groupAnagrams(self, strs: 'List[str]') -> 'List[List[str]]':
import collections
h = collections.defaultdict(list)
for s in strs:
h[''.join(sorted(s))].append(s)
return list(h.values())
return list(collectorDict.values())
| true
|
d2d6f21556955a4b8ec8893b8bf03e7478032b68
|
Razorro/Leetcode
|
/7. Reverse Integer.py
| 817
| 4.15625
| 4
|
"""
Description:
Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1].
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
"""
""" Analysis:
Easy...
Nope... forget to deal with overflow
"""
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
flag = x < 0
constant = 2**31
x = abs(x)
x = str(x)
x = x[::-1]
x = int(x)
if flag:
x = -x if x <= constant else 0
else:
x = x if x <= constant-1 else 0
return x
if __name__ == '__main__':
testCase = [
]
| true
|
92b2ac96f202ac222ccd4b9572595602abf0a459
|
jrahman1988/PythonSandbox
|
/myDataStruct_CreateDictionaryByFilteringOutKeys.py
| 677
| 4.34375
| 4
|
'''
A dictionary is like an address-book where we can find the address or contact details of a person by knowing only his/her name
i.e. we associate keys (name) with values
Dictionary is represented by dict class. Pair of keys and values are specified in dictionary using the notation
d = {key1 : value1, key2 : value2 }
When we need to create a dictionary from a dictionary by filtering specific keys
'''
# Single dictionary, from here will create another dictionary by filtering out keys 'a' and 'c':
d1 = {"c": 3, "a": 1, "b": 2, "d": 4}
filter_list = ["a", "c"]
d11 = dict((i, d1[i])
for i in filter_list if i in d1)
print("Type of d11: ", type(d11))
print(d11)
| true
|
1a4d781b35cfbb98acbc1b8b9fad8aa9a78c51ac
|
jrahman1988/PythonSandbox
|
/myPandas_DescriptiveStatistics.py
| 1,754
| 4.40625
| 4
|
'''
A large number of methods collectively compute descriptive statistics and other related operations on DataFrame.
Most of these are aggregations like sum(), mean(), but some of them, like sumsum(), produce an object of the same size.
Generally speaking, these methods take an axis argument, just like ndarray.{sum, std, ...}, but the axis can be specified by name or integer
'''
import pandas as pd
desired_width=320
pd.set_option('display.width', desired_width)
pd.set_option('display.max_columns',100)
#Read the pokemon_data.csv from the file system and transform into a DataFrame using read_csv() method
df = pd.read_csv("~/Desktop/Learning/Sandbox/PythonSandbox/Data/pokemon_data.csv")
#Output statistics of all data in the file using describe() method
print("\nOutput all basic statistics using describe(): \n", df.describe())
#Sort output using sort_values() method (default is ascending order)
print("\nOutput sorted data based on the column named 'Name': \n", df.sort_values('Name'))
#Sorting based on a single column in a file and output using sort_values() method (descending order - ascending=false)
print("\nOutput sorted data based on the column named 'Name' in descending order: \n", df.sort_values('Name', ascending=False))
#Sorting based on a multiple columns in a file and output using sort_values() method ('Name' column in ascending order and 'HP' column in descending order)
print("\nOutput sorted data based multiple columns 'Name' and 'HP' one in ascending and other in descending order: \n", df.sort_values(['Name', 'HP'], ascending=[1,0]))
#Summing the values in the columns of a DF using sum(axis) where axis = 0 is vertical and 1= horizontal
print("\nSum of the values in column with index 1 of the DF :\n", df.sum(1))
| true
|
f45471a04eef4398d02bbe12151a6b031b394452
|
jrahman1988/PythonSandbox
|
/myFunction_printMultipleTimes.py
| 427
| 4.3125
| 4
|
'''
Functions are reusable pieces of programs. They allow us to give a name to a block of statements, allowing us to run that block
using the specified name anywhere in your program and any number of times. This is known as calling the function.
'''
def printMultipleTimes(message:str, time:int):
print(message * time)
#Call the functions by passing parameters
printMultipleTimes("Hello ",2)
printMultipleTimes("Hello ",5)
| true
|
b2965c970bce71eee39841548b95ab6edf37d99b
|
jrahman1988/PythonSandbox
|
/myLambdaFunction.py
| 1,212
| 4.125
| 4
|
'''
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Syntax
lambda arguments : expression
'''
#define the lambda function
sentence = "I bought a bike, from a bike store, she bought a bike from amazon, they bought a bike from bike stores"
myLambdaFunction = lambda argument: argument.count("bike")
#here we are calling the lambda function: passing the 'sentence' as parameter and lamda function is taking it as an 'argument'
print("Total number of 'bike' word appeared = ", myLambdaFunction(sentence))
# filePath = "~/Desktop/Learning/Sandbox/PythonSandbox/Data/README.md"
# readFile=open('~/Desktop/Learning/Sandbox/PythonSandbox/Data/README.md', 'r')
with open('/home/jamil/Desktop/Learning/Sandbox/PythonSandbox/Data/README.md') as f:
readFile = f.readlines()
print (readFile)
print(readFile.count("Spark"))
sparkAppeared = lambda s: s.count("Spark")
apacheAppeared = lambda s: s.count("Apache")
hadoopAppeared = lambda s: s.count("Hadoop")
print("Spark word appeared = ", sparkAppeared(readFile))
print("Apache word appeared = ", apacheAppeared(readFile))
print("Hadoop word appeared = ", hadoopAppeared(readFile))
| true
|
76e7dc6bfa340596459f1a535e4e2e191ea483bc
|
jrahman1988/PythonSandbox
|
/myOOPclass3.py
| 2,017
| 4.46875
| 4
|
'''
There is way of organizing a software program which is to combine data and functionality and wrap it inside something called an object.
This is called the object oriented programming paradigm.
In this program we'll explore Class, behaviour and attributes of a class
'''
#Declaring a class named Mail and its methods (behaviours). All methods of a class must have a default parameter 'self'
class Mail():
#Class variable to count 'how many' types of Mail instances created
numberOfObjectsCreated = 0
#Init method to create an instance (object) by passing an object name
def __init__(self, name):
"""Initilializes the data"""
self.name = name
print("Initializing an {}".format(self.name))
Mail.numberOfObjectsCreated +=1
def destinationOfMail(self, type: str):
self.type = type
def costOfMail(self, cost: int):
self.cost = cost
def sizeOfmail(self, size: int):
self.size = size
def getDescription(self):
print("The type of the mail is ", self.type)
print("The cost of the mail is ", self.cost)
print("The size of the mail is ", self.size)
@classmethod
def countOfMail(count):
"""Prints number of Mail objects"""
print("Created objects of Mail class are = {}".format(count.numberOfObjectsCreated))
#Create an object of the class Mail named domesticMail
dMail = Mail("domesticMail")
dMail.destinationOfMail("Domestic")
dMail.costOfMail(10)
dMail.sizeOfmail("Large")
dMail.getDescription()
#Create an object of the class Mail named internationalMail
iMail = Mail("internationalMail")
iMail.destinationOfMail("International")
iMail.costOfMail(99)
iMail.sizeOfmail("Small")
iMail.getDescription()
#How many Mail objects were created (here we are using class variable 'numberOfObjectsCreated'
print("Total Mail objects created = {} ".format(Mail.numberOfObjectsCreated))
#How many Mail objects were created (here we are using class method 'countOfMail()'
Mail.countOfMail()
| true
|
cf3158ef73377ac7fe644d4637c21ae1501d804b
|
jrahman1988/PythonSandbox
|
/myStringFormatPrint.py
| 551
| 4.25
| 4
|
#Ways to format and print
age: int = 20
name: str = "Shelley"
#Style 1 where format uses indexed parameters
print('{0} was graduated from Wayne State University in Michigan USA when she was {1}'.format(name,age))
#Style 2 where 'f' is used as f-string
print(f'{name} was graduated from Wayne State University in Michigan USA when she was {age}')
#Style 3 where format's parameters can mbe changed as local variable
print('{someOne} was graduated from Wayne State University in Michigan USA when she was {someAge}'.format(someOne=name,someAge=age))
| true
|
34653fdfffaacb579ad87ee2d590c6ae37c5bb71
|
mimipeshy/pramp-solutions
|
/code/drone_flight_planner.py
| 1,903
| 4.34375
| 4
|
"""
Drone Flight Planner
You’re an engineer at a disruptive drone delivery startup and your CTO asks you to come up with an efficient algorithm that calculates
the minimum amount of energy required for the company’s drone to complete its flight.
You know that the drone burns 1 kWh (kilowatt-hour is an energy unit) for every mile it ascends, and it gains 1 kWh for every mile it descends.
Flying sideways neither burns nor adds any energy.
Given an array route of 3D points, implement a function calcDroneMinEnergy that computes and returns the minimal amount of energy the drone would need
to complete its route. Assume that the drone starts its flight at the first point in route. That is, no energy was expended to place the drone at the starting point.
For simplicity, every 3D point will be represented as an integer array whose length is 3.
Also, the values at indexes 0, 1, and 2 represent the x, y and z coordinates in a 3D point, respectively.
input: route = [ [0, 2, 10],
[3, 5, 0],
[9, 20, 6],
[10, 12, 15],
[10, 10, 8] ]
output: 5 # less than 5 kWh and the drone would crash before the finish
# line. More than `5` kWh and it’d end up with excess e
"""
# O(n) time
# O(1) space
def calc_drone_min_energy(route):
energy_balance = 0
energy_deficit = 0
prev_altitude = route[0][2]
for i in range(1, len(route)):
curr_altitude = route[i][2]
energy_balance += prev_altitude - curr_altitude
if energy_balance < 0:
energy_deficit += abs(energy_balance)
energy_balance = 0
prev_altitude = curr_altitude
return energy_deficit
def calc_drone_min_energy(route):
max_altitude = route[0][2]
for i in range(1, len(route)):
if route[i][2] > max_altitude:
max_altitude = route[i][2]
return max_altitude - route[0][2]
| true
|
dd9c666ab17a5afeb3e6c0fa1bdd1b27bb7f78ce
|
CSC1-1101-TTh9-S21/lab-week3
|
/perimeter.py
| 594
| 4.3125
| 4
|
# Starter code for week 3 lab, parts 1 and 2
# perimeter.py
# Prof. Prud'hommeaux
# Get some input from the user.
a=int(input("Enter the length of one side of the rectangle: "))
b=int(input("Enter the length of the other side of the rectangle: "))
# Print out the perimeter of the rectangle
c = a + a + b + b
print("The perimeter of your rectangle is: ", c)
# Part 1: Rewrite this code so that it gets the sides from
# command line arguments (i.e., Run... Customized)
# Part 2: Rewrite this code so that there are two functions:
# a function that calculates the perimeter
# a main function
| true
|
abdff8d3bf6c1e1cc39a24519587e5760294bdc6
|
arkiz/py
|
/lab1-4.py
| 413
| 4.125
| 4
|
studentName = raw_input('Enter student name.')
creditsDegree = input('Enter credits required for degree.')
creditsTaken = input('Enter credits taken so far.')
degreeName = raw_input('Enter degree name.')
creditsLeft = (creditsDegree - creditsTaken)
print 'The student\'s name is', studentName, ' and the degree name is ', degreeName, ' and There are ', creditsLeft, ' credits left until graduation.'
| true
|
517f231a66c9d977bc5a34eaa92b6ad986a8e340
|
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
|
/Module-3/3-1-2-12-Python-loops-else-The-while-loop-and-the-else-branch.py
| 356
| 4.15625
| 4
|
#!/usr/bin/python3
"""
Both loops, while and for, have one interesting (and rarely used) feature.
As you may have suspected, loops may have the else branch too, like ifs.
The loop's else branch is always executed once,
regardless of whether the loop has entered its body or not.
"""
i = 1
while i < 5:
print(i)
i += 1
else:
print("else:", i)
| true
|
6920b44453655be0855b3977c12f2ed33bdb0bc3
|
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
|
/Module-4/4-1-3-10-LAB-Converting-fuel-consumption.py
| 1,432
| 4.4375
| 4
|
#!/usr/bin/python3
"""
A car's fuel consumption may be expressed in many different ways. For example,
in Europe, it is shown as the amount of fuel consumed per 100 kilometers.
In the USA, it is shown as the number of miles traveled by a car using one
gallon of fuel.
Your task is to write a pair of functions converting l/100km into mpg, and
vice versa.
The functions:
are named l100kmtompg and mpgtol100km respectively;
take one argument (the value corresponding to their names)
Complete the code in the editor.
Run your code and check whether your output is the same as ours.
Here is some information to help you:
1 American mile = 1609.344 metres;
1 American gallon = 3.785411784 litres.
Test Data
Expected output:
60.31143162393162
31.36194444444444
23.52145833333333
3.9007393587617467
7.490910297239916
10.009131205673757
"""
def l100kmtompg(liters):
"""
100000 m * 3.785411784 l [ mi ]
________________________ ________
1609.344 m * liters [ g ]
"""
return ((100000*3.785411784)/(1609.344*liters))
def mpgtol100km(miles):
"""
100000 m * 3.785411784 l [ l ]
________________________ _________
1609.344 m * miles [ 100Km ]
"""
return ((100000*3.785411784)/(1609.344*miles))
print(l100kmtompg(3.9))
print(l100kmtompg(7.5))
print(l100kmtompg(10.))
print(mpgtol100km(60.3))
print(mpgtol100km(31.4))
print(mpgtol100km(23.5))
| true
|
c9bedff4032b89fbd4054b4f03093af06a3d01d0
|
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
|
/Module-2/2-1-4-10-LAB-Operators-and-expressions.py
| 567
| 4.5625
| 5
|
#!/usr/bin/python3
"""
Take a look at the code in the editor: it reads a float value,
puts it into a variable named x, and prints the value of a variable named y.
Your task is to complete the code in order to evaluate the following
expression:
3x3 - 2x2 + 3x - 1
The result should be assigned to y.
"""
x = 0
x = float(x)
y = 3 * x ** 3 - 2 * x ** 2 + 3 * x - 1
print('x =', x, ' y =', y)
x = 1
x = float(x)
y = 3 * x ** 3 - 2 * x ** 2 + 3 * x - 1
print('x =', x, ' y =', y)
x = -1
x = float(x)
y = 3 * x ** 3 - 2 * x ** 2 + 3 * x - 1
print('x =', x, ' y =', y)
| true
|
fd86bac9750e54714b1fe65d050d336dba9399ca
|
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
|
/Module-4/4-1-3-9-LAB-Prime-numbers-how-to-find-them.py
| 1,302
| 4.28125
| 4
|
#!/usr/bin/python3
"""
A natural number is prime if it is greater than 1 and has no divisors other
than 1 and itself.
Complicated? Not at all. For example, 8 isn't a prime number, as you can
divide it by 2 and 4 (we can't use divisors equal to 1 and 8, as the
definition prohibits this).
On the other hand, 7 is a prime number, as we can't find any legal divisors
for it.
Your task is to write a function checking whether a number is prime or not.
The function:
is called isPrime;
takes one argument (the value to check)
returns True if the argument is a prime number, and False otherwise.
Hint: try to divide the argument by all subsequent values (starting from 2)
and check the remainder - if it's zero, your number cannot be a prime; think
carefully about when you should stop the process.
If you need to know the square root of any value, you can utilize the **
operator. Remember: the square root of x is the same as x0.5
Complete the code in the editor.
Run your code and check whether your output is the same as ours.
Test Data
Expected output:
2 3 5 7 11 13 17 19
"""
def isPrime(num):
for n in range(2, num):
if ((num % n) == 0):
return False
return True
for i in range(1, 20):
if isPrime(i + 1):
print(i + 1, end=" ")
print()
| true
|
3e7b84ff790a508534c03cdc878f6abdf2e32a53
|
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
|
/Module-3/3-1-6-1-Operations-on-lists-The-inner-life-of-lists.py
| 1,345
| 4.375
| 4
|
#!/usr/bin/python3
"""
The inner life of lists
Now we want to show you one important, and very surprising, feature of lists,
which strongly distinguishes them from ordinary variables.
We want you to memorize it - it may affect your future programs, and cause
severe problems if forgotten or overlooked.
Take a look at the snippet in the editor.
The program:
- creates a one-element list named list1;
- assigns it to a new list named list2;
- changes the only element of list1;
- prints out list2.
The surprising part is the fact that the program will output: [2], not [1],
which seems to be the obvious solution.
Lists (and many other complex Python entities) are stored in different ways
than ordinary (scalar) variables.
You could say that:
- the name of an ordinary variable is the name of its content;
- the name of a list is the name of a memory location where the list is
stored.
Read these two lines once more - the difference is essential for
understanding what we are going to talk about next.
The assignment: list2 = list1 copies the name of the array, not its
contents. In effect, the two names (list1 and list2) identify the same
location in the computer memory. Modifying one of them affects the other,
and vice versa.
How do you cope with that?
"""
list1 = [1]
list2 = list()
list2 = list1
list1[0] = 2
print(list2)
| true
|
946ec887e106dde979717832e603732ef85a750c
|
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
|
/Module-4/4-1-2-2-How-functions-communicate-with-their-environment-Parametrized-functions.py
| 1,358
| 4.375
| 4
|
#!/usr/bin/python3
"""
It's legal, and possible, to have a variable named the same as a function's
parameter.
The snippet illustrates the phenomenon:
def message(number):
print("Enter a number:", number)
number = 1234
message(1)
print(number)
A situation like this activates a mechanism called shadowing:
parameter x shadows any variable of the same name, but...
... only inside the function defining the parameter.
The parameter named number is a completely different entity from the variable
named number.
This means that the snippet above will produce the following output:
Enter a number: 1
1234
"""
def message(number):
print("Enter a number:", number)
message(4)
number = 1234
message(1)
print(number)
"""
A function can have as many parameters as you want, but the more parameters
you have, the harder it is to memorize their roles and purposes.
Functions as a black box concept
Let's modify the function - it has two parameters now:
def message(what, number):
print("Enter", what, "number", number)
This also means that invoking the function will require two arguments.
The first new parameter is intended to carry the name of the desired value.
Here it is:
"""
def message1(what, number):
print("Enter", what, "number", number)
message1("telephone", 11)
message1("price", 6)
message1("number", "number")
| true
|
b6732e8d49b943a0391fe3d6521bdf29d2f840ee
|
rolandoquiroz/CISCO_PCAP-Programming-Essentials-In-Python
|
/Module-3/3-1-1-11-LAB-Comparison-operators-and-conditional-execution.py
| 1,014
| 4.46875
| 4
|
#!/usr/bin/python3
"""
Spathiphyllum, more commonly known as a peace lily or white sail plant,
is one of the most popular indoor houseplants that filters out harmful
toxins from the air. Some of the toxins that it neutralizes include benzene,
formaldehyde, and ammonia.
Imagine that your computer program loves these plants.
Whenever it receives an input in the form of the word Spathiphyllum,
it involuntarily shouts to the console the following string:
"Spathiphyllum is the best plant ever!"
Test Data
Sample input: spathiphyllum
Expected output: No, I want a big Spathiphyllum!
Sample input: pelargonium
Expected output: Spathiphyllum! Not pelargonium!
Sample input: Spathiphyllum
Expected output: Yes - Spathiphyllum is the best plant ever!
"""
word = input("Please input your string: ")
if word == "Spathiphyllum":
print("Yes - Spathiphyllum is the best plant ever!")
elif word == "spathiphyllum":
print("No, I want a big Spathiphyllum!")
else:
print("Spathiphyllum! Not " + word + "!")
| true
|
ad07c957de435974775396e4cc0b8a793ffe4141
|
michellecby/learning_python
|
/week7/checklist.py
| 788
| 4.1875
| 4
|
#!/usr/bin/env python3
# Write a program that compares two files of names to find:
# Names unique to file 1
# Names unique to file 2
# Names shared in both files
import sys
import biotools
file1 = sys.argv[1]
file2 = sys.argv[2]
def mkdictionary(filename):
names = {}
with open(filename) as fp:
for name in fp.readlines():
name = name.rstrip()
names[name] = True
return names
d1 = mkdictionary(file1)
d2 = mkdictionary(file2)
u1 = []
u2 = []
both = []
for word in d1:
if word in d2:
both.append(word)
else:
u1.append(word)
for word in d2:
if word not in d1:
u2.append(word)
print("Names unique to file 1:")
print(u1)
print("Names unique to file 2:")
print(u2)
print("Names shared in both files:")
print(both)
"""
python3 checklist.py file1.txt file2.txt
"""
| true
|
2f8d761707c15cef64f9e8b49aae03c733959d00
|
leetuckert10/CrashCourse
|
/chapter_9/exercise_9-6.py
| 1,668
| 4.375
| 4
|
# Exercise 9-6: Ice Cream Stand
# Write a class that inherits the Restaurant class. Add and an attribute
# called flavors that stores a list of ice cream flavors. Add a method that
# displays the flavors. Call the class IceCreamStand.
from restaurant import Restaurant
class IceCreamStand(Restaurant):
def __init__(self, name, cuisine, flavors=None):
super().__init__(name, cuisine)
self.flavors = flavors
def add_flavor(self, flavor):
"""This method adds an ice cream flavor to the the flavors list."""
self.flavors.append(flavor)
def remove_flavor(self, flavor):
"""This mehtod removes a flavor from the list of ice cream flavors."""
self.flavors.remove(flavor)
def show_flavors(self):
"""This method displays all the flavors available at the ice cream
stand."""
print("Available ice cream flavors are: ", end="")
for flavor in self.flavors:
if flavor == self.flavors[-1]:
print(f"{flavor.title()}.", end="")
else:
print(f"{flavor.title()}, ", end="")
print("")
flavors = ["chocolate","vanilla","strawberry"]
ics = IceCreamStand("Terry's Ice Cream Shop", "Ice Cream", flavors)
ics.show_flavors()
print("\nAdding new flavors!")
ics.add_flavor("butter pecan")
ics.add_flavor("cookie dough")
ics.add_flavor("carmal")
ics.show_flavors()
print("\nOops! Out of Butter Pecan because Terry ate it all!\n")
ics.remove_flavor("butter pecan")
ics.show_flavors()
ics.set_number_served(238_449)
# Showing that we have this attribute from Restaurant.
print(f"We have served {ics.number_served} customers!")
| true
|
df70e46cceaa083c3a0545af8eb83463295b0b40
|
leetuckert10/CrashCourse
|
/chapter_11/test_cities.py
| 1,339
| 4.3125
| 4
|
# Exercise 11-1: City, Country
#
# Create a file called test_city.py that tests the function you just wrote.
# Write a method called test_city_country() in the class you create for testing
# the function. Make sure it passes the test.
#
# Remember to import unittest and the function you are testing. Remember that
# the test class should inherit unittest.TestCase. Remember that the test
# methods in the class need to begin with the word 'test' to be automatically
# executed.
import unittest
from city_functions import get_formatted_city_country
class CityCountryNameTestCase(unittest.TestCase):
"""Tests get_formatted_city_country()."""
def test_city_country(self):
"""Do names like santiago chile work?"""
formatted_city_country = get_formatted_city_country('santiago', 'chile')
self.assertEqual(formatted_city_country, "Santiago, Chile")
def test_city_country_population(self):
"""Does a city name, a country name, and a population work?"""
formatted_city_country = get_formatted_city_country('santiago',
'chile', 50_000_000)
self.assertEqual(formatted_city_country, "Santiago, Chile - "
"Population 50000000")
if __name__ == '__main__':
unittest.main()
| true
|
f4f669c12f07d0320e5d9a01fec7542e249d4962
|
leetuckert10/CrashCourse
|
/chapter_4/exercise_4-10.py
| 539
| 4.5625
| 5
|
# Slices
# Use list splicing to print various parts of a list.
cubes = [value**3 for value in range(1, 11)] # list comprehension
print("The entire list:")
for value in cubes:
# check out this syntax for suppressing a new line.
print(value, " ", end="")
print('\n')
# display first 3 items
print(f"The first three items are: {cubes[:3]}")
# display items from the middle of the list
print(f"Three items beginning at index 3 are: {cubes[3:6]}")
# display last three items in list
print(f"The last three items are: {cubes[-3:]}")
print()
| true
|
1897ec6770bca8f6e0dc72abbcdcd70644e6f182
|
leetuckert10/CrashCourse
|
/chapter_8/exercise_8-14.py
| 764
| 4.3125
| 4
|
# Exercise 8-13: Cars
# Define a function that creates a list of key-value pairs for all the
# arbitrary arguments. The syntax **user_info tell Python to create a
# dictionary out of the arbitrary parameters.
def make_car(manufacturer, model, **car):
""" Make a car using a couple positional parameters and and arbitrary
number of arguments as car. """
car['manufacturer'] = manufacturer
car['model'] = model
return car
def print_car(car):
""" Print out key/value pairs in the user profile dictionary."""
for key, value in car.items():
print(f"{key}: {value}")
car = make_car('Chevrolett',
'Denali',
sun_roof=True,
heated_sterring_wheel=True,
color='Black',
towing_package=True,
)
print_car(car)
| true
|
997df0520551de4bfb67665932840b09fa1a6d5a
|
leetuckert10/CrashCourse
|
/chapter_6/exercise_6-9.py
| 1,229
| 4.21875
| 4
|
# Favorite Places:
# Make a dictionary of favorite places with the persons name as the kep.
# Create a list as one of the items in the dictionary that contains one or
# more favorite places.
favorite_places = {
'terry': ['wild cat rock', 'mount mitchell', 'grandfather mountain'],
'carlee': ['blue ridge parkway', 'tweetsie', 'boone', 'carter falls',
'cave', 'burger king'],
'linda': ['thrift store', 'home', 'little switzerland', 'sparta'],
'rebekah': [], # let's have one blank and know how to check it
}
# If you leave off items, the default behavior of the for loop is to
# return the key and the value.
# for name, place in favorite_places.items():
for name, places in favorite_places.items():
if places:
print(f"{name.title()} has {len(places)} favorite places:")
print("\t", end="")
for place in places:
# doing trailing comma control...
if place == places[-1]: # [-1] returns last item in list
print(f"{place.title()}", end="")
else:
print(f"{place.title()}, ", end="")
else:
print(f"{name.title()} doesn't have any favorite places defined yet.")
print("\n")
| true
|
ab6b62451de82d2c52b1b994cfabab7893c4f64e
|
leetuckert10/CrashCourse
|
/chapter_8/exercise_8-3.py
| 541
| 4.125
| 4
|
# Exercise 8-3: T-Shirt
# Write a function called make_shirt() that accepts a size and a string for
# the text to be printed on the shirt. Call the function twice: once with
# positional arguments and once with keyword arguments.
def make_shirt(text, size):
print(f"Making a {size.title()} T-Shirt with the text '{text}'...")
make_shirt('Love You', 'large') # positional arguments
# use keyword arguments: note the order does not matter
make_shirt(text="Love YOU", size='Medium')
make_shirt(size='extra large', text='Love YOU')
| true
|
928d97a0023a0a64773fb1df4c1e59bc20f01123
|
algorithms-21-devs/Interview_problems
|
/weekly_interview_questions/IQ_4/Q4_emmanuelcodev/Q4Medium_N.py
| 1,840
| 4.25
| 4
|
import node as n
'''
Time complexity: O(n)
Algorithm iterates through link list once only. It adds memory location as a key to a dictionary. As it iterates it checks if the
current node memory matches any in the dictionary in O(1) time. If it does a cycle must be present.
'''
def cycle(head_node):
#must be a linked list
if head_node is None:
raise Exception('Cannot process an empty linked list')
current_node = head_node
nodes_dic = {}#stores memory locations as keys and data of node as value
#iterate through the list once
while current_node is not None:
if current_node not in nodes_dic:#put in dictionary if node is not in dic
nodes_dic[current_node] = current_node.data
else:#we found a node twice meaning there is a cycle
return True
current_node = current_node.next#make sure we iterate through the list
return False
#Testing
node_a = n.Node('A')
node_b = n.Node('B')
node_c = n.Node('C')
node_d = n.Node('D')
l1 = node_a
l1.next = node_b
l1.next.next = node_c
l1.next.next.next = node_d
l1.next.next.next.next = node_b #cycle
print(cycle(l1))
node_a = n.Node('A')
node_b = n.Node('B')
node_c = n.Node('C')
node_d = n.Node('D')
#'A'->'B'-->'C'->'D'->'B' (different node with data b)
l2 = node_a
l2.next = node_b
l2.next.next = node_c
l2.next.next.next = node_d
l2.next.next.next.next = n.Node('B') #cycle
print(cycle(l2))
node_a = n.Node('A')
node_b = n.Node('B')
node_c = n.Node('C')
node_d = n.Node('D')
#your_function('A') returns False
l3 = node_a
print(cycle(l3))
node_a = n.Node('A')
node_b = n.Node('B')
node_c = n.Node('C')
node_d = n.Node('D')
#your_function('A'->'B'-->'C') returns False
l4 = node_a
l4.next = node_b
l4.next.next = node_c
print(cycle(l4))
#your_function(none) returns Exception
l5 = None
print(cycle(l5))
| true
|
4374c169c241a96ef6fc26f74a3c514f4cc216ed
|
algorithms-21-devs/Interview_problems
|
/weekly_interview_questions/IQ_2/Q2_Emmanuelcodev/Q2Medium_Nsquared.py
| 2,634
| 4.1875
| 4
|
def unique_pairs(int_list, target_sum):
#check for None
'''
Time complexity: O(n^2).
1) This is because I have a nested for loop. I search through int_list,
and for each element in int_list I search through int_list again.
N for the outer and n^2 with the inner.
2) The second part of my algorithm which iteraters through the pairs and checks a dictionary is done in O(n) time.
for x in pairs:
if x in upairs
I am checking n items (b/c of pairs), at O(1) time due to upairs being
a dictionary. Overall, highest cost is O(n^2)
Space complexity: O(n)
1) I create another array and dictionary in the worst case n size.
'''
if None in (int_list, target_sum):
raise Exception("int_list and target_sum cannot be of NoneType")
if len(int_list) < 2:
return []
pairs = []
for x in int_list:
duplicate = False #only count num if it occurs more than once, since second loop will count current num as as second instance due it starting from begining and first loop counitng it as the first INSTANCE
for y in int_list:
if x == y:#counts current num in second loop, any more occurances are duplicates and therefore valid
if duplicate == False:
duplicate = True
else:
if x + y == target_sum:
pairs.append((x,y))
else:
if x + y == target_sum:#if current num (x) and y together == target_sum, then append group
pairs.append((x,y))
#have duplicate pairs need to clean data
upairs = {}
#print(pairs)
for x in pairs:
if x[0] < x[1]:# sorts tuple of size 2 , so n operationgs for entire loop
if x in upairs:
pass
else:
upairs[str(x)]=1
else:
if (x[1],x[0]) in upairs:
pass
else:
upairs[str((x[1],x[0]))]=1
pairs = []
for x in upairs.keys():
pairs.append(x)
return pairs
#duplicate pairs
print(unique_pairs([1, 3, 2, 2,3,5,5], 4)) # Returns [(3,1),(2,2)]
print(unique_pairs([3, 4, 19, 3, 4, 8, 5, 5], 6))#returns 1,1
print(unique_pairs([-1, 6, -3, 5, 3, 1], 2)) # Returns [(-1,3),(5,-3)]
print(unique_pairs([3, 4, 19, 3, 3, 3, 3], 6)) # Returns [(3,3)]
print(unique_pairs([-1, 6, -3, 5, 3, 1], 5000)) # Returns []
print(unique_pairs([], 10)) # Returns Exception
print(unique_pairs([4],54)) #returns []
print(unique_pairs(None,54))# raises Exception
| true
|
21b935d316daacdd26b6ee02b1bcf5d4b449e462
|
serafdev/codewars
|
/merged_string_checker/code.py
| 440
| 4.125
| 4
|
def is_merge(s, part1, part2):
return merge(s, part1, part2) or merge(s, part2, part1)
def merge(s, part1, part2):
if (s == '' and part1 == '' and part2 == ''):
return True
elif (s != '' and part1 != '' and s[0] == part1[0]):
return is_merge(s[1:], part1[1:], part2)
elif (s != '' and part2 != '' and s[0] == part2[0]):
return is_merge(s[1:], part1, part2[1:])
else:
return False
| false
|
f587e8614825a2d013715057bf7cffc0ed0cf287
|
Earazahc/exam2
|
/derekeaton_exam2_p2.py
| 1,032
| 4.25
| 4
|
#!/usr/bin/env python3
"""
Python Exam Problem 5
A program that reads in two files and prints out
all words that are common to both in sorted order
"""
from __future__ import print_function
def fileset(filename):
"""
Takes the name of a file and opens it.
Read all words and add them to a set.
Args:
filename: The name of the file
Return:
a set with all unique words in the file
"""
with open(filename, mode='rt', encoding='utf-8') as reading:
hold = set()
for line in reading:
temp = line.split()
for item in temp:
hold.add(item)
return hold
def main():
"""
Test your module
"""
print("Enter the name of a file: ", end='')
file1 = input()
print("Enter the name of a file: ", end='')
file2 = input()
words1 = fileset(file1)
words2 = fileset(file2)
shared = words1.intersection(words2)
for word in shared:
print(word)
if __name__ == "__main__":
main()
exit(0)
| true
|
b2c24fe1f3d4f3474b70461b608a2c14e9d44e9b
|
viralsir/python_saket
|
/if_demo.py
| 1,045
| 4.15625
| 4
|
'''
control structure if
syntax :
if condition :
statement
else :
statement
relational operator
operator symbol
greater than >
less than <
equal to ==
not equal to !=
greater than
or equal to >=
less than
or equal to <=
logical operator
operator symbol
and and
or or
not not
'''
no1=int(input("Enter No1:"))
no2=int(input("Enter No2:"))
no3=int(input("Enter No3:"))
if no1>0 and no2>0 and no3>0 :
if no1>no2 and no1>no3:
print(no1," is a maxium no")
elif no2>no1 and no2>no3 :
print(no2," is a maximum no")
else :
print(no3," is a maximum no")
else :
if no1<0:
print(no1," is a invalid")
elif no2<0:
print(no2," is a invalid")
else :
print(no3," is a invalid")
#print("invalid input")
| true
|
0bdb3507ea776a6b421a6e8dfda6c3e47f2c38bd
|
viralsir/python_saket
|
/def_demo3.py
| 354
| 4.1875
| 4
|
def prime(no):
is_prime=True
for i in range(2,no):
if no % i == 0 :
is_prime=False
return is_prime
def factorial(no):
fact=1
for i in range(1,no+1):
fact=fact*i
return fact
# no=int(input("enter No:"))
#
# if prime(no):
# print(no," is a prime no")
# else :
# print(no," is not a prime no")
| true
|
8da0b1dd8e0dd6024cff4612ab35a83a3cfc95d2
|
Gallawander/Small_Python_Programs
|
/Caesar cipher.py
| 991
| 4.3125
| 4
|
rot = int(input("Input the key: "))
action = input("Do you want to [e]ncrypt or [d]ecrypt?: ")
data = input("Input text: ")
if action == "e" or action == "encrypt":
text = ""
for char in data:
char_ord = ord(char)
if 32 <= char_ord <= 126:
char_ord -= 32
char_ord += rot # rotating to the right == encrypting
char_ord %= 94
char_ord += 32
text += chr(char_ord)
else:
text += char
print("cipher: {}".format(text))
elif action == "d" or action == "decrypt":
text = ""
for char in data:
char_ord = ord(char)
if 32 <= char_ord <= 126:
char_ord -= 32
char_ord -= rot # rotating to the left == decrypting
char_ord %= 94
char_ord += 32
text += chr(char_ord)
else:
text += char
print("text: {}".format(text))
else:
print("Error! Wrong operation!")
| false
|
2a0ffb39c845e7827d3a841c9f0475f42e8a5838
|
kalyan-dev/Python_Projects_01
|
/demo/oop/except_demo2.py
| 927
| 4.25
| 4
|
# - Accept numbers from user until zero is given and display SUM of the numbers; handle Invalid Numbers;
# program should not crash, but should continue;
def is_integer(n):
try:
return float(n).is_integer()
except ValueError:
return False
def is_integer_num(n):
if isinstance(n, int):
return True
if isinstance(n, float):
return False
nums = []
while True:
try:
# n = int(input("Enter a number(0 to End) :"))
sn = input("Enter a number(0 to End) :")
if not is_integer_num(sn):
n = float(sn)
else:
n = int(sn)
if n == 0:
break
else:
nums.append(n)
except:
print("You have entered an invalid number. Please enter an Integer.")
continue
print(f"You have entered {nums}")
print(f"Sum of the numbers = {sum(nums)}")
| true
|
9b6a117c5d2ae6e591bc31dfd1ba748b84079710
|
tejaboggula/gocloud
|
/fact.py
| 332
| 4.28125
| 4
|
def fact(num):
if num == 1:
return num
else:
return num*fact(num-1)
num = int(input("enter the number to find the factorial:"))
if num<0:
print("factorial is not allowed for negative numbers")
elif num == 0:
print("factorial of the number 0 is 1")
else:
print("factorial of",num, "is:",fact(num))
| true
|
0fa7e809c7f4a8c7b0815a855cbc482abf600a77
|
dimpy-chhabra/Artificial-Intelligence
|
/Python_Basics/ques1.py
| 254
| 4.34375
| 4
|
#Write a program that takes three numbers as input from command line and outputs
#the largest among them.
#Question 02
import sys
s = 0
list = []
for arg in sys.argv[1:]:
list.append(int(arg))
#arg1 = sys.argv[1]
list.sort()
print list[len(list)-1]
| true
|
e8e83ac29ce59ebb1051bbe6457e3d5bd8ade162
|
snail15/AlgorithmPractice
|
/Udacity/BasicAlgorithm/binarySearch.py
| 1,127
| 4.3125
| 4
|
def binary_search(array, target):
'''Write a function that implements the binary search algorithm using iteration
args:
array: a sorted array of items of the same type
target: the element you're searching for
returns:
int: the index of the target, if found, in the source
-1: if the target is not found
'''
start = 0
end = len(array) - 1
while start <= end:
mid = (start + end) // 2
if array[mid] == target:
return mid
elif array[mid] > target:
end = mid - 1
else:
start = mid + 1
return -1
def binary_search_recursive_soln(array, target, start_index, end_index):
if start_index > end_index:
return -1
mid_index = (start_index + end_index)//2
mid_element = array[mid_index]
if mid_element == target:
return mid_index
elif target < mid_element:
return binary_search_recursive_soln(array, target, start_index, mid_index - 1)
else:
return binary_search_recursive_soln(array, target, mid_index + 1, end_index)
| true
|
460d75a61550f0ae818f06ad46a9c210fe0d254e
|
lyderX05/DS-Graph-Algorithms
|
/python/BubbleSort/bubble_sort_for.py
| 911
| 4.34375
| 4
|
# Bubble Sort For Loop
# @author: Shubham Heda
# Email: hedashubham5@gmail.com
def main():
print("**NOTE**: Elements should be less then 25 as alogrithm work best on that only")
print("Enter Bubble Sort elements sepreated by (',') Comma: ")
input_string = input()
array = [int(each) for each in input_string.split(",")]
array_len = len(array)
if array_len > 1:
for _ in range(array_len):
swapped = False
for col in range(array_len - 1):
if array[col] > array[col + 1]:
array[col], array[col + 1] = array[col + 1], array[col]
swapped = True
print("New Array: ", array)
if not swapped:
break
else:
print("Array Contains Only One Value: ", array)
print("===========================")
print("Sorted Array: ", array)
if __name__ == '__main__':
main()
| true
|
eb1a3b4a62c74a8d53416c6e5a5f48a2ab4c2e67
|
yaroslavche/python_learn
|
/1 week/1.12.5.py
| 1,034
| 4.15625
| 4
|
# Напишите программу, которая получает на вход три целых числа, по одному числу в строке, и выводит на консоль в три
# строки сначала максимальное, потом минимальное, после чего оставшееся число.
# На ввод могут подаваться и повторяющиеся числа.
# Sample Input 1:
# 8
# 2
# 14
# Sample Output 1:
# 14
# 2
# 8
# Sample Input 2:
# 23
# 23
# 21
# Sample Output 2:
# 23
# 21
# 23
a = int(input())
b = int(input())
c = int(input())
if a >= b and a >= c:
max = a
if b > c:
min = c
rest = b
else:
min = b
rest = c
elif b >= a and b >= c:
max = b
if a > c:
min = c
rest = a
else:
min = a
rest = c
elif c >= a and c >= b:
max = c
if a > b:
min = b
rest = a
else:
min = a
rest = b
print(max)
print(min)
print(rest)
| false
|
208303bdec3be5362ce314eb632da444fed96f2c
|
yaroslavche/python_learn
|
/2 week/2.1.11.py
| 504
| 4.21875
| 4
|
# Напишите программу, которая считывает со стандартного ввода целые числа, по одному числу в строке, и после первого
# введенного нуля выводит сумму полученных на вход чисел.
# Sample Input 1:
# 5
# -3
# 8
# 4
# 0
# Sample Output 1:
# 14
# Sample Input 2:
# 0
# Sample Output 2:
# 0
s = 0
i = int(input())
while i != 0:
s += i
i = int(input())
print(s)
| false
|
8674d8f7e11eae360e63b470b7b2310f7170c5cc
|
zeusumit/JenkinsProject
|
/hello.py
| 1,348
| 4.40625
| 4
|
print('Hello')
print("Hello")
print()
print('This is an example of "Single and double"')
print("This is an example of 'Single and double'")
print("This is an example of \"Single and double\"")
seperator='***'*5
fruit="apple"
print(fruit)
print(fruit[0])
print(fruit[3])
fruit_len=len(fruit)
print(fruit_len)
print(len(fruit))
print(fruit.upper())
print('My'+''+'name'+''+'is'+''+'Sumit')
print('My name is Sumit')
first='sumit'
second="Kumar"
print(first+second)
print(first+''+second)
print(first+' '+second)
fullname=first+' '+second
print(fullname)
print(fullname.upper())
print(first[0].upper())
print(first[0].upper()+first[1].lower())
print('-'*10)
happiness='happy '*3
print(happiness)
age=37
print(first.upper()+"'"+'s'+' age is: '+str(age))
print(seperator+'Formatting Strings'+seperator)
print('My name is: {}'.format(first))
print('My name is: {}'.format(first.upper()))
print('{} is my name'.format(first))
print('My name is {0} {1}. {1} {0} is my name'.format('Sumit', 'Kumar'))
print('My name is {0} {1}. {1} {0} is my name'.format(first, second))
print('{0:8} | {1:8}'. format(first, second))
print('{0:8} | {1:0}'. format('Age', age))
print('{0:8} | {1:8}'. format('Height', '6 feet'))
print('{0:8} | {1:0} {2:1}'. format('Weight', 70,'kgs'))
print(seperator+'User input'+seperator)
| true
|
33553f9506dc46c9c05101074116c5254af7d0e9
|
EderVs/hacker-rank
|
/30_days_of_code/day_8.py
| 311
| 4.125
| 4
|
""" Day 8: Dictionaries and Maps! """
n = input()
phones_dict = {}
for i in range(n):
name = raw_input()
phone = raw_input()
phones_dict[name] = phone
for i in range(n):
name = raw_input()
phone = phones_dict.get(name, "Not found")
if phone != "Not found":
print name + "=" + phone
else:
print phone
| true
|
6784ec88c6088dfcd462a124bc657be9a4c51c3c
|
asmitaborude/21-Days-Programming-Challenge-ACES
|
/generator.py
| 1,177
| 4.34375
| 4
|
# A simple generator function
def my_gen():
n = 1
print('This is printed first')
# Generator function contains yield statements
yield n
n += 1
print('This is printed second')
yield n
n += 1
print('This is printed at last')
yield n
# Using for loop
for item in my_gen():
print(item)
#Python generator using loops
def rev_str(my_str):
length = len(my_str)
for i in range(length - 1, -1, -1):
yield my_str[i]
# For loop to reverse the string
for char in rev_str("hello"):
print(char)
#python generator expression
# Initialize the list
my_list = [1, 3, 6, 10]
# square each term using list comprehension
list_ = [x**2 for x in my_list]
# same thing can be done using a generator expression
# generator expressions are surrounded by parenthesis ()
generator = (x**2 for x in my_list)
print(list_)
print(generator)
#pipeline generator
def fibonacci_numbers(nums):
x, y = 0, 1
for _ in range(nums):
x, y = y, x+y
yield x
def square(nums):
for num in nums:
yield num**2
print(sum(square(fibonacci_numbers(10))))
| true
|
46a7b9c9a436f4620dac591ed193a09c9b164478
|
asmitaborude/21-Days-Programming-Challenge-ACES
|
/python_set.py
| 2,244
| 4.65625
| 5
|
# Different types of sets in Python
# set of integers
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
# set cannot have duplicates
# Output: {1, 2, 3, 4}
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
# we can make set from a list
# Output: {1, 2, 3}
my_set = set([1, 2, 3, 2])
print(my_set)
# Distinguish set and dictionary while creating empty set
# initialize a with {}
a = {}
# check data type of a
print(type(a))
# initialize a with set()
a = set()
# check data type of a
print(type(a))
# initialize my_set
my_set = {1, 3}
print(my_set)
#if you uncomment the line below you will get an error
# my_set[0]
# add an element
# Output: {1, 2, 3}
my_set.add(2)
print(my_set)
# add multiple elements
# Output: {1, 2, 3, 4}
my_set.update([2, 3, 4])
print(my_set)
# add list and set
# Output: {1, 2, 3, 4, 5, 6, 8}
my_set.update([4, 5], {1, 6, 8})
print(my_set)
# Difference between discard() and remove()
# initialize my_set
my_set = {1, 3, 4, 5, 6}
print(my_set)
# discard an element
# Output: {1, 3, 5, 6}
my_set.discard(4)
print(my_set)
# remove an element
# Output: {1, 3, 5}
my_set.remove(6)
print(my_set)
# Output: {1, 3, 5}
my_set.discard(2)
print(my_set)
# initialize my_set
# Output: set of unique elements
my_set = set("HelloWorld")
print(my_set)
# pop an element
# Output: random element
print(my_set.pop())
# pop another element
my_set.pop()
print(my_set)
# clear my_set
# Output: set()
my_set.clear()
print(my_set)
print(my_set)
# Set union method
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use | operator
# Output: {1, 2, 3, 4, 5, 6, 7, 8}
print(A | B)
# Intersection of sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use & operator
# Output: {4, 5}
print(A & B)
# Difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use - operator on A
# Output: {1, 2, 3}
print(A - B)
# Symmetric difference of two sets
# initialize A and B
A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
# use ^ operator
# Output: {1, 2, 3, 6, 7, 8}
print(A ^ B)
| true
|
1a87238ebb8b333148d1c2b4b094370f21fd230b
|
asmitaborude/21-Days-Programming-Challenge-ACES
|
/listsort.py
| 677
| 4.4375
| 4
|
#python list sort ()
#example 1:Sort a given list
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort()
# print vowels
print('Sorted list:', vowels)
#Example 2: Sort the list in Descending order
# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels
vowels.sort(reverse=True)
# print vowels
print('Sorted list (in Descending):', vowels)
#Example 3: Sort the list using key
# take second element for sort
def takeSecond(elem):
return elem[1]
# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# sort list with key
random.sort(key=takeSecond)
# print list
print('Sorted list:', random)
| true
|
6346a452b77b895e2e686c5846553687459798ca
|
asmitaborude/21-Days-Programming-Challenge-ACES
|
/dictionary.py
| 2,840
| 4.375
| 4
|
#Creating Python Dictionary
# empty dictionary
my_dict = {}
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
# from sequence having each item as a pair
my_dict = dict([(1,'apple'), (2,'ball')])
#Accessing Elements from Dictionary
# get vs [] for retrieving elements
my_dict = {'name': 'Jack', 'age': 26}
# Output: Jack
print(my_dict['name'])
# Output: 26
print(my_dict.get('age'))
# Trying to access keys which doesn't exist throws error
# Output None
print(my_dict.get('address'))
# KeyError
#print(my_dict['address'])
#Changing and Adding Dictionary elements
# Changing and adding Dictionary Elements
my_dict = {'name': 'Jack', 'age': 26}
# update value
my_dict['age'] = 27
#Output: {'age': 27, 'name': 'Jack'}
print(my_dict)
# add item
my_dict['address'] = 'Downtown'
# Output: {'address': 'Downtown', 'age': 27, 'name': 'Jack'}
print(my_dict)
# Removing elements from a dictionary
# create a dictionary
squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# remove a particular item, returns its value
# Output: 16
print(squares.pop(4))
# Output: {1: 1, 2: 4, 3: 9, 5: 25}
print(squares)
# remove an arbitrary item, return (key,value)
# Output: (5, 25)
print(squares.popitem())
# Output: {1: 1, 2: 4, 3: 9}
print(squares)
# remove all items
squares.clear()
# Output: {}
print(squares)
# delete the dictionary itself
del squares
# Throws Error
#print(squares)
#Some Python Dictionary Methods
# Dictionary Methods
marks = {}.fromkeys(['Math', 'English', 'Science'], 0)
# Output: {'English': 0, 'Math': 0, 'Science': 0}
print(marks)
for item in marks.items():
print(item)
# Output: ['English', 'Math', 'Science']
print(list(sorted(marks.keys())))
#Python Dictionary Comprehension
# Dictionary Comprehension
squares = {x: x*x for x in range(6)}
print(squares)
# Dictionary Comprehension with if conditional
odd_squares = {x: x*x for x in range(11) if x % 2 == 1}
print(odd_squares)
#Other Dictionary Operations
#Dictionary Membership Test
# Membership Test for Dictionary Keys
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: True
print(1 in squares)
# Output: True
print(2 not in squares)
# membership tests for key only not value
# Output: False
print(49 in squares)
## Iterating through a Dictionary
squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])
# Dictionary Built-in Functions
squares = {0: 0, 1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: False
print(all(squares))
# Output: True
print(any(squares))
# Output: 6
print(len(squares))
# Output: [0, 1, 3, 5, 7, 9]
print(sorted(squares))
| true
|
f1e73874c9d09a51aa7b9c4a5890fe3cb34f5622
|
parth-sp02911/My-Projects
|
/Parth Patel J2 2019 problem.py
| 1,161
| 4.125
| 4
|
#Parth Patel
#797708
#ICS4UOA
#J2 problem 2019 - Time to Decompress
#Mr.Veera
#September 6 2019
num_of_lines = int(input("Enter the number of lines: ")) #asks the user how many lines they want and turns that into an integer
output_list = [] #creates a list which will hold the values of the message the user wants
for line in range(num_of_lines): #creates a for loop which will repeat as many times, as the user inputed in the "num_of_lines" variable
user_input = (input("Enter the message: ")).split() #in the loop I ask the user to enter the message they want and split it by the space (turning it into a list)
num_of_char = int(user_input[0]) #I create a variable which will hold the number of times the user wants their character repeated
char = user_input[1] #i create a variable which will hold the character the user wants to be repeated
output_list.append(char * num_of_char) #I make the program repeat the character as many times as the user wants and then append it to the final output list
for element in output_list:
print(element) #I print all the elements in the list
| true
|
4783c951d8caaf9c5c43fb57694cfb8d60d466b7
|
marcinosypka/learn-python-the-hard-way
|
/ex30.py
| 1,691
| 4.125
| 4
|
#this line assigns int value to people variable
people = 30
#this line assigns int value to cars variable
cars = 30
#this line assigns int value to trucks variable
trucks = 30
#this line starts compound statemet, if statemets executes suite below if satement after if is true
if cars > people:
#this line belongs to suite started by if above, prints a string to terminal
print("We should take the cars.")
#this line starts elif statement, if statement after elif is true suite below is executed, it has to be put after if compound statement
elif cars < people:
#this line belongs to suite started by elif, it prints string to terminal
print("We should not take the cars.")
#this line starts a compound statement, if if statement and all elif statements above are false then else suite is executed
else:
#this line belongs to else suite, it prints string to terminal
print("We can't decide.")
#this line starts if statement
if trucks > cars:
#this line prints string to terminal if if statement is true
print("That's too many trucks.")
#this line starts elif statement
elif trucks < cars:
#this line prints string to terminal if elif statement is true
print("Maybe we could take the trucks.")
#this line starts else statement
else:
#this line prints string to terminal if all elifs and if above is false
print("We still can't decide")
#this line starts if statement
if people > trucks or not people > cars * 2 :
#this line prints string to terminal if if statement above is true
print("Alright, let's just take the trucks.")
#this line starts else statement
else:
#this line prints string to terminal if all elifs and if statement above is false
print("Fine, let's stay home than.")
| true
|
1b59b6f971ce37b62f3ed7eb6cc5d94ed8b2df44
|
felcygrace/fy-py
|
/currency.py
| 852
| 4.21875
| 4
|
def convert_currency(amount_needed_inr,current_currency_name):
current_currency_amount=0
Euro=0.01417
British_Pound=0.0100
Australian_Dollar=0.02140
Canadian_Dollar=0.02027
if current_currency_name=="Euro":
current_currency_amount=amount_needed_inr*Euro
elif current_currency_name=="British_Pound":
current_currency_amount=amount_needed_inr*British_Pound
elif current_currency_name=="Australian_Dollar":
current_currency_amount=amount_needed_inr*Australian_Dollar
elif current_currency_name=="Canadian_Dollar":
current_currency_amount=amount_needed_inr*Canadian_Dollar
else:
print("-1")
return current_currency_amount
currency_needed=convert_currency(3500,"British_Pound")
if(currency_needed!= -1):
print(currency_needed )
else:
print("Invalid currency name")
| false
|
c5d852ead39ef70ee91f26778f4a7874e38466cf
|
bohdi2/euler
|
/208/directions.py
| 792
| 4.125
| 4
|
#!/usr/bin/env python3
import collections
import itertools
from math import factorial
import sys
def choose(n, k):
return factorial(n) // (factorial(k) * factorial(n-k))
def all_choices(n, step):
return sum([choose(n, k) for k in range(0, n+1, step)])
def main(args):
f = factorial
expected = {'1' : 2, '2' : 2, '3' : 2, '4' : 2, '5' : 2}
print("All permutations of 10: ", 9765625)
print("All permutations of pairs: ", 113400)
print("All 11s: ", 22680)
print("All 12s: ", 42840)
length = 10
count = 0
for p in itertools.product("12345", repeat=length):
p = "".join(p)
c = collections.Counter(p)
#print(c)
if c == expected:
print(p)
if __name__ == '__main__':
sys.exit(main(sys.argv))
| true
|
656d28880463fdd9742a9e2c6c33c2c247f01fbf
|
andylws/SNU_Lecture_Computing-for-Data-Science
|
/HW3/P3.py
| 590
| 4.15625
| 4
|
"""
#Practical programming Chapter 9 Exercise 3
**Instruction**
Write a function that uses for loop to add 1 to all the values from input list
and return the new list. The input list shouldn’t be modified.
Assume each element of input list is always number.
Complete P3 function
P3([5, 4, 7, 3, 2, 3, 2, 6, 4, 2, 1, 7, 1, 3])
>>> [6, 5, 8, 4, 3, 4, 3, 7, 5, 3, 2, 8, 2, 4]
P3([0,0,0])
>>> [1,1,1]
"""
def P3(L1: list) -> list:
##### Write your Code Here #####
result = []
for i in L1:
result.append(i + 1)
return result
##### End of your code #####
| true
|
b4a85cfa138df5113411b2ce9f52360a3066342d
|
ScaredTuna/Python
|
/Results2.py
| 455
| 4.125
| 4
|
name = input("Enter Name:")
phy = int(input("Enter Physics Marks:"))
che = int(input("Enter Chemistry Marks:"))
mat = int(input("Enter Mathematics Marks:"))
tot = phy + che + mat
per = tot * 100 / 450
print("-------------------------------------")
print("Name:", name)
print("Total Marks:", tot)
print("Percentage:", per)
if per >= 60:
print(name, "has Passed")
if per < 60:
print(name, "has Failed")
print("-------------------------------------")
| false
|
69e6a29d952a0a5faaceed45e30bf78c5120c070
|
TommyWongww/killingCodes
|
/Daily Temperatures.py
| 1,025
| 4.25
| 4
|
# @Time : 2019/4/22 22:54
# @Author : shakespere
# @FileName: Daily Temperatures.py
'''
739. Daily Temperatures
Medium
Given a list of daily temperatures T, return a list such that, for each day in the input, tells you how many days you would have to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead.
For example, given the list of temperatures T = [73, 74, 75, 71, 69, 72, 76, 73], your output should be [1, 1, 4, 2, 1, 1, 0, 0].
Note: The length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100].
'''
class Solution(object):
def dailyTemperatures(self, T):
"""
:type T: List[int]
:rtype: List[int]
"""
res = [0] * len(T)
stack = []
for i in range(len(T)):
while stack and (T[i] > T[stack[-1]]):
idx = stack.pop()
res[idx] = i-idx
stack.append(i)
return res
| true
|
1ae82daf01b528df650bd7e72a69107cdf686a82
|
TommyWongww/killingCodes
|
/Invert Binary Tree.py
| 1,251
| 4.125
| 4
|
# @Time : 2019/4/25 23:51
# @Author : shakespere
# @FileName: Invert Binary Tree.py
'''
226. Invert Binary Tree
Easy
Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import collections
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root is not None:
nodes = []
nodes.append(root)
while nodes:
node = nodes.pop()
node.left,node.right = node.right,node.left
if node.left is not None:
nodes.append(node.left)
if node.right is not None:
nodes.append(node.right)
return root
| true
|
9befa8049cd7c31fd959b6ad7ca652c4e1435d00
|
jillgower/pyapi
|
/sqldb/db_challeng.py
| 2,819
| 4.21875
| 4
|
#!/usr/bin/env python3
import sqlite3
def create_table():
conn = sqlite3.connect('test.db')
conn.execute('''CREATE TABLE IF NOT EXISTS EMPLOYEES
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')
print("Table created successfully")
conn.close()
def insert_data():
conn = sqlite3.connect('test.db')
conn.execute("INSERT INTO EMPLOYEES (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Paul', 32, 'California', 20000.00 )")
conn.execute("INSERT INTO EMPLOYEES (ID,NAME,AGE,ADDRESS,SALARY) VALUES (2, 'Allen', 25, 'Texas', 15000.00 )")
conn.execute("INSERT INTO EMPLOYEES (ID,NAME,AGE,ADDRESS,SALARY) VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )")
conn.execute("INSERT INTO EMPLOYEES (ID,NAME,AGE,ADDRESS,SALARY) VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )")
conn.commit()
print("Records created successfully")
conn.close()
def print_data():
conn = sqlite3.connect('test.db')
cursor = conn.execute("SELECT id, name, address, salary from EMPLOYEES")
for row in cursor:
print("ID = ", row[0])
print("NAME = ", row[1])
print("ADDRESS = ", row[2])
print("SALARY = ", row[3], "\n")
print("Operation done successfully")
conn.close()
def update_data():
conn = sqlite3.connect('test.db')
# find out which row you want to update, so print_data runs first
print_data()
update_select = input("select row to update:")
# what value needs to be changed?
print("you can change, NAME, ADDRESS or SALARY")
update_stuff = input("Enter NAME ADDRESS OR SALARY:")
update_val = input("Enter new value:")
if update_stuff == "NAME":
cursor = conn.execute("UPDATE EMPLOYEES set NAME= ? where ID = ?", (update_val,update_select))
conn.commit()
elif update_stuff == "ADDRESS":
cursor = conn.execute("UPDATE EMPLOYEES set ADDRESS= ? where ID = ?", (update_val,update_select))
conn.commit()
elif update_stuff == "SALARY":
cursor = conn.execute("UPDATE EMPLOYEES set SALARY= ? where ID = ?", (update_val,update_select))
conn.commit()
def delete_data():
conn = sqlite3.connect('test.db')
#print the table first
print_data()
line_del = input("Enter line to be deleted")
conn.execute("DELETE from EMPLOYEES where id = ?;", (line_del))
conn.commit()
print_data()
if __name__ == "__main__":
create_table()
print("="*35)
print("Inserting data")
insert_data()
print("="*35)
print("here is your table")
print_data()
print("="*35)
print("lets update it")
update_data()
print("="*35)
print("Lets delete some stuff")
delete_data()
print("all done with the challenge")
| false
|
048cc584eda064b0d148fea8d69843bb26051ed1
|
thalessahd/udemy-tasks
|
/python/ListaExercicios1/ex5.py
| 637
| 4.15625
| 4
|
# -*- coding: utf-8 -*-
"""
Escreva um programa que receba dois números e um sinal, e faça a operação matemática definida pelo sinal.
"""
print("Digite o primeiro número:")
num1 = float(input())
print("Digite o segundo número:")
num2 = float(input())
print("Digite o sinal:")
sinal = input()
if sinal=="+":
resu = num1+num2
print(resu)
elif sinal=="-":
resu = num1-num2
print(resu)
elif sinal=="*":
resu = num1*num2
print(resu)
elif sinal=="/":
try:
resu = num1/num2
print(resu)
except:
print("Não é possível divisão por 0.")
else:
print("Sinal não reconhecido")
| false
|
202bd0898352102599f6e4addccaec7a60b46a8f
|
amymhaddad/exercises_for_programmers_2019
|
/flask_product_search/products.py
| 1,454
| 4.15625
| 4
|
import json
#convert json file into python object
def convert_json_data(file):
"""Read in the data from a json file and convert it to a Python object"""
with open (file, mode='r') as json_object:
data = json_object.read()
return json.loads(data)
#set json data that's now a python object to projects_json
products_json = convert_json_data('products.json')
#Use the 'products' key from the products_json dictionary to get a LIST of dictionaries
products = products_json['products']
def show_all_products(products):
"""Display all provects from json file"""
display_product = ''
#cycle through the list of dictionaries
for product in products:
#cycle through the dicionaries
for category, detail in product.items():
if category == "price":
detail = f"${product['price']:.2f}"
display_product += f"{category.title()}: {detail}" + "\n"
return display_product
def one_product(products, itemname):
"""Return a single product based on user input"""
inventory_details = ''
for product in products:
if product['name'] == itemname:
for category, detail in product.items():
if category == 'price':
detail = f"${product['price']:.2f}"
inventory_details += f"{category.title()}: {detail}" + "\n"
return inventory_details
print(one_product(products, 'Thing'))
| true
|
6d3c6b5362c47d16b3916607be2896033e321e71
|
disha111/Python_Beginners
|
/Assignment 3.9/que2.py
| 552
| 4.1875
| 4
|
import pandas as pd
from pandas.core.indexes.base import Index
student = {
'name': ['DJ', 'RJ', 'YP'],
'eno': ['19SOECE13021', '18SOECE11001', '19SOECE11011'],
'email': ['dvaghela001@rku.ac.in', 'xyz@email.com', 'pqr@email.com'],
'year':[2019,2018,2019]
}
df = pd.DataFrame(student,index=[10,23,13])
print("Default DataFrame :\n",df)
df.sort_values('eno',inplace=True)
print("After Sorting by Values eno in DataFrame :\n",df)
df = df.sort_index()
print("After Sorting by Index eno in DataFrame :\n",df)
print(df.drop(index=df[df['name']=='DJ'].index,axis=0))
| false
|
6ef4e9543d7c7c20bdbb1ffa4976b8c3b6e9b0f5
|
disha111/Python_Beginners
|
/extra/scope.py
| 672
| 4.15625
| 4
|
#global variable
a = 10
b = 9
c = 11
print("Global Variables A =",a,", B =",b,", C =",c)
print("ID of var B :",id(b))
def something():
global a
a = 15
b = 5 #local variable
globals()['c'] = 16 #changing the global value.
x = globals()['b']
print("\nLocal Variables A =",a,", B =",b,", C =",c,", X =",x)
print("Inside func the ID of var B :",id(x))
print('In func from global to local var A changed :',a)
print('In func local var B :',b)
print('In func local var (X) accessing global var B :',x)
something()
print('Outside the func global var (A) remains Changed :',a)
print('Outside the func after changing global var C :',c)
| false
|
e323a0fe8e50ad7df9ecf1ce4ffe5ccd5aa5aa9b
|
tonnekarlos/aula-pec-2021
|
/T1-Ex04.py
| 249
| 4.28125
| 4
|
def verifica(caractere):
# ord retorna um número inteiro representa o código Unicode desse caractere.
digito = ord(caractere)
# 0 é 48 e 9 é 57
return 48 <= digito <= 57
print(verifica(input("Digite um caractere: ".strip())))
| false
|
9c0cd7be7ad5ad32f43d66d7ccceb2ddfe673a12
|
Smirt1/Clase-Python-Abril
|
/IfElifElse.py
| 611
| 4.15625
| 4
|
#if elif else
tienes_llave = input ("Tienes una llave?: ")
if tienes_llave == "si":
forma = input ("Que forma tiene la llave?: ")
color = input ("Que color tiene la llave?: ")
if tienes_llave != "si":
print ("Si no tienes llaves no entras")
if forma == "cuadrada" and color =="roja":
print ("Puedes pasar por la Puerta 1")
elif forma == "redonda" and color =="amarilla":
print ("Puedes pasar por la Puerta 2")
elif forma == "triangular" and color == "roja":
print ("Puedes pasar por la Puerta 2")
else:
print ("Tienes la llave equivocada")
| false
|
ab06ae955363b0ac7fcdfd22f35e9ea6e698d5c3
|
LakshayLakhani/my_learnings
|
/programs/binary_search/bs1.py
| 484
| 4.125
| 4
|
# given a sorted arrray with repititions, find left most index of an element.
arr = [2, 3, 3, 3, 3]
l = 0
h = len(arr)
search = 3
def binary_search(arr, l, h, search):
mid = l+h//2
if search == arr[mid] and (mid == 0 or arr[mid-1] != search):
return mid
elif search <= arr[mid]:
return binary_search(arr, l, mid, search)
# else search > arr[mid]:
else:
return binary_search(arr, mid, h, search)
print(binary_search(arr, l, h, search))
| true
|
99f8aed5acd78c31b9885eba4b830807459383be
|
chenp0088/git
|
/number.py
| 288
| 4.375
| 4
|
#!/usr/bin/env python
# coding=utf-8
number = input("If you input a number ,I will tell you if the number is multiplier of ten! Please input the number: ")
number = int(number)
if number%10 == 0:
print("It`s the multiplier of ten!")
else:
print("It`s not the multiplier of ten!")
| true
|
a01c02e5227267010b7bf6ddb54c2502797bb3c6
|
Akshay7591/Caesar-Cipher-and-Types
|
/ROT13/ROT13encrypt.py
| 270
| 4.1875
| 4
|
a=str(input("Enter text to encrypt:"))
key=13
enc=""
for i in range (len(a)):
char=a[i]
if(char.isupper()):
enc += chr((ord(char) + key-65) % 26 + 65)
else:
enc += chr((ord(char) + key-97) % 26 + 97)
print("Encrypted Text is:")
print(enc)
| false
|
08e48ae76c18320e948ec941e0be4b598720feeb
|
nkarasovd/Python-projects
|
/Data Structures and Algorithms Specialization/Algorithms on Strings/week2/4_suffix_array/suffix_array.py
| 632
| 4.1875
| 4
|
# python3
import sys
def build_suffix_array(text):
"""
Build suffix array of the string text and
return a list result of the same length as the text
such that the value result[i] is the index (0-based)
in text where the i-th lexicographically smallest
suffix of text starts.
"""
suffixes = [(text[i:], i) for i in range(len(text))]
result_util = sorted(suffixes, key=lambda x: x[0])
result = [el[1] for el in result_util]
return result
if __name__ == '__main__':
text = sys.stdin.readline().strip()
print(" ".join(map(str, build_suffix_array(text))))
| true
|
de7f2d2afcb130e6d5484bdbad0795fbf54bdf2f
|
Moloch540394/machine-learning-hw
|
/linear-regression/driver.py
| 1,398
| 4.3125
| 4
|
"""Computes the linear regression on a homework provided data set."""
__author__="Jesse Lord"
__date__="January 8, 2015"
import numpy as np
import matplotlib.pyplot as plot
from computeCost import computeCost
from gradientDescent import gradientDescent
from featureNormalization import featureNormalization
import readData
nfeatures = 2
if __name__=="__main__":
if nfeatures == 1:
(x,y,nexamples) = readData.readSingleFeature()
elif nfeatures == 2:
(x,y,nexamples) = readData.readMultiFeature()
# transforming the X array into a matrix to simplify the
# matrix multiplication with the theta_zero feature
X = np.ones((nfeatures+1,nexamples))
X[1:,:]=x[:,:]
theta = np.zeros(nfeatures+1)
if nfeatures==2:
(X_norm,mu,sigma) = featureNormalization(X)
# computes the cost as a test, should return 32.07
print computeCost(X_norm,y,theta)
if nfeatures == 1:
iterations = 1500
elif nfeatures == 2:
iterations = 400
alpha = 0.01
# computes the linear regression coefficients using gradient descent
theta = gradientDescent(X_norm,y,theta,alpha,iterations)
print theta[0]+theta[1]*((1650-mu[0])/sigma[0])+theta[2]*((3-mu[1])/sigma[1])
if nfeatures==1:
plot.plot(x,y,'o',x,np.dot(theta,X))
plot.show()
#plot.plot(x[0,:],y,'o',x[0,:],np.dot(theta[:1],X[:1,:])
#plot.show()
| true
|
1248d4aa0f0fcdb613782972fba43d20df509d96
|
elvispy/PiensaPython
|
/1operaciones.py
| 2,279
| 4.125
| 4
|
''' Existen varios tipos de operaciones en Python.
El primero, y mas comun es el de la adicion.
'''
x, y, z = 3, 9, '4'
a = 'String'
b = [1, 2, 'lol']
'''
La siguiente linea de codigo imprimira el resultado de sumar x con yield
'''
print(x+y)
'''
Debemos recordar que es imposible en la gran mayoria de los casos, sumar variables
de diferentes tipos. En ese caso, poner
print(x+z)
nos daria un error, puesto que z es del tipo string.
Sin embargo, es posible sumar dos listas
'''
c = [False, '123', 42]
print(b + c)
#la ultima linea seria parecido a b.extend(c)
#sin embargo, b.extend(c) es en realidad b = b + c. Asignandolo a b.
# Tambien podemos sumar strings, esto va a resultar en lo que se llama concatenacion
print(a + a)
'''
En general, la suma es de las pocas operaciones compartidas por distintos tipos.
El resto de operaciones, que listaremos a seguir son usadas mayoritariamente para
el tipo numerico
Resta (-):
6 - 5
Multiplicacion (*):
12 * 4
Division (/):
4 / 2
Potenciacion ( ^ ) :
3 ^ 4 (o, equivalentemente, pow(3, 4), o 3 ** 4 )
Resto de division ( % ) :
12 % 7 El resto de la division de 12 entre 7. En este caso es 5
'''
#OPERACIONES BOOLEANAS
'''
En ciertas ocaciones, necesitamos condicionar nuestro programa a mas
de una condicion. Consideremos el siguiente ejemplo:
Python, comprame una empanada si hay plata y si la despensa tiene
empanada de pollo.
Como le decimos a python que haga la instruccion?
Usando el operador and ( & )
'''
hay_plata = False
hay_empanada = True
comprar = hay_empanada and hay_plata #equivalentemente, hay_empanada & hay_plata
'''
El operador and recibe DOS booleans, y devuelve UNO. Este resultado sera verdadero
solamente si los dos booleans, sean verdadero, caso contrario devolvera Falso.
Otro operador muy comun es el operador booleano or ( | )
'''
print(hay_empanada or hay_plata) #equivalentemente, hay_empanada | hay_plata
'''
Un ultimo operador, es la negacion. Se pone al inicio del boolean, y lo cambia de sentido
'''
no_hay_plata = not hay_plata #sera Verdadero
'''
Recuerden que al igual que en matematicas, Python va a realizar lo que este dentro
de parentesis en primer lugar.
'''
print (not ( False and (True or True) ) )
#que va a imprimir la consola?
| false
|
1a3bd1022273e086eeeb742ebace201d1aceceae
|
tmoraru/python-tasks
|
/less9.py
| 434
| 4.1875
| 4
|
#Print out the slice ['b', 'c', 'd'] of the letters list.
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(letters[1:4])
#Print out the slice ['a', 'b', 'c'] of the letters list
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(letters[0:3])
#Print out the slice ['e', 'f', 'g'] of the letters list.
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print(letters[4:]) #or use the command print(letters[-3:])
| true
|
d4076402594b83189895f19cdc4730f9bd5e9072
|
liginv/LP3THW
|
/exercise11-20/ex15.py
| 547
| 4.15625
| 4
|
# Importing the function/module argv from sys library in python
from sys import argv
# Assigning the varable script & filename to argv function
script, filename = argv
# Saving the open function result to a variable txt.
# Open function is the file .txt file.
txt = open(filename)
# Printing the file name.
print(f"Here's your file {filename}:")
# Printing the content of the file.
print(txt.read())
# Closing the file.
txt.close()
# trying with inout alone.
file = input("Enter the file name: ")
txt1 = open(file)
print(txt1.read())
txt1.close()
| true
|
8aaab09f3b60c92e1b2ffa700e991086cdaf24d2
|
liweicai990/learnpython
|
/Code/Leetcode/top-interview-questions-easy/String33.py
| 1,141
| 4.21875
| 4
|
'''
功能:整数反转
来源:https://leetcode-cn.com/explore/featured/card/top-interview-questions-easy/5/strings/33/
重点:整数逆序算法
作者:薛景
最后修改于:2019/07/19
'''
# 本题需要分成正数和负数两种情况讨论,所以我们用sign存下该数的符号,然后对其求绝
# 对值,再统一进行正整数的逆序算法,以化简问题难度
# 该方案战胜 88.27 % 的 python3 提交记录
class Solution:
def reverse(self, x: int) -> int:
sign = 1 if x>=0 else -1 # 符号位
res = 0
x = abs(x) # 求绝对值
while x>0:
res = res*10 + x%10 # 求余数计算原数的最后一位,并计入结果
x = x // 10 # 通过整除,去掉原数的最后一位
res = sign * res
# 下方的代码是为了满足题目对结果范围的限定而编写的
if -2**31 <= res <= 2**31-1:
return res
else:
return 0
# 以下是本地测试代码,提交时只需复制上面的代码块即可
solution = Solution()
print(solution.reverse(-123))
| false
|
7106600daa9540e96be998446e8e199ffd56ec28
|
rhino9686/DataStructures
|
/mergesort.py
| 2,524
| 4.25
| 4
|
def mergesort(arr):
start = 0
end = len(arr) - 1
mergesort_inner(arr, start, end)
return arr
def mergesort_inner(arr, start, end):
## base case
if (start >= end):
return
middle = (start + end)//2
# all recursively on two halves
mergesort_inner(arr, middle + 1, end)
mergesort_inner(arr, start, middle)
## merge everything together
temp = [0 for item in arr]
temp_it = start
first_half_it = start
first_half_end = middle
second_half_it = middle + 1
second_half_end = end
## merge the two halves back into a temp array
while (first_half_it <= first_half_end and second_half_it <= second_half_end):
if arr[first_half_it] < arr[second_half_it]:
temp[temp_it] = arr[first_half_it]
first_half_it += 1
else:
temp[temp_it] = arr[second_half_it]
second_half_it += 1
temp_it += 1
##copy remainders/ only one of the two will fire at ay given time
while(first_half_it <= first_half_end):
temp[temp_it] = arr[first_half_it]
first_half_it += 1
temp_it += 1
while(second_half_it <= second_half_end):
temp[temp_it] = arr[second_half_it]
second_half_it += 1
temp_it += 1
## copy everything back into array
size = end - start + 1
arr[start:(start + size) ] = temp[start:(start + size)]
def quicksort(arr):
start = 0
end = len(arr) - 1
quicksort_inner(arr, start, end)
return arr
def quicksort_inner(arr, left, right):
## Base case
if left >= right:
return
#get a pivot point, in this case always use middle element
pivot_i = (left + right)//2
pivot = arr[pivot_i]
## partition array around pivot
index = partition(arr, left, right, pivot)
##recursively sort around index
quicksort_inner(arr, left, index-1)
quicksort_inner(arr, index, right)
def partition(arr, left, right, pivot):
while (left <= right):
while arr[left] < pivot:
left +=1
while arr[right] > pivot:
right -= 1
if left < right:
arr[left], arr[right] = arr[right], arr[left]
left += 1
right -= 1
return left
def main():
arr = [3,6,4,8,4,1,3,5,3]
arr2 = arr[:]
sorted_arr = mergesort(arr)
print(sorted_arr)
sorted_arr = quicksort(arr2)
print(sorted_arr)
if __name__ == "__main__":
main()
| true
|
8b54f8006c98b5e88b7dd655e8338bb4fe3ba02c
|
CyberSamurai/Test-Project-List
|
/count_words.py
| 574
| 4.4375
| 4
|
"""
-=Mega Project List=-
5. Count Words in a String - Counts the number of individual words in a string.
For added complexity read these strings in from a text file and generate a
summary.
"""
import os.path
def count_words(string):
words = string.split()
return len(words)
def main(file):
filename = os.path.abspath(file)
with open(filename, 'r') as f:
count = [count_words(line) for line in f]
for i, v in enumerate(count):
print "Line %d has %d words in it." % (i+1, v)
if __name__ == '__main__':
main('footext.txt')
| true
|
f5f862e7bc7179f1e9831fe65d20d4513106e764
|
AhmedMohamedEid/Python_For_Everybody
|
/Data_Stracture/ex_10.02/ex_10.02.py
| 1,079
| 4.125
| 4
|
# 10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
# Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.
# Use the file name mbox-short.txt as the file name
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
hour = dict()
for line in handle:
line.rstrip()
if not line.startswith('From '): continue
words = line.split()
hour[words[5]] = hour.get(words[5] , 0 ) + 1
#print (hour)
hour2 = dict()
for key in hour.keys():
key.split(":")
hour2[key[0:2]] = hour2.get(key[0:2],0)+1
#print (hour2)
lst = []
for a,b in hour2.items():
lst.append((a,b))
lst.sort()
for a,b in lst:
print (a,b)
# ############# OutPut ==
# 04 3
# 06 1
# 07 1
# 09 2
# 10 3
# 11 6
# 14 1
# 15 2
# 16 4
# 17 2
# 18 1
# 19 1
| true
|
14fd0afadadb85ccffb9e5cb447fa155874479ea
|
thienkyo/pycoding
|
/quick_tut/basic_oop.py
| 657
| 4.46875
| 4
|
class Animal(object):
"""
This is the animal class, an abstract one.
"""
def __init__(self, name):
self.name = name
def talk(self):
print(self.name)
a = Animal('What is sound of Animal?')
a.talk() # What is sound of Animal?
class Cat(Animal):
def talk(self):
print('I\'m a real one,', self.name)
c = Cat('Meow')
c.talk() # I'm a real one, Meow
# Compare 2 variables reference to a same object
a = [1, 2, 3]
b = a
print(b is a) # True
# Check if 2 variables hold same values
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b) # False
print(a == b) # True
# None is an Object
print(None is None) # True
| true
|
d0ac9c79bc132a70a1542d97018838a58e7d7835
|
OlegLeva/udemypython
|
/72 Бесконечный генератор/get_current.py
| 788
| 4.21875
| 4
|
# def get_current_day():
# week = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
# i = 0
# while True:
# if i >= len(week):
# i = 0
# yield week[i]
# i += 1
#
#
# amount_day = int(input('Введите количество дней '))
# current_day = get_current_day()
# count = 0
# while count != amount_day:
# print(next(current_day))
# count += 1
def get_infinite_square_generator():
"""
:return:
"""
i = 1
while True:
yield i ** 2
i += 1
infinite_square_generator = get_infinite_square_generator()
print(next(infinite_square_generator))
print(next(infinite_square_generator))
print(next(infinite_square_generator))
print(next(infinite_square_generator))
| false
|
4f330c0fdbe5a6cc49b506011b88c610ef1abc60
|
Jules-Boogie/controllingProgramFlow
|
/SearchAStringFunction/func.py
| 1,087
| 4.21875
| 4
|
"""
A function to find all instances of a substring.
This function is not unlike a 'find-all' option that you might see in a text editor.
Author: Juliet George
Date: 8/5/2020
"""
import introcs
def findall(text,sub):
"""
Returns the tuple of all positions of substring sub in text.
If sub does not appears anywhere in text, this function returns the empty tuple ().
Examples:
findall('how now brown cow','ow') returns (1, 5, 10, 15)
findall('how now brown cow','cat') returns ()
findall('jeeepeeer','ee') returns (1,2,5,6)
Parameter text: The text to search
Precondition: text is a string
Parameter sub: The substring to search for
Precondition: sub is a nonempty string
"""
result = ()
start = 0
l = len(sub)
while start < len(text):
print(str(start) + "first")
if (sub in text) and (text.find(sub,start,start+l+1) != -1):
start = (text.find(sub,start,start+l+1))
result = result + (start,)
start = start + 1
print(str(start) + "end")
return result
| true
|
b1185e9c9738f772857051ae03af54a4fb20487e
|
Jules-Boogie/controllingProgramFlow
|
/FirstVowel-2/func.py
| 976
| 4.15625
| 4
|
"""
A function to search for the first vowel position
Author: Juliet George
Date: 7/30/2020
"""
import introcs
def first_vowel(s):
"""
Returns the position of the first vowel in s; it returns -1 if there are no vowels.
We define the vowels to be the letters 'a','e','i','o', and 'u'. The letter
'y' counts as a vowel only if it is not the first letter in the string.
Examples:
first_vowel('hat') returns 1
first_vowel('grrm') returns -1
first_vowel('sky') returns 2
first_vowel('year') returns 1
Parameter s: the string to search
Precondition: s is a nonempty string with only lowercase letters
"""
result = len(s)
vowels = ['a','e','i','o','u']
for x in vowels:
if x in s:
result = min(result,introcs.find_str(s,x))
if not x in s and "y" in s and introcs.rfind_str(s,"y") != 0:
result = introcs.rfind_str(s,"y")
return result if result != len(s) else -1
| true
|
b7d990539a50faef24a02f8325342f385f518101
|
github0282/PythonExercise
|
/Abhilash/Exercise2.py
| 1,141
| 4.34375
| 4
|
# replace all occurrences of ‘a’ with $ in a String
text1 = str(input("Enter a string: "))
print("The string is:", text1)
search = text1.find("a")
if(search == -1):
print("Character a not present in string")
else:
text1 = text1.replace("a","$")
print(text1)
# Take a string and replace every blank space with hyphen
text2 = str(input("Enter a string: "))
print("The string is:", text2)
text2 = text2.replace(" ","-")
print(text2)
# count the number of upper case and lower-case letters in a string
text3 = str(input("Enter a desired string: "))
print(text3)
UpperCase = 0
LowerCase = 0
for i in text3:
if( i >= "a" and i <= "z"):
LowerCase = LowerCase + 1
if( i >= "A" and i <= "Z"):
UpperCase = UpperCase + 1
print("No of UpperCase Characters: ", UpperCase)
print("No of LowerCase Characters: ", LowerCase)
# Check if a substring is present in a given string
text4 = str(input("Enter a desired string: "))
substring = str(input("Enter the substring: "))
if(text4.find(substring) == -1):
print("Substring is not present in the string")
else:
print("Substring is present in the string")
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.