blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
3ac26042891246dead71c85f0fd59f5f7316a516 | akhilpgvr/HackerRank | /iterative_factorial.py | 408 | 4.25 | 4 | '''
Write a iterative Python function to print the factorial of a number n (ie, returns n!).
'''
usersnumber = int(input("Enter the number: "))
def fact(number):
result = 1
for i in range(1,usersnumber+1):
result *= i
return result
if usersnumber == 0:
print('1')
elif usersnumber < 0:
print('Sorry factorial exists only for positive integers')
else:
print(fact(usersnumber))
| true |
a412e958ac2c18dd757f6b5a3e91fd897eda6658 | akhilpgvr/HackerRank | /fuzzbuzz.py | 435 | 4.1875 | 4 | '''
Write a Python program to print numbers from 1 to 100 except for multiples of 3
for which you should print "fuzz" instead, for multiples of 5 you should print
'buzz' instead and for multiples of both 3 and 5, you should print 'fuzzbuzz' instead.
'''
for i in xrange(1,101):
if i % 15 == 0:
print 'fuzzbuzz'
elif i % 3 == 0:
print 'fuzz'
elif i % 5 == 0:
print 'buzz'
else:
print i
| true |
0cacf9f1b270d2814847c7d4091de5592bc47bad | SherriChuah/google-code-sample | /python/src/playlists.py | 1,501 | 4.1875 | 4 | """A playlists class."""
"""Keeps the individual video playlist"""
from .video_playlist import VideoPlaylist
class Playlists:
"""A class used to represent a Playlists containing video playlists"""
def __init__(self):
self._playlist = {}
def number_of_playlists(self):
return len(self._playlist)
def get_all_playlists(self):
"""Returns all available playlist information from the playlist library."""
return list(self._playlist.values())
def get_playlist(self, playlist_name):
"""Returns the videoplaylist object (name, content) from the playlists.
Args:
playlist_name: Name of playlist
Returns:
The VideoPlaylist object for the requested playlist_name. None if the playlist does not exist.
"""
for i in self._playlist:
if i.lower() == playlist_name.lower():
return self._playlist[i]
def add_playlist(self, playlist: VideoPlaylist):
"""Adds a playlist into the dic of playlists
Args:
playlist: VideoPlaylist object
"""
lower = [i.lower() for i in self._playlist.keys()]
if playlist.name.lower() in lower:
return False
else:
self._playlist[playlist.name] = playlist
return True
def remove_playlist(self, name):
"""Remove a playlist from the dic of playlists
Args:
name: name of playlist
"""
lower = [i.lower() for i in self._playlist.keys()]
if name.lower() in lower:
self._playlist.pop(self.get_playlist(name).name)
return True
else:
return False
| true |
861ada8af86a6060dfc173d19e0364e2132a447e | DataActivator/Python3tutorials | /Decisioncontrol-Loop/whileloop.py | 944 | 4.21875 | 4 | '''
A while loop implements the repeated execution of code based on a given Boolean condition.
while [a condition is True]:
[do something]
As opposed to for loops that execute a certain number of times, while loops are conditionally based
so you don’t need to know how many times to repeat the code going in.
'''
# Q1:- run the program until user don't give correct captain name
captain = ''
while captain != 'Virat':
captain = input('Who is the captain of indian Team :- ')
print('Yes, The captain of india is ' + captain)
print('Yes, the captain of india is {} ' .format(captain))
print(f'Yes, The captain of India is {captain.upper()}')
# break & continue example in while loop
i = 0
while i<5:
print(i)
if i == 3:
break
i += 1
# else block in for & while loop
i = 0
while i<5:
print(i)
# if i == 3:
# break
i += 1
else :
print('After while loop ')
print('Data Activator')
| true |
7646890051144b6315cd22fd1b5e04a44d9b266a | jabedude/python-class | /projects/week3/jabraham_guessing.py | 1,625 | 4.1875 | 4 | #!/usr/bin/env python3
'''
This program is an implementation of the "High-Low Guessing Game".
The user is prompted to guess a number from 1 to 100 and the
program will tell the user if the number is greater, lesser, or
equal to the correct number.
'''
from random import randint
def main():
'''
This function is the entry point of the program and handles user
interaction with the game.
'''
# CONSTANTS #
ANSWER = randint(1, 100)
BANNER = '''Hello. I'm thinking of a number from 1 to 100...
Try to guess my number!'''
PROMPT = "Guess> "
# MESSAGES #
err_msg = "{} is an invalid choice. Please enter a number from 1 to 100."
suc_msg = "{} was correct! You guessed the number in {} guess{}."
wrong_msg = "{} is too {}!"
print(BANNER)
valid_guesses = 0
while True:
user_input = input(PROMPT)
valid_guesses += 1
try:
user_input = int(user_input)
if user_input not in range(1, 101):
raise ValueError
elif user_input == ANSWER:
guess_ending = "es"
if valid_guesses == 1:
guess_ending = ""
print(suc_msg.format(user_input, valid_guesses, guess_ending))
exit(0)
else:
guess_clue = "high"
if user_input < ANSWER:
guess_clue = "low"
print(wrong_msg.format(user_input, guess_clue))
except ValueError:
valid_guesses -= 1
print(err_msg.format(user_input))
if __name__ == "__main__":
main()
| true |
fcdebbb78ba2d4c5b41967801b0d537c35e85c3a | jabedude/python-class | /chapter5/ex6.py | 384 | 4.125 | 4 | #!/usr/bin/env python3
def common_elements(list_one, list_two):
''' returns a list of common elements between list_one and list_two '''
set_one = set(list_one)
set_two = set(list_two)
return list(set_one.intersection(set_two))
test_list = ['a', 'b', 'c', 'd', 'e']
test_list2 = ['c', 'd', 'e', 'f', 'g']
test = common_elements(test_list, test_list2)
print(test)
| true |
53c1ca380af737aabe9ce0e265b18011a3e290a2 | jabedude/python-class | /chapter9/ex4.py | 655 | 4.3125 | 4 | #!/usr/bin/env python3
''' Code for exercise 4 chapter 9 '''
import sys
def main():
'''
Function asks user for two file names and copies the first to the second
'''
if len(sys.argv) == 3:
in_name = sys.argv[1]
out_name = sys.argv[2]
else:
in_name = input("Enter the name of the input file: ")
out_name = input("Enter the name of the output file: ")
with open(in_name, "r") as in_file, open(out_name, "w") as out_file:
while True:
line = in_file.readline()
if not line:
break
out_file.write(line)
if __name__ == "__main__":
main()
| true |
4bfff67203f0ab60a696bdb49cbc00de7db79767 | govindak-umd/Data_Structures_Practice | /LinkedLists/singly_linked_list.py | 2,864 | 4.46875 | 4 | """
The code demonstrates how to write a code for defining a singly linked list
"""
# Creating a Node Class
class Node:
# Initialize every node in the LinkedList with a data
def __init__(self, data):
# Each of the data will be stored as
self.data = data
# This is very important because is links one
# of the node to the next one and by default
# it is linked to none
self.next = None
# Creating a LinkedList class
class LinkedList:
def __init__(self, ):
# The below is the head of the LinkedList
# which is the first element of a LinkedList
self.head = None
# Writing a function to print the LinkedList
def PrintLinkedList(self):
temporary_head = self.head
while temporary_head is not None:
print(temporary_head.data)
temporary_head = temporary_head.next
# Implement addition at the beginning functionality
def addBeginning(self, new_node):
new_node_beg = Node(new_node)
new_node_beg.next = self.head
self.head = new_node_beg
# Implement addition at the end functionality
def addEnd(self, new_node):
new_node_end = Node(new_node)
# creating a temporary head
temp_head = self.head
# keep looping until the head doesn't have anything next
while temp_head.next:
temp_head = temp_head.next
temp_head.next = new_node_end
# Implement addition at the middle functionality
def removeNode(self, new_node):
new_node_removed = Node(new_node)
temp_head = self.head
# removing the first element
if self.head.data == new_node_removed.data:
temp_head = temp_head.next
self.head = temp_head
# for removing the any other element other than the first element
while temp_head.next:
if temp_head.next.data == new_node:
temp_head.next = temp_head.next.next
break
else:
temp_head = temp_head.next
if __name__ == '__main__':
# Creating a LinkedList object
linked_list_object = LinkedList()
# Defining the head for the linkedList
linked_list_object.head = Node(1)
# defining the second, third and fourth elements in the linked list
second = Node(2)
third = Node(3)
fourth = Node(4)
# Linking each element to the next element starting with
# linking the head to the second element
linked_list_object.head.next = second
second.next = third
third.next = fourth
# Testing adding in the beginning
linked_list_object.addBeginning(99)
# Testing adding at the end
linked_list_object.addEnd(55)
# Testing removing any key in the LinkedList
linked_list_object.removeNode(3)
linked_list_object.PrintLinkedList()
| true |
dc8e36cdd048bcff0c3bfaa69c71923fd53ec7bc | pgrandhi/pythoncode | /Assignment2/2.VolumeOfCylinder.py | 367 | 4.15625 | 4 | #Prompt the use to enter radius and length
radius,length = map(float, input("Enter the radius and length of a cylinder:").split(","))
#constant
PI = 3.1417
def volumeOfCylinder(radius,length):
area = PI * (radius ** 2)
volume = area * length
print("The area is ", round(area,4), " The volume is ", round(volume,1))
volumeOfCylinder(radius,length)
| true |
670e2caa200e7b81c4c67abe0e8db28c9d3bce5d | pgrandhi/pythoncode | /Class/BMICalculator.py | 584 | 4.3125 | 4 | #Prompt the user for weight in lbs
weight = eval(input("Enter weight in pounds:"))
#Prompt the user for height in in
height = eval(input("Enter height in inches:"))
KILOGRAMS_PER_POUND = 0.45359237
METERS_PER_INCH = 0.0254
weightInKg = KILOGRAMS_PER_POUND * weight
heightInMeters = METERS_PER_INCH * height
#Compute BMI = WgightInKg/(heightInMeters squared)
bmi = weightInKg /(heightInMeters ** 2)
print("BMI is: ", bmi)
if(bmi <18.5):
print("Under-weight")
elif (bmi <25):
print("Normal weight")
elif (bmi <30):
print("Over-weight")
else:
print("Obese")
| true |
7b8241125841ad4f17077ed706af394576f6a0dc | briand27/LPTHW-Exercises | /ex20.py | 1,172 | 4.15625 | 4 | # imports System
from sys import argv
# creates variables script and input_file for arguments
script, input_file = argv
# define a function that takes in a file to read
def print_all(f):
print f.read()
# define a function that takes in a file to seek
def rewind(f):
f.seek(0)
# defines a function that prints out the given line of a given file
def print_a_line(line_count, f):
print line_count, f.readline()
# creates a variable that represents the open input_file
current_file = open(input_file)
print "First let's print the whole file:\n"
# calls print_all on the given file
print_all(current_file)
print "Now let's rewind, kind of like a tape."
# calls rewind on the given current_file
rewind(current_file)
print "Let's print three lines:"
# sets current_line to 1 the prints that line of the current_file
current_line = 1
print_a_line(current_line, current_file)
# sets the current_line one higher then prints that line of the current_file
current_line += 1
print_a_line(current_line, current_file)
# sets the current_line one higher again then prints that line of
# the current_file
current_line += 1
print_a_line(current_line, current_file)
| true |
03389bd8ab6b7f1a14d681c6f209c264e2e27aad | mlbudda/Checkio | /o_reilly/index_power.py | 440 | 4.15625 | 4 | # Index Power
def index_power(array: list, n: int) -> int:
"""
Find Nth power of the element with index N.
"""
try:
return array[n] ** n
except IndexError:
return -1
# Running some tests..
print(index_power([1, 2, 3, 4], 2) == 9, "Square")
print(index_power([1, 3, 10, 100], 3) == 1000000, "Cube")
print(index_power([0, 1], 0) == 1, "Zero power")
print(index_power([1, 2], 3) == -1, "IndexError")
| true |
473d7d7500ffc160f056d661b0ef8a1d297a84a7 | mnsupreme/artificial_intelligence_learning | /normal_equation.py | 2,911 | 4.3125 | 4 | #This code solves for the optimum values of the parameters analytically using calculus.
# It is an alternative way to optimizing iterarively using gradient descent. It is usually faster
# but is much more computationally expensive. It is good if you have 1000 or less parameters to solve for.
# complexity is O(n^3)
# This examply assumes the equation y = param_0(y-intercept) + param_1 * input_1 + param_2 * input_2....
# If you have an equation in a different form such as y = param_0(y-intercept) + param_1 * input_1 * input_2 + param_2 * (input_2)^2
# then you must make adjustments to the design matrix accordignly. (Multiply the inputs acordingly and use those results in the design matrix)
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data
from matplotlib import cm
import numpy as np
from numpy.linalg import inv
data = np.loadtxt('gradient_descent/ex3Data/ex3x.dat',dtype=float)
#this function helps put the inputs in vector form as the original data already came as a design matrix.
#This way the data is more realistic. Technically, this function is unecessary
def vectorize_data():
#regular python list
vectorized_data = []
for row in data:
# inserts a 1 in the beginning every row of the matrix to represent x_0 input
row = np.insert(row,0,1)
print "row {0}, \n row_transpose {1}".format(row, row.reshape((-1,1)))
#converts [element1, element 2] to [ form.
# element1,
# element2,
# ]
vectorized_data.append(row.reshape((-1,1)))
#you need to convert design matrix into a numpy array because it starts out as a regular python list.
vectorized_data = np.array(vectorized_data)
print vectorized_data
return vectorized_data
x = vectorize_data()
#converts vectorized data into a design matrix.
# The design matrix looks like this: design_matrix = [transpose_of_each_input_vector or transpose_of_each_row_in_vectorized_data]
def assemble_design_matrix():
#regulare python list
design_matrix = []
for row in x:
design_matrix.append(row.transpose())
#you need to convert design matrix into a numpy array before you convert it to a matrix because it starts out asa regular python list.
design_matrix = np.matrix(np.array(design_matrix))
print "design_matrix {0} \n design_matrix_transpose {1}".format(design_matrix, design_matrix.transpose())
return design_matrix
def normal():
design_matrix = assemble_design_matrix()
y = np.loadtxt('gradient_descent/ex3Data/ex3y.dat', dtype=float)
y = y.reshape(47,1)
# THIS IS THE NORMAL EQUATION FORMULA
# the function is inverse(design_matrix_transpose * design_matrix) * (design_matrix_transpose * y_vector)
# this will yield a matrix full of your optimized theta parameter values
result = inv((design_matrix.transpose() * design_matrix)) * (design_matrix.transpose() * y)
print result
return result
if __name__ == '__main__':
normal() | true |
ef2fb36ea0588d36aa6b49ad55d57ee4a5d64bc0 | dguest/example-text-parser | /look.py | 1,851 | 4.15625 | 4 | #!/usr/bin/env python3
import sys
from collections import Counter
from csv import reader
def run():
input_name = sys.argv[1]
csv = reader(open(input_name), skipinitialspace=True)
# first read off the titles
titles = next(csv)
indices = {name:number for number, name in enumerate(titles)}
# keep track of something (proj_by_company) in this case
proj_by_company = Counter()
# iterate through all the records
for fields in csv:
# build up a dictionary of fields
named_fields = {titles[idx]:val for idx, val in enumerate(fields)}
company = named_fields['Company Name']
# The empty string us used in the CSV to represent zero.
comp_projs_as_string = named_fields['# projects completed']
# Unfortunately, this means that we have to manually enter
# zero in the case of en empty string. Empty strings evaluate
# to False.
#
# Note that this whole operation could be represented with some
# more magic as:
# > comp_projs = int(named_fields['# projects completed'] or 0)
# but it's a bit confusing to understand why that works.
if not comp_projs_as_string:
comp_projs = 0
else:
comp_projs = int(comp_projs_as_string)
# add to the counter
proj_by_company[company] += comp_projs
# Do some sorting. The sort function works on a container, which
# we get by using `.items()` to return a list of (key, value)
# pairs. In this case we're sorting by the second value, thus the
# anonymous function created with `lambda`.
sorted_companies = sorted(proj_by_company.items(),key=lambda x: x[1])
for company, count in reversed(sorted_companies):
if count > 0:
print(company, count)
if __name__ == '__main__':
run()
| true |
21ebaf035e0a5bda9b9836a8c77221f20c9f4388 | timomak/CS-1.3 | /First try 😭/redact_problem.py | 692 | 4.21875 | 4 | def reduct_words(given_array1=[], given_array2=[]):
"""
Takes 2 arrays.
Returns an array with the words from the first array, that were not present in the second array.
"""
output_array = [] # Array that is gonna be returned
for word in given_array1: # For each item in the first array, loop O(n)
if word not in set(given_array2): # Check if the current item is present in the second array.
output_array.append(word) # Append to output array
return output_array # return the final array after for loop
# Custom test ;)
if reduct_words([1,2,3,4,5,10], [1,2,3,4,5,6,7,8,9,0]) == [10]:
print("works")
else:
print("Doesn't work")
| true |
dfa668f57584dc42dbc99c5835ebc0a5c0b1e0cd | avir100/ConsultAdd | /task2/task2_10.py | 815 | 4.125 | 4 | from random import randint
'''
Write a program that asks five times to guess the lucky number. Use a while loop and a counter, such as
counter=1
While counter <= 5:
print(“Type in the”, counter, “number”
counter=counter+1
The program asks for five guesses (no matter whether the correct number was guessed or not). If the correct number is guessed, the program outputs “Good guess!”, otherwise it outputs “Try again!”. After the fifth guess it stops and prints “Game over!”.
'''
counter = 1
answer = randint(1,10)
print "Answer: ", answer
while counter <= 5:
number = int(raw_input("Guess the lucky number between 1-10: \n"))
if (number == answer):
print ("Good guess!")
else:
if counter == 5:
print ("Game over!")
else:
print ("Try again!")
counter += 1
| true |
8fdb362aa4fb0de01b740a5a840904bf329b5f22 | lzeeorno/Python-practice175 | /terminal&py.py | 696 | 4.125 | 4 | #how to use python in terminal
def main():
while True:
s = input('do you come to learn how to open py doc in terminal?(yes/no):')
if s.lower() == 'yes':
print('cd use to enter doc, ls to look the all file, python filename.py to open the py document')
s1 = input('do you understand?(yes/no):')
if s1.lower() == 'yes':
print('nice, bye')
break
else:
print('ok, come to ask again')
break
elif s.lower()== 'no':
print('ok, goodbye')
break
else:
print('wrong input, please enter yes/no')
continue
main()
| true |
5952daff834f8f713be39ef520f25d896034a006 | sahthi/backup2 | /backup_files/practice/sample/exp.py | 374 | 4.125 | 4 | import math
x=[10,-5,1.2,'apple']
for i in x:
try:
fact=math.factorial(i)
except TypeError:
print("factorial is not supported for given input:")
except ValueError:
print ("factorial only accepts positive integers")
else:
print ("factorial of a", x, "is",fact)
finally:
print("release any resources in use")
| true |
b3b0800b6add715999684c41393d1df9a636459d | All-I-Do-Is-Wynn/Python-Codes | /Codewars_Challenges/get_sum.py | 547 | 4.28125 | 4 | # Given two integers a and b, which can be positive or negative,
# find the sum of all the integers between and including them and return it.
# If the two numbers are equal return a or b.
# Note: a and b are not ordered!
def get_sum(a,b):
sum = 0
if a < b:
for x in range(a,b+1):
sum += x
else:
for x in range(b,a+1):
sum += x
return sum
# Shortened
def get_sum2(a,b):
return sum(range(min(a,b),max(a,b)+1))
if __name__ == '__main__':
print(get_sum(0,2))
print(get_sum2(0,-2)) | true |
15fdbc037475927e58bf3b36a60c5cffc95264bc | rayvantsahni/after-MATH | /Rotate a Matrix/rotate_matrix.py | 1,523 | 4.40625 | 4 | def rotate(matrix, n, d):
while n:
matrix = rotate_90_clockwise(matrix) if d else rotate_90_counter_clockwise(matrix)
n -= 1
return matrix
def rotate_90_counter_clockwise(matrix):
"""
The function rotates any square matrix by 90° counter clock-wise.
"""
for row in matrix:
row.reverse()
n = len(matrix)
for row in range(n):
for col in range(row, n):
matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col]
return matrix
def rotate_90_clockwise(matrix):
"""
The function rotates any square matrix by 90° clock-wise.
"""
n = len(matrix)
for row in range(n):
for col in range(row, n):
matrix[row][col], matrix[col][row] = matrix[col][row], matrix[row][col]
for row in matrix:
row.reverse()
return matrix
if __name__ == "__main__":
# matrix_1 = [[1]]
# matrix_2 = [[1, 2],
# [3, 4]]
matrix_3 = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# matrix_4 = [[1, 2, 3, 4],
# [5, 6, 7, 8],
# [9, 10, 11, 12],
# [13, 14, 15, 16]]
number_of_rotations = int(input("Enter the number of times you want to rotate the matrix:\n"))
print("To rotate COUNTER-CLOCKWISE enter 0, OR\nTo rotate CLOCKWISE enter 1.")
direction = int(input())
print("Rotated Matrix:")
for row in (rotate(matrix_3, number_of_rotations % 4, direction % 2)):
print(row)
| true |
c6d2d5095d319fdfe43ad2dc712cd97cbe44cb9e | rohit-kuma/Python | /List_tuples_set.py | 1,822 | 4.1875 | 4 | courses = ["history", "maths", "hindi"]
print(courses)
print(len(courses))
print(courses[1])
print(courses[-1])
print(courses[0:2])
courses.append("art")
courses.insert(1, "Geo")
courses2 = ["Art", "Education"]
print(courses)
#courses.insert(0, courses2)
#print(courses)
courses2.extend(courses)
print(courses2)
print(courses2.pop())
print(courses2)
courses2.remove("Geo")
print(courses2)
courses2.reverse()
print(courses2)
courses2.sort()
print(courses2)
num = [5, 1, 4]
num.sort(reverse=True)
print(num)
#without altering the original
num2 = sorted(num)
print(num2)
print(min(num2))
print(max(num2))
print(sum(num2))
print(num2.index(4))
print(4 in num2)
for i in courses2:
print(i)
for index, courses in enumerate(courses2):
print(index, courses)
for index, courses in enumerate(courses2, start = 1):
print(index, courses)
courses_str = ", ".join(courses2)
print(courses_str)
new_list = courses_str.split(", ")
print(new_list)
#Tuples
#List are mutables tuples are not
# Mutable
print("Mutable List")
list_1 = ['History', 'Math', 'Physics', 'CompSci']
list_2 = list_1
print(list_1)
print(list_2)
list_1[0] = 'Art'
print(list_1)
print(list_2)
print("Immutable List")
# Immutable
tuple_1 = ('History', 'Math', 'Physics', 'CompSci')
tuple_2 = tuple_1
print(tuple_1)
print(tuple_2)
# tuple_1[0] = 'Art'
print(tuple_1)
print(tuple_2)
print("Sets")
# Sets
cs_courses = {'History', 'Math', 'Physics', 'CompSci'}
art_courses = {"Math", "GEO", "Physics"}
print(cs_courses)
print(art_courses)
print(cs_courses.intersection(art_courses))
print(cs_courses.difference(art_courses))
print(cs_courses.union(art_courses))
# Empty Lists
empty_list = []
empty_list = list()
# Empty Tuples
empty_tuple = ()
empty_tuple = tuple()
# Empty Sets
empty_set = {} # This isn't right! It's a dict
empty_set = set()
| true |
598a1c47c454c6e31408824cdec50d9d4a262cef | mswinkels09/Critters_Croquettes_server | /animals/petting_animals.py | 2,463 | 4.3125 | 4 | # import the python datetime module to help us create a timestamp
from datetime import date
from .animals import Animal
from movements import Walking, Swimming
# Designate Llama as a child class by adding (Animal) after the class name
class Llama(Animal):
# Remove redundant properties from Llama's initialization, and set their values via Animal
def __init__(self, chip_number, name, species, shift, food ):
Animal.__init__(self, chip_number, name, species, food)
self.shift = shift # stays on Llama because not all animals have shifts
self.walking = True
def feed(self):
print(f'{self.name} was not fed {self.food} on {date.today().strftime("%m/%d/%Y")}')
class Goose(Animal, Walking, Swimming):
def __init__(self, name, species, food):
# No more super() when initializing multiple base classes
Animal.__init__(self, name, species, food)
Swimming.__init__(self)
Walking.__init__(self)
# no more self.swimming = True
...
def honk(self):
print("The goose honks. A lot")
# run is defined in the Walking parent class, but also here. This run method will take precedence and Walking's run method will not be called by Goose instances
def run(self):
print(f'{self} waddles')
def __str__(self):
return f'{self.name} the Goose'
class Goat(Animal):
def __init__(self, chip_number, name, species, shift, food ):
Animal.__init__(self, chip_number, name, species, food)
self.shift = shift
self.walking = True
def feed(self):
print(f'{self.name} was enthusiastically fed {self.food} on {date.today().strftime("%m/%d/%Y")}')
class Donkey(Animal):
def __init__(self, chip_number, name, species, shift, food ):
Animal.__init__(self, chip_number, name, species, food)
self.shift = shift
self.walking = True
def feed(self):
print(f'{self.name} was obnoxiously fed {self.food} on {date.today().strftime("%m/%d/%Y")}')
class Pig(Animal):
def __init__(self, chip_number, name, species, shift, food ):
Animal.__init__(self, chip_number, name, species, food)
self.shift = shift
self.walking = True
class Ox(Animal):
def __init__(self, chip_number, name, species, shift, food ):
Animal.__init__(self, chip_number, name, species, food)
self.shift = shift
self.walking = True | true |
c27892b565bb1731b02f2fa7f6258419bad34edd | Uma-Ravi22/Bertelsmann-Technology-Scholarship-Python-Challenges | /Day42_RedactText.py | 1,421 | 4.6875 | 5 |
# Day 42 Challenge: Redacting Text in a File
# Sensitive information is often removed, or redacted, from documents before they are released to the public.
# When the documents are released it is common for the redacted text to be replaced with black bars. In this exercise
# you will write a program that redacts all occurrences of sensitive words in a text file by replacing them with
# asterisks. Your program should redact sensitive words wherever they occur, even if they occur in the middle of
#another word. The list of sensitive words will be provided in a separate text file. Save the redacted version of the
# original text in a new file. The names of the original text file, sensitive words file, and redacted file will all
# be provided by the user...
#Main
fname = input("Enter Source File Name:")
inf = open(fname, "r")
senfile = input("Enter File name contains Sensitive words:")
fsen = open(senfile, "r")
words = []
for line in fsen.readlines():
line = line.rstrip()
line = line.lower()
if line != " ":
words.append(line)
fsen.close()
#print(words)
outfile = input("Enter Output File name:")
outf = open(outfile, "w")
line = inf.readline()
while line != "":
line = line.rstrip()
line = line.lower()
for word in words:
line = line.replace(word, "*" * len(word))
outf.write(line)
line = inf.readline()
inf.close()
outf.close()
| true |
dc24942f5115667462dd5c11064d903c92d38825 | Uma-Ravi22/Bertelsmann-Technology-Scholarship-Python-Challenges | /Day67_LastlineFile.py | 553 | 4.46875 | 4 | # Day 67 Challenge: Print last Line of a File.
# Function iterates over lines of file, store each line in lastline.
# When EOF, the last line of file content is stored in lastline variable.
# Print the result.
def get_final_line(fname):
fhand = open(fname, "r")
for line in fhand:
fhand = line.rstrip()
lastline = line
print("The Last Line is:")
print(lastline)
# Main
# Read the File name & pass it as an argument to get_final_line function.
fname = input('Enter a File Name:')
get_final_line(fname)
| true |
ec508478bbd76531f1ef8e2a7a849254092cb3e4 | Uma-Ravi22/Bertelsmann-Technology-Scholarship-Python-Challenges | /Day45_RecurStr.py | 689 | 4.28125 | 4 | # Day 45: Recursive (String) Palindrome
def Palindrome(s):
# If string length < 1, return TRUE.
if len(s) < 1:
return True
else:
# Last letter is compared with first, function called recursively with argument as
# Sliced string (With first & last character removed.)
if s[0] == s[-1]:
return Palindrome(s[1:-1])
else:
return False
# Main
# Read Input String.
str = input("Enter a String:")
# Convert to lower case to avoid mistake.
str = str.lower()
# Function call & Print Result.
if Palindrome(str):
print("The Given String is a Palindrome.")
else:
print("The Given String is Not a Palindrome.")
| true |
1645420882248e7ffa84200b538f9294884da028 | jmohit13/Algorithms-Data-Structures-Misc-Problems-Python | /data_structures/queue.py | 1,719 | 4.25 | 4 | # Queue Implementation
import unittest
class Queue:
"""
Queue maintain a FIFO ordering property.
FIFO : first-in first-out
"""
def __init__(self):
self.items = []
def enqueue(self,item):
"""
Adds a new item to the rear of the queue.
It needs the item and returns nothing.
"""
# temp_list = []; temp_list.append(item)
# self.items = temp_list + self.items
self.items.insert(0,item)
def dequeue(self):
"""
Removes the front item from the queue.
It needs no parameters and returns the item. The queue is modified.
"""
return self.items.pop()
def isEmpty(self):
"""
Tests to see whether the queue is empty.
It needs no parameters and returns a boolean value.
"""
return self.items == []
def size(self):
"""
Returns the number of items in the queue.
It needs no parameters and returns an integer.
"""
return len(self.items)
class QueueTest(unittest.TestCase):
def setUp(self):
self.q = Queue()
def testEnqueue(self):
self.q.enqueue('ball')
self.assertEqual(self.q.items[0],'ball')
def testDequeue(self):
self.q.enqueue('baseball')
removedItem = self.q.dequeue()
self.assertEqual(removedItem,'baseball')
def testIsEmpty(self):
self.assertTrue(self.q.isEmpty())
def testSize(self):
self.q.enqueue('ball')
self.q.enqueue('football')
self.assertEqual(self.q.size(),2)
if __name__ == "__main__":
unittest.main()
| true |
1a6b2d6da21f7e87c107dd45b2ffeec143c2aef6 | nivetha-ashokkumar/python-basics | /factorial.py | 459 | 4.125 | 4 | def factorial(number1, number2):
temp = number1
number1 = number2
number2 = temp
return number1, number2
number1 = int(input("enter first value:"))
number2 = int(input("enter second vakue:"))
result = factorial(nnumber1, number2)
print("factorial is:", result)
def check(result):
if(result != int):
try:
print(" given input is not integer")
except:
print("error")
return result
| true |
231490f1ba7aa8be510830ec4a16568b5e4b2adb | THUEishin/Exercies-from-Hard-Way-Python | /exercise15/ex15.py | 503 | 4.21875 | 4 | '''
This exercise is to read from .txt file
Pay attention to the operations to a file
Namely, close, read, readline, truncate, write(" "), seek(0)
'''
from sys import argv
script, filename = argv
txt = open(filename)
print(f"Here is your file {filename}")
#readline() is to read a line from the file
#strip(*) is to delete the character * at the beginning or end of the string
line = txt.readline().strip(' ').strip('\n')
while line:
print(line)
line = txt.readline().strip(' ').strip('\n')
| true |
5cfafd423c1d2d315dadc17c6796ec3cc860dad4 | aav789/pengyifan-leetcode | /src/main/python/pyleetcode/keyboard_row.py | 1,302 | 4.4375 | 4 | """
Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American
keyboard like the image below.
Example 1:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
Note:
- You may use one character in the keyboard more than once.
- You may assume the input string will only contain letters of alphabet.
"""
def find_words(words):
"""
:type words: List[str]
:rtype: List[str]
"""
keyboards = ['qwertyuiop',
'asdfghjkl',
'zxcvbnm',]
out = []
for word in words:
for row in keyboards:
in_row = False
not_in_row = False
for c in word.lower():
if c in row:
in_row = True
else:
not_in_row = True
if in_row and not not_in_row:
out.append(word)
break
return out
def test_find_words():
input = ["Hello","Alaska","Dad","Peace"]
expected = ["Alaska","Dad"]
assert find_words(input) == expected
input = ["asdfghjkl","qwertyuiop","zxcvbnm"]
expected = ["asdfghjkl","qwertyuiop","zxcvbnm"]
assert find_words(input) == expected
if __name__ == '__main__':
test_find_words() | true |
98ca0cf6d09b777507091ea494f28f756f6ca1e1 | aav789/pengyifan-leetcode | /src/main/python/pyleetcode/Reverse_Words_in_a_String_III.py | 682 | 4.40625 | 4 | """
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
"""
def reverseWords(s):
"""
:type s: str
:rtype: str
"""
if not s:
return s
return ' '.join([w[::-1] for w in s.split(' ')])
def test_reverseWords():
assert reverseWords("Let's take LeetCode contest") == "s'teL ekat edoCteeL tsetnoc"
if __name__ == '__main__':
test_reverseWords()
| true |
1af36f5047e5ed15218cdc84f3b2bc9ea77bc57c | faridmaamri/PythonLearning | /PCAP_Lab Palindromes_method2.py | 1,052 | 4.34375 | 4 | """
EDUB_PCAP path: LAB 5.1.11.7 Plaindromes
Do you know what a palindrome is?
It's a word which look the same when read forward and backward. For example, "kayak" is a palindrome, while "loyal" is not.
Your task is to write a program which:
asks the user for some text;
checks whether the entered text is a palindrome, and prints result.
Note:
- assume that an empty string isn't a palindrome;
- treat upper- and lower-case letters as equal;
- spaces are not taken into account during the check - treat them as non-existent;
there are more than a few correct solutions - try to find more than one.
"""
### Ask the user to enter the text or sentence
text=input('Please enter the text to check : ')
##remove spaces and convert all caracters to lower case
string=text.replace(' ','')
string=string.lower()
for i in range (len(string)):
if string[-i-1]!=string[i]:
print(i,(-i-1))
print('it\'s not a palindrome')
break
if i == (len(string)-1):
print('it\'s a palindrome') | true |
7a7e4c2393928ca31e584f184f4a6c51689a42c5 | DominiqueGregoire/cp1404practicals | /prac_04/quick_picks.py | 1,351 | 4.4375 | 4 | """asks the user how many "quick picks" they wish to generate. The program then generates that
many lines of output. Each line consists of 6 random numbers between 1 and 45.
pseudocode
get number of quick picks
create a list to hold each quick pick line
generate a random no x 6 to make the line
print the line
repeat this x number of quick picks"""
from random import randint
NUMBERS_PER_LINE = 6
MAXIMUM = 45
MINIMUM = 1
def main():
amount = int(input("How many quick picks? "))
while amount < 0: # check for invalid amount of quick picks
print("Invalid amount")
amount = int(input("How many quick picks? "))
for i in range(amount):
quick_pick_lines = []
for number in range(NUMBERS_PER_LINE): # create a list of 6 random numbers between 1 and 45
number = randint(MINIMUM, MAXIMUM)
if number in quick_pick_lines:
number = randint(MINIMUM, MAXIMUM)
quick_pick_lines.append(number)
# print(quick_pick_lines)
quick_pick_lines.sort()
# print(quick_pick_lines)
# quick_pick_lines = [str(number) for number in quick_pick_lines]
# print(quick_pick_lines)
# print(' '.join(quick_pick_lines))
print(' '.join('{:2}'.format(number) for number in quick_pick_lines))
main()
| true |
b78ec391ca8bbc6943de24f6b4862c8793e3cc14 | cat-holic/Python-Bigdata | /03_Data Science/2.Analysis/3.Database/2.db_insert_rows.py | 1,218 | 4.375 | 4 | # 목적 : 테이블에 새 레코드셋 삽입하기
import csv
import sqlite3
# Path to and name of a CSV input file
input_file = "csv_files/supplier_data.csv"
con = sqlite3.connect('Suppliers.db')
c = con.cursor()
create_table = """CREATE TABLE IF NOT EXISTS Suppliers(
Supplier_Name VARCHAR(20),
Invoice_Number VARCHAR(20),
Part_Number VARCHAR(20),
Cost FLOAT,
Purchase_Date);"""
c.execute(create_table)
# Read the CSV file
# Insert the data into the Suppliers table
file_reader = csv.reader(open(input_file, 'r'), delimiter=',')
header = next(file_reader, None) # Header 건너뛰고 data만 접근 하기 위함
for row in file_reader:
data = []
for column_index in range(len(header)):
data.append(row[column_index])
print(data)
c.execute("INSERT INTO Suppliers VALUES (?,?,?,?,?);", data)
con.commit()
print("데이터 베이스 삽입 완료 \n\n")
# Query the Suppliers table
output = c.execute("SELECT * FROM Suppliers")
rows = output.fetchall()
for row in rows:
output = []
for column_index in range(len(row)):
output.append(row[column_index])
print(output) | true |
e84ee8da19f091260bef637a5d7104b383f981a5 | apriantoa917/Python-Latihan-DTS-2019 | /LOOPS/loops - pyramid block.py | 366 | 4.28125 | 4 | # 3.1.2.14 LAB: Essentials of the while loop
blocks = int(input("Enter the number of blocks: "))
height = 0
layer = 1
while layer <= blocks:
blocks = blocks - layer #jumlah blok yang disusun pada setiap layer , 1,2,3...
height += 1 #bertambah sesuai pertambahan layer
layer += 1
print("The height of the pyramid:", height) | true |
02fc00ec75f78c552b47cf4376c8d655b1012cc6 | apriantoa917/Python-Latihan-DTS-2019 | /LOOPS/loops - the ugly vowel eater.py | 282 | 4.21875 | 4 | # 3.1.2.10 LAB: The continue statement - the Ugly Vowel Eater
userWord = input("Enter the word : ")
userWord = userWord.upper()
for letter in userWord :
if (letter == "A" or letter == "I" or letter == "U" or letter == "E" or letter == "O"):
continue
print(letter) | true |
83c51994945f1fc21ad3cd97c257143b23604909 | LukaszRams/WorkTimer | /applications/database/tables.py | 1,559 | 4.15625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file will store the data for the database queries that will be called to create the database
"""
# Table of how many hours an employee should work per month
class Monthly_working_time:
table_name = "MONTHLY_WORKING_TIME"
data = {
"id": ("integer", "PRIMARY KEY"),
"year": ("integer", "NOT NULL"),
"month": ("text", "NOT NULL"),
"hours": ("integer", "NOT NULL")
}
# A table that will contain data on the time worked by the employee during the month
class Working_time:
table_name = "WORKING_TIME"
data = {
"id": ("integer", "PRIMARY KEY"),
"user": ("text", "NOT NULL"),
"year": ("YEAR", "NOT NULL"),
"month": ("text", "NOT NULL"),
"total_hours": ("integer", "NOT NULL"), # number of hours worked by the employee
"base_hours": ("integer", "NOT NULL"), # the number of hours the employee was to work
"overtime_hours": ("integer", "NOT NULL"), # number of overtime hours
}
# Detailed data from employees' work, the amount of data grows very quickly so it needs to be cleaned
class Detailed_working_time:
table_name = "DETAILED_WORKING_TIME"
data = {
"id": ("integer", "PRIMARY KEY"),
"user": ("text", "NOT NULL"),
"date": ("DATE", "NOT NULL"), # detailed_working_time
"start_at": ("TIME", "NOT NULL"), # start time
"end_at": ("TIME", "NOT NULL"), # end time
}
tables = [Monthly_working_time, Working_time, Detailed_working_time]
| true |
928511975d3b85c7be7ed6c11c63ce33078cc5a1 | Silentsoul04/FTSP_2020 | /Python_CD6/reverse.py | 874 | 4.25 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 24 11:41:04 2020
@author: Rajesh
"""
"""
Name:
Reverse Function
Filename:
reverse.py
Problem Statement:
Define a function reverse() that computes the reversal of a string.
Without using Python's inbuilt function
Take input from User
Sample Input:
I am testing
Sample Output:
gnitset ma I
"""
def reverse(x):
return x[: : -1]
x = input('Enter the string from user :')
print('The Reverse string :', reverse(x))
################ OR #################
def rev_string(str1):
return str1[: : -1]
str1 = input('Enter the string from user :')
print('The Reverse string :', rev_string(str1))
################ OR #################
def rev_num(num):
return num[: : -1]
num = input('Enter any number to reverse :')
print('The Reversed number :', rev_num(num))
| true |
953ebb6e03cbac2798978798127e144ac2eee85f | Silentsoul04/FTSP_2020 | /Python_CD6/generator.py | 930 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 17:46:18 2020
@author: Rajesh
"""
"""
Name:
generator
Filename:
generator.py
Problem Statement:
This program accepts a sequence of comma separated numbers from user
and generates a list and tuple with those numbers.
Data:
Not required
Extension:
Not Available
Hint:
Not Available
Algorithm:
Not Available
Boiler Plate Code:
Not Available
Sample Input:
2, 4, 7, 8, 9, 12
Sample Output:
List : ['2', ' 4', ' 7', ' 8', ' 9', '12']
Tuple : ('2', ' 4', ' 7', ' 8', ' 9', '12')
"""
" NOTE :- split() function always split the given string and stored the values into list."
s = input('Enter some value :').split(',')
print('The List :', s)
print('The Tuple :', tuple(s))
############# OR ###############
str1 = input('enter any number :').split()
print('List :', str1)
print('Tuple :', tuple(str1))
| true |
7ad064ce2fc4150f351ef3ce360dd3d7230a34f6 | Silentsoul04/FTSP_2020 | /Python_CD6/weeks.py | 2,024 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 17:01:28 2020
@author: Rajesh
"""
"""
Name:
weeks
Filename:
weeks.py
Problem Statement:
Write a program that adds missing days to existing tuple of days
Sample Input:
('Monday', 'Wednesday', 'Thursday', 'Saturday')
Sample Output:
('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')
"""
t = ('Monday', 'Wednesday', 'Thursday', 'Saturday')
l1=list(t) # Now Tuple will be converted into list and then we will be appending some of the values into it.
print('The tuple becomes into List : ', l1)
l1.append('Tuesday')
l1.append('Friday')
l1.append('Sunday')
print('The List after Adding some missing Items are :', l1)
t1 = tuple(l1)
sorted(t1)
print('The final output will be in Tuple only :', t1)
########### OR ##############
tuple = (10,20,30,40,50)
type(t)
list1 = list(tuple) # Now Tuple will be converted into list and then we will be appending some of the values into it.
print(list1)
list1.append(100)
list1.append(250)
list1.append(350)
print(list1)
for i in list1:
list2 = list1.count(i)
i+=1
print(list1)
list1.index(100)
list1.index(30)
list1.insert(5,0)
list1.insert(0,7)
list1.insert(2,450)
list1.remove(6) # We need to pass the particular element in list not index number. [ NOT Valid ]
list1.remove(0)
list1.pop()
print(list1)
list1.append(7)
list1.index(20)
list1.pop(3)
print(list1)
list2 = [] # Empty list.
print(list2) # It will be printing empty list.
list2.clear() # It is used to clear all the data from the list2.
print(list2)
list2.extend(list1) # It will be combining both lists each other.
list2.append(list1) # It will be combining list2 then whole list1 full without removing [] bracket like single character.
list1.sort()
list1.reverse()
print(type(t))
print(t)
print(t[0])
print(t[3])
print(t[-1])
print(t[:2])
t=() # Data type is empty tuple
t=(10,) # Single value tuple value always ends with comma ( ,).
| true |
ce643b9df8113ce2ea53623aecf9d548398eea7e | Silentsoul04/FTSP_2020 | /Durga Strings Pgms/Words_Str_Reverse.py | 299 | 4.21875 | 4 | # WAP to print the words from string in reverse order and take the input from string.
# s='Learning Python is very easy'
s=input('Enter some string to reverse :')
l=s.split()
print(l)
l1=l[: :-1] # The Output will be in the form of List.
print(l1)
output=' '.join(l1)
s.count(l1)
print(output)
| true |
899db6e84ffad7514dbac57c7da77d04d78acb70 | Silentsoul04/FTSP_2020 | /Python_CD6/pangram.py | 1,480 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Jan 27 17:37:41 2020
@author: Rajesh
"""
"""
Name:
Pangram
Filename:
pangram.py
Problem Statement:
Write a Python function to check whether a string is PANGRAM or not
Take input from User and give the output as PANGRAM or NOT PANGRAM.
Hint:
Pangrams are words or sentences containing every letter of the alphabet at least once.
For example: "the quick brown fox jumps over the lazy dog" is a PANGRAM.
Sample Input:
The five boxing wizards jumps.
Sphinx of black quartz, judge my vow.
The jay, pig, fox, zebra and my wolves quack!
Pack my box with five dozen liquor jugs.
Sample Output:
NOT PANGRAM
PANGRAM
PANGRAM
PANGRAM
"""
s = input('Enter any string :')
def Pangram():
str1 = 'abcdefghijklmnopqrstuvwxyz'
for i in str1:
if i in s:
if i == str1[-1]:
print('PANGRAM')
else:
print('NOT PANGRAM')
break
Pangram()
#################### OR ###########################
str1 = 'abcdefghijklmnopqrstuvwxyz'
inp = input(">>")
inpp = inp.split()
d = "".join(inpp)
x = sorted(d)
z= set(x)
x = list(z)
x1 = sorted(x)
z = "".join(x1)
if z == str1:
print("pangram")
else:
print("not pangram")
| true |
f35d17401b20f52dd943239a2c40cb251fa53d03 | jimkaj/PracticePython | /PP_6.py | 342 | 4.28125 | 4 | #Practice Python Ex 6
# Get string and test if palindrome
word = input("Enter text to test for palindrome-ness: ")
start = 0
end = len(word) - 1
while end > start:
if word[start] != word[end]:
print("That's not a palindrome!")
quit()
start = start + 1
end = end -1
print(word," is a palindrome!") | true |
668b160fffc014a4ef3996338f118fc9d4f1db6a | jimkaj/PracticePython | /PP_9.py | 782 | 4.21875 | 4 | # Practice Python #9
# Generate random number from 1-9, have use guess number
import random
num = random.randrange(1,10,1)
print('I have selected a number between 1 and 9')
print("Type 'exit' to stop playing")
count = 0
while True:
guess = input("What number have I selected? ")
if guess == 'exit':
break
count = count + 1
try: guess = int(guess)
except:
print("Invalid Input. You must input an integer or 'exit' to quit playing")
count = count -1
continue
if guess == num:
print('You guessed it! That took you',count,'tries')
exit()
if guess < num:
print('Too low! Guess again.')
if guess > num:
print('Too high! Guess again.')
| true |
9749245820a806a3da1f256446398a3558cabc6a | darthlyvading/fibonacci | /fibonacci.py | 369 | 4.25 | 4 | terms = int(input("enter the number of terms "))
n1 = 0
n2 = 1
count = 0
if terms <= 0:
print("terms should be > 0")
elif terms == 1:
print("Fibonacci series of ",terms," is :")
print(n1)
else:
print("Fibonacci series is :")
while count < terms:
print(n1)
total = n1 + n2
n1 = n2
n2 = total
count += 1
| true |
5c96d7745ba921694275a5369cc4993c6bb5d023 | inmank/SPOJ | /source/AddRev.py | 2,292 | 4.3125 | 4 | '''
Created on Jun 20, 2014
@author: karthik
The Antique Comedians of Malidinesia prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies.
Therefore the dramatic advisor of ACM has decided to transfigure some tragedies into comedies.
Obviously, this work is very hard because the basic sense of the play must be kept intact, although all the things change to their opposites.
For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play.
Reversed number is a number written in arabic numerals but the order of digits is reversed.
The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now.
Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21).
Also note that the reversed number never has any trailing zeros.
ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum.
Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing).
Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 12).
Input:
-----
The input consists of N cases (equal to about 10000). The first line of the input contains only positive integer N. Then follow the cases.
Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add.
Output:
------
For each case, print exactly one line containing only one integer - the reversed sum of two reversed numbers. Omit any leading zeros in the output.
Example
Sample input:
3
24 1
4358 754
305 794
Sample output:
34
1998
1
'''
def reverseNum(numIn):
numOut = 0;
while (numIn <> 0):
numOut = numOut * 10
numOut = numOut + numIn%10
numIn = numIn/10
return numOut
inCount = raw_input()
print inCount
for i in range(int(inCount)):
inValues = raw_input().split(" ")
print reverseNum(reverseNum(int(inValues[0])) + reverseNum(int(inValues[1])))
| true |
c95369771981b2f1a1c73b49a0156ede63aa3675 | ginalamp/Coding_Challenges | /hacker_rank/arrays/min_swaps.py | 1,383 | 4.34375 | 4 | '''
Given an unsorted array with consecutive integers, this program
sorts the array and prints the minimum amount of swaps needed
to sort the array
'''
def main(arr):
'''
@param arr - an array of consecutive integers (unsorted)
@return the minimum amount of swaps needed to sort the given array
'''
# temp is an array where the values are the indexes
# If one accesses temp[val], one would get the index (i) as output
# The index in this case would be the expected value - 1
temp = {val: i for i, val in enumerate(arr)}
min_swaps = 0
for i in range(len(arr)):
value = arr[i]
# array contains consecutive integers starting from 1
expected_value = i + 1
# get the index of the value wanted
expected_i = temp[expected_value]
# swap values if not in the correct order
if value != expected_value:
# in the main array: swap current with the value wanted at the current index
arr[i] = expected_value
arr[expected_i] = value
# in the enum array: swap current with the value wanted at the current index
temp[value] = expected_i
temp[expected_value] = i
min_swaps += 1
print(min_swaps)
return min_swaps
if __name__ == '__main__':
arr = [1,3,5,2,4,6,7]
main(arr)
| true |
340a802c8c77fdc2c4428926a8a2904fe8a388d0 | chirag111222/Daily_Coding_Problems | /Interview_Portilla/Search/sequential_seach.py | 513 | 4.15625 | 4 |
'''
Python => x in list --> How does it work?
Sequential Search
-----------------
'''
unorder = [4,51,32,1,41,54,13,23,5,2,12,40]
order = sorted(unorder)
def seq_search(arr,t):
found = False
for i in arr:
print(i)
if i == t:
found = True
return found
def ord_seq_search(arr,t):
for i in arr:
print(i)
if i == t:
return True
if i > t:
return False
return False
seq_search(unorder,3)
ord_seq_search(order,3)
| true |
d9f9a0c1350d5d68c8e651a6c59b5f6cdd8bfbf1 | chirag111222/Daily_Coding_Problems | /DailyCodingProblem/201_max_path_sum.py | 1,816 | 4.125 | 4 |
'''
You are given an array of arrays of integers, where each array corresponds to a row in a triangle of numbers. For example, [[1], [2, 3], [1, 5, 1]] represents the triangle:
1
2 3
1 5 1
We define a path in the triangle to start at the top and go down one row at a time to an adjacent value,
eventually ending with an entry on the bottom row. For example, 1 -> 3 -> 5. The weight of the path is the sum of the entries.
Write a program that returns the weight of the maximum weight path.'''
# Could we gain something from moving it to a tree?
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
input = [[1], [2, 3], [1, 5, 1]]
'''
Approach:
Iterative calculate the max-cumulative sum at each node.
We are going to visit every node 1 time. O(N)
'''
import copy
cumulative_sum = copy.deepcopy(input)
for j in range(1,len(input)):
for i, entry in enumerate(input[j]):
print('\n\n{}'.format((j,i)))
print('cumulative_sum[{}][{}] += max(cumulative_sum[{}][max(0,{})], cumulative_sum[{}][min({},{})]'.format(
j,i,j-1,i-1,j-1,i,j-1))
print('N = {} + max({},{})'.format(
cumulative_sum[j][i], cumulative_sum[j-1][max(0,i-1)], cumulative_sum[j-1][min(i,j-1)] ))
cumulative_sum[j][i] += max(
cumulative_sum[j-1][max(0,i-1)],
cumulative_sum[j-1][min(i,j-1)] )
print(cumulative_sum)
def max_path(input):
depth = len(input)
for j in range(1,depth):
for i, entry in enumerate(input[j]):
input[j][i] += max(
input[j-1][max(0,i-1)],
input[j-1][min(i,j-1)] )
return max(input[j])
max_path(input) | true |
72cbfa9e3e72c688bf1f321b2e23d975f50fba79 | silvium76/coding_nomads_labs | /02_basic_datatypes/1_numbers/02_04_temp.py | 554 | 4.3125 | 4 | '''
Fahrenheit to Celsius:
Write the necessary code to read a degree in Fahrenheit from the console
then convert it to Celsius and print it to the console.
C = (F - 32) * (5 / 9)
Output should read like - "81.32 degrees fahrenheit = 27.4 degrees celsius"
'''
temperature_fahrenheit = int(input("Please enter the temperature in Fahrenheit: "))
print(temperature_fahrenheit)
temperature_celsius = (temperature_fahrenheit - 32) * (5 / 9)
print(str(temperature_fahrenheit) + " degrees fahrenhei = " + str(temperature_celsius) + " degrees celsius ") | true |
e1b588a089bfc843ac186549b1763db5e55b70bd | umunusb1/PythonMaterial | /python3/02_Basics/02_String_Operations/f_palindrome_check.py | 621 | 4.46875 | 4 | #!/usr/bin/python3
"""
Purpose: Demonstration of Palindrome check
palindrome strings
dad
mom
Algorithms:
-----------
Step 1: Take the string in run-time and store in a variable
Step 2: Compute the reverse of that string
Step 3: Check whether both the strings are equal or not
Step 4: If equal, print that it is palindrome string
"""
test_string = input('Enter any string:')
print(test_string)
# reverse string
reverse_string = test_string[::-1]
print(reverse_string)
if test_string == reverse_string:
print( test_string, 'is palindrome')
else:
print( test_string, 'is NOT a palindrome') | true |
4bfc733c59848c52302a52b5366704fbedce4c94 | umunusb1/PythonMaterial | /python3/04_Exceptions/13_custom_exceptions.py | 564 | 4.15625 | 4 | #!/usr/bin/python3
"""
Purpose: Using Custom Exceptions
"""
# creating a custom exception
class InvalidAge(Exception):
pass
try:
age = int(input('Enter your age:'))
age = abs(age)
if age < 18:
# raise InvalidAge('You are not eligible for voting')
raise InvalidAge(f'You are short by {18 - age} years for voting')
except InvalidAge as ex:
print(str(ex))
except ValueError:
print('Please enter valid age number')
except Exception as ex:
print('Unhandled Exception -', repr(ex))
else:
print('Eligible for voting!!!')
| true |
e53448ad9ec7cd295a7570fc4e75187533c4c134 | umunusb1/PythonMaterial | /python3/10_Modules/03_argparse/a_arg_parse.py | 1,739 | 4.34375 | 4 | #!/usr/bin/python
"""
Purpose: importance and usage of argparse
"""
# # Method 1: hard- coding
# user_name = 'udhay'
# password = 'udhay@123'
# server_name = 'issadsad.mydomain.in'
# # Method 2: input() - run time
# user_name = input('Enter username:')
# password = input('Enter password:')
# server_name = input('Enter server name:')
# # Method 3: sys.argv
# import sys
# print('sys.argv = ', sys.argv)
# assert sys.argv[0] == __file__
# # help
# if len(sys.argv) != 4:
# print('Help:')
# print(f'{__file__} username password server_fqdn')
# sys.exit(1)
# # user_name = sys.argv[1]
# # password = sys.argv[2]
# # server_name = sys.argv[3]
# # unpacking
# user_name, password, server_name = sys.argv[1:]
# Method 4: argparse
import argparse
parser = argparse.ArgumentParser(
description="Details to login to server",
epilog='-----Please follow help doc ----')
# description: for the text that is shown before the help text
# epilog: for the text shown after the help text
parser.add_argument('-u', '--username',
help='login user name',
type=str,
required=True)
parser.add_argument('-p', '--password',
help='login password',
type=str,
required=True)
parser.add_argument('-s', '--servername',
help='server name',
type=str,
default='www.google.com',
required=False)
args = parser.parse_args()
user_name = args.username
password = args.password
server_name = args.servername
print(f'''
The server login details are:
USER NAME : {user_name}
PASSWORD : {password}
SERVER NAME : {server_name}
''')
| true |
2a202dd5ba552f4bda62adb4bfc92342d867d895 | umunusb1/PythonMaterial | /python2/04_Collections/01_Lists/02_lists.py | 1,791 | 4.59375 | 5 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
List can be classified as single-dimensional and multi-dimensional.
List is representing using [].
List is a mutable object, which means elements in list can be changed.
It can store asymmetric data types
"""
numbers = [88, 99, 666]
# homogenous
print 'type(numbers)', type(numbers)
print 'dir(numbers)=', dir(numbers)
print "len(numbers)=", len(numbers)
print "numbers.__len__()=", numbers.__len__()
print len(numbers) == numbers.__len__() # True
print "str(numbers) =", str(numbers)
print "type(str(numbers)) =", type(str(numbers))
print "numbers.__str__() =", numbers.__str__()
print "type(numbers.__str__())=", type(numbers.__str__())
# print "help(numbers)=", help(numbers)
print "numbers.__doc__=", numbers.__doc__
print "numbers * 3 =", numbers * 3 # original object not modified
print 'numbers =', numbers
print "numbers.__imul__(3) =", numbers.__imul__(3) # original object IS modified
print 'numbers =', numbers
print "id(numbers)=", id(numbers)
# object overwriting
numbers = [88, 99, 666]
print "id(numbers)=", id(numbers)
# list concatenation
print 'numbers\t\t\t\t=', numbers
alphabets = ['b', 'c']
print "numbers + alphabets\t\t=", numbers + alphabets
print 'numbers\t\t\t\t=', numbers
print "numbers.__add__(alphabets)\t=", numbers.__add__(alphabets)
print 'numbers\t\t\t\t=', numbers
# list concatenation will create new obect;
# orginal objects are not changed
print "numbers.__iadd__(alphabets)\t=", numbers.__iadd__(alphabets)
print 'numbers\t\t\t\t=', numbers # first object IS changed
print "numbers.__contains__(12) =", numbers.__contains__(12)
print "12 in numbers =", 12 in numbers
print numbers.__sizeof__()
# # print help(numbers.__sizeof__())
| true |
f74b9eacbdbf872d13578b2802622482f5cf0f28 | umunusb1/PythonMaterial | /python2/15_Regular_Expressions/re7/f1.py | 274 | 4.1875 | 4 | #!/usr/bin/python
import re
string = raw_input("please enter the name of the string:")
reg = re.compile('^.....$',re.DOTALL)
if reg.match(string):
print "our string is 5 character long - %s" %(reg.match(string).group())
else:
print "our string is not 5 characate long"
| true |
b6330d881e53e6df85ec6e4a3e31822d8166252e | umunusb1/PythonMaterial | /python2/07_Functions/practical/crazy_numbers.py | 832 | 4.65625 | 5 | #!python -u
"""
Purpose: Display the crazy numbers
Crazy number: A number whose digits are when raised to the power of the number of digits in that number and then added and if that sum is equal to the number then it is a crazy number.
Example:
Input: 123
Then, if 1^3 + 2^3 + 3^3 is equal to 123 then it is a crazy number.
"""
def crazy_num(n):
a = b = int(n)
c = 0 # 'c' is the var that stores the number of digits in 'n'.
s = 0 # 's' is the sum of the digits raised to the power of the num of digits.
while a != 0:
a = int(a / 10)
c += 1
while b != 0:
rem = int(b % 10)
s += rem ** c
b = int(b / 10)
if s == n:
print ("Crazy number.")
else:
print ("Not crazy number.")
return None
n = int(input("Enter number: "))
crazy_num(n)
| true |
dedb7dacef7ef63861c76784fc7cff84cf8ca616 | umunusb1/PythonMaterial | /python3/10_Modules/09_random/04_random_name_generator.py | 775 | 4.28125 | 4 | from random import choice
def random_name_generator(first, second, x):
"""
Generates random names.
Arguments:
- list of first names
- list of last names
- number of random names
"""
names = []
for i in range(x):
names.append("{0} {1}".format(choice(first), choice(second)))
return set(names)
first_names = ["Drew", "Mike", "Landon", "Jeremy", "Tyler", "Tom", "Avery"]
last_names = ["Smith", "Jones", "Brighton", "Taylor"]
names = random_name_generator(first_names, last_names, 5)
print('\n'.join(names))
# Assignment:
# In runtime, take the gender name as input, and generate random name.
# HINT: Take a dataset of female first names, and another with male first names
# one dataset with last names
| true |
8f6d1952edb0858a9f9c9b96c6719a1dd5fcb6d2 | umunusb1/PythonMaterial | /python2/08_Decorators/06_Decorators.py | 941 | 4.59375 | 5 | #!/usr/bin/python
"""
Purpose: decorator example
"""
def addition(num1, num2):
print('function -start ')
result = num1 + num2
print('function - before end')
return result
def multiplication(num1, num2):
print('function -start ')
result = num1 * num2
print('function - before end')
return result
print addition(12, 34)
print multiplication(12, 34)
print '\n===USING DECORATORS'
def print_statements(func):
def inner(*args, **kwargs):
print('function -start ')
# print 'In print_statemenst decorator', func
myresult = func(*args, **kwargs)
print('function - before end')
return myresult
return inner
@print_statements
def addition11111(num1, num2):
result = num1 + num2
return result
@print_statements
def multiplication1111(num1, num2):
result = num1 * num2
return result
print multiplication1111(12, 3)
print addition11111(12, 34)
| true |
df4858753ba98281c0dcef4e1cfc795d3e153ae3 | OmishaPatel/Python | /miscalgos/reverse_integer.py | 391 | 4.125 | 4 | import math
def reverse_integer(x):
if x > 0:
x= str(x)
x = x[::-1]
x = int(x)
else:
x = str(-x)
x = x[::-1]
x = -1 * int(x)
if x <= math.pow(2, 31) -1 and x >= math.pow(-2,31):
return x
return 0
x = 123
x1 = -123
print(reverse_integer(x))
print(reverse_integer(x1)) | true |
65ad7a18009d3595863f35760e7cc8f0ae78657d | OmishaPatel/Python | /datastructure/linked_list_insertion.py | 1,290 | 4.3125 | 4 | class Node:
def __init__(self,data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
def append(self,data):
new_node = Node(data)
#if it is beginning of list then insert new node
if self.head is None:
self.head = new_node
return
#traverse the list if head present to find the last node
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def prepend(self,data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def insert_after_node(self, prev_node, data):
if not prev_node:
print("Previous node not in the list")
return
new_node = Node(data)
new_node.next = prev_node.next
prev_node.next = new_node
linked_list = LinkedList()
linked_list.append("A")
linked_list.append("B")
linked_list.append("C")
linked_list.append("D")
linked_list.insert_after_node(linked_list.head.next, "E")
linked_list.print_list() | true |
3683f4b62501faa80cb0a67e3979cabe0fdc7e54 | ingoglia/python_work | /part1/5.2.py | 1,063 | 4.15625 | 4 | string1 = 'ferret'
string2 = 'mouse'
print('does ferret = mouse?')
print(string1 == string2)
string3 = 'Mouse'
print('is a Mouse a mouse?')
print(string2 == string3)
print('are you sure? Try again')
print(string2 == string3.lower())
print('does 3 = 2?')
print(3 == 2)
print('is 3 > 2?')
print(3 > 2)
print('is 3 >= 2?')
print(3 >= 2)
print("I don't think that 8 = 4")
print(8 != 4)
print('is 6 <= 8?')
print(6 <= 8)
print('is 5 < 3?')
print(5 < 3)
religion1 = 'christian'
belief1 = 'god'
religion = 'religion'
belief = 'belief'
print( 'is it the case that a christian is both a deity and a believer?')
print( 'christian' == 'christian' and 'christian' == 'god' )
print( 'is it the case that a christian is either a deity or a believer?')
print( 'christian' == 'christian' or 'christian' == 'god' )
fruits = ['banana', 'blueberry', 'raspberry', 'melon']
print('is there a banana?')
print('banana' in fruits)
print('is there a raspberry?')
print('raspberry' in fruits)
print('there are no strawberries are there.')
print('strawberries' not in fruits)
| true |
ebf65f149efb4a2adc6ff84d1dce2d2f61004ce4 | ingoglia/python_work | /part1/8.8.py | 633 | 4.375 | 4 | def make_album(artist, album, tracks=''):
"""builds a dictionary describing a music album"""
if tracks:
music = {'artist': artist, 'album':album, 'number of tracks':tracks}
else:
music = {'artist': artist, 'album':album}
return music
while True:
print("\nPlease tell me an artist and an album by them:")
print("(enter 'q' at any time to quit)")
user_artist = input("Name of artist: ")
if user_artist == 'q':
break
user_album = input("Name of album: ")
if user_album == 'q':
break
user_choice = make_album(user_artist,user_album)
print(user_choice)
| true |
b4a24b3ca29f09229589a58abfa8f0c9c4f3a094 | marcellenoukimi/CS-4308-CPL-Assignment-3 | /Student.py | 2,681 | 4.34375 | 4 | """
Student Name: Marcelle Noukimi
Institution: Kennesaw State University
College: College of Computing and Software Engineering
Department: Department of Computer Science
Professor: Dr. Sarah North
Course Code & Title: CS 4308 Concepts of Programming Languages
Section 01 Fall 2021
Date: October 13, 2021
Assignment 3: Develop a Python program. Define a class in Python and use it to create an object
and display its components. Define a Student class with the following components (attributes):
Name
Student number
Number of courses current semester
This class includes several methods: to change the values of these attributes, and to display
their values. Separately, the “main program” must:
• request the corresponding data from input and create a Student object.
• invoke a method to change the value of one of its attributes of the object
• invoke a method to that displays the value of each attribute.
"""
"""
This is the Student class with its components (attributes):
Name
Student number
Number of courses current semester
and the several methods to change the values of these attributes,
and to display their values.
"""
class Student:
"""
Implementation of student class
"""
def __init__(self, name, studentNumber, numberOfCourses):
"""
Constructor. Each student holds a Name, a Student number,
and a number of courses that he/she is taken during
this semester
"""
# Name of the student
self.StudentName = name
# Student number
self.StudentNumber = studentNumber
# Number of courses current semester
self.NumberOfCourses = numberOfCourses
"""
Various setter methods
"""
# Method to change the value of a student name
def setStudentName(self, name):
self.StudentName = name
# Method to change the value of a student number
def setStudentNumber(self, number):
self.StudentNumber = number
# Method to change the value of a student number of courses
# for the current semester
def setStudentNumberOfCourses(self, courses):
self.NumberOfCourses = courses
"""
Method to display the value of each attribute of a student
"""
def display(self):
# Print student details information
return "Student Name: " + self.StudentName + "\n Student Number: " \
+ self.StudentNumber + "\n Number Of Courses taken the current semester: " + self.NumberOfCourses
| true |
51e015545046b6411f88bcf969c22b69529464d3 | bigmoletos/WildCodeSchool_France_IOI-Sololearn | /soloearn.python/sololearn_pythpn_takeAshortCut_1.py | 1,353 | 4.375 | 4 | #Quiz sololearn python test take a shortcut 1
#https://www.sololearn.com/Play/Python
#raccouri level1
from _ast import For
x=4
x+=5
print (x)
#*************
print("test 2")
#What does this code do?
for i in range(10):
if not i % 2 == 0:
print(i+1)
#*************
print("test 3")
#What is the output of this code?
list = [1, 1, 2, 3, 5, 8, 13]
print(list[list[4]])
#*************
print("test 4")
#What does this code output?
letters = ['x', 'y', 'z']
letters.insert(1, 'w')
print(letters[2])
#*************
print("test 6")
#How many lines will this code print?
while False:
print("Looping...")
#*************
print("test 7")
#Fill in the blanks to define a function that takes two numbers as arguments and returns the smaller one.
def min(x, y):
if x<=y:
return x
else:
return y
#*************
print("test 8")
#Fill in the blanks to iterate over the list using a for loop and print its values.
list = [1, 2, 3]
for var in list:
print(var)
#*************
print("test 9")
#Fill in the blanks to print the first element of the list, if it contains even number of elements.
list = [1, 2, 3, 4]
if len(list) % 2 == 0:
print(list[0])
#*************
print("test 10")
#What is the output of this code?
def func(x):
res = 0
for i in range(x):
res += i
return res
print(func(5))
| true |
da0cd5a8d5ed63e56893410eec04ab7eb3df7cff | ARCodees/python | /Calculator.py | 458 | 4.21875 | 4 | print("this is a calculator It does all oprations but only with 2 numbers ")
opration = input("Enter your opration in symbolic way ")
print("Enter Your first number ")
n1 = int(input())
print("Enter Your second number ")
n2 = int(input())
if opration == "+":
print(n1 + n2)
elif opration == "-":
print(n1 - n2)
elif opration == "*":
print(n1 * n2)
elif opration == "/":
print(n1 / n2)
else:
print("illogical Input!!")
| true |
797cdc5d2c7d19a64045bc0fc1864fcefe0633b4 | carlmcateer/lpthw2 | /ex4.py | 1,065 | 4.25 | 4 | # The variable "car" is set to the int 100.
cars = 100
# The variable "space_in_a_car" is set to the float 4.0.
space_in_a_car = 4
# The variable "drivers" is set to the int 30.
drivers = 30
# The variable "passengers" is set to the int 90.
passengers = 90
# The variable cars_not_driven is set to the result of "cars" minus "drivers"
cars_not_driven = cars - drivers
# The variable "cars_driven" is set to the variable "drivers"
cars_driven = drivers
# The variable "carpool_capacity" is set to "cars_driven" times "space_in_a_car"
carpool_capacity = cars_driven * space_in_a_car
# The variable "average_passengers_per_car" is set to "passengers" devided by "cars_driven"
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars avaiable."
print "There are only", drivers, "drivers avaiable."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."
| true |
093233f29bfc50e37eb316fdffdf3a934aa5cea3 | manasjainp/BScIT-Python-Practical | /7c.py | 1,470 | 4.40625 | 4 | """
Youtube Video Link :- https://youtu.be/bZKs65uK1Eg
Create a class called Numbers, which has a single class attribute called
MULTIPLIER, and a constructor which takes the parameters x and y (these should
all be numbers).
i. Write a method called add which returns the sum of the attributes x and y.
ii. Write a class method called multiply, which takes a single number
parameter a and returns the product of a and MULTIPLIER.
iii. Write a static method called subtract, which takes two number parameters, b
and c, and returns b - c.
iv. Write a method called value which returns a tuple containing the values of x
and y. Make this method into a property, and write a setter and a deleter for
manipulating the values of x and y.
Save File as 7c.py
Run :- python 7c.py
"""
class Numbers:
MULTIPLIER=5
def __init__(self,x,y):
self.x=x
self.y=y
#subpart-1
def add(self):
return self.x + self.y
#subpart-2
@classmethod
def multiply(cls,a):
return cls.MULTIPLIER * a
#subpart-3
@staticmethod
def substract(b,c):
return b-c
#subpart-4
@property
def value(self):
return(self.x, self.y)
@value.setter
def value(self, t):
self.x = t[0]
self.y = t[1]
@value.deleter
def value(self):
self.x=None
self.y=None
ob=Numbers(10,20)
print("Add :- ",ob.add())
print("Multiply :- ", Numbers.multiply(10))
print("Substract :- ", Numbers.substract(20,10))
ob.value=(100,200)
print("Add :- ", ob.add())
del ob.value
print("Values :- ",ob.value)
| true |
d916840b3ec5c3efbb4ee0b1c1aea1ad42844d66 | omushpapa/minor-python-tests | /Large of three/large_ofThree.py | 778 | 4.40625 | 4 | #!/usr/bin/env python2
#encoding: UTF-8
# Define a function max_of_three()
# that takes three numbers as arguments
# and returns the largest of them.
def max_of_three(num1, num2, num3):
if type(num1) is not int or type(num2) is not int or type(num3) is not int:
return False
num_list = [num1, num2, num3]
temp = 0
if num1 == num2 == num3:
return num3
for i in range(len(num_list) - 1):
if num_list[i] < num_list[i + 1]:
temp = num_list[i + 1]
return temp
def main():
value1 = input("Enter first value: ")
value2 = input("Enter second value: ")
value3 = input("Enter third value: ")
print max_of_three(value1, value2, value3)
if __name__ == "__main__":
print "Hello World"
| true |
e6134ced3a1fc1b67264040e64eba2af21ce8e1d | omushpapa/minor-python-tests | /List Control/list_controls.py | 900 | 4.15625 | 4 | #!/usr/bin/env python2
#encoding: UTF-8
# Define a function sum() and a function multiply()
# that sums and multiplies (respectively) all the numbers in a list of numbers.
# For example, sum([1, 2, 3, 4]) should return 10, and
# multiply([1, 2, 3, 4]) should return 24.
def sum(value):
if type(value) is not list:
return False
summation = 0
for i in value:
if type(i) is not int:
return False
summation = summation + i
return summation
def multiply(value):
if type(value) is not list:
return False
result = 1
for i in value:
if type(i) is not int:
return False
result = result * i
return result
def main():
ans = input("Enter values in list: ")
print sum(ans)
print multiply(ans)
if __name__ == "__main__":
main()
| true |
6c58ca9f940f7ab15d3b99f27217b3bd485b01f9 | omushpapa/minor-python-tests | /Operate List/operate_list.py | 1,301 | 4.1875 | 4 | # Define a function sum() and a function multiply()
# that sums and multiplies (respectively) all the numbers in a list of numbers.
# For example, sum([1, 2, 3, 4]) should return 10,
# and multiply([1, 2, 3, 4]) should return 24.
def check_list(num_list):
"""Check if input is list"""
if num_list is None:
return False
if len(num_list) == 0:
return False
new_list = []
for i in num_list:
if i!='[' and i!=']' and i!=',':
new_list.append(i)
for x in new_list:
if type(x) != int:
return False
return True
def sum(num_list):
"""Compute sum of list values"""
if check_list(num_list):
final_sum = 0
for i in num_list:
final_sum = final_sum + i
return final_sum
else:
return False
def multiply(num_list):
"""Multiply list values"""
if check_list(num_list):
final_sum = 1
for i in num_list:
final_sum = final_sum * i
return final_sum
else:
return False
def main():
get_list = input("Enter list: ")
operations = [sum, multiply]
print map(lambda x: x(get_list), operations)
if __name__ == "__main__":
main()
| true |
a193124758fc5b01168757d0f98cf67f9b98c664 | omushpapa/minor-python-tests | /Map/maps.py | 388 | 4.25 | 4 | # Write a program that maps a list of words
# into a list of integers representing the lengths of the correponding words.
def main():
word_list = input("Enter a list of strings: ")
if type(word_list) != list or len(word_list) == 0 or word_list is None:
print False
else:
print map(lambda x: len(x), word_list)
if __name__ == "__main__":
main() | true |
96f5fbe27bf7bd62b365d50f0266ce8297042094 | amanotk/pyspedas | /pyspedas/dates.py | 1,592 | 4.15625 | 4 | # -*- coding: utf-8 -*-
"""
File:
dates.py
Description:
Date functions.
"""
import datetime
import dateutil.parser
def validate_date(date_text):
# Checks if date_text is an acceptable format
try:
return dateutil.parser.parse(date_text)
except ValueError:
raise ValueError("Incorrect data format, should be yyyy-mm-dd: '"
+ date_text + "'")
def get_date_list(date_start, date_end):
"""Returns a list of dates between start and end dates"""
d1 = datetime.date(int(date_start[0:4]), int(date_start[5:7]),
int(date_start[8:10]))
d2 = datetime.date(int(date_end[0:4]), int(date_end[5:7]),
int(date_end[8:10]))
delta = d2 - d1
ans_list = []
for i in range(delta.days + 1):
ans_list.append(str(d1 + datetime.timedelta(days=i)))
return ans_list
def get_dates(dates):
"""Returns a list of dates
date format: yyyy-mm-dd
input can be a single date or a list of two (start and end date)
"""
ans_list = []
if not isinstance(dates, (list, tuple)):
dates = [dates]
if len(dates) == 1:
try:
validate_date(dates[0])
ans_list = dates
except ValueError as e:
print(e)
ans_list = []
elif len(dates) == 2:
try:
validate_date(dates[0])
validate_date(dates[1])
ans_list = get_date_list(dates[0], dates[1])
except ValueError as e:
print(e)
ans_list = []
return ans_list
| true |
5e0ca56488a3cda328eb88bd0a1fdd7ba6cb2bb8 | sreckovicvladimir/hexocin | /sqlite_utils.py | 1,702 | 4.125 | 4 | import sqlite3
from sqlite3 import Error
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
def create_table(conn):
""" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
"""
sql = """ CREATE TABLE IF NOT EXISTS data_points (
n integer NOT NULL,
p integer NOT NULL,
data text NOT NULL
); """
try:
c = conn.cursor()
c.execute(sql)
except Error as e:
print(e)
def populate_table(conn, row):
"""
Create a new project into the projects table
:param conn:
:param project:
:return: project id
"""
sql = ''' INSERT INTO data_points(n,p,data)
VALUES(?,?,?) '''
cur = conn.cursor()
cur.execute(sql, row)
conn.commit()
return cur.lastrowid
def select_row(conn, n, p):
"""
Return single row from data_points table
:param conn: the Connection object
:return:
"""
cur = conn.cursor()
cur.execute("SELECT data FROM data_points where n=%d and p=%d" % (n, p))
query = cur.fetchone()
if query == None:
raise ValueError("Something went wrong, probably arguments out of range or the db isn't properly populated")
return query[0]
| true |
04da350a513c7cc103b948765a1a24b9864686e1 | JayHennessy/Stack-Skill-Course | /Python_Intro/pandas_tutorial.py | 631 | 4.28125 | 4 | # Python Pandas tutorial (stackSkill)
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import style
data = pd.read_csv('C:/Users/JAY/Desktop/Machine_Learning_Course/KaggleCompetions/titanic_comp/data/test.csv')
# shows data on screen
print(data.head())
data.tail()
#print the number of rows (incldues the header)
print(len(data.index))
# return rows that meet a certain condition
# here we get the date value for all the days that have rain in the event column
rainy_days = data['Date'][df['Events']=='Rain']
# plot the results with matplotlib
style.use('classic')
data['Max.TemperatureC'].plot()
plt.show() | true |
f62bd2ec440e3929c5aee99d0b90fd726e3f3eff | aniket0106/pdf_designer | /rotatePages.py | 2,557 | 4.375 | 4 | from PyPDF2 import PdfFileReader,PdfFileWriter
# rotate_pages.py
"""
rotate_pages() -> takes three arguements
1. pdf_path : in this we have to pass the user pdf path
2. no_of_pages : in this we have to pass the number of pages we want to rotate if all then by
default it takes zero then we re-intialize it to total number of pages
3. clockwise : it is default args which take boolean value if its value is True then it
will right rotate by given angle
if it is false then it will rotate towards the left by given angle
getNumPages() : is the function present in the PyPDF2 which is used to get the total number
of page present inside the inputted pdf
getPage(i) : is the function which return the particular page for the specified pdf
rotateClockwise(angle) : is the function which rotate the specified page by given angle
towards to right
rotateCounterClockwise(angle) : is the function which rotate the specified page by given angle
towards the left
"""
def rotate_pages(pdf_path,no_of_pages=0,clockwise=True):
# creating the instance of PdfFileWriter we have already initialize it with our output file
pdf_writer = PdfFileWriter()
pdf_reader = PdfFileReader(pdf_path)
total_pages = pdf_reader.getNumPages()
if no_of_pages == 0:
no_of_pages = total_pages
if clockwise:
for i in range(no_of_pages):
page = pdf_reader.getPage(i).rotateClockwise(90)
pdf_writer.addPage(page)
with open('rotate_pages.pdf', 'wb') as fh:
pdf_writer.write(fh)
for i in range(no_of_pages,total_pages):
page = pdf_reader.getPage(i)
pdf_writer.addPage(page)
with open('rotate_pages.pdf', 'wb') as fh:
pdf_writer.write(fh)
else:
for i in range(no_of_pages):
page = pdf_reader.getPage(i).rotateCounterClockwise(90)
pdf_writer.addPage(page)
with open('rotate_pages.pdf', 'wb') as fh:
pdf_writer.write(fh)
for i in range(no_of_pages,total_pages):
page = pdf_reader.getPage(i)
pdf_writer.addPage(page)
with open('rotate_pages.pdf', 'wb') as fh:
pdf_writer.write(fh)
"""
f=FileWriter("rotate_pages.pdf","wb")
pdf_writer = PdfWriter(f)
pdf_writer.write()
"""
if __name__ == '__main__':
path = 'F:\pdf\ex1.pdf'
rotate_pages(path,no_of_pages=10,clockwise=True) | true |
e340d8b94dc7c2f32e6591d847d8778ed5b5378b | liorkesten/Data-Structures-and-Algorithms | /Algorithms/Arrays_Algorithms/isArithmeticProgression.py | 666 | 4.3125 | 4 | def is_arithmetic_progression(lst):
"""
Check if there is a 3 numbers that are arithmetic_progression.
for example - [9,4,1,2] return False because there is not a sequence.
[4,2,7,1] return True because there is 1,4,7 are sequence.
:param lst: lst of diff integers
:return: True or False if there is a 3 sequence in the lst.
"""
set_of_values = set(lst)
# Check if there is 3 monotony
for i in range(len(lst)):
for j in range(i + 1, len(lst)):
third_num = abs(lst[i] - lst[j]) + max(lst[i], lst[j])
if third_num in set_of_values:
return True
return False
| true |
6101f3df70700db06073fd8e3723dba00a02e9d9 | liorkesten/Data-Structures-and-Algorithms | /Algorithms/Arrays_Algorithms/BinarySearch.py | 577 | 4.21875 | 4 | def binary_search_array(lst, x):
"""
Get a sorted list in search if x is in the array - return true or false.
Time Complexity O(log(n))
:param lst: Sorted lst
:param x: item to find
:return: True or False if x is in the array
"""
if not lst:
return False
if len(lst) == 1:
return x == lst[0]
mid = len(lst) // 2
if lst[mid] == x:
return True
elif lst[mid] < x:
return binary_search_array(lst[mid + 1:], x)
elif lst[mid] > x:
return binary_search_array(lst[:mid], x) | true |
a0e52ed563d1f26e274ef1aece01794cce581323 | samanthaWest/Python_Scripts | /DataStructsAndAlgorithms/TwoPointersTechnique.py | 784 | 4.3125 | 4 | # Two Pointers
# https://www.geeksforgeeks.org/two-pointers-technique/
# Used for searching for pairs in a sorted array
# We take two pointers one representing the first element and the other representing the last element
# we add the values kept at both pointers, if their sum is smaller then target we shift left pointer to the
# right. If sum is larger then target we shift right pointer to the left till be get closer to the sum.
def isPairSum(arr, lenghtArray, target):
l = 0 # first pointer
r = lenghtArray - 1 # second pointer
while l < r:
curSum = numbers[l] + numbers[r]
if curSum > target:
r -= 1
elif curSum < target:
l += 1
else:
return [l + 1, r + 1]
| true |
9a02e277ab565469ef0d3b768b7c9a0c053c2545 | JamesRoth/Precalc-Programming-Project | /randomMulti.py | 554 | 4.125 | 4 | #James Roth
#1/31/19
#randomMulti.py - random multiplication problems
from random import randint
correctAns = 0
while correctAns < 5: #loop until 5 correct answers are guessed
#RNG
num1 = randint(1,10)
num2 = randint(1,10)
#correct answer
ans = num1*num2
#asking the user to give the answer to the multiplication problem
guess = int(input("What is "+str(num1)+"*"+str(num2)+"? "))
#did they get it right?
if guess == ans:
correctAns+=1
else:
print("Incorrect! The correct answer is: "+str(ans))
| true |
ddda27bf9906caf8916deb667639c8e4d052a05f | AXDOOMER/Bash-Utilities | /Other/Python/parse_between.py | 918 | 4.125 | 4 | #!/usr/bin/env python
# Copyright (c) Alexandre-Xavier Labonte-Lamoureux, 2017
import sys
import numbers
# Parser
def parse(textfile):
myfile = open(textfile, "r")
datastring = myfile.read()
first_delimiter = '\"'
second_delimiter = '\"'
index = 0
while(index < len(datastring)):
first = datastring.find(first_delimiter, index, len(datastring))
if (first == -1):
break;
second = datastring.find(second_delimiter, first + len(first_delimiter), len(datastring))
if (second == -1):
break;
index = second + len(second_delimiter);
foundstring = datastring[first + len(first_delimiter):second]
if (len(foundstring) > 0 and not foundstring.isdigit()):
print(foundstring)
quit()
def main():
if len(sys.argv) < 2:
print("No enough arguments. How to use:")
print("parse_between.py [FILE]")
quit()
textfile = sys.argv[1]
# Parsing function
parse(textfile)
# Do stuff
if __name__ == "__main__":
main()
| true |
49c33bb519c6142f0832435d2a66054baceadf1a | cmedinadeveloper/udacity-data-structures-algorithms-project1-unscramble | /Task1.py | 666 | 4.25 | 4 | """
Read file into texts and calls.
It's ok if you don't understand how to read files.
"""
import csv
phone_nums = []
with open('texts.csv', 'r') as f:
reader = csv.reader(f)
for text in list(reader):
phone_nums.extend(text[:2])
with open('calls.csv', 'r') as f:
reader = csv.reader(f)
for call in list(reader):
phone_nums.extend(call[:2])
"""
TASK 1:
How many different telephone numbers are there in the records?
Print a message:
"There are <count> different telephone numbers in the records."
"""
phone_nums = list(set(phone_nums))
print(("There are {} different telephone numbers in the records.").format(len(phone_nums)))
| true |
f150c2160c0c5b910fde7e3a05c40fc26e3c213c | HopeFreeTechnologies/pythonbasics | /variables.py | 1,419 | 4.125 | 4 | #So this file has some examples of variables, how they work, and more than just one output (like hi there.py did).
#######################
#
#Below is a variable by the name vname. V for variable and name for, well name.
# Its my first ever variable in Python so by default it's awesome, so i let it know by giving it the value (in the form of a string) awesome lol
#. Note as well that to assign a string to a variable it must still be notated as such eith quotations ^^;
#
#######################
vname = "awesome"
print(vname)
#######################
#
#Variables also have the nifty feature of being capable of changing their assigned value whenever the need arises.
#One of the simplest ways of accomplishing this task is to simply redefine aforementioned value later on inside the same file.
#Like, literally. It can even be immediately following the first value being assigned to it haha
#
#######################
vname = "having all the fun!"
print(vname)
#######################
#
#When the file is compiled (now that the block above has been added) you can see that vname isnt awesome but having all the fun by the second line of output!
#Of course vname can always be awesome again; although you'll have to give it a hand here by running the file a second (or more) time(s) lol
#At their base this is how variables are used. In their simplest format anyways ♡
#
#######################
#~ Hope Currey | true |
d22a954c0a50eb89bd5c24f37cf69a53462e1d0c | dinabseiso/HW01 | /HW01_ex02_03.py | 1,588 | 4.1875 | 4 | # HW01_ex02_03
# NOTE: You do not run this script.
# #
# Practice using the Python interpreter as a calculator:
# 1. The volume of a sphere with radius r is 4/3 pi r^3.
# What is the volume of a sphere with radius 5? (Hint: 392.7 is wrong!)
# volume: 523.3
r = 5
pi = 3.14
volume = (4 * pi * r**3) / 3
print(volume)
# 2. Suppose the cover price of a book is $24.95, but bookstores get a
# 40% discount. Shipping costs $3 for the first copy and 75 cents for
# each additional copy. What is the total wholesale cost for 60 copies?
# total wholesale cost: 945.45
discountedPrice = 24.95 * 0.60
firstShippingCost = 3
additionalShippingCost = 0.75
n = 60
firstCopyPrice = discountedPrice + firstShippingCost
additionalCopyPrice = (additionalShippingCost + discountedPrice) * (n-1)
wholesaleCost = firstCopyPrice + additionalCopyPrice
print(wholesaleCost)
# 3. If I leave my house at 6:52 am and run 1 mile at an easy pace
# (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy
# pace again, what time do I get home for breakfast?
# time:
startHour = 6
startHourToSeconds = startHour * 3600.0
startMinutes = 52.0
startMinutesToSeconds = startMinutes * 60
convertToOneHundred = 100.0 / 60
startTime = ( startHourToSeconds + startMinutesToSeconds ) * convertToOneHundred
print(startTime)
beginningRun = 1 * (8 + (15/60) ) * 60
middleRun = 3 * (7+(12/60)) * 60
endRun = 1 * (8 + (15/60)) * 60
totalRunTime = (beginningRun + middleRun + endRun )
breakfast = (( startTime + totalRunTime ) / 3600.0) * (60/100.0)
breakfast = round(breakfast, 2)
print(breakfast) | true |
b3c9b758ea0b683aa4762a1e8e30bfffb2074a00 | spsree4u/MySolvings | /trees_and_graphs/mirror_binary_tree.py | 877 | 4.21875 | 4 |
"""
Find mirror tree of a binary tree
"""
class Node:
def __init__(self, data):
self.data = data
self.left = self.right = None
def mirror(root):
if not root:
return
mirror(root.left)
mirror(root.right)
temp = root.left
root.left = root.right
root.right = temp
def in_order(root):
if not root:
return
in_order(root.left)
print(root.data)
in_order(root.right)
root1 = Node(1)
root1.left = Node(2)
root1.right = Node(3)
root1.left.left = Node(4)
root1.left.right = Node(5)
""" Print inorder traversal of
the input tree """
print("Inorder traversal of the",
"constructed tree is")
in_order(root1)
""" Convert tree to its mirror """
mirror(root1)
""" Print inorder traversal of
the mirror tree """
print("\nInorder traversal of",
"the mirror treeis ")
in_order(root1)
| true |
f29923bcb48d0f6fd0ea61207249f57ca0a69c6a | spsree4u/MySolvings | /trees_and_graphs/post_order_from_pre_and_in.py | 1,526 | 4.21875 | 4 |
# To get post order traversal of a binary tree from given
# pre and in-order traversals
# Recursive function which traverse through pre-order values based
# on the in-order index values for root, left and right sub-trees
# Explanation in https://www.youtube.com/watch?v=wGmJatvjANY&t=301s
def print_post_order(start, end, p_order, p_index, i_index_map):
# base case
if start > end:
return p_index
# get value for current p_index for updating p_index value
val = p_order[p_index]
p_index += 1
# Print value if retrieved value is of a leaf as there is no more child
if start == end:
print(val)
return p_index
# If not leaf node, get root node index from in-order map
# corresponding to value to call recursively for sub-trees
i = i_index_map[val]
p_index = print_post_order(start, i-1, p_order, p_index, i_index_map)
p_index = print_post_order(i+1, end, p_order, p_index, i_index_map)
# Print value of root node as subtrees are traversed
print(val)
return p_index
def get_post_order(in_order, pre_order):
in_order_index_map = {}
tree_size = len(in_order)
# dictionary to store the indices of in-order travel sequence
# O(n) time and O(n) space is required for the hash map
for n in range(tree_size):
in_order_index_map[in_order[n]] = n
pre_index = 0
print_post_order(0, tree_size-1, pre_order, pre_index, in_order_index_map)
get_post_order([4, 2, 1, 7, 5, 8, 3, 6], [1, 2, 4, 3, 5, 7, 8, 6])
| true |
965e5afce19c0ab3dcaf484bdafa554dd4d51e4d | spsree4u/MySolvings | /trees_and_graphs/super_balanced_binary_tree.py | 2,240 | 4.125 | 4 | """
Write a function to see if a binary tree is "super-balanced".
A tree is "super-balanced" if the difference between the depths of any two
leaf nodes is no greater than one.
Complexity
O(n) time and O(n) space.
"""
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def add_left(self, value):
self.left(Node(value))
return self.left
def add_right(self, value):
self.right(Node(value))
return self.right
def is_super_balanced(root):
if not root:
return True
depths = list()
visited = list()
visited.append((root, 0))
while len(visited):
node, depth = visited.pop()
# If leaf
if (not node.left) and (not node.right):
# If already visited depth
if depth not in depths:
depths.append(depth)
# Two ways we might now have an unbalanced tree:
# 1) more than 2 different leaf depths
# 2) 2 leaf depths that are more than 1 apart
if (len(depths) > 2) or \
(len(depths) == 2 and abs(depths[0]-depths[1]) > 2):
return False
else:
if node.left:
visited.append((node.left, depth+1))
if node.right:
visited.append((node.right, depth+1))
return True
def is_balanced(root):
# Time O(n), Space O(1)
if not root:
return 0
return 1 + abs(is_balanced(root.left) - is_balanced(root.right))
# Balanced tree
root1 = Node(1)
root1.left = Node(2)
root1.right = Node(3)
root1.left.left = Node(4)
root1.left.right = Node(5)
root1.right.left = Node(6)
# root1.right.right = Node(8)
root1.left.left.left = Node(7)
print("SuperBalanced") if is_super_balanced(root1) else print("Unbalanced")
print("Balanced") if is_balanced(root1) == 1 else print("Unbalanced")
# Unbalanced tree
root2 = Node(1)
root2.left = Node(2)
root2.right = Node(3)
root2.left.left = Node(4)
root2.left.right = Node(5)
root2.left.left.left = Node(8)
print("SuperBalanced") if is_super_balanced(root2) else print("Unbalanced")
print("Balanced") if is_balanced(root2) == 1 else print("Unbalanced")
| true |
3e92fa31734cdd480a102553fda5134de7aed2ba | aryansamuel/Python_programs | /jumble.py | 819 | 4.375 | 4 | # Aryan Samuel
# arsamuel@ucsc.edu
# prgramming assignment 6
# The following program asks the user for a jumbled word,
# then unjumbles and prints it.
# Note: The unjumbled word should be in the dictionary that is read by the prog.
def main(file):
file = open(file,'r')
word_list = file.read().split()
real_word = []
wordx = input('Please enter a jumbled word: ')
word_l = wordx.lower()
for word in word_list:
if sorted(word) == sorted(word_l):
real_word.append(word)
if len(real_word) < 1:
print('Your word cannot be unjumbled.')
if len(real_word) == 1:
print('Your word is %s.' %real_word[0])
if len(real_word) > 1:
print('Your words are: ')
for i in range(len(real_word)):
print(real_word[i])
main()
| true |
203e35f62d3a64a25c87b1f88f8ba9b7ad33c112 | Shobhits7/Programming-Basics | /Python/factorial.py | 411 | 4.34375 | 4 | print("Note that facotrial are of only +ve integers including zero\n")
#function of facorial
def factorial_of(number):
mul=1
for i in range(1,num+1):
mul=mul*i
return mul
#take input of the number
num=int(input("Enter the number you want the fatcorial of:"))
#executing the function
if num<0 :
print("Not possible")
else:
print("Factorial of ",num," is ",factorial_of(num))
| true |
e98f42af716c60f62e9929ed5fa9660b3a1d678a | Shobhits7/Programming-Basics | /Python/palindrome.py | 364 | 4.46875 | 4 | # First we take an input which is assigned to the variable "text"
# Then we use the python string slice method to reverse the string
# When both the strings are compared and an appropriate output is made
text=input("Enter the string to be checked: ")
palindrom_text= text[::-1]
if text==palindrom_text:
print("Palindrome")
else:
print("Not Palindrome")
| true |
1b2ec70312c8bf5d022cf2832fb3dfbf93c0d0f2 | Shobhits7/Programming-Basics | /Python/fibonacci_series.py | 1,110 | 4.40625 | 4 | # given a variable n (user input), the program
# prints fibinacci series upto n-numbers
def fibonacci(n):
"""A simple function to print fibonacci sequence of n-numbers"""
# check if n is correct
# we can only allow n >=1 and n as an integer number
try:
n = int(n)
except ValueError:
raise TypeError("fibonacci series is only available for n-digits, where n is an integer, and n >= 1")
if n < 1:
raise ValueError("fibonacci series is only available for n-digits, where n is an integer, and n >= 1")
# when we are assured that the value of n is correct,
# we can find the fibonacci sequence
# and finally return it as a string seperated by space
if n == 1:
series = [0]
elif n == 2:
series = [0, 1]
else:
series = [0, 1]
for _ in range(n - 2):
series.append(sum(series[-2:]))
return " ".join(map(str, series))
if __name__ == "__main__":
n = input("Enter the Number of Elements of Fibonacci Series (n >= 1, and type(n) = int): ")
print(fibonacci(n))
| true |
537bfed643c059426bc9303f369efb0e1a9cc687 | MS642/python_practice | /objects/objects.py | 1,445 | 4.28125 | 4 | class Line:
"""
Problem 1 Fill in the Line
class methods to accept coordinates as a pair of tuples and return the slope and distance of the line.
# EXAMPLE OUTPUT
coordinate1 = (3, 2)
coordinate2 = (8, 10)
li = Line(coordinate1, coordinate2)
li.distance()
9.433981132056603
li.slope()
1.6
"""
def __init__(self, point_1, point_2):
self.point_1 = point_1
self.point_2 = point_2
def distance(self):
x1, y1 = self.point_1
x2, y2 = self.point_2
return ((x1 - x2)**2 + (y1 - y2)**2)**0.5
def slope(self):
x1, y1 = self.point_1
x2, y2 = self.point_2
return (y2 - y1) / (x2 - x1)
coord_1 = (3, 2)
coord_2 = (8, 10)
li = Line(coord_1, coord_2)
assert li.distance() == 9.433981132056603
assert li.slope() == 1.6
class Cylinder:
"""
Problem 2
# EXAMPLE OUTPUT
c = Cylinder(2,3)
c.volume()
56.52
c.surface_area()
94.2
"""
pi = 3.14
def __init__(self, height=1, radius=1):
self.height = height
self.radius = radius
def volume(self):
return self.pi * self.height * self.radius**2
def surface_area(self):
return 2 * self.pi * self.radius * self.height + 2 * self.pi * self.radius**2
c = Cylinder(2, 3)
assert c.volume() == 56.52
assert c.surface_area() == 94.2
| true |
22202840ae1c77f10c7e1f301ec5c0262b92e4e3 | lucasflosi/Assignment2 | /nimm.py | 2,011 | 4.40625 | 4 | """
File: nimm.py
-------------------------
Nimm is a 2 player game where a player can remove either 1 or 2 stones. The player who removes the
last stone loses the game!
"""
STONES_IN_GAME = 20 #starting quantity for stones
def main():
stones_left = STONES_IN_GAME
player_turn = 1
while stones_left > 0:
if stones_left != STONES_IN_GAME:
print("") #prints a blank on turns after the first turn
print("There are " + str(stones_left) + " stones left")
stones_removed = int(input("Player " + str(player_turn) +" would you like to remove 1 or 2 stones? "))
while input_is_invalid(stones_removed) == False:
stones_removed = int(input("Please enter 1 or 2: "))
while taking_more_stones_than_exists(stones_left,stones_removed) == True:
print("There is only 1 stone left. You cannot remove 2 stones")
stones_removed = int(input("Player " + str(player_turn) +" would you like to remove 1 or 2 stones? "))
stones_left -= stones_removed
player_turn = switch_player(player_turn)
print("")
print("Player " + str(player_turn) + " wins!")
def input_is_invalid(user_turn):
if user_turn == 1 or user_turn == 2:
return True
else:
return False
def taking_more_stones_than_exists(num_stones_left,stones_user_wants_to_remove):
if num_stones_left < stones_user_wants_to_remove:
return True
else:
return False
def switch_player(player_turn):
if player_turn == 1:
new_player_turn = 2
if player_turn == 2:
new_player_turn = 1
return new_player_turn
"""
You should write your code for this program in this function.
Make sure to delete the 'pass' line before starting to write
your own code. You should also delete this comment and replace
it with a better, more descriptive one.
"""
# This provided line is required at the end of a Python file
# to call the main() function.
if __name__ == '__main__':
main()
| true |
e6d7b94ab9ee72d64ee17dee3db7824653bd5c51 | mgyarmathy/advent-of-code-2015 | /python/day_12_1.py | 1,078 | 4.1875 | 4 | # --- Day 12: JSAbacusFramework.io ---
# Santa's Accounting-Elves need help balancing the books after a recent order. Unfortunately, their accounting software uses a peculiar storage format. That's where you come in.
# They have a JSON document which contains a variety of things: arrays ([1,2,3]), objects ({"a":1, "b":2}), numbers, and strings. Your first job is to simply find all of the numbers throughout the document and add them together.
# For example:
# [1,2,3] and {"a":2,"b":4} both have a sum of 6.
# [[[3]]] and {"a":{"b":4},"c":-1} both have a sum of 3.
# {"a":[-1,1]} and [-1,{"a":1}] both have a sum of 0.
# [] and {} both have a sum of 0.
# You will not encounter any strings containing numbers.
# What is the sum of all numbers in the document?
import sys
import re
def main():
input_file = sys.argv[1]
json_string = open(input_file, 'r').read()
print int(sum_json_numbers_regex(json_string))
def sum_json_numbers_regex(json_string):
return sum(int(num) for num in re.findall('-?\d+', json_string))
if __name__ == '__main__':
main() | true |
040fcf183a0db97e0e341b7a3e9fec2f8adf24eb | BlueMonday/advent_2015 | /5/5.py | 1,778 | 4.15625 | 4 | #!/usr/bin/env python3
import re
import sys
VOWELS = frozenset(['a', 'e', 'i', 'o', 'u'])
NICE_STRING_MIN_VOWELS = 3
INVALID_SEQUENCES = frozenset(['ab', 'cd', 'pq', 'xy'])
def nice_string_part_1(string):
"""Determines if ``string`` is a nice string according to the first spec.
Nice strings contain at least ``NICE_STRING_MIN_VOWELS`` vowels, one
character that appears twice in a row, and do not contain any of the
invalid sequences.
"""
vowel_count = 0
duplicate_sequential_character = False
for i in range(len(string)):
if string[i] in VOWELS:
vowel_count += 1
if i < len(string) - 1:
if string[i] == string[i+1]:
duplicate_sequential_character = True
if string[i:i+2] in INVALID_SEQUENCES:
return False
return (duplicate_sequential_character and
vowel_count >= NICE_STRING_MIN_VOWELS)
def nice_string_part_2(string):
"""Determines if ``string`` is a nice string according to the second spec.
Nice strings contain two letters that appears at least twice in the string
without overlapping and at least one letter which repeats with exactly one
letter between them.
"""
return (re.search(r'(\w\w).*\1', string) and
re.search(r'(\w)(?!\1)\w\1', string))
if __name__ == '__main__':
with open(sys.argv[1]) as f:
strings = [line.strip() for line in f.readlines()]
nice_strings_part_1 = 0
nice_strings_part_2 = 0
for string in strings:
print(string)
if nice_string_part_1(string):
nice_strings_part_1 += 1
if nice_string_part_2(string):
nice_strings_part_2 += 1
print(nice_strings_part_1)
print(nice_strings_part_2)
| true |
10a4575fc55bc35c004b6ca826f7b50b9d269855 | jackedjin/README.md | /investment.py | 579 | 4.1875 | 4 | def calculate_apr():
"Calculates the compound interest of an initial investment of $500 for over 65 years"
principal=500
interest_rate=0.03
years=0
while years<65:
"While loop used to repeat the compounding effect of the investment 65 times"
principal=principal*(1+interest_rate)
"compound interest calculation"
print(f'Afer year {years}, the new principal is {principal}')
years+=1
'''counter which automatically adds 1 into integer variable years until
it reaches 65'''
print(f'On the {years}th year, the principal has become {principal}')
calculate_apr()
| true |
f44cda077b7939465d6add8a9e845b3f72bc03c2 | NSLeung/Educational-Programs | /Python Scripts/python-syntax.py | 1,166 | 4.21875 | 4 | # This is how you create a comment in python
# Python equivalent of include statement
import time
# Statements require no semicolon at the end
# You don't specify a datatype for a variable
franklin = "Texas Instruments"
# print statement in python
print (franklin)
# You can reassign a variable any datatype you want
# this will make the variable a decimal
franklin = 1.0
# You can concatnate seperate strings by adding the + symbol between them
# To convert a number to a string use the str function
print ("Printing number " + str(franklin))
# If statements end with colon
if franklin == 1.0:
# Lines under a if statement, loop or function must be indented.
# The indentation mimics what curly brackets are used for in other languages
print("Franklin equals 1.0")
# Syntax for else if. Also includes colon
elif franklin == 2.0:
print("Franklin equals 2.0")
# Syntax for else statement. Also includes colon
else:
print("Unknock value for Franklin")
# Its True and False. TRUE/FALSE or true/false will not work
if True == True:
print ("True is indeed True")
if False == False:
print ("False is indeed False")
| true |
dc7b6fdbee9d6a43089e7e1bccadd98deb2d7efc | Mezz403/Python-Projects | /LPTHW/ex16.py | 592 | 4.25 | 4 | from sys import argv # Unpack arguments entered by the user
script, filename = argv # unpack entered arguments into script and filename
txt = open(filename) # open the provided filename and assign to txt
print "Here's your file %r: " % filename # display filename to user
print txt.read() # print the contexts of the file to screen
print "Type the filename again:" # ask for the filename again
file_again = raw_input("> ") # save user input to variable
txt_again = open(file_again) # open the file
print txt_again.read() # print contents of file to screen
txt.close()
txt_again.close() | true |
0b7f5b3f5e1b5e5d4bd88c37000bbfa0843af2bd | rachelsuk/coding-challenges | /compress-string.py | 1,129 | 4.3125 | 4 | """Write a function that compresses a string.
Repeated characters should be compressed to one character and the number of
times it repeats:
>>> compress('aabbaabb')
'a2b2a2b2'
If a character appears once, it should not be followed by a number:
>>> compress('abc')
'abc'
The function should handle letters, whitespace, and punctuation:
>>> compress('Hello, world! Cows go moooo...')
'Hel2o, world! Cows go mo4.3'
"""
def compress(string):
"""Return a compressed version of the given string."""
new_str = string[0]
#new_str = "Hel2o"
current = string[0]
#current = "o"
nums = set("0123456789")
for char in string[1:]:
#char = o
if char == current:
if new_str[-1] in nums:
new_str = new_str[:-1] + str(int(new_str[-1]) + 1)
else:
new_str = new_str + "2"
else:
new_str = new_str + char
current = char
return new_str
compress("Hello, world! Cows go moooo...")
if __name__ == '__main__':
import doctest
if doctest.testmod().failed == 0:
print('\n✨ ALL TESTS PASSED!\n')
| true |
744a17e55227470c63ceb499957400bd486113ab | oddporson/intro-python-workshop | /strings.py | 721 | 4.1875 | 4 | # strings are a sequence of symbols in quote
a = 'imagination is more important than knowledge'
# strings can contain any symbols, not jus tletters
b = 'The meaning of life is 42'
# concatenation
b = a + ', but not as important as learning to code'
# functions on string
b = a.capitalize()
b = a.upper()
b = b.lower()
b = a.replace('more', 'less') # replace all instances of 'more' with 'less'
print(b)
# input/output
print(a)
b = input('Enter a number between (0, 10)')
print(a + ' ' + b)
# conversion between strings and numbers
c = int(b) # useful for converting user inputs to numbers
c = float(b)
d = str(c) # useful for combining a number with a string before printing
print('The entered number was ' + d)
| true |
d761e36ff3db8724b77a83d79537ee72db4e9129 | shirishavalluri/Python | /Objects & Classes.py | 2,574 | 4.25 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
# Import the library
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[12]:
class Circle(object):
#Constructor
def __init__(self, radius=3, color='blue'):
self.radius = radius;
self.color = color;
# In[13]:
RedCircle = Circle(10, 'red')
# In[14]:
RedCircle
# In[15]:
dir(RedCircle)
# In[16]:
RedCircle.radius
# In[17]:
RedCircle.color
# In[19]:
RedCircle.radius = 1
RedCircle.radius
# In[21]:
RedCircle.add_radius(2)
# In[22]:
print('Radius of object:',RedCircle.radius)
RedCircle.add_radius(2)
print('Radius of object of after applying the method add_radius(2):',RedCircle.radius)
RedCircle.add_radius(5)
print('Radius of object of after applying the method add_radius(5):',RedCircle.radius)
# In[23]:
BlueCircle = Circle(radius=100)
# In[44]:
BlueCircle.drawCircle
# In[45]:
class Circle(object):
# Constructor
def __init__(self, radius=3, color='blue'):
self.radius = radius
self.color = color
# Method
def add_radius(self, r):
self.radius = self.radius + r
return(self.radius)
# Method
def drawCircle(self):
plt.gca().add_patch(plt.Circle((0, 0), radius=self.radius, fc=self.color))
plt.axis('scaled')
plt.show()
# In[63]:
# Create a class Circle
class Circle(object):
# Constructor
def __init__(self, radius=3, color='blue'):
self.radius = radius
self.color = color
# Method
def add_radius(self, r):
self.radius = self.radius + r
return(self.radius)
# Method
def drawCircle(self):
plt.gca().add_patch(plt.Circle((0, 0), radius=self.radius, fc=self.color))
plt.axis('scaled')
plt.show()
# In[64]:
RedCircle = Circle(10, 'red')
# In[66]:
RedCircle.drawCircle()
# In[31]:
RedCircle.radius
# In[38]:
class Rectangle(object):
def __init__(self,width=4,height=5,color ='red'):
self.width=width
self.height = height
self.color = color
def drawRectangle(self):
plt.gca().add_patch(plt.Rectangle((0, 0), self.width, self.height ,fc=self.color))
plt.axis('scaled')
plt.show()
# In[67]:
SkinnyRedRectangle = Rectangle(2,3,'yellow')
# In[40]:
SkinnyRedRectangle.width
# In[41]:
SkinnyRedRectangle.height
# In[42]:
SkinnyRedRectangle.color
# In[68]:
SkinnyRedRectangle.drawRectangle()
# In[ ]:
| true |
687e8141335fe7d529dc850585f29ad5e50c4cbb | spacecoffin/OOPproj2 | /buildDict.py | 1,677 | 4.1875 | 4 | # Assignment does not specify that this program should use classes.
# This program is meant to be used in the __init__ method of the
# "Dictionary" class in the "spellCheck" program.
import re
def main():
# The program buildDict should begin by asking the user for a
# list of text files to read from. The user should respond by
# typing the file names as [filename1] [white space] [filename2]
# [white space] [filename3]...
inputList = input(
"Please enter the name[s] of the file[s] (including the file-type extension) from which to create the dictionary. \n\n If entering more than one name, please separate each name by a space.\n\n"
).split()
word_list = []
for f in inputList:
try:
file = open(f)
for line in file.readlines():
split_line = re.split(r'[^a-z]+', line, flags=re.IGNORECASE)
for x in split_line:
x = x.lower()
if len(x) >= 2:
if x not in word_list:
word_list.append(x)
else:
continue
else:
continue
except IOError:
# FileNotFoundError IS NEW FOR 3.3! 3.2 uses IOError!
print("***Unable to read file \'{}\'!***\n".format(f))
word_list = sorted(word_list)
try:
output = open(r'words.dat', 'w')
except (IOError, OSError):
print("***Unable to write dictionary to \'words.dat\'!***\n")
for word in word_list:
output.write("{}\n".format(word))
output.close
main() | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.