blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c46f2637edea6f94adff6a8e93f78bd858d94fc1 | jjspetz/digitalcrafts | /py-exercises2/make-a-box.py | 327 | 4.15625 | 4 | # makes a box of user inputed hieght and width
# gets user input
height = int(input("Enter a height: "))
width = int(input("Enter a width: "))
# calculate helper variables
space = width - 2
for j in range(height):
if j == 0 or j == height - 1:
print("*" * width)
else:
print("*" + (" "*space) + "*")
| true |
5c9ff36d6710c334e72abc5b9b58abc8a94758bd | jjspetz/digitalcrafts | /dict-exe/error_test.py | 343 | 4.125 | 4 | #!/usr/bin/env python3
def catch_error():
while 1:
try:
x = int(input("Enter an integer: "))
except ValueError:
print("Enter an integer!")
except x == 3:
raise myError("This is not an integer!")
else:
x += 13
if __name__ == "__main__":
catch_error()
| true |
4bdd9011b451281cdd9b3c8d4c3abbe730f9358f | kusaurabh/CodeSamples | /python_samples/check_duplicates.py | 672 | 4.25 | 4 | #!/usr/bin/python3
import sys
def check_duplicates(items):
list_items = items[:]
list_items.sort()
prev_item = None
for item in list_items:
if prev_item == item:
return True
else:
prev_item = item
return False
def create_unique_list(items):
unique_list = list()
for item in items:
if item not in unique_list:
unique_list.append(item)
return unique_list
if __name__ == "__main__":
items = ["Hello", "rt", "st", "lt", "lt"]
result = check_duplicates(items)
unqList = create_unique_list(items)
print(items)
print(result)
print(unqList)
| true |
a5a46c8dbaaf4c4ceee25803e0cca585d74eb883 | pseudomuto/sudoku-solver | /Python/model/notifyer.py | 1,164 | 4.125 | 4 | class Notifyer(object):
"""A simple class for handling event notifications"""
def __init__(self):
self.listeners = {}
def fireEvent(self, eventName, data = None):
"""Notifies all registered listeners that the specified event has occurred
eventName: The name of the event being fired
data: An optional parameter to be passed on listeners
"""
if eventName in self.listeners:
for responder in self.listeners[eventName]:
responder(data)
def addListener(self, eventName, responder):
"""Registers responder as a listener for the specified event
eventName: The name of the event to listen for
responder: A callback method that will be notified when the event occurs
"""
if not eventName in self.listeners:
self.listeners[eventName] = []
self.listeners[eventName].append(responder)
def removeListener(self, eventName, responder):
"""Removes the specified listener from the set of observers
eventName: The name of the event to stop listening for
responder: The callback method to remove
"""
if eventName in self.listeners:
if responder in self.listeners[eventName]:
self.listeners[eventName].remove(responder) | true |
3e925a8f0736eec9688f3597502d77f249c05e08 | annapaula20/python-practice | /functions_basic2.py | 2,510 | 4.4375 | 4 | # Countdown - Create a function that accepts a number as an input.
# Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
# Example: countdown(5) should return [5,4,3,2,1,0]
def countdown(num):
nums_list = []
for val in range(num, -1, -1):
nums_list.append(val)
return nums_list
# print(countdown(12))
# print(countdown(5))
# Print and Return - Create a function that will receive a list with two numbers.
# Print the first value and return the second.
# Example: print_and_return([1,2]) should print 1 and return 2
def print_and_return(nums_list):
print(nums_list[0])
return nums_list[1]
# print(print_and_return([10,12]))
# First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length.
# Example: first_plus_length([1,2,3,4,5]) should return 6 (first value: 1 + length: 5)
def first_plus_length(nums_list):
return nums_list[0] + len(nums_list)
# print(first_plus_length([13,2,3,4,5]))
# Values Greater than Second - Write a function that accepts a list and
# creates a new list containing only the values from the original list that are greater than its 2nd value.
# Print how many values this is and then return the new list.
# If the list has less than 2 elements, have the function return False
# Example: values_greater_than_second([5,2,3,2,1,4]) should print 3 and return [5,3,4]
# Example: values_greater_than_second([3]) should return False
def values_greater_than_second(orig_list):
new_list = []
# get the second value in the original list
second_val = orig_list[1]
# scan through the original list, find values greater than second value and add them to the new list
for idx in range(len(orig_list)):
if orig_list[idx] > second_val:
new_list.append(orig_list[idx])
print(len(new_list))
return new_list
# print(values_greater_than_second([5,2,3,2,1,4]))
# This Length, That Value - Write a function that accepts two integers as parameters: size and value.
# The function should create and return a list whose length is equal to the given size, and whose values are all the given value.
# Example: length_and_value(4,7) should return [7,7,7,7]
# Example: length_and_value(6,2) should return [2,2,2,2,2,2]
def length_and_value(size, value):
new_list = []
for num_times in range(size):
new_list.append(value)
return new_list
# print(length_and_value(4,7))
| true |
607e0ba035eaa2dc9216f0884c1562036797ba79 | Jagadeesh-Cha/datamining | /comparision.py | 487 | 4.28125 | 4 | # importing the required module
import matplotlib.pyplot as plt
# x axis values
x = [1,2,3,4,5,6,7,8,9,10]
# corresponding y axis values
y = [35,32,20,14,3,30,6,20,2,30]
# plotting the points
plt.plot(x, y)
# naming the x axis
plt.xlabel('busiest places in descending-order')
# naming the y axis
plt.ylabel('# of important customers')
# giving a title to my graph
plt.title('important_customers')
# function to show the plot
plt.show() | true |
b4816526ef6cc323464ac3e9f787a6032e32072f | lilimonroy/CrashCourseOnPython-Loops | /q1LoopFinal.py | 507 | 4.125 | 4 | #Complete the function digits(n) that returns how many digits the number has. For example: 25 has 2 digits and 144 has 3 digits.
# Tip: you can figure out the digits of a number by dividing it by 10 once per digit until there are no digits left.
def digits(n):
count = 0
if n == 0:
return 1
while (n > 0):
count += 1
n = n // 10
return count
print(digits(25)) # Should print 2
print(digits(144)) # Should print 3
print(digits(1000)) # Should print 4
print(digits(0)) # Should print 1
| true |
0ca00b26b0774c6e0d1891fca4567889cc657a01 | Mmingo28/Week-3 | /Python Area and Radius.py | 263 | 4.28125 | 4 |
#MontellMingo
#1/30/2020
#The program asks if the user can compute the area of an circle and the radius.
radius = int(input("what is the radius"))
#print("what is the number of the radius"+ )
print("what is the answer")
print(3.14*radius*radius)
| true |
8fbfcc3bcd13f2db5c6178cd7ed40f9eade923fc | xywgo/Learn | /LearnPython/Chapter 10/addition.py | 372 | 4.1875 | 4 |
while True:
try:
number1 = input("Please enter a number:(enter 'q' to quit) ")
if number1 == 'q':
break
number1 = int(number1)
number2 = input("Please enter another number:(enter 'q' to quit) ")
if number2 == 'q':
break
number2 = int(number2)
except ValueError:
print("You must enter a number")
else:
results = number1 + number2
print(results) | true |
d025ef9b5f54fb004dc8ed67b652469566c92754 | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/has_zero_triplets.py | 1,089 | 4.1875 | 4 | """
Given an array of integers that do not contain duplicate values,
determine if there exists any triplets that sum up to zero.
For example,
L = [-3, 2, -5, 8, -9, -2, 0, 1]
e = {-3, 2, 1}
return true since e exists
This solution uses a hash table to cut the time complexity down by n.
Time complexity: O(n^2)
Space complexity: O(n)
Hint: a+b+c = 0 => c = -(a+b)
Once we know the first two elements of the triplet, we can compute the third
and check its existence in a hash table.
"""
# @param arr the list of integers to be checked for zero triples
# @return true if three elements exist that sum up to zero
def has_zero_triplet(arr):
if not arr:
return False
numbers = set([])
for number in arr:
numbers.add(number)
for i in range(0, len(arr) - 1):
for j in range(i, len(arr)):
first = arr[i]
second = arr[j]
third = -first - second
if third in numbers:
return True
return False
if __name__ == '__main__':
print(has_zero_triplet([-3, 2, -5, 8, -9, -2, 0, 1]))
| true |
31966a029427f2de3759a8af889481c05e30339a | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/three_sum_closest.py | 1,284 | 4.34375 | 4 | """
Given an array "nums" of n integers and an integer "target", find three integers in nums such that the sum is closest
to "target". Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2)
"""
def three_sum_closest(nums, target):
if not nums:
return 0
nums.sort()
difference = float('inf')
target_sum = 0
for i in range(0, len(nums)-2):
j = i + 1
k = len(nums) - 1
while j < k:
first_num = nums[i]
second_num = nums[j]
third_num = nums[k]
element_sum = first_num + second_num + third_num
if element_sum < target:
j += 1
elif element_sum > target:
k -= 1
else:
return element_sum
current_difference = abs(element_sum - target)
if current_difference < difference:
difference = current_difference
target_sum = element_sum
return target_sum
assert three_sum_closest([-1, 2, 1, -4], 1) == 2
assert three_sum_closest([], 1) == 0
print("All tests passed successfully.") | true |
a7ad18871194654ee4d1cf04e1264b670df3d204 | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/toeplitz_matrix.py | 1,212 | 4.46875 | 4 | """
A matrix is Toeplitz if every diagonal from top-left to bottom-right has the same element. Now given an MxN matrix,
return True if and only if the matrix is Toeplitz.
Example 1:
Input: matrix = [[1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2]]
Output: True
Explanation:
1234
5123
9512
In the above grid, the diagonals are "[9]", "[5, 5]', "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]"
Note:
1. matrix will be a 2D array of integers
2. matrix will have a number of rows and columns in range [1, 20]
3. matrix[i][j] will be integers in range [0, 99]
https://leetcode.com/problems/toeplitz-matrix/description/
"""
def is_toeplitz_matrix(matrix):
for row_idx, row in enumerate(matrix):
for col_idx, value in enumerate(row):
if col_idx == 0 or row_idx == 0:
continue
if value != matrix[row_idx - 1][col_idx - 1]:
return False
return True
assert is_toeplitz_matrix([[1, 2, 3, 4],
[5, 1, 2, 3],
[9, 5, 1, 2]]) is True
assert is_toeplitz_matrix([[1, 2, 3, 4],
[5, 5, 5, 5],
[9, 9, 9, 9]]) is False
print("All tests passed successfully.")
| true |
895e80acf9eed3e1b580a9ac4dec51eb295e7319 | davidadamojr/diary_of_programming_puzzles | /sorting_and_searching/find_in_rotated_array.py | 1,653 | 4.21875 | 4 | """
Given a sorted array of n integers that has been rotated an unknown number of times,
write code to find an element in the array. You may assume that the array was originally
sorted in increasing order.
"""
def find_in_rotated(key, rotated_lst, start, end):
"""
fundamentally binary search...
Either the left or right half must be normally ordered. Find out which
side is normally ordered, and then use the normally ordered half to figure
out which side to search to find x.
"""
if not rotated_lst:
return None
if end < start:
return None
middle_idx = (start + end) / 2
middle_elem = rotated_lst[middle_idx]
leftmost_elem = rotated_lst[start]
rightmost_elem = rotated_lst[end]
if middle_elem == key:
return middle_idx
if leftmost_elem < middle_elem:
if leftmost_elem <= key < middle_elem:
return find_in_rotated(key, rotated_lst, start, middle_idx - 1)
else:
return find_in_rotated(key, rotated_lst, middle_idx + 1, end)
else:
if middle_elem < key <= rightmost_elem:
return find_in_rotated(key, rotated_lst, middle_idx + 1, end)
else:
return find_in_rotated(key, rotated_lst, start, middle_idx - 1)
if __name__ == '__main__':
assert find_in_rotated(1, [4, 5, 6, 1, 2, 3], 0, 5) == 3
assert find_in_rotated(5, [1, 2, 3, 4, 5, 6], 0, 5) == 4
assert find_in_rotated(5, [6, 6, 6, 6, 6, 6], 0, 5) == None
assert find_in_rotated(7, [6, 6, 6, 7, 7, 7, 7], 0, 6) == 3
assert find_in_rotated(6, [6, 6, 6, 6, 6, 6], 0, 5) == 2
print("All test cases passed.")
| true |
46a081380aa96ceaf062d72e0101881f8d57a08c | davidadamojr/diary_of_programming_puzzles | /bit_manipulation/hamming_distance.py | 1,025 | 4.3125 | 4 | """
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers num1 and num2, calculate the Hamming distance.
https://leetcode.com/problems/hamming-distance/
"""
# @param num1 integer
# @param num2 integer
def hamming_distance(num1, num2):
distance = 0
while num1 > 0 and num2 > 0:
xor = num1 ^ num2
if xor % 2 == 1:
distance = distance + 1
num1 = num1 >> 1
num2 = num2 >> 1
while num1 > 0:
xor = num1 ^ 0
if xor % 2 == 1:
distance = distance + 1
num1 = num1 >> 1
while num2 > 0:
xor = num2 ^ 0
if xor % 2 == 1:
distance = distance + 1
num2 = num2 >> 1
return distance
if __name__ == '__main__':
assert hamming_distance(1, 4) == 2
assert hamming_distance(0, 0) == 0
assert hamming_distance(8, 4) == 2
assert hamming_distance(4, 8) == 2
print("All test cases passed successfully.")
| true |
1ebdbdafcc3dadabe48676ca0dbda76cdb3181d8 | davidadamojr/diary_of_programming_puzzles | /misc/convert_to_hexadecimal.py | 1,658 | 4.75 | 5 | """
Given an integer, write an algorithm to convert it to hexadecimal. For negative integers, two's complement method is
used.
Note:
1. All letters in hexadecimal (a-f) must be in lowercase.
2. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero
character '0'; otherwise, the first character in the hexadecimal string will not be zero character.
3. The given number is guaranteed to fit within the range of a 32-bit signed integer.
4. You must not use any method provided by the library which converts/formats the number to hex directly.
Example 1:
Input:
26
Output:
"1a"
Example 2:
Input:
-1
Output:
"ffffffff"
"""
# @param num the number to convert to hexadecimal
# @return the hexadecimal representation of the number
def to_hex(num):
if num == 0:
return "0"
hex_digits = {
10: "a",
11: "b",
12: "c",
13: "d",
14: "e",
15: "f"
}
hex_num = ""
is_negative = False
if num < 0:
magnitude = abs(num)
mask = ((1 << 32) - 1) + (1 << 32)
inverted = magnitude ^ mask
num = inverted + 1
is_negative = True
while num != 0:
remainder = num % 16
num = num / 16
if remainder in hex_digits:
hex_num = hex_digits[remainder] + hex_num
else:
hex_num = str(remainder) + hex_num
if is_negative:
return hex_num[1:]
return hex_num
if __name__ == '__main__':
assert to_hex(0) == "0"
assert to_hex(-1) == "ffffffff"
assert to_hex(26) == "1a"
print("All test cases passed successfully.")
| true |
a6673418628269bdac32de4aaa469fc9ea6b8239 | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/integer_to_string.py | 952 | 4.6875 | 5 | """
Write a routine to convert a signed integer into a string.
"""
def integer_to_string(integer):
"""
Writes the string backward and reverses it
"""
if integer < 0:
is_negative = True
integer = -integer # for negative integers, make them positive
else:
is_negative = False
integer_string = ""
while integer != 0:
new_digit = integer % 10
# "ord" returns the character code of its argument
ascii_code = ord('0') + new_digit
# "chr" returns the string representation of its argument
integer_string = integer_string + chr(ascii_code)
integer = integer / 10
# in python, the easiest way to reverse a string is "string[::-1]"\
integer_string = '-' + integer_string[::-1] if is_negative else integer_string[::-1]
return integer_string
if __name__ == "__main__":
print(integer_to_string(-1234))
print(integer_to_string(54321))
| true |
e114ca362bb69f5298c5137696ee4aaffec569ad | davidadamojr/diary_of_programming_puzzles | /mathematics_and_probability/intersect.py | 931 | 4.125 | 4 | """
Given two lines on a Cartesian plane, determine whether the two lines would
intersect.
"""
class Line:
def __init__(self, slope, yIntercept):
self.slope = slope
self.yIntercept = yIntercept
def intersect(line1, line2):
"""
If two different lines are not parallel, then they intersect.
To check if two lines intersect, we just need to check if the slopes are
different (or if the lines are identical)
Note: Due to the limitations of floating point representations, never check
for equality with ==. Instead, check if the difference is less than an
epsilon value.
"""
epsilon = 0.000001 # used for floating point comparisons
return abs(line1.slope - line2.slope) > epsilon \
or abs(line1.yIntercept - line2.yIntercept) < epsilon;
if __name__ == '__main__':
line1 = Line(0.5, 1)
line2 = Line(0.5, 2)
print(intersect(line1, line2))
| true |
76e8af6b3ef66bce39724bd917d84150361c139e | davidadamojr/diary_of_programming_puzzles | /arrays_and_strings/excel_sheet_column_title.py | 662 | 4.15625 | 4 | """
Given a positive integer, return its corresponding column title as it appears
in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
"""
def convert_to_title(num):
integer_map = {}
characters = "ZABCDEFGHIJKLMNOPQRSTUVWXY"
for i in range(0, 26):
integer_map[i] = characters[i]
column_title = ""
while num != 0:
remainder = num % 26
num = num - 1
num = num / 26
column_title = integer_map[remainder] + column_title
return column_title
if __name__ == '__main__':
print(convert_to_title(703))
print(convert_to_title(27))
print(convert_to_title(26))
| true |
332acd1b09be1ad4bdea876a5f3f82633319c7bc | cryojack/python-programs | /charword.py | 402 | 4.34375 | 4 | # program to count words, characters
def countWord():
c_str,c_char = "",""
c_str = raw_input("Enter a string : ")
c_char = c_str.split()
print "Word count : ", len(c_char)
def countChar():
c_str,c_char = "",""
charcount_int = 0
c_str = raw_input("Enter a string : ")
for c_char in c_str:
if c_char is not " " or "\t" or "\n":
charcount_int += 1
print "Character count : ", charcount_int | true |
2c12b700e72b2cd155a8dca90a3e2389106eed3f | koenigscode/python-introduction | /content/partials/comprehensions/list_comp_tern.py | 311 | 4.25 | 4 | # if the character is not a blank, add it to the list
# if it already is an uppercase character, leave it that way,
# otherwise make it one
l = [c if c.isupper() else c.upper()
for c in "This is some Text" if not c == " "]
print(l)
# join the list and put "" (nothing) between each item
print("".join(l))
| true |
22e20f3364f8498766caf17e4dc8b967ef217f5b | BMariscal/MITx-6.00.1x | /MidtermExam/Problem_6.py | 815 | 4.28125 | 4 | # Problem 6
# 15.0/15.0 points (graded)
# Implement a function that meets the specifications below.
# def deep_reverse(L):
# """ assumes L is a list of lists whose elements are ints
# Mutates L such that it reverses its elements and also
# reverses the order of the int elements in every element of L.
# It does not return anything.
# """
# # Your code here
# For example, if L = [[1, 2], [3, 4], [5, 6, 7]] then deep_reverse(L) mutates L to be [[7, 6, 5], [4, 3], [2, 1]]
# Paste your entire function, including the definition, in the box below. Do not leave any debugging print statements.
def deep_reverse(L):
for i in L:
i.reverse()
L.reverse()
return L
# Test: run_code([[0, -1, 2, -3, 4, -5]])
# Output:
# [[-5, 4, -3, 2, -1, 0]]
# None
| true |
73e4c51440c5d6da38f297556843c0173f0153ee | alexhong33/PythonDemo | /PythonDemo/Day01/01print.py | 1,140 | 4.375 | 4 | #book ex1-3
print ('Hello World')
print ("Hello Again")
print ('I like typing this.')
print ('This is fun.')
print ('Yay! Printing.')
print ("I'd much rather you 'not'.")
print ('I "said" do not touch this.')
print ('你好!')
#print ('#1')
# A comment, this is so you can read your program later.
# Anything after this # is ignored by python
print("I could have code like this.") # and the comment after is ignored
# You can also use a comment to "disable" or comment out a piece of code:
# print "This won't run."
print("This will run.")
# this is the first Comment
spam = 1 # and this is the second Comment
# ... and now a third!
text = " # This is not a comment because it's inside quotes."
print (2 + 2)
print (50 - 5 * 6)
print ((50 - 5 * 6) / 4)
print (8/5) #division always returns a floating point number
print (8//5) #获得整数
print (8%5) #获得余数
print (5 * 3 + 2)
print (5 ** 2) #5 squared
print (2 ** 8)
print (2.5 * 4 / 5.0)
print(7.0/2) #python完全支持浮点数, 不同类型的操作数混在一起时, 操作符会把整型转化为浮点型
| true |
41af103a812a599e376b79251c7f1c76a01fe914 | KevinOluoch/Andela-Labs | /missing_number_lab.py | 787 | 4.4375 | 4 | def find_missing( list1, list2 ):
"""When presented with two arrays, all containing positive integers,
with one of the arrays having one extra number, it returns the extra number
as shown in examples below:
[1,2,3] and [1,2,3,4] will return 4
[4,66,7] and [66,77,7,4] will return 77
"""
#The lists are checked to ensure none of them is empty and if they are equal
if list1 == list2 or not (list1 or list2):
return 0
#If list1 is the larger one, the process of checking for the extra number is reversed
if len(list1) > len (list2):
return [ x for x in list1 if x not in list2 ][0]
return [ x for x in list2 if x not in list1 ][0]
print find_missing ( [66,77,7,4], [4,66,7] )
print find_missing ( [1,2,3], [1,2,3,4] ) | true |
b2875d7737c5fd6cc06a5299f9f8c888c93bebb8 | byhay1/Practice-Python | /Repl.it-Practice/forloops.py | 1,856 | 4.71875 | 5 | #--------
#Lets do for loops
#used to iterate through an object, list, etc.
# syntax
# my_iterable = [1,2,3]
# for item_name in my_iterable
# print(item_name)
# KEY WORDS: for, in
#--------
#first for loop example
mylist = [1,2,3,4,5,6,7,8,9,10]
#for then variable, you chose the variable
print('\n')
for num in mylist:
print(num)
#or you can print whatever you want, flexible
print('\n')
for num in mylist:
print ('Hi')
#ctrl flow with for loops
print('\n')
for num in mylist:
if num % 2 == 0:
print (num, 'even')
else:
print (num, 'odd future')
#get the sum of everything using loop
listsum = 0
print('\n')
for num in mylist:
listsum = listsum + num
print(listsum)
#show all by putting it in the for loop through indentation
print('\n')
for num in mylist:
listsum = listsum + num
print(listsum)
#do for strings
print('\n')
mystring = 'Hello World'
for letter in mystring:
print (letter)
#can use the underscore when you are not assigning variables '_'
print('\n')
for _ in mystring:
print("don't you dare look at me")
#tuple stuffs, tuple unpacking
print('\n')
mylist2 = [(1,2),(3,4),(5,6),(7,8)]
print(len(mylist2))
#return tuples back using a for loop
for item in mylist2:
print(item)
#Or you can do the following
#(a,b) does not need '()'
print('\n', 'unpacking the tuples!')
for (a,b) in mylist2:
print(a)
print(b)
#------------
#iterating through a dictionary
#------------
d = {'k1':1,'k2':2,'k3':3}
#only iterating the Key... not the value
#if you want only the value use .values()
print('\n')
for item in d:
print(item)
#------------
#If you want to iterate the value use the .items()
#This will give you the full item tuple set.
#------------
for item in d.items():
print(item)
#use unpacking to get the dictionary values
for key, value in d.items():
print(key, '=', value)
| true |
29d08b7acb73e2baeb8a2daf67be103e1ad302fc | byhay1/Practice-Python | /Repl.it-Practice/tuples.py | 828 | 4.1875 | 4 | #------------
#tuples are immutable and similar to list
#FORMAT of a tuple == (1,2,3)
#------------
# create a tuple similar to a list but use '()' instead of '[]'
#define tuple
t = (1,2,3)
t2 = ('a','a','b')
mylist = [1,2,3]
#want to find the class type use the typle function type(PUTinVAR)
print('',"Find the type of the var 't' by using type(t): ", type(t), '\n', "Find the other type using type(mylist): ", type(mylist),'\n')
#can use other identifiers like a len(PUTinVar) and splice it how you want VAR[start:stop:step]
#find how many times a value occurs in a tuple or list
#do so by using the .count method
print('','There are only two methods you can use to get the count and the index position \n',"So t2.count('a') = ")
print(t2.count('a'))
#get the index num
print("and t2.index('b') = ")
print(t2.index('b'))
| true |
4f3e7af26400a2f4c309cffa69d5a6f874819731 | byhay1/Practice-Python | /Repl.it-Practice/OOPattributeClass.py | 2,069 | 4.5 | 4 | #----------
# Introduction to OOP:
# Attributes and Class Keywords
#
#----------
import math
mylist = [1,2,3]
myset = set()
#built in objects
type(myset)
type(list)
#######
#define a user defined object
#Classes follow CamelCasing
#######
#Do nothing sample class
class Sample():
pass
#set variable to class
my_sample = Sample()
#see type using built-in object
type(my_sample)
#######
#Give a class attributes
#######
#do something Dog class
class Dog():
def __init__(self,breed,name,spots):
#Attributes
#We take in the argument
#Assign it using self.attribute_name
self.breed = breed
self.name = name
#Expect boolean True/False
self.spots = spots
#because attribute is used, must pass expected attribute or it will return an error
my_dog = Dog(breed='Mutt',name='Ruby',spots=False)
#Check to see type=instance of the dog class.
my_dog.breed
my_dog.name
my_dog.spots
#######PART TWO#######
#######
#Using Class object attribute and more...
#Using Methods within class
#######
######################
class Doggy():
# CLASS OBJECT ATTRIBUTE
# SAME FOR ANY INSTANCE OF A CLASS
clss = 'mammal'
# USER DEFINED ATTRIBUTE
def __init__(self,breed,name):
#Attributes
#We take in the argument
#Assign it using self.attribute_name
self.breed = breed
self.name = name
# OPERATIONS/Actions ---> Methods
def bark(self, number):
print("WOOF! My name is {} and I am {} years old".format(self.name, number))
#because attribute is used, must pass expected attribute or it will return an error
my_dog2 = Doggy(breed='whtMutt',name='Rita')
#Methods need to be executed so they need '(' ')'
my_dog2.bark(2)
#######
#Create a new class called 'Circle'
#######
class Circle():
# CLASS OBJECT ATTRIBUTE
pi = math.pi
def __init__(self, radius=1):
self.radius = radius
self.area = radius*radius*Circle.pi
# METHOD
def get_circumference(self):
return self.radius*2*Circle.pi
my_circle = Circle(33)
print(my_circle.get_circumference)
print(my_circle.area)
print(my_circle.pi)
| true |
eef86cb4c54bf7d0b38ced84acff83220b0304e3 | jongwlee17/teampak | /Python Assignment/Assignment 5.py | 988 | 4.34375 | 4 | """ Exercise 5: Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates).
Make sure your program works on two lists of different sizes.
Extras:
1. Randomly generate two lists to test this
2. Write this in one line of Python (don't worry if you can't figure this out at this point - we'll get to it soon)
"""
import random
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# random_a = range(1, random.randint(1,30))
# random_b = range(1, random.randint(1,40))
print("Random_a list consists of: ", random_a)
print("Random_b list consists of: ", random_b)
def findCommonValues(a, b):
final_list = []
for num in a:
if num in b:
if num not in final_list:
final_list.append(num)
return final_list
print(findCommonValues(a, b)) | true |
3061d9515b321d746e69674f44b9550ae0e6f151 | ankitoct/Core-Python-Code | /40. List/6. AppendMethod.py | 222 | 4.125 | 4 | # Append Method
a = [10, 20, -50, 21.3, 'Geekyshows']
print("Before Appending:")
for element in a:
print (element)
# Appending an element
a.append(100)
print()
print("After Appending")
for element in a:
print (element) | true |
0a064e70245373690e15b0a00b36ee1f2ba76c8d | ankitoct/Core-Python-Code | /45. Tuple/6. tupleModification.py | 585 | 4.125 | 4 | # Modifying Tuple
a = (10, 20, -50, 21.3, 'GeekyShows')
print(a)
print()
# Not Possible to Modify like below line
#a[1] = 40 # Show TypeError
# It is not possible to modify a tuple but we can concate or slice
# to achieve desired tuple
# By concatenation
print("Modification by Concatenation")
b = (40, 50)
tup1 = a + b
print(tup1)
print()
# By Slicing
print("Modification by Slicing")
tup2 = a[0:3]
print(tup2)
print()
# By Concatenation and Slicing
print("Modification by Concatenation and Slicing")
c = (101, 102)
s1 = a[0:2]
s2 = a[3:]
tup3 = s1+c+s2
print(tup3)
print()
| true |
a60165af0986981ea6097e34278a844d9b9b2f70 | MirandaTowne/Python-Projects | /grade_list.py | 754 | 4.46875 | 4 | # Name: Miranda Towne
# Description: Creating a menu that gives user 3 choices
# Empty list
grade = []
done = False
new_grade = ''
# Menu options
menu = """
Grade Book
0: Exit
1: Display a sorted list of grades
2: Add a grade to the list
"""
# Display menu at start of a while loop
while not done:
print(menu)
# Ask for users choice
option = int(input('\nPlease enter an option: '))
# Respond to users choice
if option == 0:
done = True
print("Good bye!")
elif option == 1:
grade.sort
print(grade)
elif option == 2:
new_grade = input('\nPlease add a new grade to the list: ')
grade.append(new_grade)
print("\nGrade added to the list")
print(grade)
| true |
bffb8076b777e4962c687e0f9c790b5fafc93041 | Silentsoul04/2020-02-24-full-stack-night | /1 Python/solutions/unit_converter.py | 697 | 4.25 | 4 | def convert_units(data):
conversion_factors = {
'ft': 0.3048,
'mi': 1609.34,
'm': 1,
'km': 1000,
'yd': 0.9144,
'in': 0.0254,
}
value, unit_from, unit_to = data
converted_m = conversion_factors[unit_from] * value
return round(converted_m / conversion_factors[unit_to], 2)
def main():
user_input = input('\nenter the distance: ')
convert_to_unit = input('\nenter units to convert to: ')
user_input_split = user_input.split(" ")
value = float(user_input_split[0])
unit = user_input_split[1]
print(f'\n{value} {unit} is {convert_units((value, unit, convert_to_unit))} {convert_to_unit}.\n')
main() | true |
63756dbda9070dd378118718383a7dbebcc469d9 | haaks1998/Python-Simple | /07. function.py | 1,011 | 4.1875 | 4 | # A function is a set of statements that take inputs, do some specific computation and returns output.
# We can call function any number of times through its name. The inputs of the function are known as parameters or arguments.
# First we have to define function. Then we call it using its name.
# format:
# def func_name(arg1,arg2,..,argN):
# function statements
# return result
def add(a,b): #Function defination
c = a+b
return c
# Indentation shows that which statements are the part of functions.
# The indented statements are considered to be the part of function. Non indented statements are not part of function
# The code which is indented is in the body block and double indented code creates a block within a block
x = int(input("Enter first number "))
y = int(input("Enter second number "))
ans = add(x,y) #Function call
print(ans)
input("\nPress any key to exit")
| true |
1520b9faa5b957da64ea48e158adacc0e5987adf | pixeltk623/python | /Core Python/Datatypes/string.py | 478 | 4.28125 | 4 | # Strings
# Strings in python are surrounded by either single quotation marks, or double quotation marks.
# 'hello' is the same as "hello".
# You can display a string literal with the print() function:
# print("Hello")
# print('Hello')
# a = "hello"
# print(a)
# a = """cdsa
# asdasdas
# asdasdassdasd
# asdasdsa"""
# print(a)
a = 'Hello, World'
# print(a[1])
# for x in a:
# print(x)
# print(len(a))
# print("Hello" in a)
# print("hello" not in a)
print(a[1:2]) | true |
4b3f9e149707817aefa696ce2d336453cd93f34a | undergraver/PythonPresentation | /05_financial/increase.py | 766 | 4.125 | 4 | #!/usr/bin/env python
import sys
# raise in percent
raise_applied=6
raise_desired=40
# we compute:
#
# NOTE: the raise is computed annually
#
# 1. the number of years to reach the desired raise with the applied raise
# 2. money lost if the desired raise is applied instantly and no other raise is done
salary_now=100
desired_salary=salary_now*(1+raise_desired/100.0)
year_count=0
money_lost=0
while salary_now < desired_salary:
year_count+=1
salary_now=salary_now*(1+raise_applied/100.0)
money_lost += (desired_salary-salary_now)*12.0
print("You will reach desired salary in:%d years" % (year_count))
print("By that time you will lose:%f" % (money_lost))
if year_count > 0:
print("Average year loss is:%f" % (money_lost/year_count))
| true |
6a293c64aabc496cc4e1669935d1659dc1042c39 | Kjartanl/TestingPython | /TestingPython/Logic/basic_logic.py | 368 | 4.21875 | 4 |
stmt = True
contradiction = False
if(stmt):
print("Indeed!")
if(contradiction):
print("Still true, but shouldn't be! Wtf?")
else:
print("I'm afraid I'm obliged to protest!")
print("------- WHILE LOOP ---------")
number = 0
while(number < 5):
print("Nr is %s" %number)
number = number+1
print("Finally, number is %s" % number) | true |
0e07914cfa997c6ee2bef28123972e089f49b454 | montaro/algorithms-course | /P0/Task4.py | 1,234 | 4.125 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
texts = list(reader)
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
calls = list(reader)
"""
TASK 4:
The telephone company want to identify numbers that might be doing
telephone marketing. Create a set of possible telemarketers:
these are numbers that make outgoing calls but never send texts,
receive texts or receive incoming calls.
Print a message:
"These numbers could be telemarketers: "
<list of numbers>
The list of numbers should be print out one per line in lexicographic order with no duplicates.
"""
callers = set()
non_telemarketers = set()
telemarketers = set()
for call in calls:
caller = call[0]
callee = call[1]
callers.add(caller)
non_telemarketers.add(callee)
for text in texts:
sender = text[0]
receiver = text[1]
non_telemarketers.add(sender)
non_telemarketers.add(receiver)
telemarketers = callers.difference(non_telemarketers)
sorted_telemarketers = sorted(telemarketers)
print('These numbers could be telemarketers: ')
for telemarketer in sorted_telemarketers:
print(telemarketer)
| true |
d3eb57ca3377dcb7462afd86e43997a1f220e940 | shivanshutyagi/python-works | /primeFactors.py | 566 | 4.3125 | 4 | def printPrimeFactors(num):
'''
prints primeFactors of num
:argument: number whose prime factors need to be printed
:return:
'''
for i in range(2, num+1):
if isPrime(i) and num%i==0:
print(i)
def isPrime(num):
'''
Checks if num is prime or not
:param num:
:return: true if num is prime, else false
'''
for i in range(2, int(num/2)+1):
if num % i == 0:
return False
return True
if __name__ == "__main__":
n = int(input('Enter the number: '))
printPrimeFactors(n)
| true |
a89ba3ea381c392845379d369981fca1a0a16d1b | roberg11/is-206-2013 | /Assignment 2/ex13.py | 1,150 | 4.4375 | 4 |
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
## Combine raw_input with argv to make a script that gets more input
## from a user.
fruit = raw_input("Name a fruit: ")
vegetable = raw_input("Name a vegetable: ")
print "The name of the fruit: %r. The name of the vegetable: %r." % (fruit, vegetable)
#### Study drills
## Try giving fewer than three arguments to your script.
## See that error you get? See if you can explain it.
## Answer: ValueError: need more than 3 values to unpack.
# Because the script assigns four values to pass the
# ArgumentValue the program won't run with less or more.
## Write a script that has fewer arguments and one that has more.
## Make sure you give the unpacked variables good names.
# Answer: 'python ex13.py apple orange' gives the error:
# ValueError: need more than 3 values to unpack
## Remember that modules give you features. Modules. Modules.
## Remember this because we'll need it later.
| true |
c232410e848da610102a0a08b4077aa2295847b0 | roberg11/is-206-2013 | /Assignment 2/ex20.py | 1,803 | 4.53125 | 5 | from sys import argv
script, input_file = argv
# Definition that reads a file given to the parameter
def print_all(f):
print f.read()
# Definition that 'seeks' to the start of the file (in bytes) given to parameter
# The method seek() sets the file's current position at the
# offset. The whence argument is optional and defaults to 0,
# which means absolute file positioning, other values are 1
# which means seek relative to the current position and 2 means
# seek relative to the file's end.
def rewind(f):
f.seek(0)
# Definition taking two parameters that counts the lines in the file
# and reads each line and prints them.
def print_a_line(line_count, f):
print line_count, f.readline()
# Variable assigned to the method of opening the file given to argument variable
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
## Each time print_a_line is run, you are passing in a variable
## current_line. Write out what current_line is equal to on
## each function call, and trace how it becomes line_count in
## print_a_line.
current_line = 1
# Current line is 1 in this function call
print_a_line(current_line, current_file)
# Current line is 1 + 1 = 2 in this function call
current_line = current_line + 1
print "This is line nr: %r\n" % current_line
print_a_line(current_line, current_file)
# Current line is 2 + 1 = 3 in this function call
current_line = current_line + 1
print "This is line nr: %r\n" % current_line
print_a_line(current_line, current_file)
## Research the shorthand notation += and rewrite the script to use that.
## current_line += 1 is the equivalent of saying current_line = current_line + 1
| true |
676817b23e15e5368746b750f48e518427c937ae | onerbs/w2 | /structures/w2.py | 1,914 | 4.28125 | 4 | from abc import ABC, abstractmethod
from typing import Iterable
from structures.linked_list_extra import LinkedList
class _Linear(ABC):
"""Abstract linear data structure."""
def __init__(self, items: Iterable = None):
self._items = LinkedList(items)
def push(self, item):
"""Adds one item."""
self._items.push(item)
@abstractmethod
def pop(self):
"""Removes one item.
:returns: The removed item.
"""
pass
def is_empty(self):
return self._items.is_empty()
def __contains__(self, item):
return item in self._items
def __iter__(self) -> iter:
return iter(self._items)
def __len__(self) -> int:
return len(self._items)
def __str__(self) -> str:
return str(self._items)
class Stack(_Linear):
def push(self, item): # O(1)
"""Adds one item to the stack."""
super().push(item)
def pop(self): # O(n)
"""Removes the oldest item from the stack."""
return self._items.pop() # LIFO
class Queue(_Linear):
def push(self, item): # O(1)
"""Adds one item to the queue."""
super().push(item)
def pop(self): # O(1)
"""Removes the most resent item from the queue."""
return self._items.shift() # FIFO
class Deque(_Linear):
def push(self, item): # O(1)
"""Adds one item to the end of the deque."""
super().push(item)
def pop(self): # O(n)
""" Removes the last item from the deque.
:returns: The removed item.
"""
return self._items.pop()
def unshift(self, value): # O(1)
"""Adds one item to the beginning of the deque."""
self._items.unshift(value)
def shift(self): # O(1)
"""Removes the first item from the deque.
:returns: The removed item.
"""
return self._items.shift()
| true |
7f7b411883c7f6985a354f163a11da1a879b0cac | nishaagrawal16/Datastructure | /Python/decorator_for_even_odd.py | 1,363 | 4.21875 | 4 | # Write a decorator for a function which returns a number between 1 to 100
# check whether the returned number is even or odd in decorator function.
import random
def decoCheckNumber(func):
print ('Inside the decorator')
def xyz():
print('*************** Inside xyz *********************')
num = func()
print(num)
if num %2 != 0: # Odd
print('number is odd')
else:
print('number is Even')
return xyz
@decoCheckNumber
def random_number():
return random.randrange(1, 100)
for i in range(10):
random_number()
# Output:
# ------
#
# Inside the decorator
# *************** Inside xyz *********************
# 17
# number is odd
# *************** Inside xyz *********************
# 3
# number is odd
# *************** Inside xyz *********************
# 6
# number is Even
# *************** Inside xyz *********************
# 32
# number is Even
# *************** Inside xyz *********************
# 66
# number is Even
# *************** Inside xyz *********************
# 84
# number is Even
# *************** Inside xyz *********************
# 96
# number is Even
# *************** Inside xyz *********************
# 45
# number is odd
# *************** Inside xyz *********************
# 14
# number is Even
# *************** Inside xyz *********************
# 64
# number is Even
| true |
aa5bc400ed332b046f45db6233975294afa48494 | nishaagrawal16/Datastructure | /Linklist/partition_a_link_list_by_a_given_number.py | 2,555 | 4.125 | 4 | #!/usr/bin/python
# Date: 2018-09-17
#
# Description:
# There is a linked list given and a value x, partition a linked list such that
# all element less x appear before all elements greater than x.
# X should be on right partition.
#
# Like, if linked list is:
# 3->5->8->5->10->2->1 and x = 5
#
# Resultant linked list should be:
# 3->2->1->5->8->5->10
#
# Approach:
# Maintain 2 linked list 'BEFORE' and 'AFTER'. Traverse given linked list, if
# value at current node is less than x insert this node at end of 'BEFORE'
# linked list otherwise at end of 'AFTER' linked list.
# At the end, merge both linked lists.
#
# Complexity:
# O(n)
class Node:
def __init__(self, value):
self.info = value
self.next = None
class LinkList:
def __init__(self):
self.start = None
def create_list(self, li):
if self.start is None:
self.start = Node(li[0])
p = self.start
for i in range(1,len(li)):
temp = Node(li[i])
p.next = temp
p = p.next
def traverse(self):
p = self.start
while p is not None:
print('%d ->' % p.info, end='')
p = p.next
print ('None')
def partitionList(self, x):
before_start = None
before_end = None
after_start = None
after_end = None
p = self.start
present = 0
while p is not None:
if p.info == x:
present = 1
if p.info < x:
if before_start is None:
before_start = p
before_end = p
else:
before_end.next = p
before_end = before_end.next
else:
if after_start is None:
after_start = p
after_end = p
else:
after_end.next = p
after_end = after_end.next
p = p.next
if not present:
print('Element %d is not present in the list.' % x)
return False
# May be possible that before list is empty as no numebr is less than x.
# so check the before end is not None otherwise make the after_start as
# starting point of the list.
after_end.next = None
if before_end is None:
self.start = after_start
return True
# merge both link lists
before_end.next = after_start
self.start = before_start
return True
def main():
print ('*************** LIST ***********************')
link_list_1 = LinkList()
link_list_1.create_list([3, 5, 8, 5, 10, 2, 1])
link_list_1.traverse()
print ('\n***** LIST AFTER PARTITIONS BY A NUMBER *****')
if link_list_1.partitionList(5):
link_list_1.traverse()
if __name__ == '__main__':
main()
| true |
bf13df5bf072797b535624bca57f87f5f5c7b39c | nishaagrawal16/Datastructure | /sorting/bubble_sort.py | 1,314 | 4.6875 | 5 | # Date: 20-Jan-2020
# https://www.geeksforgeeks.org/python-program-for-bubble-sort/
# Bubble Sort is the simplest sorting algorithm that works by
# repeatedly swapping the adjacent elements if they are in wrong order.
# Once the first pass completed last element will be sorted.
# On next pass, we need to compare till last-1 elements and in next pass
# last-2,...so on
# Example:
# list: [8, 5, 6, 9, 1, 4, 10, 3, 2, 7]
# Pass1: [5, 6, 8, 1, 4, 9, 3, 2, 7, 10]
# ---- Sorted
# Pass2: [5, 6, 1, 4, 8, 3, 2, 7, 9, 10]
# -------- Sorted
# .... So on
# Time Complexity: O(n2)
# Space Complexity: O(1)
def bubble_sort(un_list):
n = len(un_list)
for i in range(n):
for j in range(n-1-i):
if un_list[j] > un_list[j+1]:
un_list[j+1], un_list[j] = un_list[j], un_list[j+1]
def main():
unsorted_list = [8, 5, 6, 9, 1, 4, 10, 3, 2, 7]
print('************ UNSORTED LIST **************')
print(unsorted_list)
bubble_sort(unsorted_list)
print('************** SORTED LIST **************')
print(unsorted_list)
if __name__ == '__main__':
main()
# Output:
# -------
# ************ UNSORTED LIST **************
# [8, 5, 6, 9, 1, 4, 10, 3, 2, 7]
# ************** SORTED LIST **************
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
| true |
da785b4c17fbed0a35787f7db82ee578ffaf07bf | nishaagrawal16/Datastructure | /Python/overriding.py | 2,643 | 4.46875 | 4 | # Python program to demonstrate error if we
# forget to invoke __init__() of parent.
class A(object):
a = 1
def __init__(self, n = 'Rahul'):
print('A')
self.name = n
class B(A):
def __init__(self, roll):
print('B')
self.roll = roll
# If you forget to invoke the __init__()
# of the parent class then its instance variables would not be
# available to the child class.
# The self parameter within super function acts as the object of
# the parent class
super(B, self).__init__()
# OR
# A.__init__(self)
b = B(23)
print(b.roll)
print(b.name)
print(b.a)
# Output:
# -------
# B
# A
# 23
# Rahul
# 1
# Python program to demonstrate private members of the parent class
class C(object):
def __init__(self):
self.c = 21
# d is private instance variable
self.__d = 42
class D(C):
def __init__(self):
self.e = 84
self.__f = 99
C.__init__(self)
object1 = D()
print(dir(object1))
# This is the way to call the private variables
print(object1._C__d)
print(object1._D__f)
# produces an error as d is private instance variable
# print D.d
# Output:
# ------
# ['_C__d', '_D__f', '__class__', '__delattr__', '__dict__', '__doc__',
# '__format__', '__getattribute__', '__hash__', '__init__', '__module__',
# '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
# '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'c', 'e']
# 42
# 99
# Python code to demonstrate multiple inheritance
# we cannot override a private method of a superclass, which is the one having
# double underscores before its name.
# Base Class
class A(object):
def __init__(self):
constant1 = 1
def __method1(self):
print('method1 of class A')
class B(A):
def __init__(self):
constant2 = 2
A. __init__(self)
def __method1(self):
print('method1 of class B')
def calling1(self):
self.__method1()
self._A__method1()
b = B()
# AttributeError: 'B' object has no attribute '__method1'
# b.__method1()
# How to call the private methods of a class.
b._B__method1()
b._A__method1()
print('******* Calling1 **************')
b.calling1()
# Output:
# ------
# method1 of class B
# method1 of class A
# ******* Calling1 **************
# method1 of class B
# method1 of class A
| true |
fee51facfda5df96e5aa73eaf6f7d3962df39c2c | cherkesky/urbanplanner | /city.py | 762 | 4.59375 | 5 | '''
In the previous Urban Planner exercise, you practices defining custom types to represent buildings. Now you need to create a type to represent your city. Here are the requirements for the class. You define the properties and methods.
Name of the city.
The mayor of the city.
Year the city was established.
A collection of all of the buildings in the city.
A method to add a building to the city.
Remember, each class should be in its own file. Define the City class in the city.py file.
'''
class City:
def __init__ (self, name, mayor, year_established):
self.name = name
self.mayor = mayor
self.year_established = year_established
self.city_buildings = list()
def addBuildings(self, building):
self.city_buildings.append(building) | true |
8da1b3e55c7d3c0f941d28d2395c1e1d353be217 | spikeyball/MITx---6.00.1x | /Week 1 - Problem 3.py | 1,002 | 4.125 | 4 | # Problem 3
# 15.0/15.0 points (graded)
# Assume s is a string of lower case characters.
#
# Write a program that prints the longest substring of s in which the letters
# occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your
# program should print
#
# Longest substring in alphabetical order is: beggh
# In the case of ties, print the first substring. For example, if s = 'abcbcd',
# then your program should print
#
# Longest substring in alphabetical order is: abc
# Note: This problem may be challenging. We encourage you to work smart. If
# you've spent more than a few hours on this problem, we suggest that you move on
# to a different part of the course. If you have time, come back to this problem
# after you've had a break and cleared your head.
lstring = s[0]
cstring = s[0]
for char in s[1::]:
if char >= cstring[-1]:
cstring += char
if len(cstring) > len(lstring):
lstring = cstring
else:
cstring = char
print(lstring)
| true |
832de19c8b9ab75f412d3f0ebc57f6791bc0d15f | Kpsmile/Learn-Python | /Basic_Programming/Collections.py | 1,580 | 4.53125 | 5 | a = [3, 6, 8, 2, 78, 1, 23, 45, 9]
print(sorted(a))
"""
Sorting a List of Lists or Tuples
This is a little more complicated, but still pretty easy, so don't fret!
Both the sorted function and the sort function take in a keyword argument called key.
What key does is it provides a way to specify a function that returns what you would like your items
sorted by. The function gets an "invisible" argument passed to it that represents an item in the list,
and returns
a value that you would like to be the item's "key" for sorting.
So, taking a new list, let's test it out by sorting by the first item in each sub-list
"""
def getkey(item):
return item[1]
l=[[1,30],[4,21],[3,7]]
res=sorted(l, key=getkey)
print(res)
"""
Sorting a List (or Tuple) of Custom Python Objects
"""
class Custom(object):
def __init__(self, name, number):
self.name=name
self.number=number
def __repr__(self):
"""
the __repr__ function tells Python how we want the object to be represented as.
it tells the interpreter how to display the object when it is printed to the screen.
"""
return'{}: {} {}'.format(self.__class__.__name__,
self.name,
self.number)
Customlist=[Custom('abc',10),Custom('xyz',10),Custom('jklm',10),Custom('qrs',10)]
def getkey(item):
return item.name
results=sorted(Customlist, key=getkey)
result_rev=sorted(Customlist, key=getkey,reverse=True)
print(results)
print(result_rev)
| true |
50febd52f27da540cc858944a37969ed932090c6 | surya-lights/Python_Cracks | /math.py | 293 | 4.15625 | 4 | # To find the highest or lowest value in an iteration
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)
# To get the positive value of specified number using abs() function
x = abs(-98.3)
print(x)
# Return the value of 5 to the power of 4 is (same as 5*5*5*5):
x = pow(5, 4)
print(x)
| true |
f8bbfd6363010700b233934b7392629138d29e66 | sanazjamloo/algorithms | /mergeSort.py | 1,395 | 4.4375 | 4 | def merge_sort(list):
"""
Sorts a list in ascending order
Returns a new sorted List
Divide: Find the midpoint of the list and divide into sublists
Conquer: Recursively sort the sublists created in previous step
Combine: Merge the sorted sublists created in previous step
Takes O(n log n) time and O(n) space
"""
#Stopping condition of the recursion
if len(list) <= 1:
return List
left_half, right_half = split(list)
left = merge_sort(left_half)
right = merge_sort(right_half)
return merge(left, right)
def split(list):
"""
Divide the unsorted list at midpoint into sublists
Returns two sublists - left and right_half
Takes overal O(log n) time
"""
# // for floor operation
mid = len(list) //2
left = list[:mid]
right = list[mid:]
return left, right
def merge (left, right):
"""
Merges two lists (left and right), sorting them in the process
Returns a new merged list
Runs in overall O(n) time
"""
l = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
l.append(left[i])
i+ = 1
else:
l.append(right[j])
j+ = 1
return l
| true |
73631147ca4cc0322de2a68a36290502ee230907 | ytgeng99/algorithms | /Pythonfundamentals/FooAndBar.py | 1,040 | 4.25 | 4 | '''Write a program that prints all the prime numbers and all the perfect squares for all numbers between 100 and 100000.
For all numbers between 100 and 100000 test that number for whether it is prime or a perfect square. If it is a prime number print "Foo". If it is a perfect square print "Bar". If it is neither print "FooBar". Do not use the python math library for this exercise. For example, if the number you are evaluating is 25, you will have to figure out if it is a perfect square. It is, so print "Bar".'''
for i in range(100, 100001):
if i == 1:
prime = False
perfect_square = True
else:
prime = True
perfect_square = False
for j in range(2, i):
if i%j == 0:
prime = False
if j**2 == i:
perfect_square = True
if j*2 > i or j**2 > i:
break
if not prime and not perfect_square:
print i, 'FooBar'
elif prime:
print i, 'Foo'
elif perfect_square:
print i, 'Bar'
| true |
44a002f5ed28792f31033331f79f49b24d6bc3ef | ytgeng99/algorithms | /Pythonfundamentals/TypeList.py | 1,320 | 4.375 | 4 | '''Write a program that takes a list and prints a message for each element in the list, based on that element's data type.
Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the array contains. If it contains only one type, print that type, otherwise, print 'mixed'.'''
l = ['magical unicorns',19,'hello',98.98,'world']
'''l = [2,3,1,7,4,12]
l = ['magical','unicorns']
l = []'''
new_str_list = []
sum = 0
str_items = 0
num_items = 0
for item in l:
if type(item) == str:
new_str_list.append(item)
str_items += 1
elif type(item) == int or type(item) == float:
sum += item
num_items += 1
if (str_items == 0 and num_items == 0):
print 'The array you entered is empty'
elif (str_items > 0 and num_items > 0):
print 'The array you entered is of mixed type'
elif (str_items != 0 and num_items == 0):
print 'The array you entered is of string type'
elif (str_items == 0 and num_items != 0):
print 'The array you entered is of number type'
if (str_items != 0):
print 'String:', ' '.join(new_str_list)
if (num_items != 0):
print 'Sum:', sum | true |
c8bc084cc06c30404dbb8d5cd6653dd74d007405 | KatePavlovska/python-laboratory | /laboratory1&2update/Lab2_Task2_calculation_pavlovska_km_93.py | 640 | 4.25 | 4 | print("Павловська Катерина. КМ-93. Варіант 14. ")
print("Task2: Given an integer N (> 0), which is a degree of 2: N = 2K. Finding an integer K is an exponent of this degree.")
print()
import re
re_integer = re.compile("^[-+]?\d+$")
def validator(pattern, promt):
text = input(promt)
while not bool(pattern.match(text)):
text = input(promt)
return text
number = int( validator( re_integer, "Input number: "))
counter = 0
while number % 2 == 0:
number /= 2
counter += 1
if number != 1:
print("This number is not a power of 2!")
else:
print("This number is", counter, " power")
| true |
21a2fbe709284990b8d486f7aabd79ddc269d4bf | AlexChesser/CIT590 | /04-travellingsalesman/cities.py | 2,041 | 4.28125 | 4 | def read_cities(file_name)
"""Read in the cities from the given file_name, and return them as a list
of four-tuples: [(state, city, latitude, longitude), ...] Use this as your
initial road_map, that is, the cycle Alabama → Alaska → Arizona → ... → Wyoming → Alabama."""
pass
def print_cities(road_map)
"""Prints a list of cities, along with their locations. Print only one or
two digits after the decimal point."""
pass
def compute_total_distance(road_map)
"""Returns, as a floating point number, the sum of the distances of all
the connections in the road_map. Remember that it's a cycle, so that (for example)
in the initial road_map, Wyoming connects to Alabama.."""
pass
def swap_adjacent_cities(road_map, index)
"""Take the city at location index in the road_map, and the city at location
index+1 (or at 0, if index refers to the last element in the list), swap their
positions in the road_map, compute the new total distance, and return the tuple
(new_road_map, new_total_distance)."""
pass
def swap_cities(road_map, index1, index2)
"""Take the city at location index in the road_map, and the city at location
index2, swap their positions in the road_map, compute the new total distance, and
return the tuple (new_road_map, new_total_distance). Allow the possibility that index1=index2,
and handle this case correctly."""
pass
def find_best_cycle(road_map)
"""Using a combination of swap_cities and swap_adjacent_cities, try 10000 swaps,
and each time keep the best cycle found so far. After 10000 swaps, return the best cycle found
so far."""
pass
def print_map(road_map)
"""Prints, in an easily understandable format, the cities and their connections,
along with the cost for each connection and the total cost."""
pass
def main()
"""Reads in and prints out the city data, then creates the "best"
cycle and prints it out."""
pass
if __name__ == '__main__':
main() | true |
40db83e086d8857643c10447811873e55740797b | kajalubale/PythonTutorial | /While loop in python.py | 535 | 4.34375 | 4 | ############## While loop Tutorial #########
i = 0
# While Condition is true
# Inside code of while keep runs
# This will keep printing 0
# while(i<45):
# print(i)
# To stop while loop
# update i to break the condition
while(i<8):
print(i)
i = i + 1
# Output :
# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# Assuming code inside for and while loop is same
# Both While and for loop takes almost equal time
# As both converted into same machine code
# So you can use any thing which is convenient | true |
a991a9d07955fe00dad9a2b46fd32503121249e8 | kajalubale/PythonTutorial | /For loop in python.py | 1,891 | 4.71875 | 5 |
################### For Loop Tutorial ###############
# A List
list1 = ['Vivek', 'Larry', 'Carry', 'Marie']
# To print all elements in list
print(list1[0])
print(list1[1])
print(list1[2])
print(list1[3])
# Output :
# Vivek
# Larry
# Carry
# Marie
# We can do same thing easily using for loop
# for loop runs len(list1) times
# each time item is equal to one elemrnt of list from starting
for item in list1:
print(item)
# Output :
# Vivek
# Larry
# Carry
# Marie
# We can iterate tuple, list of lists, dictionary,
# and many more containers using for loop
# Examples :
# Iterating tuple
list1 = ('Vivek', 'Larry', 'Carry', 'Marie')
for item in list1:
print(item)
# Output :
# Vivek
# Larry
# Carry
# Marie
# Iterating a list of lists
list1 = [["Vivek", 1], ["Larry", 2],
["Carry", 6], ["Marie", 250]]
for item in list1:
print(item)
# Output :
# ['Vivek', 1]
# ['Larry', 2]
# ['Carry', 6]
# ['Marie', 250]
# Iterating a dictionary
dict1 = dict(list1)
print(dict1)
# Output :
# {'Vivek': 1, 'Larry': 2, 'Carry': 6, 'Marie': 250}
for item in dict1:
print(item) # It will print only keys
# Output :
# Vivek
# Larry
# Carry
# Marie
# to print both key and value while iterating dictionary
for item, lollypop in dict1.items():
print(item, "and lolly is ", lollypop)
# Output :
# Vivek and lolly is 1
# Larry and lolly is 2
# Carry and lolly is 6
# Marie and lolly is 250
# Quiz time :
# Ques : Create a list if item in list is numerical
# and number is greater than 6
# Solution
items = [int, float, "HaERRY", 5, 3, 3, 22, 21, 64, 23, 233, 23, 6]
for item in items:
if str(item).isnumeric() and item >= 6:
print(item)
# Remember str(item).isnumeric() is correct
# item.isnumeric() is wrong
# Output :
# 22
# 21
# 64
# 23
# 233
# 23
# 6
| true |
2a3ca27dd93b4c29a43526fa2894f79f38280b82 | kajalubale/PythonTutorial | /41.join function.py | 971 | 4.34375 | 4 | # What is the join method in Python?
# "Join is a function in Python, that returns a string by joining the elements of an iterable,
# using a string or character of our choice."
# In the case of join function, the iterable can be a list, dictionary, set, tuple, or even a string itself.
# The string that separates the iterations could be anything.
# It could just be a comma or a full-length string.
# We can even use a blank space or newline character (/n ) instead of a string.
lis = ["john","cena","khali","randy","ortan","sheamus","jinder mahal"]
# suppose i want to write like john and cena and khali and so no , then we write it as
# for item in lis:
# print(item,"and", end="")# end it used to ignore new line
# simply we can use join method
a = " and ".join(lis)
print(a)
b = " , ".join(lis)
print(b)
#output :
# john and cena and khali and randy and ortan and sheamus and jinder mahal
# john , cena , khali , randy , ortan , sheamus , jinder mahal | true |
060eb25956088487b27ab6fe31077f73b6691857 | mondler/leetcode | /codes_python/0006_ZigZag_Conversion.py | 1,866 | 4.15625 | 4 | # 6. ZigZag Conversion
# Medium
#
# 2362
#
# 5830
#
# Add to List
#
# Share
# The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
#
# P A H N
# A P L S I I G
# Y I R
# And then read line by line: "PAHNAPLSIIGYIR"
#
# Write the code that will take a string and make this conversion given a number of rows:
#
# string convert(string s, int numRows);
#
#
# Example 1:
#
# Input: s = "PAYPALISHIRING", numRows = 3
# Output: "PAHNAPLSIIGYIR"
# Example 2:
#
# Input: s = "PAYPALISHIRING", numRows = 4
# Output: "PINALSIGYAHRPI"
# Explanation:
# P I N
# A L S I G
# Y A H R
# P I
# Example 3:
#
# Input: s = "A", numRows = 1
# Output: "A"
#
#
# Constraints:
#
# 1 <= s.length <= 1000
# s consists of English letters (lower-case and upper-case), ',' and '.'.
# 1 <= numRows <= 1000
class Solution:
def convert(self, s: str, numRows: int) -> str:
if (numRows == 1) or (numRows > len(s)):
return s
rows = [''] * numRows
row = 0
increment = 1
for c in s:
rows[row] += c
row += increment
if (row == (numRows - 1)) or (row == 0):
increment *= -1
return ''.join(rows)
def convert2(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
rows = [[] for i in range(numRows)]
n = len(s)
for i in range(n):
j = i % (2 * numRows - 2)
if j < numRows:
rows[j].append(s[i])
else:
rows[2 * numRows - 2 - j].append(s[i])
sNew = [row[i] for row in rows for i in range(len(row))]
return ''.join(sNew)
# s = "PAYPALISHIRING"
s = "ABCDEFG"
numRows = 3
Solution().convert(s, numRows)
| true |
4decf52cae21f429395dbb079c3bada56f7bf326 | basu-sanjana1619/python_projects | /gender_predictor.py | 683 | 4.21875 | 4 | #It is a fun program which will tell a user whether she is having a girl or a boy.
test1 = input("Are you craving spicy food? (Y/N) :")
test2 = input("Are you craving sweets? (Y/N) :")
test3 = input("Are you suffering from extreme morning sickeness or hyperemesis (Y/N) :")
test4 = input("Is the baby's heart rate above 150 beats per minute? (Y/N) :")
if test1.upper() == "N" and test2.upper() == "N" and test3.upper() == "Y" and test4.upper() == "Y":
print("CONGRATS!..Its a GIRL!..YAYYY")
elif test1.upper() == "Y" and test2.upper() == "Y" and test3.upper() == "Y" and test4.upper() == "Y":
print("CONGRATS!..Its a GIRL!..YAYYY")
else:
print("CONGRATS!..Its a BOY!..YAYYY")
| true |
9d77a0ee4b5f9d90d48c67fcc19a686f6cb3b508 | cookcodeblog/python_work | /ch07/visit_poll.py | 543 | 4.125 | 4 | # 7-10 Visit Poll
visit_places = {}
poll_active = True
while poll_active:
name = input("What is your name? ")
place = input("If you could visit one place in the world, where would you go? ")
visit_places[name] = place # It is like map.put(key, value)
repeat = input("Would you like to let another person respond? (yes / no)")
if repeat.lower() == "no":
poll_active = False
print("\n---Poll Result---\n")
for name, place in visit_places.items():
print(name.title() + " likes to visie " + place.title() + ".")
| true |
bdeab6a046d4236f6dd006dd5c44bdcdf62bf029 | amigojapan/amigojapan.github.io | /8_basics_of_programming/fruits.py | 580 | 4.71875 | 5 | fruits=["banana","apple","peach","pear"] # create a list
print(fruits[0]) # print first element of list
print(fruits[3]) # print last element
print("now reprinting all fruits")
for fruit in fruits: # loops thru the fruits list and assigns each values to th>
print(fruit) # prints current "iteration" of the fruit
print("now reprinting all fruits in reverse")
fruits.reverse() # reverses the list
for fruit in fruits:
print(fruit)
print("now printing fruits in alphabetical order")
fruits.sort() # sorts the list in alphabetical order
for fruit in fruits:
print(fruit)
| true |
c087789647cad25fc983acd3bfceee19ab0a507f | Narfin/test_push | /controlFlows.py | 636 | 4.28125 | 4 | # if, elif, else
def pos_neg(n):
"""Prints whether int n is positive, negative, or zero."""
if n < 0:
print("Your number is Negative... But you already knew that.")
elif n > 0:
print("Your number is super positive! How nice.")
else:
print("Zero? Really? How boring.")
my_num = int(input("Enter a number: "))
pos_neg(my_num)
# for
def reverse_str(word):
"""Prints word in reverse"""
print(word[::-1], " lol") # [begin:end:step], in this case reversing word.
my_word = input("Enter a word to flip: ")
reverse_str(my_word)
# while
x = 8
while (x != 0):
print(x)
x -= 1
| true |
e80688442c643ed05976d0b872cffb33b1c3c054 | Minashi/COP2510 | /Chapter 5/howMuchInsurance.py | 301 | 4.15625 | 4 | insurance_Factor = 0.80
def insurance_Calculator(cost):
insuranceCost = cost * insurance_Factor
return insuranceCost
print("What is the replacement cost of the building?")
replacementCost = float(input())
print("Minimum amount of insurance to buy:", insurance_Calculator(replacementCost))
| true |
039b84d58b8410e1017b71395ac44082e19323ec | milolou/pyscript | /stripMethod.py | 1,756 | 4.65625 | 5 | # Strip function.
'''import re
print('You can strip some characters by strip method,\n
just put the characters you want to strip in the parenthese\n
followed function strip')
print('Please input the text you wanna strip.')
text = input()
print('Please use the strip function.')
def strip(string):
preWhiteSpace = re.compile(r'^\s+')
epiWhiteSpace = re.compile(r'\s+$')
specificPattern = re.compile(r'%s'%string)
if string == None:
textOne = preWhiteSpace.sub('',text)
textTwo = epiWhiteSpace.sub('',text)
print('The stripped text is:\n' + textTwo)
return textTwo
else:
textThree = specificPattern.sub('',text)
print('The stripped text is:\n' + textThree)
return textThree
# start the program.
functionCall = input()
n = len(functionCall)
if n > 7:
stripString = functionCall[6:(n-1)]
elif n == 7:
stripString = None
else:
print('The input is not valid.')
strip(stripString)'''
import re
# Another version.
def strip(text,characters):
preWhiteSpace = re.compile(r'^\s+')
epiWhiteSpace = re.compile(r'\s+$')
specificPattern = re.compile(r'%s'%characters)
if characters == None:
textOne = preWhiteSpace.sub('',text)
textTwo = epiWhiteSpace.sub('',text)
print('The stripped text is:\n' + textTwo)
return textTwo
else:
textThree = specificPattern.sub('',text)
print('The stripped text is:\n' + textThree)
return textThree
# start the program.
print('please use the strip function.')
functionCall = input()
n = len(functionCall)
coreString = functionCall[7:(n-2)]
variableList = coreString.split("','")
newText = variableList[0]
newCharacters = variableList[1]
strip(newText,newCharacters)
| true |
d00c5dd8c996aaed2784a30a925122bee2a4ac9d | rafaeljordaojardim/python- | /basics/exceptions.py | 1,891 | 4.25 | 4 | # try / Except / Else / Finally
for i in range(5):
try:
print(i / 0)
except ZeroDivisionError as e:
print(e, "---> division by 0 is not allowed")
for i in range(5):
try:
print(i / 0)
except NameError: # it doesn't handle ZeroDivisionError
print("---> division by 0 is not allowed")
for i in range(5):
try:
print(i / 1)
except ZeroDivisionError: # it doesn't handle ZeroDivisionError
print("---> division by 0 is not allowed")
except NameError:
print("---> division by 0 is not allowed")
except ValueError:
print("---> division by 0 is not allowed")
# if it doesn't raise any exception
try:
print(4 / 2)
except NameError: # it doesn't handle ZeroDivisionError
print("---> division by 0 is not allowed")
else:
print("if it doesn't raise any exception")
try:
print(4 / 2)
except NameError: # it doesn't handle ZeroDivisionError
print("---> division by 0 is not allowed")
finally:
print("it executes anyway if it raises error or not")
#Try / Except / Else / Finally - handling an exception when it occurs and telling Python to keep executing the rest of the lines of code in the program
try:
print(4/0) #in the "try" clause you insert the code that you think might generate an exception at some point
except ZeroDivisionError:
print("Division Error!") #specifying what exception types Python should expect as a consequence of running the code inside the "try" block and how to handle them
else:
print("No exceptions raised by the try block!") #executed if the code inside the "try" block raises NO exceptions
finally:
print("I don't care if an exception was raised or not!") #executed whether the code inside the "try" block raises an exception or not
#result of the above block
# Division Error!
# I don't care if an exception was raised or not!
| true |
7521cbf4b76c785fe8d0b78e837fba5cdf41cce1 | evanlihou/msu-cse231 | /clock.py | 1,436 | 4.4375 | 4 | """
A clock class.
"""
class Time():
"""
A class to represent time
"""
def __init__(self, __hour=0, __min=0, __sec=0):
"""Constructs the time class.
Keyword Arguments:
__hour {int} -- hours of the time (default: {0})
__min {int} -- minutes of the time (default: {0})
__sec {int} -- seconds of the time (default: {0})
"""
self.hour = __hour
self.min = __min
self.sec = __sec
def __repr__(self):
"""Creates the shell representation of a time with proper formatting
Returns:
string -- the representation of the time
"""
outstr = "Class Time: {:0>2d}:{:0>2d}:{:0>2d}"
return outstr.format(self.hour, self.min, self.sec)
def __str__(self):
"""Creates the string representation of a time with proper formatting
Returns:
string -- the representation of the time
"""
outstr = "{:0>2d}:{:0>2d}:{:0>2d}"
return outstr.format(self.hour, self.min, self.sec)
def from_str(self, time_str):
"""Updates the Time in place with a given str
Arguments:
time_str {str} -- Time to convert with format hh:mm:ss
"""
time_lst = time_str.split(":")
self.hour = int(time_lst[0])
self.min = int(time_lst[1])
self.sec = int(time_lst[2]) | true |
f5d77a708522b6febacc4c1e43704d1c63a2d07d | evanlihou/msu-cse231 | /proj01.py | 1,123 | 4.3125 | 4 | ###########################################################
# Project #1
#
# Algorithm
# Prompt for rods (float)
# Run conversions to other units
# Print those conversions
###########################################################
# Constants
ROD = 5.0292 # meters
FURLONG = 40 # rods
MILE = 1609.34 # meters
FOOT = 0.3048 # meters
WALKING_SPEED = 3.1 # miles per hour
# Take input and convert to float inline, then print
rods = float(input("Input rods: "))
print("You input", rods, "rods.\n")
# Run conversions, but don't round yet for accuracy
meters = rods * ROD
feet = meters / FOOT
miles = meters / MILE
furlongs = rods / FURLONG
walking_hours = miles / WALKING_SPEED
walking = walking_hours * 60 # Converts hours to minutes of walking
# Round all floats for prettier printing
meters = round(meters, 3)
feet = round(feet, 3)
miles = round(miles, 3)
furlongs = round(furlongs, 3)
walking = round(walking, 3)
# Print conversions
print("Conversions")
print("Meters:", meters)
print("Feet:", feet)
print("Miles:", miles)
print("Furlongs:", furlongs)
print("Minutes to walk", rods, "rods:", walking)
| true |
4fc1e7a055c830baa4ea154de82a4568a60b3bdf | alicevillar/python-lab-challenges | /conditionals/conditionals_exercise1.py | 1,058 | 4.46875 | 4 |
#######################################################################################################
# Conditionals - Lab Exercise 1
#
# Use the variable x as you write this program. x will represent a positive integer.
# Write a program that determines if x is between 0 and 25 or between 75 and 100.
# If yes, print the message:_ is between 0 and 25 or 75 and 100, where the blank would be the value of x.
# The program should do nothing if the value of x does not fit into either range.
#
#Expected Output
# If x is 8, then the output would be: 8 is between 0 and 25 or 75 and 100.
# If x is 80, then the output would be: 80 is between 0 and 25 or 75 and 100.
# If x is 50, then the output would be blank (your program does not print anything).
#######################################################################################################
x = 8
if x <= 25:
print(str(x) + " is between 0 and 25")
elif x > 75 and x < 100:
print(str(x) + " is between 75 and 100")
# Output => 8 is between 0 and 25
| true |
56870e9f3f322e09042d9e10312ed054fa033fa2 | rghosh96/projecteuler | /evenfib.py | 527 | 4.15625 | 4 |
#Define set of numbers to perform calculations on
userRange = input("Hello, how many numbers would you like to enter? ")
numbers = [0] * int(userRange)
#print(numbers)
numbers[0] = 0
numbers[1] = 1
x = numbers[0]
y = numbers[1]
i = 0
range = int(userRange)
#perform fibonacci, & use only even values; add sums
sum = 0
while x < int(userRange):
if x % 2 == 0:
#print (x, end=", ")
sum = sum + x
z = x + y
x = y
y = z
#i = i + 1
print("The total sum of the even-valued terms is:", sum)
| true |
3c21bd12834e39d8fd1c53bb5d9885c2cc75a360 | biniama/python-tutorial | /lesson6_empty_checks_and_logical_operators/logical_operators.py | 490 | 4.1875 | 4 | def main():
students = ["Kidu", "Hareg"]
name = input("What is your name? ")
if name not in students:
print("You are not a student")
else:
print("You are a student")
# if name in students:
# print("You are a student")
# else:
# print("You are not a student")
# Second example
value = False
if not value:
print("Value is false")
else:
print("Value is true")
if __name__ == '__main__':
main()
| true |
bac2a9c57de523788893acc83ddfb37a2e10ce0d | biniama/python-tutorial | /lesson2_comment_and_conditional_statements/conditional_if_example.py | 1,186 | 4.34375 | 4 | def main():
# Conditional Statements( if)
# Example:
# if kidu picks up her phone, then talk to her
# otherwise( else ) send her text message
# Can be written in Python as:
# if username is ‘kiduhareg’ and password is 123456, then go to home screen.
# else show error message
# Conditional statement example
# Assumption
# child is someone who is less than 10 years old
# young is someone who is between 10 - 30 years old
# adult is someone who is between 30 - 50 years old
# accepting input from the user
ageString = input('Please enter your age ')
age = int(ageString) # converts string to integer
if age < 10:
print('child')
elif age >= 10 and age < 30: # T and F = F, T and T = T
print('young')
elif age > 30 and age <= 50:
print('adult')
else:
print('old - sheba')
# another example with ‘if’ only
# TODO: Un comment it to execute
# if age < 10:
# print('child')
# if age >= 10 and age <= 30: # T and F = F, T and T = T
# print('young')
# if age > 30:
# print('adult')
if __name__ == "__main__":
main()
| true |
62ac86c00c6afcbb16dcc58a1a12bc426070001a | aiperi2021/pythonProject | /day_4/if_statement.py | 860 | 4.5 | 4 | # Using true vs false
is_Tuesday = True
is_Friday = True
is_Monday = False
is_Evening = True
is_Morning = False
if is_Monday:
print("I have python class")
else:
print("I dont have python class")
# try multiple condition
if is_Friday or is_Monday:
print("I have python class")
else:
print("I dont have python class")
if is_Friday and is_Evening:
print("I have python class")
else:
print("I dont have python class")
if is_Friday and is_Morning:
print("I have python class")
else:
print("I dont have python class")
if is_Friday and not is_Morning:
print("I have python class")
else:
print("I dont have python class")
if is_Friday and is_Morning:
print("I dont have python class")
elif is_Monday and is_Evening:
print("I have python class")
else:
print("I dont have python class in any of this time ")
| true |
f6c60e2110d21c44f230ec710f3b74631b772195 | aiperi2021/pythonProject | /day_7/dictionar.py | 298 | 4.3125 | 4 | # Mapping type
## Can build up a dict by starting with the the empty dict {}
## and storing key/value pairs into the dict like this:
## dict[key] = value-for-that-key
#create dict
dict = {}
dict['a'] = 'alpha'
dict['g'] = 'gamma'
dict['o'] = 'omega'
for key in dict:
print(key, '->', dict[key]) | true |
00e3304a1b6216c18d5cd8fc9ea5c266ed72149e | Vaspe/Coursera_Python_3_Programming_Michigan | /Python_Project_pillow_tesseract_and_opencv_Mod5/Week2_Tesseract/ipywidgets_stuff.py | 2,172 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 30 19:49:51 2020
@author: Vasilis
"""
# In this brief lecture I want to introduce you to one of the more advanced features of the
# Jupyter notebook development environment called widgets. Sometimes you want
# to interact with a function you have created and call it multiple times with different
# parameters. For instance, if we wanted to draw a red box around a portion of an
# image to try and fine tune the crop location. Widgets are one way to do this quickly
# in the browser without having to learn how to write a large desktop application.
#
# Lets check it out. First we want to import the Image and ImageDraw classes from the
# PILLOW package
from PIL import Image, ImageDraw
# Then we want to import the interact class from the widgets package
from ipywidgets import interact
# We will use interact to annotate a function. Lets bring in an image that we know we
# are interested in, like the storefront image from a previous lecture
image=Image.open('readonly/storefront.png')
# Ok, our setup is done. Now we're going to use the interact decorator to indicate
# that we want to wrap the python function. We do this using the @ sign. This will
# take a set of parameters which are identical to the function to be called. Then Jupyter
# will draw some sliders on the screen to let us manipulate these values. Decorators,
# which is what the @ sign is describing, are standard python statements and just a
# short hand for functions which wrap other functions. They are a bit advanced though, so
# we haven't talked about them in this course, and you might just have to have some faith
@interact(left=100, top=100, right=200, bottom=200)
# Now we just write the function we had before
def draw_border(left, top, right, bottom):
img=image.copy()
drawing_object=ImageDraw.Draw(img)
drawing_object.rectangle((left,top,right,bottom), fill = None, outline ='red')
display(img)
# Jupyter widgets is certainly advanced territory, but if you would like
# to explore more you can read about what is available here:
# https://ipywidgets.readthedocs.io/en/stable/examples/Using%20Interact.html | true |
0229eae841f5fec0563ad643a508650a3b1b235c | nadiiia/cs-python | /extracting data with regex.py | 863 | 4.15625 | 4 | #Finding Numbers in a Haystack
#In this assignment you will read through and parse a file with text and numbers.
#You will extract all the numbers in the file and compute the sum of the numbers.
#Data Format
#The file contains much of the text from the introduction of the textbook except that random numbers are inserted throughout the text.
#Handling The Data
#The basic outline of this problem is to read the file, look for integers using the re.findall(), looking for a regular expression of '[0-9]+' and then converting the extracted strings to integers and summing up the integers.
import re
name = raw_input("Enter file:")
if len(name) < 1 : name = "regex_sum_212308.txt"
handle = open(name)
sum=0
for line in handle:
stuff=re.findall('[0-9]+',line) #list of strings
for str in stuff:
num=int(str)
sum=sum+num
print 'Summ', sum | true |
59bb55684bffde3abd337b0617af2117a9e4abb4 | jinwei15/java-PythonSyntax-Leetcode | /LeetCode/src/FindAllAnagramsinaString.py | 2,464 | 4.1875 | 4 | # 438. Find All Anagrams in a String
# Easy
# 1221
# 90
# Favorite
# Share
# Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
# Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
# The order of output does not matter.
# Example 1:
# Input:
# s: "cbaebabacd" p: "abc"
# Output:
# [0, 6]
# Explanation:
# The substring with start index = 0 is "cba", which is an anagram of "abc".
# The substring with start index = 6 is "bac", which is an anagram of "abc".
# Example 2:
# Input:
# s: "abab" p: "ab"
# Output:
# [0, 1, 2]
# Explanation:
# The substring with start index = 0 is "ab", which is an anagram of "ab".
# The substring with start index = 1 is "ba", which is an anagram of "ab".
# The substring with start index = 2 is "ab", which is an anagram of "ab".
# Accepted
# 94,870
# Submissions
# 268,450
# my first idea is that to remain a hashtable window and keep looping the the long string form 0 to len(long string) - len(short string)
class Solution:
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
block = dict()
winBlock = dict()
returnList = list()
for ch in p:
block[ch] = block.get(ch, 0) + 1
for i in range(0, len(s)):
if i - len(p) >= 0:
occur = winBlock.get(s[i - len(p)]) - 1
if occur == 0:
del winBlock[s[i - len(p)]]
else:
winBlock[s[i - len(p)]] = occur
winBlock[s[i]] = winBlock.get(s[i], 0) + 1
# print(winBlock)
# print(i+1-len(p))
if winBlock == block:
returnList.append(i + 1 - len(p))
return returnList
# def findAnagrams(self, s, p):
# """
# :type s: str
# :type p: str
# :rtype: List[int]
# """
# block = dict()
# returnList = list()
# for ch in p:
# block[ch] = block.get(ch,0)+1
# for i in range(0,len(s)-len(p) + 1):
# winBlock = dict() # window of length len(p)
# for ch in s[i:i+len(p)]:
# winBlock[ch] = winBlock.get(ch,0)+1
# if winBlock == block:
# returnList.append(i)
# return returnList
| true |
795cbf40f98ad3a775af177e11913ce831752854 | MenacingManatee/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 504 | 4.21875 | 4 | #!/usr/bin/python3
'''Prints a string, adding two newlines after each of the following:
'.', '?', and ':'
Text must be a string'''
def text_indentation(text):
'''Usage: text_indentation(text)'''
if not isinstance(text, str):
raise TypeError('text must be a string')
flag = 0
for char in text:
if flag is 1 and char is ' ':
continue
print(char, end="")
flag = 0
if char in ['.', ':', '?']:
print('\n')
flag = 1
| true |
d5d557f24d2e74375e95cf22f7df5d2ed5587e8c | MenacingManatee/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 321 | 4.3125 | 4 | #!/usr/bin/python3
'''Defines a function that appends a string to a text file (UTF8)
and returns the number of characters written:'''
def append_write(filename="", text=""):
'''Usage: append_write(filename="", text="")'''
with open(filename, "a") as f:
f.write(text)
f.close()
return len(text)
| true |
d91f8e862b939ab0131fab2bf97c96681fba005a | MenacingManatee/holbertonschool-higher_level_programming | /0x0B-python-input_output/100-append_after.py | 595 | 4.1875 | 4 | #!/usr/bin/python3
'''Defines a function that inserts a line of text to a file,
after each line containing a specific string'''
def append_after(filename="", search_string="", new_string=""):
'''Usage: append_after(filename="", search_string="", new_string="")'''
with open(filename, "r") as f:
res = []
s = f.readline()
while (s != ""):
res.append(s)
if search_string in s:
res.append(new_string)
s = f.readline()
f.close()
with open(filename, "w") as f:
f.write("".join(res))
f.close()
| true |
faefe53c66424e822ce06109fc4d095f013e64c0 | MenacingManatee/holbertonschool-higher_level_programming | /0x06-python-classes/102-square.py | 1,442 | 4.40625 | 4 | #!/usr/bin/python3
'''Square class'''
class Square:
'''Defines a square class with logical operators available based on area,
as well as size and area'''
__size = 0
def area(self):
'''area getter'''
return (self.__size ** 2)
def __init__(self, size=0):
'''Initializes size'''
self.__size = size
@property
def size(self):
'''size getter'''
return (self.__size)
@size.setter
def size(self, value):
'''size setter'''
if (type(value) is int):
if (value >= 0):
self.__size = value
else:
raise ValueError('size must be >= 0')
else:
raise TypeError('size must be an integer')
def __eq__(self, other):
'''Sets __eq__ to check area'''
return (self.area() == other.area())
def __lt__(self, other):
'''Sets __lt__ to check area'''
return (self.area() < other.area())
def __gt__(self, other):
'''Sets __gt__ to check area'''
return (self.area() > other.area())
def __ne__(self, other):
'''Sets __ne__ to check area'''
return (not (self.area() == other.area()))
def __le__(self, other):
'''Sets __le__ to check area'''
return (self.area() <= other.area())
def __ge__(self, other):
'''Sets __ge__ to check area'''
return (self.area() >= other.area())
| true |
61a293256dff4c87004e8627f0afadd9a9d202ca | shea7073/More_Algorithm_Practice | /2stack_queue.py | 1,658 | 4.15625 | 4 | # Create queue using 2 stacks
class Stack(object):
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def size(self):
return len(self.items)
def pop(self):
return self.items.pop()
def push(self, item):
self.items.append(item)
# Works only if entire set is passed during enqueue before any dequeueing
class Queue2Stacks(object):
def __init__(self):
self.stack1 = Stack()
self.stack2 = Stack()
def enqueue(self, element):
for item in element:
self.stack1.push(item)
while not self.stack1.isEmpty():
current = self.stack1.pop()
self.stack2.push(current)
return self.stack2
def dequeue(self):
return self.stack2.pop()
# Works better if enqueueing is happening randomly
# instead of all at once at the beginning
class Queue2Stacks2(object):
def __init__(self):
self.stack1 = Stack()
self.stack2 = Stack()
def enqueue(self, element):
self.stack1.push(element)
def dequeue(self):
while not self.stack1.isEmpty():
current = self.stack1.pop()
self.stack2.push(current)
answer = self.stack2.pop()
while not self.stack2.isEmpty():
current = self.stack2.pop()
self.stack1.push(current)
return answer
queue = Queue2Stacks2()
queue.enqueue(1)
queue.enqueue(2)
print(queue.dequeue())
queue.enqueue(5)
queue.enqueue(6)
print(queue.dequeue())
print(queue.dequeue())
print(queue.dequeue()) | true |
29436d6802295d6eb8992d2f510427219d29f35b | Mark9Mbugua/Genesis | /chatapp/server.py | 1,892 | 4.125 | 4 | import socket #helps us do stuff related to networking
import sys
import time
#end of imports ###
#initialization section
s = socket.socket()
host = socket.gethostname() #gets the local hostname of the device
print("Server will start on host:", host) #gets the name of my desktop/host of the whole connection(when I run the program)
port = 8080 #make sure the port is on my local host(my computer)
s.bind((host,port)) #binds the socket with the host and the port
print("")
print("Server done binding to host and port successfully")
print("")
print("Server is waiting for incoming connections")
print("")
#we can now start listening to incoming connections
s.listen(1) #we accept only one connection
conn,addr = s.accept()
print("")
#conn is assigned to the socket itself which is the physical socket (s?) coming from the client
#addr is assigned to the IP address of the client that we'll be connecting
print(addr, "Has connected to the server and is now online...") #prints the IP Address/Hostname of the client that is connected to us
print("")
#now move on to the client side.
#we're back!
while 1:
message = input(str(">>"))#for a decoded message
message = message.encode()#to change this message into bytes since s/w interface only supports bytes
conn.send(message)#conn is the client that is connected to us
print("message has been sent..")
print("")
#piece of code that will accept the message and display it
incoming_message = conn.recv(1024) #when you type a message and press enter, it is going to be stored here.
#we need to decode the message since we had encoded it
incoming_message = incoming_message.decode()
print("Server: ", incoming_message)
print("")
#so far we have a one-sided chat
#we need to therefore put it in a loop
| true |
80192a8c2357a805072936ccb99b9dabc8e27778 | GANESH0080/Python-WorkPlace | /ReadFilePractice/ReadDataOne.py | 291 | 4.25 | 4 | # Created an File
file = open("ReadFile.txt" ,"w+")
# Enter string into the file and stored into variable
file.write("Ganesh Salunkhe")
# Open the for for reading
file = open("ReadFile.txt" ,"r")
# Reading the file and store file date into variable
re= file.read()
# Printing file data
print(re)
| true |
de3cf5eec6681b391cddf58e4f48676b8e84e727 | KapsonLabs/CorePythonPlayGround | /Decorators/instances_as_decorators.py | 660 | 4.28125 | 4 | """
1. Python calls an instance's __call__()
when it's used as a decorator
2. __call__()'s return value is used as the
new function
3. Creates groups of callables that you can
dynamically control as a group
"""
class Trace:
def __init__(self):
self.enabled = True
def __call__(self, f):
def wrap(*args, **kwargs):
if self.enabled:
print('Calling {}'.format(f))
return f(*args, **kwargs)
return wrap
tracer = Trace()
@tracer
def rotate_list(l):
return l[1:] + [l[0]]
l = [1,2,3]
t = rotate_list(l)
print(t)
#disable the tracer
tracer.enabled = False
t = rotate_list(l)
print(t) | true |
ee9cf22dae8560c6ee899431805231a107b8f0e6 | smalbec/CSE115 | /conditionals.py | 1,110 | 4.4375 | 4 | # a and b is true if both a is true and b is true. Otherwise, it is false.
# a or b is true if either a is true or b is true. Otherwise, it is false.
#
# if morning and workday:
# wakeup()
#
# elif is when you need another conditional inside an if statement
def higher_lower(x):
if x<24:
return("higher")
elif x>24:
return("lower")
else:
return("correct u dumb")
print(higher_lower(24))
def categorize(x):
if x<20:
return("low")
elif x>=20 and x<36:
return("medium")
else:
return("high")
#or the more optimal one
def categorize2(x):
if x<15:
return("low")
elif 15<=x<=24:
return("medium")
else:
return("high")
print(categorize2(60))
def categorizelen(x):
if len(x)<5:
return("short")
elif 5<=len(x)<=14:
return("medium")
else:
return("long")
def compute_xp(x,y):
if y==False:
return(92884)
else:
return(92884 + x)
def replacement(x):
x = x.replace("a", "j")
return(x)
print(replacement("alalala")) | true |
4c403bd4174b1b71461812f9926e6dac87df2610 | JasmanPall/Python-Projects | /lrgest of 3.py | 376 | 4.46875 | 4 | # This program finds the largest of 3 numbers
num1 = float(input(" ENTER NUMBER 1: "))
num2 = float(input(" ENTER NUMBER 2: "))
num3 = float(input(" ENTER NUMBER 3: "))
if num1>num2 and num1>num3:
print(" NUMBER 1 is the greatest")
elif num2>num1 and num2>num3:
print(" NUMBER 2 is the greatest")
else:
print(" NUMBER 3 is the greatest")
| true |
c8b69c1728f104b4f308647cc72791e49d84e472 | JasmanPall/Python-Projects | /factors.py | 370 | 4.21875 | 4 | # This program prints the factors of user input number
num = int(input(" ENTER NUMBER: "))
print(" The factors of",num,"are: ")
def factors(num):
if num == 0:
print(" Zero has no factors")
else:
for loop in range(1,num+1):
if num % loop == 0:
factor = loop
print(factor)
factors(num) | true |
9718066d59cdbd0df8e277d5256fd4d7bb10d90c | JasmanPall/Python-Projects | /Swap variables.py | 290 | 4.25 | 4 | # This program swaps values of variables.
a=0
b=1
a=int(input("Enter a: "))
print(" Value of a is: ",a)
b=int(input("Enter b: "))
print(" Value of b is: ",b)
# Swap variable without temp variable
a,b=b,a
print(" \n Now Value of a is:",a)
print(" and Now Value of b is:",b) | true |
87dfe7f1d78920760c7e1b7131f1dd941e284e5a | JasmanPall/Python-Projects | /odd even + - 0.py | 557 | 4.375 | 4 | # This program checks whether number is positive or negative or zero
number=float(input(" Enter the variable u wanna check: "))
if number < 0:
print("THIS IS A NEGATIVE NUMBER")
elif number == 0:
print(" THE NUMBER IS ZERO")
else:
print(" THIS IS A POSITIVE NUMBER")
if number%2 == 0:
print("The number %i is even number" %number)
else:
print("The Number %i is odd" % number)
#loop=float(input(" DO U WISH TO CONTINUE: "))
#if loop == "Y" or "y":
#elif loop == "N" or "n":
# break: | true |
17739c9ef743a4eea06fc2de43261bfc72c21678 | elijahwigmore/professional-workshop-project-include | /python/session-2/stringfunct.py | 1,612 | 4.21875 | 4 | string = "Hello World!"
#can extract individual characters using dereferencing (string[index])
#prints "H"
print string[0]
#prints "e"
print string[1]
#print string[2]
#Slicing
#of form foo[num1:num2] - extract all elements from and including num1, up to num2 (but not including element at num2)
#all of the below prints World
print string[-6:-1]
print string[6:-1]
print string[6:11]
#print everything before the space: prints Hello
print string[:5]
#print everything after the space: World!
print string[6:]
sentence = "I am a teapot!"
print sentence.split(" ")
#***LISTS***
myList = ["a word", 3, 3, 4.6, "end"]
print myList
print myList[0]
print myList[1:]
print myList + [5, 4, 5, 67]
myList.append([1, 2, 3, 4])
print myList
myList.remove('end')
print myList
print len(myList)
myList[1] = 'one'
print myList
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in nums:
if ((i % 2) == 1):
nums.remove(i)
print nums
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in nums:
if ((i % 2) == 1):
nums = nums[0:i-1] + nums[i+1:]
print nums
#***DICTIONARIES***
myDict = {'one':1, 'two':2, 'three':3, 'four':4}
print myDict['two']
myDict['five'] = 5
print myDict
for i in myDict:
print myDict[i]
months = {'jan':1, 'feb':2, 'mar':3, 'apr':4, 'may':5, 'jun':6, 'jul':7, 'aug':8, 'sep':9, 'oct':10, 'nov':11, 'dec':12}
print ('apr' in months)
#PRACTICE:
#Input: "A man a plan a canal Panama" -> {'A':1, 'a':2, 'man':1, 'plan':1, 'Panama':1, 'canal':1}
| true |
50a3e1da1482569c0831227e0e4b5ead75433d43 | PatrickKalkman/pirplepython | /homework01/main.py | 1,872 | 4.59375 | 5 | """
Python Is Easy course @Pirple.com
Homework Assignment #1: Variables
Patrick Kalkman / patrick@simpletechture.nl
Details:
What's your favorite song?
Think of all the attributes that you could use to describe that song. That is:
all of it's details or "meta-data". These are attributes like "Artist",
"Year Released", "Genre", "Duration", etc. Think of as many different
characteristics as you can. In your text editor, create an empty file and name
it main.py.
Now, within that file, list all of the attributes of the song, one after
another, by creating variables for each attribute, and giving each variable
a value.
"""
# Favorite Song: Tennessee Whiskey by Chris Stapleton
Artist = "Chris Stapleton"
ArtistGender = "Male"
Title = "Tenessee Whiskey"
Album = "Traveller"
NumberOfSongsOnAlbum = 14
Year = 2015
Genre = "Country"
DurationInSeconds = 293
OriginalAutor = "David Allan Coe"
Country = "United States"
TimesPlayedOnSpotify = 287881875
PriceInDollars = 2.75
Bio = "Christopher Alvin Stapleton is an American singer-songwriter, " + \
"guitarist, and record producer.x He was born in Lexington, Kentucky," + \
" and grew up in Staffordsville, Kentucky, until moving to Nashville, " + \
"Tennessee, in 2001 to pursue a career in music writing songs. " + \
" Subsequently, Stapleton signed a contract with Sea Gayle Music to " + \
"write and publish his music."
WikipediaLink = "https://en.wikipedia.org/wiki/Chris_Stapleton"
print(f"Title: {Title}")
print(f"Artist: {Artist}")
print(f"Gender: {ArtistGender}")
print(f"Album: {Album}")
print(f"Number of songs on album: {NumberOfSongsOnAlbum}")
print(f"Year: {Year}")
print(f"Genre: {Genre}")
print(f"Country: {Country}")
print(f"Duration: {DurationInSeconds} s")
print(f"Original autor: {OriginalAutor}")
print(f"Number of plays on Spotify: {TimesPlayedOnSpotify}")
print(f"Price: ${PriceInDollars}")
print(f"Bio: {Bio}")
print(f"Wikipedia link: {WikipediaLink}")
| true |
b884cc6e8e590ef59a9c3d69cad3b5d574368916 | Ardrake/PlayingWithPython | /string_revisited.py | 1,674 | 4.21875 | 4 | str1 = 'this is a sample string.'
print('original string>>', str1,'\n\n')
print('atfer usig capitalising>>',str1.capitalize())
#this prints two instances of 'is' because is in this as well
print('using count method for "is" in the given string>>', str1.count('is'))
print('\n\n')
print('looking fo specfic string literal with spaces>>', str1.count(' is '),'\n')
print('using find method for "amp" in the string>>', str1.find('amp'),'\n')
print('checkin if sring.isupper()>>',str1.isupper(),'\n')
print(bin(255)) #prints in binary
stru = str1.upper()
print('making string upper case>>',stru,'\n\n')
print('now testing new string.isupper()>>', stru.isupper(),'\n\n')
print(str1.upper().isupper())
print('lower string "',stru.lower(),'"')
print('\n\nTitle method', str1.title())
##working with spaces in the string
str2 = ' five taps of the SPACEBAR '
print('\n\n',str2)
print('using s.lstrip() to remove all the whitespaces from the left\n\
', str2.lstrip(),'\n')
print('now on the right\n', str2.rstrip(),'next letter \n')
print('this is about removing whitespaces from both sides\n',str2.strip())
# replacing text in a string
print(str1.replace('sample', 'testing')) #replaces the first instance in the string
#splitting string into a list
str3 = str1.split(' ')
print(str3)
#joining it back together
str4 = ' '.join(str3) #because lists don't have join() method quoted string is necessary
print(str4)
##formatting a string
## there are two ways to do that
s = '%s is %d years old' % ('Harry', 29) #old c style still supported by python3
print(s)
t= '{0} is {1} years old and can pass {2} string data'.format('Harry', 29, 'third')
print(t)
| true |
93f34502472cddeb27d9d3404fb0f4f5269bb920 | ladipoore/PythonClass | /hass4.py | 1,239 | 4.34375 | 4 | """ I won the grant for being the most awesome. This is how my reward is calculated.
My earnings start at $1 and can be doubled or tripled every month.
Doubling the amount can be applied every month and tripling the amount can be applied every other month.
Write a program to maximize payments given the number of months by user. """
#Introducing the program
Welcome = "Congratulations!"
Welcome2 = "If you are using this program, that means you won the You-Are-Awesome award!"
print (100*"*")
print(format(Welcome,'^100s'))
print(format(Welcome2,'^100s'))
print (100*"*")
print("\n")
print("I am sure you are dying to know how much you won, let's compute!")
print("\n")
#Calculating and printing out the results.
amount = 1
months = int(input("For how many months did they say you will receive payments? "))
print("\n")
print("Here are the monthly installment amounts:")
print("\n")
for strategy in range(1,months+1,1):
if strategy == 1:
payment = "$"+str(amount)
print("Month ",strategy, ":", payment.rjust(50))
elif strategy %2 == 0:
amount *= 2
payment = "$"+str(amount)
print("Month ",strategy, ":", payment.rjust(50))
else:
amount *= 3
payment = "$"+str(amount)
print("Month ",strategy, ":", payment.rjust(50))
| true |
aaf077c666e7c6d687e953d9b3e7d35596e7f430 | dxab/SOWP | /ex2_9.py | 427 | 4.5 | 4 | #Write a program that converts Celsius temperatures to Fahrenheit temp.
#The formula is as follows: f = 9 / 5 * C + 32
#This program should ask the user to enter a temp in Celsius and then
#display the temp converted to Fahrenheit
celsius = float(input('Please enter todays temperature (in celsius): '))
fahr = 9 / 5 * celsius + 32
print("Today's temperature in degrees fahrenheit is", format(fahr, '.0f'), 'degrees.')
| true |
fe0ed51cf0cdab74d7d87b9f8317e18776d0c27d | ostanleigh/csvSwissArmyTools | /dynamicDictionariesFromCSV.py | 2,363 | 4.25 | 4 | import csv
import json
from os import path
print("This script is designed to create a list of dictionaries from a CSV File.")
print("This script assumes you can meet the following requirements to run:")
print(" 1) The file you are working with has clearly defined headers.")
print(" 2) You can review the headers ('.head') ")
print(" 3) You wish to leverage the headers as keys, create a dict per row, and use the row values as Dict vals.")
while True:
userFileVal = input("\n Dynamic Dictionaries from CSV file,"
"\n \n What is the name of the csv file you would like to work with? (Don't enter the file extension.): ")
try:
filename = path.exists(userFileVal+'.csv')
except FileNotFoundError:
print("Wrong file or file path")
else:
break
#filename = input("What is the name of the csv file you would like to work with? (Don't enter the file extension.) ? ")
userEvalIn = input("Do you want to remove any columns or characters from the left of the header? Y or N?: ")
userEval = str.lower(userEvalIn)
if userEval == 'y':
startIndex = int(input("How many fields should be trimmed from left margin? Enter an integer: "))
# If file corruption introduces characters, or redundant file based index is in place
# Can add lines to support further indexing / slicing as needed
else:
startIndex = 0
outFileName = input("What do you want to name your output file? Please enter a valid csv file name: ")
with open (userFileVal+'.csv', 'r') as csvInputFile:
filereader = csv.reader(csvInputFile)
headerRaw = next(filereader)
header = headerRaw
header = headerRaw[startIndex:]
print(f"header is: {header}")
with open (outFileName+'.json','w',newline='') as jsonOutputFile:
filereader = csv.reader(csvInputFile)
outDicts = [ ]
for line in filereader:
keyValsRaw = next(filereader)
keyVals = keyValsRaw[ startIndex: ]
# If file corruption introduces characters, or redundant index is in place
# keyVals = keyValsRaw[1:]
# use further indexing / slicing as needed
headerKeys = dict.fromkeys(header)
zipObj = zip(headerKeys, keyVals)
dictObj = dict(zipObj)
outDicts.append(dictObj)
filewriter = json.dump(outDicts,jsonOutputFile)
print("Close")
| true |
89ec0897f99163edb014c185425b3054332f6dbe | RamyaRaj14/assignment5 | /max1.py | 258 | 4.25 | 4 | #function to find max of 2 numbers
def maximum(num1, num2):
if num1 >= num2:
return num1
else:
return num2
n1 = int(input("Enter the number:"))
n2 = int(input("Enter the number:"))
print(maximum(n1,n2)) | true |
f8ec2566b82d611fe6e8ae0ecff036978de9a002 | ayaabdraboh/python | /lap1/shapearea.py | 454 | 4.125 | 4 | def calculate(a,c,b=0):
if c=='t':
area=0.5*a*b
elif c=='c':
area=3.14*a*a
elif c=='s':
area=a*a
elif c=='r':
area=a*b
return area
if __name__ == '__main__':
print("if you want to calculate area of shape input char from below")
c = input("enter char between t,s,c,r : ")
a=int(input("enter num1"))
b=int(input("enter num2"))
print(calculate(a,c,b))
| true |
ef3f6373867dbacee7aae3af141d9fcd1edbd311 | PabloG6/COMSCI00 | /Lab4/get_next_date_extra_credit.py | 884 | 4.28125 | 4 | from datetime import datetime
from datetime import timedelta
'''the formatting on the lab is off GetNextDate(day, month, year, num_days_forward)
would not return 9/17/2016 if GetNextDate(2, 28, 2004) is passed because
28 is not a month.
'''
def GetNextDate(day, month, year, num_days_forward):
num_days_forward = int(num_days_forward) if (type(num_days_forward) == str) else num_days_forward
day = str(day).zfill(2)
month = str(month).zfill(2)
year = str(year).zfill(2)
date = '{0}/{1}/{2}'.format(day, month, year)
new_date = datetime.strptime(date, '%d/%m/%Y')
new_date += timedelta(days=num_days_forward)
new_date = new_date.strftime('%m/%d/%Y')
return new_date
print(GetNextDate(input("Please enter the day: "), input("Please enter the month: "),
input("Please enter the year: "), input("Enter number of days forward: ")))
| true |
af817ff14fbc1b00968c49da3f427ddb3d75622d | PabloG6/COMSCI00 | /Lab2/moon_earths_moon.py | 279 | 4.125 | 4 | first_name = input("What is your first name?")
last_name = input("What is your last name?")
weight = int(input("What is your weight?"))
moon_gravity= 0.17
moon_weight = weight*moon_gravity
print("My name is", first_name, last_name+".", "And I weigh", moon_weight, "on the moon") | true |
683ce144348dbb8d1f15f38ada690d70e9b1a22f | joeschweitzer/board-game-buddy | /src/python/bgb/move/move.py | 827 | 4.3125 | 4 |
class Move:
"""A single move in a game
Attributes:
player -- Player making the move
piece -- Piece being moved
space -- Space to which piece is being moved
"""
def __init__(self, player, piece, space):
self.player = player
self.piece = piece
self.space = space
class MoveHistory:
"""Records a move that was made
Attributes:
move -- Move that was made
time -- Time move was made
"""
def __init__(self, move, time):
self.move = move
self.time = time
class InvalidMoveError(Exception):
"""Error thrown for invalid move
Attributes:
value -- Error string
"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value) | true |
2b0293a0bd0452e9e94a7c6aea0d13a803cc9dbd | Demesaikiran/MyCaptainAI | /Fibonacci.py | 480 | 4.21875 | 4 | def fibonacci(r, a, b):
if r == 0:
return
else:
print("{0} {1}".format(a, b), end = ' ')
r -= 1
fibonacci(r, a+b, a+ 2*b)
return
if __name__ == "__main__":
num = int(input("Enter the number of fibonacci series you want: "))
if num == 0 or num < 0:
print("Incorrect choice")
elif num == 1:
print("0")
else:
fibonacci(num//2, 0, 1)
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.