blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
c91cea964cc5f6b8931497a93c6ac1b37cf8ca62 | serereg/homework-repository | /homeworks/homework2/hw5.py | 1,611 | 4.15625 | 4 | """
Some of the functions have a bit cumbersome behavior when we deal with
positional and keyword arguments.
Write a function that accept any iterable of unique values and then
it behaves as range function:
import string
assert = custom_range(string.ascii_lowercase, 'g') ==
['a', 'b', 'c', 'd', 'e', 'f']
assert = custom_range(string.ascii_lowercase, 'g', 'p') ==
['g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']
assert = custom_range(string.ascii_lowercase, 'p', 'g', -2) ==
['p', 'n', 'l', 'j', 'h']
"""
def custom_range(iter, *args):
"""function that accept any iterable of unique values and then
it behaves as range function
Args:
iter (iterable, start_elemeng):
iter (iterable, start_elemeng, stop_element):
iter (iterable, start_elemeng, stop_element, step):
Example:
assert = custom_range(string.ascii_lowercase, 'g') ==
['a', 'b', 'c', 'd', 'e', 'f']
assert = custom_range(string.ascii_lowercase, 'g', 'p') ==
['g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o']
assert = custom_range(string.ascii_lowercase, 'p', 'g', -2) ==
['p', 'n', 'l', 'j', 'h']
"""
if len(args) == 1:
start_element, stop_element, step = None, args[0], None
if len(args) == 2:
start_element, stop_element, step = args[0], args[1], None
if len(args) == 3:
start_element, stop_element, step = args
begin = 0
if start_element:
begin = iter.index(start_element)
end = iter.index(stop_element)
return [element for element in iter[begin:end:step]]
| true |
c312bb50572e8260c13796c143961aa68d2cb8f8 | serereg/homework-repository | /homeworks/homework2/hw3.py | 752 | 4.125 | 4 | """
Write a function that takes K lists as arguments and
returns all possible
lists of K items where the first element is from the first list,
the second is from the second and so one.
You may assume that that every list contain at least
one element
Example:
assert combinations([1, 2], [3, 4]) == [
[1, 3],
[1, 4],
[2, 3],
[2, 4],
]
"""
import itertools
from typing import List, Any
def combinations(*args: List[Any]) -> List[List]:
"""
Returns all combinations of given lists in a list
"""
return [list(item) for item in itertools.product(*args)]
if __name__ == "__main__":
all_combinations = combinations([1, 2], [4, 3])
for i in all_combinations:
print(i, type(i))
print(all_combinations)
| true |
d9085475d79d664153e73818e7a07fe628910a06 | DonCastillo/learning-python | /0060_sets_intro.py | 2,661 | 4.25 | 4 | farm_animals = {"sheep", "cow", "hen"} # sets are unordered, can set the order randomly every time the code is ran
print(farm_animals) # sets only contains one copy of each element
for animal in farm_animals:
print(animal)
print("=" * 40)
wild_animals = set(["lion", "tiger", "panther", "elephant", "hare"]) # converting list to set
print(wild_animals)
for animal in wild_animals:
print(animal)
farm_animals.add("horse") # adding an element
wild_animals.add("horse")
print(farm_animals)
print(wild_animals)
empty_set = set() # this is an empty set, should be specificied explicitly
empty_set_2 = {} # this is an empty dictionary not an array
empty_set.add("a")
# empty_set_2.add("a")
even = set(range(0, 40, 2))
print(even)
print(len(even))
squares_tuple = (4, 6, 9, 16, 25)
squares = set(squares_tuple)
print(squares)
print(len(squares))
# gets all the union
# adds all the elements of the two sets together
print(even.union(squares))
print(len(even.union(squares)))
print(squares.union(even))
print("-" *40)
# gets all the intersection
# add only the common elements from each set
print(even.intersection(squares))
print(even & squares)
print(squares.intersection(even))
print(squares & even)
# set operation
print("-" * 40)
even = set(range(0, 40, 2))
print(sorted(even))
squares_tuple = (4, 6, 9, 16, 25)
squares = set(squares_tuple)
print(sorted(squares))
# removes all the elements in squares from even set
print("even minus squares")
print(sorted(even.difference(squares)))
print(sorted(even - squares))
print("squares minus even")
print(sorted(squares.difference(even)))
print(sorted(squares - even))
print("=" * 40)
print(sorted(even))
print(squares)
even.difference(squares)
print(sorted(even))
print("-" * 40)
print("symmetric even minus squares")
print(sorted(even.symmetric_difference(squares)))
print("symmetric squares minus even")
print((squares.symmetric_difference(even)))
print()
print(squares)
squares.discard(4)
squares.remove(16) # throws an error if the element does not exist
squares.discard(8) # no error, does nothing if the element does not exist
print(squares)
try:
squares.remove(8)
except KeyError:
print("The item 8 is not a member of the set")
print("-" * 40)
even = set(range(0, 40, 2))
print(sorted(even))
squares_tuple = (4, 6, 16)
squares = set(squares_tuple)
print(sorted(squares))
if squares.issubset(even):
print("squares is a subset of even")
if even.issuperset(squares):
print("even is a superset of square")
print("-" * 40)
even = frozenset(range(0, 100, 2)) # just like set but is constant, cannot add or manipulate
print(even)
even.add(3)
| true |
c67e8738b515c6f514123d1b27e57bdbee27a628 | mnovak17/wojf | /lab01/secondconverter.py | 497 | 4.125 | 4 | #secondconverter.py
#Translates seconds into hours, minutes, and seconds
#Mitch Novak
def main():
print("Welcome to my Second Converter! \n")
print("This program will properly calculate the number of \n minutes and seconds under 60 from a given number of seconds")
n = eval(input("How many seconds have you got?"))
total = n
h = n//3600
n = n%3600
m = n//60
s = n%60
print (total, " seconds is equal to ", h ," hours, ", m ," minutes, and ", s ,"seconds.")
main()
| true |
4a0738f39e7d517d81903dd7a63f76b7f6b8d7a5 | RinkuAkash/Python-libraries-for-ML | /Numpy/23_scalar_multiplication.py | 426 | 4.1875 | 4 | '''
Created on 21/01/2020
@author: B Akash
'''
'''
problem statement:
Write a Python program to create an array of (3, 4) shape, multiply every element value by 3 and display the new array.
Expected Output:
Original array elements:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
New array elements:
[[ 0 3 6 9]
[12 15 18 21]
[24 27 30 33]]
'''
import numpy as np
array=np.array([[0,1,2,3],[4,5,6,7],[8,9,10,11]])
print(array*3) | true |
0ac549f8f324ddc0246cc9a6227ed0ddb715ffde | sabgul/python-mini-projects | /guess_the_number/main.py | 1,110 | 4.28125 | 4 | import random
def guess(x):
random_number = random.randint(1, x)
guess = 0
while guess != random_number:
guess = input(f'Guess a number between 1 and {x}: ')
guess = int(guess)
if guess < random_number:
print('Guess was too low. Try again.')
elif guess > random_number:
print('Guess was too high. Guess again.')
print(f'Congrats, you have guessed the right number {random_number} correctly! ')
# letting the computer guess any number we are thinking of
def computer_guess(x):
low = 1
high = x
feedback = ''
while feedback != 'c': # c -- correct
if low != high:
guess = random.randint(low, high)
else:
guess = low
feedback = input(f'Is {guess} too high (H), too low (L), or correct (C)?').lower()
if feedback == 'h':
high = guess - 1
elif feedback == 'l':
low = guess + 1
print(f'Yes, the computer guessed the number you were thinking of ({guess}) correctly.')
#guess(10)
computer_guess(10)
| true |
5f215b292c15000d73a2007e8ed8e81d32e536a5 | OmarKimo/100DaysOfPython | /Day 001/BandNameGenerator.py | 465 | 4.5 | 4 | # 1. Create a greeting for your program.
print("Welcome to My Band Name Generator. ^_^")
# 2. Ask the user for the city that they grow up in.
city = input("What's the name of the city you grow up in?\n")
# 3. Ask the user for the name of a pet.
pet = input("Enter a name of a pet.\n")
# 4. Combine the name of their city and pet and show them their band name.
print(f"Your band name could be {city} {pet}")
# 5. Make sure the input cursor shows on a new line.
| true |
ebca9d6de69c7539774b2a57852d492ab0d7295d | Nicodona/Your-First-Contribution | /Python/miniATM.py | 2,703 | 4.25 | 4 | # import date library
import datetime
currentDate = datetime.date.today()
# get name from user
name = input("enter name : ")
# create a list of existing name and password and account balance
nameDatabase = ['paul', 'peter', 'emile', 'nico']
passwordDatabase = ['paulpass', 'peterpass','emilepass', 'nicopass']
accountBalance= [ 20000, 20000, 20000, 20000] # an example of initial accountbalance of various persons
# comparing name with name in list
if(name in nameDatabase):
passoword = input('enter password: ')
# nesting if condition to check for password if valid name is used and also making sure the existing n
# ame correspond to the index of the passwordDatabse list so that existing user uses only their password to login
realPass = nameDatabase.index(name)
if passoword == passwordDatabase[realPass]:
# print the date after successful login
currentBalance = accountBalance[realPass]
print(currentDate.strftime('%d %b, %Y'))
# output the user with options to do either withdraw deposit or complain
try: #this line is used to catch errors for example if the user enters a character instead of an interger
option = int(input('enter\n 1: withdraw\n 2:deposit\n 3:complaint\n'))
# this option checks the option input and deducts the withdraw cash from accountBalance
if option == 1:
withdraw = int(input('how much will you like to withdraw'))
currentBalance = currentBalance - withdraw
accountBalance[realPass] = currentBalance
print('take your cash %d' % withdraw)
print(f'ACCOUNT BALANCE is {currentBalance}')
# this block checks the option input and add the deposit to the accountBalance
elif option == 2:
deposit = int(input('how much will you like to deposit?'))
currentBalance = currentBalance + deposit
accountBalance[realPass] = currentBalance
print('successfully deposit into accountbalance is')
print(currentBalance)
# this option ask checks the option input and produce a complaint for users having issues
elif option == 3:
complaint = input('what issue will you like to report?')
print('thank you for contacting us')
except ValueError: # this is an alternative message if an error ValueError occurs
print('error please try again, enter an interger in option')
else:
print('wrong password please try again')
else:
print('user does not exit please input a valid username')
#for index in accountBalance:
# print(index)
| true |
6614083932d6659190d7eb0dc5ba9693d2faa44e | jeremyosborne/python | /iters_lab/solution/itools.py | 816 | 4.28125 | 4 | """
Lab
---
Using the iterutils, figure out the number of permutations possible when
rolling two 6-sided dice. (Hint: Think cartesian product, not the
permutations function.)
Print the total number of permutations.
Make a simple ascii chart that displays the count of permutations for
a particular combination (i.e. sum of a permutation).
Example:
3 *
4 **
... etc...
"""
from itertools import product
from collections import Counter
rolls = Counter()
for roll in product(range(1, 7), repeat=2):
rolls[sum(roll)] += 1
print "Total permutations:", sum(rolls.values())
print "Distribution of rolls"
# Since the dataset is small, we don't normalize.
for total, numperms in rolls.items():
print "{:2}".format(total), "*" * numperms
| true |
edc84c8a30911e7bd2d8c82fbdcac975cd3a1f40 | Deathcalling/Data-Analysis | /pythonData/pythonPandas/pandasBasics1.py | 1,529 | 4.125 | 4 | import pandas as pd #Here we import all necessary modules for us to use.
import datetime
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import style #This simply tells python that we want to make matplotlib look a bit nicer.
style.use('ggplot') #Here we tell python what kind of style we would like to use for matplotlib
#Now I just made a dictionary to represent a dataframe type of datastructure
web_stats = {'Day' : [1,2,3,4,5,6],
'Visitors' : [43,56,76,46,54,34],
'Bounce_Rate' : [65,23,34,45,87,65]}
stats = pd.DataFrame(web_stats) #Turned our dictionary into a dataframe
print(stats) #Head and tail display the first five and last five of a dataframe
print(stats.head(2))
print(stats.tail(2))
print(stats.set_index('Day')) #Another way to get the same result, telling python we want stats to show the index of Day.
stats2 = stats.set_index('Day')
print(stats2.head())
print(stats['Bounce_Rate']) #more ways to display data
print(stats.Visitors)
print(stats[['Bounce_Rate','Visitors']]) # One way to get two or more different columns.
print(stats.Visitors.tolist()) #Here we told python to turn this column of data into a list.
print(np.array(stats[['Bounce_Rate','Visitors']])) # Using numpy we can make a dataset into an array!
stats3 = pd.DataFrame(np.array(stats[['Bounce_Rate','Visitors']])) # And just like we can turn dataframes to arrays, we can also turn arrays to dataframes!!!
print(stats3)
stats.plot()
plt.show()
| true |
ef5ad01f85285601321ec6fa246a16e6f07b775b | siddharth456/python_scripts | /python/add_elements_to_a_list.py | 251 | 4.34375 | 4 | # add elements to an empty list
testlist=[]
x=int(input("enter number of elements to be added to the list:"))
for i in range(x):
e=input("enter element:")
testlist.insert(i,e)
print() # adds an empty line
print("Your list is",testlist)
| true |
911040a477c107f353b3faace1d688dafde3064d | siddharth456/python_scripts | /python/create_user_input_list.py | 209 | 4.375 | 4 | # We will create a list using user input
userlist = [] # this is how you initialize a list
for i in range(5):
a=input("Enter element:")
userlist.append(a)
print ("your created list is:",userlist)
| true |
b32a498930d2701520f45965a56d65fa09e533ad | SergioG84/Python | /weight_converter.py | 1,113 | 4.15625 | 4 | from tkinter import *
window = Tk()
# define function for conversion
def convert_from_kg():
grams = float(entry_value.get()) * 1000
pounds = float(entry_value.get()) * 2.20462
ounces = float(entry_value.get()) * 35.274
text1.insert(END, grams)
text2.insert(END, pounds)
text3.insert(END, ounces)
# set labels for units
# add text box for conversion answers
label = Label(window, text="Kg")
label.grid(row=0, column=0)
entry_value = StringVar()
entry = Entry(window, textvariable=entry_value)
entry.grid(row=0, column=1)
button = Button(window, text="Convert", command=convert_from_kg)
button.grid(row=0, column=2)
label = Label(window, text="Grams")
label.grid(row=1, column=0)
text1 = Text(window, height=1, width=20)
text1.grid(row=2, column=0)
label = Label(window, text="Pounds")
label.grid(row=1, column=1)
text2 = Text(window, height=1, width=20)
text2.grid(row=2, column=1)
label = Label(window, text="Ounces")
label.grid(row=1, column=2)
text3 = Text(window, height=1, width=20)
text3.grid(row=2, column=2)
window.mainloop() | true |
8aece43ba3fef62e3bd9b1f2cead27608995c2c4 | SHASHANKPAL301/Rock-Paper-and-Scissor-game | /game.py | 1,311 | 4.25 | 4 | import random
print(''' Welcome to the Rock,Paper and Scissor game. THe rule of the game is shown below:-
1. rock vs scissor---> rock win
2. scissor vs paper---> scissor win
3. paper vs rock---> paper win''')
def game(computer, player):
if computer == player:
return None #tie
elif computer == 'R':
if player == 'P':
return True #winner
elif player == 'S':
return False #lose
elif computer == 'P':
if player == 'S':
return True
elif player == 'R':
return False
elif computer == 'S':
if player == 'R':
return True
elif player == 'P':
return False
computer = print("Computer turn: Rock(R), Paper(P) and Scissor(S)")
randomNum = random.randint(1, 3)
# print(randomNum)
# 1-->rock
# 2-->Paper
# 3-->scissor
if randomNum == 1:
computer = 'R'
elif randomNum == 2:
computer = 'P'
elif randomNum == 3:
computer = 'S'
player = input("Player turn: Rock(R), Paper(P) and Scissor(S) ")
i=game(computer,player)
if i==None:
print("game is tie!")
elif i==True:
print("You win")
elif i==False:
print("computer Win!")
print(f"computer choose { computer}")
print(f"player choose { player}") | true |
a43a0d590b70294442e9d92916cad822be961d3e | ohlemacher/pychallenge | /3_equality/equality.py | 2,339 | 4.34375 | 4 | #!/usr/bin/env python
'''
Find lower case characters surrounded by exactly three upper case
characters on each side.
'''
import pprint
import re
import unittest
def file_to_string():
'''Read the file into a string.'''
strg = ''
with open('equality.txt', 'r') as infile:
for line in infile:
for cha in line:
if cha != '\n':
strg += cha
return strg
def find_guarded_matches(strg):
'''
Use a regex to find the guarded chars.
'''
guard_re = re.compile(r"""
(^|[^A-Z]{1}) # Beginning or 3 non-uppercase
[A-Z]{3} # Three uppercase (guard)
([a-z]{1}) # One lowercase
[A-Z]{3} # Three uppercase (guard)
($|[^A-Z]{1}) # End or 3 non-uppercase
""",
re.VERBOSE)
matches = guard_re.findall(strg)
# Since three groups are used in the regex, tuples are returned.
# We only want the middle one.
answer = ''
for tup in matches:
answer += tup[1]
return answer
def explore():
'''Find the solution. Run iteractively.'''
strg = file_to_string()
print find_guarded_matches(strg)
class EqualityTest(unittest.TestCase):
'''Unit test set.'''
def test_start_match(self):
'''Test match at start of strg.'''
strg = "AAAxBBBooCCCyDDDo"
answer = 'xy'
result = find_guarded_matches(strg)
self.failUnless(result==answer)
def test_middle_match(self):
'''Test match in middle of strg.'''
strg = "mNoAAAxBBBooCCCyDDDmNo"
answer = 'xy'
result = find_guarded_matches(strg)
self.failUnless(result==answer)
def test_end_match(self):
'''Test match at end of strg.'''
strg = "ooAAAxBBBooCCCyDDD"
answer = 'xy'
result = find_guarded_matches(strg)
self.failUnless(result==answer)
def test_no_match(self):
'''Test no matches in strg.'''
strg = "ooAaAxBBBooCCCyDdD"
answer = ''
result = find_guarded_matches(strg)
self.failUnless(result==answer)
if __name__ == '__main__':
# A real app would use argparse to optionally exec the unit tests.
unittest.main()
| true |
3fbe28eaf7e972df0dc5c38e6adcc6857769fccd | fhossain75/CS103-UAB | /lab/lab07/reverse_stubbed.py | 441 | 4.375 | 4 | # 19fa103; john k johnstone; jkj at uab dot edu; mit license
# reverse1 iterates over the element;
# this is the one to remember, since it is the most natural and clear;
# so this is the one to practice
def reverse1 (s):
"""Reverse a string, iteratively using a for loop (by element).
>>> reverse1 ('garden')
nedrag
Params: s (str)
Returns: (str) reversal of s
"""
return
s = 'garden'
print (reverse1 (s))
| true |
8385b7cca4d9d2e2a7d25209233d5462ab8af24c | ErenBtrk/Python-Exercises | /Exercise21.py | 723 | 4.15625 | 4 | '''
Take the code from the How To Decode A Website exercise
(if you didn’t do it or just want to play with some different code, use the code from the solution),
and instead of printing the results to a screen, write the results to a txt file. In your code,
just make up a name for the file you are saving to.
Extras:
Ask the user to specify the name of the output file that will be saved.
'''
import random
fileName = input("Please enter the file name : ")
number_list = [random.randrange(1, 100, 1) for i in range(10)]
number_list_str = [ str(item) for item in number_list]
print(number_list_str)
with open(fileName,"w") as file:
for item in number_list_str:
file.write(item+' ')
file.close()
| true |
f99df6b2eabb591210ef8a18b648deaf198a9ef8 | ErenBtrk/Python-Exercises | /Exercise5.py | 1,280 | 4.25 | 4 | '''
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists
(without duplicates). Make sure your program works on two lists of different sizes.
Extras:
1-Randomly generate two lists to test this
2-Write this in one line of Python (don’t worry if you can’t figure this out at this point - we’ll get to it soon)
'''
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
new_list = []
for item in a:
if(not item in new_list):
new_list.append(item)
for item in b:
if(not item in new_list):
new_list.append(item)
new_list.sort()
print(new_list)
################################################################
import random
randomList = range(30)
list1 = random.sample(randomList,random.randint(5,20))
list2 = random.sample(randomList,random.randint(5,20))
print(list1)
print(list2)
new_list2 = []
for item in list1:
if(not item in new_list2):
new_list2.append(item)
for item in list2:
if(not item in new_list2):
new_list2.append(item)
new_list2.sort()
print(new_list2)
| true |
8b53226541e87eaee9b5ad490c425a35d84e3ab6 | Dinesh-Sivanandam/LeetCode | /53-maximum-subarray.py | 1,083 | 4.25 | 4 | #Program to find the maximum sum of the array
def maxSubArray(A):
"""
:type nums: List[int]
:rtype: int
"""
#length of the variable is stored in len_A
len_A = len(A)
#if the length of the variable is 1 then returning the same value
if 1 == len_A:
return A[0]
"""
Else we are taking the element one by one and adding the elements
if the value is less then zeor we are storing sum = 0
else if sum > max we are placing max value is equal to sum
else leaving the sum value and continue the process
after the process returning the max value
"""
max = None
sum = 0
for n in range(0, len_A):
sum += A[n]
if None == max or sum > max:
max = sum
if sum < 0:
sum = 0
continue
return max
#Starting the main
if __name__ == "__main__":
#declaring the values
nums = [-2,1,-3,4,-1,2,1,-5,4]
#storing the result in the variable
result = maxSubArray(nums)
#printing the result
print(result)
| true |
71929d852440e9767bed7adf6cb2d1deb9ed93b3 | ul-masters2020/CS6502-BigData | /lab_week2/intersection_v1.py | 349 | 4.1875 | 4 | def intersection_v1(L1, L2):
'''This function finds the intersection between
L1 and L2 list using in-built methods '''
s1 = set(L1)
s2 = set(L2)
result = list(s1 & s2)
return result
if __name__ == "__main__":
L1 = [1,3,6,78,35,55]
L2 = [12,24,35,24,88,120,155]
result = intersection_v1(L1, L2)
print(f"Intersection elements: {result}")
| true |
8b2ec04aef80d96e472eaf2592d180f41c0b06a2 | ABDULMOHSEEN-AlAli/Guess-The-Number | /Guess-The-Number.py | 2,895 | 4.25 | 4 | from random import randint # imports the random integer function from the random module
computer_guess = randint(1, 50) # stores the unknown number in a variable
chances = 5 # sets the chances available to the user to 5
def mainMenu(): # defines the main menu function, which will be prompted to the user every now and then
global chances
print('-' * 55)
print("Guess the number from 1 up to 50, You have %d chances..." % chances)
print('OR enter 404 to give up and show the answer...')
print('-' * 55)
user_value = int(input()) # stores the user's value
return user_value
def hotCold(num,unknown): # defines the hot or cold function that will assist the user in guessing the number
if num > unknown:
if (num - 5) < unknown:
result = 'Hotter'
elif (num - 10) < unknown:
result = 'bit hotter'
else:
result = 'Colder'
elif num < unknown:
if (num + 5) > unknown:
result = 'Hotter'
elif (num + 10) > unknown:
result = 'bit hotter'
else:
result = 'Colder'
else:
result = 'Colder'
return result
choice = mainMenu() # stores the choice made by the user from the main menu function into a variable
# Computation Section
while computer_guess != choice and choice != 404: # this while loop will be executed till the specified condition
# validates the range
if choice > 50 or choice < 1:
print('Be careful mate... Your guess is out of range')
choice = mainMenu()
else:
# deducts the counter with each valid guess
chances -= 1
# if there are no more chances available, the loop gets interrupted and the code proceeds to the next lines
if chances == 0:
break
tip = hotCold(choice, computer_guess) ## stores the result of the hot or cold function in a variable
print('Try again... \"Hint: You are getting %s \"' % tip) ### prints the result of it
choice = mainMenu() # prompts the user for another guess
# Check for the result based on the above computations
if computer_guess == choice and chances == 5: # If the user wins from the first time
print("\nYOU WIN")
print('You guessed the number successfully!!!')
print("CASINO")
elif computer_guess == choice:
print("\nYOU WIN")
print('You guessed the number successfully!!!')
elif choice == 404: # if the user gives up and wants to see the unknown number
print('Sorry mate...')
print('The unknown number was %d' % computer_guess)
print('Thanks for your time')
else: # if the user failed to guess the number
print("YOU LOSE GG MAN")
print('The unknown number was %d' % computer_guess)
print("\nThanks for your time, and I hope you have fun")
# developer's message to the user
print("Feel free to contact me if you face any issues.") | true |
7906bb35b5f7c0c0acb8730ff7ccc6423fdd1623 | LesroyW/General-Work | /Python-Work/Loops.py | 470 | 4.4375 | 4 | #Looping over a set of numbers
# For number in numbers:
# print(number) examples of for loop
# For loops can also loop of a range
#e.g for x in range(5):
# print(x)
#While loops can also be used within it
#Break and continue statements can be used to skip the current block or return to the for/whil statement
# else clause can be used at the end after a while/for loop but won't be executed if a break function is reached in the loop but will if continue is used. | true |
9b3267d9488f10a980a2935d77bf906c4468f281 | adityagith/pythonprograms | /prime number.py | 278 | 4.15625 | 4 | a = int(input("Enter a number to check its prime or not\n"))
if(a<=0):
print("No")
elif(a==2):
print("Yes")
elif(a>2):
for i in range(2,a):
if(a%i==0):
print("Not a prime")
break
else:
print("Prime")
| true |
2584097aff364d6aeb60030eda2117628cbceda9 | siva4646/DataStructure_and_algorithms | /python/string/longest_word_indictioary_through_deleting.py | 986 | 4.15625 | 4 | """
Given a string and a string dictionary, find the longest string in the dictionary that can be formed by deleting some characters of the given string. If there are more than one possible results, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.
Example 1:
Input:
s = "abpcplea", d = ["ale","apple","monkey","plea"]
Output:
"apple"
"""
class Solution:
def findLongestWord(self, s: str, d: list[str]) :
print (s,d)
def check(s,s1):
i=0
j=0
while(i<len(s) and j<len(s1)):
if s[i]==s1[j]:
i=i+1
j=j+1
continue
i=i+1
return j==len(s1)
res=""
for word in d:
if check(s,word) and (len(res)<len(word) or (len(res)==len(word) and res>word)):
res=word
return res
findLongestWord(self,"abpcplea",["ale","apple","monkey","plea"])
| true |
2e274a24f93f81017686ad4c5ceabfaece95d419 | sebasbeleno/ST0245-001 | /laboratorios/lab02/codigo/laboratorio2.py | 1,610 | 4.15625 | 4 | import random
import sys
import time
sys.setrecursionlimit(1000000)
# Function to do insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
"""
Mohit Kumra (2020) Insertion Sort. [Source code] https://www.geeksforgeeks.org/python-program-for-insertion-sort/.
"""
# Python program for implementation of MergeSort
def mergeSort(arr):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr)//2
# Dividing the array elements
L = arr[:mid]
# into 2 halves
R = arr[mid:]
# Sorting the first half
mergeSort(L)
# Sorting the second half
mergeSort(R)
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
"""
Mayank Khanna(2021) Merge Sort. [Source code] https://www.geeksforgeeks.org/merge-sort/.
""" | true |
afd31e371feaed5fdf84e4372460b931416b3284 | karankrw/LeetCode-Challenge-June-20 | /Week 3/Dungeon_Game.py | 1,918 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 22 01:25:32 2020
@author: karanwaghela
"""
"""
The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon.
The dungeon consists of M x N rooms laid out in a 2D grid.
Our valiant knight (K) was initially positioned in the top-left room and
must fight his way through the dungeon to rescue the princess.
The knight has an initial health point represented by a positive integer.
If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons,
so the knight loses health (negative integers) upon entering these rooms;
other rooms are either empty (0's) or contain magic orbs that increase
the knight's health (positive integers).
In order to reach the princess as quickly as possible,
the knight decides to move only rightward or downward in each step.
Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.
For example, given the dungeon below,
the initial health of the knight must be at least 7
if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.
-2(K) -3 3
-5 -10 1
10 30 -5(P)
Note:
The knight's health has no upper bound.
Any room can contain threats or power-ups,
even the first room the knight enters and the bottom-right room where the princess is imprisoned.
"""
class Solution(object):
def calculateMinimumHP(self, dungeon):
"""
:type dungeon: List[List[int]]
:rtype: int
"""
m, n = len(dungeon), len(dungeon[0])
dp = [[float("inf")]*(n+1) for _ in range(m+1)]
dp[m-1][n], dp[m][n-1] = 1, 1
for i in range(m-1,-1,-1):
for j in range(n-1,-1,-1):
dp[i][j] = max(min(dp[i+1][j],dp[i][j+1])-dungeon[i][j],1)
return dp[0][0] | true |
65c2f70ca2dae1538060ac49c894702961d52e91 | Python-lab-cycle/Swathisha6 | /2.fibopnnaci.py | 214 | 4.15625 | 4 | n =int(input("enter the number of terms:"))
f1,f2=0,1
f3=f2+f1
print("fibonacci series of first" , n, "terms")
print(f1)
print(f2)
for i in range (3, n+1):
print(f3)
f1=f2
f2=f3
f3=f1+f2
| true |
ee934da6f5e0eee00050b8ed0845a2a9f70dd3e7 | katherfrain/Py101 | /tipcalculator2.py | 810 | 4.125 | 4 | bill_amount = float(input("What was the bill amount? Please don't include the dollar sign! "))
service_sort = input("What was the level of service, from poor to fair to excellent? ")
people_amount = int(input("And how many ways would you like to split that? "))
service_sort = service_sort.upper()
if service_sort == "POOR":
tip_amount = (bill_amount*.1)
elif service_sort == "FAIR":
tip_amount = (bill_amount*.15)
elif service_sort == "EXCELLENT":
tip_amount = (bill_amount*.2)
else:
bill_amount = float(input("I didn\'t understand your first statement. What amount did you owe, sans dollar sign? "))
total = bill_amount + tip_amount
perperson = float(total/people_amount)
print(f"Your tip is ${tip_amount:.2f}, and your total is ${total:.2f}, which splits to ${perperson:.2f} per person.") | true |
2efd2878071e1534f85d45a7c3f36badb42c7a96 | katherfrain/Py101 | /grocerylist.py | 447 | 4.125 | 4 | def want_another():
do_you_want_another = input("Would you like to add to your list, yes/no? ")
if do_you_want_another == "yes":
grocery = input("What would you like to add to your list? ")
grocery_list.append(grocery)
print("You have added ", grocery, "to the list")
print("Your current list is: ", grocery_list)
do_you_want_another = input("Would you like to add another item? Yes or no?") | true |
15cba18ee92d82bf0f612e96ece1dc4a2911d9fc | ghimire007/jsonparser1 | /jsonparser.py | 1,111 | 4.1875 | 4 | # json parsor
import csv
import json
file_path = input("path to your csv file(add the name of your csv file as well):") # takes file path
base_new = "\\".join(file_path.split("\\")[:-1])
file_name = input(
"name of th file that you want to save as after conversion(no extension required):") # takes name of file you want to save as
file_name = base_new + "\\" + file_name + ".json" # adds extension to file name
with open(file_path, "r") as qna: # opens g n fileive
with open(file_name, "w") as qnajson: # makes new file as you entered
final_json = []
reader = csv.reader(qna)
headings = next(reader) # reads header of csv file
for line in reader:
x = {}
for i in range(len(headings)):
x[headings[i]] = line[i]
ready_json = json.dumps(x)
final_json.append(ready_json)
new_json = ",".join([str(elem) for elem in final_json])
last_json = "[" + new_json + "]"
qnajson.write(last_json)
print("your json file has been created at " + base_new)
| true |
84e0a3ba3678e6e5bc8618871e8d7a2eb6cebfe1 | himala76/Codding_Lesson_1 | /Lectures_Note_Day_1/Cancat.py | 352 | 4.4375 | 4 | # This is the result we want to have in the console
#print "Hello, world! My name is Josh."
# Create a variable to represent the name and introduction statement to print
name = "Josh"
# Comment out this line for the moment
# intro_statement = "Hello, world! My name is "
# print the concatenated string
print "Hello, world! My name is " + name + "." | true |
4b02cf096cd437659968330d1e2fed228fd2036f | asenath247/COM404 | /1-basics/4-repetition/3-ascii/bot.py | 212 | 4.15625 | 4 | print("How many bars should be charged.")
bars = int(input())
chargedBars = 0
while chargedBars < bars:
print("Charging "+"█" * chargedBars)
chargedBars += 1
print("The battery is fully charged.")
| true |
4b3fd151726e2692179e72be9fb71e4b3fb632a3 | vishal-B-52/Documentation_of_Python | /GuessTheNumberModified.py | 1,693 | 4.25 | 4 | # Guess the number :-
print("This is a 'Guess the Number Game'. You have 10 Life(s) to guess the hidden number. You have to win in 10 Life(s) "
"else You lose!!! ")
Life = 10
while True:
N = int(input("Enter the number:- "))
Life -= 1
if 0 <= N < 18:
if Life == 0:
print("Sorry but you have lost the game, Secret number was 18.\n")
break
else:
print("You are too close to the number. Try to focus!!")
elif N == 18:
print("Hurray You won the game !!!")
print("You won with", Life, "life(s) still left\n")
break
elif 19 <= N <= 36:
if Life == 0:
print("Sorry but you have lost the game, Secret number was 18.\n")
break
else:
print("You are close to the number, Please concentrate!!")
elif 37 < N <= 100:
if Life == 0:
print("Sorry but you have lost the game, Secret number was 18.\n")
break
else:
print("You are going too far. You need to come back")
elif N > 100:
if Life == 0:
print("Sorry but you have lost the game, Secret number was 18.\n")
break
else:
print("Number is smaller than 100, Please Try again!!!")
if Life == 9:
print("You lost one life,", Life, "life(s) left\n")
elif Life == 8:
print("You lost another life,", Life, "life(s) left\n")
elif 1 < Life <= 7:
print("You lost another life again,", Life, "life(s) left\n")
elif Life == 1:
print("You have the last life. Best of Luck.", Life, "Life(s) left\n")
| true |
9790f37381a1455af2fbb10777525caa9b8d0ab0 | innovatorved/BasicPython | /x80 - Tuples.py | 541 | 4.3125 | 4 | #turple
#turple is immutable
#once u defined turple u cannot change its elements
bmi_cat = ('Underweight' , 'Normal', 'Overweight' ,'very Overweight')
#type
print('Type: ',type(bmi_cat))
#access element of turple
print(bmi_cat[1]) #we use positive value
print(bmi_cat[-2]) #and we also use negative value
print(bmi_cat[0:3])#indexing range
print(bmi_cat.index('Normal')) #searching index of value
#for searching any element was in turple or not
#it is Case sensitive
print('Very underweight' in bmi_cat) #it return Boolean value
| true |
43fd97252b25c653bfdbe8a1349cd89475d40e60 | HananeKheirandish/Assignment-8 | /Rock-Paper-Scissor.py | 876 | 4.125 | 4 | import random
options = ['rock' , 'paper' , 'scissor']
scores = {'user' : 0 , 'computer' : 0}
def check_winner():
if scores['user'] > scores['computer']:
print('Play End. User Win!! ')
elif scores['user'] < scores['computer']:
print('Play End. Computer Win!! ')
else:
print('Play End.No Win!! ')
exit()
print('Choose from this list: ' , options)
for i in range(10):
computer = random.choice(options)
user = input('Play the game: ')
if (computer == 'rock' and user == 'scissor') or (computer == 'paper' and user == 'rock')\
or (computer == 'scissor' and user == 'paper'):
print('Computer win! ')
scores['computer'] += 1
elif computer == user:
print('No win! Try again. ')
else:
print('User win! ')
scores['user'] += 1
check_winner() | true |
e2a0c342c90cd07b387b7739b9869aee46df4090 | luroto/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 761 | 4.15625 | 4 | #!/usr/bin/python3
"""
Function handbook:
text_identation("Testing this. Do you see the newlines? It's rare if you don't: all are in the code."
Testing this.
Do you see the newlines?
It's rare if you dont:
all are in the code.
"""
def text_indentation(text):
""" This function splits texts adding newlines when some separators are found"""
if type(text) != str:
raise TypeError("text must be a string")
i = 0
total = len(text)
while i < total:
if text[0] == ' ':
pass
if text[i] == '.' or text[i] == ':' or text[i] == "?":
print("{}{}".format(text[i],'\n'))
i += 2
print("{}".format(text[i]), end="")
i += 1
if text[total -1] == ' ':
pass
| true |
3b0fe27b3dc3448de0bdcdd034ff6220af9bad2d | mtocco/ca_solve | /Python/CA041.py | 2,774 | 4.28125 | 4 | ## Code Abbey
## Website: http://www.codeabbey.com/index/task_view/median-of-three
## Problem #41
## Student: Michael Tocco
##
##
##
## Median of Three
##
##
## You probably already solved the problem Minimum of Three - and it was
## not great puzzle for you? Since programmers should improve their logic
## (and not only skills in programming language), let us change the task to
## make it more tricky.
##
## You will be again given triplets of numbers, but now the middle of them
## should be chosen - i.e. not the largest and not the smallest one. Such number
## is called the Median (of the set, array etc).
##
## Be sure, this problem is not simply "another stupid exercise" - it is used
## as a part in powerful QuickSort algorithm, for example.
##
## Input data will contain in the first line the number of triplets to follow.
## Next lines will contain one triplet each.
## Answer should contain selected medians of triplets, separated by spaces.
##
## Example:
## data:
## 3
## 7 3 5
## 15 20 40
## 300 550 137
##
## answer:
## 5 20 300
## Note: if your program will have a lot of if-else-if-else statements, then you
## are probably doing something wrong. Simple solution should have no more
## than three of them.
##
def main():
userArray = []
print()
print()
yesOrNo = input("Would you like proceed with the calculation? (enter[y , n]): ")
if yesOrNo == "y":
buildArray()
else:
print("Thank you, come again")
def buildArray():
arrayPairs = int(input("Please enter in " + \
"a desired number of sets to analyze"))
print("Enter/Paste your content. Ctrl-D to save it.")
answer = ""
contents = []
for i in range(int(arrayPairs+1)):
try:
line = input().split(" ")
if len(line) > 1:
intSet = [int(i) for i in line]
median = [i for i in intSet if i != min(intSet) and i != max(intSet)]
answer = answer + str(median).replace("[","").replace("]","") + " "
except EOFError:
break
print(answer)
main()
## The result was correct - the author listed some notes as well:
##
## Author's Notes
## To select the middle of three elements A, B and C let us try to reorder them:
##
## if A > B swap A with B
## if B > C swap B with C
## if A > B swap A with B
## For swapping X and Y use the temporary variable T in three assignment,
## for example:
##
## T = X; X = Y; Y = T
##
## At the 2nd step the largest element of three would be moved to C.
## After 3rd step the smallest of the remaining two is moved to A.
## Therefore B contains the middle element.
| true |
fbec208c8dae08742e23d199f4a4debc8d125430 | unknownpgr/algorithm-study | /code-snippets/02. permutation.py | 724 | 4.15625 | 4 | '''
Recursive function may not be recommanded because of stack overflow.
However, permutation can be implemented with recursive function without warring about overflow.
That is because n! grows so fast that it will reach at time limit before it overflows.
'''
def permutation(array):
'''
This function returns the array of all available permutations of given array.
If the given array is sorted in ascending order, the result also will be sorted.
'''
l = len(array)
if l == 1:
return [array]
result = []
for i in range(l):
sub_array = array[:i]+array[i+1:]
for sub_result in permutation(sub_array):
result.append([array[i]]+sub_result)
return result
| true |
af800a84a2887a6cc0561a74b3a44215ac9e8457 | jhglick/comp120-sp21-lab09 | /longest_increasing_subsequence.py | 467 | 4.125 | 4 | """
File: longest_increasing_subsequence.py
Author: COMP 120 class
Date: March 23, 2021
Description: Has function for longest_increasing_subsequence.
"""
def longest_increasing_subsequence(s):
"""
Returns the longest substring in s. In case of
ties, returns the first longest substring.
"""
pass
if __name__ == "__main__":
s = input("Enter a string: ")
print(f"Maximum consecutive subsequence is {longest_increasing_subsequence(s)}")
| true |
5b17d6216a339ee9642c7d826ff468a2bdd99139 | rachit-mishra/Hackerrank | /Sets 1 intro.py | 681 | 4.25 | 4 | # Set is an unordered collection of elements without duplicate entries
# when printed, iterated or converted into a sequence, its elements appear in an arbitrary order
# print set()
# print set('HackerRank')
# sets basically used for membership testing and eliminating duplicate entries
array = int(input())
sumlist = 0
for i in range(array):
s = input()
num = map(int, s.split())
my_list = list(set(num))
for j in range(len(my_list)):
sumlist += (my_list[j])
avg=sumlist/len(my_list)
print(avg)
## num = map(int, s.split())
# in python 3, map no longer returns a list
# num was being stored as a list earlier
# so use map | true |
a5daff0eccc74862ba2f2cd962971a27f2ec7099 | tinybeauts/LPTHW | /ex15_mac.py | 1,197 | 4.375 | 4 | from sys import argv
script, filename = argv
txt = open(filename)
print "Here's your file %r:" % filename
print txt.read()
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
# Extra Credit 4
# from sys import argv
#
# script, filename = argv
#
# txt = open(filename)
#
# print "Here's your file %r:" % filename
# print txt.read()
# Extra Credit 5
# print "Type the filename again:"
# file_again = raw_input("> ")
#
# txt_again = open(file_again)
#
# print txt_again.read()
# A reason to get the file name as input rather than when you call the file
# would be if you have a lot of files you're calling
# Another reason is maybe you're calling multiple files, but the names of
# some of them are contained in other ones. So you might need to open them
# before you can call the next one.
# Extra Credit 8
# from sys import argv
#
# script, filename = argv
#
# txt = open(filename)
#
# print "Here's your file %r:" % filename
# print txt.read()
#
# txt.close()
#
# print "Type the filename again:"
# file_again = raw_input("> ")
#
# txt_again = open(file_again)
#
# print txt_again.read()
#
# txt_again.close() | true |
de7f58a8084ee33e834c6487c65ef0cf13a19913 | Md-Hiccup/Problem-Solving | /HackerRank/Rank/easy/symmetric_difference.py | 2,623 | 4.125 | 4 | """
a new data type: sets.
Concept:
If the inputs are given on one line separated by a space character, use split() to get the separate values in the form of a list:
>> a = raw_input()
5 4 3 2
>> lis = a.split()
>> print (lis)
['5', '4', '3', '2']
If the list values are all integer types, use the map() method to convert all the strings to integers.
>> newlis = list(map(int, lis))
>> print (newlis)
[5, 4, 3, 2]
Sets are an unordered bag of unique values. A single set contains values of any immutable data type.
CREATING SETS
>> myset = {1, 2} # Directly assigning values to a set
>> myset = set() # Initializing a set
>> myset = set(['a', 'b']) # Creating a set from a list
>> myset
{'a', 'b'}
MODIFYING SETS
Using the add() function:
>> myset.add('c')
>> myset
{'a', 'c', 'b'}
>> myset.add('a') # As 'a' already exists in the set, nothing happens
>> myset.add((5, 4))
>> myset
{'a', 'c', 'b', (5, 4)}
Using the update() function:
>> myset.update([1, 2, 3, 4]) # update() only works for iterable objects
>> myset
{'a', 1, 'c', 'b', 4, 2, (5, 4), 3}
>> myset.update({1, 7, 8})
>> myset
{'a', 1, 'c', 'b', 4, 7, 8, 2, (5, 4), 3}
>> myset.update({1, 6}, [5, 13])
>> myset
{'a', 1, 'c', 'b', 4, 5, 6, 7, 8, 2, (5, 4), 13, 3}
REMOVING ITEMS
Both the discard() and remove() functions take a single value as an argument and removes that value from the set. If that value is not present, discard() does nothing, but remove() will raise a KeyError exception.
>> myset.discard(10)
>> myset
{'a', 1, 'c', 'b', 4, 5, 7, 8, 2, 12, (5, 4), 13, 11, 3}
>> myset.remove(13)
>> myset
{'a', 1, 'c', 'b', 4, 5, 7, 8, 2, 12, (5, 4), 11, 3}
COMMON SET OPERATIONS Using union(), intersection() and difference() functions.
>> a = {2, 4, 5, 9}
>> b = {2, 4, 11, 12}
>> a.union(b) # Values which exist in a or b
{2, 4, 5, 9, 11, 12}
>> a.intersection(b) # Values which exist in a and b
{2, 4}
>> a.difference(b) # Values which exist in a but not in b
{9, 5}
The union() and intersection() functions are symmetric methods:
>> a.union(b) == b.union(a)
True
>> a.intersection(b) == b.intersection(a)
True
>> a.difference(b) == b.difference(a)
False
These other built-in data structures in Python are also useful.
Output Format
Output the symmetric difference integers in ascending order, one per line.
Sample Input
4
2 4 5 9
4
2 4 11 12
Sample Output
5
9
11
12
"""
# m = int(input())
# lm = list(map(int, input().split()))
# n = int(input())
# ln = list(map(int, input().split()))
m = 4
lm = set([2, 4, 5, 9])
n = 4
ln = set([2, 4, 11, 12])
data = sorted(lm.difference(ln).union(ln.difference(lm)))
print(*data, sep='\n') | true |
acfbd6ce55de265ead5aa37b15d13d6ad78c6060 | Md-Hiccup/Problem-Solving | /HackerRank/Rank/easy/any_or_all.py | 719 | 4.125 | 4 | """
any():
This expression returns True if any element of the iterable is true.
If the iterable is empty, it will return False.
all():
This expression returns True if all of the elements of the iterable are true. If the iterable is empty, it will return True.
Prob: Print True if all the conditions of the problem statement are satisfied. Otherwise, print False
Sample Input
5
12 9 61 5 14
Sample Output
True
"""
# Enter your code here. Read input from STDIN. Print output to STDOUT
n, numb = int(input()), list(map(int, input().split()))
chk_any = all(list(map(lambda x: x > 0, numb)))
pallindromic_any = any(list(map(lambda x: list(str(x)) == list(reversed(str(x))), numb)))
print(chk_any and pallindromic_any) | true |
1ef078d6c92399bc43e5737112cf6d41105963de | Md-Hiccup/Problem-Solving | /HackerRank/Rank/easy/collection_namedtuple.py | 924 | 4.4375 | 4 | """
collections.namedtuple()
Basically, namedtuples are easy to create, lightweight object types.
They turn tuples into convenient containers for simple tasks.
With namedtuples, you don’t have to use integer indices for accessing members of a tuple.
Example:
>>> from collections import namedtuple
>>> Point = namedtuple('Point','x,y')
>>> pt1 = Point(1,2)
>>> pt2 = Point(3,4)
>>> dot_product = ( pt1.x * pt2.x ) +( pt1.y * pt2.y )
>>> print dot_product
11
Problem:
Sample Input:
5
ID MARKS NAME CLASS
1 97 Raymond 7
2 50 Steven 4
3 91 Adrian 9
4 72 Stewart 5
5 80 Peter 6
Sample Output:
81.00 # Average = (97+50+91+72+80)/5
"""
from collections import namedtuple
n = int(input())
Student = namedtuple('Student', 'ID, Marks, Name, Class')
| true |
c2c0745b71a66464daf21d104a2831c38de9d9bb | ErenBtrk/Python-Fundamentals | /Numpy/NumpyStrings/Exercise16.py | 313 | 4.125 | 4 | '''
16. Write a NumPy program to count the lowest index of "P" in a given array, element-wise.
'''
import numpy as np
np_array = np.array(['Python' ,'PHP' ,'JS' ,'examples' ,'html'])
print("\nOriginal Array:")
print(np_array)
print("count the lowest index of ‘P’:")
r = np.char.find(np_array, "P")
print(r) | true |
339a24e71cbd4b32a815332c1ad9426a1d99c335 | ErenBtrk/Python-Fundamentals | /Python Operators/4-ComparisonOperatorsExercises.py | 1,368 | 4.34375 | 4 | #1 - Prompt user to enter two numbers and print larger one
number1 = int(input("Please enter a number : "))
number2 = int(input("Please enter a number : "))
result = number1 > number2
print(f"number1 : {number1} is greater than number2 : {number2} => {result}")
#2 - Prompt user to enter 2 exam notes and calculate average.If >50 print Passed ,if no print Try Again
exam1 = float(input("Please enter your exam note : "))
exam2 = float(input("Please enter your exam note : "))
average = (exam1+exam2)/2
result = average >= 50
print(f"Average is : {average} , You Passed the class : {result}")
#3 - Prompt user to enter a number.Print if its odd or even
number3 = int(input("Please enter a number : "))
result = (number3 % 2 != 0)
print(f"The number : {number3} is an odd number : {result}")
#4 - Prompt user to enter a number.Print if its negative or positive
number3 = int(input("Please enter a number : "))
result = (number3 > 0)
print(f"The number : {number3} ,is positive : {result}")
#5 - Prompt user to enter email and password.Check if its true
# ( email = email@gmail.com password = abcd123)
email = "email@gmail.com"
password = "abcd123"
inputUserEmail = input("Please enter your email : ")
inputUserPassword = input("Please enter your password : ")
result = (email == inputUserEmail.strip()) & (password == inputUserPassword.strip())
print(f"Logged in : {result}")
| true |
b9d440a9aafd661b1d1ed641cc8921e5e24ebd02 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyLinearAlgebra/Exercise14.py | 256 | 4.1875 | 4 | '''
14. Write a NumPy program to compute the condition number of a given matrix.
'''
import numpy as np
m = np.array([[1,2],[3,4]])
print("Original matrix:")
print(m)
result = np.linalg.cond(m)
print("Condition number of the said matrix:")
print(result) | true |
b99c2578051bef4298f3c7110ac76b9b3c0c9063 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyLinearAlgebra/Exercise10.py | 270 | 4.125 | 4 | '''
10. Write a NumPy program to find a matrix or vector norm.
'''
import numpy as np
v = np.arange(7)
result = np.linalg.norm(v)
print("Vector norm:")
print(result)
m = np.matrix('1, 2; 3, 4')
print(m)
result1 = np.linalg.norm(m)
print("Matrix norm:")
print(result1) | true |
d888cf76ca3c466760c7c6397a7c056aa44f9368 | ErenBtrk/Python-Fundamentals | /Python Conditional Statements/4-IfElseExercises2.py | 2,940 | 4.46875 | 4 | #1- Prompt the user to enter a number and check if its between 0-100
number1 = int(input("Please enter a number : "))
if(number1>0) and (number1<100):
print(f"{number1} is between 0-100")
else:
print(f"{number1} is NOT between 0-100")
#2- Prompt the user to enter a number and check if its positive even number
number2 = int(input("Please enter a number : "))
if(number2 > 0):
if(number2 % 2 == 0):
print(f"{number2} is positive even number")
else:
print(f"{number2} is not an even number")
else:
print(f"{number2} is not a positive number")
#3- Prompt the user to enter password and email and check if info is right
email = "email@gmail.com"
password = "123456"
inputEmail = input("Email : ")
inputPassword = input("Password : ")
if (email == inputEmail.strip()):
if(password == inputPassword.strip()):
print("Logged in.")
else:
print("Password is wrong.")
else:
print("Email is wrong.")
#4- Prompt the user to enter 3 numbers and compare them
number3 = int(input("Please enter a number : "))
number4 = int(input("Please enter a number : "))
number5 = int(input("Please enter a number : "))
if(number3 > number4) and (number3 > number5):
print(f"{number3} is the greatest")
if(number4 > number3) and (number4 > number5):
print(f"{number4} is the greatest")
if(number5 > number3) and (number5 > number4):
print(f"{number5} is the greatest")
#5- Prompt the user to enter 2 exam notes (%60) and 1 final note.And calculate average.
# if average is equal or larger than 50 print passed
# a-)Even though average is 50 final note has to be at least 50
# b-)If final note is equal or larger than 70 student can pass
exam1 = int(input("Please enter your first exam note : "))
exam2 = int(input("Please enter your second exam note : "))
final = int(input("Please enter your final exam note : "))
average = (((exam1+exam2) / 2)*0.6 + final*0.4)
print(f"Your average is {average}")
if(average >= 50):
print("You passed the class.")
else:
if(final >= 70):
print("You passed the class.Cause you got at least 70 in final exam.")
else:
print("You could not pass the class.")
#6- Prompt the user to enter name,weight,height and calculate body mass index
# Formula : (weight / height**2)
# Whats user BMI according to table below
# 0-18.4 => thin
# 18.5-24.9 => Normal
# 25.0-29.9 => Overweight
# 30.0-34.9 => Obese
name = input("Please enter your name : ")
weight = float(input("Please enter your weight : "))
height = float(input("Please enter your height in meters : "))
bmi = weight / (height**2)
print(f"Your body mass index is {bmi}")
if (bmi >= 0) and (bmi <=18.4):
print(f"{name} has thin bmi")
elif (bmi >= 18.5) and (bmi <=24.9):
print(f"{name} has normal bmi")
elif (bmi >= 25.0) and (bmi <=29.9):
print(f"{name} has overweight bmi")
elif (bmi >= 30.0):
print(f"{name} is obese")
| true |
31e0a2c1b41f587b63bb213ebda6c68d96d83d36 | ErenBtrk/Python-Fundamentals | /Pandas/PandasDataSeries/Exercise13.py | 289 | 4.15625 | 4 | '''
13. Write a Pandas program to create a subset of a given series based on value and condition.
'''
import pandas as pd
pd_series = pd.Series([1,2,3,4,5])
print(pd_series)
relationalVar = pd_series > 3
new_series = pd_series[relationalVar]
new_series.index = [0,1]
print(new_series) | true |
66c7b75d33b882e78fc35a61720bd25ded68c7cf | ErenBtrk/Python-Fundamentals | /Numpy/NumpyStatistics/Exercise13.py | 515 | 4.4375 | 4 | '''
13. Write a Python program to count number of occurrences of each value
in a given array of non-negative integers.
Note: bincount() function count number of occurrences of each value
in an array of non-negative integers in the range of the array between
the minimum and maximum values including the values that did not occur.
'''
import numpy as np
array1 = [0, 1, 6, 1, 4, 1, 2, 2, 7]
print("Original array:")
print(array1)
print("Number of occurrences of each value in array: ")
print(np.bincount(array1)) | true |
2461f2c598528a6a45b35da2708517717532fd3a | ErenBtrk/Python-Fundamentals | /Pandas/PandasDataframe/Exercise53.py | 425 | 4.5 | 4 | '''
53. Write a Pandas program to insert a given column at a specific column index in a DataFrame.
'''
import pandas as pd
d = {'col2': [4, 5, 6, 9, 5], 'col3': [7, 8, 12, 1, 11]}
df = pd.DataFrame(data=d)
print("Original DataFrame")
print(df)
new_col = [1, 2, 3, 4, 7]
# insert the said column at the beginning in the DataFrame
idx = 0
df.insert(loc=idx, column='col1', value=new_col)
print("\nNew DataFrame")
print(df) | true |
789d52f7c4e9b6fd3a91586d188bd06fec4da709 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyRandom/Exercise13.py | 288 | 4.4375 | 4 | '''
13. Write a NumPy program to find the most frequent value in an array.
'''
import numpy as np
x = np.random.randint(0, 10, 40)
print("Original array:")
print(x)
print("Most frequent value in the above array:")
print(np.unique(x))
print(np.bincount(x))
print(np.bincount(x).argmax()) | true |
dcecd4f5f65e24e8bcf2bb130d180b590c3aae74 | ErenBtrk/Python-Fundamentals | /Pandas/PandasDataSeries/Exercise24.py | 311 | 4.25 | 4 | '''
24. Write a Pandas program convert the first and last character
of each word to upper case in each word of a given series.
'''
import pandas as pd
import numpy as np
pd_series = pd.Series(["kevin","lebron","kobe","michael"])
print(pd_series.map(lambda x: x[0].upper() + x[1:-1] + x[-1].upper() ))
| true |
68131c94887ff1da6069d0a22c3a07352769ea24 | ErenBtrk/Python-Fundamentals | /Numpy/NumpyLinearAlgebra/Exercise1.py | 304 | 4.40625 | 4 | '''
1. Write a NumPy program to compute the multiplication of two given matrixes.
'''
import numpy as np
np_matrix1 = np.arange(0,15).reshape(5,3)
print(np_matrix1)
np_matrix2 = (np.ones(9,int)*2).reshape(3,3)
print(np_matrix2)
print(f"Multiplication of matrixes :\n{np.dot(np_matrix1,np_matrix2)}")
| true |
a82bd7fba196142b95745e0fef2c83054557c2cb | ErenBtrk/Python-Fundamentals | /Numpy/NumpySortingAndSearching/Exercise1.py | 407 | 4.5 | 4 | '''
1. Write a NumPy program to sort a given array of shape 2
along the first axis, last axis and on flattened array.
'''
import numpy as np
a = np.array([[10,40],[30,20]])
print("Original array:")
print(a)
print("Sort the array along the first axis:")
print(np.sort(a, axis=0))
print("Sort the array along the last axis:")
print(np.sort(a))
print("Sort the flattened array:")
print(np.sort(a, axis=None)) | true |
924527cad45d7f7c910fc4658a0b60b50517dbc3 | anshu9/LeetCodeSolutions | /easy/add_digits.py | 796 | 4.21875 | 4 | """
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
"""
def add_digits_simple(num):
num_total = 0
while (len(str(num)) > 1):
num_string = str(num)
for i in range(len(num_string)):
num_total = num_total + int(num_string[i])
num = num_total
num_total = 0
return num
def add_digits_digital_root(num):
"""
This method comes solving the digital root for the number given.
The formula for solving the digital root is:
dr = 1 + ((n-1) % 9)
"""
return 1 + ((num - 1) % 9)
| true |
67334c8d4146f1c8ba8580a5c95039a163e4bec2 | juliancomcast/100DaysPython | /Module1/Day09/day09_indexing.py | 1,121 | 4.5 | 4 | #specific items can be retrieved from a list by using its indicies
quotes = ["Pitter patter, let's get ar 'er", "Hard no!", "H'are ya now?", "Good-n-you", "Not so bad.", "Is that what you appreciates about me?"]
print(quotes[0])
print(f"{quotes[2]}\n\t {quotes[3]}\n {quotes[4]}")
#slicing uses the format [start:stop:step], start is inclusive but stop is exclusive
print(quotes[2:5])
#the step can be used to identify how manuy items to skip between returned values
print(quotes[::2])
#the step can also be used to reverse the order of the returned values
print(quotes[::-1])
print("break")
#slicing can be combined with indices to return a sequence from a specific item
print(quotes[0][::2])
print(quotes[0][::-1])
#slicing doesn't only need to applied to lists
wayne = "Toughest Guy in Letterkenny"
print(wayne[::-1])
print("break")
#retrieval by index and slicing can also be applied to a string
print("That's a Texas sized 10-4."[0:9:2])
print("0123456789_acbdef"[0:9:2])
#neither the start, nor the stop values are required when slicing
print(quotes[:])
print(quotes[3:])
print(quotes[:3])
print(quotes[::3]) | true |
4fe297d8354295929f95c9f78e80dd4c90e131d1 | juliancomcast/100DaysPython | /Module1/Day11/day11_augAssign.py | 811 | 4.59375 | 5 | #An augmented assignment improves efficiency because python can iterate a single variable instead of using a temporary one.
#There are several types of augmented assignment operators:
# += : Addition
# -= : Subtraction
# *= : Multiplication
# /= : Division
# //= : Floor Division
# %= : Remainder/Modulus
# **= : Exponent
# <<= : Left Shift
# >>= : Right Shift
# &= : And
# ^= : Exclusive Or (XOR)
# |= : Inclusive Or (OR)
x = 42
x += 3
print(x)
x = 42
x -= 3
print(x)
x = 42
x *= 3
print(x)
x = 42
x /= 3
print(x)
x = 42
x //= 3
print(x)
x = 42
x %= 3
print(x)
x = 42
x **= 3
print(x)
x = 1
x <<= 2
print(x)
x = 4
x >>= 1
print(x)
x = True
y = False
x &= y
print(x)
x = True
y = False
x ^= y
print(x)
x = True
y = False
x |= y
print(x)
x = "Ten Million"
y = "Dollars"
x *= 3
x += y
print(x) | true |
dc853f47647cfa8185eeded8b7b4abd458463413 | jpike/PythonProgrammingForKids | /BasicConcepts/Functions/FirstFunction.py | 828 | 4.4375 | 4 | # This is the "definition" of our first function.
# Notice the "def" keyword, the function's name ("PrintGreeting"),
# the parentheses "()", and the colon ":".
def PrintGreeting():
# Here is the body of our function, which contains the block
# or lines of code that will be executed when our function is
# called. A function body can contain any code just like
# our previous Python programs.
# Note how the body of the function is indented once more
# from the first line of the function definition above.
print("Hello!")
# Here is where we're calling our function. Without the line below,
# the code in our function would not execute, and our program would
# do nothing.
# Notice how we call the function - the function's name ("PrintGreeting"),
# followed by parentheses "()".
PrintGreeting()
| true |
5a63befb4bb2b1b00552c54b2416ad8c1da0b99e | jpike/PythonProgrammingForKids | /BasicConcepts/SyntaxErrors/Volume1_Chapter3_SyntaxErrors.py | 689 | 4.125 | 4 | # String variable statements with syntax errors.
string variable = 'This line should have a string variable.'
1string_variable_2 = "This line should have another string variable."
another_string_variable = 'This line has another string variable."
yet_another_string_variable = "This line has yet another string variable.'
first_string_variable_to_print = This string variable should be printed on the next line
print(first_strng_variable_to_print)
print("Here is the string variable's value again: " + first_strng_variable_to_print)
combined_strings = "Here's a case where multiple strings " + string_variable + first_string_variable_to_print " are being combined"
print(combined_strings)
| true |
4cf02d87043e701ed04156a935e710a10f54e7a0 | techacker/Hackerank | /commandlistchallenge.py | 1,279 | 4.21875 | 4 | print('The program performs the given function on a list in a recursive manner.')
print('First enter an "Integer" to tell how many functions you would like to do.')
print('Then enter the command with appropriate values.')
print()
print('Enter an integer.')
N = int(input())
z = []
def operation(inst, item, ind):
if inst == 'append':
z.append(item)
return z
elif inst == 'insert':
z.insert(ind, item)
return z
elif inst == 'remove':
if item in z:
z.remove(item)
return z
elif inst == 'sort':
z.sort()
return z
elif inst == 'pop':
z.pop(-1)
return z
elif inst == 'reverse':
z.reverse()
return z
elif inst == 'print':
print(z)
#continue
print("Now enter a command in format: 'list_operation number number'")
for i in range(N):
commands = input().split(sep=" ")
if len(commands) == 1:
inst = commands[0]
ind = None
item = None
elif len(commands) == 2:
inst = commands[0]
ind = None
item = int(commands[1])
elif len(commands) == 3:
inst = commands[0]
ind = int(commands[1])
item = int(commands[2])
operation(inst, item, ind)
| true |
68571bcf57eaa90a749cfbeaa39e613e6aeaa7f6 | techacker/Hackerank | /calendarModule.py | 392 | 4.125 | 4 | # Task
# You are given a date. Your task is to find what the day is on that date.
# Input Format
# A single line of input containing the space separated month, day and year, respectively, in MM DD YYYY format.
import calendar
s = input().split()
m = int(s[0])
d = int(s[1])
y = int(s[2])
day = calendar.weekday(y,m,d)
weekday = calendar.day_name.__getitem__(day)
print(weekday.upper())
| true |
3215b0ada68e50621452d257cac18e767d0239e6 | techacker/Hackerank | /alphabetRangoli.py | 811 | 4.25 | 4 | # You are given an integer, N.
# Your task is to print an alphabet rangoli of size N.
# (Rangoli is a form of Indian folk art based on creation of patterns.)
#
# Example : size 5
#
# --------e--------
# ------e-d-e------
# ----e-d-c-d-e----
# --e-d-c-b-c-d-e--
# e-d-c-b-a-b-c-d-e
# --e-d-c-b-c-d-e--
# ----e-d-c-d-e----
# ------e-d-e------
# --------e--------
import string
# To be able to quickly create a list of alphabets.
# Function that actually creates the design.
def print_rangoli(size):
alpha = string.ascii_lowercase
printList = []
for i in range(size):
tmp = '-'.join(alpha[i:size])
printList.append((tmp[::-1] + tmp[1:]).center(4*size - 3, '-'))
print('\n'.join(printList[:0:-1] + printList))
n = int(input())
print_rangoli(n)
| true |
0b0dcbc0b619f5ce51dd55a65a7ede07dfbb5695 | Joeshiett/beginner-python-projects | /classes_example.py | 633 | 4.125 | 4 | class Person: # Instantiate class person as blueprint to create john and esther object
def __init__(self, name, age):
self.name = name
self.age = age
def walking(self): #defining of behaviour inside of class indentation
print(self.name +' ' + 'is walking...')
def speaking(self):
print(self.name + ' is ' + str(self.age) + ' Years old!')
john = Person('John', 22) # Instantiate object and define exact properties name and age
Esther = Person('Esther', 23)
john.walking() #invoking walking behaviour
Esther.walking()
john.speaking() #invoking speaking behaviour
Esther.speaking()
| true |
3f8cd4a99aeffc1420bf4dd4c9af2f1b487914f7 | Jonie23/python-calculator | /calculator.py | 2,095 | 4.375 | 4 | #welcome user
def welcome():
print('''
Welcome to Jones's calculator built with python
''')
welcome()
# calculator()
#define a function to run program many times
def calculator():
#ask what operation user will want to run
operation = input('''
Please type in the calculator operation you will want to run
+ for addition
- for subtraction
* for multiplication
/ for division
** for exponent
% for modulus
''')
#prompt user for inputs
#And convert input to float data type to take floats(decimals)
first_number = float(input('Enter the first number: '))
second_number = float(input('Enter the second number: '))
#Addition Operators
if operation == '+' :
print(' {} + {} = '.format(first_number, second_number)) #use string format to provide more feedback
print(first_number + second_number)
#Subtraction Operator
elif operation == '-' :
print(' {} - {} = '.format(first_number, second_number))
print(first_number - second_number)
#Multiplication Operator
elif operation == '*' :
print(' {} * {} = '.format(first_number, second_number))
print(first_number * second_number)
#Division
elif operation == '/' :
print(' {} / {} = '.format(first_number, second_number))
print(first_number / second_number)
elif operation == '**':
print(' {} / {} = '.format(first_number, second_number))
print(first_number ** second_number)
elif operation == '%':
print(' {} / {} ='.format(first_number, second_number))
print(first_number % second_number)
else:
print('Please type a valid operator and run again.')
repeat()
#function to repeat calculator
def repeat():
repeat_calc = input('''
Do you want to calculate again?
Please type Y for YES or N for NO.
''')
if repeat_calc.upper() == 'Y':
calculator()
elif repeat_calc.upper() == 'N':
print('Alright. Hope to see you another time')
else:
repeat()
#Call calculator
calculator()
| true |
4d7a1ccf22595544dfedd57e7cc2181d18013d5c | milan-crypto/PRACTICE_PYTHON | /Divisors.py | 503 | 4.3125 | 4 | # Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
# (If you don’t know what a divisor is, it is a number that divides evenly into another number.
# For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
number = int(input("Please choose a number to divide: "))
list_range = list(range(1, number+1))
divisorlist = []
for num in list_range:
if number % num == 0:
divisorlist.append(num)
print(divisorlist)
| true |
68247317c0145405a949c82d10f08dd4d535bd52 | dhirajMaheswari/findPhoneAndEmails | /findPhonesAndEmails.py | 1,853 | 4.4375 | 4 | '''this code makes use of the command line to find emails and/or phones from supplied text file
or text using regular expressions.
'''
import argparse, re
def extractEmailAddressesOrPhones(text, kKhojne = "email"):
''' this function uses the regular expressions to extract emails from the
supplied text
import re '''
if kKhojne.lower() == "email":
Pattern = re.compile(r'[a-zA-Z0-9_.]+@[a-zA-Z0-9.]+[a-zA-Z]+') # pattern for email
elif kKhojne.lower() == "phone":
Pattern = re.compile(r'(\d{3}-\d{3}-\d{4})|(\d{10})|(\d{3}\.\d{3}\.\d{4})') # pattern for phone
emailPhoneLists = Pattern.findall(text)
return emailPhoneLists
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--filePath",required = True, help = "path to file.")
ap.add_argument("-f", "--find", required = True, help = "What to find? options are phone and email.")
args = vars(ap.parse_args())
n = len(args)
filep = args["filePath"]
findwhat = args["find"]
sourceText = []
fp = open(filep, 'r')
for l in fp:
sourceText.append(l)
fp.close()
sourceText = ' '.join(sourceText)
if findwhat.lower() == "email":
tt = extractEmailAddressesOrPhones(sourceText)
print("I found {} email addresses in the file {}" .format(len(tt), args["filePath"]))
print("**************")
for w in range(len(tt)):
print("Email address {}: {}".format(w+1, tt[w]))
elif findwhat.lower() == "phone":
tt = extractEmailAddressesOrPhones(sourceText, kKhojne = "phone")
print("I found {} phone numbers in the file {}" .format(len(tt), args["filePath"]))
print("**************")
for w in range(len(tt)):
print("Phone number {}: {}".format(w+1, tt[w]))
else:
print("Invalid request made.")
print("Correct Usage: findPhonesAndEmails.py --filePath fileName --find phone/email.")
| true |
04f9b9e623652aff89ff6261069df137c4e48c25 | ManishVerma16/Data_Structures_Learning | /python/recursion/nested_recursion.py | 226 | 4.125 | 4 | # Recursive program to implement the nested recursion
def nestedFun(n):
if (n>100):
return n-10
else:
return nestedFun(nestedFun(n+11))
number=int(input("Enter any number: "))
print(nestedFun(number)) | true |
88db8f87b369d7626c0f2e0466e60cc73b1d11cc | BrettMcGregor/coderbyte | /time_convert.py | 499 | 4.21875 | 4 | # Challenge
# Using the Python language, have the function TimeConvert(num)
# take the num parameter being passed and return the number of
# hours and minutes the parameter converts to (ie. if num = 63
# then the output should be 1:3). Separate the number of hours
# and minutes with a colon.
# Sample Test Cases
#
# Input:126
#
# Output:"2:6"
#
# Input:45
#
# Output:"0:45"
def time_convert(num):
return str(num // 60) + ":" + str(num % 60)
print(time_convert(126))
print(time_convert(45))
| true |
6eb3619bec8465aab552c5ad9043447217d81334 | BrettMcGregor/coderbyte | /check_nums.py | 578 | 4.1875 | 4 | # Challenge
# Using the Python language, have the function CheckNums(num1,num2)
# take both parameters being passed and return the string true if num2
# is greater than num1, otherwise return the string false. If the
# parameter values are equal to each other then return the string -1.
# Sample Test Cases
#
# Input:3 & num2 = 122
#
# Output:"true"
#
# Input:67 & num2 = 67
#
# Output:"-1"
def check_nums(num1, num2):
if num2 > num1:
return 'true'
elif num2 == num1:
return '-1'
return 'false'
print(check_nums(3, 122))
print(check_nums(67, 67)) | true |
1645c0e1b348decce12680b6e3980b659f87c82a | RahulBantode/Pandas_python | /Dataframe/application-14.py | 702 | 4.40625 | 4 | '''
Write a program to delete the dataframe columns by name and index
'''
import pandas as pd
import numpy as np
def main():
data1 = [10,20,30,40]
data2 = ["a","b","c","d"]
data3 = ["jalgaon","pune","mumbai","banglore"]
df = pd.DataFrame({"Int":data1,"Alpha":data2,"city":data3})
print(df)
#To delete the dataframe entity pandas provide drop function
print("\n Drop Column by Name \n")
print(df.drop("Alpha",axis=1))
print("\n Drop columns by index \n")
print(df.drop(df.columns[:-1],axis=1))
print("\n Drop the row by name/id \n") #we know that by default id will be start from 0
print(df.drop([0,1],axis=0))
if __name__ == '__main__':
main() | true |
141abe7dfe844acd5ce5f999880197ce266a2865 | ziyadedher/birdynet | /src/game/strategy.py | 2,091 | 4.1875 | 4 | """This module contains strategies used to play the game."""
import random
import pygame
from game import config
class Strategy:
"""Defines an abstract strategy that can be built on."""
def __init__(self) -> None:
"""Initialize this abstract strategy.
Do not initialize an abstract strategy.
"""
pass
def get_move(self) -> bool:
"""Return whether or not to move the player."""
raise NotImplementedError
class IdleStrategy(Strategy):
"""Defines a strategy to do nothing at all."""
def __init__(self) -> None:
"""Initialize this idle strategy."""
super().__init__()
def get_move(self) -> bool:
"""Return whether or not to move the player."""
return False
class InputStrategy(Strategy):
"""Defines a strategy to move when the user hits space."""
_key_down_this_frame: bool = False
def __init__(self) -> None:
"""Initialize this input strategy."""
super().__init__()
@classmethod
def key_down(cls, val: bool):
"""Flag that the input key has or has not been pressed this frame."""
cls._key_down_this_frame = val
def get_move(self) -> bool:
"""Return whether or not to move the player."""
return self._key_down_this_frame
class WordStrategy(Strategy):
"""Defines a strategy to move depending on word."""
_current_word: str
def __init__(self) -> None:
"""Initialize this word strategy."""
super().__init__()
self._current_word = ""
self.new_word()
def new_word(self) -> None:
"""Assign a new word for the strategy."""
self._current_word = random.choice(config.WORDS).lower()
print(self._current_word)
def get_move(self) -> bool:
"""Return whether or not to move the player."""
if pygame.key.get_pressed()[ord(self._current_word[0])]:
self._current_word = self._current_word[1:]
if not self._current_word:
self.new_word()
return True
return False
| true |
dadaab812f4ce7ee2e0a5a95436088f109a0a63d | saadhasanuit/Lab-04 | /question 11.py | 487 | 4.125 | 4 | print("Muhammad Saad Hasan 18B-117-CS Section:-A")
print("LAB-04 -9-NOV-2018")
print("QUESTION-11")
# Program which calculates the vowels from the given string.
print("This program will count total number of vowels from user defined sentence")
string=input("Enter your string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)
| true |
877a89267774f79b7b4516e112c8f73a1ebad162 | MariyaAnsi/Python-Assignments | /Assignment_5.py | 363 | 4.34375 | 4 | #Write a program that prompts for a file name, then opens that file and reads through the file,
#and print the contents of the file in upper case.
fname = input("Enter file name: ")
fh = open(fname)
print("fh___", fh)
book = fh.read()
print("book___", book)
bookCAPITAL = book.upper()
bookCAPITALrstrip = bookCAPITAL.rstrip()
print(bookCAPITALrstrip) | true |
e23db0c2b2df63611d1066b76cf1606fd40852ba | TewariUtkarsh/Python-Programming | /Tuple.py | 553 | 4.1875 | 4 | myCars = ("Toyota","Mercedes","BMW","Audi","BMW") #Tuple declared
print("\nTuple: ",myCars)
# Tuple has only 2 built in functions:
# 1.count()- To count the number of Element ,that is passed as the Parameter, in the Tuple
print("\nNumber of times BMW is present in the Tuple: ",myCars.count("BMW"))
print("Number of times Audi is present in the Tuple: ",myCars.count('Audi'))
# 2.index()- Returns the Index of the Element that is passed as an Arguement
print("\nToyota is present at index ",myCars.index("Toyota"))
print(f"\nTuple: {myCars}")
| true |
6717306792716cbc062e400eeb7c6d434f28544a | gorkememir/PythonProjects | /Basics/pigTranslator.py | 1,160 | 4.21875 | 4 | # Take a sentence from user
original = input("Please enter a sentence: ").strip().lower()
# Split it into words
splitted = original.split()
# Define a new list for storing the final sentence
new_words = []
# Start a for loop to scan all the splitted words one by one
for currentWord in splitted:
# If the first letter of the word in the current loop is a vowel, add "Yay" at the end,
# and store this as the new_word
if currentWord[0] in "aieou":
new_word = currentWord + "Yay"
# If the first letter is not a vowel, scan through the word until you find a vowel,
# mark the vowel position, split the word as consonants up to that vowel and the rest.
# set new_word as such: cons + theRest + "Ay"
else:
vowelPos = 0
for letter in currentWord:
if letter not in "aieou":
vowelPos = vowelPos + 1
else:
break
new_word = currentWord[vowelPos:] + currentWord[:vowelPos] + "Ay"
# Append the new_word to the new_words list
new_words.append(new_word)
# Turn the list into a sentence, and print it.
output = " ".join(new_words)
print(output) | true |
a23034a6ada538ad5c35ec45b514900a68183d1f | GospodinJovan/raipython | /Triangle.py | 1,234 | 4.5625 | 5 | """""
You are given the lengths for each side on a triangle. You need to find all three angles for this triangle. If the given side lengths cannot form a triangle
(or form a degenerated triangle), then you must return all angles as 0 (zero). The angles should be represented as a list of integers in ascending order.
Each angle is measured in degrees and rounded to the nearest integer number (Standard mathematical rounding).
triangle-angles
Input: The lengths of the sides of a triangle as integers.
Output: Angles of a triangle in degrees as sorted list of integers.
Example:
checkio(4, 4, 4) == [60, 60, 60]
checkio(3, 4, 5) == [37, 53, 90]
checkio(2, 2, 5) == [0, 0, 0]
1
2
3
How it is used: This is a classical geometric task. The ideas can be useful in topography and architecture. With this concept you can measure an angle without the need for a protractor.
Precondition:
0 < a,b,c ≤ 1000
"""
from math import acos, degrees
get_angle = lambda a, b, c: round(degrees(acos((b*b+c*c-a*a)/(float(2*b*c)))))
def checkio(a, b, c):
if a + b <= c or b + c <= a or c + a <= b:
return [0, 0, 0]
return sorted([get_angle(a, b, c), get_angle(b, c, a), get_angle(c, a, b)])
a=2
b=4
c=5
print (checkio(a,b,c))
| true |
6681c74eed15a86ce699efb6e28cbf1e98630cfb | bipuldev/US_Bike_Share_Data_Analysis | /Bike_Share_Analysis_Q4a.py | 2,117 | 4.4375 | 4 | ## import all necessary packages and functions.
import csv # read and write csv files
from datetime import datetime # operations to parse dates
from pprint import pprint # use to print data structures like dictionaries in
# a nicer way than the base print function.
def number_of_trips(filename):
"""
This function reads in a file with trip data and reports the number of
trips made by subscribers, customers, and total overall.
"""
with open(filename, 'r') as f_in:
# set up csv reader object
trip_reader = csv.DictReader(f_in)
# initialize count variables
n_subscribers = 0
n_customers = 0
# tally up ride types
for row in trip_reader:
if row['user_type'] == 'Subscriber':
n_subscribers += 1
else:
n_customers += 1
# compute total number of rides
n_total = n_subscribers + n_customers
# return tallies as a tuple
return(n_subscribers, n_customers, n_total)
## Modify this and the previous cell to answer Question 4a. Remember to run ##
## the function on the cleaned data files you created from Question 3. ##
#data_file = './data/NYC-2016-Summary.csv'
city_info = {'Washington':'./data/Washington-2016-Summary.csv',
'Chicago': './data/Chicago-2016-Summary.csv',
'NYC': './data/NYC-2016-Summary.csv'}
for city, data_file in city_info.items():
n_subscribers, n_customers, n_total = number_of_trips(data_file)
n_proportion_subscribers = round(n_subscribers/n_total, 4)
n_proportion_customers = round(n_customers/n_total,4)
print ("City: {0} ".format(city))
print ("Subscribers: {0}".format(n_subscribers))
print ("Customers: {0}".format(n_customers))
print ("Total Trips: {0}".format(n_total))
print ("Subscriber proportion: {0}".format(n_proportion_subscribers))
print ("Customer proportion: {0}".format(n_proportion_customers))
print ()
| true |
006d4318ecc5f77efd912464de98ef2cf852dd42 | NataliaBeckstead/cs-module-project-recursive-sorting | /src/searching/searching.py | 1,278 | 4.40625 | 4 | # TO-DO: Implement a recursive implementation of binary search
def binary_search(arr, target, start, end):
if start > end:
return -1
mid = (start + end) // 2
if arr[mid] == target:
return mid
elif target < arr[mid]:
return binary_search(arr, target, start, mid-1)
else:
return binary_search(arr, target, mid+1, end)
# STRETCH: implement an order-agnostic binary search
# This version of binary search should correctly find
# the target regardless of whether the input array is
# sorted in ascending order or in descending order
# You can implement this function either recursively
# or iteratively
def agnostic_binary_search(arr, target):
left = 0
right = len(arr)-1
ascending_order = arr[0] < arr[right]
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
if ascending_order:
if target < arr[mid]:
right = mid - 1
else:
left = mid + 1
else:
if target > arr[mid]:
right = mid - 1
else:
left = mid + 1
return -1
print(agnostic_binary_search([1, 2, 3, 4, 5], 4))
print(agnostic_binary_search([5, 4, 3, 2, 1], 4)) | true |
70dcd1ee1a606f67646d7e8f7f3862908e3a0c76 | JannickStaes/LearningPython | /TablePrinter.py | 1,061 | 4.21875 | 4 | #! python3
# prints a table of a list of string lists
tableDataExample = [['apples', 'oranges', 'cherries', 'banana'],
['Alice', 'Bob', 'Carol', 'David'],
['dogs', 'cats', 'moose', 'goose']]
def determineMaxColumnWidths(tableData):
columnWidths = [] #a list to store the max length of each string row, to be used as the max column width
for stringList in tableData:
maxLength = 0
for word in stringList:
if len(word) > maxLength:
maxLength = len(word)
columnWidths.append(maxLength)
return columnWidths
def printTable(tableData):
columnWidths = determineMaxColumnWidths(tableDataExample)
rows = len(tableData[0]) #all lists are equal length so we can just take the first one
columns = len(tableData)
for row in range(rows):
printRow = []
for column in range(columns):
printRow.append( tableData[column][row].rjust(columnWidths[column]))
line = ' '.join( printRow )
print(line)
printTable(tableDataExample) | true |
af175e0913b72d5c984cd90490f8405d8843d258 | Hubert51/pyLemma | /Database_sqlite/SecondPart_create class/Test_simplify_function/class2.py | 1,440 | 4.125 | 4 | import sqlite3
class DatabaseIO:
l12 = [1, 2, 3]
d_table = {}
def __init__(self, name):
"""
In my opinion, this is an initial part. If I have to use variable from
other class, I can call in this part and then call to the following
part.
Some variable must be renamed again.
"""
self.con = sqlite3.connect(name)
self.cur = self.con.cursor()
d_table = {}
def create_table1(self):
table_name = raw_input("Please entre the table name ==> ")
i = 0
l = [] # This list stores the info which is used to create table
l2 = [] # This list stores the table info which will be useful when we need to know the columns of table
d_table = dict()
check = True
while check:
column = raw_input('''Please entre column with this data tpye such as
INTEGER or TXT (if finish, type: end) ==> ''')
if column != "end":
l.append(column)
l2.append(column)
else:
break
d_table[table_name] = l2
key = raw_input("Please enter the key ==> ")
command = "CREATE TABLE {:} (".format(table_name)
for i in l:
command += "{:} NOT NULL,".format(i)
command += "PRIMARY KEY ({:}))".format(key)
self.cur.execute(command)
self.con.commit()
| true |
5a2dd5cb914cdbd397847ab8d77521e0612580e0 | shubhranshushivam/DSPLab_22-10-2020 | /ques8.py | 605 | 4.1875 | 4 | # 8. Find the Union and Intersection of the two sorted arrays
def union(arr1,arr2):
res=arr1+arr2
res=set(res)
return list(res)
def intersection(arr1, arr2):
res=[]
for i in arr1:
if i in arr2:
res.append(i)
return res
n1=int(input("Enter size of 1st array="))
arr1, arr2=[],[]
for i in range(n1):
arr1.append(int(input("ENter element=")))
n2=int(input("Enter size of 2nd array="))
for i in range(n2):
arr2.append(int(input("ENter element=")))
print("UNION=",union(arr1, arr2))
print("INTERSECTION=",intersection(arr1, arr2)) | true |
fd8b7a3eb61438223ca6563de920c9e7f8eab7a4 | jadenpadua/Data-Structures-and-Algorithms | /efficient/validParenthesis/validParenthesis.py | 1,772 | 4.125 | 4 | #Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
#imports functions from our stack data structure file
from stack import Stack
#helper method checks if our open one and closed are the same
def is_match(p1, p2):
if p1 == "(" and p2 == ")":
return True
elif p1 == "{" and p2 == "}":
return True
elif p1 == "[" and p2 == "]":
return True
else:
return False
#can be called to check if paren are balanced
def is_paren_balanced(paren_string):
#creates new stack object, sets balanced flag to true and starts an index that will iterate through string
s = Stack()
is_balanced = True
i = 0
#while string is still balanced it will loop through string
while i < len(paren_string) and is_balanced:
#current parenthesis pointer is on
paren = paren_string[i]
#pushes element to stack if in those value ranges case where open paren
if paren in "([{":
s.push(paren)
#case where closing paren
else:
#returns false if only one closing paren in stack
if s.is_empty():
is_balanced = False
#pops our open paren, calls helper
else:
#pops our open paren
top = s.pop()
#checks if the open paren and closed one are equal
if not is_match(top, paren):
is_balanced = False
i += 1
#if stack is empty and balanced by default return true
if s.is_empty() and is_balanced:
return True
else:
return False
print(is_paren_balanced("(((({}))))"))
print(is_paren_balanced("[][]]]"))
print(is_paren_balanced("[][]"))
| true |
3b98b69d8a5182fca01f3ceea90444eff427a5a6 | jadenpadua/Data-Structures-and-Algorithms | /bruteforce/largest_swap.py | 370 | 4.21875 | 4 | Write a function that takes a two-digit number and determines if it's the largest of two possible digit swaps.
To illustrate:
largest_swap(27) ➞ False
largest_swap(43) ➞ True
def largest_swap(num):
original = num
d = 0
rev = 0
while num > 0:
d = num % 10
num = int(num/10)
rev = rev*10 + d
if rev > original:
return False
else:
return True
| true |
d6404fac5d7e72741972ade1038e83de849ac709 | jadenpadua/Data-Structures-and-Algorithms | /bruteforce/needleInHaystack.py | 564 | 4.25 | 4 | # Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
def strStr(haystack,needle):
for i in range(len(haystack) - len(needle) + 1):
if haystack[i:i+len(needle)] == needle:
return i
return - 1
haystack = "Will you be able to find the needle in this long haystack sentence?"
needle = "te"
print("Haystack: Will you be able to find the needle in this long haystack sentence?")
print("Needle: te")
print("The index of the needle in the haystack is: ")
print(strStr(haystack,needle))
| true |
3702a2e59ec372033ed9f0f3cb2aa2af7bc4653b | jadenpadua/Data-Structures-and-Algorithms | /bruteforce/alternating_one_zero.py | 626 | 4.46875 | 4 | Write a function that returns True if the binary string can be rearranged to form a string of alternating 0s and 1s.
Examples
can_alternate("0001111") ➞ True
# Can make: "1010101"
can_alternate("01001") ➞ True
# Can make: "01010"
can_alternate("010001") ➞ False
can_alternate("1111") ➞ False
def can_alternate(s):
if '1' not in s or '0' not in s:
return False
else:
zero_count = 0
one_count = 0
for i in range(len(s)):
if s[i] == '0':
zero_count += 1
else:
one_count += 1
if abs(zero_count - one_count) == 1 or abs(zero_count - one_count) == 0:
return True
else:
return False
| true |
0ccbe214b5bc91d4c53e4f16218b0835b1b9d513 | jadenpadua/Data-Structures-and-Algorithms | /bruteforce/digits_in_list.py | 689 | 4.3125 | 4 | #Create a function that filters out a list to include numbers who only have a certain number of digits.
#Examples
#filter_digit_length([88, 232, 4, 9721, 555], 3) ➞ [232, 555]
# Include only numbers with 3 digits.
#filter_digit_length([2, 7, 8, 9, 1012], 1) ➞ [2, 7, 8, 9]
# Include only numbers with 1 digit.
#filter_digit_length([32, 88, 74, 91, 300, 4050], 1) ➞ []
# No numbers with only 1 digit exist => return empty list.
#filter_digit_length([5, 6, 8, 9], 1) ➞ [5, 6, 8, 9]
# All numbers in the list have 1 digit only => return original list.
def filter_digit_length(lst, num):
temp = []
for item in lst:
if len(str(item)) == num:
temp.append(item)
return temp
| true |
67c62395c49f7327da7f66d2ab1d04b96886b53a | UnicodeSnowman/programming-practice | /simulate_5_sided_die/main.py | 565 | 4.1875 | 4 | # https://www.interviewcake.com/question/simulate-5-sided-die?utm_source=weekly_email
# You have a function rand7() that generates a random integer from 1 to 7.
# Use it to write a function rand5() that generates a random integer from 1 to 5.
# rand7() returns each integer with equal probability. rand5() must also return each integer with equal probability.
from random import random
from math import floor
def rand_7():
return floor(random() * 7) + 1
def rand_5():
rando = rand_7()
while rando > 5:
rando = rand_7()
return rando
print(rand_5())
| true |
7443a894f9ca0f6e6276d36e49a12f27dbd76b80 | JITHINPAUL01/Python-Assignments | /Day_5_Assignment.py | 1,654 | 4.25 | 4 | """
Make a generator to perform the same functionality of the iterator
"""
def infinite_sequence(): # to use for printing numbers infinitely
num = 0
while True:
yield num
num += 1
for i in infinite_sequence():
print(i, end=" ")
"""
Try overwriting some default dunder methods and manipulate their default behavior
"""
class distance:
def __init__(self, ft=0,inch=0):
self.ft=ft
self.inch=inch
def __add__(self,x):
temp=distance()
temp.ft=self.ft+x.ft
temp.inch=self.inch+x.inch
if temp.inch>=12:
temp.ft+=1
temp.inch-=12
return temp
def __str__(self):
return 'ft:'+str(self.ft)+' in: '+str(self.inch)
d1=distance(3,10)
d2=distance(4,4)
print(f"d1= {d1} d2={d2}")
d3=d1+d2 # overridden the + operator __add__
print(d3)
"""
Write a decorator that times a function call using timeit
start a timer before func call
end the timer after func call
print the time diff
"""
import timeit
def time_function(inner_fun):
def time(*args, **kwargs):
t_start=timeit.default_timer()
print(f"satrt time : {t_start}")
inner_fun(*args, **kwargs)
t_end=timeit.default_timer()
print(f"end time : {t_end}")
run_time=t_end-t_start
print(f"execution time : {run_time}")
return time
@time_function
def my_loop_method(i):
total=0
print(f'I am a loop method to sum numbers in entered range having decorator to track time of execution!')
for i in range(0,i):
total +=i
my_loop_method(10000) # takes more execution time
my_loop_method(10)
| true |
36a3aa0df6425f0876442c374eca48c0c709d592 | shahasifbashir/LearnPython | /ListOver/ListOverlap.py | 591 | 4.28125 | 4 | import random
#This Examples gives the union of two Lists
A = [1,2,3,4,5,6,7,8,5,4,3,3,6,7,8]
B=[6,7,8,9,4,3,5,6,78,97,2,3,4,5,5,6,7,7,8]
# we will use the set becouse a set contains unique elemets only ann then use an and operator
print(list(set(A)&set(B)))
# The same example using Random Lists
A= range(1,random.randint(1,30))
B= range(1,random.randint(1,40))
print("_____________________________")
print(list(set(A)&set(B)))
myList=[]
# Ths same example using a for loop
for item in A:
if item in B:
if item not in myList:
myList.append(item)
print(myList)
| true |
57992d8e576a9c5df264083e74d67b6d29ae00c9 | susanbruce707/Virtual-Rabbit-Farm | /csv_mod.py | 1,205 | 4.125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Feb 13 00:27:26 2020
@author: susan
Module to read CSV file into nested dictionary and
write nested dictionar to CSV file
rd_csv requires 1 argument file, as file name for reading
wrt_csv requires 2 arguments file name and dictionary name to write CSV file.
"""
import csv
def wrt_csv(file, dictionary):
with open(file, 'w',newline='') as f:
dic = dictionary[0]
header = list(dic.keys())
writer = csv.DictWriter(f, fieldnames=header)
writer.writeheader()
for dic in dictionary:
writer.writerow(dictionary[dic])
def rd_csv(file):
dictionary = {}
with open(file) as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
dictionary[line_count] = row
line_count += 1
return dictionary
#rabbits = rd_csv('rabbits.csv') # example use read
# wrt_csv('rabbits1.csv', rabbits) # example use write
#k = len(list(rabbits.keys()))
#lrk = []
#for num in range(k):
# print(num)
# rk = list(rabbits[num].values())
# lrk.append(rk)
#print(lrk) | true |
29e7fdf995e4f6245899f4a61aac03ac1cac6426 | fadhilmulyono/cp1404practicals | /prac_09/sort_files_1.py | 910 | 4.25 | 4 | """
CP1404/CP5632 Practical
Sort Files 1.0
"""
import os
def main():
"""Sort files to folders based on extension"""
# Specify directory
os.chdir('FilesToSort')
for filenames in os.listdir('.'):
# Check if there are any files in directory
if os.path.isdir(filenames):
continue
# Split the filename between the file name and extension
extension = filenames.split('.')[-1]
# If folder does not exist in directory, create the folder
try:
os.mkdir(extension)
except FileExistsError:
pass
# Move the files to the folders that were just created
os.rename(filenames, "{}/{}".format(extension, filenames))
print()
for directory_name, subdirectories, filenames in os.walk('.'):
print("Directory:", directory_name)
print("\tcontains files:", filenames)
main()
| true |
6e6569c90097c6ae65b39aa6736e234fbf6f4bdf | BruderOrun/PY111-april | /Tasks/a0_my_stack.py | 798 | 4.1875 | 4 | """
My little Stack
"""
stak = []
def push(elem) -> None:
"""
Operation that add element to stack
:param elem: element to be pushed
:return: Nothing
"""
stak.append(elem)
def pop():
"""
Pop element from the top of the stack
:return: popped element
"""
if stak == []:
return None
else:
return stak.pop()
def peek(ind: int = 0):
"""
Allow you to see at the element in the stack without popping it
:param ind: index of element (count from the top)
:return: peeked element
"""
try:
s = stak[ind - 1]
except IndexError:
return None
else:
return s
def clear() -> None:
"""
Clear my stack
:return: None
"""
stak.clear()
return None
| true |
7f72b1120e1a02c17ccc9113866e32cab1164830 | tjgiannhs/Milisteros | /GreekBot/greek_preprocessors.py | 1,609 | 4.15625 | 4 | """
Statement pre-processors.
"""
def seperate_sentences(statement):
'''
Adds a space after commas and dots to seperate sentences
If this results in more than one spaces after them another pre-processor will clean them up later
:param statement: the input statement, has values such as text
:return: the statement with the modified text
'''
statement.text = statement.text.replace(",",", ")
statement.text = statement.text.replace(".",". ")
return statement
def capitalize(statement):
'''
Makes the first letter after dots capital
Adds a dot at the end if no other punctuation exists already
:param statement: the input statement, has values such as text
:return: the statement with the modified text
'''
text = ""
for protash in statement.text.split('.'):
text = text + protash.strip().capitalize() +"."
if text[-2]=="." or text[-2]=="!" or text[-2]=="?" or text[-2]==";":
statement.text = text[:-1]
else:
statement.text = text
return statement
def clean_apostrophes(statement):
'''
Removes apostrophes, both single and double
Uses a different way to remove the double because replace wouldn't work correctly with them
:param statement: the input statement, has values such as text
:return: the statement with the modified text
'''
text = ""
statement.text = statement.text.replace("'","")
for protash in statement.text.split('"'):
text = text+protash
statement.text = text
return statement | true |
24409c8cc7b6c497409449e8327e5f16a2162020 | qufeichen/Python | /asciiUni.py | 352 | 4.15625 | 4 | # program that prints out a table with integers from decimal 0 to 255, it's hex number, and the character corresponding to the unicode with UTF-8 encoding
# using a loop
for x in range(0, 256):
print('{0:d} {0:#04x} {0:c}'.format(x))
# using list comprehension
ll = [('{0:d} {0:#04x} {0:c}'.format(x)) for x in range(0, 256)]
print( "\n".join(ll) )
| true |
f2a34668c27bc15c17545666e077ad857937c554 | PravinSelva5/LeetCode_Grind | /Dynamic Programming/BestTimetoBuyandSellaStock.py | 1,006 | 4.125 | 4 | '''
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
-------
RESULTS
-------
Time Complexity: O(N)
Space Complexity: O(1)
Runtime: 64 ms, faster than 52.70% of Python3 online submissions for Best Time to Buy and Sell Stock.
Memory Usage: 15 MB, less than 70.66% of Python3 online submissions for Best Time to Buy and Sell Stock.
'''
class Solution:
def maxProfit(self, prices: List[int]) -> int:
buyPrice = 10000
profit = 0
for price in prices:
if buyPrice > price:
buyPrice = price
else:
profit = max(profit, price - buyPrice)
return profit | true |
e238362a9fe70015b725ea93b7d4ea60663dfcab | PravinSelva5/LeetCode_Grind | /RemoveVowelsFromAString.py | 1,081 | 4.21875 | 4 | '''
Given a string S, remove the vowels 'a', 'e', 'i', 'o', and 'u' from it, and return the new string.
Example 1:
Input: "leetcodeisacommunityforcoders"
Output: "ltcdscmmntyfrcdrs"
Example 2:
Input: "aeiou"
Output: ""
Runtime: 28 ms, faster than 75.93% of Python3 online submissions for Remove Vowels from a String.
Memory Usage: 14.3 MB, less than 99.95% of Python3 online submissions for Remove Vowels from a String
'''
class Solution:
def removeVowels(self, S: str) -> str:
"""
- Create a vowel_list that contains the possible vowels
- Iterate through the given string
- If current letter IN vowel_list
- pop the letter out
- ELSE
CONTINUE WITH the loop
"""
vowel_list = ['a', 'e', 'i', 'o', 'u']
output = ""
for letter in S:
if letter not in vowel_list:
output += letter
else:
continue
return output
| true |
1f5c2a31e43d65a1bb470666f432c53b1e0bd8c9 | PravinSelva5/LeetCode_Grind | /SlidingWindowTechnique.py | 1,204 | 4.125 | 4 | # It is an optimization technique.
# Given an array of integers of size N, find maximum sum of K consecutive elements
'''
USEFUL FOR:
- Things we iterate over sequentially
- Look for words such as contiguous, fixed sized
- Strings, arrays, linked-lists
- Minimum, maximum, longest, shortest, contained with a specific set
- maybe we need to calculate something
'''
def maxSum(arr, WindowSize):
arraySize = len(arr)
if( arraySize <= WindowSize):
print("Invalid operation")
return -1
window_sum = sum( [arr[i] for i in range(WindowSize)])
max_sum = window_sum
# To compute the new sum, we remove (subtract) the first element in the previous window AND add the second element in the NEW WINDOW
for i in range(arraySize-WindowSize):
window_sum = window_sum - arr[i] + arr[i + WindowSize] # This is where you subtract the first element from the previous window and ADD the second element of the NEW WINDOW
max_sum = max(window_sum, max_sum)
return max_sum
arr = [80, -50, 90, 100]
k = 2 # window size
answer = maxSum(arr, k) # Final answer should be 190
print(answer) | true |
41fa5b705be4a2f44f143a811186796fa94f9e01 | PravinSelva5/LeetCode_Grind | /Trees and Graphs/symmetricTree.py | 1,008 | 4.28125 | 4 | '''
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
-------------------
Results
-------------------
Time Complexity: O(N)
Space Complexity: O(N)
Runtime: 28 ms, faster than 93.85% of Python3 online submissions for Symmetric Tree.
Memory Usage: 14.4 MB, less than 52.06% of Python3 online submissions for Symmetric Tree.
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isMirror(self,node1, node2):
if node1 == None and node2 == None:
return True
if node1 == None or node2 == None:
return False
return (node1.val == node2.val) and (self.isMirror(node1.left, node2.right)) and (self.isMirror(node1.right, node2.left))
def isSymmetric(self, root: TreeNode) -> bool:
return self.isMirror(root, root) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.