blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
26ccdbc2bae76c99ce4409f4dbaef17419d78086 | sam676/PythonPracticeProblems | /Robin/palindromeNumber.py | 1,709 | 4.3125 | 4 | """
Sheltered at home, you are so bored out of your mind that you start thinking
about palindromes. A palindrome, in our case, is a number that reads the
same in reverse as it reads normally. Robin challenges you to write a
function that returns the closest palindrome to any number of your choice.
If your number is exactly in between two palindromes, return the smaller
number. If the number you chose IS a palindrome, return itself. Have fun!
"""
def palindromeNum(number):
number = str(number)
reverse = number
reverse = reverse[::-1]
#if the given number is the same going forwards as is backwards
#return the number
if str(number) == reverse:
return(number)
else:
#otherwise divide the number in half
half = len(number) // 2
#convert the number from an int to a string
number = str(number)
#if the length of the number is odd, add one to the legth
if (len(number) % 2):
half += 1
#store the firt half of the number
start = number[:half]
#store the seconf half of the number minus the middle number
end = start[0:half-1]
#reverse the second half of the number
end = end[::-1]
#combine both parts of the number to make a palindrome
newNumber = start + end
else:
#if the number is even, divide it in half
newNumber = number[:half]
#reverse the beginning and combine both parts of the number to
#make a palindrome
newNumber += newNumber[::-1]
return(newNumber)
#drivers
print(palindromeNum(123456))
print(palindromeNum(1234567))
| true |
095000b97fa3e4993fef3682cb33e688586eb4ae | sam676/PythonPracticeProblems | /Robin/isMagic.py | 1,199 | 4.53125 | 5 | """
You've heard about Magic Squares, right?
A magic square is one big square split into separate squares
(usually it is nine separate squares, but can be more), each containing a unique number.
Each horizontal, vertical, and diagonal row MUST add up to the same number
in order for it to be considered a magic square.
Now, it's up to you to write a function that accepts a two-dimensional
array and checks if it is a magic square or not.
Examples:
isMagic([
[6, 1, 8],
[7, 5, 3],
[2, 9, 4]
]) β true
isMagic([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]) β false
"""
def isMagic(array):
magic = True
sumEach = []
rowNumber = 0
colNumber = 0
for row in range (len(array)):
for column in range (len(array)):
rowNumber += array[row][column]
colNumber += array[column][row]
sumEach.append(rowNumber)
sumEach.append(colNumber)
rowNumber = 0
colNumber = 0
for x in range(1, len(sumEach)):
if sumEach[x] != sumEach[x-1] :
magic = False
return magic
#driver
print(isMagic([
[6, 1, 8],
[7, 5, 3],
[2, 9, 4]
]))
print(isMagic([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
])) | true |
57a76e4402bad59476588863a63a67e89e5d5bd0 | sam676/PythonPracticeProblems | /Robin/numScanner.py | 1,174 | 4.25 | 4 | """
How are our lovely number people doing today?
We're going to have an exclusive numbers-only party next week.
You can bring any type of friends that wear "String" clothes as long as they are real number.
As we expect the infinite number of numbers to come to the party,
we should rather build a scanner that will scan every guest and validate whether
they are a real numbers. If any number brings a fake guest, it will be kicked out of our world!
Can your team build a special function that will be used in the scanner?
Please remember, all guests will be wearing string clothes.
For example,
numScanner("2.2") β true
numScanner("1208") β true
numScanner("number") β false
numScanner("0x71e") β false
numScanner("2.5.9") β false
"""
def numScanner(input):
count = 0
if input.isdigit():
return True
for x in input:
if x.isalpha():
return False
if x == '.':
count += 1
if count > 1:
return False
return True
#driver
print(numScanner("2.2"))
print(numScanner("1208"))
print(numScanner("number"))
print(numScanner("0x71e"))
print(numScanner("2.5.9"))
| true |
a4b9901488a005c10a02c477fa009b2131fa8906 | sam676/PythonPracticeProblems | /Robin/addPositiveDigit.py | 501 | 4.125 | 4 | """
Beginner programmer John Doe wants to make a program that adds and outputs each positive digit
entered by the user (range is int). For instance, the result of 5528 is 20 and the result of 6714283 is 31.
"""
def addPositiveDigit(n):
total = 0
if n >= 0:
for x in str(n):
total += int(x)
else:
return "Please enter a positive number!"
return total
#driver
print(addPositiveDigit(5528))
print(addPositiveDigit(6714283))
print(addPositiveDigit(-6714283))
| true |
e241aa2106c8e48c37c3531b6d7fa8bdbbf216e7 | amirrulloh/python-oop | /leetcode/2. rverse_integer.py | 863 | 4.1875 | 4 | #Definition
"""
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers
within the 32-bit signed integer range: [β231, 231 β 1]. For the purpose
of this problem, assume that your function returns 0 when the reversed
integer overflows.
"""
class Solution:
def reverse(self, x):
negFlag = 1
if x < 0:
negFlag = -1
strx = str(x)[1:]
else:
strx = str(x)
x = int(strx[::-1])
return 0 if x > pow(2, 31) else x * negFlag
test = Solution()
print(test.reverse(123))
print(test.reverse(-123))
print(test.reverse(120)) | true |
c097cfa78f6c8bc2a62eb04cd86023c51f221b5d | miller9/python_exercises | /17.py | 1,337 | 4.625 | 5 | print ('''
17. Write a version of a palindrome recognizer that also accepts phrase palindromes
such as "Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?",
"Step on no pets", "Sit on a potato pan, Otis", "Lisa Bonet ate no basil",
"Satan, oscillate my metallic sonatas", "I roamed under it as a tired nude Maori",
"Rise to vote sir", or the exclamation "Dammit, I'm mad!".
Note that punctuation, capitalization, and spacing are usually ignored.
Palindrome examples:
"Go hang a salami I'm a lasagna hog.",
"Was it a rat I saw?",
"Step on no pets",
"Sit on a potato pan, Otis",
"Lisa Bonet ate no basil",
"Satan, oscillate my metallic sonatas",
"I roamed under it as a tired nude Maori",
"Rise to vote sir",
"Dammit, I'm mad!".
''')
def palindrome_recognizer():
print ('---')
str1 = str( input('Please enter the phrase to verify if its palindrome or not: ') )
phrase = str1.lower()
phrase = phrase.strip('ΒΏ?.,\'Β‘!')
print (phrase)
print ()
str2 = ""
subs = -1
i = 0
for index, character in enumerate(phrase):
str2 += phrase[len(phrase) + subs]
subs -= 1
if str2[index] == phrase[len(phrase) + subs]:
print (True, '--> The phrase is palindrome!')
else:
print (False, '--> The phrase is not a palindrome!')
print ('---')
print ()
palindrome_recognizer()
| true |
571f2c597feb3192b9d5f7cf72e6403ef8b332c9 | miller9/python_exercises | /12.py | 384 | 4.21875 | 4 | print ('''
12. Define a procedure histogram() that takes a list of integers and prints a histogram to the screen.
For example, histogram( [ 4, 9, 7 ] ) should print the following:
****
*********
*******
''')
def histogram(l):
for value in l:
print ("*" * value)
int_list = [4, 9, 7]
print ('The histogram of the list:', int_list, 'is:')
histogram(int_list)
print ()
| true |
111e530378568654c44b14627fe5f11fe8493a43 | miller9/python_exercises | /10.py | 1,024 | 4.34375 | 4 | print ('''
10. Define a function overlapping() that takes two lists and
returns True if they have at least one member in common, False otherwise.
You may use your 'is_member()' function, or the 'in' operator,
but for the sake of the exercise, you should (also) write it using two nested for-loops.
''')
def overlapping(a_list, b_list):
print ('The first list is: ', a_list)
print ('The second list is: ', b_list)
i = 0
x1 = []
x2 = []
if (len(a_list) > len(b_list)):
x1 = a_list
x2 = b_list
else:
x1 = b_list
x2 = a_list
while i < len(x1):
for num in x1:
# Using the 'in' operator to verify if the member belongs to the other list
# if num in x2:
if (num == x2[i]):
print ('\nThere is at least 1 member repeated -->', num)
return True
i += 1
return False
list_1 = ['python', 963, 'abc', 321, 954810, 3]
list_2 = [12, 'py', 'bwqeqweqwc', 9, 1, 2, 4, 5, 6, 7, 8, 963]
ans = overlapping(list_1, list_2)
print ('Have both lists at least 1 member in common?', ans)
print () | true |
e14c143ea086ca19b10c2f4f9cb59e0d4d55f651 | benjaminhuanghuang/ben-leetcode | /0306_Additive_Number/solution.py | 2,106 | 4.21875 | 4 | '''
306. Additive Number
Additive number is a string whose digits can form additive sequence.
A valid additive sequence should contain at least three numbers. Except for the first two numbers,
each subsequent number in the sequence must be the sum of the preceding two.
For example:
"112358" is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8.
1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
"199100199" is also an additive number, the additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.
Given a string containing only digits '0'-'9', write a function to determine if it's an additive number.
Follow up:
How would you handle overflow for very large input integers?
'''
class Solution(object):
def isAdditiveNumber(self, nums):
"""
:type num: str
:rtype: bool
"""
if not nums or len(nums) < 3:
return False
n = len(nums)
for i in xrange(1, n):
for j in xrange(i + 1, n):
if self.dfs(0, i, j, n, nums):
return True
return False
def dfs(self, start, first, second, n, num):
first_num, second_num = num[start:first], num[first:second]
if (len(first_num) > 1 and first_num[0] == '0') or (len(second_num) > 1 and second_num[0] == '0'):
return False
temp_sum = int(first_num) + int(second_num)
if temp_sum == int(num[second:]) and num[second] != '0':
return True
max_len = max(first - start, second - first)
if second + max_len <= n:
status = False
if temp_sum == int(num[second:second + max_len]):
status = self.dfs(first, second, second + max_len, n, num)
if not status and second + max_len + 1 <= n and temp_sum == int(num[second:second + max_len + 1]):
status = self.dfs(first, second, second + max_len + 1, n, num)
return status
return False
| true |
a4ff52bf767bec2d17ad4e192855aa4380807c6b | benjaminhuanghuang/ben-leetcode | /0398_Random_Pick_Index/solution.py | 1,366 | 4.125 | 4 | '''
398. Random Pick Index
Given an array of integers with possible duplicates, randomly output the index of a given target number.
You can assume that the given target number must exist in the array.
Note:
The array size can be very large. Solution that uses too much extra space will not pass the judge.
Example:
int[] nums = new int[] {1,2,3,3,3};
Solution solution = new Solution(nums);
// pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
solution.pick(3);
// pick(1) should return 0. Since in the array only nums[0] is equal to 1.
solution.pick(1);
'''
import random
# passed at first try!
class Solution(object):
def __init__(self, nums):
"""
:type nums: List[int]
:type numsSize: int
"""
self.nums = nums
self.dict = {}
for i in xrange(len(nums)):
if nums[i] in self.dict:
self.dict[nums[i]].append(i)
else:
self.dict[nums[i]] = [i]
def pick(self, target):
"""
:type target: int
:rtype: int
"""
# You can assume that the given target number must exist in the array.
indexes = self.dict[target]
return indexes[random.randint(0, len(indexes) - 1)]
s = Solution([1, 2, 3, 3, 3])
print s.pick(3)
print s.pick(1)
| true |
fc6127107d0807ee269b4505543ee30741c4695a | benjaminhuanghuang/ben-leetcode | /0189_Rotate_Array/solution.py | 1,649 | 4.1875 | 4 | '''
189. Rotate Array
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
'''
class Solution(object):
def rotate_lazy(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k = k % n
# !! Do not use nums = nums[n - k:] + nums[:n - k]
nums[:] = nums[n - k:] + nums[:n - k]
def reverse(self, nums, start, end):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start += 1
end -= 1
# time O(n) space O(1)
def rotate(self, nums, k):
if not nums:
return
if k <= 0:
return
n = len(nums)
k %= n
# reverse first part
self.reverse(nums, 0, n - k - 1)
# reverse second part
self.reverse(nums, n - k, n - 1)
# reverse whole list
self.reverse(nums, 0, n - 1)
# time O(kn) space O(1)
def rotate_3(self, nums, k):
if not nums:
return
if k <= 0:
return
n = len(nums)
k %= n
t = 0
while t < k:
last = nums[-1]
for i in xrange(n - 1, 0, -1):
nums[i] = nums[i - 1]
nums[0] = last
t += 1
s = Solution()
nums = [1, 2, 3, 4, 5, 6, 7]
s.rotate_3(nums, 3)
print nums
| true |
45929efac6474bb344733cd8130f9c2ea68f7bcd | benjaminhuanghuang/ben-leetcode | /0414_Third_Maximum_Number/solution.py | 2,003 | 4.1875 | 4 | '''
414. Third Maximum Number
Given a non-empty array of integers, return the third maximum number in this array. If it does not exist,
return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.
'''
MIN_INT = -2 ** 31
class Solution(object):
def thirdMax_my(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_1 = MIN_INT - 1 # for case [1,2,MIN_INT]
max_2 = MIN_INT - 1
max_3 = MIN_INT - 1
for n in nums:
if n >= max_1:
if n > max_1:
max_3 = max_2 # Note the order!!!
max_2 = max_1
max_1 = n
elif n >= max_2:
if n > max_2:
max_3 = max_2
max_2 = n
elif n >= max_3:
max_3 = n
if max_3 == MIN_INT - 1:
return max_1
return max_3
def thirdMax_better(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_1 = MIN_INT - 1 # for case [1,2,MIN_INT]
max_2 = MIN_INT - 1
max_3 = MIN_INT - 1
for n in nums:
if n > max_1:
max_3 = max_2 # Note the order!!!
max_2 = max_1
max_1 = n
elif max_1> n and n > max_2:
max_3 = max_2
max_2 = n
elif max_2 > n and n > max_3:
max_3 = n
if max_3 == MIN_INT - 1:
return max_1
return max_3
s = Solution()
n = s.thirdMax([2, 2, 3, 1])
print n
| true |
e6cdd47a3fe566991b401e000debe99d16451178 | benjaminhuanghuang/ben-leetcode | /0031_Next_Permutation/solution.py | 1,715 | 4.125 | 4 | '''
31. Next Permutation
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 -> 1,3,2
3,2,1 -> 1,2,3
1,1,5 -> 1,5,1
'''
class Solution(object):
# https://www.hrwhisper.me/leetcode-permutations/
#
def nextPermutation(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
j, k = len(nums) - 2, len(nums) - 1
# from right to left, find out the "first" number it is less than the adjacent number at right side
while j >= 0:
if nums[j] < nums[j + 1]:
break
j -= 1
# if all number arranges descending, sort (ascending order) and return
if j < 0:
nums.sort()
return
# The right section of the numbers are in descending order
# find smallest number (bigger than nums[j])in the right section of the numbers
while k > j:
if nums[k] > nums[j]:
break
k -= 1
nums[j], nums[k] = nums[k], nums[j]
# reverse the right section
nums[:] = nums[:j + 1] + nums[:j:-1]
s = Solution()
input = [1, 3, 0, 6, 5]
s.nextPermutation(input)
print input
input = [1, 2, 3, 4]
s.nextPermutation(input)
print input
input = [3, 2, 1]
s.nextPermutation(input)
print input
| true |
b8f6e39447a33973e6a3d806cc407b73b372f7be | walokra/theeuler | /python/euler-1_fizzbuzz.py | 413 | 4.125 | 4 | # Problem 1
# 05 October 2001
#
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
#
# Answer: 233168
#
#!/usr/bin/python
sum = 0
max = 1000
for i in range(1,max):
if i%3 == 0 or i%5 == 0:
sum = sum + i
print 'sum of 3/5 modulos < ' + str(max) + ': ' + str(sum)
| true |
503423d6683506ce9ff4fde7f73cfbd7b1cb5145 | tolaoner/Python_Exercises | /different_numbers.py | 613 | 4.125 | 4 | '''Create a sequence of numbers and determine whether
all the numbers of it are different from each other'''
import random
list_numbers=[]
different=True
for i in range(5):
list_numbers.append(random.randrange(1,10,1))
print(list_numbers[i])
for i in range(5):
for j in range(5):
if i==j:
continue
if list_numbers[i]==list_numbers[j]:
different=False
print('All numbers are different!'if different else 'There are same numbers!')
'''Correct solution.
Better Solution:
with set() method! set() sorts the iterables and removes repeating
elements! In dictionary, only keys remain after conversion!''' | true |
399474bdd93e47d000ed9ae9734dd2e5b85fe660 | Siddhant6078/Placement-Programs | /Python/factors_of_a_num.py | 214 | 4.25 | 4 | # Python Program to find the factors of a number
def print_factors(n):
print 'Factors of {0} are:'.format(n)
for x in xrange(1,n+1):
if n % x == 0:
print x
n1 = int(input('Enter a n1: '))
print_factors(n1) | true |
92f4bea4efbe1c7549407a44b85bf03ceeb25104 | Siddhant6078/Placement-Programs | /Python/swap two variables.py | 663 | 4.34375 | 4 | # Python program to swap two variables using 3rd variable
x = input('Enter value of x: ')
y = input('Enter value of y: ')
print 'The value of x: Before:{0}'.format(x)
print 'The value of y: Before:{0}'.format(y)
temp = x
x = y
y = temp
print 'The value of x: After:{0}'.format(x)
print 'The value of y: After:{0}'.format(y)
# Python program to swap two variables without using 3rd variable
a = input('Enter value of a: ')
b = input('Enter value of b: ')
print 'The value of a: Before:{0}'.format(a)
print 'The value of b: Before:{0}'.format(b)
a = a+b
b = a-b
a = a-b
print 'The value of a: After:{0}'.format(a)
print 'The value of b: After:{0}'.format(b) | true |
e3f91759b3e4661e53e1c5bb42f6525cef89b2d5 | Siddhant6078/Placement-Programs | /Python/Positive or Negative.py | 319 | 4.5 | 4 | # Program to Check if a Number is Positive, Negative or 0
# Using if...elif...else
num = float(input('Enter a Number: '))
if num > 0:
print 'Positive'
elif num == 0:
print 'Zero'
else:
print 'Negative'
# Using Nested if
if num >= 0:
if num == 0:
print 'Zero'
else:
print 'Positive'
else:
print 'Negative' | true |
73fed6743975942f340fc78009c16b9e2cf7b875 | abhinavkuumar/codingprogress | /employeeDict.py | 1,049 | 4.1875 | 4 | sampleDict = {
'emp1': {'name': 'John', 'salary': 7500},
'emp2': {'name': 'Emma', 'salary': 8000},
'emp3': {'name': 'Tim', 'salary': 6500}
}
while 1:
answer = input("Do you want to add or remove an employee? Select q to quit (a/r/q) ")
newlist = list(sampleDict.keys())
if answer == 'a':
name = input("Please enter the name ")
salary = int(input("Please enter the salary "))
value = newlist[-1]
newID=(int(value[-1]) + 1)
employeeID = "emp" + str(newID)
sampleDict[employeeID] = {'name': name, 'salary': salary}
print(str(sampleDict))
print("Employee sucessfully added to database")
if answer == 'r':
empID = input("Please enter the employee ID (ex: emp45) ")
if empID in newlist:
print("Employee found")
del sampleDict[empID]
print("Employee removed from database")
else:
print("Employee not found")
if answer == 'q':
break
print("Thank you for using our system!")
| true |
2da72ad227e82145ffd64f73b39620330c83c21d | greenhat-art/guess-the-number | /guessingGame.py | 604 | 4.3125 | 4 | import random
print("Number guessing game")
number = random.randint(1, 9)
chances = 0
print("Guess a number between 1 to 9:")
while chances < 5:
guess = int(input("Enter your guessed number:- "))
if guess == number:
print("Congratulation you guessed the right number!")
break
elif guess < number:
print("Your guess was low...Choose a higher number than", guess)
else:
print("Your guess was too high: Guess a number lower than", guess)
chances += 1
if not chances < 5:
print("Sorry, you lost. The number is", number) | true |
957d95428e0af1b303930e7071dfbe710f84f99b | anasm-17/DSA_collaborative_prep | /Problem_sets/fizzbuzz/fizzbuzz_jarome.py | 1,879 | 4.3125 | 4 | from test_script.test import test_fizzbuzz
"""
A classic Data Structures an algorithms problem, you are given an input array of integers from 1 to 100 (inclusive).
You have to write a fizzbuzz function that takes in an input array and iterates over it. When your function receives
a number that is a factor of 3 you should store 'Fizz' in the output array, if the number is a factor of 5 then you
should store 'Buzz' in the output array. Additionally, if the number is a factor of both 3 and 5, you must store
'FizzBuzz' in the output array. For all other cases, you must store the numbers as they are. Return the output array
from your function.
"""
def jaybuzz(some_input):
""" This function consumes a LIST of integers from 1 to 100 (inclusive) and produces a LIST with values
corresponding to the following rules:
For a number that is a factor of 3, output 'Fizz'
For a number that is a factor of 5, output 'Buzz'
For a number that is a factor of 3 and 5, output 'Fizzbuzz'
For all other numbers return them as is
Paramaters:
some_input - A list
Example:
jaybuzz([1,2,3,5,15]) = [1,2,'Fizz', 'Buzz', 'Fizzbuzz']
"""
result = []
if len(some_input) == 0:
return result
for i in some_input:
assert(type(i)== int), "Invalid input provided. Numbers must be integers"
assert(1 <= i <= 100),"Invalid input provided. Function should consume an array of integers from 1 to 100 (inclusive)"
if i % 15 == 0:
result.append('FizzBuzz')
continue
elif i % 3 == 0:
result.append('Fizz')
continue
elif i % 5 == 0:
result.append('Buzz')
continue
else:
result.append(i)
return result
if __name__ == '__main__':
test_fizzbuzz(jaybuzz) | true |
dd80e66757066ef8d97911680ffb0e47411d9c25 | jineshshah101/Python-Fundamentals | /Casting.py | 580 | 4.3125 | 4 | # variable example
x = 5
print(x)
# casting means changing one data type into another datatype
# casting the integer x into a float
y = float(x)
print(y)
# casting the integer x into a string
z = str(x)
print(z)
# Note: Cannot cast a string that has letters in it to a integer. The string itself must be numbers
# Casting string to an integer
t = int("55")
print(t)
# for boolen if you have the value be 0 it will be false. Any other value except for 0 will come out as true
h = bool(0)
print(h)
j = bool(1)
print(j)
k = bool(-5)
print(k) | true |
6141bb86224dbc1c19efca92f530682d1a04e570 | jineshshah101/Python-Fundamentals | /Calendar.py | 1,448 | 4.46875 | 4 | import calendar
#figuring things out with calendar
# printing out the week headers
# using the number 3 so we can get 3 characters for the week header
week_header = calendar.weekheader(3)
print(week_header)
print()
# print out the index value that represents a weekday
# in this case we are getting the index of the first weekday
# [0,1,2,3,4,5,6] correlates to Mon, Tue, Wed, Thu, Fri, Sat, Sun
weekday_index = calendar.firstweekday()
print(weekday_index)
print()
# print out the march month of 2019
# w stands for the number of characters shown for the week header
march_month = calendar.month(2019, 3, w=3)
print(march_month)
print()
# print out the days of a month in a matrix format
# in this case this is for march 2019
matrix_month_march = calendar.monthcalendar(2019, 3)
print(matrix_month_march)
print()
# print out the calendar for the entire year of 2020
entire_year = calendar.calendar(2020, w=3)
print(entire_year)
print()
# prints out the day of the week based on specific specifications in index format
day_of_the_week = calendar.weekday(2020, 1, 15)
print(day_of_the_week)
print()
# will tell you if a certain year is a leap year or not
leap_year = calendar.isleap(2020)
print(leap_year)
print()
# print out the number of leapdays within the specified years
# note: year 2 is not included in this search
leap_days_amount = calendar.leapdays(2000, 2021)
print(leap_days_amount) | true |
ce0cfdebf310432f6641ef77c298ebefefa2d2d6 | gihs-rpc/01-Sleeping-In | /challenge-1-sleeping-in-MoseliaTemp3/1.1 ~ Sleeping In.py | 1,612 | 4.34375 | 4 | #Repeatedly used things defined here for ease of modification.
EndBool = "\n (Y/N) > "
Again = "Incorrect input."
#Begin Program.
while True:
print("\n")
#Is tomorrow a school day?
SchoolTomorrow = input("Do you have school tomorrow?" + EndBool)
print()
#Repeat question until answer is "y" or "n".
while not (SchoolTomorrow.lower() == "y" or SchoolTomorrow.lower() == "n"):
print(Again)
SchoolTomorrow = input("Do you have school tomorrow?" + EndBool)
print()
#If tomorrow is a school day, is it a Wednesday?
if SchoolTomorrow.lower() == "y":
TomorrowWednesday = input("Is today Tuesday?" + EndBool)
print()
#Repeat question until answer is "y" or "n".
while not (TomorrowWednesday.lower() == "y" or TomorrowWednesday.lower() == "n"):
print(Again)
TomorrowWednesday = input("Is today Tuesday?" + EndBool)
print()
if SchoolTomorrow.lower() == "n":
#If there is no school.
print("You do not have school tomorrow, so you can sleep in as long as you want.")
elif TomorrowWednesday.lower() == "y":
#If there is school, but its a late Wednesday.
print("You have school tomorrow, but it is a Wednesday so you can sleep in a bit.")
else:
#If there is school and it is not a late Wednesday.
print("You have school tomorrow and cannot sleep in.")
#Repeat program or break loop?
print()
if input("Run again?" + EndBool).lower() != "y":
print()
break
| true |
2d9ca18c7b90af0ac266f5f8b8b684492c2bbc4e | laurendayoun/intro-to-python | /homework-2/answers/forloops.py | 2,846 | 4.40625 | 4 | """
Reminders:
for loop format:
for ELEMENT in GROUP:
BODY
- ELEMENT can be any variable name, as long as it doesn't conflict with other variables in the loop
- GROUP will be a list, string, or range()
- BODY is the work you want to do at every loop
range format is:
range(start, stop, step) or range(start, stop) or range(stop)
- if step not given, step = 1; if start not given, start = 0
- if step is negative, we decrease
"""
def forloop_1():
'''Create a for loop that prints every element in the list numbers'''
numbers = [5, 10, 15, 20, 25, 30]
### Your code here ###
for n in numbers:
print(n)
def forloop_1_2():
'''Create a for loop that prints every multiple of 5 from 5 to 30'''
# Hint: Use range. You are not allowed to use a list!
### Your code here ###
for n in range(5, 31, 5):
print(n)
def forloop_2():
'''Create a for loop that adds together all of the strings in words.
Your final string should be: My name is <name>. Replace <name> with your name in the list!'''
words = ["My ", "name ", "is ", "Lauren"]
sentence = ""
### Your code here ###
for s in words:
sentence += s
print("The string is: " + sentence)
def forloop_2_2():
'''Create a for loop that adds together all of the strings in words. Every time you add a word, add a space (" ") so that the sentence is easy to read!
Your final string should be: My name is <name>. Replace <name> with your name in the list!'''
words = ["My", "name", "is", "Lauren"]
sentence = ""
### Your code here ###
for s in words:
sentence += s + " "
print("The string is: " + sentence)
def forloop_3():
'''Create a for loop that doubles (multiplies by 2) the variable a 7 times.
The final value of a should be 128.'''
a = 1
### Your code here ###
for i in range(7):
a *= 2
print("Your result is: " + str(a))
def forloop_4():
'''Create a for loop that prints the numbers, and then the letters in mixed_list
The order of things printed should be: 1, 3, 5, b, d, f'''
mixed_list = [1, 'b', 3, 'd', 5, 'f']
### Your code here ###
for i in range(0, 6, 2):
print(mixed_list[i])
for i in range(1, 7, 2):
print(mixed_list[i])
def forloop_5():
'''Challenge Question (optional):
Code 2 different programs that print:
5
4
3
2
1
Take off!
Hint: Use a list in one program, and range in another. '''
### Your code here ###
for i in range(5, 0, -1):
print(i)
print("Take off!")
###
for i in [5, 4, 3, 2, 1, 'Take off!']:
print(i)
def main():
print("Question 1:")
forloop_1()
print("\nQuestion 1.2:")
forloop_1_2()
print("\nQuestion 2:")
forloop_2()
print("\nQuestion 2.2:")
forloop_2_2()
print("\nQuestion 3:")
forloop_3()
print("\nQuestion 4:")
forloop_4()
print("\nQuestion 5:")
forloop_5() | true |
8a93636bd5b7b955f431bc4f351583b742fe14cf | senavarro/function_scripts | /functions.py | 947 | 4.40625 | 4 | #Create a function that doubles the number given:
def double_value(num):
return num*2
n=10
n=double_value(n)
print(n)
--------------------------------------
#Create a recursive function that gets the factorial of an undetermined number:
def factorial(num):
print ("Initial value =", num)
if num > 1:
num = num * factorial(num -1)
print ("Final value =", num)
return num
print (factorial(5))
--------------------------------------
#Create a function that makes a countdown:
def countdown(num):
while num > 0:
num -=1
print(num)
else:
print("It's the final countdown")
countdown(5)
--------------------------------------
#Create a function that allows undetermined args and kwargs:
def indetermined_position(*args, **kwargs):
t=0
for arg in args:
t+=arg
print("the total amount of args is:", t)
for kwarg in kwargs:
print(kwarg, kwargs[kwarg])
indetermined_position(1,2,3,4,5,6,7,8,9, name="Sergi", age=24)
| true |
d48b8e88545ebcf87820f63294285c9b0d370331 | kingdunadd/PythonStdioGames | /src/towersOfHanoi.py | 2,977 | 4.34375 | 4 | # Towers of Hanoi puzzle, by Al Sweigart al@inventwithpython.com
# A puzzle where you must move the disks of one tower to another tower.
# More info at https://en.wikipedia.org/wiki/Tower_of_Hanoi
import sys
# Set up towers A, B, and C. The end of the list is the top of the tower.
TOTAL_DISKS = 6
HEIGHT = TOTAL_DISKS + 1
# Populate Tower A:
completeTower = list(reversed(range(1, TOTAL_DISKS + 1)))
TOWERS = {'A': completeTower,
'B': [],
'C': []}
def printDisk(diskNum):
# Print a single disk of width diskNum.
emptySpace = ' ' * (TOTAL_DISKS - diskNum)
if diskNum == 0:
# Just draw the pole of the tower.
print(emptySpace + '||' + emptySpace, end='')
else:
# Draw the disk.
diskSpace = '@' * diskNum
diskNumLabel = str(diskNum).rjust(2, '_')
print(emptySpace + diskSpace + diskNumLabel + diskSpace + emptySpace, end='')
def printTowers():
# Print all three towers.
for level in range(HEIGHT - 1, -1, -1):
for tower in (TOWERS['A'], TOWERS['B'], TOWERS['C']):
if level >= len(tower):
printDisk(0)
else:
printDisk(tower[level])
print()
# Print the tower labels A, B, and C.
emptySpace = ' ' * (TOTAL_DISKS)
print('%s A%s%s B%s%s C\n' % (emptySpace, emptySpace, emptySpace, emptySpace, emptySpace))
print('The Towers of Hanoi')
print('Move the tower, one disk at a time, to another pole.')
print('Larger disks cannot rest on top of a smaller disk.')
while True: # Main program loop.
# Display the towers and ask the user for a move:
printTowers()
print('Enter letter of "source" and "destination" tower: A, B, C, or QUIT to quit.')
print('(For example, "AB" to move the top disk of tower A to tower B.)')
move = input().upper()
if move == 'QUIT':
sys.exit()
# Make sure the user entered two letters:
if len(move) != 2:
print('Invalid move: Enter two tower letters.')
continue
# Put the letters in move in more readable variable names:
srcTower = move[0]
dstTower = move[1]
# Make sure the user entered valid tower letters:
if srcTower not in 'ABC' or dstTower not in 'ABC' or srcTower == dstTower:
print('Invalid move: Enter letters A, B, or C for the two towers.')
continue
# Make sure the src disk is smaller than the dst tower's topmost disk:
if len(TOWERS[srcTower]) == 0 or (len(TOWERS[dstTower]) != 0 and TOWERS[dstTower][-1] < TOWERS[srcTower][-1]):
print('Invalid move. Larger disks cannot go on top of smaller disks.')
continue
# Move the top disk from srcTower to dstTower:
disk = TOWERS[srcTower].pop()
TOWERS[dstTower].append(disk)
# Check if the user has solved the puzzle:
if completeTower in (TOWERS['B'], TOWERS['C']):
printTowers() # Display the towers one last time.
print('You have solved the puzzle! Well done!')
sys.exit()
| true |
0b0329ee3244562c8c7aa7abb3068f2c06737bde | codesheff/DS_EnvTools | /scripts/standard_functions.py | 706 | 4.21875 | 4 | #!/usr/bin/env python3
def genpassword(forbidden_chars:set={'!* '} , password_length:int=8) -> str:
"""
This function will generate a random password
Password will be generated at random from all printable characters.
Parameters:
forbidden_chars: Characters that are not allowed in the password
passwordLenght: Length of the password to be generated
"""
import random
import string
characters=set(string.printable)
for character in forbidden_chars:
characters.discard(character)
str_characters=''.join(characters)
new_password = ''.join(random.choice(str_characters) for i in range(password_length))
return new_password | true |
97defbcbd96034d5ac170250340d05d18732da78 | willpxxr/python | /src/trivial/sorting/quicksort.py | 2,527 | 4.25 | 4 | from math import floor
from typing import List
def _medianOf3(arr: List, begin: int, end: int) -> (int, int):
"""
Brief: Help method to provide median of three functionality to quick sort
An initial pivot is selected - then adjusted be rotating the first index, center index
and end index into the correct order. The pivot is then moved to the penultimate index
Args:
arr: List being sorted
begin: The first index in scope
end: The final index in scope
Returns: Pivot Value - The value being used at the pivot
Pivot Index - The index which contains the pivot value
"""
center = floor((begin + end) / 2)
if arr[center] < arr[begin]:
arr[begin], arr[center] = arr[center], arr[begin]
if arr[end] < arr[begin]:
arr[end], arr[begin] = arr[begin], arr[end]
if arr[end] < arr[center]:
arr[center], arr[end] = arr[end], arr[center]
arr[center], arr[end - 1] = arr[end - 1], arr[center]
return arr[end - 1], end - 1 # Pivot is not at end - 1
def _partition(arr: List, begin: int, end: int) -> int:
"""
Brief: Partition an array around a pivot point - with larger values moving to the RHS, and smaller values
to the LHS
Args:
arr: List being sorted
begin: The first index in scope
end: The final index in scope
Returns: The index held by the pivot
"""
primary_pivot, pivot_index = _medianOf3(arr, begin, end)
tortoise = begin
for hare in range(begin, pivot_index):
if arr[hare] < primary_pivot:
arr[tortoise], arr[hare] = arr[hare], arr[tortoise]
tortoise += 1
arr[tortoise], arr[pivot_index] = (
arr[pivot_index],
arr[tortoise],
) # Restore the pivot
return tortoise
def _recursiveQuickSort(arr: List, begin: int, end: int) -> None:
"""
Brief: Recursive implementation of Quicksort following the median of three rule,
to provide a more optimal pivot selection
Args:
arr: List being sorted
begin: The first index in scope
end: The final index in scope
Returns: None
"""
if begin < end:
index = _partition(arr, begin, end)
_recursiveQuickSort(arr, begin, index - 1)
_recursiveQuickSort(arr, index + 1, end)
def quickSort(arr: List) -> None:
_recursiveQuickSort(arr, 0, len(arr) - 1)
if __name__ == "__main__":
raise NotImplementedError("There is no main programme")
| true |
52d309fa9f4cca8b527da7850fca9256a34c2b6c | hannahbishop/AlgorithmPuzzles | /Arrays and Strings/rotateMatrix.py | 1,244 | 4.25 | 4 | def rotate_matrix(matrix, N):
'''
Input:
matrix: square, 2D list
N: length of the matrix
Returns:
matrix, rotated counter clockwise by 90 degrees
Example:
Input:
[a, b]
[c, d]
Returns:
[b, d]
[a, c]
Efficiency:
O(N^2)
'''
for layer in range(N):
for index in range(layer, N - 1 - layer):
temp = matrix[layer][index]
#store right in top
matrix[layer][index] = matrix[index][N - 1 - layer]
#store bottom in right
matrix[index][N - 1 - layer] = matrix[N - 1 - layer][N - 1 - index]
#store left in bottom
matrix[N - 1 - layer][N - 1 - index] = matrix[N - 1 - index][layer]
#store temp in left
matrix[N - 1 - index][layer] = temp
return matrix
def print_matrix(matrix, N):
for i in range(N):
print(matrix[i])
def main():
print("start matrix:")
N = 9
matrix = [[x for x in range(N)] for y in range(N)]
print_matrix(matrix, N)
print("rotated matrix:")
matrix_rotated = rotate_matrix(matrix, N)
print_matrix(matrix_rotated, N)
if __name__ == "__main__":
main() | true |
e72fe631c3633f59c643e7a58de5ab3c9c564eb9 | Ziiv-git/HackerRank | /HackerRank23.py | 1,987 | 4.1875 | 4 | '''
Objective
Today, weβre going further with Binary Search Trees. Check out the Tutorial tab for learning materials and an instructional video!
Task
A level-order traversal, also known as a breadth-first search, visits each level of a treeβs nodes from left to right, top to bottom. You are given a pointer, , pointing to the root of a binary search tree. Complete the levelOrder function provided in your editor so that it prints the level-order traversal of the binary search tree.
Hint: Youβll find a queue helpful in completing this challenge.
Input Format
The locked stub code in your editor reads the following inputs and assembles them into a BST:
The first line contains an integer, (the number of test cases).
The subsequent lines each contain an integer, , denoting the value of an element that must be added to the BST.
Output Format
Print the value of each node in the treeβs level-order traversal as a single line of space-separated integers.
Sample Input
6
3
5
4
7
2
1
Sample Output
3 2 5 1 4 7
'''
import sys
class Node:
def __init__(self,data):
self.right=self.left=None
self.data = data
class Solution:
def insert(self,root,data):
if root==None:
return Node(data)
else:
if data<=root.data:
cur=self.insert(root.left,data)
root.left=cur
else:
cur=self.insert(root.right,data)
root.right=cur
return root
def levelOrder(self, root):
queue = [root]
while len(queue) is not 0:
curr = queue[0]
queue = queue[1:]
print(str(curr.data) + " ", end="")
if curr.left is not None:
queue.append(curr.left)
if curr.right is not None:
queue.append(curr.right)
T=int(input())
myTree=Solution()
root=None
for i in range(T):
data=int(input())
root=myTree.insert(root,data)
myTree.levelOrder(root)
| true |
53cecd207777cb4b81667a0869fc3318f8673f47 | mciaccio/pythonCode | /udacityPythonCode/classes/inheritance.py | 2,075 | 4.34375 | 4 |
# class name first letter uppercase "P"
class Parent():
# constructor
def __init__(self, last_name, eye_color):
print("Parent Constructor called\n")
self.last_name = last_name
self.eye_color = eye_color
# super class instance method
def show_info(self):
print('Parent class - show_info instance method self.last_name is -> {}'.format(self.last_name))
print('Parent class - show_info instance method self.eye_color is -> {}\n'.format(self.eye_color))
# class name first letter uppercase "C"
# "Parent" specified as super class
class Child(Parent):
# constructor
def __init__(self, last_name, eye_color, number_of_toys):
print("Child Constructor called")
Parent.__init__(self,last_name,eye_color) # invoke (and populate) super class constructor
self.number_of_toys = number_of_toys
# subclass instance method
# method overriding - same name in super Parent class
def show_info(self):
print('Child class - show_info instance method self.last_name is -> {}'.format(self.last_name))
print('Child class - show_info instance method self.eye_color is -> {}'.format(self.eye_color))
print('Child class - show_info instance method self.number_of_toys is -> {}\n'.format(self.number_of_toys))
print("\nBegin inheritance.py module\n")
# Parent class instance
billy_cyrus = Parent("Cyrus", "blue")
print('billy_cyrus.last_name is -> {}'.format(billy_cyrus.last_name))
print('billy_cyrus.eye_color is -> {}\n'.format(billy_cyrus.eye_color))
billy_cyrus.show_info()
# Child class instance
miley_cyrus = Child("Cyrus", "Green", 5)
print('miley_cyrus.eye_color is -> {}'.format(miley_cyrus.eye_color))
print('miley_cyrus.last_name is -> {}'.format(miley_cyrus.last_name))
print('miley_cyrus.number_of_toys is -> {}\n'.format(miley_cyrus.number_of_toys))
# Child instance calls inherited super class instance method - when instance method not defined in Child class
miley_cyrus.show_info()
print("End inheritance.py module\n")
| true |
8ad0f485fbad4f5edc9df95ba3a4b21257add7bc | ashwin-magalu/Python-OOPS-notes-with-code | /access.py | 713 | 4.28125 | 4 | class Employee:
name = "Ashwin" # public member
_age = 27 # protected member
__salary = 10_000 # private member --> converted to _Employee__salary
def showEmpData(self):
print(f"Salary: {self.__salary}")
class Test(Employee):
def showData(self):
print(f"Age: {self._age}")
# print(f"Salary: {self.__salary}") # error
ashwin = Employee()
print(ashwin.name)
print(ashwin._age)
# print(ashwin.__salary) # error
print(ashwin._Employee__salary) # no error, this way we can access private variable
t = Test()
t.showData()
ashwin.showEmpData()
""" Python don't have private or protected, we use these naming conventions to make the members private, public or protected """ | true |
5761bda1dc5763f3e0acae42b4b98c928c84fb19 | pr0d33p/PythonIWBootcamp | /Functions/7.py | 422 | 4.21875 | 4 | string = "The quick Brow Fox"
def countUpperLower(string):
lowerCaseCount = 0
upperCaseCount = 0
for letter in string:
if letter.isupper():
upperCaseCount += 1
elif letter.islower():
lowerCaseCount += 1
print("No. of Upper case characters: {}".format(upperCaseCount))
print("No. of Lower case Characters: {}".format(lowerCaseCount))
countUpperLower(string) | true |
8ec919cee9c1ce1c5a1a92e94e661e153449b5cd | axisonliner/Python | /del_files.py | 1,854 | 4.125 | 4 | # Script for deleting files from a folder using the command line:
# command line: python del_files.py arg1 arg2
# - arg1 = folder path
# - arg2 = file extention
# Example: python del_files.py C:\Desktop\folder_name .exr
import os
import sys
import math
def get_size(filename):
st = os.stat(filename)
return st.st_size
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return "{0} {1}".format(s, size_name[i])
def del_files(path, file):
files_size = 0
file_num = 0
try:
directory = str(sys.argv[1])
ext_file = str(sys.argv[2])
for root, dirs, files in os.walk(directory):
path = root.split(os.sep)
for file in files:
if file.endswith(ext_file):
path_to_file = '/'.join(path) + '/' + file
files_size += get_size(path_to_file)
print("delete file: {}".format(path_to_file))
os.remove(path_to_file)
file_num += 1
if not file_num:
print("'{}' files not found".format(ext_file))
else:
print
print("{} - files have been deleted".format(file_num))
print("{} - total file size".format(convert_size(files_size)))
except IndexError:
print("Please, please provide two arguments:")
print("arg1 = folder path")
print("arg2 = file extention")
print("Example: python del_files.py C:/Desktop/folder_name .exr")
if __name__ == '__main__':
path = ""
file = ""
print
del_files(path, file)
| true |
2a0f013ad2aac2a67e9eafb1fa8a009d9aa663a8 | ESROCOS/tools-pusconsole | /app/Utilities/Database.py | 2,907 | 4.375 | 4 | import sqlite3 as sq3
from sqlite3 import Error
class Database(object):
"""
This class represents a database object. It implements
some methods to ease insertion and query tasks
"""
def __init__(self, dbname: str):
"""
This is the constructor of the class
:param dbname: The name of the database to open
"""
self.db = None
self.cursor = None
self.open_db(dbname)
def create_dump_table(self, table_name: str = "packages"):
"""
This method creates a table in the database with the
name passed as argument
:param table_name: The name of the table
"""
query = """CREATE TABLE
IF NOT EXISTS """ + table_name + """(
type text,
serv_id integer,
msg_id integer,
time text,
src integer,
des integer,
seq integer,
status text,
info text,
rest_of_data json
);"""
self.cursor.execute(query)
def create_history_table(self, table_name: str = "history"):
"""
This method creates a table in the database with the
name passed as argument
:param table_name: The name of the table
"""
query = """CREATE TABLE
IF NOT EXISTS """ + table_name + """(
name text,
packets json
);"""
self.cursor.execute(query)
def open_db(self, db_name: str):
"""
This method opens the database with the name passed as an argument
:param db_name: The name of the database to be opened
"""
try:
self.db = sq3.connect(db_name)
self.cursor = self.db.cursor()
except Error as e:
print(e)
def query_db(self, query: str, _list: tuple = None):
"""
This methods execute a query or an insertion in the db
:param query: Query using prepared statement
:param _list: Parameters of the prepared statement
:return: Results of the query
"""
if _list is None:
return self.cursor.execute(query)
else:
return self.cursor.execute(query, _list)
#REVISAR: SE ANADIERON DOS PARΓMETROS MAS A CADA ELEMENTO DE LA TABLA
#QUE NO TIENEN QUE SER INSERTADOS. ESTOS SON EL INDICE Y EL PAQUETE
#EN FORMA DE PAQUETE.
def insert_db(self, query: str, elem):
"""
This methods execute an insertion in the db
:param query: Query using prepared statement
:param elem: Parameters of the prepared statement
"""
self.cursor.executemany(query, elem)
self.db.commit()
| true |
e7eea0e92c5c8cf7c537f545b05a17a819b4d108 | pab2163/pod_test_repo | /Diana/stock_market_challenge.py | 1,221 | 4.25 | 4 | # Snippets Challenge
# Playing with the stock market.
# Write code to take in the name of the client as the user input
name = input("Hi there!\nWhat is your name?: ")
print("Hello "+ name + "!" )
# Write code to get user input savings" and personalize message with "name"
savings =int(input("What are your current savings?"))
print(f"Wow, thats amazing, you have $ {savings} to invest.")
stock = input("The avaible stocks are Apple, Amazon, Facebook, Google and Microsoft.\nWhich of these would you like to see the breakdown on?" )
print(f"Great choice {name}! We love {stock}. ")
Amazon = 3000
Apple = 100
Facebook = 250
Google = 1400
Microsoft = 200
if stock == "Amazon":
price = (3000)
shares = (savings / Amazon)
elif stock == "apple":
price = (100)
shares = (savings / Apple)
elif stock == "facebook":
price = (250)
shares = (savings / Facebook)
elif stock == "google":
price = (1400)
shares = (savings / Google)
elif stock == "microsoft":
price = (200)
shares = (savings / Microsoft)
print(f"Based on your selection, you are able to purchase {shares} of {stock}.The current market price is {price} per share.")
#else
# Perform user-specific calculation
| true |
d3db4c2dbb599de13e7396db16f96912d335b126 | Abdullahalmuhit/BT_Task | /BT_Solution.py | 548 | 4.125 | 4 | value = int (input("How many time you want to run this program?: "))
def check_palindromes(value):
charecter = input("Enter Your One Character: ")
my_str = charecter+'aDAm'
# make it suitable for caseless comparison
my_str = my_str.casefold()
# reverse the string
rev_str = reversed(my_str)
# check if the string is equal to its reverse
if list(my_str) == list(rev_str):
print("It is palindrome")
else:
print("It is not palindrome")
for x in range(value):
check_palindromes(value) | true |
9297bd49c2a7ddd20007b3d0f599ce7a15cfa670 | rajatkashyap/Python | /make_itemsets.py | 564 | 4.21875 | 4 | '''Exercise 3 (make_itemsets_test: 2 points). Implement a function, make_itemsets(words). The input, words, is a list of strings. Your function should convert the characters of each string into an itemset and then return the list of all itemsets. These output itemsets should appear in the same order as their corresponding words in the input.'''
def make_itemsets(words):
words_l=words.split()
print words_l
make_itemsets=[]
for w in words_l:
make_itemsets.append(set(w))
return make_itemsets
print make_itemsets("Hi how are you Rajat")
| true |
8095f1c33d099fcdad65003a2f4add5d07bd5090 | orionbearduo/Aizu_online_judge | /ITP1/ITP_1_6_A.py | 539 | 4.28125 | 4 | """
Reversing Numbers
Write a program which reads a sequence and prints it in the reverse order.
Input
The input is given in the following format:
n
a1 a2 . . . an
n is the size of the sequence and ai is the ith element of the sequence.
Output
Print the reversed sequence in a line. Print a single space character between adjacent elements (Note that your program should not put a space character after the last element).
"""
n = int(input())
table = list(map(int, input().split()))
table.reverse()
print(' '.join(map(str, table)))
| true |
0935e6a46fdd933261931fa71727206015745918 | orionbearduo/Aizu_online_judge | /ITP1/ITP_1_5_C.py | 824 | 4.28125 | 4 | """
Print a Chessboard
Draw a chessboard which has a height of H cm and a width of W cm. For example, the following figure shows a chessboard which has a height of 6 cm and a width of 10 cm.
#.#.#.#.#.
.#.#.#.#.#
#.#.#.#.#.
.#.#.#.#.#
#.#.#.#.#.
.#.#.#.#.#
Note that the top left corner should be drawn by '#'.
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero).
Output
For each dataset, print the chessboard made of '#' and '.'.
Print a blank line after each dataset.
"""
while True:
H, W = map(int, input().split())
if H == 0 and W == 0:
break
for i in range(H):
for j in range(W):
if (i + j) % 2 == 0:
print("#", end = '')
else:
print(".", end = '')
print()
print()
| true |
bdff89efc61f5158b6d87dd6b5eeb5f11e91b898 | orionbearduo/Aizu_online_judge | /ITP1/ITP_1_8_A.py | 245 | 4.3125 | 4 | # Write a program which converts uppercase/lowercase letters to lowercase/uppercase for a given string.
# Sample Input
# fAIR, LATER, OCCASIONALLY CLOUDY.
# Sample Output
# Fair, later, occasionally cloudy.
n = str(input())
print(n.swapcase())
| true |
dd8e680dc6602a27517af06f09319447b4256735 | renuit/renu | /factor.py | 226 | 4.125 | 4 | n=int(input("Enter a number:"))
fact=1
if(n<0):
print("No factorial for -Ve num")
elif(n==0):
print("factorial of 0 is 1")
else:
for i in range(1,n+1):
fact=fact*i
print("factorial of", n,"is",fact)
| true |
7c94602bbc0ce53124f4e2c892c85d24dcbd0331 | garima-16/Examples_python | /occurrence.py | 260 | 4.4375 | 4 | #Program to find the occurrences of a character in a string
string1=input("enter any string ")
ch=input("enter a character ")
count=0
for i in string1:
if ch==i:
count+=1
print("number of occurrences of character in string ",count)
| true |
c310929561622e694202ce37ffcd91d77ef4551c | Dinesh-Sivanandam/Data-Structures | /Linked List/insert_values.py | 1,664 | 4.375 | 4 | #Creating the class node
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
#Creating the class for linked list
class LinkedList:
#this statement initializes when created
#initializing head is none at initial
def __init__(self):
self.head = None
"""
Function for printing the linked list
if the head is none the link list is empty
else
initializing the itr value as head and incrementing
iterating until the itr is none and printing the values
"""
def print(self):
if self.head is None:
print("Linked list is empty")
return
itr = self.head
llstr = ''
while itr:
llstr += str(itr.data)+' --> ' if itr.next else str(itr.data)
itr = itr.next
print(llstr)
"""
function to insert the set of values in the linked list
this function gets the list of values
then iterate through the list values one by one
then insering the value to the end by insert_at_end function
"""
def insert_values(self, data_list):
self.head = None
for data in data_list:
self.insert_at_end(data)
def insert_at_end(self, data):
if self.head is None:
self.head = Node(data, None)
return
itr = self.head
while itr.next:
itr = itr.next
itr.next = Node(data, None)
if __name__ == '__main__':
ll = LinkedList()
ll.insert_values(["banana","mango","grapes","orange"])
ll.print()
| true |
0693111789c72af4db96730c3caa7b0cf4422571 | sachinasy/oddevenpython | /prac1.py | 268 | 4.34375 | 4 | # program to identify the even/odd state of given numbers
# function to print oddeven of given number
#oddeven function
number = int(input("enter a number: "))
if number % 2== 0:
print ("the entered number is even")
else:
print ("the entered number is odd")
| true |
e3459e66daea9d2747d6b5e5f05db326b8f2a127 | epangar/python-w3.exercises | /String/1-10/5.py | 343 | 4.125 | 4 | """
5. Write a Python program to get a single string from two given strings,
separated by a space and swap the first two characters of each string.
"""
def style_str(str1, str2):
answer1 = str2[0:2] + str1[2:]
answer2 = str1[0:2] + str2[2:]
answer = answer1 + " " + answer2
return answer
print(style_str('abc', 'xyz')) | true |
3f12cfba4069f64e2c4218935ae0649fbb5d05bd | epangar/python-w3.exercises | /String/1-10/2.py | 327 | 4.28125 | 4 | """
2. Write a Python program to count the number of characters (character frequency) in a string.
"""
def count_char(str):
dict = {}
for i in range(0, len(str)):
key = str[i]
if key in dict:
dict[key] += 1
else:
dict[key] = 1
return dict
| true |
2afa17246ba3754f0694b361e4d8f6cbc0df047d | pdshah77/Python_Scripts | /Input_Not_Required/PreFixMapSum.py | 776 | 4.28125 | 4 | '''
Write a Program to Implement a PrefixMapSum class with the following methods:
insert(key: str, value: int): Set a given key's value in the map. If the key already exists, overwrite the value.
sum(prefix: str): Return the sum of all values of keys that begin with a given prefix.
Developed By: Parth Shah
Python Version: Python 3.7
'''
class PrefixMapSum:
map_dict = {}
def insert(self,key,value):
self.map_dict[key] = value
def sum(self,prefix):
sum = 0
leng = len(prefix)
for key,value in self.map_dict.items():
if key[:leng] == prefix:
sum += value
print(sum)
mapsum = PrefixMapSum()
mapsum.insert("columnar", 3)
mapsum.sum("col")
#assert mapsum.sum("col") == 3
mapsum.insert("column", 2)
mapsum.sum("col")
#assert mapsum.sum("col") == 5
| true |
35615a6933af9421794d96c35d06310a87ac0562 | Flact/python100 | /Codes/day_02.py | 2,417 | 4.3125 | 4 |
# it will print "H"
# print("Hello"[0])
# ---------------------------
# type checking
# num_char = len(input("What is your name? "))
# this print function will throw a erorr
# print("Your name has " + num_char + " Characters")
# -----------------------------------------------------
# print(type(num_char))
# the fix
# new_num_char = str(num_char)
# print("Your name has " + new_num_char + " Characters")
# -----------------------------------------------------------
# this will print 112
# print(1_2 + 100)
# -------------------------------------
# a = float(124)
# print(type(a))
# print(70 + float("100.12"))
# ---------------------------------
# entering two digits numer and add those two digits
# num = input("Enter two digits number: ")
# print("\n" + str(int(num[0]) + int(num[1])))
# -----------------------------------------------------
# print(2 ** 3)
# print(type( 6 / 2))
# -------------------------------
# PEMDAS
# Parentheses ()
# Exponents **
# Multiplication/Division * /
# Addition/Subtraction + -
# print(3 * 3 + 3 / 3 - 3)
# ---------------------------------
# BMI Calculator
# weight = float(input("Input weight in kg: "))
# height = float(input("Enter hheight in m: "))
# print(int(weight / height ** 2))
# -----------------------------------------------
# ROUND
# print(round(8 / 3, 2))
# print(round(2.66666666, 2))
# ------------------------------------------
# floor division --***
# print(8 // 3)
# print(type(8 // 3))
# -----------------------------------
# f-string
# score = 100
# height = 1.8
# iswinning = True
# print(f"Your score is {score} and your height is {height} You are winng is {iswinning}")
# -------------------------------------------------------------------------------------------
# Years to live calculator(if you live 90yrs)
# age = int(input("Enter your age :"))
# years_remain = 90 - age
# print(f"You have {years_remain * 365} days, {years_remain * 52} weeks, {years_remain * 12} months")
# -------------------------------------------------------------------------------------------------------
# Tip calculator
total_bill = float(input("Welcome to tip claculator\nWhat was the total bill? $"))
precentage = int(input("What precentage whould you like to tip 10, 12 or 15: "))
people = int(input("How many people to split the bill? "))
print(f"Each person should pay {round((total_bill / people) * (1 + precentage / 100) , 2)}")
| true |
edd17e6ae441888ea4ea37c64c203075231f5e79 | Flact/python100 | /Codes/day_05/loop_with_range.py | 292 | 4.28125 | 4 |
# for number in range(1, 10):
# print(number) # this will print 1 - 9 (not include 10, but include 1)
# this will print 1 - 10 numbers step by 3
# for number in range(1, 11, 3):
# print(number)
# total up to 100
total = 0
for num in range(1, 101):
total += num
print(total)
| true |
f229875b6fbae36c226b1df10b1ec46a724d3383 | kalpanayadav/python | /cosine.py | 802 | 4.34375 | 4 | def myCos(x):
'''
objective: to compute the value of cos(x)
input parameters:
x: enter the number whose cosine value user wants to find out
approach: write the infinite series of cosine using while loop
return value: value of cos(x)
'''
epsilon=0.00001
multBy=-x**2
term=1
total=1
nxtInSeq=1
while abs(term)>epsilon:
divBy=nxtInSeq*(nxtInSeq+1)
term=term*multBy/divBy
total+=term
nxtInSeq+=2
return total
def main():
'''
objective: to compute the value of cos(x)
input parameters:
x: enter the number whose cosine value user wants to find out
return value: cos(x)
'''
x=float(input('Enter a number :'))
print('cos(x) = ',myCos(x))
if __name__=='__main__':
main()
| true |
35fe7adbad7d0928347a52e7bc91f0fd2b4662a5 | ikemerrixs/Au2018-Py210B | /students/arun_nalla/session02/series.py | 1,900 | 4.375 | 4 | ο»Ώ#!use/bin/env python
def fibo(n):
'''Write a alternative code to get the nth value of the fibonacci series using type (list)
0th and 1st position should return 0 and 1 and indexing nth position should
return SUM of previous two numbers'''
if n ==0: return 0
elif n ==1: return 1
my_list = [0,1]
for x in range(2,n+1):
y = my_list[-2] + my_list[-1]
my_list.append(y)
return my_list[-1]
print (fibo (5))
print (fibo (10))
print ('Done with fibonacci series')
def lucas(n):
'''a code to get the nth value of the Lucas series using type (list)
indexing the 0th and 1st position should return 2 and 1,respectively and indexing nth position should
return SUM of previous two numbers'''
if n ==0: return 2
elif n ==1: return 1
my_list2 = [2,1]
for x in range(2,n+1):
y = my_list2[-2] + my_list2[-1]
my_list2.append(y)
return my_list2[-1]
print (lucas (5))
print (lucas(10))
print ('Done with lucas series')
def sum_series(n, a=0, b=1):
list_sum_series = [a,b]
if n ==0: return a
elif n ==1: return b
for x in range (2,n+1):
y = list_sum_series[-2] + list_sum_series[-1]
list_sum_series.append(y)
return list_sum_series[-1]
print (sum_series (10))
print (sum_series(10,2))
print (sum_series(10,2,1))
print (sum_series(10,1))
print (sum_series(10,3,5))
print ('Next is assertion statements')
if __name__ == "__main__":
# run some tests
assert fibo(0) == 0
assert fibo(1) == 1
assert fibo(2) == 1
assert fibo(3) == 2
assert fibo(4) == 3
assert fibo(5) == 5
assert fibo(6) == 8
assert fibo(7) == 13
assert lucas(0) == 2
assert lucas(1) == 1
assert lucas(4) == 7
assert sum_series(5) == fibo(5)
# test if sum_series matched lucas
assert sum_series(5, 2, 1) == lucas(5)
print("tests passed")
| true |
c69af38ba8fc630402d9e5415d128a00948cb973 | ikemerrixs/Au2018-Py210B | /students/ejackie/session04/trigrams.py | 843 | 4.3125 | 4 | #!/usr/bin/env python3
import sys
from collections import defaultdict
words = "I wish I may I wish I might".split()
def build_trigrams(words):
"""
build up the trigrams dict from the list of words
returns a dict with:
keys: word pairs
values: list of followers
"""
trigrams = defaultdict(list)
# build up the dict here!
for i in range(len(words)-2):
pair = words[i:i + 2]
follower = words[i + 2]
#if tuple(pair) in trigrams:
trigrams[tuple(pair)].append(follower)
#list(trigrams[tuple(pair)]).append(follower)
#trigrams[tuple(pair)] = [trigrams[tuple(pair)], follower]
#else:
# trigrams[tuple(pair)] = [follower]
return trigrams
if __name__ == "__main__":
trigrams = build_trigrams(words)
print(trigrams) | true |
6886b16e533f10be42a0cf60f0a8381c805eb6ad | KarmanyaT28/Python-Code-Yourself | /59_loopq4.py | 424 | 4.21875 | 4 | # Write a program to find whether a given number is prime or not
number=int(input("enter your number which has to be checked"))
# i=2
# for i in range(2,number):
# if(number%i==0):
# break
# print("Not a prime number")
prime = True
for i in range(2,number):
if(number%i==0):
prime=False
break
if prime:
print("Prime number")
else:
print("not a prime bro")
| true |
812e5fb56f013781312790cd6b4a2a20cc255647 | KarmanyaT28/Python-Code-Yourself | /17_playwithstrings.py | 1,014 | 4.40625 | 4 | # name = input("Enter your name\n")
# print("Good afternoon, " + name)
# ---------------------------------------------------------------------------
# Write a program to fill in a letter template given below
# letter = '''Dear <Name> , you are selected ! <DATE>'''
# letter = '''
# Greetings from TalkPy.org
# Dear <|NAME|>,
# You are selected !
# Date : <|DATE|>
# With regards
# '''
# name = input("Enter your name\n")
# date = input("Enter date\n")
# letter = letter.replace("<|NAME|>",name)
# letter = letter.replace("<|DATE|>",date)
# print(letter)
#-------------------------------------------------------------------------
# Write a program to detect double spaces in a string without using conditional statements
st = "A string with double spaces"
doubleSpaces = st.find(" ")
print(doubleSpaces)
#-----------------------------------------------------------------------
#Replacing the double space with single spaces
st = st.replace(" "," ")
print(st)
| true |
027170862720a141e62cd700cc30dc11db0a3b73 | KarmanyaT28/Python-Code-Yourself | /45_conditionalq3.py | 542 | 4.25 | 4 | # A spam comment is defined as a text containing following keywords:
# "make a lot of money" , "buy now","subscribe this",
# "click this".
# Write a program to detect these spams.
text= input("Enter the text")
spam = False
if("make a lot of money" in text):
spam = True
elif("buy now" in text):
spam = True
elif("subscribe this" in text):
spam=True
elif("click this" in text):
spam = True
else:
spam=False
if(spam):
print("This text is spam")
else:
print("This text is not spam") | true |
a0b6a8921da7aa3562a1441fbe826bf528aa5ed6 | RealMrRabbit/python_workbook | /exercise_3.py | 2,794 | 4.5 | 4 | #Exercise 3: Area of a Room
#(Solvedβ13 Lines)
#Write a program that asks the user to enter the width and length of a room. Once
#the values have been read, your program should compute and display the area of the
#room. The length and the width will be entered as floating point numbers. Include
#units in your prompt and output message; either feet or meters, depending on which
#unit you are more comfortable working with.
from time import sleep
print("Hello and welcome to Room Calculator!")
def calculator(x):
if x.upper() == "M":
width_meters = input("What's the width (in meters)? ")
length_meters = input("What's the length (in meters)? ")
area_meters = str(float(width_meters) * float(length_meters))
return area_meters
if x.upper() == "F":
width_feet = input("What's the width (in feet)? ")
length_feet = input("What's the length (in feet)? ")
area_feet = str(float(width_feet) * float(length_feet))
return area_feet
def interface():
start = True
while start:
user_choice_unit = input("Do you want to calulate in meters (M) or feet (F), or exit enter (x). ")
area = calculator(user_choice_unit)
#convert meters
if user_choice_unit.upper() == "M":
print("Your area is: " + area + " M^2")
user_choice = input("Would you like to convert to feet (y/n), or start over (x)? ")
if user_choice.lower() == "x":
continue
if user_choice.lower() == "y":
print("Your area in feet is: " + str(float(area) ** 3.28084) + " ft^2")
continue
if user_choice.lower() == "n":
print("Thank you for using this calculator!")
sleep(2)
print("calculator shutting down...")
sleep(2)
start = False
#convert feet
if user_choice_unit.upper() == "F":
print("Your area is: " + area + " ft^2")
user_choice = input("Would you like to convert to meters (y/n), or start over (x)? ")
if user_choice.lower() == "x":
continue
if user_choice.lower() == "y":
print("Your area in meters is: " + str(float(area) ** 0.3048) + " M^2")
continue
if user_choice.lower() == "n":
print("Thank you for using this calculator!")
sleep(2)
print("calculator shutting down...")
sleep(2)
start = False
if user_choice_unit.lower() == "x":
print("Thank you for using this calculator!")
sleep(2)
print("calculator shutting down...")
sleep(2)
start = False
print(interface())
| true |
12853d4c6fbd6325541bce74c1307871c28bf8f9 | z0k/CSC108 | /Exercises/e2.py | 1,960 | 4.1875 | 4 | # String constants representing morning, noon, afternoon, and evening.
MORNING = 'morning'
NOON = 'noon'
AFTERNOON = 'afternoon'
EVENING = 'evening'
def is_a_digit(s):
''' (str) -> bool
Precondition: len(s) == 1
Return True iff s is a string containing a single digit character (between
'0' and '9' inclusive).
>>> is_a_digit('7')
True
>>> is_a_digit('b')
False
'''
return '0' <= s and s <= '9'
# Write your three function definitions here:
def time_of_day(hours, minutes):
''' (int, int) -> str
Return the value MORNING if the time is before 12:00, NOON if it is 12:00,
AFTERNOON if it is after 12:00 and before 17:00, and EVENING otherwise.
>>> time_of_day(12, 0)
'noon'
>>> time_of_day(8, 59)
'morning'
'''
if hours < 12:
return MORNING
elif hours == 12 and minutes == 0:
return NOON
elif hours == 12 and not minutes == 0:
return AFTERNOON
elif 12 < hours < 17:
return AFTERNOON
else:
return EVENING
def closest_time(time1, time2, actual_time):
''' (str, str, str) -> str
Return the parameter between time1 and time2 that is closest to actual_time.
>>> closest_time('11:59', '12:01', '12:00')
'11:59'
>>> closest_time('01:40', '13:40', '05:40')
'1:40'
'''
time1_mins = int(time1[:2]) * 60 + int(time1[-2:])
time2_mins = int(time2[:2]) * 60 + int(time2[-2:])
actual_time_mins = int(actual_time[:2]) * 60 + int(actual_time[-2:])
if abs(time1_mins - actual_time_mins) <= abs(time2_mins - actual_time_mins):
return time1
return time2
def sum_digits(string):
''' (str) -> int
Return the sum of the values of each integer digit that appears in string.
>>> sum_digits('CSC108H1S')
10
>>> sum_digits('2')
2
'''
total = 0
for e in string:
if is_a_digit(e):
total = total + int(e)
return total
| true |
f23776b0ea7d95b86dc0ab31d15f208657050d50 | Tavheeda/python-programs | /lists.py | 1,882 | 4.25 | 4 | # fruits = ['apple','orange','mango','apple','grapes']
# print(fruits)
# print(fruits[1])
# import math
# for fruit in fruits:
# print(fruit)
# numbers = [1,2,3,4,5,8,9,10]
# print(numbers[2:5])
# print(numbers[3:])
# for number in numbers:
# print(number)
# i = 0
# while i < len(numbers):
# print(numbers[i])
# i +=1
# SNAKE CASING
# float_numbers = [12.2,34.1,22.5]
# employees = ["tanveer ahmad baba",580000.80,28]
# for employee in employees:
# print(employee)
# python basic data structure - sequence
# subjects = ["physics","chemistry","bilogy"]
# other_subjects = ["english","urdu"]
# # print(subjects)
# print(subjects[2])
# subjects[2]="biology"
# print(subjects)
# subjects.append("english")
# print(subjects)
# subjects.insert(1,"Atlas")
# print(subjects)
# subjects.remove("english")
# print(subjects)
# print(len(subjects))
# all_subjects = subjects + other_subjects
# print(all_subjects)
# repitions = subjects*3
# print(repitions)
# for i in ["physics","chemistry","bilogy"]:
# print(i)
# INDEXING
# print(all_subjects[3:])
# print(all_subjects[:4])
# print(all_subjects[2:4])
# print(all_subjects[:-2])
# print(all_subjects[-5:-3])
# print(all_subjects[2:-4])
# print(cmp(subjects,other_subjects))
# print(all_subjects.count("urdu"))
# list1 = [1,2,3,4,5]
# list2 = ["eng","phy","chem","bio","zoo"]
# list3 = ["tavheeda",14,90]
# print(list1)
# print(list2)
# print(list3)
# print(list1*2)
# print(list1[:3])
# print(list2[1:5])
# print(list3[-3:-1])
# list1[2]="urdu"
# print(list1)
# list1.append("6")
# print(list1)
# list1.insert(3,"his")
# print(list1)
# del list1[2]
# print(list1)
# print(list1*3)
# print(list1)
#
# list1.reverse()
# print(list1)
# a=30
# b=3
# a//b=c
# a/b=d
# print(c)
# print(d)
# n = 5
# i = 0
# while i<=n:
# print(i*i)
# i +=1
# WRTE A PROGRAM TO CONVERT LIST INTO TUPLE
l = [1,2,3,4]
t = tuple(l)
print(t)
print(l)
| true |
1d675bd4f0271c09a8998b7ea02f4b2d3110b6cf | powerlego/Main | /insertion_sort.py | 1,053 | 4.125 | 4 | """
file: insertion_sort.py
language: python3
author: Arthur Nunes-Harwitt
purpose: Implementation of insertion sort algorithm
"""
def insertion_sort(lst):
"""
insertionSort: List( A ) -> NoneType
where A is totally ordered
effect: modifies lst so that the elements are in order
"""
for mark in range(len(lst) - 1):
insert(lst, mark)
def insert(lst, mark):
"""
insert: List( A ) * NatNum -> NoneType
where A is totally ordered
effect: moves the value just past the mark to its sorted position
"""
for index in range(mark, -1, -1):
if lst[index] > lst[index + 1]:
swap(lst, index, index + 1)
else:
return
def swap(lst, i, j):
"""
swap: List( A ) * NatNum * NatNum -> NoneType
where A is totally ordered
effect: swaps the values in lst at positions i and j
"""
(lst[i], lst[j]) = (lst[j], lst[i])
if __name__ == "__main__":
L = [1, 5, 3, 4, 2, 2, 7, 5, 3, 4, 9, 0, 1, 2, 5, 4, 76, 6]
insertion_sort(L)
print(L)
| true |
a0dbb5f621dd2a58469e0d26bf9190f45dfc86d8 | Rossorboss/Python_Functions_Prac | /map,filter,lambda.py | 2,621 | 4.5625 | 5 | #map, lambda statements
def square(num):
return num ** 2
my_nums = [1,2,3,4,5]
for x in map(square,my_nums): #the map function allows it to be used numerous times at once
print(x)
# Luke i am your father example--using map to call all 3 at the same time
def relation_to_luke(name):
if name == 'Darth Vader':
return('Luke, I am your father')
elif name == 'Leia':
return('Luke, I am your sister')
elif name == 'Han':
return('Luke, I am your brother in law')
else:
return('Luke, I dont know you')
relation = ['Darth Vader', 'Leia', 'Han']
for item in map(relation_to_luke,relation):
print(item)
#age(years) to days now using map to calculate numerous ages at once
def calc_age(x):
days_old = x * 365
return(days_old)
ages = [10,20,30]
for age in map(calc_age,ages):
print(age)
#-------------
#lamba function you only use once...no need to def function to use it
#return the first letter
names_of_people =['Ross', 'Chelsea', 'Hallie', 'Bonnie']
list(map(lambda letter: letter[0],names_of_people))
#this would return ['R','C','H','B']
names_of_people =['Ross', 'Chelsea', 'Hallie', 'Bonnie']
list(map(lambda letter: letter[::-1],names_of_people))
#this would return ['ssoR','aeslehC','eillaH','einnoB']
my_numbers = [1,2,3,4,5]
double_num = list(map(lambda num: num *2,my_numbers)) #will return a list of nums in my_numbers
print(double_num) #will print the list
#-------------------
#filter allows you to filter results
def check_even(num):
return num%2 == 0
mynums = [1,2,3,4,5,6,7,8,9,10]
for n in filter(check_even,mynums): #the filter function will only retur n even numbers while if we used the map() it would return either true or false for all numbers in mynums
print(n)
#count upper lower, .isupper() .islower()
def up_low(s):
lowercase = 0
uppercase = 0
for char in s:
if char.isupper():
uppercase += 1
elif char.islower():
lowercase += 1
else:
pass
print(f'Original String : {s}')
print(f'No. of Upper case characters : {uppercase}')
print(f'No. of Lower case characters : {lowercase}')
#^^^^^^^^^but using a dictionary
def up_low(s):
d = {'uppercase': 0,'lowercase': 0}
for char in s:
if char.isupper():
d['uppercase']+= 1
elif char.islower():
d['lowercase'] += 1
else:
pass
print(f'Original String : {s}')
print(f'No. of Upper case characters : {d["uppercase"]}')
print(f'No. of Lower case characters : {d["lowercase"]}')
| true |
67065afeef4f82ff240a6920f642cc739a486010 | dearwendy714/web-335 | /week-8/Portillo_calculator.py | 645 | 4.625 | 5 | # ============================================
# ; Title: Assignment 8.3
# ; Author: Wendy Portillo
# ; Date: 9 December 2019
# ; Modified By: Wendy Portillo
# ; Description: Demonstrates basic
# ; python operation
# ;===========================================
# function that takes two parameters(numbers) and adds them together
def add(x, y):
return x + y
# function that takes two parameters(numbers) and finds the difference
def subtract(x, y):
return x - y
# function that takes two parameters(numbers) and finds the quotient of them
def divide(x, y):
return x / y
print(add(10, 10))
print(subtract(10, 10))
print(divide(10, 10))
| true |
84f611ef059a51b87074835a430eedf3da9f346c | davestudin/Projects | /Euler Problems/Euler Problems/Question 6.py | 529 | 4.34375 | 4 | from math import *
input = int(raw_input("Enter sum of the desired Pythagorean Triple: "))
def pythag(sum):
a,b,c=0.0,0.0,0.0
for a in range (1,sum):
for b in range(a,sum):
c=sqrt(a*a+b*b)
if c%1==0 and a%1==0 and b%1==0:
if (a+b+c)==sum:
return 'The Pythagorean triple with sides that add up to '+ str(sum) + ', is a = ' + str(a) + ', b = ' +str(b) + ', c = ' +str(int(c)) + '.'
else:
return 'There is no Pythagorean triple with sides that add up to '+ str(sum)
print pythag(input) | true |
0e06bc1f938f34183388ac64c76def7a328c4ba1 | BNHub/Python- | /Made_Game.py | 495 | 4.40625 | 4 | #1. Create a greeting for your program.
print("Welcome to the best band name game!")
#2. Ask the user for the city that they grew up in.
city = input("What is name of the city you grew up in?\n")
#3. Ask the user for the name of a pet.
pet_name = input("What's your pet's name?\n")
#4. Combine the name of their city and pet and show them their band name.
print("Your band name could be " + city + " " + pet_name)
#5. Make sure the input cursor shows on a new line, see the example at:
| true |
1689f5917ee66e8fbdc904983a506f0afdfb06fc | tochukwuokafor/my_chapter_4_solution_gaddis_book_python | /bug_collector.py | 285 | 4.15625 | 4 | NUMBER_OF_DAYS = 5
total = 0
for day in range(NUMBER_OF_DAYS):
print('Enter the number of bugs collected on day #' + str(day + 1) + ': ', sep = '', end = '')
bugs_collected = int(input())
total += bugs_collected
print('The total number of bugs collected is', total) | true |
0d1890ddd1b000d26c4f5433970f2db1dc26090a | tochukwuokafor/my_chapter_4_solution_gaddis_book_python | /average_word_length.py | 372 | 4.25 | 4 | again = input('Enter a sentence or a word: ')
total = 0
words_list = []
while again != '':
words = again.split()
for word in words:
words_list.append(word)
total += len(word)
again = input('Enter another sentence or another word: ')
average = total / len(words_list)
print('The average length of the words entered is', round(average)) | true |
742ecea8c97e08e476b86cd4f5dcc38cab2bb947 | era153/pyhton | /her.py | 456 | 4.21875 | 4 | name=int(input("no days employee1 work"))
print("no days hour" , name)
name1=int(input("no of hour employee1 work in first day"))
print("no days hour" , name1)
name2=int(input("no days hour employee1 work in second day"))
print("no days hour" , name2)
name3=int(input("no hour employee1 work in third day"))
print("no days hour" , name3)
print("you have work", name1+name2+name3, "hour")
print("your average work", ((name1+name2+name3)/3), "in total days") | true |
1504008a8d33a1bc1fcd9dcca04fcb05221e1eb6 | hiteshpindikanti/Coding_Questions | /DCP/DCP140.py | 950 | 4.125 | 4 | """
This problem was asked by Facebook.
Given an array of integers in which two elements appear exactly once and all other elements appear exactly twice, find the two elements that appear only once.
For example, given the array [2, 4, 6, 8, 10, 2, 6, 10], return 4 and 8. The order does not matter.
Follow-up: Can you do this in linear time and constant space?
"""
def get_odd_elements(array: list) -> tuple:
xor = 0
for element in array:
xor = xor ^ element
set_bit_index = 0
while not xor & (1 << set_bit_index):
set_bit_index += 1
group1_xor = 0
group2_xor = 0
for element in array:
if element & (1 << set_bit_index):
# Group 1
group1_xor = group1_xor ^ element
else:
# Group 2
group2_xor = group2_xor ^ element
return group1_xor, group2_xor
if __name__ == "__main__":
print(get_odd_elements([2, 4, 6, 8, 10, 2, 6, 10]))
| true |
9484cc99d76ae1d45dced6765fb9d850210ed1bc | hiteshpindikanti/Coding_Questions | /DCP/DCP9.py | 1,348 | 4.21875 | 4 | """
This problem was asked by Airbnb.
Given a list of integers, write a function that returns the largest sum of non-adjacent numbers.
Numbers can be 0 or negative.
For example, [2, 4, 6, 2, 5] should return 13, since we pick 2, 6, and 5. [5, 1, 1, 5] should return 10,
since we pick 5 and 5.
Follow-up: Can you do this in O(N) time and constant space?
"""
def largest_sum(arr):
odd_max = float('-inf')
even_max = float('-inf')
if len(arr) <= 2:
return max(arr)
else:
even_max = arr[0]
odd_max = arr[1]
index = 2
while index < len(arr):
if index % 2 == 0:
odd_max = max(odd_max, even_max)
if odd_max < 0:
odd_max = 0
even_max = max(even_max, even_max + arr[index])
if even_max < 0:
even_max = 0
else:
even_max = max(odd_max, even_max)
if even_max < 0:
even_max = 0
odd_max = max(odd_max, odd_max + arr[index])
if odd_max < 0:
odd_max = 0
index += 1
if max(odd_max, even_max) <= 0:
return max(arr)
else:
return max(odd_max, even_max)
print(largest_sum([5, 1, 1, 5]))
print(largest_sum([2, 4, 6, 2, 5]))
print(largest_sum([0, 0, 9, 10, 8, 0, 0]))
print(largest_sum([-1, -10, -1, -5, 10]))
| true |
1f7e0f8e5af1f2f26af8d46cfdc55a235fed2168 | hiteshpindikanti/Coding_Questions | /DCP/DCP61.py | 512 | 4.25 | 4 | """
This problem was asked by Google.
Implement integer exponentiation. That is, implement the pow(x, y) function, where x and y are integers and returns x^y.
Do this faster than the naive method of repeated multiplication.
For example, pow(2, 10) should return 1024.
"""
def pow(base: int, power: int) -> int:
extra = 1
while power > 1:
if power % 2:
extra *= base
power -= 1
base *= base
power //= 2
base *= extra
return base
pow(2, 100) | true |
fcedd0fd56b0b84c51738c5e1fff640a6d79ffd5 | hiteshpindikanti/Coding_Questions | /DCP/DCP46.py | 1,148 | 4.1875 | 4 | """
This problem was asked by Amazon.
Given a string, find the longest palindromic contiguous substring. If there are more than one with the maximum length, return any one.
For example, the longest palindromic substring of "aabcdcb" is "bcdcb". The longest palindromic substring of "bananas" is "anana".
"""
from copy import deepcopy
def get_longest_palindrom_substring(s: str) -> str:
lps_length_table = [[1] * len(s) for _ in range(len(s))]
lps = ""
for row in range(len(s) - 1, -1, -1):
for col in range(len(s) - 1, row, -1):
if lps_length_table[row + 1][col - 1] == (col - 1) - (row + 1) + 1:
# s[row+1:col] is a palindrome
if s[row] == s[col]:
# s[row:col+1] is a palindrome
lps_length_table[row][col] = col - row + 1
if len(lps) < col - row + 1:
lps = s[row:col + 1]
else:
lps_length_table[row][col] = lps_length_table[row + 1][col - 1]
return lps
print(get_longest_palindrom_substring("aabcdcb"))
print(get_longest_palindrom_substring("bananas")) | true |
890055af08088ea6a059a404b41f58f5a858cd0c | hiteshpindikanti/Coding_Questions | /DCP/DCP102.py | 684 | 4.125 | 4 | """
This problem was asked by Lyft.
Given a list of integers and a number K, return which contiguous elements of the list sum to K.
For example, if the list is [1, 2, 3, 4, 5] and K is 9, then it should return [2, 3, 4], since 2 + 3 + 4 = 9.
"""
from queue import Queue
def get_sublist(l: list, k: int) -> list:
result_list = Queue()
current_sum = 0
for element in l:
if current_sum < k:
result_list.put(element)
current_sum += element
if current_sum > k:
current_sum -= result_list.get()
if current_sum == k:
return list(result_list.queue)
return []
print(get_sublist([1, 2, 3, 4, 5], 9))
| true |
7134e0ee6a87054c906298ed87461d2e0d7af0eb | hiteshpindikanti/Coding_Questions | /DCP/DCP99.py | 1,089 | 4.15625 | 4 | """
This problem was asked by Microsoft.
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example, given [100, 4, 200, 1, 3, 2], the longest consecutive element sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
"""
def get_longest_consecutive_sequence_length(arr: list):
arr_set = set(arr)
visited = set()
max_count = 0
for index in range(len(arr)):
if arr[index] not in visited:
count = 1
# Back search
num = arr[index] - 1
while num in arr_set:
visited.add(num)
num -= 1
count += 1
# Forward Search
num = arr[index] + 1
while num in arr_set:
visited.add(num)
num += 1
count += 1
max_count = max(max_count, count)
return max_count
if __name__ == "__main__":
lst = [100, 4, 200, 1, 3, 2]
print(get_longest_consecutive_sequence_length(lst)) # answer=4
| true |
793efcdcacb8e3d8865cfcca067fd02c52479fda | hiteshpindikanti/Coding_Questions | /DCP/DCP57.py | 1,263 | 4.15625 | 4 | """
This problem was asked by Amazon.
Given a string s and an integer k, break up the string into multiple lines such that each line has a length of k or less. You must break it up so that words don't break across lines. Each line has to have the maximum possible amount of words. If there's no way to break the text up, then return null.
You can assume that there are no spaces at the ends of the string and that there is exactly one space between each word.
For example, given the string "the quick brown fox jumps over the lazy dog" and k = 10, you should return: ["the quick", "brown fox", "jumps over", "the lazy", "dog"]. No string in the list has a length of more than 10.
"""
def break_up(s: str, k: int) -> list:
words = s.split(" ")
result = []
i = 1
line = words[0]
while i < len(words):
line_copy = line
line += " " + words[i]
if len(line) > k:
result.append(line_copy)
line = words[i]
elif len(line) == k:
result.append(line)
i += 1
line = words[i]
i += 1
else:
if line:
result.append(line)
return result
sentence = "the quick brown fox jumps over the lazy dog"
print(break_up(sentence, k=10))
| true |
1bec2c55f061c3fd1f367ba492d0b580950583e3 | santosh1561995/python-practice | /python-variables.py | 429 | 4.125 | 4 | print("For the datatypes in python an variable declaration")
#in python data type will be calculated automtically no need to declare explicitly
#integer type
x=5
print(x)
#float
f=5.5
print(f)
#multiple assignment to variable
a=b=c=10
print(a,b,c)
#assign values in one line
a,b=1,"India"
print(a,b)
#Swapping the values
x,y="X","Y"
y,x=x,y
print(x,y)
#Strings in python
x='String 1'
y="String 2"
print(x,y)
| true |
69cba86251ad064401c15b3a52c496026f0e8d3a | aliensmart/in_python_algo_and_dat_structure | /Code_1_1.py | 738 | 4.46875 | 4 | print('Welcome to GPA calculator')
print('Please enter all your letter grades, one per line')
print('Enter a blank line to designate the end.')
#map from letter grade to point value
points = {
'A+':4.0,
'A':4.0,
'A-':3.67,
'B+':3.33,
'B':3.0,
'B-':2.67,
'C+':2.33,
'C':2.0,
'C':1.67,
'D+':1.33,
'D':1.0,
'F':0.0
}
num_courses = 0
total_point = 0
done = False
while not done:
grade = input()
if grade == '':
done = True
elif grade not in points:
print("Unknown grade '{0}' being ignored".format(grade))
else:
num_courses +=1
total_point +=points[grade]
if num_courses > 0:
print('Your GPA is {0:.3}'.format(total_point/num_courses)) | true |
633cf9adaadad858607db184e9495e9a69d41937 | aZuh7/Python | /oop.py | 1,440 | 4.25 | 4 | # Python Object-Oriented Programming
class Employee:
raise_amount = 1.04
num_of_emps = 0
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + "." + last + "@company.com"
Employee.num_of_emps += 1
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.pay = int(self.pay * Employee.raise_amount)
# Class is a blueprint for creating instances
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'User', 60000)
print(Employee.num_of_emps)
emp_1.raise_amount = 1.05
print(emp_1.__dict__)
print(Employee.raise_amount)
print(emp_1.raise_amount)
print(emp_2.raise_amount)
# emp_1.apply_raise()
# print(emp_1.pay)
# # emp_1.raise_amount
# # Employee.raise_amount
# Instnce variables contain data that is unique to each instance
#emp_1.first = "Corey"
#emp_1.last = "Schafer"
#emp_1.email = 'Corey.Schaer@company.com'
#emp_1.pay = 60000
#emp_2.first = "Test"
#emp_2.last = "User"
#emp_2.email - 'Test.User@company.com'
#emp_2.pay = 60000
# We want the abililty to perform some action
# can do manually like:
#print('{} {}'.format(emp_1.first, emp_1.last))
# or create a method in our class.
# print(emp_1.fullname())
# print(emp_1.email)
# print(emp_2.email)
# can also run these methods by using the class itself
# emp_1.fullname()
# print(Employee.fullname(emp_1))
| true |
567c3b801b9679d4b30733df891d558e947fb65a | archisathavale/training | /python/basic_progs/min_max_nums.py | 904 | 4.3125 | 4 | #funtion of finding the minimum number
def find_min_val(array):
# assigning 1st element of array to minval
minval=array[0]
# traversing through the array
for element in array:
# to check whether the next element is smaller than the current
if element < minval:
# if yes assigning that number to minval
minval = element
return minval
#funtion of finding the maximum number
def find_max_val(array):
# assigning 1st element of array to maxval
maxval=array[0]
# to check whether the next element is greater than the current
for element in array:
# to check whether the next element is greater than the current
if element > maxval:
#if yes assigning that number to maxval
maxval = element
return maxval
if __name__ == '__main__':
print (find_min_val([2, 3, 4]))
print (find_min_val([55,83,14,-4]))
print (find_max_val([2,3,4]))
print (find_max_val([55,83,14,-4])) | true |
cee62cc8bd73c1f9be83e55fdc5e4c4ceb920a55 | archisathavale/training | /python/Archis/addressbook.py | 790 | 4.1875 | 4 | addressbook={}
# Empty Dictionary
# Function of adding an address
# email is the key and name is the value
def add_address(email , name):
addressbook [email] = name
#print (addressbook)
return (email, name)
# Function of deleting an address
# only key is enough to delete the value in a dictionary
def dele_address(email):
del addressbook[email]
#print (addressbook)
return (email)
# Function of printing the addressbook
def print_address():
print (addressbook)
return (addressbook)
# Passing parameters
if __name__ == '__main__' :
add_address('archisathavale', 'Archis')
add_address('avinashathavale', 'Avinash')
add_address('arnavathavale','Arnav')
dele_address('arnavathavale')
dele_address('avinashathavale')
add_address('pankajaathavale', 'Pankaja')
print_address()
| true |
93d48b9b89f9ebaabe098bf46fcea589a96cd384 | GuySK/6001x | /minFixPaymentCent.py | 2,218 | 4.125 | 4 | # This program calculates the minimum fixed payment to the cent
# for cancelling a debt in a year with the interest rate provided.
# minFixPaymentCent.py
#
def annualBalance(capital, annualInterestRate, monthlyPayment):
'''
Calculates balance of sum after one year of fixed payments.
Takes capital, interst rate and payment as int or floats.
'''
period = 0
interest = 0.0
newBalance = capital
#
for period in range(1,13):
newBalance -= monthlyPayment # update balance with payment
interest = newBalance * (annualInterestRate/12.0) # calculate interest
newBalance += interest # and add it to next period"s balance
return newBalance # final balance
# end of function
#
# Main
while True:
# The following lines must be commented before submitting to grader
#
balance = float(raw_input('Enter capital: '))
annualInterestRate = float(raw_input('Enter rate: '))
#
# validate input
if balance < 0 or annualInterestRate < 0:
print('Error. Balance, interest rate cannot be negative.')
break
monthlyInterestRate = annualInterestRate/12.0 # monthly rate
lowerPayment = balance / 12.0 # lower limit is for no interest
upperPayment = (balance * (1 + monthlyInterestRate)**12)/12 # upper limit
loopCounter = 0 # just to know how many iterations takes
payment = lowerPayment + (upperPayment - lowerPayment) / 2.0 # starting point
#
while abs(annualBalance(balance,annualInterestRate,payment)) > 0.01:
loopCounter +=1 # count how many iterations
if (annualBalance(balance,annualInterestRate,payment) > 0.0): # not enough
lowerPayment = payment # set new lower limit
else:
upperPayment = payment # set new upper limit
payment = lowerPayment + (upperPayment - lowerPayment)/2 # recalculate
# print('Iter no: ' + str(loopCounter))
# print('Lower limit: ' + str(lowerPayment))
# print('Upper limit: ' + str(upperPayment))
# print('New Payment: ' + str(payment))
# print('Number of iterations: ' + str(loopCounter))
print('Lowest payment: ' + str(round(payment,2)))
break # finish main loop
# end of code | true |
e19161d4378b326e7c2e9f2c0a570d1952f9fd2b | GuySK/6001x | /PS6/Answer/reverseString.py | 524 | 4.46875 | 4 | def reverseString(aStr):
"""
Given a string, recursively returns a reversed copy of the string.
For example, if the string is 'abc', the function returns 'cba'.
The only string operations you are allowed to use are indexing,
slicing, and concatenation.
aStr: a string
returns: a reversed string
"""
if len(aStr) == 0:
return ''
elif len(aStr) == 1:
return aStr
else:
return aStr[-1] + reverseString(aStr[:-1])
# end of code for reverseString | true |
4e7410fee77d106caab46c92cb6e9d978bfb4376 | GuySK/6001x | /PS6/Answer/buildCoder.py | 661 | 4.40625 | 4 | def buildCoder(shift):
"""
Returns a dict that can apply a Caesar cipher to a letter.
The cipher is defined by the shift value. Ignores non-letter characters
like punctuation, numbers, and spaces.
shift: 0 <= int < 26
returns: dict
"""
import string
lowcase = string.ascii_lowercase
upcase = string.ascii_uppercase
codeDict = {}
i = 0
for letter in lowcase:
codeDict[lowcase[i]] = lowcase[(i+shift)%26]
i += 1
i = 0
for letter in upcase:
codeDict[upcase[i]] = upcase[(i+shift)%26]
i += 1
return codeDict
# end of code for buildCoder | true |
2d9b308bb95891e46a2f5d6cf8b9a46e7f18e54b | GuySK/6001x | /PS4/Answers/bestWord.py | 839 | 4.28125 | 4 | def bestWord(wordsList):
'''
Finds the word with most points in the list.
wordsList is a list of words.
'''
def wordValue(word):
'''
Computes value of word. Word is a string of lowercase letters.
'''
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
value = 0
for letter in word:
value += SCRABBLE_LETTER_VALUES[letter]
return value
# end of code
topL = ['', 0]
for word in wordsList:
value = wordValue(word)
if value > topL[1]:
topL[1] = value
topL[0] = word
return topL
# end of code | true |
cec85a8e1acb2412389030e89ec6722bd9c83fbb | Mariappan/LearnPython | /codingbat.com/list_2/centered_average.py | 977 | 4.125 | 4 | # Return the "centered" average of an array of ints, which we'll say is the mean average of the values,
# except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value,
# ignore just one copy, and likewise for the largest value.
# Use int division to produce the final average. You may assume that the array is length 3 or more.
# centered_average([1, 2, 3, 4, 100]) β 3
# centered_average([1, 1, 5, 5, 10, 8, 7]) β 5
# centered_average([-10, -4, -2, -4, -2, 0]) β -3
def centered_average(nums):
large = nums[0]
for i in nums:
if i > large:
large = i
small = nums[0]
for i in nums:
if i < small:
small = i
count = 0
sum = 0
leave = False
for i in nums:
if i == small:
small = 0
leave = True
if i == large:
large = 0
leave = True
if leave == False:
sum += i
count += 1
leave = False
return sum//count
| true |
3bd5b189e5a3beb450efad8e39a346d7cd9300c3 | lynellf/learing-python | /collections/slices.py | 1,944 | 4.4375 | 4 | # Sometimes we don't want an entie list or string, just a part.
# A slice is a new list or string made from a previous list or string
favorite_things = ['raindrops on roses', 'whiskers on kittens', 'bright coppeer kettles', 'warm woolen mittens',
'bright paper packages tied up with string', 'cream colored ponies', 'crisp apple strudels']
# The number before the colon is the starting point. The number after is the end-point
some_favorite_things = favorite_things[0:2]
template = 'Some of my favorite things include {}'
print(template.format(some_favorite_things))
# we can omit the first number to always start from the first item
some_favorite_things = favorite_things[:2]
print(template.format(some_favorite_things))
# we can omit the second number to always select through the last item
some_favorite_things = favorite_things[3:]
print(template.format(some_favorite_things))
# copy a list
new_favorite_things = favorite_things[:]
print(template.format(new_favorite_things))
# Step through a sliced list (like every odd or even number)
# We can go from left to right with a positive number, or reverse with a negative number
numbered_list = list(range(21))
print(numbered_list[::-2]) # [20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0]
# We can use slices to delete or replace values
letters = ['a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
del letters[4:8] # ['a', 'b', 'c', 'd', 'i', 'j', 'k', 'l', 'm', 'n']
letters = ['a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
letters[2:4] = ['hmm']
print(letters)
apple = ['a', 'p', 'p', 'l', 'e']
banana = ['b', 'a', 'n', 'a', 'n', 'a']
def sillycase(string):
length = len(string)
breakpoint = int(length / 2)
first_half = string[:(breakpoint)].lower()
second_half = string[breakpoint:length].upper()
output = first_half + second_half
return output
print(sillycase('BANANA'))
| true |
5fd6323dab3a5e3221775e1be76bab49f7f3f68f | lynellf/learing-python | /python_basics/numbers.py | 587 | 4.34375 | 4 | # Numeric Data
three = 1 + 2
print('The number %s' %(three))
# Rounding numbers
_float = 0.233 + .442349
rounded = round(_float)
print('A number is %s, and a rounded number is %s' %(_float, rounded))
# Converting strings to numbers
string_num = '12'
int_num = int(string_num)
float_num = float(string_num)
string_num_type = type(string_num)
int_num_type = type(int_num)
float_num_type = type(float_num)
print('The type of the variable "string_num" is %s. The type of variable "float_num" is %s. The type of variable "int_num" is %s.' %(string_num_type, float_num_type, int_num_type))
| true |
6203dd89bad719a8003dd573f08865acb6301e10 | arsummers/python-data-structures-and-algorithms | /challenges/comparator/comparator.py | 1,060 | 4.3125 | 4 | """
Comparators are used to compare two objects. In this challenge, you'll create a comparator and use it to sort an array. The Player class is provided in the editor below. It has two fields:
name: a string.
score: an integer.
Given an array of n Player objects, write a comparator that sorts them in order of decreasing score. if 2 or more players have the same score, sort those players alphabetically ascending by name. To do this, you must create a Checker class that implements the Comparator interface, then write an int compare(Player a, Player b) method implementing the Comparator.compare(T o1, T o2) method.
example:
input = [[Smith, 20], [Jones, 15], [Jones, 20]]
output = [[Jones, 20],[Smith, 20], [Jones, 15]]
"""
"""
works on a -1, 0, 1 scale to sort with comparators.
"""
class Player:
def __init__(self, name, score):
self.name = name
self.score = score
def comparator(a, b):
if a.score != b.score:
return b.score - a.score
return (a.name > b.name) - (a.name < b.name) | true |
b937852ce70a3d673ec5d34f7d9b9f6f87a73617 | arvakagdi/Basic-Algos | /IterativeBinarySearch.py | 1,139 | 4.25 | 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
'''
startarr = 0
endarr = len(array)-1
while startarr <= endarr:
midlen = (startarr + endarr)//2
mid = array[midlen]
if mid == target:
return array[midlen]
if target > mid:
startarr = mid+1
else:
endarr = mid-1
return -1
def test_function(test_case):
answer = binary_search(test_case[0], test_case[1])
if answer == test_case[2]:
print("Pass!")
else:
print("Fail!")
array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 6
index = 6
test_case = [array, target, index]
test_function(test_case)
array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 11
index = -1
test_case = [array, target, index]
test_function(test_case) | true |
01dd8d67ceaad408cb442d882cf3c4c08f3eb445 | eduardomrocha/dynamic_programming_problems | /tabulation/python/06_can_construct.py | 1,574 | 4.25 | 4 | """Can construct.
This script implements a solution to the can construct problem using tabulation.
Given a string 'target' and a list of strings 'word_bank', return a boolean indicating
whether or not the 'target' can be constructed by concatenating elements of 'word_bank'
list.
You may reuse elements of 'word_bank' as many times as needed.
"""
from typing import List
def can_construct(target: str, word_bank: List[str]) -> bool:
"""Check if a given target can be constructed with a given word bank.
Args:
target (str): String that must be constructed.
word_bank (List[str]): List of strings that can possibly construct the target.
Returns:
bool: Returns True if it can be constructed or False if it cannot.
"""
table: List = [False] * (len(target) + 1)
table[0] = True
for i in range(len(target)):
if table[i]:
suffix = target[i:]
for word in word_bank:
if suffix.startswith(word):
table[i + len(word)] = True
return table[len(target)]
if __name__ == "__main__":
print(can_construct("abcdef", ["ab", "abc", "cd", "def", "abcd"])) # True
print(
can_construct("skateboard", ["bo", "rd", "ate", "t", "ska", "sk", "boar"])
) # False
print(
can_construct("enterapotentpot", ["a", "p", "ent", "enter", "ot", "o", "t"])
) # True
print(
can_construct(
"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef",
["e", "ee", "eee", "eeee", "eeeee", "eeeeee"],
)
) # False
| true |
326a3bc0283e5864a9b7f1930410749884f3fdbc | eduardomrocha/dynamic_programming_problems | /tabulation/python/08_all_construct.py | 2,053 | 4.34375 | 4 | """All construct.
This script implements a solution to the all construct problem using tabulation.
Given a string 'target' and a list of strings 'word_bank', return a 2D list containing
all of the ways that 'target' can be constructed by concatenating elements of the
'word_bank' list. Each element of the 2D list should represent one combination that
constructs the 'target'.
You may reuse elements of 'word_bank' as many times as needed.
"""
from typing import List, Union
def all_construct(target: str, word_bank: List[str]) -> Union[List[List], List]:
"""Count in how many ways the target can be constructed with a given word bank.
Args:
target (str): String that must be constructed.
word_bank (List[str]): List of strings that can possibly construct the target.
Returns:
List[List[str]]:
int: Returns the number of ways that 'target' can be constructed by
concatenating elements of the 'word_bank' list.
"""
table: List = [[] for _ in range(len(target) + 1)]
table[0].append([])
for i in range(len(target)):
if len(table[i]) > 0:
suffix = target[i:]
for word in word_bank:
if suffix.startswith(word):
for combination in table[i]:
new_combination = combination + [word]
table[i + len(word)].append(new_combination)
return table[len(target)]
if __name__ == "__main__":
print(all_construct("purple", ["purp", "p", "ur", "le", "purpl"]))
"""
[
["purp", "le"],
["p", "ur", "p", "le"]
]
"""
print(all_construct("abcdef", ["ab", "abc", "cd", "def", "abcd", "ef", "c"]))
"""
[
["ab", "cd", "ef"],
["ab", "c", "def"],
["abc", "def"],
["abcd", "ef"]
]
"""
print(
all_construct("skateboard", ["bo", "rd", "ate", "t", "ska", "sk", "boar"])
) # []
print(
all_construct("aaaaaaaaaaz", ["a", "aa", "aaa", "aaaa", "aaaaa", "aaaaaa"],)
) # []
| true |
f6d6484b84550580fe2941e92fee20054c66d468 | aakhedr/algo1_week2 | /part3/quickSort3.py | 2,470 | 4.21875 | 4 | def quickSort(A, fileName):
quickSortHelper(A, 0, len(A) - 1, fileName)
def quickSortHelper(A, first, last, fileName):
if first < last:
pivot_index = partition(A, first, last, fileName)
quickSortHelper(A, first, pivot_index - 1, fileName)
quickSortHelper(A, pivot_index + 1, last, fileName)
def partition(A, first, last, fileName):
'''
The partition around the pivot element part -
Pivot is chosen according to MEDIAN OF THREE pivot rule
fileName parameter refers to the file that will be written to calculate the comparisons
and the number of paritions
'''
### File writing part ### Not related to the algorith
f = open("count_" + fileName, "a")
f.write(str(last - first) + '\n')
f.close()
###
# choose a MEDIAN OF THREE pivot element from the array passed
if (last - first + 1) % 2 == 0:
mid = ((last - first + 1) / 2) - 1 + first
else:
mid = ((last - first)/ 2 + first)
three = sorted([A[first], A[mid], A[last]])
# pick the median of three
three = sorted([A[first], A[mid], A[last]])
median = three[1]
## swap the median with the first element of the aray
if median == A[mid]:
A[first], A[mid] = A[mid], A[first]
if median == A[last]:
A[first], A[last] = A[last], A[first]
pivot = A[first]
i, j = first + 1, first + 1
while j <= last:
if A[j] < pivot:
A[j], A[i] = A[i], A[j]
i += 1
j += 1
A[first], A[i - 1] = A[i -1], A[first]
return i - 1
import os
def count(dataFile):
'''count the number of comparisons and the number of partitions (recurisve calls) '''
inFile = open(dataFile, "r")
total = [int(line) for line in inFile]
comparisons, partitions = sum(total), len(total)
os.remove(dataFile)
return comparisons, partitions
def sort():
''' Computes the number of comparisons and the number of partitions
(i.e. recurisve calls) in quickSort algorithm '''
files= ['10.txt', '100.txt', '1000.txt', '10000.txt']
result = []
for aFile in files:
inFile = open(aFile, "r")
intArray = [int(line) for line in inFile]
quickSort(intArray, aFile)
comparisons, partitions = count("count_" + aFile)
result.append((comparisons, partitions))
return result
print sort()
# import timeit
# t = timeit.Timer(sort)
# print 'pivot median', t.timeit(number=1)
| true |
f66e6d8773c886adb6c1932f8904ef545b2e2476 | YuSheng05631/CrackingInterview | /ch4/4.5.py | 1,184 | 4.15625 | 4 | """
Implement a function to check if a binary tree is a binary search tree.
"""
import Tree
def isBST(bt):
if bt.left is None and bt.right is None:
return True
if bt.left is not None and bt.left.data > bt.data:
return False
if bt.right is not None and bt.right.data < bt.data:
return False
if bt.left is None:
return isBST(bt.right)
if bt.right is None:
return isBST(bt.left)
return isBST(bt.left) and isBST(bt.right)
def isBST2(bt):
return isBST2_a(bt, -99999, 99999)
def isBST2_a(bt, min, max):
if bt is None:
return True
if bt.data <= min or bt.data > max:
return False
if not isBST2_a(bt.left, min, bt.data) or not isBST2_a(bt.right, bt.data, max):
return False
return True
bt = Tree.Node(1)
bt.left = Tree.Node(0)
bt.right = Tree.Node(20)
Tree.levelorderTraversal(bt)
print()
print(isBST(bt))
print(isBST2(bt))
bt2 = Tree.Node(10)
bt2.left = bt
Tree.levelorderTraversal(bt2)
print()
print(isBST(bt2)) # wrong
print(isBST2(bt2))
bt2 = Tree.Node(10)
bt2.left = bt
bt2.right = Tree.Node(9)
Tree.levelorderTraversal(bt2)
print()
print(isBST(bt2))
print(isBST2(bt2))
| true |
1c428f7cf06fa3b6113b2571221becade498a030 | fire-ferrets/cipy | /cipy/alphabet/alphabet.py | 1,452 | 4.46875 | 4 | """
The Alphabet class provides a general framework to embed alphabets
It takes a string of the chosen alphabet as attribute. This provides
the encryption and decryption functions for the ciphers with a performance
boost.
"""
class Alphabet():
def __init__(self, alphabet):
"""
Initialise an Alphabet
Attributes
----------
alphabet : str
The alphabet string
"""
self.alphabet = alphabet
self._length = len(alphabet)
self._numbers_to_alphabet = dict(enumerate(self.alphabet))
self._alphabet_to_numbers = dict((v, k) for k,v in self._numbers_to_alphabet.items())
def __repr__(self):
return self.alphabet
def __len__(self):
return self._length
def __len_hint__(self):
return self._length
def __getitem__(self, key):
if key in self._numbers_to_alphabet:
return self._numbers_to_alphabet[key]
elif key in self._alphabet_to_numbers:
return self._alphabet_to_numbers[key]
def __missing__(self,key, value):
raise KeyError("Key not found in Alphabet")
def __iter__(self):
return self._alphabet_to_numbers.items()
def __reversed__(self):
return reversed(self._alphabet_to_numbers.keys())
def __contains__(self, item):
if item in self._alphabet_to_numbers.keys():
return True
else:
return False
| true |
0c26e158842e1f3fcbd260a1115982c3a3303a6a | BenMarriott/1404 | /prac_02/exceptions.py | 1,036 | 4.28125 | 4 | """
CP1404/CP5632 - Practical
Answer the following questions:
1. When will a ValueError occur? When usings floating point numbers
2. When will a ZeroDivisionError occur? When attempting n/0
3. Could you change the code to avoid the possibility of a ZeroDivisionError?
"""
"""""
try:
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
fraction = numerator / denominator
print(fraction)
except ValueError:
print("Numerator and denominator must be valid numbers!")
except ZeroDivisionError:
print("Cannot divide by zero!")
print("Finished.")
"""""
"""
CP1404/CP5632 - Practical
Fill in the TODOs to complete the task
"""
finished = False
result = 0
while not finished:
try:
result = int(input("Please enter an integar: \n")) # TODO: this line
finished = True
except (ValueError): # TODO - add something after except
print("Please enter a valid integer.\n")
print("Valid result is:", result) | true |
5a530c11bf9ff825ace09f85299d8ac1419ce7a3 | nitishprabhu26/HackerRank | /Practice - Python/005_Loops.py | 760 | 4.46875 | 4 | if __name__ == '__main__':
n = int(input())
for i in range(n):
print(i**2)
# The range() function
# The range function is a built in function that returns a series of numbers. At a minimum, it needs one integer parameter.
# Given one parameter, n, it returns integer values from 0 to n-1. For example, range(5) returns the numbers 0 through 4 in sequence.
# To start at a value other than 0, call range with two arguments. For example, range(1,5) returns the numbers 1 through 4.
# Finally, you can add an increment value as the third argument. For example, range(5, -1, -1) produces the descending sequence from 5 through 0 and range(0, 5, 2) produces 0, 2, 4. If you are going to provide a step value, you must also include a start value. | true |
219a8fe816e6bad703c55d6b75435fc761ace602 | supriya1110vuradi/Python-Tasks-Supriyav | /task4.py | 753 | 4.34375 | 4 | # Write a program to create a list of n integer values and do the following
# Add an item in to the list (using function)
# Delete (using function)
# Store the largest number from the list to a variable
# Store the Smallest number from the list to a variable
a = [1, 2, 3, 4, 5, 6]
hi = max(a)
lo = min(a)
print(hi)
print(lo)
b = [1, 2, 3, 4, 5]
del b[3]
print(b)
c = list([1, 2, 3, 4])
c.append(8)
print(c)
# Create a tuple and print the reverse of the created tuple
# method1
d = (1, 2, "hey", "hello", 3, 4)
print(d)
e = reversed(d)
print(tuple(e))
# method2
tuples = (1, 2, 3, 4, 5, 67, 8)
reversedTuples = tuples[::-1]
print(reversedTuples)
# Create a tuple and convert tuple into list
f = (1, 2, "hi", "hey", 8, 10)
lis = list(f)
print(lis)
| true |
8e488771b4e8aa522e9246dc9f50aec625dbd872 | long2691/activities | /activity 5/comprehension.py | 1,521 | 4.15625 | 4 | prices = ["24", "13", "16000", "1400"]
price_nums = [int(price) for price in prices]
print(prices)
print(price_nums)
dog = "poodle"
letters = [letter for letter in dog]
print(letters)
print(f"we iterate over a string into al ist : {letters}")
capital_letters = [letter.upper() for letter in letters]
#long version of same thing above
capital_letters = []
for letter in letters:
capital_letters.append(letter.upper())
no_o = [letter for letter in letters if letter != 'o']
print(no_o)
#same as abvoe but longer - no o's
no_o = []
for letter in letters:
if letter != 'o':
no_o.append(letter)
june_temperature = [72,65,59,87]
july_temperature = [87,85,92,79]
august_temperateure = [88,77,66,100]
temperature = [june_temperature, july_temperature, august_temperateure]
lowest_summer_temperature = [min(temps) for temps in temperature]
lowest_summer_temperature = []
print(lowest_summer_temperature)
for temps in temperature:
lowest_summer_temperature.append(min(temps))
print(sum(lowest_summer_temperature)/len(lowest_summer_temperature))
print(lowest_summer_temperature)
print(lowest_summer_temperature[0])
print(lowest_summer_temperature[1])
print(lowest_summer_temperature[2])
print("=" * 30)
#longhand
def name(parameter):
return "Hello" + parameter
def average(data1,data2):
return sum(data)/len(data1) + (sum(data2)/len(data2))
print(name("Loc"))
print(Average([1,2,3,4,5],))
#git status
#git add .
# git status
# git commit -m "Description comment"
# git push origin master
| true |
ccd5218382ffe23b84fffc1e0d137feb35b0ea18 | andthenenteredalex/Allen-Downey-Think-Python | /thinkpy107.py | 404 | 4.125 | 4 | """ Allen Downey Think Python Exercise 10-7
This function checks if two words are anagrams and returns True if they are.
"""
def is_anagram(word_one, word_two):
one = sorted(list(word_one))
two = sorted(list(word_two))
if one == two:
return True
elif one != two:
return False
word = 'hello'
word2 = 'hlehol'
anagram = is_anagram(word, word2)
print anagram
| true |
aa0616170bc2dbbd2dca519e550437bb0365ac12 | daviddlhz/holbertonschool-higher_level_programming | /0x0B-python-input_output/3-write_file.py | 403 | 4.25 | 4 | #!/usr/bin/python3
"""write to a text file"""
def write_file(filename="", text=""):
"""writes to a file
Keyword Arguments:
filename {str} -- name of file (default: {""})
text {str} -- text beingwritten (default: {""})
Returns:
int -- number of charaters
"""
with open(filename, mode="w", encoding="utf-8") as fd:
fd.write(text)
return len(text)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.