blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
ef28f1eb265cb90c47a2c1fec8c714d3542f7d8c | Toruitas/Python | /Practice/Daily Programmer/DP13 - Find number of day in year.py | 2,659 | 4.40625 | 4 | __author__ = 'Stuart'
"""
http://www.reddit.com/r/dailyprogrammer/comments/pzo4w/2212012_challenge_13_easy/
Find the number of the year for the given date. For example, january 1st would be 1, and december 31st is 365.
for extra credit, allow it to calculate leap years, as well.
https://docs.python.org/3.4/library/datetime.html
http://www.tutorialspoint.com/python/python_date_time.htm
"""
def test_leap(date):
"""
Year evenly divisible by 4, by 400, but not 100.
:param date:
:return:Boolean for leap year confirmation
"""
if date % 400 != 0 and date % 100 == 0:
return False
elif date %4 == 0:
return True
else:
return False
def lazyway(year,month,day):
"""
Returns number of day in teh year. Includes leap year calculation already. Super Lazy.
d.timetuple() == time.struct_time((d.year, d.month, d.day, 0, 0, 0, d.weekday(), yday, -1))
yday = d.toordinal() - date(d.year, 1, 1).toordinal() + 1 is the day number within the current year starting with 1 for January 1st.
:param year: Year you wanna check
:param month: Month
:param day: Day
:return: ordinal date in the year
"""
that_day = datetime.date(year,month,day)
return that_day.timetuple()[7]
if __name__ == "__main__":
import calendar # if I were a lazy man, I could use this to test for leapness
import datetime # or could use date.timetuple()'s yday to find it easily from a date object
months = {"january":1,
"february":2,
"march":3,
"april":4,
"may":5,
"june":6,
"july":7,
"august":8,
"september":9,
"october":10,
"november":11,
"december":12}
days = [31,28,31,30,31,30,31,31,30,31,30,31] #days in each month
thedate = input("What is the date you want to test? Format January 21st, 1987 please.")
thedate = thedate.split()
thedate[0],thedate[1],thedate[2] = thedate[0].lower(),int(thedate[1].replace("st","").replace("th","").replace(",","")),int(thedate[2])
month_index = months[thedate[0]]-1 #since month indexes start at 1 in the dictionary, but 0 in the days list
year = thedate[2]
month = months[thedate[0]] #months start at 1 for this library too, so no need to -1
day = thedate[1]
print(lazyway(year,month,day))
if test_leap(thedate[2]): #test for leapness
days[1] += 1
numday = 0
for i in range(month_index): #adds all the months before the entered month
numday += days[i]
numday += thedate[1] #then adds the date of current month
print(numday) | true |
185f03b68bac3ca937ecee2d5b4b033314fb3d06 | Toruitas/Python | /Practice/Daily Programmer/Random Password Generator.py | 811 | 4.15625 | 4 | __author__ = 'Stuart'
"""
Random password generator
default 8 characters, but user can define what length of password they want
"""
def password_assembler(length=8):
"""
Takes user-defined length (default 8) and generates a random password
:param length: default 8, otherwise user-defined
:return: password of length length
"""
password = ""
for i in range(length+1):
password += random_character()
return password
def random_character():
"""
random character generator
:return: random character
"""
characters = string.printable
return random.choice(characters)
if __name__ == "__main__":
import random
import string
length = input("What length password would you like? Default is 8")
print(password_assembler(int(length))) | true |
47567240773ccbedbccd4a4f098e3911419cd163 | Toruitas/Python | /Practice/Daily Exercises/day 11 practice.py | 1,409 | 4.25 | 4 | _author_ = 'stu'
#exercise 11
#time to complete: 15 minutes
"""Ask the user for a number and determine whether the number is prime or not.
(For those who have forgotten, a prime number is a number that has no divisors.)
You can (and should!) use your answer to Exercise 4 to help you.
Take this opportunity to practice using functions, described below."""
"""
def get_integer(help_text="Give me a number: "): #using help_text = gives it a default argument, for when there is no argument submitted
return int(input(help_text))
age = get_integer("Tell me your age: ")
school_year = get_integer("What grade are you in? ")
if age > 15:
print("You are over the age of 15")
print("You are in grade " + str(school_year))
"""
def get_number(help_text="Give me a number: "): #gets number to test from user
return int(input(help_text))
def prime_test(number):
divisors = []
for i in range(2,number/2 +1): #iterates through the list of values. Excludes 1, by definition of prime only divisible by self and 1.
if number % i == 0: #tests if it is a divisor
divisors.append(i) #adds to list of divisors
if len(divisors) == 0: #if any numbers tested have been added to the list, returns prime/not prime
return number," is a prime number."
else:
return number," is not a prime number."
print prime_test(get_number("Give me a number to test: ")) | true |
e825be3736c83d1579e2e155ac0a1c2d3bc8255c | fabiancaraballo/CS122-IntroToProg-ProbSolv | /project1/P1_hello.py | 213 | 4.25 | 4 | print("Hello World!")
print("")
name = "Fabian"
print("name")
print(name)
#print allows us to print in the console whenever we run the code.
print("")
ambition = "I want to be successful in life."
print(ambition)
| true |
634ad3c17d105f95cd627425354fd78826177710 | meridian-school-computer-science/pizza | /src/classes_pizza.py | 930 | 4.53125 | 5 | # classes for pizza with decorator design
class Pizza:
"""
Base class for the building of a pizza.
Use decorators to complete the design of each pizza object.
"""
def __init__(self, name, cost):
self.name = name
self.cost = float(cost)
def __repr__(self):
return f"Pizza({self.name})"
def __str__(self):
return f"{self.name}"
def get_cost(self):
return self.cost
class PizzaType(Pizza):
def __init__(self, name, cost):
super().__init__(name, cost)
class PizzaElement(Pizza):
def __init__(self, name, cost, pizza):
super().__init__(name, cost)
self.decorate = pizza
def get_cost(self):
return self.cost + self.decorate.get_cost()
def __str__(self):
return self.decorate.__str__() + f" + {self.name}"
@property
def show_cost(self):
return f" ${self.get_cost():.2f}"
| true |
684ada57ad12df9053cad5f14c71452e1625c0f2 | bear148/Bear-Shell | /utils/calculatorBase.py | 637 | 4.28125 | 4 | def sub(num1, num2):
return int(num1)-int(num2)
def add(num3, num4):
return int(num3)+int(num4)
def multiply(num5, num6):
return int(num5)*int(num6)
def divide(num7, num8):
return int(num7)/int(num8)
# Adding Strings vs Adding Ints
# When adding two strings together, they don't combine into a different number, they are only put next to eachother.
# For example, if I were to add str(num7)+str(num8), and num7 == "4" then num8 == "6", instead of getting 10, you'd
# get 46. However, with an integer, it add the numbers and you'd get 10. So make sure when doing this you make the numbers integers
# before the get added together. | true |
bf3a5caa3e68bdf5562bf7270ba11befeb5ab21c | jijo125-github/Solving-Competitive-Programs | /LeetCode/0001-0100/43-Multiply_strings.py | 832 | 4.28125 | 4 | """ Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
"""
class Solution:
def multiply(self, num1: str, num2: str) -> str:
li, lj = len(num1), len(num2)
i, j = 0, 0
n1, n2 = 0, 0
while i < li:
n1 += (ord(num1[i]) - 48) * (10 ** (li-i-1))
i += 1
while j < lj:
n2 += (ord(num2[j]) - 48) * (10 ** (lj-j-1))
j += 1
return str(n1*n2)
obj = Solution()
num1, num2 = "123", "456"
print(obj.multiply(num1,num2)) | true |
95e04761f619193d2190a9d62d5ec9c0ffe0beea | SharmaManish/crimsononline-assignments | /assignment1/question2.py | 863 | 4.15625 | 4 | def parse_links_regex(filename):
"""question 2a
Using the re module, write a function that takes a path to an HTML file
(assuming the HTML is well-formed) as input and returns a dictionary
whose keys are the text of the links in the file and whose values are
the URLs to which those links correspond. Be careful about how you handle
the case in which the same text is used to link to different urls.
For example:
You can get file 1 <a href="1.file">here</a>.
You can get file 2 <a href="2.file">here</a>.
What does it make the most sense to do here?
"""
pass
def parse_links_xpath(filename):
"""question 2b
Do the same using xpath and the lxml library from http://lxml.de rather
than regular expressions.
Which approach is better? (Hint: http://goo.gl/mzl9t)
"""
pass | true |
130b0896fc57c51d0601eea2483449f51de4142d | xfLee/Python-DeepLearning_CS5590 | /Lab_2/Source/Task_1.py | 640 | 4.1875 | 4 | """
Python program that accepts a sentence as input and remove duplicate words.
Sort them alphanumerically and print it.
"""
# Taking the sentence as input
Input_Sentence = input('Enter any sentence: ')
# Splitting the words
words = Input_Sentence.split()
# converting all the strings to lowercase
words = [element.lower() for element in words]
# Taking the words as a set to remove the duplicate words
words = set(words)
# Now taking the set of words as list
word_list = list(words)
# Sorting the words alphanumerically
word_list = sorted(word_list)
# Printing the sorted words
print(' '.join(word for word in word_list))
| true |
eec458d8c6806cacabeef7b0188edd7db65306bc | xfLee/Python-DeepLearning_CS5590 | /Lab_2/Source/Task_2.py | 433 | 4.28125 | 4 | """
Python program to generate a dictionary that contains (k, k*k).
And printing the dictionary that is generated including both 1 and k.
"""
# Taking the input
num = int(input("Input a number "))
# Initialising the dictionary
dictionary = dict()
# Computing the k*k using a for loop
for k in range(1,num+1):
dictionary[k] = k*k
# Printing the whole dictionary
print('Dictionary with (k, k*k) is ')
print(dictionary)
| true |
591d265f4773fab8be1362b349278cd8ed41574a | mercy17ch/dictionaries | /dictionaries.py | 2,262 | 4.375 | 4 | '''program to show dictionaries'''
#A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values
#
#creating dictionary#
thisdict={"name":"mercy",
"sex":"female",
"age":23}
print(thisdict)
#dictionary methods#
#clear() Removes all the elements from the dictionary#
person = {"name":"mercy",
"sex":"female",
"age":23}
person.clear()
print(person)
#copy() Returns a copy of the dictionary#
person = {"name":"mercy",
"sex":"female",
"age":23}
x=person.copy()
print(x)
#fromkeys() Returns a dictionary with the specified keys and value#
x = ('key1', 'key2', 'key3')
y = 4
thisdict = dict.fromkeys(x, y)
print(thisdict)
#get() Returns the value of the specified key#
person = {"name":"mercy",
"sex":"female",
"age":23}
x=person.get("age")
print(x)
#items() Returns a list containing a tuple for each key value pair#
person = {"name":"mercy",
"sex":"female",
"age":23}
x=person.items()
print(x)
#keys() Returns a list containing the dictionary's keys#
person = {"name":"mercy",
"sex":"female",
"age":23}
x=person.keys()
print(x)
#pop() Removes the element with the specified key#
person = {"name":"mercy",
"sex":"female",
"age":23}
person.pop("age")
print(person)
#popitem() Removes the last inserted key-value pair#
person = {"name":"mercy",
"sex":"female",
"age":23}
person.popitem()
print(person)
#setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value#
person = {"name":"mercy",
"sex":"female",
"age":23}
x=person.setdefault("age","18")
print(x)
#update() Updates the dictionary with the specified key-value pairs#
person = {"name":"mercy",
"sex":"female",
"age":23}
person.update({"skin color":"brown"})
print(person)
#values() Returns a list of all the values in the dictionary#
person = {"name":"mercy",
"sex":"female",
"age":23}
x=person.values()
print(x)
| true |
d4e2cb6d1dac6e74e0097146360ac77b5e7132ea | sajjad065/assignment2 | /Function/function5.py | 270 | 4.1875 | 4 | def fac(num):
fact=1;
if(num<0):
print(int("Please enter non-negative number"))
else:
for i in range(1,(num+1)):
fact=fact*i
print("The factorial is: ")
print(fact)
number=int(input("Enter number "))
fac(number)
| true |
b1282fc3cf4bfe3895451cbbbd18fa6517f92dce | sajjad065/assignment2 | /Function/function17.py | 295 | 4.28125 | 4 | str1=input("Enter any string:")
char=input("enter character to check:")
check_char=lambda x: True if x.startswith(char) else False
if(check_char(str1)):
print(str1 +" :starts with character :" +char)
else:
print(str1 +": does not starts with character: " +char)
| true |
d6c476378fac0c7a2ce31678cb34da2f1977ee57 | sajjad065/assignment2 | /Datatype/qsn28.py | 637 | 4.21875 | 4 | total=int(input("How many elements do you want to input in dictionary "))
dic={}
for i in range(total):
key1=input("Enter key:")
val1=input("Enter value:")
dic.update({key1:val1})
print("The dictionary list is :")
print(dic)
num=int(input("please input 1 if you want to add key to the given dictionary "))
if(num==1):
total=int(input("How many elements do you want to input in the given dictionary "))
for i in range(total):
key2=input("Enter key:")
val2=input("Enter value:")
dic.update({key2:val2})
print("The final dictionary list is :")
print(dic)
| true |
8e22e05cf4401dd89fa578671472c856cd9e824c | danielvillanoh/datatypes_operations | /primary.py | 2,323 | 4.5625 | 5 | #author: Daniel Villano-Herrera
# date: 7/1/2021
# --------------- Section 1 --------------- #
# ---------- Integers and Floats ---------- #
# you may use floats or integers for these operations, it is at your discretion
# addition
# instructions
# 1 - create a print statement that prints the sum of two numbers
# 2 - create a print statement that prints the sum of three numbers
# 3 - create a print statement the prints the sum of two negative numbers
print(3 + 5)
print(4 + 12 + 42)
print(-53 + -42)
# subtraction
# instructions
# 1 - create a print statement that prints the difference of two numbers
# 2 - create a print statement that prints the difference of three numbers
# 3 - create a print statement the prints the difference of two negative numbers
print(95-2)
print(2 - 53 - 632)
print(-32 - -34)
# multiplication and true division
# instructions
# 1 - create a print statement the prints the product of two numbers
# 2 - create a print statement that prints the dividend of two numbers
# 3 - create a print statement that evaluates an operation using both multiplication and division
print(21 * 9)
print(23/4)
print(21*3/5)
# floor division
# instructions
# 1 - using floor division, print the dividend of two numbers.
print(6//3)
# exponentiation
# instructions
# 1 - using exponentiation, print the power of two numbers
print(32**7)
# modulus
# instructions
# 1 - using modulus, print the remainder of two numbers
print(23 % 3)
# --------------- Section 2 --------------- #
# ---------- String Concatenation --------- #
# concatenation
# instructions
# 1 - print the concatenation of your first and last name
# 2 - print the concatenation of five animals you like
# 3 - print the concatenation of each word in a phrase
print('Daniel' + ' Villano-Herrera')
print('Cat' + ' Rabbit' + ' Bird' + ' Bear' + ' Seal')
print('I\'m' + ' very' + ' short.')
# duplication
# instructions
# 1 - print the duplpication of your first 5 times
# 2 - print the duplication of a song you like 10 times
print('Daniel' * 5)
print('In da Club' * 10)
# concatenation and duplpication
# instructions
# 1 - print the concatenation of two strings duplicated 3 times each
print('Wow' * 3 + 'lol' * 3)
| true |
12d70ddace6d64ace1873bd5e1521efe579daf6f | pedronobrega/ine5609-estrutura-de-dados | /doubly-linked-list/__main__.py | 967 | 4.21875 | 4 | from List import List
from Item import Item
if __name__ == "__main__":
lista: List = List(3)
# This will throw an exception
# lista.go_ahead_positions(3)
# This will print None
print(lista.access_actual())
# This will print True
print(lista.is_empty())
# This will print False
print(lista.is_full())
item1 = Item(123)
lista.insert_at_the_start(item1)
# This will print 123
print(lista.access_actual().value)
item2 = Item(456)
lista.insert_at_the_end(item2)
lista.go_to_last()
# This will print 456
print(lista.access_actual().value)
item3 = Item(789)
lista.insert_at_the_start(item3)
lista.go_to_first()
# This will print 789
print(lista.access_actual().value)
lista.remove_element(456)
lista.go_to_last()
# This will print 123
print(lista.access_actual().value)
item4 = Item(111)
lista.insert_in_position(2, item4)
lista.go_to_last()
# This will print 111
print(lista.access_actual().value) | true |
54a38474bcfc39ee234c64a8b7808d3df7e31c7d | payal-98/Student_Chatbot-using-RASA | /db.py | 1,205 | 4.15625 | 4 | # importing module
import sqlite3
# connecting to the database
connection = sqlite3.connect("students.db")
# cursor
crsr = connection.cursor()
# SQL command to create a table in the database
sql_command = """CREATE TABLE students (
Roll_No INTEGER PRIMARY KEY,
Sname VARCHAR(20),
Class VARCHAR(30),
Marks INTEGER);"""
# execute the statement
crsr.execute(sql_command)
# SQL command to insert the data in the table
sql_command = """INSERT INTO students VALUES (1, "Payal", "10th", 100);"""
crsr.execute(sql_command)
# another SQL command to insert the data in the table
sql_command = """INSERT INTO students VALUES (2, "Devanshu", "9th", 98);"""
crsr.execute(sql_command)
# another SQL command to insert the data in the table
sql_command = """INSERT INTO students VALUES (3, "Jagriti", "8th", 95);"""
crsr.execute(sql_command)
# another SQL command to insert the data in the table
sql_command = """INSERT INTO students VALUES (4, "Ansh", "5th", 90);"""
crsr.execute(sql_command)
# To save the changes in the files. Never skip this.
# If we skip this, nothing will be saved in the database.
connection.commit()
# close the connection
connection.close()
| true |
bf0e360370d704920509e4a61e7c0b79f983c2de | Maxim1912/python | /list.py | 352 | 4.15625 | 4 | a = 33
b = [12, "ok", "567"]
# print(b[:2])
shop = ["cheese", "chips", "juice", "water", "onion", "apple", "banana", "lemon", "lime", "carrot", "bacon", "paprika"]
new_element = input("ะงัะพ ะตัั ะบัะฟะธัั?\n")
if new_element not in shop:
shop.append(new_element)
print('We need to buy:')
for element in shop:
print(" - ", element)
| true |
86de52a241ae3645d41c693383b7b232c95126c5 | gcnTo/Stats-YouTube | /outliers.py | 1,256 | 4.21875 | 4 | import numpy as np
import pandas as pd
# Find the outlier number
times = int(input("How many numbers do you have in your list: "))
num_list = []
# Asks for the number, adds to the list
for i in range(times):
append = float(input("Please enter the " + str(i+1) + ". number in your list: "))
num_list.append(append)
print("Your list of numbers now include: " + str(num_list))
# Finding 25th and 75th quantiles and the IQR
def ascend(name_of_the_list):
name_of_the_list = name_of_the_list.sort()
return name_of_the_list
ascend(num_list)
q1 = np.quantile(num_list, .25)
q3 = np.quantile(num_list, .75)
iqr = q3 - q1
# Finding the outliers
outlier_range_lower = q1 - 1.5 * iqr
outlier_range_upper = q3 + 1.5 * iqr
outliers = []
for i in range(times):
if num_list[i] < outlier_range_lower or num_list[i] > outlier_range_upper:
outliers.append(num_list[i])
#else:
# print(str(i) + " is not an outlier.")
# Printing out the outliers.
for i in range(len(outliers)):
if len(outliers) > 1:
print(str(outliers[i]) + " are the outliers).")
elif len(outliers) > 0:
print(str(outliers[i]) + " is the outlier.")
else:
print("There were no outliers to be found.")
| true |
03362a677a4b090f092584c63197e01151937781 | ihanda25/SCpythonsecond | /helloworld.py | 1,614 | 4.15625 | 4 | import time
X = raw_input("Enter what kind of time mesurement you are using")
if X == "seconds" :
sec = int(raw_input("Enter num of seconds"))
status = "calculating..."
print(status)
hour = sec // 3600
sec_remaining = sec%3600
minutes = sec_remaining // 60
final_sec_remaining = sec_remaining%60
time.sleep(5)
status = "Done!"
print status
time.sleep(0.5)
print(hour, "hours", minutes, "minutes", final_sec_remaining, "seconds")
else:
if X == "minutes":
if (type(X)) == int:
minutes = int(raw_input("Enter num of minutes"))
status = "calculating..."
print status
sec = minutes *60
hour = sec//3600
sec_remaining = sec %3600
final_minutes = sec_remaining // 60
final_sec_remaining = sec_remaining%60
time.sleep(5)
status = "Done!"
print(status)
time.sleep(0.5)
print(hour, "hours", final_minutes, "minutes", final_sec_remaining, "seconds")
else:
minutes = float(raw_input("Enter num of minutes"))
status = "calculating..."
print status
sec = minutes *60
hour = sec//3600
sec_remaining = sec %3600
final_minutes = sec_remaining // 60
final_sec_remaining = sec_remaining%60
time.sleep(5)
status = "Done!"
print(status)
time.sleep(0.5)
print(hour, "hours", final_minutes, "minutes", final_sec_remaining, "seconds")
| true |
4785fd11ab80f0e29f7f8ef7ec60a8dab5c893de | japneet121/Python-Design-Patterns | /facade.py | 1,006 | 4.21875 | 4 | '''
Facade pattern helps in hiding the complexity of creating multiple objects from user and encapsulating many objects under one object.
This helps in providing unified interface for end user
'''
class OkButton:
def __init__(self):
pass
def click(self):
print("ok clicked")
class CancelButton:
def __init__(self):
pass
def click(self):
print("cancel clicked")
class SaveButton:
def __init__(self):
pass
def click(self):
print("save clicked")
'''
Page class encapsulates the behaviour of all the three buttons and the end user only needs to manage one object
'''
class Page:
def __init__(self):
self.ok=OkButton()
self.save=SaveButton()
self.cancel=CancelButton()
def press_ok(self):
self.ok.click()
def press_save(self):
self.save.click()
def press_cancel(self):
self.cancel.click()
p=Page()
p.press_cancel()
p.press_ok()
p.press_save() | true |
2f9f0e381ba3e08a5a2487967a942d82292ab48c | Kenny-W-C/Tkinter-Examples | /drawing/draw_image.py | 866 | 4.1875 | 4 | #!/usr/bin/env python3
"""
ZetCode Tkinter tutorial
In this script, we draw an image
on the canvas.
Author: Jan Bodnar
Last modified: April 2019
Website: www.zetcode.com
"""
from tkinter import Tk, Canvas, Frame, BOTH, NW
from PIL import Image, ImageTk
class Example(Frame):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.master.title("High Tatras")
self.pack(fill=BOTH, expand=1)
self.img = Image.open("tatras.jpg")
self.tatras = ImageTk.PhotoImage(self.img)
canvas = Canvas(self, width=self.img.size[0]+20,
height=self.img.size[1]+20)
canvas.create_image(10, 10, anchor=NW, image=self.tatras)
canvas.pack(fill=BOTH, expand=1)
def main():
root = Tk()
ex = Example()
root.mainloop()
if __name__ == '__main__':
main()
| true |
5a9c60245722eb710122e1af18778d212db4a84a | johnnymcodes/computing-talent-initiative-interview-problem-solving | /m07_stacks/min_parenthesis_to_make_valid.py | 1,008 | 4.25 | 4 | #
# Given a string S of '(' and ')' parentheses, we add the minimum number of
# parentheses ( '(' or ')', and in any positions ) so that the resulting
# parentheses string is valid.
#
# Formally, a parentheses string is valid if and only if:
# It is the empty string, or
# It can be written as AB (A concatenated with B), where A and B are valid
# strings, or It can be written as (A), where A is a valid string.
#
# Given a parentheses string, return the minimum number of
# parentheses we must add to make the resulting string valid.
#
# Input
# S.length <= 1000
# S only consists of '(' and ')' characters.
#
def minAddToMakeValid(S):
stack = []
for ch in S :
if ch == ")" and "(" in stack:
stack.pop()
else:
stack.append(ch)
return len(stack)
sampleInput = '()'
print(minAddToMakeValid(sampleInput))
# Sample Output
# input#1
# ())
# output#1
# 1
#
# input#2
# (((
# output#2
# 3
#
# input#3
# ()
# output#3
# 0
#
#
# input#4
# ()))((
# output#4
# 4
| true |
e978f07ced6f205af8593c88b55503e436f75a88 | catwang42/Algorithm-for-data-scientist | /basic_algo_sort_search.py | 2,886 | 4.4375 | 4 |
#Algorithms
"""
Search: Binary Search , DFS, BFS
Sort:
"""
#bubble sort -> compare a pair and iterate though ๐(๐2)
#insertion sort
"""
Time Complexity: ๐(๐2),
Space Complexity: ๐(1)
"""
from typing import List, Dict, Tuple, Set
def insertionSort(alist:List[int])->List[int]:
#check from index 1
for i in range(1,len(alist)):
currentValue = alist[i]
while (i-1)>0 and alist[i-1]>currentValue: #if current value less than lagest, move forward
alist[i]=alist[i-1]
i -= 1
alis[i] = currentValue #if larger than current value, don't move
#Merge Sort
"""
Time Complexity: ๐(๐log๐)
Space Complexity: ๐(๐)
"""
def merge(left:List[int],right:List[int])->List[int]:
result = []
left_index, right_index = 0, 0
while left_index < len(left) and right_index < len(right):
if left[left_index]<=right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index +=1
#one of the list will end first and leaving the other list unmerged
#so append the remaining list to the result
result += left[left_index:]
result += right[right_index:]
return result
def merge_sort(alist=List[int])->List[int]:
#need to build a base case first
#recursion can only happend in the else
if len(alist)<=1:
return alist
mid = len(alist)//2
left_list = merge_sort(alist[:mid])
right_list = merge_sort(alist[mid:])
return merge(left_list, right_list)
def create_array(size=10, max=50):
from random import randint
return [randint(0,max) for _ in range(size)]
merge_sort(array)
#quick sort
"""
Time Complexity: average ๐(๐log๐), worest ๐(๐2)
Space Coplexity: ๐(๐log๐)
check the validility , this print out the value
"""
def quickSort(l:int,h:int,alist:List[int])->List[int]:
while(h>l):
pivot = partition(l,h,alist)
quickSort(l,pivot-1,alist)
quickSort(pivot,h,alist)
def partition(l,h,alist):
pivot = alist[l]
i, j = l, h
while(i<j):
if alist[i]<=pivot:
i +=1
if alist[j]>=pivot:
j -=1
i, j = j, i
pivot, j = j , pivot
return j
#Heapsort
#binary search
def binarySearch(alist:List[int], num:int)->bool:
first = 0
last = len(alist)-1
result = False
while last >= first and not result: #be careful when checking the logic
mid = (last+first)//2
if num == alist[mid]:
result = True
else:
if num < alist[mid]:
last = mid-1
else:
first = mid+1
return result
alist = [2,7,19,34,53,72]
print(binarySearch(alist,34))
#depth first search
#breadth first search | true |
fd84dcb1ea5513f1a8447155147761d345f2e0dd | Taranoberoi/PYTHON | /practicepython_ORG_1.py | 580 | 4.28125 | 4 | # 1 Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
import datetime as dt
Name = input("Please Enter the Name :")
# Taking input and converting into Int at the same time
Age = int(input("Please Enter your age in Years please:"))
yr = dt.datetime.today().year
calc = (yr+(100 - Age))
# using "f" to reduce the code
print(f"Name of the Person is {Name} and Age is {Age}")
# print("Age",Age)
print("You would be 100 years old in Year:::", calc) | true |
de4dd804df9777ac13b9e1f4ba3b0b96c701da3a | Taranoberoi/PYTHON | /Practise1.py | 874 | 4.15625 | 4 | #1 Practise 1 in favourites
#1Write a Python program to print the following string in a specific format (see the output). Go to the editor
#Sample String : "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are" Output :
####Str = "Twinkle, twinkle, little star, How I wonder what you are! Up above the world so high, Like a diamond in the sky. Twinkle, twinkle, little star, How I wonder what you are"
####print("Twinkle, twinkle, little star,\n\tHow I wonder what you are!\n\t\t\tUp above the world so high\n\t\t\tLike a diamond in the sky.\nTwinkle, twinkle, little star,\n\tHow I wonder what you are")
#2 Write a Python program to get the Python version you are using
#### import sys
#### print(sys.version)
#### print(sys.version_info)
| true |
81e5bd642345c074b4ac9c55ee4e630a7d6ebd73 | BSchweikart/CTI110 | /M3HW1_Age_Classifier_Schweikb0866.py | 726 | 4.25 | 4 | # CTI - 110
# M3HW1 : Age Classifier
# Schweikart, Brian
# 09/14/2017
def main():
print('Please enter whole number, round up or down')
# This is to have user input age and then classify infant, child,...
# Age listing
Age_a = 1
Age_b = 13
Age_c = 20
# 1 year or less = infant
# 1 year less then 13 = child
# 13 years - 19 = teenager
# 20 + = Adult
# user input for age
age =int(input('Enter age'))
if age <= Age_a:
print('Infant')
elif age > Age_a and age < Age_b:
print('Child')
elif age >= Age_b and age < Age_c:
print('Teenager')
else:
print('Adult')
# program start
main()
| true |
4bd2765c5c80cdb85fa9a2f6c1d9603ac6f26bd6 | Varunaditya/practice_pad | /Python/stringReversal.py | 1,454 | 4.125 | 4 | """
Given a string and a set of delimiters, reverse the words in the string while
maintaining the relative order of the delimiters.
For example, given "hello/world:here", return "here/world:hello"
"""
from sys import argv, exit
alphabets = ['a', 'b', 'c', 'd', 'e',
'f' , 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z']
def delims_handler(ch: str, delims: dict, wc: int) -> dict:
if wc not in delims:
delims[wc] = ch
else:
delims[wc] += ch
return delims
def get_words_delims(inp: str) -> (list, dict):
global alphabets
prev_delim = False
words, word, word_count = list(), str(), 0
delims = dict()
for char in inp:
if char.lower() in alphabets:
prev_delim = False
word += char
else:
words.append(word)
word = str()
if not prev_delim:
word_count += 1
prev_delim = True
delims = delims_handler(char, delims, word_count)
if word:
words.append(word)
return (words, delims)
def rearr(inp: str) -> str:
words, delims = get_words_delims(inp)
output = str()
word_count = 0
for word in words[::-1]:
if word_count in delims:
output += delims[word_count]
output += word
word_count += 1
if word_count in delims:
output += delims[word_count]
return output
def main():
if len(argv) <= 1 :
print('No Input!')
exit(-1)
inp = argv[1]
new_sent = rearr(inp)
print(new_sent)
if __name__ == '__main__':
main()
| true |
91c5976e429e09729f3857b8e5a633073837b368 | Varunaditya/practice_pad | /Python/merge_accounts.py | 1,915 | 4.28125 | 4 | """
Given a list accounts, each element accounts[i] is a list of strings, where the first element accounts[i][0] is a name,
and the rest of the elements are emails representing emails of the account.
Now, we would like to merge these accounts. Two accounts definitely belong to the same person if there is some email
that is common to both accounts. Note that even if two accounts have the same name, they may belong to different people
as people could have the same name. A person can have any number of accounts initially, but all of their accounts
definitely have the same name.
After merging the accounts, return the accounts in the following format: the first element of each account is the name,
and the rest of the elements are emails in sorted order. The accounts themselves can be returned in any order.
"""
def merge_accounts(accounts: list) -> list:
merged_accounts, temp = list(), set()
visited = list()
while accounts:
temp = set()
current_account = accounts.pop(0)
if len(accounts) < 1:
merged_accounts.append(sorted(current_account))
break
for i in range(1, len(accounts)):
[temp.add(i) for i in current_account]
if current_account[0] == accounts[i][0]:
if len(set(current_account[1:]).intersection(set(accounts[i][1:]))):
[temp.add(i) for i in accounts[i][1:]]
visited.append(accounts[i])
visited.append(current_account)
if list(temp) not in merged_accounts and len(temp) > 0:
merged_accounts.append(sorted(list(temp)))
return merged_accounts
def main():
accounts = [["John", "johnsmith@mail.com", "john00@mail.com"],
["John", "johnnybravo@mail.com"],
["John", "johnsmith@mail.com", "john_newyork@mail.com"],
["Mary", "mary@mail.com"]]
ans = merge_accounts(accounts)
print(ans)
if __name__ == "__main__":
main()
| true |
dc363f27cc6e52277b539fbaabd2aedae1691933 | gpastor3/Google-ITAutomation-Python | /Course_2/Week_2/iterating_through_files.py | 971 | 4.5 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 11/28/2020
"""
with open("Course_2/Week_2/spider.txt") as file:
for line in file:
print(line.upper())
# when Python reads the file line by line, the line variable will always have
# a new line character at the end. In other words, the newline character is
# not removed when calling read line. When we ask Python to print the line,
# the print function adds another new line character, creating an empty line.
# We can use a string method, strip to remove all surrounding white space,
# including tabs and new lines.
with open("Course_2/Week_2/spider.txt") as file:
for line in file:
print(line.strip().upper())
# Another way we can work with the contents of the file is to read the file
# lines into a list. Then, we can do something with the lists like sort
# contents.
file = open("Course_2/Week_2/spider.txt")
lines = file.readlines()
file.close()
lines.sort()
print(lines)
| true |
77efe1b0c6dce387b29f9719ec8be6c217373b86 | gpastor3/Google-ITAutomation-Python | /Course_1/Week_4/iterating_over_the_contents_of_a_dictionary.py | 1,835 | 4.6875 | 5 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/20/2020
"""
# You can use for loops to iterate through the contents of a dictionary.
file_counts = {"jpg": 10, "txt": 14, "csc": 2, "py": 23}
for extension in file_counts:
print(extension)
# If you want to access the associated values, you can either use the keys as
# indexes of the dictionary or you can use the items method which returns a
# tuple for each element in the dictionary. The tuple's first element is the
# key. Its second element is the value.
# We can use the .items method to get key, value pairs
for ext, amount in file_counts.items():
print("There are {} files with the .{} extension". format(amount, ext))
# Sometimes you might just be interested in the keys of a dictionary. Other
# times you might just want the values. You can access both with their
# corresponding dictionary methods
# Use the keys() method to just get the keys
print(file_counts.keys())
# Use the values() method to just get the values
print(file_counts.values())
for value in file_counts.values():
print(value)
# Complete the code to iterate through the keys and values of the cool_beasts
# dictionary. Remember that the items method returns a tuple of key, value
# for each element in the dictionary.
cool_beasts = {"octopuses": "tentacles", "dolphins": "fins", "rhinos": "horns"}
for beast, apendage in cool_beasts.items():
print("{} have {}".format(beast, apendage))
# Dictionaries are a great tool for counting elements and analyzing frequency.
def count_letters(text):
result = {}
for letter in text:
if letter not in result:
result[letter] = 0
result[letter] += 1
return result
print(count_letters("aaaaa"))
print(count_letters("tenant"))
print(count_letters("a long string with a lot of letters"))
| true |
2d593998eaf8c47e2b476f7d5c50143ef75f409a | gpastor3/Google-ITAutomation-Python | /Course_2/Week_5/charfreq.py | 873 | 4.1875 | 4 | #!/usr/bing/env python3
"""
This script is used for course notes.
Author: Erick Marin
Date: 12/26/2020
"""
# To use a try-except block, we need to be aware of the errors that functions
# that we're calling might raise. This information is usually part of the
# documentation of the functions. Once we know this we can put the operations
# that might raise errors as part of the try block, and the actions to take
# when errors are raised as part of a corresponding except block.
def character_frequency(filename):
"""Count the frequency of a character in a given file."""
# First try to open the file
try:
f = open(filename)
except OSError:
return None
# now process the file
characters = {}
for line in f:
for char in line:
characters[char] = characters.get(char, 0) + 1
f.close()
return characters
| true |
7c1386e726f4867617ac9682657532da2425df07 | gpastor3/Google-ITAutomation-Python | /Course_1/Week_2/returning_values.py | 1,324 | 4.25 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/08/2020
"""
def area_triangle(base, height):
""" Calculate the area of triange by multipling `base` by `height` """
return base * height / 2
def get_seconds(hours, minutes, seconds):
""" Calculate the `hours` and `minutes` into seconds, then add with
the `seconds` paramater. """
return 3600*hours + 60*minutes + seconds
def convert_seconds(seconds):
""" Convert the duration of time in 'seconds' to the equivalent
number of hours, minutes, and seconds. """
hours = seconds // 3600
minutes = (seconds - hours * 3600) // 60
remaining_seconds = seconds - hours * 3600 - minutes * 60
return hours, minutes, remaining_seconds
def greeting(name):
""" Print out a greeting with provided `name` parameter. """
print("Welcome, " + name)
AREA_A = area_triangle(5, 4)
AREA_B = area_triangle(7, 3)
SUM = AREA_A + AREA_B
print("The sum of both areas is: " + str(SUM))
AMOUNT_A = get_seconds(2, 30, 0)
AMOUNT_B = get_seconds(0, 45, 15)
result = AMOUNT_A + AMOUNT_B
print(result)
HOURS, MINUTES, SECONDS = convert_seconds(5000)
print(HOURS, MINUTES, SECONDS)
# Assigning result of a function call, where the function has no return
# will result in 'None'
RESULT = greeting("Christine")
print(RESULT)
| true |
aa96e9acb44032b35e1b53784b117d989af43758 | gpastor3/Google-ITAutomation-Python | /Course_1/Week_4/iterating_over_lists_and_tuples.py | 2,405 | 4.59375 | 5 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/20/2020
"""
animals = ["Lion", "Zebra", "Dolphin", "Monkey"]
chars = 0
for animal in animals:
chars += len(animal)
print("Total characters: {}, Average length: {}".format(chars, chars/len(animals)))
# The 'enumerate' function returns a tuple for each element in the list. The
# first value in the tuple is the index of the element in the sequence. The
# second value in the tuple is the element in the sequence.
winners = ["Ashley", "Dylan", "Reese"]
for index, person in enumerate(winners):
print("{} - {}".format(index + 1, person))
# Try out the enumerate function for yourself in this quick exercise. Complete
# the skip_elements function to return every other element from the list, this
# time using the enumerate function to check if an element is on an even
# position or an odd position.
def skip_elements(elements):
new_elements = []
for element_index, element in enumerate(elements):
# Becuase you are enumerating the list, no need for index += 1
# to cycle the loop to the next index for evaulation.
if element_index % 2 == 0:
new_elements.append(element)
return new_elements
# Should be ['a', 'c', 'e', 'g']
print(skip_elements(["a", "b", "c", "d", "e", "f", "g"]))
# Should be ['Orange', 'Strawberry', 'Peach']
print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach']))
def full_emails(people):
result = []
for email, name in people:
result.append("{} <{}>".format(name, email))
return result
print(full_emails([("alex@example.com", "Alex Diego"),
("shay@example.com", "Shay Brandt")]))
# Because we use the range function so much with for loops, you might be
# tempted to use it for iterating over indexes of a list and then to access
# the elements through indexing. You could be particularly inclined to do this
# if you're used to other programming languages before. Because in some
# languages, the only way to access an element of a list is by using indexes.
# Real talk, this works but looks ugly. It's more idiomatic in Python to
# terate through the elements of the list directly or using enumerate when you
# need the indexes like we've done so far. There are some specific cases that
# do require us to iterate over the indexes, for example, when we're trying to
# modify the elements of the list we're iterating.
| true |
b0570c87b7a5d7389973b315aca7d79de585a452 | gpastor3/Google-ITAutomation-Python | /Course_1/Week_2/defining_functions.py | 919 | 4.125 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/08/2020
"""
def greeting(name, department):
""" Print out a greeting with provided `name` and department
parameters. """
print("Welcome, " + name)
print("Your are part of " + department)
# Flesh out the body of the print_seconds function so that it prints the total
# amount of seconds given the hours, minutes, and seconds function parameters.
# Remember that there are 3600 seconds in an hour and 60 seconds in a minute.
def print_seconds(hours, minutes, seconds):
""" Prints the total amount of seconds given the hours, minutes,
and seconds function parameters. Note: There are 3600
seconds in an hour and 60 seconds in a minute. """
print((hours * 3600) + (minutes * 60) + seconds)
greeting("Blake", "IT Department")
print("\n")
greeting("Ellis", "Software Engineering")
print("\n")
print_seconds(1, 2, 3)
| true |
123187441133b573b5058569e0a972964d11221b | gpastor3/Google-ITAutomation-Python | /Course_1/Week_4/the_parts_of_a_string.py | 1,668 | 4.34375 | 4 | """
This script is used for course notes.
Author: Erick Marin
Date: 10/11/2020
"""
# String indexing
name = "Jaylen"
print(name[1])
# Python starts counting indices from 0 and not 1
print(name[0])
# The last index of a string will always be the one less than the length of
# the string.
print(name[5])
# If we try to access index past the characters availble, we get an index
# error telling us that it's out of range.
# print(name[6])
# IndexError: string index out of range
# Using negative indexes lets us access the positions in the string starting
# from the last.
""" text = "Random string with a lot of characters"
print(text[-1])
print(text[-2]) """
# Want to give it a go yourself? Be my guest! Modify the first_and_last
# function so that it returns True if the first letter of the string is the
# same as the last letter of the string, False if theyโre different. Remember
# that you can access characters using message[0] or message[-1]. Be careful
# how you handle the empty string, which should return True since nothing is
# equal to nothing.
def first_and_last(message):
emptystr = ""
if message == emptystr:
return True
elif message[0] == message[-1]:
return True
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
# Slice - The portion of a string that can contain more than one character;
# also sometimes called a substring.
color = "Orange"
# In this case, we start with indexed one, the second letter of the string,
# and go up to index three, the fourth letter of the string.
print(color[1:4])
fruit = "Pineapple"
print(fruit[:4])
print(fruit[4:])
| true |
2eb52a42c37125937cbffd68468398956aa7d575 | foofaev/python-project-lvl1 | /brain_games/games/brain_progression.py | 1,454 | 4.25 | 4 | """
Mini-game "arithmetic progression".
Player should find missing element of provided progression.
"""
from random import randint
OBJECTIVE = 'What number is missing in the progression?'
PROGESSION_SIZE = 10
MIN_STEP = 1
MAX_STEP = 10
def generate_question(first_element: int, step: int, index_of_missing: int):
"""Generate string representing arithmetic progression with missing element.
Args:
first_element (int): initial element of the progression
step (int): Step of the progression
index_of_missing (int): Index of missing element
Returns:
str: Description of return value
"""
progression = ''
index = 0
while index < PROGESSION_SIZE:
separator = '' if index == 0 else ' '
next_element = (
'..'
if index_of_missing == index
else first_element + index * step
)
progression += '{0}{1}'.format(separator, next_element)
index += 1
return progression
def generate_round():
"""Generate question and correct answer for game round.
Returns:
tuple of question and answer
"""
first_element = randint(0, 100)
index_of_missing = randint(0, PROGESSION_SIZE - 1)
step = randint(MIN_STEP, MAX_STEP)
missing_element = first_element + step * index_of_missing
question = generate_question(first_element, step, index_of_missing)
return (question, str(missing_element))
| true |
5f1d89b45c61f68d2b23aa01bfb4c83d6e88fd1b | Sungmin-Joo/Python | /Matrix_multiplication_algorithm/Matrix_multiplication_algorithm.py | 1,284 | 4.1875 | 4 | # -*- coding: utf-8 -*-
import numpy as np
if __name__ == '__main__':
print("Func_called - main")
A = np.array([[5,7,-3,4],[2,-5,3,6]])
B = np.array([[3,0,8],[-5,1,-1],[7,4,4],[2,4,3]])
len_row_A = A.shape[0]
len_col_A = A.shape[1]
len_col_B = B.shape[1]
result = np.zeros((len_row_A,len_col_B))
print("---------- use numpy function ----------")
print(np.dot(A,B))
print("----------------------------------------")
'''
Python can easily implement difficult algorithms.
But I wanted to practice implementing algorithms with python.
'''
for row in range(0,len_row_A):
for col in range(0,len_col_B):
for index in range(0,len_col_A):
result[row,col] = result[row,col] + A[row,index]*B[index,col]
print("----------- use my algorithm -----------")
print(result)
print("----------------------------------------")
else:
print('Func_called - imported')
'''
----------result----------
Func_called - main
---------- use numpy function ----------
[[-33 11 33]
[ 64 31 51]]
----------------------------------------
----------- use my algorithm -----------
[[-33. 11. 33.]
[ 64. 31. 51.]]
----------------------------------------
--------------------------
''' | true |
73d9af8a966990d3c06060b56516c7e22e637fda | andyly25/Python-Practice | /data visualization/e01_simplePlot.py | 761 | 4.34375 | 4 | '''
1. import pyplot module and using alias plt to make life easier.
2. create a lit to hold some numerical data.
3. pass into plot() function to try plot nums in meaningful way.
4. after launching, shows you simple graph that you can navigate through.
'''
# 1
import matplotlib.pyplot as plt
# input values will help set what the x-axis values would be
input_values = [1, 2, 3, 4, 5]
# 2
squares = [1, 4, 9, 16, 25]
# 3
# line width controls thickness of line plot() generates.
plt.plot(input_values, squares, linewidth=5)
# set chart title and label axes
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# set size of tick labels
plt.tick_params(axis='both', labelsize=14)
plt.show()
| true |
69681798f10be785c5e6d247222832f32e7fcf91 | andyly25/Python-Practice | /AlgorithmsAndChallenges/a001_isEven.py | 1,008 | 4.34375 | 4 | '''
I've noticed the question of determining if a number is an even number
often, and it seems easy as you can just use modulo 2 and see if 0 or some
other methods with multiplication or division.
But here's the catch, I've seen a problem that states:
You cannot use multiplication, modulo, or division operators in doing so.
So what does that leave? Bitwise operators:
here's a small tutorial on them:
AND: 1 & 1 = 1
OR: 0 | 1 = 1, 1 | 0 = 1, 1 | 1 = 1
XOR: 0^1 = 1 , 1^0 = 1
NOT: !0 = 1
Here's an example with AND
010 : 2
011 : 3
----
010 : 2
now using that 2 & with 010 : 1
010 : 2
001 : 1
----
000 : 0
thus we can say that even numbers &1 gives 0
'''
def is_even(k):
if((k&1)==0):
return True;
return False;
# x = input("Input an int")
num1 = 3
num2 = 50
num3 = 111111111111
print("is num1 even? ", is_even(num1))
print("is num2 even? ", is_even(num2))
print("is num3 even?", is_even(num3)) | true |
1a3689681b252e87b0c323aa73b32166bb3e8469 | oktaran/LPTHW | /exercises.py | 1,367 | 4.21875 | 4 |
"""
Some func problems
~~~~~~~~~~~~~~~~~~
Provide your solutions and run this module.
"""
import math
def add(a, b):
"""Returns sum of two numbers."""
return a + b
def cube(n):
"""Returns cube (n^3) of the given number."""
# return n * n * n
# return n**3
return math.pow(n, 3)
def is_odd(n):
"""Return True if given number is odd, False otherwise."""
return n % 2 == 1
def print_nums(num):
"""Prints all natural numbers less than given `num`."""
for i in range(num):
print(i)
def print_even(num):
"""Prints all even nums less than a given `num`."""
for i in range(num):
if not is_odd(i):
print(i)
def cube_lst(lst):
"""Returns a list of cubes based on input list."""
# lst_1 = []
#
# for i in lst:
# lst_1.append(cube(i))
#
# return lst_1
return [cube(i) for i in lst]
# === Don't modify below ===
def test():
assert add(3, 2) == 5
assert add(8, -1) == 7
assert cube(3) == 27
assert cube(-1) == -1
assert is_odd(3)
assert is_odd(5)
assert is_odd(11)
assert not is_odd(2)
assert cube_lst([1, 2, 5]) == [1, 8, 125]
def main():
try:
test()
except AssertionError:
print("=== Tests FAILED ===")
else:
print("=== Success! ===")
if __name__ == '__main__':
main()
| true |
3a097f2425a884b0869818f8bf2646854f2ef6af | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Basic Programs/Factorial.py | 556 | 4.25 | 4 | """Find factorial of given number"""
def fact(num):
if num < 0:
return 'factorial of negative number not possible'
elif num == 0:
return 1
else:
factorial= 1
for i in range(1, num+1):
factorial *= i
return factorial
def recurse_fact(num):
if num < 0:
return 'Factorial of negative number not possible'
elif num == 0 or num == 1:
return 1
else:
return num*recurse_fact(num-1)
num= int(input('Enter number:'))
print(fact(num))
print(recurse_fact(num))
| true |
7aa66e034df46248f0a8cc6d12617137533fc4ab | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/Strings/03_ReplaceChar.py | 377 | 4.1875 | 4 | """program to get a string from a given string where all occurrences of its first char have been
changed to '$', except the first char itself"""
string = 'restart'
ch = 'r'
i = string.index(ch) # using str.replace() method returns new string with all replacements
print(string[:i+1]+string[i+1:].replace(ch, '$'))
# count given replace that many characters only
| true |
546f755653d647de1c8afec21f7b630aab5ef626 | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/Dictionary/13_CountValuesAsList.py | 343 | 4.125 | 4 | """Program to count number of items in a dictionary value that is a list"""
dict1 = {'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5], 'c': 1, 'd': 'z', 'e': (1,)}
# if value is list added True i.e. 1 else False i.e. 0
count = sum(isinstance(value, list) for value in dict1.values()) # sum fn & generator expression
print(f'{count} values are list')
| true |
25778e07eadbe6059b64b6d79cc384bc7150525c | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/Dictionary/01_SortByValue.py | 418 | 4.4375 | 4 | """Sort (ascending and descending) a dictionary by value"""
d = {'a': 26, 'b': 25, 'y': 2, 'z': 1}
# to access and map key value pairs dict.item gives list of tuples of key, value pairs
print(f'Ascending order by value {dict(sorted(d.items(),key=lambda x: x[1]))}') # using second element of tuple
print(f'Descending order by value {dict(sorted(d.items(),key=lambda x: x[1], reverse= True))}') # reverse parameter
| true |
dcca3f992e91118ce37e7bb14a2942cef6ea431c | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Sorting Algorithms/InsertionSort.py | 488 | 4.15625 | 4 | """Sort numbers in list using Insertion sort algorithm"""
numbers = [int(i) for i in input('Enter list of numbers:').split()]
print(numbers)
for i in range(1, len(numbers)): # first element already sorted
j = i # insert element at j index in left part of array at it's appropriate position
while j >= 1:
if numbers[j] < numbers[j-1]:
numbers[j], numbers[j-1] = numbers[j-1], numbers[j]
j -= 1
print(numbers)
| true |
33bb259270a1bc8fd006b9f441a6b3267cff63b5 | vaibhavyesalwad/Basic-Python-and-Data-Structure | /Python Data Structure/List/06_RemoveDuplication.py | 205 | 4.15625 | 4 | """Program to remove duplicates from a list"""
numbers = [10, 15, 15, 20, 50, 55, 65, 20, 30, 50]
print(f'Unique elements: {set(numbers)}') # set accepts only unique elements so typecasting to set
| true |
74207f09ecbe9354d93ace2c3d0edd34613997fb | thesayraj/DSA-Udacity-Part-II | /Project-Show Me Data Structures/problem_2.py | 863 | 4.21875 | 4 | import os
def find_files(suffix = "", path = "."):
"""
Find all files beneath path with file name suffix.
Note that a path may contain further subdirectories
and those subdirectories may also contain further subdirectories.
There are no limit to the depth of the subdirectories can be.
Args:
suffix(str): suffix if the file name to be found
path(str): path of the file system
Returns:
a list of paths
"""
files = []
if os.path.isfile(path):
if path.endswith(suffix):
return [path]
else:
new_paths = os.listdir(path)
for item in new_paths:
files += find_files(suffix, "{}/{}".format(path, item))
return files
ff = find_files(suffix=".c",path="C:/Users/Sumit/Downloads/testdir")
for f in ff:
print(f)
| true |
258decfc38f5f05740389356d78bcdfaf780bfc8 | lujamaharjan/pythonAssignment2 | /question5.py | 791 | 4.75 | 5 | """
5. Create a tuple with your first name, last name, and age. Create a list,
people, and append your tuple to it. Make more tuples with the
corresponding information from your friends and append them to the
list. Sort the list. When you learn about sort method, you can use the
key parameter to sort by any field in the tuple, first name, last name,
or age.
"""
my_tuple = ('sachin', 'maharjan', '23')
people = list()
people.append(my_tuple)
people.append(('Kathy', 'Williams', '24'))
people.append(('Raman', 'Dangol', '22'))
print(people)
#sorts according to first member of tuple
people.sort()
print(people)
#sorts according to last name
people.sort(key = lambda people: people[1])
print(people)
#sorts according to age
people.sort(key = lambda people: people[2])
print(people)
| true |
6065ac1867f7dafea2872a50162e1b8f4f2a2527 | lujamaharjan/pythonAssignment2 | /question15.py | 700 | 4.3125 | 4 | """
Imagine you are designing a bank application.
what would a customer look like? What attributes
would she have? What methods would she have?
"""
class Customer():
def __init__(self, account_no, name, address, email, balance):
self.account_no = account_no
self.name = name
self.address = address
self.email = email
self.balance = balance
def get_balance(self):
return self.balance
def add_balance(self, amount):
self.balance = self.balance + amount
def withdraw(self, amount):
if amount > self.balance:
print("Not enough balance")
else:
self.balance = self.balance - amount
| true |
14569d9e12b63f29b2002c014fe8fdb79d990bcf | babbgoud/maven-project | /guess-numapp/guessnum.py | 765 | 4.15625 | 4 | #! /usr/bin/python3
import random
print('Hello, whats your name ?')
myname = input()
print('Hello, ' + myname + ', I am thinking of a number between 1 and 20.')
secretNumber = random.randint(1,20)
for guesses in range(1,7):
print('Take a guess.?')
guessNumber = int(input())
if int(guessNumber) > secretNumber:
print('sorry, your guess is too high.')
elif int(guessNumber) < secretNumber:
print(' sorry, your guess is too low.')
else:
break # this is condition for the correct guess(number)!
if guessNumber == secretNumber:
print('Good Job, ' + myname + '! you guessed the number correct in ' + str(guesses) + ' guesses!')
else:
print('Nope. The nuber I was thinking of was ' + str(secretNumber))
| true |
0dcc567b62cb6e81893fd99471a32737388d04b2 | ramyanaga/MIT6.00.1x | /Pset2.py | 2,332 | 4.3125 | 4 | """
required math:
monthly interest rate = annual interest rate/12
minimum monthly payment = min monthly payment rate X previous balance
monthly unpaid balance = previous balance - min monthly payment
updated balance each month = monthly unpaid balance + (monthly interest rate X monthly unpaid balance)
NEED TO PRINT:
Month:
Minimum monthly payment:
Remaining balance:
"""
#don't specify variables balance, annualInterestRate, monthlyPaymentRate
#balance = 4213
#annualInterestRate = .2
#monthlyPaymentRate = .04
#total_paid = 0
def question1():
for month in range(1,13):
monthly_interest_rate = annualInterestRate/12
min_monthly_payment = monthlyPaymentRate*balance
monthly_unpaid_balance = balance - min_monthly_payment
balance = monthly_unpaid_balance + (monthly_interest_rate*monthly_unpaid_balance)
total_paid += min_monthly_payment
print "Month:" + str(month)
print "Minimum monthly payment:" + str(round(min_monthly_payment,2))
print "Remaining balance:" + str(round(balance,2))
if month == 12:
print "Total paid:" + str(round(total_paid,2))
print "Remaining balance:" + str(round(balance,2))
#balance = 4773
#annualInterestRate = .2
#updatedBalance = balance
def question2():
lowestPayment = 10
monthlyInterestRate = annualInterestRate/12
while updatedBalance > 0:
for month in range(1,13):
monthlyUnpaidBalance = updatedBalance - lowestPayment
updatedBalance = monthlyUnpaidBalance + (monthlyInterestRate*monthlyUnpaidBalance)
if updatedBalance < 0:
print "Lowest Payment:" + str(lowestPayment)
else:
updatedBalance = balance
lowestPayment+=10
def question3():
updatedBalance = balance
monthlyInterestRate = annualInterestRate/12
paymentLb = balance/12
paymentUb = (balance*(1+monthlyInterestRate)**12)/12
mid = (paymentLb + paymentUb)/2
while (updatedBalance > .01) or (updatedBalance < -.01):
for month in range(1,13):
monthlyUnpaidBalance = updatedBalance - mid
updatedBalance = monthlyUnpaidBalance + (monthlyInterestRate*monthlyUnpaidBalance)
if updatedBalance > .01:
paymentLb = mid
mid = (paymentUb+paymentLb)/2
updatedBalance = balance
elif updatedBalance < -.01:
paymentUb = mid
mid = (paymentUb+paymentLb)/2
updatedBalance = balance
else:
mid = round(mid,2)
print "lowestPayment:" + str(mid)
| true |
3eb482c7861a7a2ea0e293cacce0d75d2f41de77 | AlexDT/Playgarden | /Project_Euler/Python/001_sum.py | 542 | 4.1875 | 4 | # coding: utf-8
#
# ONLY READ THIS IF YOU HAVE ALREADY SOLVED THIS PROBLEM!
# File created for http://projecteuler.net/
#
# Created by: Alex Dias Teixeira
# Name: 001_sum.py
# Date: 06 Sept 2013
#
# Problem: [1] - Multiples of 3 and 5
# If we list all the natural numbers below 10 that are multiples of
# 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
#
total = 0
for i in range(1000):
if (i % 3 == 0) or (i % 5 == 0):
total = total + i
print total
| true |
34534abc70987c7c05910c3436868db6b0a97148 | sasathornt/Python-3-Programming-Specialization | /Python Basics/Week 4/assess_week5_01.py | 331 | 4.34375 | 4 | ##Currently there is a string called str1. Write code to create a list called chars which should contain the characters from str1. Each character in str1 should be its own element in the list chars
str1 = "I love python"
# HINT: what's the accumulator? That should go here.
chars = []
for letter in str1:
chars.append(letter) | true |
1d71ab1f3585ef7d344998afffe54b01ab443c59 | KazuoKitahara/challenge | /cha45.py | 275 | 4.125 | 4 |
def f(x):
"""
Returns float of input string.
:param x: int,float or String number
try float but if ValueError, print "Invalid input"
"""
try:
return float(x)
except ValueError:
print("Invalid input")
print(f(10))
print(f("ten"))
| true |
1aba84f4c9ccb999895378980f14101ba10d3adb | Fang-Molly/CS-note | /python3 for everybody/exercises_solutions/ex_09_05.py | 897 | 4.375 | 4 | '''
Python For Everybody: Exploring Data in Python 3 (by Charles R. Severance)
Exercise 9.5: This program records the domain name (instead of the address) where the message was sent from instead of who the mail came from (i.e., the whole email address). At the end of the program, print out the contents of your dictionary.
python schoolcount.py Enter a file name: mbox-short.txt {'media.berkeley.edu': 4, 'uct.ac.za': 6, 'umich.edu': 7, 'gmail.com': 1, 'caret.cam.ac.uk': 1, 'iupui.edu': 8}
'''
domain_counts = dict()
fname = input('Enter a file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
for line in fhand:
words = line.split()
if len(words) < 3 or words[0] != 'From':
continue
word = words[1]
email = word.split('@')
domain = email[1]
domain_counts[domain] = domain_counts.get(domain,0) + 1
print(domain_counts)
| true |
537ab14e1654a023e4de4c0cd4c3dc37ab2394e1 | paulcockram7/paulcockram7.github.io | /10python/l05/Exercise 2.py | 261 | 4.125 | 4 | # Exercise 2
# creating a simple loop
# firtly enter the upper limit of the loop
stepping_variable = int(input("Enter the amount of times the loop should run "))
#set the start value
i = 0
for i in range(stepping_variable):
print("line to print",str(i))
| true |
92a8edcc1b4419cda07813c301607d0e036de96f | Biytes/learning-basic-python | /loops.py | 749 | 4.15625 | 4 | '''
Description:
Author: Biytes
Date: 2021-04-12 17:55:57
LastEditors: Biytes
LastEditTime: 2021-04-12 18:50:23
FilePath: \python\basic\loops.py
'''
# A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
people = ['John', 'Paul', 'Sara', 'Susan']
# Simple for loop
# for person in people:
# print(f'Current Person: {person}')
# Break
# for person in people:
# if person == 'Sara':
# break
# print(f'Current Person: {person}')
# range
# for i in range(1, 11):
# print(f'Number: {i}')
# while loops execute a set of statements as long as a condition is true
count = 0
while count < 10:
print(f'Count: {count}')
count += 1
print(f'Count: {count}')
| true |
14e5b26ac617c4e2f871fd162b8c07d64132ce9f | koltpython/python-slides | /Lecture7/lecture-examples/lecture7-1.py | 828 | 4.34375 | 4 |
# Free Association Game
clues = ('rain', 'cake', 'glass', 'flower', 'napkin')
# Let's play a game. Give the user these words one by one and ask them to give you the first word that comes to their mind.
# Store these words together in a dictionary, where the keys are the clues and the values are the words that the user tells.
# We want another user to be able to learn the previous user's associations. For this reason, ask the user which word's association
# they want to learn and print the related word.
pairs = dict()
for word in clues:
answer = input(f"What word comes to your mind when you see {word} ")
pairs[word] = answer
print(pairs)
key = input("What do you want to learn? ")
while key != 'exit':
print(pairs[key])
key = input("What do you want to learn? ")
open("texts/my_text.txt", mode='w') | true |
8013c5a1d5760cd65eca1c8c3c009003dc53b8a3 | JulianTrummer/le-ar-n | /code/01_python_basics/examples/02_lists_tuples_dictionaries/ex4_tuples.py | 333 | 4.34375 | 4 | """Tuple datatypes"""
# A tuple is similar to a list, however the sequence is immutable.
# This means, they can not be changed or added to.
my_tuple_1 = (1, 2, 3)
print(my_tuple_1, type(my_tuple_1))
print(len(my_tuple_1))
my_tuple_2 = tuple(("hello", "goodbye"))
print(my_tuple_2[0])
print(my_tuple_2[-1])
print(my_tuple_2[1:3]) | true |
483d8c2a95519c1e81242ec1420e7b80640595bc | JulianTrummer/le-ar-n | /code/01_python_basics/examples/05_classes/ex1_class_intro.py | 606 | 4.25 | 4 | # Classes introduction
# Class definition
class Vehicle():
# Initiation function (always executed when the class object is being initiated)
def __init__(self, colour, nb_wheels, name):
self.colour = colour
self.nb_wheels = nb_wheels
self.name = name
# Creating objects from class
vehicle_1 = Vehicle("blue", 2, "bike")
vehicle_2 = Vehicle("red", 4, "car")
# Print the results
print("This is a", vehicle_1.colour, vehicle_1.name, "with", vehicle_1.nb_wheels, "wheels.")
print("This is a {} {} with {} wheels.".format(vehicle_2.colour, vehicle_2.name, vehicle_2.nb_wheels)) | true |
1d7659b09b39394fbc031fe4799a21530d5cf8f1 | jarrettdunne/coding-problems | /daily/problem1.py | 1,077 | 4.21875 | 4 | import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')
def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
def test_split(self):
'''
input:
[1, 2, 3]
output:
3
'''
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
# Given a list of numbers and a number k, return whether any two numbers from the list add up to k.
# For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.
def two_sum(lst, k):
seen = set()
for num in lst:
if k - num in seen:
return True
seen.add(num)
return False
if __name__ == '__main__':
# unittest.main()
test = unittest.TestCase()
lst = [10, 15, 3, 7]
k = 17
test.assertEqual(two_sum(lst, k), True) | true |
eb7bc39f59c1d5ed19f206a85ccec13c4a6a7e00 | winniewjeng/StockDatabase | /Example.py | 2,330 | 4.40625 | 4 | #! /usr/bin/env python3
"""
File: Jeng_Winnie_Lab1.py
Author: Winnie Wei Jeng
Assignment: Lab 2
Professor: Phil Tracton
Date: 10/07/2018
The base and derived classes in this file lay out
the structure of a simple stock-purchasing database
"""
from ExampleException import *
# Base Class
class ExampleBase:
# constructor takes care of instantiating member variables of the class
def __init__(self, my_company_name, my_stocks_dict, **kwargs):
self.company_name = my_company_name
self.stocks = my_stocks_dict
# string method prints the company's name
def __str__(self):
return self.company_name
# this fxn expands stock purchases by adding more entries to the dictionary
def add_purchase(self, other, **kwargs):
self.stocks.update(other, **kwargs)
return
# Derived Class
class Useful(ExampleBase):
# constructor calls base class' constructor
def __init__(self, my_company_name, my_stocks_dict, **kwargs):
ExampleBase.__init__(self, my_company_name, my_stocks_dict, **kwargs)
# go through the self.stocks dictionary and calculate total value
# as summation of shared purchase values multiplied by stock price
def compute_value(self):
value_sum = 0
for item in list(self.stocks.values()):
# compute the value of the stocks
product = item[0] * item[1]
value_sum += product
# if the number of share is negative, raise a custom exception
if item[0] < 0:
raise ExampleException("ERROR: Invalid number of shares!!")
return value_sum
# string method overriding the one from base class
# outputs a table of stock dictionary and total stock value
def __str__(self):
print("Company's Symbol " + self.company_name)
for date, item in self.stocks.items():
if item[0] == 1:
print("On {} {} share is purchased at ${}".format(date, item[0], item[1]))
elif item[0] > 1:
print("On {} {} shares are purchased at ${}".format(date, item[0], item[1]))
else:
e = ExampleException("!INVALID!")
print("On {} {} shares are purchased at ${}".format(date, e, item[1]))
return "------------------------------------------------------"
| true |
c145820dfe8508a0091293b96dbf1b45d5507bd1 | Stephania86/Algorithmims | /reverse_statement.py | 449 | 4.5625 | 5 | # Reverse a Statement
# Build an algorithm that will print the given statement in reverse.
# Example: Initial string = Everything is hard before it is easy
# Reversed string = easy is it before hard is Everything
def reverse_sentence(s):
word_list = s.split()
word_list.reverse()
reversed_sentence = " ".join(word_list)
return reversed_sentence
str = "Everything is hard before it is easy"
print(str)
print(reverse_sentence(str)) | true |
c09cbd12035fbd857e646f2379691090df8e267c | Stephania86/Algorithmims | /Even_first.py | 674 | 4.34375 | 4 | # Even First
# Your input is an array of integers, and you have to reorder its entries so that the even
# entries appear first. You are required to solve it without allocating additional storage (operate with the input array).
# Example: [7, 3, 5, 6, 4, 10, 3, 2]
# Return [6, 4, 10, 2, 7, 3, 5, 3]
def even_first(arr):
next_even = 0
next_odd = len(arr) - 1
while next_even < next_odd:
if arr[next_even] % 2 == 0:
next_even += 1
else:
arr[next_even], arr[next_odd] = arr[next_odd], arr[next_even]
next_odd -= 1
test_data = [7, 3, 5, 6, 4, 10, 3, 2]
print(test_data)
even_first(test_data)
print(test_data)
| true |
8fb6a2464a7c668ea237ed170a3e84a237c4a049 | Lincxx/py-PythonCrashCourse | /ch3 lists/motorcycles.py | 1,470 | 4.59375 | 5 | motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
# change an element in a list
motorcycles[0] = 'ducati'
print(motorcycles)
# append to a list
motorcycles.append('Indian')
print(motorcycles)
# Start with an empty list
friends = []
friends.append("Jeff")
friends.append("Nick")
friends.append("Corey")
friends.append("Erick")
friends.append("Chuck")
print(friends)
# inserting into a list
letters = ['a', 'c', 'd']
letters.insert(1, 'b')
print(letters)
# remove an element from a list
pets = ['dog', 'cat', 'fish', 'bird']
del pets[1]
print(pets)
# pop an item from a. The pop() method removes the last item in a list,
# but it lets you work with that item after removing it
sports = ['football', 'hockey', 'fencing', 'skiing']
print(sports)
# How might this pop() method be useful? Imagine that the sports
# in the list are stored in chronological order according to when we played
# them.
popped_sport = sports.pop()
print(sports)
print(popped_sport)
# popping items from any position in a list
fav_sport = sports.pop(1)
print("This has been one of my fav sports since I was a child " + fav_sport)
print(sports)
# Removing an Item by Value
# Sometimes you wonโt know the position of the value you want to remove
# from a list. If you only know the value of the item you want to remove, you
# can use the remove() method
lab_colors = ['yellow', 'black', 'chocolate']
print(lab_colors)
lab_colors.remove('yellow')
print(lab_colors)
| true |
fddb55fdc2d951f6c8dbcf265ee894ed6b853c43 | Lincxx/py-PythonCrashCourse | /ch3 lists/exercises/3-5.py | 1,030 | 4.25 | 4 | # 3-5. Changing Guest List: You just heard that one of your guests canโt make the
# dinner, so you need to send out a new set of invitations. Youโll have to think of
# someone else to invite.
# โข Start with your program from Exercise 3-4. Add a print statement at the
# end of your program stating the name of the guest who canโt make it.
# โข Modify your list, replacing the name of the guest who canโt make it with
# the name of the new person you are inviting.
# โข Print a second set of invitation messages, one for each person who is still
# in your list.
interesting_people = ['Einstein', 'Jack Black', 'The Queen']
cant_attend = interesting_people.pop(1)
print("Mr/Mrs " + cant_attend+ ", can not attend the dinner")
interesting_people.append('Elvis')
print("Mr/Mrs, " + interesting_people[0] + ". I would like to invite you to dinner")
print("Mr/Mrs, " + interesting_people[1] + ". I would like to invite you to dinner")
print("Mr/Mrs, " + interesting_people[2] + ". I would like to invite you to dinner")
| true |
ec339af34ee862e4be09aa357477f6be7512c868 | Lincxx/py-PythonCrashCourse | /ch3 lists/exercises/3-4.py | 577 | 4.34375 | 4 | # 3-4. Guest List: If you could invite anyone, living or deceased, to dinner, who
# would you invite? Make a list that includes at least three people youโd like to
# invite to dinner. Then use your list to print a message to each person, inviting
# them to dinner.
interesting_people = ['Einstein', 'Jack Black', 'The Queen']
print("Mr/Mrs, " + interesting_people[0] + ". I would like to invite you to dinner")
print("Mr/Mrs, " + interesting_people[1] + ". I would like to invite you to dinner")
print("Mr/Mrs, " + interesting_people[2] + ". I would like to invite you to dinner") | true |
42ab61361b181d15deeb79ddcee10368643786c2 | tramxme/CodeEval | /Easy/RollerCoaster.py | 1,043 | 4.125 | 4 | '''
CHALLENGE DESCRIPTION:
You are given a piece of text. Your job is to write a program that sets the case of text characters according to the following rules:
The first letter of the line should be in uppercase.
The next letter should be in lowercase.
The next letter should be in uppercase, and so on.
Any characters, except for the letters, are ignored during determination of letter case.
CONSTRAINTS:
The length of each piece of text does not exceed 1000 characters.
'''
import sys, re
def doStuff(string):
string = re.sub(r'\n','', string)
chars = list(string)
res = ""
up = True
for i in range(len(chars)):
if(chars[i].isalpha() == True and up == True):
up = False
res += chars[i].upper()
else:
if chars[i].isalpha():
up = True
res += chars[i]
print(res)
def main(file_name):
fileName = open(file_name, 'r')
for line in fileName.readlines():
doStuff(line)
if __name__ == '__main__':
main(sys.argv[1])
| true |
569fb617c5b2721bd3df06cf09fd12cc80cd071b | tramxme/CodeEval | /Easy/ChardonayOrCabernet.py | 2,096 | 4.1875 | 4 | '''
CHALLENGE DESCRIPTION:
Your good friend Tom is admirer of tasting different types of fine wines. What he loves even more is to guess their names. One day, he was sipping very extraordinary wine. Tom was sure he had tasted it before, but what was its name? The taste of this wine was so familiar, so delicious, so pleasantโฆ but what is it exactly? To find the answer, Tom decided to taste the wines we had. He opened wine bottles one by one, tasted different varieties of wines, but still could not find the right one. He was getting crazy, โNo, itโs not that!โ desperately breaking a bottle of wine and opening another one. Tom went off the deep end not knowing what this wine was. Everything he could say is just several letters of its name. You can no longer look at it and decided to help him.
Your task is to write a program that will find the wine name, containing all letters that Tom remembers.
CONSTRAINTS:
Wine name length can be from 2 to 15 characters.
Number of letters that Tom remembered does not exceed 5.
Number of wine names in a test case can be from 2 to 10.
If there is no wine name containing all letters, print False.
The number of test cases is 40.
'''
import sys, re, math
def countChar(s):
count = {}
for c in s:
if c in count:
count[c] += 1
else:
count.setdefault(c,1)
return count
def doStuff(string):
values = string.split(" | ")
wines = values[0].split()
rememberedChars_count = countChar(values[1])
res = []
for wine in wines:
temp = countChar(wine)
correctWine = True
for k,v in rememberedChars_count.items():
if k not in temp or temp[k] < v:
correctWine = False
break
if correctWine == True:
res.append(wine)
if len(res) == 0:
print("False")
else:
print(" ".join(res))
def main(file_name):
fileName = open(file_name, 'r')
for line in fileName.readlines():
doStuff(re.sub(r'\n','', line))
if __name__ == '__main__':
main(sys.argv[1])
| true |
f78f231145b031de661340f6bb6dbedcd567b837 | randalsallaq/data-structures-and-algorithms-python | /data_structures_and_algorithms_python/challenges/array_reverse/array_reverse.py | 350 | 4.4375 | 4 | def reverse_array(arr):
"""Reverses a list
Args:
arr (list): python list
Returns:
[list]: list in reversed form
"""
# put your function implementation here
update_list = []
list_length = len(arr)
while list_length:
update_list.append(arr[list_length-1])
list_length-=1
return arr
| true |
70291137c6c759f268f7ab8b45591a3d1ec95cd9 | dnwigley/Python-Crash-Course | /make_album.py | 492 | 4.21875 | 4 | #make album
def make_album(artist_name , album_title):
""""Returns a dictionary based on artist name and album title"""
album = {
'Artist' : artist_name.title(),
'Title' : album_title.title(),
}
return album
print("Enter q to quit")
while True:
title = input("Enter album title: ")
if title == "q":
break
artist = input("Enter artist: ")
if artist =="q":
break
album = make_album(artist , title)
print(album)
print("Good-bye!")
| true |
53fb20fc1ba77ca145dea0b93a89cc020f887619 | naveensambandan11/PythonTutorials | /tutorial 39_Factorial.py | 224 | 4.34375 | 4 | # Funtion to calculate factorial
def Fact(n):
fact = 1
for i in range(1, n+1):
fact = fact * i
return fact
n = int(input('enter the number to get factorial:'))
result = Fact(n)
print(result) | true |
da85714a0fea257a811e53d95d5b0bf3d99717a5 | TwitchT/Learn-Pythonn-The-Hard-Way | /ex4.py | 1,687 | 4.4375 | 4 | # This is telling me how many cars there is
cars = 100
# This is going to tell me how much space there is in a car
space_in_a_car = 40
# This is telling me how many drivers there is for the 100 cars
drivers = 30
# This is telling how many passengers there is
passengers = 90
# This tells me how many empty cars there is going to be so you have to substract how many cars there is by how many drivers there is available
cars_not_driven = cars - drivers
# How many cars are going to be driven base on how many drivers there is
cars_driven = drivers
# To find the carpool capacity, I am going to multiply how many cars are going to be driven by the space in the car
carpool_capacity = cars_driven * space_in_a_car
# This is telling me how many average passengers is going to be in 1 car
average_passengers_per_car = passengers / cars_driven
# The print is going to tell me how many cars are available
print("There are", cars, "cars available.")
# The print is going to tell me how many drivers is available to drive the cars
print("There are", drivers, "drivers available.")
# This print is going to tell me how many cars are empty
print("There will be", cars_not_driven, "empty cars today.")
# This print is going to tell me how many people will be able to fit in one car
print("We can transport", carpool_capacity, "people today.")
# The print is telling me how many passengers I have today
print("We have", passengers, "to carpool today.")
# This print is going to average the passengers per car
print("We need to put about", average_passengers_per_car, "in each car.")
# _ is called an underscore character and it is used a lot to put an imaginary space between words in variable names | true |
1dfed477aa45a48f640d4d869f5ae051c99b363a | TwitchT/Learn-Pythonn-The-Hard-Way | /ex13.py | 984 | 4.125 | 4 | from sys import argv
# Read the WYSS section for how to run this
# These will store the variables
script, first, second, third = argv
# Script will put the first thing that comes to the line, 13.py is the first thing
# So script will put it 13.py and it will be the variable
print("The script is called:", script)
# If you put Kiwi after the 13.py then kiwi will be the varaible and it will replace first
print("Your first variable is called:", first)
# What ever you put after kiwi then it would turn it into a variable so if you put mango then
# Mango would be the second variable
print("Your second variable is called:", second)
# Your last and third variable is whatever you out after Mango so if you put Watermelon
# Then third would be replace with watermelon
print("Your third variable is called:", third)
# It tells me that there is too many values to unpack
#print("Your fourth variable is called:", fourth)
# One study drill
# The errors says "not enough values to unpack " | true |
33115232faf0951e37f4b48521e3e22f6bbc2a00 | TwitchT/Learn-Pythonn-The-Hard-Way | /ex23.py | 916 | 4.125 | 4 | import sys
# Will make the code run on bash
script, input_encoding, error = sys.argv
# Defines the function to make it work later on
def main(language_file, encoding, errors):
line = language_file.readline()
if line:
print_line(line, encoding, errors)
return main(language_file, encoding, errors)
# Defines this function to make it work when I use it again in the code
def print_line(line, encoding, errors):
next_lang = line.strip()
raw_bytes = next_lang.encode(encoding, errors=errors)
cooked_string = raw_bytes.decode(encoding, errors=errors)
# This will print out '<===>' for every raw bytes that the txt have
print(raw_bytes, "<===>", cooked_string)
# This will open the language.txt and it will encode something called a utf-8
languages = open("languages.txt", encoding="utf-8")
# Function that we define before
main(languages, input_encoding, error) | true |
03cd39bc59234bd30b84a89ae3157a44363f8a93 | Ishan-Bhusari-306/applications-of-discrete-mathematics | /dicestrategy.py | 988 | 4.28125 | 4 | def find_the_best_dice(dices):
# you need to use range (height-1)
height=len(dices)
dice=[0]*height
#print(dice)
for i in range(height-1):
#print("this is dice number ",i+1)
# use height
for j in range(i+1,height):
#print("comparing dice number ",i+1," with dice number ",j+1)
check1=0
check2=0
for element1 in dices[i]:
for element2 in dices[j]:
if element1>element2:
check1=check1+1
elif element2>element1:
check2=check2+1
else:
continue
if check1>check2:
print("the dice number ",i+1,"is better than dice number ",j+1)
dice[i]=dice[i]+1
else:
print("the dice number ",j+1,"is better than dice number ",i+1)
dice[j]=dice[j]+1
print(dice)
maxelement=max(dice)
maxindex=dice.index(max(dice))
for i in range(len(dice)):
if i != maxindex:
if dice[i]==maxelement:
return -1
return maxindex
dices=[[1, 2, 3, 4, 5, 6], [1, 1, 2, 4, 5, 7], [1, 2, 2, 3, 4, 7]]
print(find_the_best_dice(dices))
| true |
892ba5dc80b77da4916db1e1afb0f0b4a06c75ba | ibndiaye/odd-or-even | /main.py | 321 | 4.25 | 4 | print("welcome to this simple calculator")
number = int(input("Which number do you want to check? "))
divider = int(input("what do you want to divide it by? "))
operation=number%divider
result=round(number/divider, 2)
if operation == 0:
print(f"{result} is an even number")
else:
print(f"{result} is an odd number")
| true |
d475df99c67157cfad58ce2514cae3e378ed785c | adwardlee/leetcode_solutions | /0114_Flatten_Binary_Tree_to_Linked_List.py | 1,520 | 4.34375 | 4 | '''
Given the root of a binary tree, flatten the tree into a "linked list":
The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null.
The "linked list" should be in the same order as a pre-order traversal of the binary tree.
Example 1:
Input: root = [1,2,5,3,4,null,6]
Output: [1,null,2,null,3,null,4,null,5,null,6]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [0]
Output: [0]
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-100 <= Node.val <= 100
Follow up: Can you flatten the tree in-place (with O(1) extra space)?
'''
# 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 flatten(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
if root == None:
return None
_ = self.flattenSubtree(root)
return root
def flattenSubtree(self, root):
a = None
tmpright = root.right
if root.left:
a = self.flattenSubtree(root.left)
tmp = a
root.right = root.left
tmp.right = tmpright
root.left = None
if tmpright:
a = self.flattenSubtree(tmpright)
return a if a else root | true |
6bf88ae9e8933f099ed1d579af505fc8ef0d04b4 | Abicreepzz/Python-programs | /Decimal_to_binary.py | 462 | 4.25 | 4 | def binary(n):
result=''
while n>0:
result=str(n%2)+str(result)
n//=2
return int(result)
binary(5) ##output= 101
# Another simple one line code for converting the decimal number to binary is followed:
def f(n): print('{:04b}'.format(n))
binary(5) ##output =101
# If we want to print in the 8 bit digit of the binary numbers then we can just specify the 8 bit in function.
def f(n): print('{:08b}'.format(n))
binary(5) ##output = 00000101
| true |
9e188e9dcd5fd64231f883943ab83e307158a5f7 | Jewel-Hong/SC-projects | /SC101Lecture_code/SC101_week6/priority_queue_list.py | 1,402 | 4.46875 | 4 | """
File: priority_queue_list.py
Name:
----------------------------------
This program shows how to build a priority queue by
using Python list. We will be discussing 3 different
conditions while appending:
1) Prepend
2) Append
3) Append in between
"""
# This constant controls when to stop the user input
EXIT = ''
def main():
priority_queue = []
print('--------------------------------')
# TODO:
while True:
name = input('Patient: ')
if name == EXIT:
break
priority = int(input('Priority: '))
data = (name, priority)
if len(priority_queue) == 0:
priority_queue.append(data)
else:
# Prepend
if priority < priority_queue[0][1]:
priority_queue.insert(0, data)
# Append
elif priority >= priority_queue[len(priority_queue)-1][1]:
priority_queue.append(data)
# In between
else:
for i in range(len(priority_queue) - 1): # ๅจpythonไนไธญfor loopไธๆๅๆ
ๆดๆฐ๏ผๅ
ถไป่ช่จๆ
if priority_queue[i][1] <= priority < priority_queue[i+1][1]:
priority_queue.insert(i+1, data)
break #ไธ็ถๆ็ข็็ก้่ฟดๅ
print('--------------------------------')
print(priority_queue)
if __name__ == '__main__':
main()
| true |
7ce2f22d370784db0284cac76eba4becb42f7556 | Jewel-Hong/SC-projects | /SC101Lecture_code/SC101_week3/word_occurrence.py | 1,397 | 4.21875 | 4 | """
File: student_info_dict.py
------------------------------
This program puts data in a text file
into a nested data structure where key
is the name of each student, and the value
is the dict that stores the student info
"""
# The file name of our target text file
FILE = 'romeojuliet.txt'
# Contains the chars we would like to ignore while processing the words
PUNCTUATION = '.,;!?#&-\'_+=/\\"@$^%()[]{}~'
def main():
d = {}
with open(FILE, 'r') as f:
for line in f:
token_list = line.split()
for token in token_list:
token = string_manipulation(token)
# ไธ็ฅ้ๅญไธๅญๅจๆ้บผๅ ๅฆ! key error~
# d[token] += 1
# key็บ่ฉฒๆๅญ๏ผvalue็บ่ฉฒๆๅญๅบ็พไนๆฌกๆธ
if token in d:
d[token] += 1
else:
# ๆณจๆๅๅงๅผ็บ1๏ผ้0๏ผๅ ็บ็ถไฝ ็ๅฐๅฎๆๆฏๅฎๅบ็พ็็ฌฌไธๆฌก!!
d[token] = 1
print_out_d(d)
def print_out_d(d):
"""
: param d: (dict) key of type str is a word
value of type int is the word occurrence
---------------------------------------------------------------
This method prints out all the info in d
"""
for key, value in sorted(d.items(), key=lambda t: t[1]):
print(key, '->', value)
def string_manipulation(word):
word = word.lower()
ans = ''
for ch in word:
if ch.isalpha() or ch.isdigit():
# if ch not in PUNTUATION:
ans += ch
return ans
if __name__ == '__main__':
main()
| true |
80f2cfaaa82a18157ebc3b8d6015ac36b3412bc4 | uppala-praveen-au7/blacknimbus | /AttainU/Robin/Code_Challenges/Day2/Day2/D7CC3.py | 1,984 | 4.21875 | 4 | # 3) write a program that takes input from the user as marks in 5 subjects and assigns a grade according to the following rules:
# Perc = (s1+s2+s3+s4+s5)/5.
# A, if Perc is 90 or more
# B, if Perc is between 70 and 90(not equal to 90)
# C, if Perc is between 50 and 70(not equal to 90)
# D, if Perc is between 30 and 50(not equal to 90)
# E, if Perc is less than 30
# Defining a function to check a number contains no characters
# and the marks less than 100
def my_func(a):
# Defining a list for reference to compare the characters of the input
list=['0','1','2','3','4','5','6','7','8','9','.']
for i in range(0,len(a)):
if a[i] in list:
continue
else:
a=input('Enter valid marks: ')
continue
# after confirming the entered input contains only numbers
# checking whether the given number is greater than 100
# and if it is greater than 100 asking the student to enter
# the marks scaled to 100
if float(a)>100:
a=input('please enter your marks scaled to 100: ')
my_func(a)
else:
pass
return float(a)
# getting the individual subject marks from a student
subject1=(input('enter the subject1 marks out of 100 here: '))
sub1=my_func(subject1)
subject2=(input('enter the subject2 marks out of 100 here: '))
sub2=my_func(subject2)
subject3=(input('enter the subject3 marks out of 100 here: '))
sub3=my_func(subject3)
subject4=(input('enter the subject4 marks out of 100 here: '))
sub4=my_func(subject4)
subject5=(input('enter the subject5 marks out of 100 here: '))
sub5=my_func(subject5)
total= sub1+sub2+sub3+sub4+sub5
print('Total: ',total)
perc =(sub1+sub2+sub3+sub4+sub5)/5
print('Average: ',perc)
if perc>=90:
print('Your grade is \'A\'')
elif perc>=70 and perc<90:
print('your grade is \'B\'')
elif perc>=50 and perc<70:
print('Your grade is \'C\'')
elif perc>=30 and perc<50:
print('Your grade is \'D\'')
else:
print('Your grade is \'E\'')
| true |
2c49ef300a9d5a6b783f103e064132f222fe4977 | ruchirbhai/Trees | /PathSum_112.py | 2,125 | 4.15625 | 4 | # https://leetcode.com/problems/path-sum/
# Given a binary tree and a sum, determine if the tree has a root-to-leaf path such
# that adding up all the values along the path equals the given sum.
# Note: A leaf is a node with no children.
# Example:
# Given the below binary tree and sum = 22,
# 5
# / \
# 4 8
# / / \
# 11 13 4
# / \ \
# 7 2 1
# return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
from collections import deque
answer = False
# Definition for a binary tree node.
class TreeNode:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
class Solution:
def path_sum(self, root):
# Edge case when the root is empty
if root is None:
# if the target is Zero and the tree is null its not clear if we return true of false.
# another corner case to consider
return False
global answer
self.path_sum_helper(root, 0, 22)
return answer
def path_sum_helper(self, node, slate_sum, target):
#base case: leaf node
if node.left is None and node.right is None:
if slate_sum + node.data == target:
global answer
answer = True
return answer
# recursive case
if node.left is not None:
self.path_sum_helper(node.left, slate_sum + node.data, target)
#right side
if node.right is not None:
self.path_sum_helper(node.right, slate_sum + node.data, target)
#driver program for the above function
# #left side of the tree
# root = TreeNode(1)
root = TreeNode(5)
root.left = TreeNode(4)
root.left.left = TreeNode(11)
root.left.left.left = TreeNode(7)
root.left.left.right = TreeNode(2)
#right side of the tree
root.right = TreeNode(8)
root.right.left = TreeNode(13)
root.right.right = TreeNode(4)
root.right.right.right = TreeNode(1)
# Create a object for the class
obj = Solution()
#now call the class methos with the needed arguments
print(obj.path_sum(root)) | true |
58118aa6dac147138a91cdfb393ddf328be961b0 | 44858/variables | /multiplication and division.py | 484 | 4.34375 | 4 | #Lewis Travers
#12/09/2014
#Multiplying and dividing integers
first_integer = int(input("Please enter your first integer: ")
second_integer = int(input("Please enter an integer that you would like the first to be multiplied by: "))
third_integer = int(input("Please enter an integer that you would like the total of the previous to be divided by: "))
end_total = (first_integer * second_integer) / third_integer
print("The total is {0}").format(end_total)
| true |
9995de8314efb0c98d03f0c893bb7b7ddbbfd239 | jjsherma/Digital-Forensics | /hw1.py | 2,967 | 4.3125 | 4 | #!/usr/bin/env python
import sys
def usage():
"""Prints the correct usage of the module.
Prints an example of the correct usage for this module and then exits,
in the event of improper user input.
>>>Usage: hw1.py <file1>
"""
print("Usage: "+sys.argv[0]+" <file1>")
sys.exit(2)
def getFile():
"""Creates a file descriptor for a user-specified file.
Retreives the filename from the second command line argument
and then creates a file descriptor for it.
Returns:
int: A file descriptor for the newly opened file specified
by the user.
Raises:
An error occured while attempting to open the file
"""
if len(sys.argv) > 1:
filename = sys.argv[1]
else:
usage()
try:
fd = open(filename, "rb")
return fd
except:
print("error opening program ")
sys.exit()
def partialLine(bytes):
"""Adds additional spacing so the ASCII on a shortened line lines up with preceeding lines.
Takes the number of bytes on a short line and finds the difference
between a full line. This difference is then used to calculate
the number of spaces necessary to properly align the ASCII with
the rows above.
>>>00000000 32 b4 51 7a 3b 3c 64 dd c3 61 da 8a ff 60 5c 9b |2.Qz;<d..a...`\.|
>>>00000120 91 93 f7 |...|
Args:
bytes: The number of bytes currently being processed
"""
if sys.getsizeof(bytes) < 33:
difference = 33 - sys.getsizeof(bytes)
while difference != 0:
print(" ", end = "")
difference = difference - 1
def process():
"""Forms a table with byte hex values, memory positions in hex, and associated ASCII
Uses the file descriptor from getFile() to continually read 16 bytes
formatting each line so that the memory position, in hex, of the first
byte of a line, followed by all of the hex values for those bytes, and then
the associated ASCII values for the hex values.
>>>00000000 32 b4 51 7a 3b 3c 64 dd c3 61 da 8a ff 60 5c 9b |2.Qz;<d..a...`\.|
Raises:
An error occured while attempting to close the file
"""
fd = getFile()
count = 0
bytes = fd.read(16)
while bytes:
print("%08x" % count + " ", end = "")
for b in bytes:
print("%02x" % b + " ", end = "")
count = count + 1
if sys.getsizeof(bytes) < 33 and sys.getsizeof(bytes) > 17:
partialLine(bytes)
print("|", end = "")
for b in bytes:
if b > 31 and b < 127:
print(chr(b), end = "")
else:
print(".", end = "")
print("|")
bytes = fd.read(16)
print("%08x" % count + " ")
try:
fd.close()
except:
print("error closing program ")
sys.exit()
def main():
process()
if __name__=="__main__":
main()
| true |
2f9c1a23384af6b52ab218621aa937a294a6b793 | bainjen/python_madlibs | /lists.py | 895 | 4.125 | 4 | empty_list = []
numbers = [2, 3, 5, 2, 6]
large_animals = ["african elephant", "asian elephant", "white rhino", "hippo", "guar", "giraffe", "walrus", "black rhino", "crocodile", "water buffalo"]
a = large_animals[0]
b = large_animals[5]
# get the last animal in list
c = large_animals[-1]
# return index number
d = large_animals.index('crocodile')
# accessing slices (chunks) of list - (first element, last element)
e = large_animals[0:3] # returns indices 0, 1, 2
f = large_animals[3] = 'penguin' # change value
# delete
del large_animals[3]
# find length
g = len(a)
# can have nested lists
animal_kingdom = [
['cat', 'dog'],
['turtle', 'lizard'],
['eagle', 'robin', 'crow']
]
biggest_bird = animal_kingdom[-1][0]
# strings are also lists of symbols and can be treated as such
h = 'this is a list of symbols'
i = h[5:7]
j = h.split(' ')
k = h.split('symbols')
print(j)
print(k) | true |
36e830aa4a52c6f8faa1347722d1dab6333088c8 | tom1mol/core-python | /test-driven-dev-with-python/refactoring.py | 1,197 | 4.3125 | 4 | #follow on from test-driven-development
def is_even(number):
return number % 2 == 0 #returns true/false whether number even/not
def even_number_of_evens(numbers):
evens = sum([1 for n in numbers if is_even(n)])
return False if evens == 0 else is_even(evens)
""" this reduces to line 7/8 above
evens = 0 #initialise a variable to say currently zero evens
#loop to check each number and see if it's even
for n in numbers:
if is_even(n): #remainder when divided by 2 is zero(modulo)..then is even number
evens += 1 #if even...increment by 1
if evens == 0: # if number of evens = 0
return False
else:
return is_even(evens) #returns true if number of evens is even
"""
assert even_number_of_evens([]) == False, "No numbers"
assert even_number_of_evens([2, 4]) == True, "2 even numbers"
assert even_number_of_evens([2]) == False, "1 even number"
assert even_number_of_evens([1,3,9]) == False, "3 odd numbers"
print("All tests passed!") | true |
bc547b6f91f5f3133e608c4aa479eb811ddf7c58 | sgspectra/phi-scanner | /oldScripts/wholeFile.py | 835 | 4.40625 | 4 | # @reFileName is the name of the file containing regular expressions to be searched for.
# expressions are separated by newline
# @fileToScanName is the name of the file that you would like to run the regex against.
# It is read all at once and the results returned in @match
import re
#reFileName = input("Please enter the name of the file containing regular expressions:")
#reFile = open(reFileName, 'r')
reFile = open('lib/phi_regex.txt', 'r')
#fileToScanName = input("Please enter the name of the file you wish to scan:")
fileToScanName = 'test_text.txt'
for line in reFile:
fileToScan = open(fileToScanName, 'r')
# strip the newline from the regex
line = line.rstrip('\n')
print(line)
exp = re.compile(line)
print(exp)
match = exp.findall(fileToScan.read())
print(match)
fileToScan.close()
| true |
b28a938c098b5526fb6541b41f593d30a665b185 | elguneminov/Python-Programming-Complete-Beginner-Course-Bootcamp-2021 | /Codes/StringVariables.py | 1,209 | 4.46875 | 4 | # A simple string example
short_string_variable = "Have a great week, Ninjas !"
print(short_string_variable)
# Print the first letter of a string variable, index 0
first_letter_variable = "New York City"[0]
print(first_letter_variable)
# Mixed upper and lower case letter variable
mixed_letter_variable = "ThIs Is A MiXeD VaRiAbLe"
print(mixed_letter_variable.lower())
# Length of the variable
print(len(mixed_letter_variable))
# Use '+' sign inside a print command
first_name = "David"
print("First name is : " +first_name)
# Replace a part of a string
first_serial_number = "ABC123"
print("Changed serial number #1 : " +first_serial_number.replace('123' , '456'))
# Replace a part of a string -> Twice !
second_serial_number = "ABC123ABC"
print("Changed serial number #2 : " +second_serial_number.replace('ABC' , 'ZZZ' , 2))
# Take a part of a variable, according to specific index range
range_of_indexes = second_serial_number[0:3]
print(range_of_indexes)
# One last thing - adding spaces between multiple variables in print
first_word = "Thank"
second_word = "you"
third_word = "NINJAS !"
print(first_word +" " +second_word +" " +third_word)
"automationninja.qa@gmail.com"
| true |
201a2b05930cd4064623156c2b9248665d378647 | Dumacrevano/Dumac-chen_ITP2017_Exercise2 | /3.1 names.py | 234 | 4.375 | 4 | #Store the names of a few of your friends in a list called names .
# Print each personโs name by accessing each element in the list, one at a time .
names=["Suri", "andy", "fadil", "hendy"]
print(names[0],names[1],names[2],names[3]) | true |
9454b32184aa1c29ad0db72ec564036666dff0f9 | EnriqueStrange/portscannpy | /nmap port-scanner.py | 1,508 | 4.1875 | 4 | #python nmap port-scanner.py
#Author: P(codename- STRANGE)
#date: 10/09/2020
import argparse
import nmap
def argument_parser():
"""Allow target to specify target host and port"""
parser = argparse.ArgumentParser(description = "TCP port scanner. accept a hostname/IP address and list of ports to"
"scan. Attenpts to identify the service running on a port.")
parser.add_argument("-o", "--host", nargs = "?", help = "Host IP address")
parser.add_argument("-p", "--ports", nargs="?", help = "comma-separation port list, such as '25,80,8080'")
var_args = vars(parser.parse_args()) # Convert argument name space to dictionary
return var_args
def nmap_scan(host_id, port_num):
"""Use nmap utility to check host ports for status."""
nm_scan = nmap.PortScanner()
nm_scan.scan(host_id, port_num)
state = nm_scan[host_id]['tcp'][int(port_num)]['state'] # Indicate the type of scan and port number
result = ("[*] {host} tcp/{port} {state}".format(host=host_id, port=port_num, state=state))
return result
if __name__ == '__main__': # Runs the actual program
try:
user_args = argument_parser()
host = user_args["host"]
ports = user_args["ports"].split(",") # Make a list from port numbers
for port in ports:
print(nmap_scan(host, port))
except AttributeError:
print("Error, please provide the command_line argument before running.")
| true |
f484aab33a5142f6fbe20f6072e035339f561d0b | programmer290399/Udacity-CS101-My-Solutions-to-Exercises- | /CS101_Shift_a_Letter.py | 387 | 4.125 | 4 | # Write a procedure, shift, which takes as its input a lowercase letter,
# a-z and returns the next letter in the alphabet after it, with 'a'
# following 'z'.
def shift(letter):
ASCII = ord(letter)
if ASCII == 122 :
return chr(97)
else :
return chr(ASCII + 1)
print shift('a')
#>>> b
print shift('n')
#>>> o
print shift('z')
#>>> a
| true |
62c129920b2c9d82d35eaba02a73924596696280 | Maxrovr/concepts | /python/sorting/merge_sort.py | 1,982 | 4.21875 | 4 | class MergeSort:
def _merge(self, a, start, mid, end):
"""Merges 2 arrays (one starting at start, another at mid+1) into a new array and then copies it into the original array"""
# Start of first array
s1 = start
# Start of second array
s2 = mid + 1
# The partially sorted array
s = []
# for - till we iterate over all elements of partial array being sorted
for i in range(end - start + 1):
# If second array has been completely been traversed - first one still has some elements left - copy them all
if s1 > mid:
s.append(a[s2])
s2 += 1
# Vice-Versa
elif s2 > end:
s.append(a[s1])
s1 += 1
# Actual sorting - change symbols (either hardcode or dynamically with a bool descending)
elif a[s1] <= a[s2]:
s.append(a[s1])
s1 += 1
# Vice-Versa
else:
s.append(a[s2])
s2 += 1
# Copy partially sorted array into original array
a[start:end+1] = s
def _merge_sort(self, a, start, end):
"""Divides array into halves and calls merge on them"""
if start < end:
mid = start + (end - start) // 2
self._merge_sort(a, start, mid)
self._merge_sort(a, mid + 1, end)
self._merge(a, start, mid, end)
def merge_sort(self, a):
self._merge_sort(a, 0, len(a) - 1)
a = [i for i in range(8,0,-1)]
print(f'Before: {a}')
obj = MergeSort()
obj.merge_sort(a)
print(f'After: {a}')
a = [i for i in range(7,0,-1)]
print(f'Before: {a}')
obj = MergeSort()
obj.merge_sort(a)
print(f'After: {a}')
a = [i for i in range(1,9)]
print(f'Before: {a}')
obj = MergeSort()
obj.merge_sort(a)
print(f'After: {a}')
a = [i for i in range(1,8)]
print(f'Before: {a}')
obj = MergeSort()
obj.merge_sort(a)
print(f'After: {a}') | true |
a5333dc221c0adcb79f583faceb53c7078333601 | tocheng/Book-Exercises-Intro-to-Computing-using-Python | /Book-Chapter5_2-Range.py | 1,922 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Dec 29 09:48 2020
Introduction to Computation and Programming Using Python. John V. Guttag, 2016, 2nd ed
Book Chapter 5 Structured types, mutability and higher-order functions
Ranges
@author: Atanas Kozarev - github.com/ultraasi-atanas
RANGE the Theory
The range function takes three parameters - start, stop, step
Returns the progression of integers - start, start + step, start + step*2 etc
If step is positive, the last integer is the largest start + step*i smaller than stop
If step is negative, the last integer is the smallest integer start + step*i greater then stop
If two arguments are supplied, step is 1
If one argument is supplied, step is 1, stop is taken from arg, start is 0
All of the operations on tuples apply on ranges, except concatenation and repetition
The numbers of the progression are generated on an "as needed" basis, so even
expressions such as range(10000) consume little memory (Python3.x)
The arguments of the range function are evaluated just before the first iteration
of the loop and not reevaluated for subsequent iteration
"""
# RANGE SLICE
rangeSlice = range(10)[2:6][2] # returns 4
print('RangeSlice of range(10)[2:6][2] is ', rangeSlice, '\n')
# RANGE COMPARISON
range2 = range(0,7,2)
range3 = range(0,8,2)
print('Range 2 is equal to Range 3?', range2 == range3)
print('Range 2 is', range2)
print('Range 3 is', range3)
print("Range2: ")
for e in range2:
print(e)
print("Range3:")
for e in range3:
print(e)
# NEGATIVE STEP
range4 = range(40,-10,-10)
print('\n', 'Range4 is', range4)
for i in range4:
print('\n', i)
# EXECUTING RANGE INSIDE A FOR LOOP
x = 5
for i in range(0,x):
print(i)
x = 8 # it doesnt change the range set in the loop condition
x = 5
y = range(0,x)
for i in y:
print('\n', y)
print(i)
x = 8 # it doesnt change the range set in the loop condition
| true |
0240f939041db7bfe697fecd110ca33dd83f84b8 | tocheng/Book-Exercises-Intro-to-Computing-using-Python | /Book-Chapter2_2-FE-odd-number.py | 1,173 | 4.46875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 11 09:54:53 2020
Introduction to Computation and Programming Using Python. John V. Guttag, 2016, 2nd ed
Book Chapter 2 Finger Exercises - Find the largest odd number
@author: Atanas Kozarev - github.com/ultraasi-atanas
"""
# edge cases 100, 2, 3 and 100,2,-3 and 2,2,2
x = 301
y = 2
z = 1
# what if the largest number is not odd? We need to discard any non-odd numbers
# if none of them are odd - go straight to else
if (x % 2 != 0) or (y % 2 != 0) or (z % 2 != 0):
#codeblock if we have some odd numbers
print("ok")
# initialising the variable with one odd number, so we check each in turn
if (x % 2 != 0):
largest = x
elif (y % 2 != 0):
largest = y
elif (z % 2 != 0):
largest = z
# here we check each against the largest
# no need to check for x as we did already
if (y % 2 != 0):
if y > largest:
largest = y
if (z % 2 != 0):
if z > largest:
largest = z
print("The largest odd number is:", largest)
print("The numbers were", x, y, z)
else:
print("No odd number found")
| true |
32edc5c1c32209e99e6b51d2bf0cb14ba3f1a07c | tocheng/Book-Exercises-Intro-to-Computing-using-Python | /Book-Chapter2_3-Exercises-LargestOddNumberOf10.py | 1,186 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 13 14:15:03 2020
Introduction to Computation and Programming Using Python. John V. Guttag, 2016, 2nd ed
Book Chapter 2 Finger Exercises
Largest Odd number of 10, using user input
Prints the largest odd number that was entered
If no odd number was entered, it should print a message to that effect
@author: Atanas Kozarev - github.com/ultraasi-atanas
"""
# big goal is to handle and compare negative numbers entered
# we will build in a logic that start with an initial value of 0
# and then the first odd value entered by the user is
largest = 0
userPromptsRemaining = 10
print("You will be asked to enter a number 10 times")
while userPromptsRemaining > 0:
# get a number in
newNumber = int(input("Please enter a number: "))
# check if it's odd
if (newNumber % 2) != 0:
# check if that's the first registered number
if largest == 0:
largest = newNumber
elif newNumber > largest:
# do we have found a new largest
largest = newNumber
userPromptsRemaining -= 1
if largest == 0:
print("No odd numbers entered")
else:
print("Largest odd number entered ", largest)
| true |
1b049dc1145f1269bcbf38c96965fa0b13d585ca | guyjacks/codementor-learn-python | /string_manipulation.py | 872 | 4.1875 | 4 | print "split your and last name"
name = "guy jacks"
# split returns a list of strings
print name.split()
print "/n"
print "split a comma separated list of colors"
colors = "yellow, black, blue"
print colors.split(',')
print "\n"
print "get the 3rd character of the word banana"
print "banana"[2]
print "\n"
blue_moon = "Blue Moon"
print "get the first character of Blue Moon. get the last."
print blue_moon[0]
print blue_moon[-1]
print "\n"
print "get the last four characters of Blue Moon"
print blue_moon[4:]
print "\n"
print "get the first four characters of Blue Moon"
print blue_moon[:4]
print "\n"
print "get \"Moo\" from Blue Moon"
print blue_moon[5:8]
print "\n"
print "replace Blue with Full in Blue Moon"
print blue_moon.replace("Blue", "Full")
print "\n"
print "covert Blue Moon to lowercase. uppercase"
print blue_moon.lower()
print blue_moon.upper()
| true |
427e6f0978cd52b339ef4f89256ace7ff9298c4d | learnthecraft617/dev-sprint1 | /RAMP_UP_SPRINT1/exercise54.py | 291 | 4.21875 | 4 |
def is_triangle (a, b, c):
if a > b + c
print "YES!"
else
print "NO!"
is_triangle (4, 2, 5)
#5.4
question = raw_input('Please enter 3 lengths to build this triangle in this order (a, b, c)/n')
length = raw_input (a, b, c)
is triangle (raw_input)
| true |
afed5225df3b7a8cc6b42ba7691710a8a019459d | colten-cross/CodeWarsChallenges---Python | /BouncingBalls.py | 784 | 4.375 | 4 | # A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known.
# He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66).
# His mother looks out of a window 1.5 meters from the ground.
# How many times will the mother see the ball pass in front of her window (including when it's falling and bouncing?#
# Note:
# The ball can only be seen if the height of the rebounding ball is strictly greater than the window parameter.
# Example:
# h = 3, bounce = 0.66, window = 1.5, result is 3
def bouncing_ball(h, bounce, window):
Sightcount = 1
current = h * bounce
while current > window:
current *= bounce
Sightcount += 2
return Sightcount
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.