blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
9167003e750f0216857d8dab3aa3424231a33e11 | jiezheng5/PythonFundamentals | /app5-DatabaseAppUsing-TinkerSqlite/app5_backend.py | 2,261 | 4.375 | 4 | """
A program that stores the book information:
Title, Author
Year, ISBN
User can:
view all records
search an entry
add entry
update entry
delete
close
https://www.udemy.com/the-python-mega-course/learn/v4/t/lecture/4775396?start=0
"""
from tkinter import *
import sqlite3
import numpy as np
import itertools as it
#import app5_frontend
def create():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTs books \
(id INTEGER PRIMARY KEY, title TEXT, author TEXT, year INTEGER, isbn INTEGER)")
conn.commit()
conn.close()
def insert(title, author, year, isbn):
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("INSERT INTO books VALUES (NULL, ?,?,?,?)", (title, author, year, isbn))
conn.commit()
conn.close()
def update(id, title, author, year, isbn):
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("UPDATE books SET title=?, author=?, year=?, isbn=? WHERE id=?", \
(title, author, year, isbn, id))
conn.commit()
conn.close()
def delete(id):
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("DELETE FROM books WHERE id=?", (id,))
conn.commit()
conn.close()
def search(title='', author='', year='', isbn=''):
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("SELECT * FROM books WHERE title=? OR author=? OR year=? OR isbn=?", \
(title,author,year, isbn))
selected_rows=cur.fetchall()
#conn.commit()
conn.close()
return selected_rows
def view_table():
conn=sqlite3.connect("books.db")
cur=conn.cursor()
cur.execute("SELECT * FROM books")
rows=cur.fetchall()
#conn.commit()
conn.close()
return rows
create()
# insert('The Earch', 'John Smith', 1980, 908223214)
# insert('The Sun', 'Joe 3th', 1976, 908223214)
# update(112,'The Moon', 'Brian 4th', 1917, 908223214 )
# print(view_table())
# for i in it.chain(range(0, 110), range(120, 150)):
# #for i in range(0,112):#np.arange(40,100):#range(30):
# delete(i)
# print(view_table())
# print('\n search result: \n' , search(year='1980'))
#print('test running of backend.py in importing')
#print('\nTable: \n', view_table())
#print('\n search result: \n' , search(author='John Smith'))
#print('test') | true |
a521ef2d94a766a9dfbfcc33fa6145537855af9e | Rekapi/PyProblemSolving | /PS02.py | 2,898 | 4.1875 | 4 | # Continue
from __future__ import print_function
import sys
import math
import textwrap
import http.client
# 41. how to Sum two given numbers and return a number (functions)
def summation(x, y):
suma = x + y
if suma in range(15, 20):
return 20
else:
return suma
print(summation(2, 2))
# 42. how to add two objects if both objects are an integer type
def add_number(a, b):
if not (isinstance(a, int) and isinstance(b, int)):
raise TypeError("Must be Integer")
return a + b
print(add_number(1, 1))
# 43. how to display name, age, address in three different lines
def personal_detail():
name, age = "mahmoud", 20
address = "El Shrouk city "
print("Name : {}\nage: {}\naddress: {}".format(name, age, address))
personal_detail()
# 44. how to solve quadratic equation
def solve_eq(a, b, c):
y = b ** 2 - 4 * a * c
z = 2 * a
x1 = (-b + (math.sqrt(y)))
x2 = (-b - (math.sqrt(y)))
return x1 / z, x2 / z
"""a1 = float(input("The value of a : "))
b1 = float(input("The value of b : "))
c1 = float(input("The value of c : "))"""
print("(x1, x2) =", solve_eq(1, 5, 6))
# 45. how to calculate the future value of rate of interest and a number of years
# 46. how to calculate the distance between two points
p1 = [4, 0]
p2 = [6, 8]
distance = math.sqrt(((p1[0] - p2[0]) ** 2 + ((p1[1] - p2[1]) ** 2)))
print(distance)
# 47. check if a file exists
# 48. check if python version is 64 or 32
# 49. check the os name, platform and release information
# 50. how to find the location of python site package directory
# 51. how to call an external command
# 52. how to get path and name of a file that currently executing in python
# 53. how to find out the number of CPUs
# 54. how to convert strings to float or int
n = "244.3"
print(float(n))
print(int(float(n)))
# 55. how to print stderr
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
eprint("abc", "efg", "xyz", sep="__")
# 56. how to sort counter by value
# 57. converts height in feet and inches to centimeters
# 58. calculate the hypotenuse of a right angled triangle
# 59. how to get file creation & modification date times
# 60. calculate body mass index
# 61. converts seconds to day, hour, minutes and seconds
# 62. get a list of built in modules
module_name = ', '.join(sorted(sys.builtin_module_names))
print(textwrap.fill(module_name, width=70))
# 63. how to find ASCII value of a character
# 64. remove the first item of a list
# 65. how to read the contents of an URL
conn = http.client.HTTPConnection("www.google.com")
conn.request("GET", "/")
result = conn.getresponse()
contents = result.read()
print(contents)
# 66. how to get the system hostname
# 67. how to swap two variables
# 68. how to concatenate N strings
# 69. how to find file path or directory
# 70. how to get the users environment (77 in the PlayList)
| true |
90aa9b98e719c314488a86b049ba9d220eda47fb | PrtagonistOne/Beetroot_Academy | /lesson_04/task_2.py | 815 | 4.21875 | 4 |
def main():
number = input('Enter your phone number here: ')
message = phone_validator(number)
if message == 'lenght':
print('Your number should consist of exactly 10 digits')
elif message == 'digits':
print('Your number should consist of only numerical chars')
elif message == 'valid':
print('Your number is valid!')
else:
print('Something went wrong! Contact developer')
def phone_validator(phone_number: str) -> str:
"""Return tuple(bool and message) if the phone number consist of 10 digits
Message specifies the what's wrong with the number provided"""
if len(phone_number) < 10:
return f'lenght'
elif not phone_number.isdigit():
return 'digits'
else:
return 'valid'
if __name__ == '__main__':
main() | true |
5faa6ec0949f2cc7700a12ead0f83e74265d6bb3 | PrtagonistOne/Beetroot_Academy | /lesson_07/task_1.py | 704 | 4.125 | 4 | # Make a program that has some sentence (a string) on input and returns a dict
# containing all unique words as keys and the number of occurrences as values.
# For testing:
# 'Hello, my name is Andrey. Andrey is from Odessa. Andrey currently studies python language at Beetroot Academy in Python for Begginers course. Beetroot Academy is a great place to learn python!'
import string
raw_text = input('Enter your text here: ')
# get rid of punctuation in a raw_string
processed_text = raw_text.translate(str.maketrans('', '', string.punctuation))
# count words in a dict
words = {}
for word in processed_text.split():
word = word.lower()
words[word] = words.get(word, 0) + 1
print(words) | true |
94204564422e698810bbcad1c30c3faf3fc20833 | PrtagonistOne/Beetroot_Academy | /lesson_13/task_1.py | 1,157 | 4.21875 | 4 | # Method overloading.
# Create a base class named Animal with a method called talk and then create two subclasses: Dog and Cat,
# and make their own implementation of the method talk be different. For instance, Dog’s can be to print ‘woof woof’,
# while Cat’s can be to print ‘meow’.
# Also, create a simple generic function, which takes as input instance of a Cat or Dog classes and performs talk method on input parameter.
class Animal:
def __init__(self, name, color) -> None:
self.name = name
self.color = color
def talk(self) -> None:
print('Sound')
class Dog(Animal):
def __init__(self, name, color) -> None:
super().__init__(name, color)
def talk(self) -> None:
print('woof woof')
class Cat(Animal):
def __init__(self, name, color) -> None:
super().__init__(name, color)
def talk(self) -> None:
print('meow meow')
def talk_func(animal: object) -> None:
animal.talk()
unknown_spicie = Animal('Alien', 'black')
dog = Dog('Jack', 'black')
cat = Cat('Marty', 'white')
talk_func(unknown_spicie)
talk_func(dog)
talk_func(cat)
| true |
7c68e814e22c38c69fdd41fc981f8bcfb9153479 | Pabitra-26/Problem-Solved | /LeetCode/Flipping_an_image.py | 792 | 4.28125 | 4 | # Problem name: Flipping an image
# Description: Given a binary matrix A, we want to flip the image horizontally, then invert it, and return the resulting image.
# To flip an image horizontally means that each row of the image is reversed.
# For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].
# To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0.
# For example, inverting [0, 1, 1] results in [1, 0, 0].
class Solution:
def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]:
for i in range(len(A)):
A[i].reverse()
for j in range(len(A[i])):
if(A[i][j]==0):
A[i][j]=1
else:
A[i][j]=0
return A | true |
88433a61b1a4375a5c71b61e8aa900e11a954961 | Pabitra-26/Problem-Solved | /Hackerrank/Marc'sCakewalk.py | 1,290 | 4.28125 | 4 | # Problem name: Marc's Cakewalk
""" Description: Marc loves cupcakes, but he also likes to stay fit. Each cupcake has a calorie count, and Marc can walk a distance to expend those calories.
If Marc has eaten j cupcakes so far, after eating a cupcake with c calories he must walk at least (2^j)*c miles to maintain his weight.
Given the individual calorie counts for each of the cupcakes, determine the minimum number of miles Marc must walk to maintain his weight. Note that he can eat the cupcakes in any order.
Strategy: Multiply the largest number with smallest power of two. Arrange the array of calories in descending order and multiply each with ascending powers of 2"""
import math
import os
import random
import re
import sys
def marcsCakewalk(calorie):
calorie.sort(reverse=True) # descending order
s=0 # to calculate sum
for i in range(len(calorie)):
s+=(calorie[i]*(2**i)) # multiply with increasing powers of 2
return s
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
calorie = list(map(int, input().rstrip().split()))
result = marcsCakewalk(calorie)
fptr.write(str(result) + '\n')
fptr.close()
| true |
fd7c6633a7d1479b223fa8ce8f9e2cf5a05d326c | Pancc123/python_learning | /base_practice/quit.py | 475 | 4.21875 | 4 | pizza=''
message='\nplease choose a ingredients on pizza:'
message+="\nplease input 'quit' to stop"
while pizza != 'quit':
pizza=input(message)
if pizza != 'quit':
print(pizza)
message='How old are you ?'
age=''
while True:
age=input(message)
if int(age)<3:
print('you can look the movie for free.')
elif int(age)<=12:
print('you need pay 10 dollars for the movie')
else:
print('you need pay 15 dollars for the movie')
if age =='quit':
break
| true |
c74ff911b9ee2da78543d23f131934fcff166f4e | alehpineda/bitesofpy | /Bite_15/enumerate_data.py | 1,061 | 4.1875 | 4 | """
Iterate over the given names and countries lists, printing them
prepending the number of the loop (starting at 1). Here is the
output you need to deliver:
1. Julian Australia
2. Bob Spain
3. PyBites Global
4. Dante Argentina
5. Martin USA
6. Rodolfo Mexico
Notice that the 2nd column should have a fixed width of 11 chars,
so between Julian and Australia there are 5 spaces, between Bob
and Spain, there are 8. This column should also be aligned to
the left.
Ideally you use only one for loop, but that is not a requirement.
Good luck and keep calm and code in Python!
"""
names = "Julian Bob PyBites Dante Martin Rodolfo".split()
countries = "Australia Spain Global Argentina USA Mexico".split()
def enumerate_names_countries():
"""Outputs:
1. Julian Australia
2. Bob Spain
3. PyBites Global
4. Dante Argentina
5. Martin USA
6. Rodolfo Mexico"""
c = 1
for i, j in zip(names, countries):
print("{}. ".format(c) + i + " " * (11 - len(i)) + j)
c += 1
| true |
e9220e9906b453816143716ec56a5f26cd294959 | alehpineda/bitesofpy | /159/calculator.py | 733 | 4.125 | 4 | import operator
CALCULATIONS = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.truediv,
}
def simple_calculator(calculation):
"""Receives 'calculation' and returns the calculated result,
Examples - input -> output:
'2 * 3' -> 6
'2 + 6' -> 8
Support +, -, * and /, use "true" division (so 2/3 is .66
rather than 0)
Make sure you convert both numbers to ints.
If bad data is passed in, raise a ValueError.
"""
try:
num1, sign, num2 = calculation.split()
return CALCULATIONS[sign](int(num1), int(num2))
except (ValueError, KeyError, ZeroDivisionError) as error:
print(error)
raise ValueError
| true |
22ba385cb0df70b44cb22f6fea070d33db4ecb7a | alehpineda/bitesofpy | /Bite_107/list_comprehensions.py | 570 | 4.15625 | 4 | """
Complete the function below that receives a list of numbers and returns
only the even numbers that are > 0 and even (divisible by 2).
The challenge here is to use Python's elegant list comprehension feature
to return this with one line of code (while writing readable code).
"""
def filter_positive_even_numbers(numbers):
"""Receives a list of numbers, and returns a filtered list of only the
numbers that are both positive and even (divisible by 2), try to use a
list comprehension."""
return [i for i in numbers if i % 2 == 0 and i > 0]
| true |
1c0617c520da6181d9379cf8e7ba471b8b8a78c6 | alehpineda/bitesofpy | /119/xmas.py | 913 | 4.21875 | 4 | def generate_xmas_tree(rows=10):
"""Generate a xmas tree of stars (*) for given rows (default 10).
Each row has row_number*2-1 stars, simple example: for rows=3 the
output would be like this (ignore docstring's indentation):
*
***
*****"""
xmas = []
for row in range(1, rows + 1):
space = (rows - row) * " "
xmas.append(space + (row * 2 - 1) * "*")
return "\n".join(xmas)
# Pybites solution
def generate_xmas_tree1(rows=10):
"""Generate a xmas tree of stars (*) for given rows (default 10).
Each row has row_number*2-1 stars, simple example: for rows=3 the
output would be like this (ignore docstring's indentation):
*
***
*****"""
width = rows * 2
output = []
for i in range(1, width + 1, 2):
row = "*" * i
output.append(row.center(width, " "))
return "\n".join(output)
| true |
cd70d79780f6305f1feaa9af76346bf3568d5ef5 | alehpineda/bitesofpy | /127/ordinal.py | 1,286 | 4.53125 | 5 | def get_ordinal_suffix(number):
"""Receives a number int and returns it appended with its ordinal suffix,
so 1 -> 1st, 2 -> 2nd, 4 -> 4th, 11 -> 11th, etc.
Rules:
https://en.wikipedia.org/wiki/Ordinal_indicator#English
- st is used with numbers ending in 1 (e.g. 1st, pronounced first)
- nd is used with numbers ending in 2 (e.g. 92nd, pronounced ninety-second)
- rd is used with numbers ending in 3 (e.g. 33rd, pronounced thirty-third)
- As an exception to the above rules, all the "teen" numbers ending with
11, 12 or 13 use -th (e.g. 11th, pronounced eleventh, 112th,
pronounced one hundred [and] twelfth)
- th is used for all other numbers (e.g. 9th, pronounced ninth).
"""
number = str(number)
# create a dictionary with keys 1,2,3 and values st, nd, rd
f_123 = dict(zip("1 2 3".split(), "st nd rd".split()))
# save the suffix
# use get from dict to check if the number ends with 1,2, or 3 if not
# save 'th'
suffix = f_123.get(number[-1]) or "th"
# teen numbers
# if the number is 10 or more and the second last is 1
if len(number) > 1 and number[-2] == "1":
suffix = "th"
# return f-string with number and suffix
return f"{number}{suffix}"
| true |
07fff703625eb01413ea7445b7be39b9c0590681 | alehpineda/bitesofpy | /Bite_3/wordvalue.py | 2,730 | 4.21875 | 4 | """
Calculate the dictionary word that would have the most value in Scrabble.
There are 3 tasks to complete for this Bite:
- First write a function to read in the dictionary.txt file ( = DICTIONARY
constant), returning a list of words (note that the words are separated
by new lines).
- Second write a function that receives a word and calculates its value.
Use the scores stored in LETTER_SCORES. Letters that are not in
LETTER_SCORES should be omitted (= get a 0 score).
With these two pieces in place.
- Third write a function that takes a list of words and returns the word with the highest value.
Look at the TESTS tab to see what your code needs to pass. Enjoy!
"""
import os
import urllib.request
from tempfile import gettempdir
# PREWORK
TMP = gettempdir()
DICTIONARY = os.path.join(TMP, "dictionary.txt")
urllib.request.urlretrieve("http://bit.ly/2iQ3dlZ", DICTIONARY)
scrabble_scores = [
(1, "E A O I N R T L S U"),
(2, "D G"),
(3, "B C M P"),
(4, "F H V W Y"),
(5, "K"),
(8, "J X"),
(10, "Q Z"),
]
LETTER_SCORES = {
letter: score
for score, letters in scrabble_scores
for letter in letters.split()
}
# start coding
def load_words():
"""load the words dictionary (DICTIONARY constant) into a list and return it"""
words = []
# don't read the whole file into memory when you don't have too
# files are iterable
with open(DICTIONARY) as f:
for line in f:
line = line.strip()
if not line:
continue
words.append(line)
return words
def calc_word_value(word):
"""given a word calculate its value using LETTER_SCORES"""
value = []
for char in word:
for val, lists in scrabble_scores:
if char.lower() in lists.lower().split():
value.append(val)
return sum(value)
def max_word_value(words=None):
"""given a list of words return the word with the maximum word value"""
if words == None:
words = load_words()
value_list = [calc_word_value(word) for word in words]
return words[value_list.index(max(value_list))]
# Pybites solution
# START HERE
def load_words1():
"""load the words dictionary (DICTIONARY constant) into a list and return it"""
with open(DICTIONARY) as f:
return [word.strip() for word in f.read().split()]
def calc_word_value1(word):
"""given a word calculate its value using LETTER_SCORES"""
return sum(LETTER_SCORES.get(char.upper(), 0) for char in word)
def max_word_value1(words=None):
"""given a list of words return the word with the maximum word value"""
if words is None:
words = load_words()
return max(words, key=calc_word_value)
| true |
c1a03320e99ded66b6d47084423527e367ed43c8 | Innanov/PYTHON | /Area_of_rectangle.py | 282 | 4.1875 | 4 | # By INNAN Nouhaila
# Compute the area of a rectangle, given its width and height.
width = 5
height = 9
# Rectangle area formula
area = width * height
print("A rectangle " + str(width) + " inches wide and " + str(height) + " inches high has an area of " + str(area) + " square inches.")
| true |
bf2deeb289ddb3539008fcf4312d09921fc8d477 | Ratna04priya/-Python-worked-problems- | /prob_-_soln/age_finder.py | 359 | 4.21875 | 4 | # Gives the age
from datetime import date
def calculate_age(dtob):
today = date.today()
return today.year - dtob.year - ((today.month, today.day) < (dtob.month, dtob.day))
a= int(input("Enter the year of birth : "))
b= int(input("Enter the month of birth : "))
c= int(input("Enter the date of birth : "))
print(calculate_age(date(a,b,c)))
| true |
b8cd317c831848b1d33ba51ad96ec0acc80c1272 | poly451/Tutorials | /Instance vs Class Variables/dunder classes (iter, next).py | 1,819 | 4.3125 | 4 | # -------------------------------------------------
# clas Car
# -------------------------------------------------
class Car:
def __init__(self, name, tires, seats):
self.name = name
self.tires = tires
self.seats = seats
def print_car(self):
s = "name: {}, tires: {}, seats: {}".format(self.name, self.tires, self.seats)
print(s)
# -------------------------------------------------
# clas Cars
# -------------------------------------------------
class Cars:
def __init__(self):
self.cars = []
self.current = 0
def add_car(self, name, tires, seats):
new_car = Car(name, tires, seats)
self.cars.append(new_car)
def print_car(self):
print("Number of cars:", len(self.cars))
print("-" * 30)
for elem in self.cars:
elem.print_car()
def __len__(self):
return len(self.cars)
def __repr__(self):
s = ""
for elem in self.cars:
s += "{}\n".format(elem.print_string())
return(s.strip())
def __iter__(self):
return self
def __next__(self):
print("current:", self.current)
try:
item = self.cars[self.current]
except IndexError:
self.current = 0
raise StopIteration()
self.current += 1
return item
# *************************************************
# mycars = Cars()
# mycars.add_car(name="ford", tires=4, seats=4)
# mycars.add_car(name="parsche", tires=4, seats=4)
# mycars.print_car()
mycars = Cars()
mycars.add_car(name="ford", tires=4, seats=4)
mycars.add_car(name="parsche", tires=4, seats=2)
print("You have {} cars.".format(len(mycars)))
print("=" * 40)
for a_car in mycars:
a_car.print_car()
| true |
a9036924ef986718c083163b1dff30880ad8d108 | orkunkarag/py-oop-tutorial | /oop-py-code/oop-python-main.py | 696 | 4.15625 | 4 | # Object Oriented Programming
'''
def hello():
print("hello")
x = 1
print(type(hello))
'''
'''
string = "hello"
print(string.upper())
'''
#creating class
class Dog:
#special method init
def __init__(self, name, age):
self.name = name #Attribute of the class Dog - unique for every object
self.age = age
def get_name(self):
return self.name
def get_age(self):
return self.age
def set_age(self, age):
self.age = age
def add_one(self, x):
return x + 1
def bark(self):
print("bark")
d = Dog("Tim", 34)
print(d.get_name())
d.set_age(22)
print(d.get_age())
d2 = Dog("Bill", 12)
print(d2.get_name())
print(d2.get_age())
d.bark()
print(d.add_one(5))
print(type(d))
| true |
f7729652596f8a71a8b172e337a95a10b18435ef | alluong/code | /python/prime.py | 510 | 4.28125 | 4 | def is_prime(num):
if num > 1:
if len(check_prime_list) == 0:
return True
return False
while 1:
num = int(input("please enter a number: "))
# check_prime_list is empty if num is a prime number
# otherwise, check_prime_list contains a list of divisors divisible by num
check_prime_list = [x for x in range(2, num) if num % x == 0]
if is_prime(num):
prime = ""
else:
prime = "not "
print(str(num) + " is " + prime + "a prime number")
| true |
d06da6cf62aa2ac6cc4d915a83ce74e7ac03cfc0 | balbachl/CIT228-1 | /Chapter10/addition.py | 402 | 4.125 | 4 | def addition(n,d):
return n+d
quit=""
while quit != "q":
try:
n = int(input("Type an integer"))
d = int(input("Type another integer"))
except ValueError:
print("You entered a non-integer")
else:
print(n, "+", d, "=", addition(n,d))
finally:
print("Thank you for the math problems!")
quit=input("Would you like to continue, q to quit?")
| true |
9c99d10cdd77bb0e433ac2e69bd0b353c469d1b3 | balbachl/CIT228-1 | /Chapter7/multiplesOfTen.py | 235 | 4.28125 | 4 | number = int(input("Please enter a number and I will tell you if it is a multiple of ten"))
if number%10==0:
print("The number ", number, " is a multiple of ten")
else:
print("The number ", number, " is not a multiple of ten") | true |
4bb93fb5614fc29bc99632a3103b870995c98b4f | aavinashjha/IamLearning | /Algorithms/Sorting/mergeSort.py | 2,049 | 4.125 | 4 | """
- Divide array into half
- Merge in sorted order
- Single element is always sorted: Base Case
Time Complexity:
- MergeSort uses at most NlgN compares and 6NlgN array accesses to sort any array of size N
- C(N) <= C(ceil(N/2)) + C(ceil(N/2)) + N for N>1 with C(1) = 0
- A(N) <= A(ceil(N/2)) + A(ceil(N/2)) + 6N for N>1 with A(1) = 0
Improvements:
- Use a cutoff value below that use insertion sort (avoid recursive calls)
- While merging do nothing if The biggest item in first half is less than or equal to smallest item in second half
Already sorted array:
- Comapirisons made are: 1/2 nlogn and optimized version a[mid] <= a[mid+1] makes n-1 comparisons
"""
def merge(a, aux, lo, mid, hi):
# a[lo..mid]: Already sorted
# a[mid+1..high]: Already sorted
# Maintains original copy, a is updated
for k in range(lo, hi+1):
aux[k] = a[k]
#if aux[mid] <= aux[mid+1]: return
i, j = lo, mid+1
for k in range(lo, hi+1):
if i > mid: # All elements of left half are exhausted
a[k] = aux[j]
j += 1
elif j > hi:
a[k] = aux[i]
i += 1
elif aux[i] <= aux[j]:
a[k] = aux[i]
i += 1
else: # aux[j] < aux[i]
a[k] = aux[j]
j += 1
def sort(array, aux, lo, hi):
if hi <= lo: return
mid = lo + (hi-lo)//2
sort(array, aux, lo, mid)
sort(array, aux, mid+1, hi)
# The biggest item in first half is less than or equal to smallest item in second half
merge(array, aux, lo, mid, hi)
def mergeSort(array):
aux = [-1] * len(array)
sort(array, aux, 0, len(array)-1)
def bottomUpMergeSort(array):
N = len(array)
aux = [-1] * N
size = 1
while size < N:
for lo in range(0, N-size+1, size):
mid, hi = lo+size, min(lo+2*size, N-1)
merge(array, aux, lo, mid, hi)
size += size
array = [3, 4, 1, 2, 5]
mergeSort(array)
print(array)
array = [3, 4, 1, 2, 5]
bottomUpMergeSort(array)
print(array)
| true |
4ea3a2bc913ad93cb3dad696b9cc9b138ac04309 | aavinashjha/IamLearning | /OOPS/Patterns/factory.py | 2,921 | 4.8125 | 5 | """
Problem:
- Who should be responsible for creating objects when there are special
considerations such as complex creation logic, a desire to separate
the creation responsibilites for better cohesion?
When you need a factory pattern?
- When you don't know ahead of time what class object you need
- When all the potential classes are in same subclass hierarchy
- To centralize class selection code
- When you don't want the user to have to know every subclass
- To encapsulate object creation
Solution:
- Create a Pure Fabrication object called factory that handles the creation
NOTES:
- When a method returns one of several possible classes that share a common super class
> Create a new enemy in game
> Random number generator picks a number assigned to a specific enemy
> The factory returns the enemy associated with that number
> Class is chosen at runtime
Client -> EnemyShipFactory -> EnemyShip (Implemented by UFOEnemyShip, RocketEnemyShip)\
The Factory Pattern allows you to create objects without specifying the exact class of object
that will be created.
"""
from abc import ABC, abstractmethod
class EnemyShip(ABC):
def getName(self):
return self.name
def setName(self, name):
self.name = name
def getDamage(self):
return self.damage
def setDamage(self, damage):
self.damage = damage
def followHeroShip(self):
print("{} is following the hero".format(self.getName()))
def displayEnemyShip(self):
print("{} is on the screen".format(self.getName()))
def enemyShipShoots(self):
print("{} attacks and does {}".format(self.getName(), self.getDamage()))
class UFOEnemyShip(EnemyShip):
def __init__(self):
self.setName("UFO Enemy Ship")
self.setDamage(20)
class RocketEnemyShip(EnemyShip):
def __init__(self):
self.setName("Rocket Enemy Ship")
self.setDamage(10)
class BigEnemyShip(EnemyShip):
def __init__(self):
self.setName("Big Enemy Ship")
self.setDamage(40)
class EnemyShipFactory:
def makeEnemyShip(self, shipType):
enemy = None
if shipType == "U": enemy = UFOEnemyShip()
elif shipType == "R": enemy = RocketEnemyShip()
elif shipType == "B": enemy = BigEnemyShip()
return enemy
def doStuffEnemy(enemyShip):
enemyShip.displayEnemyShip()
enemyShip.followHeroShip()
enemyShip.enemyShipShoots()
shipFactory = EnemyShipFactory()
while True:
shipType = input("Which ship you want: U/R/B")
enemy = shipFactory.makeEnemyShip(shipType)
doStuffEnemy(enemy)
# This bunch of if else is bad, we have a better way by using factory pattern
"""
while True:
shipType = input("Which ship you want: U/R")
enemy = None
if shipType == "U":
enemy = UFOEnemyShip()
if shipType == "R":
enemy = RocketEnemyShip()
doStuffEnemy(enemy)
"""
| true |
bbf313aac3b7fb8130c4a3f4503011d5abf59a69 | Mohitgola0076/Day6-Internity | /Creating_Arrays.py | 1,549 | 4.15625 | 4 | '''
A new ndarray object can be constructed by any of the following array creation routines or using a low-level ndarray constructor.
'''
numpy.empty
# It creates an uninitialized array of specified shape and dtype. It uses the following constructor −
numpy.empty(shape, dtype = float, order = 'C')
# Example 1
# The following code shows an example of an empty array.
import numpy as np
x = np.empty([3,2], dtype = int)
print x
# The output is as follows −
[[22649312 1701344351]
[1818321759 1885959276]
[16779776 156368896]]
#############################################
numpy.zeros
# Returns a new array of specified size, filled with zeros.
numpy.zeros(shape, dtype = float, order = 'C')
# Example 2
# array of five zeros. Default dtype is float
import numpy as np
x = np.zeros(5)
print x
# The output is as follows −
[ 0. 0. 0. 0. 0.]
# Example 3
import numpy as np
x = np.zeros((5,), dtype = np.int)
print x
# Now, the output would be as follows −
[0 0 0 0 0]
###############################
numpy.ones
# Returns a new array of specified size and type, filled with ones.
numpy.ones(shape, dtype = None, order = 'C')
# Example 4
# array of five ones. Default dtype is float
import numpy as np
x = np.ones(5)
print x
The output is as follows −
[ 1. 1. 1. 1. 1.]
# Example 2
import numpy as np
x = np.ones([2,2], dtype = int)
print x
# Now, the output would be as follows −
[[1 1]
[1 1]]
| true |
fbc8821835083eea2a2002bb3970d740e80cf48b | yavani/pycourse | /merge.py | 675 | 4.21875 | 4 | """
merge module
"""
def merge ( list1, list2) :
# set everything to zero.
i = j = k = 0
list3 = [ ]
'''
The below method merges two lists in sorted order, returns sorted new list.
Prerequisite: all argument lists should eb sorted.
'''
while True:
if len ( list1 ) == i :
list3.extend ( list2[ j: ] )
break
elif len(list2) == j :
list3.extend(list1[i:])
break
if list1[i] < list2[j] :
list3.append(list1[i])
i += 1
k += 1
else:
list3.append(list2[j])
j += 1
k += 1
return list3
| true |
9fa852a2e8d7479a8e48fe829ccaae77c646b47c | AhmetGurdal/Guess-Game | /Guess-Game.py | 1,914 | 4.125 | 4 | #-*- coding: cp1254 -*-
import random
import time
print "Name?"
ad = raw_input(":")
print "OK, ",ad,"! let's play a game I think a number that between 1 and 1000."
while True:
print "If u can ,guess"
num = random.randrange(1,1000)
ts = 1
while True:
ta = input(":")
if num > ta:
print "up"
ts = ts + 1
elif num < ta:
print "down"
ts = ts + 1
elif num == ta:
print "True Guess"
ts = ts + 1
if ts > 10 and ts <= 15:
print"U guessed true in" ts,"guesses. Not Bad."
elif ts > 15 and ts <= 20:
print"U guess true in" ts,"guesses. Really Bad Result."
elif ts > 20:
print"U guess true in" ts,"guesses. Too Bad for Humanity."
else:
print"U guess true in" ts,"guesses. Awesome."
break
print "\nIt's my turn. Now U think a numbet between 1-1000 and i will guess.(press Enter)\n"
raw_input("")
print "\nIf I have to increase my guess, enter 'i' (press Enter)\n"
raw_input()
print "\nIf I've to decrease my guess, enter'd' If my guess is True, enter 't' (press Enter)\n"
raw_input()
print "Think Now!"
time.sleep(2)
a = 1
b = 1000
ts2 = 1
while True:
num2 = random.randrange(a,b)
while True:
print num2
th = raw_input(":")
if th == "i":
a = num2 + 1
ts2 = ts2 + 1
break
elif th == "d":
b = num2
ts2 = ts2 + 1
break
elif th == "t":
print "I guess true in "ts2," guesses."
if ts2 > ts:
print "U beat me. Well Done!"
elif ts2 < ts:
print "I bear u. U loser"
elif ts2 == ts:
print "It's tie."
break
else:
print "\nIf I have to increase my guess, enter 'i' If I've to decrease my guess, enter'd'\n"
print "\nIf my guess is True, enter 't'\n"
print "If u wanna play again, enter 'r'"
yeni = raw_input(":")
if yeni != "r":
print "\nNice game. Bye!!\n"
time.sleep(3)
quit()
| true |
591d3941a9c5218323cb600c46d81bfce0eb4666 | yarnpuppy/Python-the-Hard-Way | /ex6.py | 922 | 4.15625 | 4 | # d is some sort of variable. % allows you define the value
x = "There are %d types of people." % 10
# defines binary as a string binary
binary = "binary"
# defines do_not as the string "don't"
do_not = "don't"
# Compound variable description for s and s. %(s,s), allows for consecutive variable substitution.
y = "Those who know %s and those who %s." % (binary, do_not)
print x
print y
# r is defined as x, which should print I said: 'There are 10 types of people.'.
print "I said: %r." % x
# s is defined as y, which should print I also said: 'Those who know binary and those who don't.'.
print "I also said: '%s'. " % y
hilarious = False
joke_evaluation = "Isn't that joke so funny?! %r"
print joke_evaluation % hilarious
w = "This is the left side of..."
e = "a string with a right side."
#prints This is the left side of...a string with a right side.
print w + e
m= "Marja is very "
a = "very cool"
print m + a | true |
99be2dd68589f521adffd6594f42cc1b0c95b395 | e-walther-rudman/ProjectEulerSolutions | /PE_problem4_Maxime_Emily.py | 647 | 4.125 | 4 | #A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
#
#Find the largest palindrome made from the product of two 3-digit numbers.
LargestPalindrome = 0
for FirstNumber in range(100,1000):
for SecondNumber in range(FirstNumber, 1000):
NumberAsList = list(str(FirstNumber*SecondNumber))
NumberAsListOriginal = NumberAsList.copy()
NumberAsList.reverse()
if NumberAsListOriginal == NumberAsList and FirstNumber*SecondNumber >LargestPalindrome:
LargestPalindrome = FirstNumber*SecondNumber
print(LargestPalindrome)
| true |
a7e42c9f2b2ad26b47ba97061729c86bc3b14c87 | MarHakopian/Intro-to-Python-HTI-3-Group-2-Marine-Hakobyan | /Homework_3/factorial.py | 222 | 4.15625 | 4 | def factorial_f(n):
factorial_n = 1
for i in range(1, int(n) + 1):
factorial_n = factorial_n * i
return f"The factorial of {n} is {factorial_n}!"
n = input("Enter the number: ")
print(factorial_f(n))
| true |
f50ee5231eaa848d646ffe5aa71ad76a13498c7c | HaykBarca/Python | /tuples.py | 457 | 4.4375 | 4 | # A tuple is an immutable container that stores objects in a specific order
my_tuple = tuple()
print(my_tuple)
my_new_tuple = ()
print(my_new_tuple)
# You should add items when you creating tuple, you can't change, add, remove items from tuple
tuple_items = ("Apple", "Orange")
print(tuple_items)
print(tuple_items[1])
new_tuple_items = tuple_items[0:1] # Slice tuple
print(new_tuple_items)
print("Orange" in tuple_items) # Check if Orange exists in tuple | true |
f1864d27157164507fde1e72b21b10d7a681701f | ashish-netizen/AlgorithmsAndDataStructure | /Python/DataStructure/Stack/stack.py | 505 | 4.40625 | 4 | #here we are using demonstrating stack in python
#Initally we take an empty list a then we use append function to push element in the list.
#printed [1,2,3]
#after that elements poped out in Last In First Out Order
a = []
a.append(1)
a.append(2)
a.append(3)
print('Initial stack')
print(a)
print('\nElements popped out from stack:')
print(a.pop())
print(a.pop())
print(a.pop())
print("Stack printed in LIFO Order")
print('\nStack after all elements are popped out:')
print(a)
| true |
98ac1ee97fbfb2e0b931aee26ba575164ff4d002 | crawler4o/Learning_Python | /Hang_Man/hangman.py | 2,483 | 4.375 | 4 | ### Hangman
### Exercise 32 (and Solution)
###
### This exercise is Part 3 of 3 of the Hangman exercise series. The other exercises are: Part 1 and Part 2.
###
### You can start your Python journey anywhere, but to finish this exercise you will have to have finished Parts 1 and 2 or use the solutions (Part 1 and Part 2).
###
### In this exercise, we will finish building Hangman. In the game of Hangman, the player only has 6 incorrect guesses (head, body, 2 legs, and 2 arms) before they lose the game.
###
### In Part 1, we loaded a random word list and picked a word from it. In Part 2, we wrote the logic for guessing the letter and displaying that information to the user. In this exercise, we have to put it all together and add logic for handling guesses.
###
### Copy your code from Parts 1 and 2 into a new file as a starting point. Now add the following features:
###
### Only let the user guess 6 times, and tell the user how many guesses they have left.
### Keep track of the letters the user guessed. If the user guesses a letter they already guessed, don’t penalize them - let them guess again.
###
### Optional additions:
###
### When the player wins or loses, let them start a new game.
### Rather than telling the user "You have 4 incorrect guesses left", display some picture art for the Hangman. This is challenging - do the other parts of the exercise first!
###
### Your solution will be a lot cleaner if you make use of functions to help you!
import pick_word
import guess_letters
def game_play():
print('\n \n__________________________________ \n Hello to the new game ! \n')
word = pick_word.pick_word()
print(word) # to see the word for testing
attempts = 0 # means the wrong guesses
guesses = 0
guessed_letters = set()
guessed_word = '-'*len(word)
games = 1
print(guessed_word)
while not (guess_letters.game_over(attempts) or guess_letters.game_win(word, guessed_word)): # play while not lose or win
[guessed_word, guessed_letters, attempts] = guess_letters.guess(word, guessed_word, guessed_letters, attempts)
guesses +=1
print(guessed_word)
if guess_letters.new_game(): # if lose or win, offer a new game.
games +=1
game_play()
else:
print('It was a pleasure to play with you! You played %s games' % games) # Say bye if no new game is desired
quit()
if __name__ == '__main__':
games = 1
game_play()
| true |
528baefe3109452a19479d82a649018bbb35aa3b | terrylovesbird/lecture-w2-d2-OOP-CSV | /classes/animals/dog.py | 676 | 4.34375 | 4 | class Dog:
species = "Canis Lupus Familiaris" # example of a *class attribute*
sound = "Woof"
legs = 4
tail = 1
mammal = True
def __init__(self, name, breed):
self.name = name # example of an *instance attribute*
self.breed = breed
def __str__(self):
return f"I am a dog named {self.name} and my breed is {self.breed}. I have {self.legs} legs and I say {self.sound}!"
def __eq__(self, other_dog):
return self.breed == other_dog.breed
def __add__(self, other_dog):
return Dog(self.name + other_dog.name, self.breed)
def speak(self): # example of an *instance method*
print(self.sound) | true |
4b3d9a9351988f4e9038ed24535be5473fa8b048 | jasminegrewal/algos | /algorithms/bubbleSort.py | 1,050 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 28 11:14:37 2017
@author: jasmine
"""
def bubbleSort(arr):
for i in range(len(arr)-1):
''' i will go from 0 to second last element
last element will be compared at second last position'''
for j in range((len(arr)-1)-i):
'''j will go from 0 till n-i^th position as largest element will keep taking their
right position and unsorted array will keep decreasing to left
i.e largest elements will take their position first '''
if(arr[j]>arr[j+1]):
arr[j],arr[j+1]=arr[j+1],arr[j]
return arr
def optimizedSort(arr):
isSorted=False
lastUnsorted=len(arr)-1
while(not isSorted):
isSorted=True
for i in range(lastUnsorted):
if(arr[i]>arr[i+1]):
arr[i],arr[i+1]=arr[i+1],arr[i]
isSorted=False
lastUnsorted-=1
return arr
numbers=[6,4,7,3,9,1,2,8,0]
#print(bubbleSort(numbers))
print(optimizedSort(numbers)) | true |
b2578f87fc2bd326e5f588888a11e7a98ab670c4 | Luxura/Learning | /Collatz square.py | 328 | 4.21875 | 4 | # this will try to use the collatz squar
# if number even return number // 2, sinon number * 3 +1
# projet en cours
def collatz(number):
if number % 2 == 0:
b = number // 2
print(b)
else:
b = number * 3 + 1
print(b)
b = (int(input("Taper un chiffre: ")))
while b != 1:
collatz(b)
| true |
aed710442c5cf49a03b9c8e2d21eec260d75ef75 | vvek475/Competetive_Programming | /Competitive/comp_8/Q2_LION_squad.py | 687 | 4.28125 | 4 |
def reverse_num(inp):
#this line converts number to positive if negative
num=abs(inp)
strn=str(num)
nums=int(strn[::-1])
#these above lines converts num to string and is reversed
if inp>0:
print(nums)
else:
#if input was negative this converts to negative again after above process
nums*=-1
print(nums)
def Input_validator():
while True:
num=input('Enter string to be reversed: \n')
if num.isdigit() or (num[0]=='-' and num[1:].isdigit()):
reverse_num(int(num))
break
print('Please enter a valid number \n')
if __name__=='__main__':
Input_validator()
| true |
e79b3bee9714ca2a548311b7e78fd203503d70e1 | ShifaZaman/IntroToPython | /Pyramid.py | 215 | 4.34375 | 4 | print("Input a number to make a pyramid!")
number=input()
for a in range(2,13): #I started at 2 because when you start at 1, it repeats. it'll be like
#3
#3
#33
#333
print(number*a)
'''c="5"
print(3*c)''' | true |
fc0c9b2102f094a2f6b79dd97e276ed6eb0f0679 | ShifaZaman/IntroToPython | /24hourto12hour.py | 1,283 | 4.5 | 4 | print("Type hours in 24-hour mode")
hours=int(input())
hoursnew=hours%12 #% - gives you the remainder. Modulus of something that is smaller will be itself e.g 11 is smaller than 12 so it will be 11
if((hours>24)|(hours<1)): # If comparing two things, put brackets around both so it does bedmas and evaluates brackets first. | = OR operator, & = AND Operator.
print("This time does not exist")
elif(hours==24): # Elif runs if if statement is false
print("Your time in 12-hour mode is:12am")
#these spaces dont have to be here
elif(hours>12):
print("Your time in 12-hour mode is:" ,hoursnew, "pm")
elif(hours==12):
print("Your time in 12-hour mode is: 12pm")
else:
print("Your time in 12-hour mode is:" ,hoursnew, "am") #else comes when none of the others apply
#You can comment out several lines of code using ''' to have your code saved for later but not run by python
'''example program '''
'''if((hours>24)| (hours<1)):
print("This does not exist")
elif((hours>12) & (hours<24)):
print("Your time in 12-hour mode is:" ,hoursnew, "pm")
elif(hours==24):
print("Your time in 12-hour mode is:12am")
elif(hours==12):
print("Your time in 12-hour mode is: 12pm")
else:
print("Your time in 12-hour mode is:" ,hoursnew, "am")'''
#this is the less complex one
| true |
bb66288e230ed522491b095ba3e344221bd27ba1 | CodeSeven-7/password_generator | /password_generator.py | 670 | 4.25 | 4 | # password_generator.py
import random
import string
print('Welcome to PASSWORD GENERATOR!')
# input the length of password
length = int(input('Enter the length of the password you would like to create: '))
# define data
num = string.digits
symbols = string.punctuation
lower = string.ascii_lowercase
upper = string.ascii_uppercase
# sum the data
all = num + symbols + lower + upper
# use random
temp = random.sample(all,length)
# create the password
password = "".join(temp)
print('Your generated password contains lowercase and uppercase letters, numbers and symbols in a random arrangement:')
print(password)
| true |
df43194f5d82d5808925736e24351938641ac355 | Juanjo-M/Primero | /Lab31112.py | 360 | 4.125 | 4 | year = int(input("Enter a year: "))
if year >= 1582:
if year % 4 != 0:
print("This is a common year.")
elif year % 100 != 0:
print("This is a leap year.")
elif year % 400 != 0:
print("This is a common year.")
else:
print("This is a leap year.")
else:
print("Not within the Gregorian calendar period") | true |
473e2eff54f1ee5faa5151c8968fab0f705b73c1 | unclebae/python_tutorials | /DataStructures/DictionariesTest.py | 2,154 | 4.34375 | 4 | # Dictionaries are sometimes found in other languages as "associative memories" or "associative arrays"
# Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys,
# which can be any immutable type;
# strings and numbers can always be keys
tel = {'jack':4098, 'sape':4139}
tel['guido'] = 4127
print(tel)
print(tel['jack'])
del tel ['sape']
tel['irv'] = 4127
print(tel)
print(list(tel.keys()))
print(tel.values())
print(list(tel.values()))
print(sorted(tel.keys()))
print('guido' in tel)
print('sape' in tel)
# The dict() constructor builds dictionaries directly from sequences of key-value pairs.
a = dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
print(a)
print({x: x**2 for x in (2, 5, 6)})
b = dict(shape=4139, guido=4127, jack=4098)
print(b)
# When looping throught dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.
knights = {'gallahad':'the_pure', 'robin':'the brave'}
for k, v in knights.items():
print(k, v)
# When looping throught a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
# To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
questiongs = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questiongs, answers) :
print('What is your {0}? It is {1}.'.format(q, a))
# To loop over a sequence in reverse, first sepcify the sequence in a forward direction and then call the reversed() function/
for i in reversed(range(1, 10, 2)):
print(i)
# The loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.
basket = ['apple', 'oragne', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)):
print(f)
import math
raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8]
filtered_data = []
for value in raw_data:
if not math.isnan(value):
filtered_data.append(value)
| true |
4598d2e50265da88fab8cfe116c5581a57816524 | nshagam/Python_Practice | /Divisors.py | 463 | 4.28125 | 4 | # Create a program that asks the user for a number and then prints out a list of all
# the divisors of that number. (If you don’t know what a divisor is, it is a number that
# divides evenly into another number. For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
num = int(input("Enter a number: "))
numrange = range(1, num + 1)
divisors = []
for i in numrange:
if num % i == 0:
divisors.append(i)
print(divisors) | true |
ed105b7cf0dbaee6468a2c8a298708a344894b08 | shanekelly/SoftDesSp15 | /toolbox/word_frequency_analysis/frequency.py | 1,568 | 4.5625 | 5 | """ Analyzes the word frequencies in a book downloaded from
Project Gutenberg """
import string
def get_word_list(file_name):
""" Reads the specified project Gutenberg book. Header comments,
punctuation, and whitespace are stripped away. The function
returns a list of the words used in the book as a list.
All words are converted to lower case.
"""
f = open(file_name,'r')
lines = f.readlines()
curr_line = 0
while lines[curr_line].find('START OF THIS PROJECT GUTENBERG EBOOK') == -1:
curr_line += 1
lines = lines[curr_line+1:]
text = ''.join(lines)
text = text.replace('\n', ' ')
words = text.split()
for x in xrange(len(words)):
words[x] = words[x].lower()
return words
def get_top_n_words(word_list, n):
""" Takes a list of words as input and returns a list of the n most frequently
occurring words ordered from most to least frequently occurring.
word_list: a list of words (assumed to all be in lower case with no
punctuation
n: the number of words to return
returns: a list of n most frequently occurring words ordered from most
frequently to least frequentlyoccurring
"""
#Create a dictionary in the format 'word':'number of times word appears'
word_counts = dict()
for word in word_list:
if word not in word_counts:
word_counts[word] = 1
else:
word_counts[word] += 1
#Sort the dictionary by number of times word appears
ordered_by_frequency = sorted(word_counts, key=word_counts.get, reverse=True)
return ordered_by_frequency[:n]
print get_top_n_words(get_word_list('MobyDick.txt'), 100) | true |
ddc7d4172e1200bef9ffa01f9b5682eab34e8be1 | bearddan2000/python-cli-pydoc-ugly-num-functional-prog | /bin/main.py | 1,323 | 4.1875 | 4 | """
Given a number find the next number
that is divides by 2, 3, or 5.
"""
def max_divide(a, b):
"""
This function divides a by greatest divisible power of b
:param a: const number 2, 3, 5
:param b: current number iteration
:return: max number 2, 3, 5
"""
if a % b != 0:
return a;
c = a/b;
return max_divide(c, b);
def is_ugly(n, args, no):
"""
Function to check if a number is ugly or not
:param n: index of const list
:param args: const list of 2,3,5
:param no: number to test
:return: is number tested ugly
"""
if n >= len(args):
return no == 1
c = max_divide(no, args[n]);
return is_ugly(n+1, args, c);
def find_ugly(n, i, count, args):
"""
Recursively iterate numbers to find first
ugly number.
:param n: number to test
:param i: index of iteration
:param count: running index of recurcion
:param args: const list of 2,3,5
:return: first ugly number found
"""
if (n < count):
return i-1
if is_ugly(0, args, i):
return find_ugly(n, i+1, count+1, args);
else:
return find_ugly(n, i+1, count, args)
def main():
i = 10
args = [2,3,5]
print( "[INPUT] %d" % i)
output = find_ugly(i, 1, 1, args)
print( "[OUTPUT] %d" % output)
main()
| true |
aa124bfe70359c8c48a3e43d12949bc2ec18c8d0 | Sarah1108/HW070172 | /hw_5/ch_6_3.py | 475 | 4.21875 | 4 | #exercise 3
#
import math
def sphereArea(radius):
area = 4* math.pi * radius**2
return area
def sphereVolume(radius):
volume = 4/3 * math.pi* radius**3
return volume
def main():
print("This programm calculates the Volume and surface area of a sphere.")
print()
radius = int(input("Enter the radius of the sphere: "))
print("The Volume of the sphere is", sphereVolume(radius) , "and the surface area is", sphereArea(radius))
main() | true |
a56255215d64a8f5e8481ec0ab04c7132510bf0c | AayushmanJung/pythonProjectlab1 | /lab1/lab6.py | 371 | 4.34375 | 4 | '''
Solve each of the problem using Python Scripts. Make sure you use appropriate variable names and comments. When
there is a final answer have Python print it to the screen.
A person's body mass index (BMI) is defined as:
BMI = mass in kg / (height in m)**2
'''
mass= int(input('Enter the mass'))
height= int(input('Enter the height'))
bmi = mass/height**2
print(bmi)
| true |
dfcf70c0ecbb6bc19cec52deee8c5483ecce962f | divyatejakotteti/100DaysOfCode | /Day 62/Collections.deque().py | 753 | 4.125 | 4 | '''
Task
Perform append, pop, popleft and appendleft methods on an empty deque
.
Input Format
The first line contains an integer
, the number of operations.
The next
lines contains the space separated names of methods and their values.
Constraints
Output Format
Print the space separated elements of deque
.
Sample Input
6
append 1
append 2
append 3
appendleft 4
pop
popleft
Sample Output
1 2
'''
from collections import deque
d = deque()
for i in range(int(input())):
s = input().split()
if s[0] == 'append':
d.append(s[1])
elif s[0] == 'appendleft':
d.appendleft(s[1])
elif s[0] == 'pop':
d.pop()
else:
d.popleft()
print (" ".join(d)) | true |
edc95514a21b81e5ed7c36399fb35a1b5ba666a4 | divyatejakotteti/100DaysOfCode | /Day 23/SherlockAndAnagrams.py | 1,512 | 4.21875 | 4 | '''
Two strings are anagrams of each other if the letters of one string can be rearranged to form the other string. Given a string, find the number of pairs of substrings of the string that are anagrams of each other.
For example s= mom, the list of all anagrammatic pairs is [m,m],[mo,om]at positions [[0],[2]],[[0,1],[1,2]]respectively.
Function Description
Complete the function sherlockAndAnagrams in the editor below. It must return an integer that represents the number of anagrammatic pairs of substrings in s.
sherlockAndAnagrams has the following parameter(s):
s: a string .
Input Format
The first line contains an integer q, the number of queries.
Each of the next q lines contains a string s to analyze.
Output Format
For each query, return the number of unordered anagrammatic pairs.
Sample Input
2
abba
abcd
Sample Output
4
0
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the sherlockAndAnagrams function below.
def sherlockAndAnagrams(s):
l=0
for i in range(1,len(s)):
d={}
for j in range(len(s)-i+1):
string="".join(sorted(s[j:j+i]))
if string not in d:
d[string]=1
else:
d[string]+=1
l+=d[string]-1
return l
if __name__ == '__main__':
q = int(input())
for q_itr in range(q):
s = input()
result = sherlockAndAnagrams(s)
| true |
d0dab6a753a2682e9a5f4a898ca72cef7908d9b5 | divyatejakotteti/100DaysOfCode | /Day 38/FairRations.py | 2,329 | 4.15625 | 4 | '''
You are the benevolent ruler of Rankhacker Castle, and today you're distributing bread. Your subjects are in a line, and some of them already have some loaves. Times are hard and your castle's food stocks are dwindling, so you must distribute as few loaves as possible according to the following rules:
Every time you give a loaf of bread to some person
, you must also give a loaf of bread to the person immediately in front of or behind them in the line (i.e., persons or
).
After all the bread is distributed, each person must have an even number of loaves.
Given the number of loaves already held by each citizen, find and print the minimum number of loaves you must distribute to satisfy the two rules above. If this is not possible, print NO.
For example, the people in line have loaves
. We can first give a loaf to and so . Next we give a loaf to and and have which satisfies our conditions. We had to distribute
loaves.
Function Description
Complete the fairRations function in the editor below. It should return an integer that represents the minimum number of loaves required.
fairRations has the following parameter(s):
B: an array of integers that represent the number of loaves each persons starts with .
Input Format
The first line contains an integer
, the number of subjects in the bread line.
The second line contains
space-separated integers.
Output Format
Print a single integer taht denotes the minimum number of loaves that must be distributed so that every person has an even number of loaves. If it's not possible to do this, print NO.
Sample Input 0
5
2 3 4 5 6
Sample Output 0
4
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the fairRations function below.
def fairRations(B):
loaves=0
for i in range(N-1):
if(B[i]%2==0):
continue
B[i]+=1
B[i+1]+=1
loaves+=2
if(B[-1]%2==1):
return("NO")
else:
return(loaves)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
N = int(input())
B = list(map(int, input().rstrip().split()))
result = fairRations(B)
fptr.write(str(result) + '\n')
fptr.close()
| true |
dc1b524bca8b58ea8c13d461eda010e45d759ba4 | divyatejakotteti/100DaysOfCode | /Day 74/CheckStrictSuperset.py | 1,057 | 4.15625 | 4 | '''
You are given a set and other sets.
Your job is to find whether set is a strict superset of each of the
sets.
Print True, if
is a strict superset of each of the
sets. Otherwise, print False.
A strict superset has at least one element that does not exist in its subset.
Example
Set
is a strict superset of set.
Set is not a strict superset of set.
Set is not a strict superset of set
.
Input Format
The first line contains the space separated elements of set
.
The second line contains integer , the number of other sets.
The next
lines contains the space separated elements of the other sets.
Constraints
Output Format
Print True if set
is a strict superset of all other
sets. Otherwise, print False.
Sample Input 0
1 2 3 4 5 6 7 8 9 10 11 12 23 45 84 78
2
1 2 3 4 5
100 11 12
Sample Output 0
False
'''
A = set(input().split())
n = int(input())
c = True
for i in range(n):
s = set(input().split())
if (s&A != s) or (s == A):
c = False
break
print(c) | true |
2f8d24b3f1bea47e316b56a6484a82888b9c80ab | divyatejakotteti/100DaysOfCode | /Day 60/WordOrder.py | 1,079 | 4.125 | 4 | '''
You are given
words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification.
Note: Each input line ends with a "\n" character.
Constraints:
The sum of the lengths of all the words do not exceed
All the words are composed of lowercase English letters only.
Input Format
The first line contains the integer,
.
The next
lines each contain a word.
Output Format
Output
lines.
On the first line, output the number of distinct words from the input.
On the second line, output the number of occurrences for each distinct word according to their appearance in the input.
Sample Input
4
bcdef
abcdefg
bcde
bcdef
Sample Output
3
2 1 1
'''
import collections
N = int(input())
d = collections.OrderedDict()
for i in range(N):
word = input()
if word in d:
d[word] +=1
else:
d[word] = 1
print(len(d))
for k,v in d.items():
print(v,end=' ') | true |
f574490c0c3e9924c031d262b6d43440d5ad5552 | divyatejakotteti/100DaysOfCode | /Day 25/SequenceEquation.py | 917 | 4.15625 | 4 | '''
Given a sequence of integers, where each element is distinct and satisfies . For each x where 1<=x<n, find any integer y such that p(p(y))=x and print the value of y on a new line.
Function Description
Complete the permutationEquation function in the editor below. It should return an array of integers that represent the values of
.
permutationEquation has the following parameter(s):
p: an array of integers
Input Format
The first line contains an integer
, the number of elements in the sequence.
The second line contains space-separated integers where .
'''
#!/bin/python3
import math
import os
import random
import re
import sys
def permutationEquation(p):
print((p.index(p.index(x+1)+1)+1)for x in range(n))
if __name__ == '__main__':
n = int(input())
p = list(map(int, input().rstrip().split()))
permutationEquation(p)
| true |
2a88f0aa503ceb61fcd07144fdd10e2562c32b62 | divyatejakotteti/100DaysOfCode | /Day 37/FlatlandSpaceStations.py | 1,718 | 4.5 | 4 | '''
Flatland is a country with a number of cities, some of which have space stations. Cities are numbered consecutively and each has a road of
length connecting it to the next city. It is not a circular route, so the first city doesn't connect with the last city. Determine the maximum distance from any city to it's nearest space station.
For example, there are
cities and of them has a space station, city . They occur consecutively along a route. City is unit away and city is units away. City is units from its nearest space station as one is located there. The maximum distance is
.
Function Description
Complete the flatlandSpaceStations function in the editor below. It should return an integer that represents the maximum distance any city is from a space station.
flatlandSpaceStations has the following parameter(s):
n: the number of cities
c: an integer array that contains the indices of cities with a space station,
-based indexing
Input Format
The first line consists of two space-separated integers,
and .
The second line contains
space-separated integers, the indices of each city having a space-station. These values are unordered and unique.
There will be at least
city with a space station.
No city has more than one space station.
Output Format
Print an integer denoting the maximum distance that an astronaut in a Flatland city would need to travel to reach the nearest space station.
Sample Input 0
5 2
0 4
Sample Output 0
2
'''
n,m=(int,input().split())
c=sorted(map(int,input().strip.split())
m=max(n-c[-1]-1,c[0])
for i in range(1,len(c)):
d=math.floor((c[i]-c[i-1])/2)
if(d>m):
m=d
print(m) | true |
b6be72984e340456b8f87b4ddd8ec845a21fc938 | divyatejakotteti/100DaysOfCode | /Day 27/SherlockAndSquares.py | 1,206 | 4.46875 | 4 | '''
Watson likes to challenge Sherlock's math ability. He will provide a starting and ending value describing a range of integers. Sherlock must determine the number of square integers within that range, inclusive of the endpoints.
Function Description
Complete the squares function in the editor below. It should return an integer representing the number of square integers in the inclusive range from
to
.
squares has the following parameter(s):
a: an integer, the lower range boundary
b: an integer, the uppere range boundary
Input Format
The first line contains q, the number of test cases.
Output Format
For each test case, print the number of square integers in the range on a new line.
Sample Input
2
3 9
17 24
Sample Output
2
'''
#!/bin/python3
import math
import os
import random
import re
import sys
def squares(a, b):
sqrtA = math.ceil(math.sqrt(a))
sqrtB = math.floor(math.sqrt(b))
return(sqrtB - sqrtA + 1)
if __name__ == '__main__':
q = int(input())
for q_itr in range(q):
ab = input().split()
a = int(ab[0])
b = int(ab[1])
result = squares(a, b)
| true |
3a054171a05293d817336dc7b56af7ab7421fcb3 | divyatejakotteti/100DaysOfCode | /Day 25/BeautifulDays_at_theMovies.py | 1,733 | 4.4375 | 4 | '''
Lily likes to play games with integers. She has created a new game where she determines the difference between a number and its reverse. For instance, given the number 12, its reverse is 21. Their difference is 9. The number 120reversed is 21, and their difference is 99.
She decides to apply her game to decision making. She will look at a numbered range of days and will only go to a movie on a beautiful day.
Given a range of numbered days,|i....j| and a number k, determine the number of days in the range that are beautiful. Beautiful numbers are defined as numbers where |i-reverse(i)|is evenly divisible by k. If a day's value is a beautiful number, it is a beautiful day. Print the number of beautiful days in the range.
Function Description
Complete the beautifulDays function in the editor below. It must return the number of beautiful days in the range.
beautifulDays has the following parameter(s):
i: the starting day number
j: the ending day number
k: the divisor
Input Format
A single line of three space-separated integers describing the respective values of i, j, and k.
Output Format
Print the number of beautiful days in the inclusive range between i and j.
Sample Input
20 23 6
Sample Output
2
'''
#!/bin/python3
import math
import os
import random
import re
import sys
def beautifulDays(i, j, k):
count=0
for i in range(i,j+1):
a=str(i)
b=a[::-1]
c=abs(int(i)-int(b))%k
if(c==0):
count+=1
return(count)
if __name__ == '__main__':
ijk = input().split()
i = int(ijk[0])
j = int(ijk[1])
k = int(ijk[2])
result = beautifulDays(i, j, k) | true |
339c11950657fd59e71804f3a54b0f548642c627 | divyatejakotteti/100DaysOfCode | /Day 48/StrongPassword.py | 2,194 | 4.15625 | 4 | '''
Louise joined a social networking site to stay in touch with her friends. The signup page required her to input a name and a password. However, the password must be strong. The website considers a password to be strong if it satisfies the following criteria:
Its length is at least
.
It contains at least one digit.
It contains at least one lowercase English character.
It contains at least one uppercase English character.
It contains at least one special character. The special characters are: !@#$%^&*()-+
She typed a random string of length
in the password field but wasn't sure if it was strong. Given the string she typed, can you find the minimum number of characters she must add to make her password strong?
Note: Here's the set of types of characters in a form you can paste in your solution:
numbers = "0123456789"
lower_case = "abcdefghijklmnopqrstuvwxyz"
upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
special_characters = "!@#$%^&*()-+"
Input Format
The first line contains an integer
denoting the length of the string.
The second line contains a string consisting of
characters, the password typed by Louise. Each character is either a lowercase/uppercase English alphabet, a digit, or a special character.
Constraints
Output Format
Print a single line containing a single integer denoting the answer to the problem.
Sample Input 0
3
Ab1
Sample Output 0
3
'''
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the minimumNumber function below.
def minimumNumber(n, password):
count = 0
if any(i.isdigit() for i in password)==False:
count+=1
if any(i.islower() for i in password)==False:
count+=1
if any(i.isupper() for i in password)==False:
count+=1
if any(i in '!@#$%^&*()-+' for i in password)==False:
count+=1
return max(count,6-n)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
password = input()
answer = minimumNumber(n, password)
fptr.write(str(answer) + '\n')
fptr.close()
| true |
eb5770b15ba0e06dbff9cb5e9f4ac1b4aaca1453 | divyatejakotteti/100DaysOfCode | /Day 06/SocksMerchant.py | 1,064 | 4.5625 | 5 | '''
John works at a clothing store. He has a large pile of socks that he must pair by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are.
For example, there are n=7 socks with colors ar=[1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2. There are three odd socks left, one of each color. The number of pairs is 2.
Function Description:
Complete the sockMerchant function in the editor below. It must return an integer representing the number of matching pairs of socks that are available.
sockMerchant has the following parameter(s):
n: the number of socks in the pile
ar: the colors of each sock
Input Format:
The first line contains an integer n, the number of socks represented in ar.
The second line contains space-separated integers describing the colors ar[i] of the socks in the pile.
'''
#Code:
n=input()
socks=input().strip().split()
pair=0
for i in set(socks):
pair=pair+socks.count(i)//2
print(pair)
| true |
606334ca145a342d401e35dc271d7d0ee5080fab | joehammahz808/CS50 | /pset6/mario/mario.py | 789 | 4.125 | 4 | # Ruchella Kock
# 12460796
# this program will take a given height and print a pyramid with two spaces in between
from cs50 import get_int
# prompt user for positive integer
while True:
height = get_int("height: ")
if height > 23 or height < 0:
continue
else:
break
# do this height times
for x in range(height):
# calculate the number of spaces
number_of_spaces = height - (x + 1)
for y in range(number_of_spaces):
print(" ", end="")
# calculate the number of #'s
hashtag = 1 + x
for y in range(hashtag):
print("#", end="")
# print two spaces in between
print(" ", end="")
# print the other hashes
for y in range(hashtag):
print("#", end="")
# make a space to go to the next line
print() | true |
110737c9958d67282c27f00c82543f97723bbf06 | bpatgithub/hacker | /python/objectPlay/Inheritance.py | 1,495 | 4.53125 | 5 | # Understanding inheritance.
#
class PartyAnimal:
# this class has two local data store x and name.
x = 0
name = ""
# now lets define constructor.
# Constructor is optional. Complier will perform that operation by itself if you don't.
# all methods with __ are special.
# self is just the point to the instant of the object. That's always the first argument and it is optional.
# you will see that I am constructed is displayed as soon as we execute the program.
def __init__(self, nm):
self.name = nm
print "I am constructed ", self.name
def party(self):
self.x = self.x + 1
print "So far ", self.x, "for", self.name
#Destructor are optional too just like constructor.
# you will see that when program ends, it will display I am destructed.
def __del__(self):
print "I am destructed"
# Now lets create subclass which inherits from PartyAnimal.
class FootballFan(PartyAnimal):
# this subclass has its own local data store for points.
points = 0
# this subclass also has its own local method, which is more stuff than parent class.
def touchdown(self):
self.points += 7
print self.name, "has points ", self.points
# Now main block of the function.
# Create the class, just like calling function.
# This will now create an object and assigned to variable to s and another to j.
s = PartyAnimal("Sally")
s.party()
j = FootballFan("Jim")
j.party()
j.touchdown()
| true |
3c6ee85b82e2410032e6f5be4c6d9750b59977e4 | bpatgithub/hacker | /machineLearning/mapReduce/asymmetricFriends/mr_asymmetric_friends.py | 1,780 | 4.21875 | 4 | '''
Find all Asymmetric relationship in a friend circle.
The relationship "friend" is often symmetric, meaning that if I am your friend,
you are my friend. MapReduce algorithm to check whether this property
holds. It will generate a list of all non-symmetric friend relationships.
Map Input
Each input record is a 2 element list [personA, personB] where personA is a
string representing the name of a person and personB is a string representing
the name of one of personA's friends. Note that it may or may not be the case
that the personA is a friend of personB.
Reduce Output
The output should be all pairs (friend, person) such that (person, friend)
appears in the dataset but (friend, person) does not.
author: bhavesh patel
'''
import mro_asymmetric_friends as mr
import sys
import json
# Part 1
# create map reduce object.
mro = mr.MapReduce()
# Part 2
# Mapper: tokenizes each doc and emits key-value pair.
def mapper(record):
mro.emit_intermediate(record[0], record[1])
# Part 3
# Reducer: Sums up the list of occurrence counts and emits a count for word.
def reducer(key, list_of_values):
# first let's create list of all names.
list = []
opp_friend_list = None
for friend in list_of_values:
#if my friend has a list, check to see if I am in his friend list.
flist = mro.intermediate.get(friend, None)
if flist == None: # My friend has no friends!
mro.emit([friend, key])
mro.emit([key, friend])
else: # my friend has friends.
# Am I in his list?
if key not in flist:
mro.emit([friend,key])
mro.emit([key, friend])
# Part 4
# Load data and executes mr (map reduce).
inputdata = open(sys.argv[1])
mro.execute(inputdata, mapper, reducer)
| true |
a8bd48aeefb58ed69fd609ffa55c27bb32aa048f | borko81/SU_OOP_2021 | /Iterators_generators/fibo_gen.py | 256 | 4.21875 | 4 | def fibonacci():
previous = 0
current = 1
while True:
yield previous
previous, current = current, current + previous
if __name__ == '__main__':
generator = fibonacci()
for i in range(5):
print(next(generator))
| true |
b3080e1275ecd99a94af2492bfe5ed5894b48fc8 | likair/python-programming-course-assignments | /Assignment3_4.py | 773 | 4.15625 | 4 | '''
Created on 15.5.2015
A program, which finds all the indexes of word 'flower' in the following text:
"A flower is a beautiful plant, which can be planted in the garden or used to decorate
home. One might like a flower for its colors and the other might like a flower for its
smell. A flower typically symbolizes soft feelings".
@author: e1201757
'''
text = 'A flower is a beautiful plant, which can be planted in the garden or used to decorate home. One might like a flower for its colors and the other might like a flower for its smell. A flower typically symbolizes soft feelings'
index = 0
while index < len(text):
index = text.find('flower', index)
if index == -1:
break
print(index)
index += 6
| true |
b6184226d54b6c62649165d0c0cfec0eec104e2a | TimJJTing/test-for-gilacloud | /part1_multiples.py | 703 | 4.3125 | 4 | # part1_multiples.py
# 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.
def find_multiples_of_3_or_5(below):
# ans = []
# multiples of 3
# n = 0
# while 3*n < below:
# ans.append(3*n)
# n += 1
# multiples of 5
# n = 0
# while 5*n < below:
# # if n is not a multiple of 3, 5*n won't be.
# if n%3 != 0:
# ans.append(5*n)
# n += 1
# return ans
mult = [i for i in range(below) if i % 3 == 0 or i % 5 == 0]
return mult
print(sum(find_multiples_of_3_or_5(1000)))
| true |
f9db575371ab34db729a931c0db269a8ae17e041 | wildflower-42/FLVS-Foundations-of-Programing | /FavoriteColoursProgram.py | 1,710 | 4.375 | 4 | #Alaska Miller
#6/23/2020
#The Perpouse of this program is to prompt the human end user to input a series of questions that will have them rank their favorite colours, then the program will match them against MY previously listed into the program, favorite colours!
def favoritesCompare():
#This section of code creates the nessecary variables and lists to preform the functions of the program:
myFavoriteColours = ["blue","pink","red","black","white"] #This is the List of my favorite colours
numOfColours = len(myFavoriteColours) #This variable tells us how many colours are in the previous list "myFavoriteColours"
yourFavoriteColours = [] #This list is blank and is used to be a blank target for the "xyz.appened", so we can pogressively create a list and check it against the "myFavoriteColours" list
#This section of code is a loop that prompts the human end user to input their favorite colours into a series of promts, ranking them:
for n in range(0,numOfColours):
humanListNum = int(n)+int(1)
inputColours = input(str("please enter your #")+str(humanListNum)+str(" favorite colour:"))
yourFavoriteColours.append(inputColours)
#This section of code is a loop that checks the user input against the existing list "myFavoriteColours", and then uses an "if-else" statement to detirmine what it's response should be, then lists the responses:
for n in range(0,numOfColours):
if myFavoriteColours[n] == yourFavoriteColours[n]:
print("Your #"+str(n+1)+" favorite colour is: "+str(yourFavoriteColours[n])+", Mine is too!")
else:
print("Your #"+str(n+1)+" favorite colour is: "+str(yourFavoriteColours[n])+", but mine is: "+str(myFavoriteColours[n]))
favoritesCompare()
| true |
ea3ee2d7d504aa666b0c6823f27359135482ec0e | jeffdeng1314/CS16x | /cs160_series/python_cs1/labs/lab2/again.py | 261 | 4.28125 | 4 | x = input("Give me a positive number that is less than 256\n")
try:
x = int()
if x > 256 or x <0:
print('error')
else:
while (x > 0):
print(int(x%2))
x=x//2
except ValueError:
print('bad input')
| true |
f3ebdc3e84c3eaf396fccbe1d32eef39b1eb97e0 | sarcasm-lgtm/Python-Learning | /Printing Arrays Homework Assignment.py | 616 | 4.3125 | 4 | #I tried doing it, but it said this:
#['Ahana', 'is', 'my', 'sister']
#Traceback (most recent call last):
#File "/Users/aarohi/Documents/Printing Arrays Homework Assignment.py", line 4, in <module>
#v=ahana
#NameError: name 'ahana' is not defined
array1=["Ahana","is","my","sister"]
print(array1)
v="Ahana "
q="is "
t="my "
s="sister"
print(v + q + t + s + ". Noice, right?")
#This is some code that I got from a website
arr = [2,4,5,7,9]
print("The Array is : ")
for i in arr:
print(i, end = ' ')
arr2 = ["Ahana","is","my","sister"]
print("The Array is : ")
for i in arr:
print(i, end = ' ')
| true |
2d16bb6cf202fdccdee2c8e1b679173b652fb48c | armstrong019/coding_n_project | /Jiuzhang_practice/implement_trie.py | 2,083 | 4.25 | 4 | class TrieNode():
def __init__(self):
self.children = {}
self.is_word = False
class Trie(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TrieNode()
def insert(self, word):
"""
Inserts a word into the trie.
:type word: str
:rtype: None
"""
root = self.root
for w in word:
if w not in root.children:
root.children[w] = TrieNode()
root = root.children[w] # iterate on root
else:
root = root.children[w]
root.is_word = True
def search(self, word):
"""
Returns if the word is in the trie.
:type word: str
:rtype: bool
"""
root = self.root
for w in word:
print(w)
if w not in root.children:
return False
else:
root = root.children[w]
if root.is_word:
return True
else:
return False
def startsWith(self, prefix):
"""
Returns if there is any word in the trie that starts with the given prefix.
:type prefix: str
:rtype: bool
"""
root = self.root
for w in prefix:
if w not in root.children:
return False
else:
root = root.children[w]
return True
# Your Trie object will be instantiated and called as such:
obj = Trie()
obj.insert('apple')
param_2 = obj.search('apple')
print(param_2)
print('a' in obj.root.children)
# Trie Node has two attributes
#1. children: initially is empty dict, as we insert, this became a dictionary with child name: child TireNode object
# 名字和名字对应的那个Node, dictionary 这个structure比较好理解, 主要是找对应关系
# 那么为什么需要node? 因为我们需要封装, 否则关系混乱
#2. is_word: whether at the level all the node above form a word. Initally is False
| true |
5ebd4360a8efde45eb3803b5e0adffea32030691 | Abhishek19009/Algorithms_and_Data_structures | /Common_Algorithms/String_splitting.py | 649 | 4.5 | 4 | # String splitting algorithm is basic but will be used multiple times so know how to create it
# String splitter will split the string into list based on the special character
def string_splitter(string, replace):
string_temp = ""
string_list = []
for char in string:
if char != replace:
string_temp += char
else:
string_list.append(string_temp)
string_temp = ""
string_list.append(string_temp)
return string_list
def main():
string = input("Enter the string: ")
split_list = string_splitter(string, " ")
print(split_list)
if __name__ == "__main__":
main() | true |
981f67ed61c882fff9322d9538615cbde8a99a68 | Abhishek19009/Algorithms_and_Data_structures | /Miscellaneous/Swap_quickly.py | 320 | 4.25 | 4 | '''
Python has a very cool and short codeline to swap elements without using any temporary variable.
'''
arr = [3,4,5,6,9,1]
arr[2],arr[3] = arr[3],arr[2] # swap element at 3 index with element at 2 index
'''
This is much shorter than creating temp variable to store 3 element and then assigning it to 2 element.
''' | true |
ce648722f6691b0801d22da61026fe3b8f1e04d3 | Abhishek19009/Algorithms_and_Data_structures | /Data Structures/Hashing/Hashing_with_chaining.py | 419 | 4.125 | 4 | '''
Usually hashing creates problem of multiple elements belonging to same hash.
To accommodate this we can store such elements in some data structure like list.
'''
# Consider the hash function f(n) = n mod 7 where n is the element of the list.
arr = [15, 47, 23, 34, 85, 97, 56, 89, 70]
# Creating 7 empty buckets
buckets = [[] for _ in range(7)]
for elem in arr:
buckets[elem%7].append(elem)
print(buckets) | true |
4e293ceb648bf422376f5deb5386b8923ef5ad57 | Abhishek19009/Algorithms_and_Data_structures | /Common_Algorithms/Graph/Dijkstra_shortest_path.py | 1,956 | 4.1875 | 4 | # Implementing Dijkstra
# Not working, fix the bug
import heapq as hp
class Node:
def __init__(self, index, distance): # We can also add extra properties of the node.
self.index = index
self.distance = distance
class Graph:
def __init__(self, n): # n == no of nodes
self.n = n
self.adj = [[] for _ in range(n)]
self.visited = [0 for _ in range(n)]
self.nodeList = [None for _ in range(n)]
self.pq = []
def nodeInit(self, node):
# Initialize the nodes in Graph
# The distance is what we need to update. The shortest path to reach Node(6) would be corresponding distance.
self.nodeList[node.index] = node
def addEdge(self, u, v, path_cost): # u, v corresponds to node index NOT distances!!
self.adj[u].append((v, path_cost))
def dijkstra(self, start, dest):
hp.heappush(self.pq, (self.nodeList[start].distance, start, 0))
self.visited[start] = 1
cur = (0, start, 0)
while self.pq:
print(cur)
if cur[1] == dest:
break
prev_distance = cur[0]
for neighbour in self.adj[cur[1]]:
if not self.visited[neighbour[0]]:
hp.heappush(self.pq, (self.nodeList[neighbour[0]].distance, neighbour[0], neighbour[1]))
# neighbour[0] = index, neighbour[1] = path_cost
self.visited[neighbour[0]] = 1
cur = hp.heappop(self.pq)
if prev_distance + cur[2] < cur[0]:
self.nodeList[cur[1]].distance = prev_distance + cur[2]
return self.nodeList[cur[1]].distance
if __name__ == "__main__":
g = Graph(7)
g.addEdge(0, 1, 2)
g.addEdge(0, 2, 3)
g.addEdge(1, 3, 4)
g.addEdge(2, 4, 9)
g.addEdge(3, 4, 8)
g.addEdge(3, 5, 3)
g.addEdge(4, 6, 7)
g.nodeInit(Node(0, 0))
g.nodeInit(Node(1, 2))
g.nodeInit(Node(2, 3))
g.nodeInit(Node(3, float("Inf")))
g.nodeInit(Node(4, float("Inf")))
g.nodeInit(Node(5, float("Inf")))
g.nodeInit(Node(6, float("Inf")))
print(g.dijkstra(0, 6))
| true |
0bf431af9180d8e61c6d6ef1bd95d453d72d9a82 | antoniotorresz/python | /py/Logical/factorial_number.py | 324 | 4.375 | 4 | #Recursive function to calculate factorial froma given number
def get_factorial(number):
if not number == 0 or number == 1:
return (get_factorial(number - 1) * number)
else:
return 1
x = int(input("Please, type a number to calculate its factorial: "))
print(str(x) + "! = " + str(get_factorial(x)))
| true |
5a7b7cfe9cef4d67c8942b549b604ce77f2b7dd0 | rusalinastaneva/Python-Advanced | /07. Error handling/01. Numbers Dictionary.py | 1,039 | 4.3125 | 4 | numbers_dictionary = {}
line = input()
class IsNotNumberStringError(Exception):
"""Raised when the value is a digit"""
pass
while line != "Search":
try:
number_as_string = line
if number_as_string.isdigit():
raise IsNotNumberStringError("Input must be a string")
number = int(input())
numbers_dictionary[number_as_string] = number
except ValueError:
print("The variable number must be an integer")
except IsNotNumberStringError as error:
print(error)
finally:
line = input()
line = input()
while line != "Remove":
searched = line
try:
print(numbers_dictionary[searched])
except KeyError:
print("Number does not exist in dictionary")
finally:
line = input()
line = input()
while line != "End":
searched = line
try:
del numbers_dictionary[searched]
except KeyError:
print("Number does not exist in dictionary")
finally:
line = input()
print(numbers_dictionary)
| true |
71013446d528f0dce9a7439ee4c84b364a5ea2c6 | hancoro/Python_Learn_Project | /PythonFile_RPH7_If_Statements.py | 1,036 | 4.4375 | 4 |
# set a boolean variable as true
boolean_for_if_statement = False
second_boolean_for_if_statement = False
# If statement with one condition
if boolean_for_if_statement:
print("One condition if statement HAS been met")
else:
print("One condition if statement was NOT met")
# If statement with multiple conditions
if boolean_for_if_statement and second_boolean_for_if_statement:
print("Both conditions have been met")
else:
print("Both conditions were not met")
# If statement with multiple conditions
if boolean_for_if_statement or second_boolean_for_if_statement:
print("One conditions has been met")
else:
print("Neither conditions were met")
# If statement where a condition is not equal and else if
if boolean_for_if_statement and second_boolean_for_if_statement:
print("Both conditions has been met")
elif not boolean_for_if_statement and not second_boolean_for_if_statement:
print("Neither condition has been met")
else:
print("one of the conditions was met")
| true |
3b31c41338a759b313b8195f4765aebca106c17c | hancoro/Python_Learn_Project | /PythonFile_RPH13_Exponent_Function.py | 266 | 4.15625 | 4 |
# this is a function that accepts 2 parameters
def raise_to_the_power_of(base_num, pow_num):
result = 1
for num in range(pow_num):
result = result * base_num
# print(num)
return result
print(raise_to_the_power_of(3, 3))
| true |
aeaf4ad44859525a4845e9a178e66bc3173c137f | hancoro/Python_Learn_Project | /PythonFile_RPH14_2d_lists_nested_loops.py | 661 | 4.5 | 4 |
# 2d lists are essentially lists of lists
# for example
number_grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[0]
]
# the example now has 4 rows with three columns
# to access a specific element in the list by reference to the row and column
print(number_grid[1][2]) # This will print row 1, column 2
# to print row
print(number_grid[2])
# this for loop will read out each row of the grid
for row in number_grid:
print(row)
# Nested for loop will read each element of the grid
# each column of row 0 will be read before moving onto the next row
for row in number_grid:
for col in row:
print(col)
| true |
fba98d5bc7c45544c8dbc47aa6ca5b75c4ae7762 | anuraga2/Coding-Problem-Solving | /Sorting/BubbleSort.py | 404 | 4.1875 | 4 | #Function to sort the array using bubble sort algorithm.
def bubbleSort(self,arr, n):
# code here
# running the outer loop
for i in range(n-1):
swapped = True
for j in range(n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = False
if swapped:
return arr
return arr | true |
386583b7139d1ffa01daaf3f430e2972e9dd821e | SravaniDash/Coursera-Python-For-Everyone | /exercises/chapter13/extractXML.py | 696 | 4.125 | 4 | # In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/geoxml.py. The program will
# prompt for a URL, read the XML data from that URL using urllib and then parse and extract the comment counts from the XML data,
# compute the sum of the numbers in the file.
# Actual Data: http://py4e-data.dr-chuck.net/comments_1012757.xml
import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
sum=0
address = input('Enter location: ')
handle = urllib.request.urlopen(address).read()
tree = ET.fromstring(handle)
for count in tree.findall('comments/comment'):
val = int(count.find('count').text)
sum = sum + val
print(sum)
| true |
143b32c0cbf692e4072c707d9e9de0bf77fb077f | HohShenYien/Harvard-CS50 | /Week6/credit.py | 1,954 | 4.125 | 4 | def main():
# Putting in all the return strings into a list
# so that the function just return an int
return_type = ["INVALID", "AMEX", "MASTERCARD", "VISA"]
nums = all_nums(get_nums())
# Print invalid if failed Luhn algorithm
if not luhn_check(nums):
print(return_type[0])
# Prevent the main function from proceeding to 11th line
return
print(return_type[check_card(nums)])
# A simple function to convert the numbers into a list
# This enables easier manipulation
def all_nums(n):
nums = []
while n > 0:
nums.append(n % 10)
n //= 10
# Inverts the list because the numbers are put into the list
# in an inverted order
return nums[::-1]
# Repeats until getting a valid number
def get_nums():
while True:
try:
nums = int(input("Number: "))
return nums
except:
pass
# Luhn algorithm implemented here
def luhn_check(nums):
# Copied the given list so that it can be changed in place
my_nums = nums.copy()
# every 2 numbers from 2nd last is multiplied by 2
for i in range(-2, -len(nums) - 1, -2):
my_nums[i] *= 2
total = 0
# Summing up the digits of the numbers in the list
for i in my_nums:
while i > 0:
total += i % 10
i //= 10
# Checking if last digit of total is 0
if total % 10 == 0:
return True
return False
# Finally, this checks the type of the card
def check_card(nums):
if len(nums) == 15:
if nums[0] == 3 and (nums[1] == 4 or nums[1] == 7):
return 1
elif len(nums) == 13 or len(nums) == 16:
if nums[0] == 4:
return 3
elif len(nums) == 16:
if nums[0] == 5:
for i in range(1, 6):
if nums[1] == i:
return 2
return 0
main()
| true |
b84126a63bac595977f08afcfe84130d80bd6f64 | Jahir575/Python3.8OOP | /EmployeeAssaignment.py | 1,342 | 4.4375 | 4 | """
Create an Employee class with following attributes and methods:
- constructor, which will create an instance of Employee class based on provided arguments:
first name, last name, email address and monthly salary
- get_annual_salary method, which will calculate and return employee annual salary
- show_employee_information method, which will show employee information in such syntax:
Employee: <full name>
Email address: <email>
Annual salary: <annual salary>
- an attribute, which will store the number of created objects of an Employee class
"""
class Employee:
def __init__(self, first_name, last_name, email, monthly_salary):
self.first_name = first_name
self.last_name = last_name
self.email = email
self.monthly_salary = monthly_salary
def annual_salary(self):
annual_salary = self.monthly_salary * 12
return annual_salary
def employee_details(self):
print(f"Employee: {self.first_name} {self.last_name}\n")
print(f"Email: {self.email}\n")
print(f"Annual Salary: {self.annual_salary()}\n")
employee1 = Employee('Sudhir', 'Ghosh','sudhir.ghosh@gmail.com', 16000)
employee2 = Employee('Ismail', 'Sheikh','ismail.sk@gmail.com', 18000)
employees = [employee1, employee2]
for employee in employees:
employee.employee_details()
print('\n')
| true |
a34dc0a076d26372679924c80bafee594878891b | gocommitz/PyLearn | /pydict.py | 732 | 4.15625 | 4 | #Import library
import json
#Loading the json data as python dictionary
#Try typing "type(data)" in terminal after executing first two line of this snippet
data = json.load(open("data.json"))
#Function for retriving definition
def retrive_definition(word):
if word in data:
return data[word]
elif word.title() in data:
return data[word.title()]
elif word.upper() in data:
return data[word.upper()]
elif word.lower() in data:
return data[word.lower()]
else:
return("Try later please check again, we cant find this word")
#Input from user
word_user = input("Enter a word: ")
#Retrive the definition using function and print the result
print(retrive_definition(word_user)) | true |
941223ed6e1f2897992eb7b0db86c7918305110a | Bshock817/basic-python | /basic2.py | 1,709 | 4.1875 | 4 | """
# Countdown - Create a function that accepts a number as an input.
# Return a new list that counts down by one, from the number (as the 0th element) down to 0 (as the last element).
def countdown(num):
nums = []
for val in range(num,-1,-1):
nums.append(val)
return nums
print(countdown(15))
# Print and Return - Create a function that will receive a list with two numbers.
# Print the first value and return the second.
def pr(nums_list):
print(nums_list[0])
return(nums_list[1])
print(pr([5,2]))
# First Plus Length - Create a function that accepts a list and returns the sum of the first value in the list plus the list's length.
def fpl(lst):
return lst[0] + len(lst)
print(fpl([5,2,3,5,6]))
# Write a function that accepts a list and creates a new list containing only the values from the original list that are greater than its 2nd value. Print how many values this is and then return the new list. If the list has less than 2 elements, have the function return False
def val_g(orig_list):
new_list = []
sec_val = orig_list[1]
for idx in range(len(orig_list)):
if orig_list[idx] > sec_val:
new_list.append(orig_list[idx])
print(len(new_list))
return new_list
print(val_g([3,5,8,4,7,9,6,1]))
# This Length, That Value - Write a function that accepts two integers as parameters: size and value.
# The function should create and return a list whose length is equal to the given size, and whose values are all the given value.
def l_v(size, value):
new_list = []
for num_times in range(size):
new_list.append(value)
return new_list
print(l_v(4,7))
"""
| true |
1111183e8cd379b298acbc3535787508395ba06b | Ajay-Puthiyath/Luminar_Django | /Luminar_Project/Flow_Controls/Decesion_Making_Statement/Maximum_Of_Three_Numbers.py | 985 | 4.25 | 4 | num1 = int(input("Enter the first number"))
num2 = int(input("Enter the second number"))
num3 = int(input("Enter the third number"))
if(num1>=num2) and (num1>=num3):
largest = num1
print("The largest number is",largest)
elif(num2>=num1) and (num2>=num3):
largest = num2
print("The largest number is",largest)
else:
largest = num3
print("The largest number is",largest)
if(num1>=num2) and (num1<=num3) or (num1>=num3) and (num1<=num2):
secondLargest = num1
print("the second largest number is", secondLargest)
if (num2 >= num1) and (num2 <= num3) or (num2 >= num3) and (num2 <= num1):
secondLargest = num2
print("the second largest number is", secondLargest)
if (num3 >= num2) and (num3 <= num1) or (num3 >= num1) and (num3 <= num2):
secondLargest = num3
print("the second largest number is", secondLargest)
a1 = min(num1,num2,num3)
a3 = max(num1,num2,num3)
a2 = (num1+num2+num3) - a1 - a3
print("Numbers in sorted order: ", a1, a2, a3)
| true |
e8a759ffe437a57b693b79f6d3eb7dcff18f921e | addinkevin/programmingchallenges | /MedalliaChallenges/2017Challenge/problema2.py | 1,382 | 4.1875 | 4 | import unittest
"""
Given an integer n, we want you to find the amount of four digit
numbers divisible by n that are not palindromes.
A palindromic number is a number that remains the same when
its digits are reversed. Like 1661, for example, it is
"symmetrical".
For example, if n equals 4000, the only four digit numbers
divisible by 4000 are 4000 and 8000. Neither of those numbers
is a palindrome, so the answer would be 2.
If n equals 2002, then the only four digit numbers divisible by
2002 are 2002, 4004, 6006 and 8008. As all of them are
palindromes, the answer would be 0.
Complete a function named nonPalindromicMultiples that
receives an integer n. It should return the amount of four digit
numbers divisible by n that are not palindromes.
"""
MAX_NUMBER = 10000
def isPalindrom(number):
number = str(number)
i = 0
j = len(number) - 1
while i < j:
if number[i] != number[j]:
return False
i += 1
j -= 1
return True
def nonPalindromicMultiples(n):
count = 0
for number in range(n, MAX_NUMBER, n):
if not isPalindrom(number):
count += 1
return count
class MyTestCase(unittest.TestCase):
def test0(self):
self.assertEqual(2, nonPalindromicMultiples(4000))
self.assertEqual(0, nonPalindromicMultiples(2002))
if __name__ == '__main__':
unittest.main()
| true |
04caeadc2469e4bca2256b0731e62ee1d93c13a1 | SreeramSP/Python-Data-Collection-and-Processing | /#Below, we have provided a list of tuuple.py | 399 | 4.34375 | 4 | #Below, we have provided a list of tuples that contain students’ names and their final grades in PYTHON 101. Using list comprehension, create a new list passed that contains the names of students who passed the class (had a final grade of 70 or greater).
l1 = ['left', 'up', 'front']
l2 = ['right', 'down', 'back']
opposites=filter(lambda x: len(x[1])>3 and len(x[0])>3 , zip(l1,l2) )
| true |
fc72535954544203ce0c60b5dbdfa23c608bf7f3 | JustinKnueppel/CSE-1223-ClosedLab-py | /ClosedLab07a.py | 374 | 4.25 | 4 | def getWordCount(input):
numWords = 1
while " " in input:
numWords += 1
input = input[input.index(' ') + 1: len(input)]
return numWords
string = input('Enter a string: ')
while not string:
print('ERROR - string must not be empty\n')
string = input('Enter a string: ')
print(getWordCount(string))
print('Your string has', str(getWordCount(string)), 'words in it.') | true |
e68cf7c5c99d97df4dc021ba20c7a0fd01ae791b | UF-CompLing/Word-Normalization | /FromLecture.py | 1,010 | 4.21875 | 4 | import re
TextName = 'King-James-Bible'
## ~~~~~~~~~~~~~~~~~~~~
## START OF FUNCTIONS
print('opening file\n')
input_file = open('Original-Texts/' + TextName + '.txt', 'r')
# the second parameter of both of these open functions is
# the permission. 'r' means read-only.
#
# The 'Original-Texts/' part is so that it looks
# in the 'Original-Texts' folder
print('going through every line in file. hold on a sec...')
# store every word in here
for line in input_file:
# regex expressions
regexed = re.compile(r'\W+', re.UNICODE).split(line)
# this function takes out characters that are not
# letter or numbers
#
# BUT... it makes a list. let's join that list back together!
# build word to print back to file
toOutput = ''
for word in regexed:
# there are lots of blank spaces that get
# caught up in our program
if word is '':
continue
toOutput += word.lower() + ' '
# print word to our screen
print(toOutput + '\n')
| true |
2aa0ea0761121f1eeb626b17e3c04c97282c9bd1 | amcclintock/Breakfast_Programming_Guild | /broken_1_6.py | 1,217 | 4.46875 | 4 | Take user input, and tell me stuff about the data
user_input = input('Enter something:')
#Check if the data contains alpha
if (user_input.isalpha()):
print (user_input, " contains alpha characters")
#Do some math on characters
three_user_input = user_input * 3
print (user_input, " three times is: ", three_user_input) # End of code comment
#Is it upper case?
if (user_input.isupper()):
print (user_input, " is all uppercase")
elif (user_input.islower()):
print (user_input, " is all lowercase")
else:
print (user_input, " is a mix of upper and lowercase")
#Check if the data is a whole number
if (user_input.isdigit()):
print (user_input, " is a whole numbers")
#Only if a whole number, dig deeper
three_user_value = int(user_input) * 3
print (user_input, " times 3 =", three_user_value)
#is it an even number?
if (int(user_input) % 2 == 0):
print (user_input, " is an even number")
else:
print ("Checking to see if it's odd")
elif:
print (user_input, " is an odd number")
#No good guess for the data
print ("I don't know what ", user_input, " is!")
| true |
abad7aaa10a6918b8eb3b763e179178eeb677253 | driscoll42/leetcode | /0876-Middle_of_the_Linked_List.py | 1,381 | 4.15625 | 4 | '''
Difficulty: Easy
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
If there are two middle nodes, return the second middle node.
Example 1:
Input: [1,2,3,4,5]
Output: Node 3 from this list (Serialization: [3,4,5])
The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
Note that we returned a ListNode object ans, such that:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
Example 2:
Input: [1,2,3,4,5,6]
Output: Node 4 from this list (Serialization: [4,5,6])
Since the list has two middle nodes with values 3 and 4, we return the second one.
Note:
The number of nodes in the given list will be between 1 and 100.
'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
'''
midNode = head
cnt = 0
while True:
cnt += 1
if cnt == 2:
cnt = 0
midNode = midNode.next
if head.next is None:
break
head = head.next
return midNode
'''
slow = head
while head and head.next:
head = head.next.next
slow = slow.next
return slow | true |
016b4c71006d62f4ca5857c8d3eb52c46a109c74 | saisatwikmeda/Personal-Programs | /find_short.py | 471 | 4.15625 | 4 | #Sai Satwik Reddy Meda
# Returning the length of the smallest word in a given string
def find_short(s):
L = s.split(' ') #split list
final = ""
final = L[0]
for i in range(len(L)):
if len(final) > len(L[i]):
final = L[i] # Assign smallest word everytime it changes
i += 1
return len(final) # returning length of hte smallest word
#Alternatively
def find_short(s):
return min(len(x) for x in s.split())
#After learning more python | true |
36ad03ca7141958e68f7429d438c9f0f7a51834e | clintmod/aiden | /2023.05.06/Worldcount.py | 451 | 4.15625 | 4 | # Ask the user to enter a sentence
sentence = input("Enter a sentence: ")
# Initialize a variable to count vowels
vowel_count = 0
# Loop over each character in the sentence
for char in sentence:
# Check if the character is a vowel
if char.lower() in "aeiou":
# If it is, increment the vowel count
vowel_count += 1
# Print the total number of vowels found
print("The total number of vowels in the sentence is:", vowel_count)
| true |
98c9974136879a86fbc53fcc7ec65c4ee81b9864 | Davin-Rousseau/ICS3U-Assignment-6-Python | /assignment_6.py | 1,198 | 4.25 | 4 | #!/usr/bin/env python3
# Created by: Davin Rousseau
# Created on: November 2019
# This program uses user defined functions
# To calculate surface area of a cube
import math
def surface_area_cube(l_c):
# calculate surface area
# process
surface_area = (l_c ** 2) * 6
# output
return surface_area
def main():
# This checks if input is an integer and positive,
# then calls function and keeps going until user
# enters a positive integer
# Input
input_1 = input("Enter the length of the cube(cm): ")
print("")
while True:
try:
length_cube = int(input_1)
if length_cube > 0:
# call functions
surface_area = surface_area_cube(l_c=length_cube)
print("The surface area of the cube is: {0:,.2f}cm^2"
.format(surface_area))
break
else:
print("Invalid input")
input_1 = input("Please try again: ")
continue
except ValueError:
print("Invalid input.")
input_1 = input("Please try again: ")
continue
if __name__ == "__main__":
main()
| true |
83376880f7ac1c33a8b35d4b00b6b703891a1d32 | jkim23/python-code-samples-1 | /radius JTKIM (1).py | 445 | 4.34375 | 4 | #jt kim
#2.29.2019
#compute radius of circle
#radius = int(input("Enter radius for your circle: "))
#area_of_circle = (radius * 3.14) * radius
#print ("Your circle is: ", area_of_circle)
def areaOfCircle(radius):
area = (radius ** 2) * 3.14
return area
print("the area of the circle is ", areaOfCircle(10))
print("the area of the circle is ", areaOfCircle(20))
print("the area of the circle is ", areaOfCircle(30))
| true |
4cbdb9a15e97a8bc1158cc1db2588d095bfc6003 | carlos-carlos/different-solutions | /solution_03.py | 1,535 | 4.46875 | 4 | '''
Write a script that sorts a list of tuples based on the number value in the tuple.
For example:
unsorted_list = [('first_element', 4), ('second_element', 2), ('third_element', 6)]
sorted_list = [('second_element', 2), ('first_element', 4), ('third_element', 6)]
'''
#driver code and empty list for the desired results
unsorted_list = [('first_element', 4), ('second_element', 2), ('third_element', 6)]
sorted_list = []
#for each item in the unsorted_list for the whole list
#set to 'min' to value of list index 0 tuple index 1
for x in range(0, len(unsorted_list)):
min = unsorted_list[0][1]
print(min)
index = 0
#for each item in unsorted_list for the whole list
# if index 1 of each item in unsorted_list is less than the value of 'min'
# min should equal the value of index 1 of each item in unsorted_list
# 'index' shall equal each item in the unsorted list
for i in range(0, len(unsorted_list)):
if unsorted_list[i][1] < min:
min = unsorted_list[i][1]
index = i
# add to sorted_list each index from unsorted_list
sorted_list.append(unsorted_list[index])
#remove each index from unsorted_list
unsorted_list.remove(unsorted_list[index])
print(unsorted_list)
print(sorted_list)
# this is super confusing to me. I'm not exactly sure what is going on starting from 'min'
# especially confused by the unsorted_list[0][1] bit and the use of range(). Why not use just len()?
# I lost track of how the end connects to index which is set to zero
| true |
34dc764b76b229373cda809ddde5a0372170ef6b | outoftune2000/Python | /strings/substringcount.py | 508 | 4.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#program to count the number of times a given substring has been repeated in a given string
def countingSubstrings(string,substring):
count=0
for i in range(0,len(string)):
if string[i:i+len(substring)]==substring:
count=count+1
return count
S=input("Enter a string: ")
SUB=input("Enter the subsring: ")
COUNT=countingSubstrings(S,SUB)
print ("The number of times the given substring: ",SUB," ,in the string: ",S,", is: ",COUNT)
| true |
accd5bfd406cab61113d642643f2bed1307bd865 | danieltshibangu/Mini-projects | /kilometer.py | 598 | 4.34375 | 4 | # This program will prmpt for distance in km
# then convert distace to miles by formula
# miles = kilometers * 0.6214
# define variables
miles = 0.0
kilometers = 0.0
# define miles constant
K_FACTOR = 0.6214
# main will prompt for kilometers,
# use km to miles funtion
# print result
def main():
kilometers = float( input( "Enter number of kilometers: " ) )
km_to_miles( kilometers )
print( format( km_to_miles( kilometers ), '.3f' ) )
# takes argument, returns miles
def km_to_miles( kilometers ):
miles = kilometers * K_FACTOR
return miles
# call main function
main()
| true |
1cdb8009743880959b3f7b17feecfec0a3e64031 | danieltshibangu/Mini-projects | /PYTHON PRACT.py | 598 | 4.21875 | 4 | # This program displays property taxes
TAX_FACTOR = 0.0065 #Represents tax factor
# Get the first lot number
print( 'Enter the property lot number' )
print( 'or rnter 0 to end.' )
lot = int( input( 'Lot number: ' ) )
# continue processing as long as the user
# does not enter lot number 0
while lot != 0:
#Get the property tax
tax = value * TAX_FACTOR
#Display the tax
print( 'Property tax: $', format( tax, '.2f' ), sep=' ' )
#get the next lot number
print( 'Enter the next lot number or' )
print( 'enter 0 to end.' )
lot = int( input( 'Lot number: ' ) )
| true |
a2b2651ad516b9d159954d37d301cda056dcced4 | danieltshibangu/Mini-projects | /initials.py | 932 | 4.1875 | 4 | # this program gets title data from user and
# prints the data
# the main function gets a first, middle and
# last name from user, passing them as arguments
# for get_initials functions. Initial name
# entered and the initials of name printed
def main():
first = input( "Enter first name: " )
middle = input( "Enter middle name: " )
last = input( "Enter last name: " )
get_initials( first, middle, last )
print( "Initial name:", first, middle, last )
print( "Initials:", get_initials( first, middle, last ) )
# the get_initials function gets first, middle,
# last names as arguments and returns a string
# containing each inital
def get_initials( first, middle, last ):
initials = ''
first = first[0].upper() + '.'
middle = middle[0].upper() + '.'
last = last[0].upper() + '.'
initials += first + middle + last
return initials
# call main function
main()
| true |
e6710b0744d0703493aa2434f4a7a171cda70c28 | danieltshibangu/Mini-projects | /total_sales.py | 709 | 4.34375 | 4 | # this program will display the total sales for
# the days of the week
# DAYS_OF_WEEK is used as a constant for the
# size of the list
DAYS_OF_WEEK = 7
def main():
# create the list for days of the week
sales = [0] * DAYS_OF_WEEK
# define the accumulator
total = 0.0
# get the sales for each day of the week
for index in range( DAYS_OF_WEEK ):
print( "Enter sales for day", index+1,
": ", end='' )
sales[ index ] = float( input() )
# Get the total sales for the week
for value in sales:
total += value
# print the values
print( "The total is: $", format( total, ',.2f'),
sep='' )
# call the main function
main()
| true |
ba2de7234a0c6c4ad0c467db583dd97bd6721be2 | danieltshibangu/Mini-projects | /kinetic_energy.py | 732 | 4.3125 | 4 | # program calculates kinetic energy of object
# define variables
mass = 0.0
velocity = 0.0
k_energy = 0.0
# main function will prompt for
# mass and velocity, call the kinetic_energy
# function and display the kinetic energy
def main():
mass = float( input( "Enter mass in kilograms: " ) )
velocity = float( input( "Enter velocity in m/s: " ) )
kinetic_energy( mass, velocity )
print( "The kinetic energy of this object is:" )
print( format( kinetic_energy( mass, velocity ), ',.3f' ) )
# kinetic_energy func calculates
# kinetic energy from mass and velocity
def kinetic_energy( mass, velocity ):
k_energy = 0.5 * mass * ( velocity ** 2 )
return k_energy
# calls main function
main()
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.