blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
4afa52589eb762e8c7e14a8103b417ee80811e88 | projectspace000/data_science | /max_number.py | 720 | 4.15625 | 4 | number1 = 0
number2 = 0
while True:
try:
input1 = input("Please enter an integer: ")
input1 = int(input1)
except ValueError:
print("That is not an integer, please try again.")
continue
else:
number1 = input1
break
while True:
try:
input2 = int(inp... | true |
b1c30be9517a160073af35a582c4f1b72ce59336 | kursatfelsen/Mypythoncodes | /Nihilceng advanced Iteration.py | 2,311 | 4.375 | 4 | """
Perfect Numbers
Write a function named "perfect_numbers" which takes an integer N and returns a tuple containing three lists. The first list contains "perfect" numbers, the second list contains a list of "deficient" numbers, and the third list contains a list of "abundant" numbers.
A number is "perfect" if it... | true |
b7d7597ae187abf6cb1a80dfd9e1b4e8370b7625 | nicolasquinchia/holbertonschool-higher_level_programming | /0x0B-python-input_output/4-append_write.py | 548 | 4.3125 | 4 | #!/usr/bin/python3
"""This module holds a funtion
to append text on a specific file
"""
def append_write(filename="", text=""):
"""Append text in a specific file returning
the numer of characters writen
Keyword Arguments:
filename {str} -- Name of the file where texts is append(default: {... | true |
a061d8d43ffd7d9c206641b8ef0c33769c5f8151 | nicolasquinchia/holbertonschool-higher_level_programming | /0x07-python-test_driven_development/5-text_indentation.py | 696 | 4.15625 | 4 | #!/usr/bin/python3
"""Module with a function that insert new lines
with specific characters on a string
"""
def text_indentation(text):
"""Print text with new lines on specific Characters
Arguments:
text {[str]} -- string to print
Raises:
TypeError: text must be a string
"... | true |
052d82db6aa6b9ea0f47d070730a6b334bb33478 | janhavi-code/Python-codes | /py6.py | 2,393 | 4.34375 | 4 | # Take the inputs of list from user and insert it into another list
# numbers=[]
# number_of_elements=int(input("Enter the number of elements:"))
# for index in range(0,number_of_elements):
# elements=int(input())
# numbers.append(elements)
# print("The numbers are:",numbers)
# -----------------------------... | true |
eaf78b46c139223e60e6d92733bbfa80c61a1fef | poisonivysaur/LOGPROG | /ITERATIVE STATEMENTS & LOOPING exercises/Loops problemsOct 13 SW-Oct15/LOGPROG review 10-29.py | 2,610 | 4.3125 | 4 | #1
'''Write a program that will allow the user to enter two integers, start and end.
The program ensures that start is less than or equal to end, then displays numbers from start to end on the screen.'''
start=int(input('start: '))
end=int(input('end: '))
if end < start:
temp=start
start=end
end=tem... | true |
7eca0683b7a503627908bb6fb364de07303763f1 | poisonivysaur/LOGPROG | /ITERATIVE STATEMENTS & LOOPING exercises/LOOPS 6. no. of days Jan to month.py | 405 | 4.40625 | 4 | '''
6. Write a program that will compute for the number of days from January until month. month may be any value between
1 - 12.
'''
Sum=0
start=1
month=int(input('enter month ended: '))
while start <= month:
if start==2:
days=28
elif start==4 or start==6 or start== 9 or start==11:
da... | true |
60ec7f0cb4ccef8894def44f9d1ff64a12c3261e | poisonivysaur/LOGPROG | /Python Exercises/Day 5/EXERCISE4-Month, Day, Year.py | 634 | 4.125 | 4 | '''Exercise 4
Write a program that will allow the user to enter an 8-digit number to
represent a date value (with the format of mmddyyyy). The rst 2 digits
of this number represent the month, next 2 digits the day and the last 4
digits represent the year.'''
strInput=input('Enter a number: ')
n=int(strInput)
... | true |
7b158879553a7b00deec6a8866708df1d806d2ce | poisonivysaur/LOGPROG | /MORE EXERCISES/13 Dean's Lister.py | 1,171 | 4.4375 | 4 | '''
13. Dean's Lister
Assuming we only have three subjects in the term:
LOGPROG 3 units
INTR-IT 3 units
FITWELL 2 units
Write a program that accepts the grades of the student for each of those subjects, and then displays the
grade point average (GPA) of the student for the term. To compute for the GPA, multiply ... | true |
4ee70628b4b6b6ffe9c35a71357faf2d0975d547 | poisonivysaur/LOGPROG | /Python Exercises/Day 5/PRACTICE1-reverse number.py | 432 | 4.375 | 4 | '''Practice 1
Write a program that displays the reverse of an input 3-digit number while
retaining it as a whole.
S.'''
strInput=input('enter number: ')
n=int(strInput)
n1=n%10
n1=int(n1)
n2=(n%100-n%10)/10
n2=int(n2)
n3=(n-n%100)/100
n3=int(n3)
print('reverse is: ',str(n1)+str(n2)+str(n3))
#be... | true |
caee3edb34f83fcde33fda0ac37fc6e2c11ecefe | poisonivysaur/LOGPROG | /Python Exercises/Day 6/EXERCISE4-mm months.py | 858 | 4.21875 | 4 | '''
Exercise 4
Write a program that will accept as input an integer, assuming the
following format mmddyyyy. Depending on the value in mm, display the
corresponding month in words. If mm is 1, display \January"; if 2, display
\February", and so on.
S.
'''
strInput=input('enter date: ')
n=int(strInput)
mon... | true |
5a5399329b4a5002a4b3770bb6f1e46d9eae24c2 | Baghee23/University | /Introduction to Computer Science(Python simple projects)/neun.py | 902 | 4.3125 | 4 | def maxSequence(lista):
#Calculate the length of the given list
lilen=len(lista)
#Initialize the variables to start the search of the biggest sum amongst the sequences of the given list
max=0
p=0
a=0
#Loop needed to access in every cell of the list in order to check all possible sequences and sums
f... | true |
f4ab73603aa8294878095193fce0c64cc721d0f0 | Funtron5000/CodeInPlace | /Week2/hailstone_sequence.py | 740 | 4.15625 | 4 | """
Gets an integer from the user and prints the hailstone sequence
"""
def main():
number = int(input('Enter a number: '))
run_hailstone(number)
#runs the hailstone sequence
def run_hailstone(number: int):
while number != 1:
if number % 2 == 0:
number = even(number)
else:
... | true |
b83cd180c9ece9549e0b9903cdbb773b72df0b2a | Funtron5000/CodeInPlace | /Week2/Kaprekar.py | 1,863 | 4.125 | 4 | """
Gives the Kaprekar sequence for a given number
That is the number in least-to-greatest order for its digits
subtracted from its greatest-to-least order for its digits
until the result is 6174, Kaprekar's constant
This number should be reached in at most 8 iterations
Some numbers will reach 0 instead though
Kapreka... | true |
efc55513727dbd41d02de410561ecc04ea58906e | Sarthak2601/Python_Basics | /dictionaries.py | 891 | 4.28125 | 4 | customer = {
"name": "John Smith",
"age": 30,
"is_verified": True
}
# Keys should be unique
# Look at it as a dictionary with a word and its meaning
print(customer.get("birthdate")) # Using the get method we will not be returned an error.
print(customer.get("Birthdata", "26-01-2001")) # Prints the valu... | true |
4367ac33c571cc8b962d97edfbb4c94b35181a75 | rosemincj/PythonLearning | /palindrome.py | 335 | 4.46875 | 4 | # Checking whether given string is a palindrome or not using for loop
string = input("Please enter your own String : ")
str1 = ""
for i in string:
str1 = i + str1
print("String in reverse Order : ", str1)
if string == str1:
print("This is a Palindrome String")
else:
print("This is Not a Palind... | true |
4f0f9f1fe921acbe45d390c854eadf4e903cd663 | ori-x/Codewars | /6-Kyu/parity_ol.py | 725 | 4.46875 | 4 | """
You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns this "outlier" N.
... | true |
52d4ff6554a31d7f2de4df04535f8e059456df31 | alethiaQ/learning_python | /lists.py | 728 | 4.34375 | 4 | # similar to arrays, can be iterated over, limitless in size, zero-based, can contain any type of variable
list = []
# can add to a list with .append method
# The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item... | true |
4c45fc0929a9c5989f7f47cf491a226eeb73cddc | isobelfc/eng84_python_exercises | /age_and_permission.py | 1,222 | 4.375 | 4 | # Simple program to use control flow
# check for age
age_check = True
while age_check:
age = input("How old are you? ")
if age.isdigit():
age = int(age) # casts to integer so that we can compare it
age_check = False # ends loop when age is correct
else:
print("Please enter your ag... | true |
5457a8b9677df4275941ff0eeef3abe7c30c2260 | Mr19/Guess-the-Number | /Guess_The_Number.py | 1,204 | 4.1875 | 4 | import random
def main():
print("Welcome to the Number Guessing Game!")
print("I am thinking of a number between 1 and 100.\n")
difficulty = input("Choose a difficulty. Type 'easy or 'hard': ").lower()
difficulty_dict = {"easy": 10, "hard": 5}
computer_guess = random.randint(1, 100)
attempts... | true |
b35688f19c35211dee9d24ddbfbdc039c79a4bd0 | LizzHale/Hackbright | /skills1/skills1.py | 2,743 | 4.125 | 4 | # Things you should be able to do.
# Write a function that takes a list and returns a new list with only the odd numbers.
def all_odd(some_list):
new_list = []
for n in some_list[::-1]:
if n % 2 != 0:
#new_list.append(n)
new_list[0:0] = [n]
else:
pass
ret... | true |
184459c36620036d801a582e5b3356837557dcaa | rprusia/pythonwars | /Buying_A_Car.py | 1,694 | 4.125 | 4 | # Let us begin with an example:
# A man has a rather old car being worth $2000.
# He saw a secondhand car being worth $8000.
# He wants to keep his old car until he can buy the secondhand one.
# He thinks he can save $1000 each month but the prices of his old car
# and of the new one decrease of 1.5 percent... | true |
c3e665ff82d737f7bf8ce382cb8a2aed2c3f5985 | rprusia/pythonwars | /TailBodyHead.py | 718 | 4.1875 | 4 | # you're at the zoo... all the meerkats look weird.
# Something has gone terribly wrong - someone has gone and switched their heads and tails around!
# Save the animals by switching them back. You will be given an array which will have three values (tail, body, head).
# It is your job to re-arrange the array so that th... | true |
812142ef11d93e42a9b557571c336017f376b47f | Leem0sh/leetcode | /1323.py | 848 | 4.125 | 4 | # Given a positive integer num consisting only of digits 6 and 9.
# Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
# Example 1:
# Input: num = 9669
# Output: 9969
# Explanation:
# Changing the first digit results in 6669.
# Changing the second digit results in 9969.... | true |
1ba7e87f5feae95a791d3aa45f4279549681c180 | Saeed-Jalal/Jungle-practice | /Jungle.py | 1,281 | 4.15625 | 4 | #Save your life in jungle by using import random and import time
#usage of loops
#usgae of functions at basic level
import random
import time
def displayIntro():
print('You are in the jungle.\n\nYou can see Dragons in front of you.')
print("There is two dragons and two caves.\n\nIn one cave dragon is friendly\... | true |
5fdc98f19b48184930dbd2adcd960b34f74abbd6 | amalfiyd/explore-repo | /12 - Python Algo and DS/Python Algo and DS/stack.py | 1,073 | 4.21875 | 4 | # Aux class for Node
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
# Main class for stack
class Stack:
# Initialization
# Initialize stack object
def __init__(self):
self.top = None
# Print
# Print the elements in the stack from t... | true |
ee732116faf51c00cff9e139fe9d458fc69b30ac | mvkumar14/Sprint-Challenge--Algorithms | /recursive_count_th/count_th.py | 1,243 | 4.21875 | 4 | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
count = 0
if len(word) < 2:
return... | true |
d8b14e0acbb37984faea45638eb6f721c18fb82f | tan2line/sf-restaurants-sql | /pt1_essentials.py | 2,034 | 4.1875 | 4 | # Part 1: Essentials
def business_ids_count():
"""
Write a SQL query that finds the number of business ids in the
businesses table
:return: a string representing the SQL query
:rtype: str
"""
sqlite_query = 'SELECT COUNT(business_id) FROM businesses'
return sqlite_query
def unique_bu... | true |
05c0c22c5583047776d2a021cc56f66f55a96a32 | hyphaltip/AoC15 | /day05/naughtynice.py | 979 | 4.125 | 4 | #!/usr/bin/python
import re
# It contains at least three vowels (aeiou only), like aei, xazegov, or aeiouaeiouaeiou.
# It contains at least one letter that appears twice in a row, like xx, abcdde (dd), or aabbccdd (aa, bb, cc, or dd).
# It does not contain the strings ab, cd, pq, or xy, even if they are part of one of... | true |
fa97e29a096465b57cc5b24139522d18ab045086 | DefiantAFI/DevOps | /Scripts/BasicClass.py | 501 | 4.21875 | 4 | class Robot:
# Method functions must always use the self perameter
def introduce_self(self):
print("My name is " + self.name)
'''Creates the Robot object with three attributes'''
r1 = Robot()
r1.name = "Cory"
r1.color = "red"
r1.weight = 170
''' Runs the introduce_self member function and sends
r1 as... | true |
a743490fb20a52e6f10ba4499f920f487a667479 | Vishal10492/Basic_to_Brillance | /PycharmProjects/Basic to Brillance/start coding in python.py | 501 | 4.1875 | 4 | # First Simple Program
name = input('What is your name?\n')
age = input('What is your age?\n')
print('Thank You for using my program')
print('Hi', name, 'Your age is', age)
# Simple program to calc age
print('Answer the question to know your age')
name = input('Name:')
print('What is your age?', name, '?')
age = int... | true |
7e57705353c0a513bcf3394dd16fd970a81ffbb9 | TomSerrano/python-dir-renamer | /dir_rename.py | 1,835 | 4.1875 | 4 | '''
Allows the user to rename all the files in a directory sequentially.
Adapted from a geeksforgeeks article.
'''
import os
def main():
#Get current working directory (CWD)
folder = ''
while folder != '!exit':
path = os.getcwd()
print('\nInput a directory to rename the files in it. The director... | true |
ceed4fa6374d50a3f620d7c758a51e72a68c52ed | iamnimonic/Algorithms | /matrixMultiplication.py | 739 | 4.125 | 4 | # matrix multiplication using Divide and Conquer Paradigm
# intro to Strassen's algorithm (1969)
# so, I've just finished watching the lecture and I've reached to a conclusion that Straussen's algorithm uses 7 product that subs the general divide and conquer approach for matrix
# multiplication of time complexity O(n... | true |
6086df168afa71f8558b3a8437749827ed700e23 | ColeTrammer/cty_2014_intro_to_computer_science | /Day 10/My Programs/OOP/Country.py | 2,490 | 4.25 | 4 | class Country:
""" Allowing a new instance of the Country class """
def __init__(self, name, population, size, education, average_temp):
self.name = name
self.population = population
self.size = size
self.education = education
self.average_temp = average_temp
""" T... | true |
d8ba0fb25807d5a3c20cbaab186b03597dc426ac | ralex1975/Python_learning_curve | /Used Defined Functions/decorators.py | 1,356 | 4.5625 | 5 | #____________Defining a decorator Function____________#
def decorator_func(original_func):
def wrapper_func(*args, **kwargs): #*args & **kwargs help take functions with multiple arguments as argument
print('wrapper executed this before {}'.format(original_func.__name__))
return original_func(*... | true |
c4f5335a85d9bbf31b040564088ebc48a8e49717 | manastole03/Programming-practice | /python/Array/index array.py | 458 | 4.21875 | 4 | #Write a python program to find the index of an array element.
inp=input('enter alphabetical elements separated by space: ')
split=inp.split()
print('the list of array is: ',split)
char=input('enter the value you want to find: ')
a=0
index=0
for i in range(len(split)):
if split[i]==char:
a = 1
... | true |
25e70b75f7ba42530a53ac2cd56a69b51ba27d2d | manastole03/Programming-practice | /python/calendar.py | 204 | 4.21875 | 4 | # To get the calendar of the specific month and year from the user input
import calendar
y = int(input("Input the year (YYYY) : "))
m = int(input('Input the month (MM) : '))
print(calendar.month(y,m))
| true |
cbc202cc270dc89d4d4c9dc7c356f085143300c3 | manastole03/Programming-practice | /python/swapping names.py | 246 | 4.25 | 4 | # Swapping the first name and last name
first_name=str(input('enter your first name : '))
last_name=str(input('enter your last name : '))
a=first_name
first_name=last_name
last_name=a
print('the names after swapping :'+first_name+' ',last_name)
| true |
02d356030c16fb7e4af93ddd6e5b9255ebe06bf7 | manastole03/Programming-practice | /python/String/replace.py | 268 | 4.1875 | 4 | # Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.
inp=input('enter the string: ')
char = inp[0]
inp = inp.replace(char, '$')
inp = char + inp[1:]
print(inp)
| true |
c035b73ee4e86f52d71364d8f4361b618392dd94 | AnetaEva/Shopping_List | /ShoppingList.py | 2,782 | 4.21875 | 4 | class ItemToPurchase:
# attributes: item_name, item_price and Item_quantity
def __init__(self, item_name, item_price, item_quantity):
self.item_name = item_name
self.item_price = item_price
self.item_quantity = item_quantity
# actions
def get_item_name(self):
return self... | true |
aea0413c299db6b6d2cc01cc4f321938139d03ea | shahriya07/Python-Exercise | /Ex_Conditionals.py | 438 | 4.3125 | 4 | print("Program to calculate the BMI ")
userHeight = float( input("Enter your Height in meters"))
userWeight = float( input("Enter your Weight in Kg"))
bmi = userWeight / (userHeight * userHeight)
print("Your BMI is: ", round(bmi, 2))
if( bmi <= 18.5 ):
print("Underweight")
elif( bmi > 18.5 or bmi <= 24.9):
pr... | true |
c245ce26ba7b12f02e2b9cd94e86b68b8f56e538 | griffinbentley/Minesweeper | /minesweeper_driver.py | 1,710 | 4.15625 | 4 | from minesweeper import Minesweeper
playing = True
wins = 0
losses = 0
# Loops as long as the player doesn't input "quit"
while playing:
height = input("Enter a height: ")
# Checks to make sure height is valid
while (not height.isdigit()) or (not 1 < int(height)):
print("Invalid Input")
... | true |
e07cd6f8fcb514687fdea7b45237c2999523933e | LizinczykKarolina/Python | /Lists/ex11.py | 652 | 4.53125 | 5 | #46. Write a Python program to select the odd items of a list.
def odd_numbers(lst1):
new_list = []
for i in lst1:
if i % 2 != 0:
new_list.append(i)
return new_list
print odd_numbers([1,2,3,4,5])
#47. Write a Python program to insert an element before each element of a list.
a_list... | true |
865095c86b4664675013a006d67091db27323755 | LizinczykKarolina/Python | /Dictionary/ex9.py | 719 | 4.1875 | 4 | #24. Write a Python program to create a dictionary from a string.
sample_string = 'w3resource'
d = {}
for i in sample_string:
if i not in d:
d[i] = 1
else:
d[i] += 1
print d
#25. Write a Python program to print a dictionary in table format.
my_dict = {'C1':[1,2,3],'C2':[5,6,7],'C3':... | true |
8d2f48bed3bbd87f3ef86be4e3479e0c5b71fa23 | LizinczykKarolina/Python | /Lists/ex4.py | 1,056 | 4.5 | 4 | #ex20. Write a Python program access the index of a list.
my_list = [1,2,3]
for i,j in enumerate(my_list):
print i,j
#21. Write a Python program to convert a list of characters into a string.
my_list = ['a','b','c']
new_list = ''.join(my_list)
print new_list
#22. Write a Python program to find the index ... | true |
ea4e27704b85346cc127661a9ac5d62cdd0b18f8 | LizinczykKarolina/Python | /Dictionary/ex11.py | 1,133 | 4.3125 | 4 | #28. Write a Python program to sort a list alphabetically in a dictionary.
num = {'n1': [2, 3, 1], 'n2': [5, 1, 2], 'n3': [3, 2, 4]}
sorted_num = {k: sorted(v) for k,v in num.items()}
print sorted_num
for k,v in num.items():
num[k] = sorted(v)
print num
#29. Write a Python program to remove spaces ... | true |
0d44cf6a478ee110cb20f3c37d522e7642b3a47d | LizinczykKarolina/Python | /Data Structures/ex3.py | 430 | 4.375 | 4 | #3. Write a Python program to display all the member name of an enum class ordered by their values.
from enum import Enum
class Country(Enum):
Afghanistan = 93
Albania = 355
Algeria = 213
Andorra = 376
Angola = 244
Antarctica = 672
z = [c.name for c in Country]
d = sorted(z)
prin... | true |
50113e920b515c05256192e53591101c69144497 | LizinczykKarolina/Python | /Dictionary/ex15.py | 607 | 4.375 | 4 | #38. Write a Python program to convert a dictionary to OrderedDict.
import collections
Bob = {"W": 25, "Race": "White", "Job": "Mechanic", "Random": "stuff"}
print Bob
print "----------------------"
Bob = collections.OrderedDict(Bob)
print Bob
print "------------------------------"
#39. Write a Python program to ... | true |
ec9591c47ef8e989c3aa6ea703a417f657db6c43 | LizinczykKarolina/Python | /Functions/ex2.py | 422 | 4.40625 | 4 | #2. Write a Python function to sum all the numbers in a list.
def sum_numbers(list1):
sum_of_numbers = sum(i for i in list1)
return sum_of_numbers
print sum_numbers([1, 3, 5, 7])
#3. Write a Python function to multiply all the numbers in a list.
def multiply_numbers(list1):
mul_of_numbers = 1
for... | true |
768e886e601a5437ce55e8bd65bc23b6f3ce1384 | LizinczykKarolina/Python | /Lists/ex12.py | 1,395 | 4.71875 | 5 | #48. Write a Python program to print a nested lists (each list on a new line) using the print() function.
a_list = [['Red'], ['Green'], ['Black']]
for x in a_list:
print x
#ex49. Write a Python program to convert list to list of dictionaries.
lst1 = ["Black", "Red", "Maroon", "Yellow"]
lst2 = ["#000000", "#F... | true |
b7a00dc6007db14a7c76929e3a16dc5c81b6c94e | LizinczykKarolina/Python | /Functions/ex7.py | 678 | 4.34375 | 4 | #9. Write a Python function that takes a number as a parameter and check the number is prime or not.
def prime_num(number):
division_counter = 0
for i in xrange(1, number + 1):
if number % i == 0:
division_counter += 1
if division_counter == 2:
print "{0} is a prime number".form... | true |
3326cd36c9efdf28748d429676680f5e5f537d97 | LizinczykKarolina/Python | /Regex/ex16.py | 362 | 4.34375 | 4 | #20 Write a python program to search a literals in a string and also find the location within the original string where the pattern occurs.
import re
my_string = "Hello world. Hello 2.7 Python and JASON and JAVA"
patterns = (r"Python|JASON|PHP")
for m in re.finditer(patterns, my_string):
print "{0}-{1}: {2}".for... | true |
f0a2997e352176803e9ea4f5cf5408229ea3c818 | LizinczykKarolina/Python | /Data Structures/ex14.py | 516 | 4.25 | 4 | #22. Write a Python program to create a heapsort, pushing all values onto a heap and then popping off the smallest values one at a time.
from heapq import *
l = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heap = []
for value in l:
heappush(heap, value)
z = [heappop(heap) for i in range(len(heap))]
print z
#23. Write a Py... | true |
8d92a1d68bd2a62f306576453ca3b74ca36b251a | LizinczykKarolina/Python | /Algorithms/ex3.py | 580 | 4.125 | 4 | #3. Write a Python program for binary search for an ordered list.
def ordered_binary_search(a_list, item):
a_list.sort()
first = 0
last = len(a_list) - 1
found = False
while first <= last and not found:
midpoint = (first + last)/2
if a_list[midpoint] == item:
found = Tru... | true |
bfd9148c805f798306c7baf8a28ce91e2a7c6f03 | LizinczykKarolina/Python | /file IO/ex8.py | 457 | 4.125 | 4 | #9. Write a Python program to count the number of lines in a text file.
def line_counter(fname):
with open(fname) as f:
lines = len(f.readlines())
return lines
print line_counter("C:\ex15_sample.txt")
def file_lengthy(fname):
with open(fname) as f:
for i, l in enumerate(f):... | true |
195ba444187df44b151f7eee809c650d3d165ac3 | pydeereddy792/PYTHON | /div.py | 391 | 4.25 | 4 | #write a program to take 2 numbers from the user
#then take option to add/subtract/multiple/divide
#and perform that operation
a=int(input("enter value of a"))
b=int(input("enter value of b"))
c=a+b
print("addition of two numbers",c)
d=a-b
print("sub of two numbers",d)
e=a*b
print("multiple of two numbers",e)
f=a/b
pri... | true |
fabbc26d81849a664e657c2e2c6ee86969f3cb2e | BrianMc1/Python-For-Everyone-Coursera | /3_1.py | 279 | 4.125 | 4 | hours = input("How many hours my dude?")
hours = float(hours)
rate = input("And the rate is:")
rate = float(rate)
total = -1
overtime = 0
if hours <= 40:
total = hours * rate
else :
overtime = hours - 40
total = (40 * rate) + (overtime * (1.5 * rate))
print (total)
| true |
216f62f22d90cbb47a92c9a8b2ca6d9dd2ef16e6 | Benjamin1118/CodeChallenge | /isIPV4Address.py | 1,243 | 4.1875 | 4 | # An IP address is a numerical label assigned to each device
# (e.g., computer, printer) participating in a computer network that uses the
# Internet Protocol for communication. There are two versions of the Internet protocol,
# and thus two versions of addresses. One of them is the IPv4 address.
# Given a str... | true |
3bdb15914d182ca1b1715ff0967906a54463f4d6 | Benjamin1118/CodeChallenge | /candies.py | 610 | 4.15625 | 4 | # n children have got m pieces of candy.
# They want to eat as much candy as they can, but each child must eat exactly
# the same amount of candy as any other child.
# Determine how many pieces of candy will be eaten by all the children together.
# Individual pieces of candy cannot be split.
# Example
# F... | true |
3fe2cb84e392a96bb5ea6caf930a58427265ba8a | MastersAcademy/Programming-Basics | /homeworks/dmitriy.datsenko_DmitriyDats/homework-2/сollections.py | 850 | 4.125 | 4 | # the variable is assigned a demo file
fileName = 'demo.txt'
# It opens the file for writing only. Index stands at the beginning of
# the file. Creates a file with the filename, if such does not exist.
accessMode = 'w'
# Collections(Dictionaries)
user_info = {
'user_name': str(input('What is your name? ')),
'us... | true |
98416cb27e31dd30d823baa19ad084ebd7e0cfd2 | cmmolanos1/holbertonschool-machine_learning | /unsupervised_learning/0x02-hmm/5-backward.py | 1,882 | 4.375 | 4 | #!/usr/bin/env python3
"""
Markov chain
"""
import numpy as np
def backward(Observation, Emission, Transition, Initial):
"""performs the forward algorithm for a hidden markov model.
Args:
Observation (np.ndarray): shape (T,) that contains the index of the
observatio... | true |
e3e31659a581d3eb98e0964be500707ad05b1165 | cmmolanos1/holbertonschool-machine_learning | /unsupervised_learning/0x02-hmm/0-markov_chain.py | 1,246 | 4.15625 | 4 | #!/usr/bin/env python3
"""
Markov chain
"""
import numpy as np
def markov_chain(P, s, t=1):
""" determines the probability of a markov chain being in a particular
state after a specified number of iterations.
Args:
P (np-ndarray): of shape (n, n) representing the transition matrix.
... | true |
e960063aa0ca69a04d70048444b969f401c3eb6d | NetUnit/Lv-527.PythonCore | /home_task_1.2.py | 685 | 4.25 | 4 | import time
# hometask2 - SoftServe1 - Lesson1
#2.1 Basic Arithmetic Operators (using function)
time.sleep(1)
print ('We are going to execute some code ')
time.sleep(1)
print ('...')
def calculations():
c = input ( 'Please select the \'a\' variable: ')
a = int (c) # we can put except here to catch a ValueError... | true |
befe16c960cef480451ca70fba8c165a547373c9 | Ranjit007ai/InterviewBit-Bactracking | /backtracking/modular_expression_using_recursion/solution.py | 628 | 4.34375 | 4 | # given values of A and B , we have to return the value of the expression pow(A,B) % C. using recursion
# the idea is simple
# if the B value is even i.e 2^4 = 2^2 * 2^2 = 4 * 4 = 16
# if the B value is odd i.e 2 ^ 5 = 2 ^ 2 * 2 ^ 2 * 2 = 4 * 4 * 2 = 32
def pow_expression(A,B):
# base condition
if A == 0... | true |
fae2add4960fbdf8ebdf84d6fdd16566fdb3dd73 | awestover89/Project-Euler | /Problem-1/problem1.py | 279 | 4.125 | 4 | def getMultiples(max):
multiples = []
for i in range(max):
if i % 3 == 0 or i % 5 == 0:
multiples.append(i)
return multiples
def sum(numbers):
total = 0
for i in numbers:
total += i
return total
print sum(getMultiples(1000))
| true |
764a57b5848244f492e0c9bff87e468a8d1c07c1 | andreschamorro/pfc | /card.py | 1,540 | 4.375 | 4 |
class Card:
"""
A card contains a definition and a list of answers that correspond with it.
Cards can optionally contain hints.
Attributes:
__answer (list of str): A list of possible answers for the card.
__question (str): The question for the card.
__hint (str, optional):... | true |
7b7d85413cbc3360791092718bc1b7b2f0bcdad8 | Vinay4123/Pythonprogs_1 | /Create_third_list_fromtwolists.py | 841 | 4.15625 | 4 | # creating an empty list
list1 = []
list2=[]
# number of elemetns as input
n = int(input("Enter number of elements : "))
# iterating till the range
for i in range(0, n):
ele = int(input())
list1.append(ele) # adding the element
print(list1)
n1 = int(input("Enter number of... | true |
082d7532652bd3863088fa85ead2a8db2d3b8a2e | mepujan/IWAssignment_1_python | /data_types/data_type_7.py | 440 | 4.34375 | 4 | # Write a Python function that takes a list of words and returns the length of the
# longest one.
def length_of_longest_one(list_of_words):
len_of_words=[];
for n in list_of_words:
len_of_words.append(len(n))
len_of_words.sort()
return len_of_words[-1]
def main():
list_of_words=input('En... | true |
06c8177e3a87ae65e36afd28161d8d29bfc69165 | mepujan/IWAssignment_1_python | /data_types/data_type_5.py | 560 | 4.65625 | 5 | # Write a Python program to add 'ing' at the end of a given string (length should
# be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the
# string length of the given string is less than 3, leave it unchanged.
def add_ing_or_ly(string):
if len(string) < 3:
return string
... | true |
4dd20ecb12c281e12eed918ea6b41bed232f83ae | mepujan/IWAssignment_1_python | /data_types/data_type_3.py | 373 | 4.40625 | 4 | # Write a Python program to get a string from a given string where all
# occurrences of its first char have been changed to '$', except the first char itself.
def string_manipulate(string):
return string[0]+string[1:].replace(string[0],'$')
def main():
string=input("Enter the string: ")
print(string_manip... | true |
38337ca9db6c7b9c9e2500e3aec68bd7a6279f18 | charlessokolowski/Problems | /Binary Search/pow.py | 1,135 | 4.21875 | 4 | """
Implement pow(x, n). (n is an integer.)
Example
Example 1:
Input: x = 9.88023, n = 3
Output: 964.498
Example 2:
Input: x = 2.1, n = 3
Output: 9.261
Example 3:
Input: x = 1, n = 0
Output: 1
"""
class Solution:
"""
@param x {float}: the base number
@param n {int}: the power number
@return {float... | true |
35936a94fa51ec5ddbcdfa73ec95b8e964ba0a07 | charlessokolowski/Problems | /Hash_and_Heap/first_unique.py | 970 | 4.28125 | 4 | """
Find the first unique character in a given string. You can assume that there is at least one unique character in the string.
Example
Example 1:
Input: "abaccdeff"
Output: 'b'
Explanation:
There is only one 'b' and it is the first one.
Example 2:
Input: "aabccd"
Output: 'b'
Explanation:
'b' is the fir... | true |
d9c9e38a3e190b0987f6911e6cbdbe924d02e082 | charlessokolowski/Problems | /Binary Search/fast_power.py | 884 | 4.125 | 4 | """
Calculate the an % b where a, b and n are all 32bit non-negative integers.
Example
For 231 % 3 = 2
For 1001000 % 1000 = 0
"""
class Solution:
"""
@param a: A 32bit integer
@param b: A 32bit integer
@param n: A 32bit integer
@return: An integer
"""
def fastPower(self, a, b, n):
... | true |
ac2164028333fb41a9bc8f12688a02befc4de8d4 | charlessokolowski/Problems | /Hash_and_Heap/moving_average.py | 1,340 | 4.15625 | 4 | """
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
Example
Example 1:
MovingAverage m = new MovingAverage(3);
m.next(1) = 1 // return 1.00000
m.next(10) = (1 + 10) / 2 // return 5.50000
m.next(3) = (1 + 10 + 3) / 3 // return 4.66667
m.next(5) = (10 + ... | true |
beea6b5f556e01a55461652065f5a5ad31194a25 | blackowe/Project_3a | /min_max.py | 749 | 4.25 | 4 | # Author: Erik Blackowicz
# Date: 7/6/20
# Description: Code asks user for a # of integers(postive # only), then loops thru values to return the min & max values of that dataset.
user_limit = int(input("How many integers would you like to enter?\n")) # Number should be >=1
print("Please enter", user_limit, "integers."... | true |
4b966a764d04c79566a9de3002b56b7bf2bf946f | Jarmander333/Ch.04_Conditionals | /4.2_Grading_2.0.py | 2,571 | 4.5625 | 5 | '''
GRADING 2.0
-------------------
Copy your Grading 1.0 program and modify it to also print out the letter grade depending on the numerical grade.
If they fail, tell them to "Transfer to Johnston!"
Grading PROGRAM
---------------
Create a program that asks the user for their semester grade, final exam grade,
and fi... | true |
860f292dff4ae1948aef7e98c9788b94d2679087 | thinthread/python_cs_131a_ccsf | /string_stuff/str_rotation_clockwise.py | 280 | 4.15625 | 4 | def str_rotation(word, n):
""" Rotate a string with given amount of round clockwise """
n = n % len(word) # With this this works for any amount of rounds even grater than the length
return word[n:] + word[:n]
def main():
print(str_rotation("Python", 4))
main() | true |
369b7e782a6e1675c41f2078ad1265319be33a92 | thinthread/python_cs_131a_ccsf | /string_stuff/is_site_secure.py | 391 | 4.4375 | 4 | def is_secure_site(url):
""" Given a URL, check whether this URL belongs to a secure site, eg:'https:'"""
if url[0:6] == "https:":
return "YAY,this site is secure!"
else:
return "Sorry, this is not a secure site... :-(("
def main():
url_to_check = input("Please submit a url to... | true |
c6fc059a7afe20fd374ce86c8d364539c15580f6 | zhangruochi/leetcode | /035/Solution.py | 1,818 | 4.125 | 4 | """
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2
Example 2:
Inp... | true |
895c34026d3f03674be95903a03d5a22ce06f7e7 | zhangruochi/leetcode | /009/Solution.py | 1,049 | 4.28125 | 4 | """
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
For example, 121 is a palindrome while 123 is not.
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Inpu... | true |
db8248aeab3b5e0702feaa87bd87849a4db8d897 | zhangruochi/leetcode | /687/Solution.py | 1,508 | 4.28125 | 4 | """
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
Note: The length of path between two nodes is represented by the number of edges between them.
Example 1:
Input:
5
/ \
4... | true |
604f828ee43105f577948070225f91bb00bfa580 | zhangruochi/leetcode | /461/Solution.py | 985 | 4.28125 | 4 | """
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows p... | true |
f36aa666bcd13ff1c7f1e9b73d7068d3b5558443 | zhangruochi/leetcode | /116/Solution.py | 2,470 | 4.3125 | 4 | """
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use ... | true |
2b8d7049fa0501f3d4ec81cf416254e8966663d1 | jebbica/Map-and-Cheese | /main.py | 2,086 | 4.34375 | 4 | # Create an intro message for the user :) Come up with a good name
# name -> Map & Cheese
print("\n--------------------Map & Cheese----------------------")
print("Welcome to Map & Cheese! Been around since '21")
print("Visit our website -> 222.mapandcheese.com")
print("Our business hours are at the bottom of our page :... | true |
37b05dd298864b0931e8bd8147d7bd09c73a4b62 | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/kuhnbt/lesson3/lockes.py | 870 | 4.40625 | 4 | """
Locke class for lesson 3
"""
class Locke:
def __init__(self, capacity, handle_exception):
self.capacity = capacity
self.handle_exception = handle_exception
def move_boats_through(self, num_boats):
if num_boats <= self.capacity:
print('Stopping the pumps')
... | true |
6828258e2c9d5ba786801eaba42c6e1c6a53a909 | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/TerranceJ/lesson3/context_manager.py | 1,073 | 4.40625 | 4 | """
Lesson 3 Context Manager Assignment
Terrance J
2/28/2019
"""
class Locke:
def __init__(self,max_boats):
self.max_boats = max_boats
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is ValueError:
print(exc_val)
... | true |
5be018c9f44e7757e46a46fe872c2ff38eecf8eb | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/roy_t/lesson10/non_profiling_timeit.py | 1,160 | 4.21875 | 4 | import time
from timeit import timeit
"""
Generate the fibonacci sequence in three different ways and determine which method works best.
Three different methods are timed using the timeit module.
"""
def memoize(f):
memo = {}
def helper(x):
if x not in memo:
memo[x] = f(x)
return... | true |
6b917808fc67a1eeda907248c202b73326885e2e | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/LauraDenney/lesson01/iterator_1.py | 1,800 | 4.375 | 4 | #-------------------------------------------------#
# Title: Iterator Exercise
# Dev: LDenney
# Date: February 3rd, 2019
# ChangeLog: (Who, When, What)
# Laura Denney, 2/3/19, Started work on Iterator Exercise
#-------------------------------------------------#
"""
Simple iterator examples
"""
class IterateMe_1... | true |
5dafe233998bcb7577f6a038ec0514ef17f5cdb6 | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/rgpag/lesson01/iterator_1.py | 1,342 | 4.4375 | 4 | #!/usr/bin/env python
"""
Simple iterator examples
"""
class IterateMe_1:
"""
About as simple an iterator as you can get:
returns the sequence of numbers from zero to 4
( like range(4) )
"""
def __init__(self, stop=5):
self.current = -1
self.stop = stop
def __iter__(sel... | true |
7c0115a49b8c920d100c170f86dd6dae02638c68 | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/AurelP/lesson3/locke.py | 2,566 | 4.3125 | 4 | #!/usr/bin/python
#Lesson 3 Aurel Perianu
"""
Context Managers - Ballard locks
"""
class Locke(object):
"""
define class locks
"""
def __init__(self, capacity=1):
capacity = int(capacity)
if capacity < 1:
raise ValueError("Capacity must be a positive integer, try ag... | true |
64a49f4a33ed286db64eaca66b08bd37b6e6e327 | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/jaredmulholland/lesson_2/music_generator.py | 1,582 | 4.15625 | 4 | """
Last week we looked at Spotify’s top tracks from 2017. We used comprehensions and perhaps a lambda to find tracks we might like.
Having recovered from last week’s adventure in pop music we’re ready to venture back.
Write a generator to find and print all of your favorite artist’s tracks from the data set.
Your f... | true |
e4644d8303ca3f239443f2e129cf74c251611c39 | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/mark_luckeroth/lesson09/async_executor.py | 1,700 | 4.28125 | 4 | #!/usr/bin/env python
"""
An example of runing a blocking task in an Executor:
"""
import asyncio
import time
import datetime
import random
async def small_task(num):
"""
Just something to give us little tasks that run at random intervals
These will go on forever
"""
while True: # keep doing th... | true |
9218828ea28f650393bafe71e07889251ede62ea | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/csdotson/lesson01/generator_solution.py | 832 | 4.15625 | 4 | #!/usr/bin/env python
""" A series of simple generators """
def intsum():
# Add series of integers
current, total = 0, 0
while True:
yield(total)
current += 1
total += current
def doubler():
# Each value is double the previous value
total = 1
while True:
yield(... | true |
3356e4da2d0333faba468f3d77c1521f963e3085 | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/imaStudent/lesson03/locke.py | 1,026 | 4.15625 | 4 |
class Locke:
def __init__(self, capacity):
self.capacity = capacity
def __enter__(self):
print("Stopping the pumps")
print("Opening the doors")
return self
def move_boats_through(self, boats):
if self.capacity < boats:
raise Exception("CapacityExceptio... | true |
52666670601ffccd5adfd6501103bd12d7e9f212 | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/alexLaws/lesson03/factorial.py | 694 | 4.5 | 4 | #!/usr/bin/env python3
def factorial(num):
if num < 0:
print('You tried factorial of {}. '
'Factorials do not work for negative numbers!'.format(num))
elif num == 1 or num == 0:
return 1
else:
return num * factorial(num - 1)
factorial(-5)
print('The factorial of 0 i... | true |
fe45899e4960620a6ace735cff0dd861a296df08 | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/Craig_Morton/Lesson01/generator_solution.py | 925 | 4.125 | 4 | # ------------------------------------------------- #
# Title: Lesson 1, pt 3, Generator Assignment
# Dev: Craig Morton
# Date: 11/7/2018
# Change Log: CraigM, 11/7/2018, Generator Assignment
# ------------------------------------------------- #
# !/usr/bin/env python3
def intsum():
"""Sum of integers"""
... | true |
6807c90b592d62dfe3feaa31be819fbbff43f167 | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | /students/JerryH/Lesson06/calculator/adder.py | 432 | 4.125 | 4 | """
Adder class
"""
class Adder():
"""
Adder class
Produces operand 1 + operand 2
"""
@staticmethod
def calc(operand_1, operand_2):
"""
method to add two given values.
:param operand_1: first operand (a number)
:param operand_2: second operand (a number)
... | true |
abcc1395b6d97b8244a015e1ea44ae7f320920f3 | toraj58/pythonproject | /src/threads/threadpool.py | 1,073 | 4.15625 | 4 | from multiprocessing.dummy import Pool as ThreadPool
# [Touraj] :: Good sample for simple ThreadPool and parallel processing of some algorithms that can be complex
# and time Consuming
def squareNumber(n):
return n ** 2
# function to be mapped over
def calculateParallel(numbers, threads=2):
pool = ThreadPoo... | true |
4d51f54ddbce9311d65680ea3817ee83a30b7a55 | Lyasinkovska/BeetRootPython | /lesson_22/task_3.py | 616 | 4.25 | 4 | """
This function works only with positive integers
mult(2, 4) == 8
True
mult(2, 0) == 0
True
mult(2, -4)
ValueError("This function works only with positive integers")
"""
from typing import Optional, Union
Result = Union[int, float]
def mult(a: Optional[Result], n: Optional[Result]) -> Optional[Result]... | true |
4779dff246d5cb4063c3f87947b512c7c8b9d098 | Lyasinkovska/BeetRootPython | /lesson_8/task_2.py | 758 | 4.125 | 4 | """
Write a function that takes in two numbers from the user via input(), call the numbers a and b,
and then returns the value of squared a divided by b, construct a try-except block which raises an exception
if the two values given by the input function were not numbers, and if value b was zero (cannot divide by zero)... | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.