blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
621e1af4f3edb03d2bae0330bbc3b187ed8ff61d | thestrawberryqueen/python | /1_beginner/chapter6/practice/names.py | 381 | 4.125 | 4 | """
Names
Make a list called people and fill it with
at least 6 names. Make another list and use
list slicing to fill it with every other name
from the original list, starting with the 1st name.
Print both lists.
"""
# Insert your code here.
"""
Use a for loop to ask the user to add 4 names
to the list. After you ask for each name, print
out the last 5 names of the list.
"""
| true |
6acd5669a95a0d811a60ceae4b96bfdd25ee9be1 | thestrawberryqueen/python | /3_advanced/chapter19/solutions/type_checker.py | 766 | 4.40625 | 4 | # Domestic bees make their honeycombs in rings where the total cells is
# (n + 1) * (3n) + 1 where n is the number of rows in the honeycomb
# Create a function that takes one argument and prints how many total
# cells there are in the honeycomb.
# If the argument is not the correct type, print a message saying so.
# It should be able to run through the list provided.
def type_checker(x):
try:
print((x + 1) * (3 * x) + 1)
# note to students: print(x * any number) would not result in
# an error if x is a string; it would just print x that many
# times
except TypeError:
print("That's not a valid number")
arg_list = [4, "hi", "obviously NAN", 5.6, None, {3: 4}, [3, 3]]
for i in arg_list:
type_checker(i)
| true |
2ff3b5ec86c67ff0a57b7488d51135c35524516e | thestrawberryqueen/python | /2_intermediate/chapter13/practice/matrix_frobenius_norm.py | 845 | 4.3125 | 4 | """
Write a modified version of the Matrix class(that was defined in
one of the example problems in this section) so that the __str__
method instead returns a string containing a single number: the
matrix's Frobenius norm. The formula for the Frobenius norm will
be the square root of the sum of all the elements squared in the
matrix. Also, the unmodified Matrix class code will be given.
"""
"""
This is the unmodified Matrix class code.
class Matrix:
def __init__(self,thelist: list):
self.thelist=thelist
for items in range(len(self.thelist)):
assert type(self.thelist[items])==list
assert len(self.thelist[0]) == len(self.thelist[items])
for things in range(len(self.thelist[items])):
assert type(self.thelist[items][things])==int
def __str__(self):
return str(self.thelist)
"""
# write your code below
| true |
0adbb41a03958007771928986cf7fa527171b0db | thestrawberryqueen/python | /1_beginner/chapter5/solutions/TV.py | 408 | 4.46875 | 4 | # TV
# Pretend you just got a 50 on your test,
# and you mom says you can’t watch TV until you get
# a score of at least 80. (HINT: comparison operators).
# You increase your test score by 10 points per day.
# Write a program that tells you after
# how many days you'll be able to watch TV. Use a loop.
x = 50
days = 0
while x < 80:
x += 10
days += 1
print("You can watch TV after", days, "days")
| true |
54324f064cbc81d048cab0c3e6398718b4cd494c | thestrawberryqueen/python | /1_beginner/chapter1/solutions/style.py | 311 | 4.15625 | 4 | # Style
# Fix the style in this file so that it runs properly
# and there are comments explaining the program
# Prints messages to greet the user
print("Hello World!")
print("This is a Python program")
# Prompts the user for their age and prints it
age = input("Enter your age: ")
print("Your age is " + age)
| true |
4bbc63c4c35e5ba90d237fbe132d33946ae1d06d | thestrawberryqueen/python | /3_advanced/chapter17/solutions/odd_set_day.py | 618 | 4.3125 | 4 | """
Given a set, remove all the even numbers from
it, and for each even number removed, add
"Removed [insert the even number you removed]".
Example: {1,54, 2, 5} becomes {"Removed 54", 1,
5, "Removed 2"}. It is possible to solve this
problem using either discard or remove.
"""
def odd_set_day(given_set):
add_remove = []
for elem in given_set:
if elem % 2 == 0:
add_remove.append(elem)
for remove in add_remove:
given_set.remove(remove)
given_set.add("Removed " + str(remove))
given_set = {1, 2, 4, 5}
odd_set_day(given_set)
print(given_set)
| true |
329aedfc3be6264412ddb069828d8b58fe07d0b3 | thestrawberryqueen/python | /2_intermediate/chapter13/solutions/triangle.py | 1,676 | 4.4375 | 4 | """
Write a class called Triangle which will take three tuples
(each tuple contains two integers: the x and y coordinates
of a vertex). Then, define an __add__ operation that acts as
a translation operation. Its input argument will be a tuple
of two integers that will indicate the x and y translations
that will be applied to each coordinate. (basically, add the
tuple to each coordinate of the triangle). Also, define a
vertical and horizontal transformation tool in the form
of __mul__ which will also take a tuple of two integers that
will be multiplied to the x and y coordinates of each vertex
respectively.
"""
# write your code below
class Triangle:
def __init__(self, pair1, pair2, pair3):
self.coordinatelist = [pair1, pair2, pair3]
for i in range(len(self.coordinatelist)):
assert (
type(self.coordinatelist[i]) == tuple
and len(self.coordinatelist[i]) == 2
)
self.coordinatelist[i] = list(self.coordinatelist[i])
def __add__(self, other):
assert type(other) == tuple and len(other) == 2
for i in range(len(self.coordinatelist)):
self.coordinatelist[i][0] += other[0]
self.coordinatelist[i][1] += other[1]
return tuple(self.coordinatelist)
def __mul__(self, other):
assert type(other) == tuple and len(other) == 2
for i in range(len(self.coordinatelist)):
self.coordinatelist[i][0] *= other[0]
self.coordinatelist[i][1] *= other[1]
return tuple(self.coordinatelist)
mytriangle = Triangle((0, 0), (1, 0), (0, 1))
print(mytriangle + (1, 1))
print(mytriangle * (2, 2))
| true |
1f586207e764db9251e9f7603f9206979c00b68e | thestrawberryqueen/python | /1_beginner/chapter3/solutions/circle.py | 518 | 4.65625 | 5 | # Circle
# Write a program that asks the user for the radius of a circle.
# Then print the area and circumference of the circle.
# Store 3.14 as the value of pi, which is a constant.
# Don't forget to add comments!
PI = 3.14
# Prompt the user for a radius
radius = float(input("Enter a radius: "))
# Calculate the area and circumference
area = PI * radius ** 2
circumference = 2 * PI * radius
# Print the result
print("The area of the circle is ", area)
print("The circumference of the circle is ", circumference)
| true |
da28ed3ee4a892c9f0045506d78a5f46aa504fd1 | thestrawberryqueen/python | /3_advanced/chapter17/practice/challenge (hard math + python)/linear_independence_checker.py | 1,300 | 4.3125 | 4 | # In linear algebra, a vector (list) of n vectors (lists) each
# containing n integers are considered linearly independent if we
# solve the following equation
# a * x + a * x + a * x + a * x = 0
# 1 1 2 2 3 3 n n
# for where they can be any real constant, and we find that all of
# them equal to 0 being the only possible solution for this system
# of equations (this is called the trivial solution). Write a method
# which takes a vector of n vectors each of size n and determine if
# they are linearly independent. Return true if linearly independent,
# and false otherwise.
# (for this question, assume n is less than equal to 4 and greater than 1)
# Note: Another way we can determine if n vectors is linearly independent is if
# you find that the matrix formed by concatenating the vectors has a nonzero
# determinant. This might be somewhat easier
# (search up calculating “determinant using cofactor expansion”).
def calculateDeterminant(matrix):
# put your code here; remove "pass"
pass
def testLinearIndependence(mat):
return calculateDeterminant(mat) != 0
# mat is an example of an acceptable list of 3 (n) lists each containing
# 3 (n) integers; hint: if you use mat, it should give you True
mat = [[1, 1, 4], [0, 0, 5], [0, 7, 8]]
| true |
cc2156c9cd27f9ef180d73fc2655a706936fddc0 | EriiMitte/ProgramacionUCV2019 | /cripto.py | 1,213 | 4.28125 | 4 | def Crypto(*args):
"""La funcion Crypto recibe una cadena de texto y mediante el encriptado Cesar, le otorga
un desplazamiento dado para devolver un mensaje encriptado"""
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
mov = 5
text = input("Introduce texto a encriptar: ")
text = text.lower()
text_crypt = ""
for i in text:
place = alphabet.index(i)
if place+mov > 26:
text_crypt = text_crypt+alphabet[place+mov-26]
else:
text_crypt = text_crypt+alphabet[place+mov]
print(text_crypt)
return text_crypt
def Decrypt(*args):
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' ]
mov = 5
text = input("Introduce texto a desencriptar: ")
text = text.lower()
text_decrypt = ""
for i in text:
place = alphabet.index(i)
if place+mov > 26:
text_decrypt = text_decrypt+alphabet[place-mov-26]
else:
text_decrypt = text_decrypt+alphabet[place-mov]
print(text_decrypt)
return text_decrypt
| false |
8d0fa75d8c62aed312b6735fca941d1bc5c9b246 | pstivers3/pythonlearn | /hpclass/oo/oopy/practice/paulclass.py | 676 | 4.1875 | 4 | #!/usr/bin/env python
class paulclass():
""" Paul's simple class """
def __init__(self, name):
self.name = name
def hi(self):
print "saying %s" % self.name
pc = paulclass('boo')
pc.hi()
class paulclass2(paulclass): # inherit from paulclass
def __init__(self, name, food): # override init
paulclass.__init__(self, name)
self.food = food
def feedme(self): # add another method
print "My name is %s. Please feed me %s" % (self.name, self.food)
def hi(self): # override hi method from base class
print "Hi my name is %s. I like %s." % (self.name, self.food)
pc2 = paulclass2('Paul','Pizza')
pc2.feedme()
pc2.hi()
| false |
3f68a33beb960b25f76369ef0e755e0d66d3c6e2 | pstivers3/pythonlearn | /intro.to.python.jessica/filter_vowel_words.py | 334 | 4.25 | 4 | names = ["Alice", "Bob", "Cara", "Dan", "Edith" ]
def starts_with_a_vowel(word):
return word[0] in "AEIOUaeiou"
def filter_vowel_words(word_list):
vowel_words = []
for word in word_list:
if starts_with_a_vowel(word):
vowel_words.append(word)
return vowel_words
print(filter_vowel_words(names))
| false |
72fafadc2dd2c03e4559050dd91af4d178522b0b | csheahan/NumberTheoryProblems | /chapter3/section5/problem6/problem6.py | 910 | 4.21875 | 4 | '''
Problem:
Find the number of powerful numbers less than a positive integer n.
Constraints:
n - must be a positive integer
'''
# Primality
from chapter3.section1.problem1 import problem1 as isNotPrime
# Sieve
from chapter3.section1.problem2 import problem2 as primesLessThanN
def solve(n):
if (n < 1):
raise ValueError("n must be a positive integer")
# Get a list of primes < n to check the divisions
# Use a sieve to find all primes less than n
primes = primesLessThanN.solve(n)
# Add n if n is prime
if (not isNotPrime.solve(n)):
primes.append(n)
powerful_numbers = [1]
for i in xrange(2, n):
powerful = True
for prime in xrange(2, i + 1):
if (prime in primes):
if (i % prime == 0):
if (i % (prime ** 2) != 0):
powerful = False
break
if (powerful):
powerful_numbers.append(i)
return powerful_numbers
| true |
49cfec1c61b045a06605e4ebcabe12943efc771b | csheahan/NumberTheoryProblems | /chapter1/section5/problem4/problem4.py | 397 | 4.125 | 4 | '''
Problem:
Find the Collatz sequence for a positive integer n
Constraints:
n - must be a positive integer
'''
def solve(n):
if (n <= 0):
raise ValueError("n must be a positive integer")
if (n == 1):
return [1]
answer = []
while (n > 1):
answer.append(n)
if (n % 2 == 0):
n = n / 2
else:
n = (3 * n + 1) / 2
answer.append(n)
return answer | true |
bf80988df927d6463b3e178047c55d002819b50c | Alee4738/leetcode | /src/longest_palindrome.py | 1,838 | 4.15625 | 4 | def longest_palindrome(s):
"""
s a string, max length 1000
returns longest palindrome in s
"""
if s == '' or len(s) == 1:
return s
max_palin_length = 1
max_palin_left, max_palin_right = 0, 0
for i in range(len(s)):
odd_length, even_length = 0, 0
odd_palin = longest_palindrome_at(s, i, i)
odd_length = odd_palin[1] - odd_palin[0] + 1
if (i + 1) < len(s) and s[i] == s[i + 1]:
even_palin = longest_palindrome_at(s, i, i + 1)
even_length = even_palin[1] - even_palin[0] + 1
if odd_length > max_palin_length:
max_palin_left, max_palin_right, max_palin_length = odd_palin[0], odd_palin[1], odd_length
if even_length > max_palin_length:
max_palin_left, max_palin_right, max_palin_length = even_palin[0], even_palin[1], even_length
return s[max_palin_left : max_palin_right + 1]
def longest_palindrome_at(s, left_ctr_idx, right_ctr_idx):
"""
:param s: str
:param left_ctr_idx: int [0,len(s))
:param right_ctr_idx: int [0, len(s))
:return: 2-tuple (l, r) where s[l:r+1] is the longest palindrome at center
It is invalid to call when s[left_ctr_idx : right_ctr_idx + 1] is not a palindrome
(i.e. usage is designed to expand 1-length and 2-length palindromes)
"""
left_edge, right_edge = left_ctr_idx, right_ctr_idx
while 0 <= left_edge - 1 < len(s) and 0 <= right_edge + 1 < len(s) and \
s[left_edge - 1] == s[right_edge + 1]:
left_edge = left_edge - 1
right_edge = right_edge + 1
return left_edge, right_edge
str_list = [
'babad', 'abba', 'abcd', 'abbabbac', 'cabbabba', 'asdfabbabbac',
'bbbbbbbbbbbbbbbbbbbb'
]
for st in str_list:
print('Input: %s' % st)
print('Output: %s\n' % longest_palindrome(st))
| false |
0145aa465ab9f78a334c4d21b43e15f5d1d2f0ee | Alee4738/leetcode | /src/length_longest_substr.py | 1,347 | 4.125 | 4 | """
3. Longest Substring Without Repeating Characters
Medium
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
"""
from typing import *
def lengthOfLongestSubstring(s: str) -> int:
# sliding window solution
# current substr is s[start:end] (end is not inclusive)
start = end = 0
# answer and current substring length
ans = substr_len = 0
# set of chars in current substr
seen = set()
while end < len(s):
if s[end] not in seen:
seen.add(s[end])
end += 1
substr_len += 1
else:
while start < end:
if s[start] != s[end]:
seen.remove(s[start])
start += 1
substr_len -= 1
else:
start += 1
break
end += 1
ans = max(ans, substr_len)
# print('Current substr: ' + s[start:end])
# print('Current length: ' + str(end - start))
# print('Max length: ' + str(ans))
# print()
return ans
| true |
e1cc646caf90bcf54d00e3223c4c793342825006 | Akash1Dixit/PythonFundamentals | /day9/lambda2.py | 420 | 4.34375 | 4 | #lambda returns a function
#assigning name to function returned is optonal
print (lambda x,y,z: x+y+z)(2,3,4)
#here we are assigning name to the function returned
f = lambda x,y,z: x+y+z
#calling the function and storing the result
result = f(2,3,4)
print result
#same task using def statement
def g():
def f(x,y,z):
return x+y+z
return f
f = g()
result = f(2,3,4)
print result
| true |
e65012fd7470d7f69b1cf4a5ddf4353e85ee1494 | Akash1Dixit/PythonFundamentals | /day12/tk1.py | 495 | 4.25 | 4 | #
#import the module Tkinter
from Tkinter import *
root.mainloop( )
#Create the GUI application main window
root = Tk( )
root.title("A simple application")
#Add one or more widgets to the GUI application.
label=Label(root,text='hello world!!')
#pack the Label in the parent widget
label.pack()
#Adding a button and packing it in the same statement
Button(text='click', command= exit).pack()
#calls the mainloop to bring up the window and start the tkinter event loop
| true |
e678e2cf288d56d90ba02db6ab33642898f101ab | Akash1Dixit/PythonFundamentals | /day3/tuple.py | 414 | 4.40625 | 4 | tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print tuple # Prints complete list
print tuple[0] # Prints first element of the list
print tuple[1:3] # Prints elements starting from 2nd till 3rd
print tuple[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints list two times
print tuple + tinytuple # Prints concatenated lists | true |
a6d01f2238477e01c1df712e78c1323e483ffd0c | JuanJMendoza/PythonCrashCourse | /Ch4: Working with Lists/foods.py | 1,642 | 4.90625 | 5 | '''
To copy a list, we can make a slice that includes the entire original list by ommiting
the first index and the second index ([:]). This tells Python to make a slice that
starts at the first item and ends witht the last item, producing a copy of the entire
list.
'''
favorite_foods = ["pizza", "falafel", "carrot cake"]
friend_fav_food = favorite_foods[:]
print("My favorite foods are: ", "\n", favorite_foods, "\n",)
print("My friend's favorite foods are: ", "\n", friend_fav_food)
print("\n")
'''
To prove that we have two seperate lists, we'll add a new food to each list and show
that each list keeps track of the appropriate person's favorite foods.
'''
favorite_foods.append("lasagna")
friend_fav_food.append("zuccini")
print("My favorite foods are: ", "\n", favorite_foods, "\n",)
print("My friend's favorite foods are: ", "\n", friend_fav_food)
print("\n")
'''
If we had simply set
friend_fav_foods = favorite_foods,
we would not produce two seperate lists.
For example, here's what happens when you try to copy a list without using a slice:
'''
#This doesn't work:
my_foods = ["pizza", "falafel", "carrot cake"]
friends_food = my_foods
my_foods.append("banana")
friends_food.append("apple")
print("My fav. foods are:")
print(my_foods)
print("\n")
print("My friend's fav. foods are:")
print(friends_food)
print("\n")
'''
This sytax actually tells Python to associate the new variable friend_foods with the
list that is already associated with my_foods, so now both variables point to the same
list.
MAKE SURE YOU'RE COPYING A LIST USING A SLICE IF YOU WANT A SEPERATE LIST WITH THE
SAME ELEMENTS AS THE LIST BEING COPIED.
''' | true |
7898a5e2abd18bde4f79a47f7f0c313c4b5b99d8 | JuanJMendoza/PythonCrashCourse | /Ch5: if Statements/favorite_foods.py | 306 | 4.1875 | 4 | '''
Make a list of your favorite fruits, and then write a series of independent if statements
that check for certain fruits in your list.
'''
fav_fruits = ["green apple", "pineapple", "banana"]
fav_fruit = "green apple"
if (fav_fruit in fav_fruits):
print(f"Wow, I didn't know you liked {fav_fruit}s") | true |
620adcb82d4e708c699ae0eec7b1eb58f08a092d | JuanJMendoza/PythonCrashCourse | /Ch10: Files and Exceptions/write_message.py | 663 | 4.46875 | 4 | '''WRITING TO AN EMPTY FILE'''
'''To write text to a file, you need to call open() with a second argument telling Python that you want to write to the file.'''
filename = 'programming.txt'
'''The first argument is still the name of the file we want to open. The second argument, 'w', tells Python that we want to open the file in '[w]rite mode'.'''
'''You can also open a file in read mode ('r'), write mode ('w'), append mode('a'), or a mode that allows you to read and write ('r+').'''
'''If you omit the mode argument, Python opens the file in read-only mode by defualt.'''
with open(filename, 'w') as file_object:
file_object.write("I love programming.") | true |
4b327ac7967995c3c3e1c58bad30eacee194b380 | JuanJMendoza/PythonCrashCourse | /Ch4: Working with Lists/dimensions.py | 1,471 | 4.75 | 5 | '''
A tuple looks like a list except it has parentheses instead of square brackets.
Once you define a tuple, you can access individual elements by using each item's index,
just as you would for a list. Tuples are immutable, so once you put an element in one
you cannot change it.
'''
rectangle = (200, 50)
print(rectangle[0])
print(rectangle[1])
print(rectangle)
'''The line below gives a TypeError: 'tuple object does not support item assignment'''
#rectangle[0] = 250
'''
Tuples are technically defined by the presence of a comma; the parentheses make them
look neater and more readable. If you want to define a tuple with one element, you need
to include the trailing comma.
'''
my_t = (3,)
print(my_t)
print(my_t[0])
'''
You can loop over all the elements in a tuple just like you can with a list
'''
print("loop below")
for dim in rectangle:
print(dim)
'''
Although we can't modify a tuple, you can assign a new value to a variable that
represents a tuple. So if we wanted to change our dimensions, we could redefine
the entire tuple:
'''
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
'''Python doesn't raise any values this time because reassigning a variable is valied'''
'''
Use tuples when you want to store a set of values that should not be changed throughout
the life of a program.
''' | true |
089460f303156ba9ba17c49ab36038c306f04033 | JuanJMendoza/PythonCrashCourse | /Ch6: Dictionaries/rivers.py | 594 | 4.90625 | 5 | '''
Make a dictionary containing three major rivers and country each river runs through.
One key-value pair might be 'nile': 'egypt'.
- Use a loop to print a sentence about each river, such as The Nile runs through Egypt.
- Use a loop to print the name of each river included in the dictionary.
- Use a loop to print the name of each counrty included in the dictionary.
'''
rivers = {
'nile': 'egypt',
'missisippi' : 'united states',
'danube': 'germany',
}
for river, country in rivers.items():
print(f'The {river.title()} river flows through {country.title()}. Unbelivable!!') | true |
63d7143b62b0220af036bde631828ee05c811faf | sdaless/psychic-carnival | /Other Files/help.py | 277 | 4.5 | 4 | # Example of Recursion (calculating factorials)
def factorial(num):
# Set the base case (stopping point)
if num == 1:
return 1
# Make the function call itself with a smaller number
else:
return num * factorial(num - 1)
print(factorial(5))
print(factorial(25)) | true |
bdd9b7d7962bfacbb5209b563b81b4324c4c2c64 | sdaless/psychic-carnival | /HW Batch 2/Hw8-pr1.py | 802 | 4.34375 | 4 | #Sara D'Alessandro
#Homework #8
from math import *
print("Hi, welcome to the | Euclidean Algorithm |! To ensure an accurate answer, please make sure your dimensions are the same unit!")
x = int(input("What are the x dimensions of your rectangle? " ))
y = int(input("What are the y dimensions of your rectangle? "))
#Example:
#x = 210, y = 45
#Divide 210 by 45, get result 4 with remainder 30, so 210 = 4 x 45 + 30
#Divide 45 by 30, get result 1 with remainder 15, so 45 = 1 x 30 + 15
#Divide 30 by 15, get result 2 with remainder 0, so 30 = 2 x 15 + 0
#Greatest common divison or 210 and 45 is 15
def euclid(x, y):
if x % y == 0:
return y
return euclid(y, x % y)
print("You should use", euclid(x, y), "tiles.")
#if x < y:
#return x % y
#while
#as long as the remainder is greater than 0...
| true |
d132c8729e8e892e2b8471cbabde5fdf2263e12a | piyushgoyal1620/HacktoberFest2021 | /Python/sort_words_like_dictonary.py | 1,020 | 4.375 | 4 | def sort_words(): #defining the function for sorting the words.
k=1
while k==1: #this condition is used so that the porgram doesnt stop untill all the data has been fed
word=input('Enter the word, leave blank if you want to stop')
#'word' variable stores the word entered by the user
if word=='':
break #if the user want to stop entering the data, they can just press enter and the data entering phase will be over
else:
l.append(word)
print('Enter the order in which you want the Words to be displayed')
#message for the user
order=input('Enter \'A\' for asscending order, \'B\' for decending order')
#'A' is entered for alphabetical order and 'B' for the opposite
if order=='A':
l.sort() #Alphabatical sort
print(l)
if order=='B':
l.sort(reverse=True) #Opposite sort
print(l)
l=[] #the list that will store all the data is the variable 'l'
sort_words() #the function is called
| true |
30144c86739bffa4c834b1c9c414335087c6e1e2 | IanSkyles/Main | /Rice University - Fundamentals of Computing/An Introduction to Interactive Programming in Python (Part 1)/second_GuessTheNumber.py | 2,892 | 4.15625 | 4 | # Ian Skyles
# Mini Project 2: Guess the number
# March 17th, 2015 (3/17/2015)
# input will come from buttons and an input field
# all output for the game will be printed in the console
#imports
import simplegui
import random
secret_number = 0
number_of_guesses = 7
num_range = 100
# helper function to start and restart the game
def new_game():
# initialize global variables
global secret_number
global num_range
global number_of_guesses
# assign secret number based on number range, default range is 0-99
secret_number = random.randrange(0, num_range)
if(num_range == 100):
number_of_guesses = 7
elif(num_range == 1000):
number_of_guesses = 10
print "New game. Range is from 0 to " + str(num_range)
print "Number of remaining guesses is " + str(number_of_guesses)
# define event handlers for control panel
def range100():
# button that changes the range to [0,100) and starts a new game
global num_range
num_range = 100
def range1000():
# button that changes the range to [0,1000) and starts a new game
global num_range
num_range = 1000
def input_guess(guess):
# main game logic here
global number_of_guesses
global num_range
global secret_number
#code assumes variable is an integer, haven't learned how to check if it is yet
guess_to_number = int(guess)
print
print "Guess was " + guess
number_of_guesses = number_of_guesses - 1
if(number_of_guesses == 0):
print "You ran out of guesses. The number was " + str(secret_number)
print
new_game()
else:
if(guess_to_number == secret_number):
print "You guessed the secret number!"
print
new_game()
else:
print "Number of remaining guesses is " + str(number_of_guesses)
if(guess_to_number > secret_number):
print "Guess lower!"
elif(guess_to_number < secret_number):
print "Guess higher!"
else:
print "Error in input_guess"
def button_handler_range_100():
#start a new game with secret number in range 0-99
#handles button clicked events
range100()
print
new_game()
def button_handler_range_1000():
#start a new game with secret number in range 0-999
#handles button clicked events
range1000()
print
new_game()
# create frame
frame = simplegui.create_frame("Guess a number", 200, 200)
#add input listener
inp = frame.add_input("My Number", input_guess, 100)
#add buttons
button1 = frame.add_button('Range 100', button_handler_range_100)
button2 = frame.add_button('Range 1000', button_handler_range_1000)
# register event handlers for control elements and start frame
frame.start()
# call new_game
new_game()
| true |
59ba518aa7eac33e4678a8fef17fbdd9af652544 | JoeKhoa/python_basic_ | /Bài 13- Bài tập rèn luyện-Tính điểm trung bình.mp4/exercise_cal_AVG_score.py | 246 | 4.15625 | 4 | math = float(input("enter the math score"))
physic = float(input("enter the physic score"))
chemical = float(input("enter the chemical score"))
avg = (math+physic+chemical)/3
print("the average score is: ",avg)
print("average is:", round(avg,2)) | true |
1a28317a621f8a8983b8e1540b6e19bc1b2f49c0 | JoeKhoa/python_basic_ | /Bài 45- Bài tập rèn luyện-Tính diện tích tam giác.mp4/Bài 45- Bài tập rèn luyện-Tính diện tích tam giác.mp4.py | 551 | 4.21875 | 4 | from math import sqrt
print('enter the line of triangle : ')
while True:
a = float(input('enter a > 0: '))
b = float(input('enter b > 0: '))
c = float(input('enter c > 0: '))
if a <= 0 or b <= 0 or c <= 0 or (a+b) < c or (a+c) < b or (c+b) < a :
print(" stupid, don't see the alert? huh. enter AGAIN ")
print('*'*30,'AGAIN','*'*30)
continue
else:
p = a + b + c
p_half = p/2
s = sqrt(p_half*(p_half-a)*(p_half-b)*(p_half-c))
print('the area of triangle is: ',s)
break
| false |
20e37d6e24bd101c48efd83f7932cbca6d3247b9 | d1joseph/HackerRank-problem-sets-and-solutions | /Mutations.py | 635 | 4.15625 | 4 | """
Task
Read a given string, change the character at a given index and then print the modified string.
Input Format
The first line contains a string,S.
The next line contains an integer i, denoting the index location and a character, c, separated by a space.
Output Format
Using any of the methods explained above, replace the character at index
with character.
Sample Input
abracadabra
5 k
Sample Output
abrackdabra
"""
def mutate_string(string, position, character):
mutableString = list(string)
mutableString[position] = character
string = ''.join(mutableString)
return string
| true |
418fd8526bead9d5d5915559c56ee3ebe45c3f69 | Victor-Agali/Python-code | /assert.py | 987 | 4.25 | 4 | import unittest
def add_list_element(my_list, element):
"""Appends specified element to specified list,
IF the element is a string that contains only characters, and can not be
empty, have all the characters be spaces, contain any numbers or be already in the list. """
if not element or element.isspace():
print("You have not entered anything!")
elif any(num in element for num in "0123456789"):
print("No numbers can be included in the name.")
elif element.capitalize() not in my_list:
my_list.append(element.capitalize())
print(f"Your choice: {element.capitalize()} was successfully added!")
else:
print("Already on the list. Try a different option.")
return my_list
# def my_list():
# # Arrange
# element = 'Victor'
# list_name = []
# expected = list_name + [element]
# # act
# actual = add_list_element(list_name, element)
# #Assert
# assert expected == actual
# my_list()
| true |
c6458748d95951707e4afaec2d8dbff9bde552e0 | jcohen66/python-sorting | /lists/rev.py | 1,268 | 4.25 | 4 | class ListNode(object):
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def reverse_recursive(head):
# If head is empty or has reached the end
# of the list. BASE CASE
if head is None or head.next is None:
return head
# Reverse the rest of the list after the head.
tail = reverse_recursive(head.next)
# Put first element at the end
head.next.next = head
head.next = None
# Fix the head pointer
return tail
def reverse(root):
if not root or not root.next:
return
prev = None
while root:
next = root.next
root.next = prev
prev = root
root = next
return prev
'''
1 -> 2 -> 3 -> 4 -> None
h
p
c
n
1) next = curr.next
2) curr.next = prev
3) prev = curr
4) curr = next
5) if next == None: head = prev
'''
root = ListNode(1, ListNode(2, ListNode(3, ListNode(4))))
head = reverse(root)
while head:
print(head.value, end=" ")
head = head.next
root = ListNode(1, ListNode(2, ListNode(3, ListNode(4))))
head = reverse_recursive(root)
while head:
print(head.value, end=" ")
head = head.next
| true |
b2c2e1fbc1d3b6806daf2afb800b636889023dd5 | jcohen66/python-sorting | /questions/medium/keypad_string.py | 2,985 | 4.21875 | 4 | import string
def get_key_to_letters():
'''
Create a map
'''
possible_letters = string.ascii_lowercase
possible_keys = string.digits
key_to_letters = {}
start_index = 0
for key in possible_keys:
if key == '0':
key_to_letters[key] = " "
elif key == '1':
key_to_letters[key] = ""
else:
num_letters = 3
if key in {"7", "9"}:
num_letters = 4
letters = possible_letters[start_index: start_index + num_letters]
key_to_letters[key] = letters
start_index += num_letters
return key_to_letters
# Build the map from keys to letters
KEY_TO_LETTERS = get_key_to_letters()
def keypad_string(keys):
'''
Given a string consisting of 0-9,
find the string that is created using
a standard phone keypad.
| 1 | 2 (abc) | 3 (def) |
| 4 (ghi) | 5 (jkl) | 6 (mno) |
| 7 (pqrs) | 8 (tuv) | 9 (wxyz) |
| * | 0 ( ) | # |
You can ignore 1, and 0 corresponds to space
>>> keypad_string("12345")
'adgj'
>>> keypad_string("4433555555666")
'hello'
>>> keypad_string("2022")
'a b'
>>> keypad_string("")
''
>>> keypad_string("111")
''
>>> keypad_string("157")
'jp'
>>> keypad_string("*")
Traceback (most recent call last):
...
AssertionError: Invalid Key
'''
result = ""
count = 0
prev_key = ""
curr_key = ""
valid_keys = set(string.digits)
# Loop through the keys and add the
for curr_key in keys:
assert curr_key in valid_keys, "Invalid Key"
if curr_key == "1":
pass
else:
if not prev_key:
# first key press
prev_key = curr_key
count = 1
else:
# get the map
curr_key_letters = KEY_TO_LETTERS[curr_key]
# press same key
if prev_key == curr_key:
# press X times already
if count == len(curr_key_letters):
# get last key
result += curr_key_letters[-1]
count = 1
# hasn't pressed X times
else:
count += 1
# press different key
else:
prev_letters = KEY_TO_LETTERS[prev_key]
result += prev_letters[count - 1]
prev_key = curr_key
count = 1
# Handle special case where key was pressed
# multiple times but the key wouldnt have changed
# so capture the last keypress.
if curr_key:
curr_key_letters = KEY_TO_LETTERS[curr_key]
# check if there is a mapping for the
# last key pressed.
if len(curr_key_letters) > 0:
result += curr_key_letters[count - 1]
return result
| false |
8c8b91e591ab7ceaf51c2648c7bd0cd580c02495 | jcohen66/python-sorting | /backtracking/flight_itinerary_hash.py | 1,901 | 4.15625 | 4 | '''
Given an unordered list of flights taken by someone, each
represented as (origin, destination) pairs, and a starting
airport, compute the person's itinerary. If no such itinerary
exists, return null. All flights must be used in the itinerary.
For example, given the following list of flights:
HNL ➔ AKL
YUL ➔ ORD
ORD ➔ SFO
SFO ➔ HNL
and starting airport YUL, you should return YUL ➔ ORD ➔ SFO ➔ HNL ➔ AKL.
'''
def is_valid():
'''
Check if solution is invalid if:
1) there are no flights leaving from our last destination
2) there are still flights remaining that can be taken. Since
all flights must be used, we are at a dead end.
:return:
'''
pass
def get_itinerary(flights):
'''
:param flights: List of [origin, destination]
:param current_itinerary: [origin, destination]
:return:
'''
# Base case: If we've used up all the flights, we're done
if not flights or len(flights) == 0:
return
# Load up two dictionaries: one in each direction
dir_flights = {}
rev_flights = {}
for flight in flights:
dir_flights[flight[0]] = flight[1]
rev_flights[flight[1]] = flight[0]
# Find the starting point where a city
# is a starting point but not destination.
starting_point = ''
for origin in dir_flights.keys():
if origin not in rev_flights.keys():
starting_point = origin
break
# Walk the flights from origin to destination.
to = dir_flights[starting_point]
while to is not None:
print(f"{starting_point} -> {to}")
if to not in dir_flights:
break
starting_point = to
to = dir_flights[to]
# driver
flights = []
flights.append(['HNL', 'AKL'])
flights.append(['YUL', 'ORD'])
flights.append(['ORD', 'SFO'])
flights.append(['SFO', 'HNL'])
get_itinerary(flights)
| true |
a60b473f2ec5f372704c11cf45ad66f6d7eab054 | jcohen66/python-sorting | /strings/ascii.py | 873 | 4.34375 | 4 | import string
from timeit import timeit
def is_upper(s):
for letter in s:
if letter not in string.ascii_uppercase:
return False
return True
uppercase_set = set(string.ascii_uppercase)
def is_upper_using_set(s):
for letter in s:
if letter not in uppercase_set:
return false
return True
def is_upper_cleaner(s):
"""
Uses generator and short circuits
:param s:
:return:
"""
return all(letter in uppercase_set for letter in s)
whitespace_set = string.whitespace
def remove_whitespace(s):
return ''.join(letter for letter in s if letter not in whitespace_set)
print(remove_whitespace("HELLO WORLD"))
print(string.ascii_letters)
print(string.punctuation)
print(string.ascii_uppercase)
print(string.ascii_lowercase)
print(string.hexdigits)
print(string.octdigits)
print(string.printable)
| true |
1960ffad5b79a6e3fe8704b6d3289c78f8a0504c | Hoshitter1/Python | /Class/magic_methods/callable.py | 969 | 4.46875 | 4 | """
1. Useful for creating function-like objects that need to maintain state
2. Useful for creating decorator classes
"""
class Partial:
"""
partial from functools like class that calls func of input when called.
"""
def __init__(self, func, *args):
self._func = func
self._args = args
def __call__(self, *args):
print(self._args, *args)
return self._func(*self._args, *args)
def some_func(a, b, c):
return a, b, c
class NotCallable:
pass
if __name__ == '__main__':
partial = Partial(some_func, 1, 2)
print(partial(3))
print('all true because Partial has __call__')
print(f'Partial: {callable(Partial)}')
print(f'callable(partial): {callable(partial)}')
not_callable_instance = NotCallable()
print('instance not true because it has no __call__')
print(f'NotCallable(): {callable(NotCallable)}')
print(f'not_callable_instance: {callable(not_callable_instance)}')
| true |
8115509fd858cb984032c0c56cf265bb45d1412f | azmath2762/letsugradepython | /ASSIGNMENT DAY 8.py | 599 | 4.125 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[4]:
file = open("assignment day 8.txt", "r")
file.write("hi letsupgrade")
file.close()
# In[6]:
def getinput(calculate_arg_fun):
def wrap_function():
print ("entered numbers are :")
x=int(input("enter num1 value"))
y=int(input("enter num1 value"))
calculate_arg_fun(x,y)
return wrap_function
# In[13]:
@getinput
def evenorodd(x,y):
for x in range(x,y):
if x == 237:
print(x)
break;
elif x % 2 == 0:
print(x)
# In[14]:
evenorodd()
# In[ ]:
| false |
50e9625e3ce4563aec9d3fb1fe88c97d29e6bd7b | AndrewNduati/intro_to_programming | /101016/encrypt.py | 1,499 | 4.15625 | 4 | import sys
def open_file(file): #opens file
f=open(file,"r")
text=f.read()
f.close()
return text
def write_file(filename, message): #Writes the files
with open(filename, 'w') as f: #Sets write mode
f.write(message)
f.close()
def encryption (txt,key):
text= open_file(txt)
output= ""
#Convert to Ascii Then Apply Caesar cypher
for i in text:
list_word=ord(i) #ordinance changes the character to it's ASCII value
cy=(list_word+key)%256 #Caesar cypher Encryption as a mathematical expression. %256 because of the ASCII value sets.
output+=chr(cy) #incrementing output. It would have otherwise replaced the value of output. Also chr writes the string output of the Ascii values
return output
def decryption (txt, key):
text= open_file(txt)
key = int(key)
output = ""
for i in text:
output += chr ( (ord(i) - key) % 256)# Because ASCII is limited to 256 characters
return output
#running the program on the Terminal
encrypt_case = sys.argv[3]
private_key = int(sys.argv[2])
if encrypt_case == '--encrypt':
plaintext_file = sys.argv[1]
encrypted_message = encryption(plaintext_file, private_key)
print encrypted_message
write_file(plaintext_file, encrypted_message)
elif encrypt_case == '--decrypt':
ciphertext_file = sys.argv[1]
decrypted_message = decryption(ciphertext_file, private_key)
print decrypted_message
write_file(ciphertext_file, decrypted_message)
else:
print "We don't encrypt such words!!!"
| true |
247bf2fe5460fdd2bff0e9f0373242c8c0569b46 | kjlundsgaard/calculator-1 | /arithmetic.py | 948 | 4.28125 | 4 | def add(num1, num2):
"""addition
adds two numbers and returns the sum
"""
return num1 + num2
def subtract(num1, num2):
"""subtraction
subtracts the second parameter
from first parameter"""
return num1 - num2
def multiply(num1, num2):
"""multiplication
multiplies first parameter by second"""
return num1 * num2
def divide(num1, num2):
""" division
divides first parameter by second parameter"""
return float(num1) / num2
def square(num1):
""" squaring
input multiplied by itself"""
return num1 * num1
def cube(num1):
"""cubing
returns cube of parameter"""
return num1 * num1 * num1
def power(num1, num2):
"""raising to nth power
raise first parameter to power of second"""
return num1 ** num2
def mod(num1, num2):
"""modulo operand
returns the remainder of the first parameter
divided by the second parameter"""
return num1 % num2
| true |
6e652055ed16283761c60acd565a7e59e0326ee0 | amberpang/codes | /medium/largestmul.py | 828 | 4.15625 | 4 | """
Given an integer array nums, find the contiguous subarray within an array
(containing at least one number) which has the largest product. 最大乘积
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
"""
class Solution:
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
maxafter = minafter = res = nums[0]
for i in nums[1:]:
maxhere = max(maxafter * i, minafter * i, i)
minhere = min(maxafter * i, minafter * i, i)
res = max(res, maxhere)
maxafter = maxhere
minafter = minhere
return res | true |
75859a38658dd81664be12a6fb4a57636c70df78 | 935375572/git_learning | /03and04_list_table/add_list.py | 661 | 4.1875 | 4 | """
增加列表元素
append(元素的值) : 在列表末尾添加元素
insert(索引,元素的值) : 在列表中插入元素
"""
bicycless = ["trek","cannondale","redline","speciallized"]
bicycless.append("boy")
print(bicycless)
# 创建空列表非常常见,例如经常要等到程序运行后,才知道用户要在程序中存储哪些数据。可以首先创建一个空列表。用户存储用户
# 输入的值然后将新值加到列表中
bicycless = []
bicycless.append("boy")
bicycless.append("trek")
print(bicycless)
# 使用insert()方法 在列表中插入新元素
bicycless.insert(0,"haohan")
bicycless.insert(1,"hh")
print(bicycless) | false |
41cf52c7e6248a097368054f4372779cfad8d7c8 | KevinB-a/exercise_python | /part2.py | 1,000 | 4.125 | 4 | # exercise1 true or false
variable=""
variable1="OK"
print(bool(variable)) #use function bool for display True or False here display False
print(bool(variable1)) #use function bool for display True or False here display True
#exercice2 calculate my age
actual_year=int(input("please enter current year"))
born_year=int(input("please enter year of birth"))
age=actual_year-born_year
print("Your age is" ,age)
age1=int(input("enter age of your neighboor"))
print(age +age1)
#exercise3 :Shoes issues
shoes=70
jean=59
t_shirt=20
total=(shoes+jean+t_shirt)*(80/100)
print(total)
#exercise4 : mini calculator
number1=float(input("please enter a number"))
number2=float(input("please enter a sencond number"))
print(number1+number2)
#exercise5 : work with property
name=input("please enter your name").upper()
last_name=input("please enter your last name").upper()
letter=name[0]+name[-1]+last_name[0]+last_name[-1]
print(letter)
age=int(input("please enter your age"))
result=int(age/33)
print(result)
| true |
d69dc5bebe613ed0d0bd78971a79c38e4d4dcef1 | SureshEzhumalai/python_excercises | /oopexample/instancevariable.py | 751 | 4.15625 | 4 |
"""
This examples is about instance variable and instance methods
They are nothing but the properties andn functions of the object
"""
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.email = first + '.' + last + '@company.com'
self.pay = pay
def fullname(self):
print(self.first + ' ' + self.last)
emp_1 = Employee('suresh', 'ezhumalai', 5000)
emp_2 = Employee('test', 'user', 6000)
emp_1.fullname()
emp_2.fullname()
# emp_1.first = "Suresh"
# emp_1.last = "Ezhumalai"
# emp_1.email = "Suresh.Ezhumalai@company.com"
# emp_1.pay = 50000
#
# emp_2.first = "Test"
# emp_2.last = "User"
# emp_2.email = "Test.User@company.com"
# emp_2.pay = 6000
# print(emp_1.email)
# print(emp_2.email)
| false |
5aff8b0db5a968a226ddf105216b3c0c1ba621b6 | rnayan78/Hackerrank-Data-Structure-Solution | /Equal Stacks.py | 2,698 | 4.3125 | 4 | """
ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times.
Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of the three stacks until they're all the same height, then print the height. The removals must be performed in such a way as to maximize the height.
Note: An empty stack is still a stack.
Input Format
The first line contains three space-separated integers, , , and , describing the respective number of cylinders in stacks , , and . The subsequent lines describe the respective heights of each cylinder in a stack from top to bottom:
The second line contains space-separated integers describing the cylinder heights in stack . The first element is the top of the stack.
The third line contains space-separated integers describing the cylinder heights in stack . The first element is the top of the stack.
The fourth line contains space-separated integers describing the cylinder heights in stack . The first element is the top of the stack.
Constraints
Output Format
Print a single integer denoting the maximum height at which all stacks will be of equal height.
Sample Input
5 3 4
3 2 1 1 1
4 3 2
1 1 4 1
Sample Output
5"""
#!/bin/python3
import os
import sys
#
# Complete the equalStacks function below.
#
def equalStacks(h1, h2, h3):
sum1, sum2, sum3 = 0, 0, 0
for i in range(n1):
sum1 += h1[i]
for i in range(n2):
sum2 += h2[i]
for i in range(n3):
sum3 += h3[i]
top1 , top2, top3 = 0, 0, 0
ans = 0
while(True):
if(top1 == n1 or top2 == n2 or top3 == n3):
return 0
if (sum1 == sum2 and sum2 == sum3):
return sum1
if (sum1 >= sum2 and sum1 >= sum3):
sum1 -= h1[top1]
top1=top1+1
elif (sum2 >= sum3 and sum2 >= sum3):
sum2 -= h2[top2]
top2=top2+1
elif (sum3 >= sum2 and sum3 >= sum1):
sum3 -= h3[top3]
top3=top3+1
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n1N2N3 = input().split()
n1 = int(n1N2N3[0])
n2 = int(n1N2N3[1])
n3 = int(n1N2N3[2])
h1 = list(map(int, input().rstrip().split()))
h2 = list(map(int, input().rstrip().split()))
h3 = list(map(int, input().rstrip().split()))
result = equalStacks(h1, h2, h3)
print(result)
fptr.write(str(result) + '\n')
fptr.close()
| true |
e636baedccf7169b994f99279db273a83bcb7816 | asifhaider/Numerical-Methods_2-1 | /Bisection Method/main.py | 778 | 4.21875 | 4 | """
Solution to the Assignment on Bisection Method
Author: Md. Asif Haider
Student ID: 1805112
Date: March 19, 2021
"""
import plot as plt
import table
import root
if __name__ == '__main__':
# plotting the function data
plt.plot_function()
# using bisection method (0.001, 0.25 or 0.01, 0.1)
lower_range = input('Input the estimated lower bound of the chosen region!\n')
upper_range = input('Input the estimated upper bound of the chosen region!\n')
print('The root found by bisection method is: ' + str(
root.root_by_bisection(float(lower_range), float(upper_range))))
print("=====================================================")
# printing data in tabular format
table.print_table(float(lower_range), float(upper_range))
| true |
d37f2885864b741f6bf9db9aebce1713946f6fb5 | somasekharreddy1119/DS-Algo-with-python | /Algorithms/sorting/insertion.py | 456 | 4.15625 | 4 | '''
Insertion Sort: Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.
BEST CASE: O(n)
AVG CASE: O(n^2)
WORST CASE: O(n^2)
'''
arr = [5, 6, 1, 7, 0, 4, 12, 10, 9]
n = len(arr)
def insertion(arr,n):
for i in range(1,n):
j = i - 1
key = arr[i]
while key < arr[j] and j >= 0:
arr[j+1] = arr[j]
j = j - 1
arr[j+1] = key
insertion(arr,n)
print(arr) | false |
10bedd8442aee2b91fbaa4fa92ff7b40a574006d | somasekharreddy1119/DS-Algo-with-python | /Algorithms/bit_manipulation/bits_required_to_flip.py | 412 | 4.53125 | 5 | #https://www.geeksforgeeks.org/count-number-of-bits-to-be-flipped-to-convert-a-to-b-set-2/
'''
Count number of bits to be flipped to convert A to B
Approach:
1. compute A ^ B
2. Calculate #set bits in A ^ B
'''
def bits_required_to_flip(a,b):
xor = a ^ b
return bin(xor).count('1')
a = int(input('Enter A:'))
b = int(input('Enter B:'))
count = bits_required_to_flip(a,b)
print(count, 'bits required') | true |
2577e3cb1019fb5dcb1b9e470c5f47ba5183eb42 | achaudhary8299/numberGuessingGame | /new_computer_guessing.py | 1,921 | 4.34375 | 4 | import random
# Part 1: source code for human guessing the secret number created by computer...
# main game function...
def get_guess(x):
guess = 0
random_number = random.randint(1,x)
num_already_entered = False
guess_count = 0
while guess != random_number and guess_count < 3:
guess = int(input(f" Guess the random number between 1 and {x}: "))
if guess < random_number:
if num_already_entered:
print("OOps!! this number was previously entered .. Try different higher number .. ")
else:
num_already_entered = True
print("sorry.. too low... please try higher number")
elif guess > random_number:
if not num_already_entered:
num_already_entered = True
print("sorry.. too high ... please try lower number")
else:
num_already_entered = False
print("OOPS... This number was entered previously.. please try different lower number")
else:
print("Congratulations you have won the game")
break
guess_count += 1
else:
print("Sorry you lost the game")
# function call..
get_guess(x)
# source code for computer guessing the secret number thought by human..
print('''
NOw the game of computer vs human..
''')
def computer_guess(y):
lower_boundary = 1
higher_boundary = y
human_response = ""
while human_response != "correct":
guess = random.randint(lower_boundary, higher_boundary)
human_response = input(f"Is the computer guess of {guess} too High, too Low, or Correct? :").lower()
if human_response == "high":
higher_boundary = guess -1
elif human_response == "low":
lower_boundary = guess +1
print("Yay.. congrats to the computer, you beat the human player...")
computer_guess(y)
| true |
0d1c00a866cc502e41e26425e410c96f1ec11f17 | nasilo/python-practice | /lesson05.py | 1,997 | 4.125 | 4 | def clinic():
print "You've just entered the clinic!"
print "Do you take the door on the left or the right?"
answer = raw_input("Type left or right and hit 'Enter'.").lower()
if answer == "left" or answer == "l":
print "This is the Verbal Abuse Room, you heap of parrot droppings!"
elif answer == "right" or answer == "r":
print "Of course this is the Argument Room, I've told you that already!"
else:
print "You didn't pick left or right! Try again."
clinic()
clinic()
"""
Boolean Operators
------------------------
True and True is True
True and False is False
False and True is False
False and False is False
True or True is True
True or False is True
False or True is True
False or False is False
Not True is False
Not False is True
not is evaluated first;
and is evaluated next;
or is evaluated last.
"""
def using_control_once():
if 10**2 == 100:
return "Success #1"
def using_control_again():
if not False:
return "Success #2"
print using_control_once()
print using_control_again()
answer = "'Tis but a scratch!"
def black_knight():
if answer == "'Tis but a scratch!":
return True
else:
return False # Make sure this returns False
def french_soldier():
if answer == "Go away, or I shall taunt you a second time!":
return True
else:
return False # Make sure this returns False
def greater_less_equal_5(answer):
if answer > 5:
return 1
elif answer < 5:
return -1
else:
return 0
print greater_less_equal_5(4)
print greater_less_equal_5(5)
print greater_less_equal_5(6)
# Make sure that the_flying_circus() returns True
def the_flying_circus():
if "Brian" == "Messiah":
naughty_boy = "Now listen here! He's not the Messiah. He's a very naughty boy!"
print naughty_boy
elif "Woman" <= "Duck" and "Duck" == "Wood":
print "She's a witch!"
else:
return True
| true |
a39bac86d881103f034e8f8b8de33737e3ca11ed | LivMadrid/HW_underpaid_customers | /accounting.py | 2,186 | 4.25 | 4 | melon_cost = 1.00
customer1_name = "Joe"
customer1_melons = 5
customer1_paid = 5.00
customer2_name = "Frank"
customer2_melons = 6
customer2_paid = 6.00
customer3_name = "Sally"
customer3_melons = 3
customer3_paid = 3.00
customer4_name = "Sean"
customer4_melons = 9
customer4_paid = 9.50
customer5_name = "David"
customer5_melons = 4
customer5_paid = 4.00
customer6_name = "Ashley"
customer6_melons = 3
customer6_paid = 2.00
# define melon_cost globally because it may be used in business's program more than just this specfic function
melon_cost = 1.00
# create a function that takes in a text file of customer orders
def customer_acccounting(customer_orders):
""" calculate the amount a customer has either overpaid/underpaid"""
# open a file of customer info -- use pythondocs for help here--- do need to include r or w???
customer_orders= open("customer-orders.txt")
#iterate through each customer order ---name -melons bought- and price paid
for line in customer_orders:
customer_order = line.split('|')
customer_name = customer_order[1]
num_melons = customer_order[2]
melon_cost = customer_order[3]
# define what customer is expected to pay by number of melons purchased multiplied by cost of melons
customer_expected = float(num_melons) * float(melon_cost)
#implement an if statement that will work for any number of customers/values entered - cutting down on repetition of previous code
#add in float so that index[3] gets processed from str --> float
if customer_expected != float(melon_cost):
if customer_expected > float(melon_cost):
#return a statement for Underpaying customers
print(f"{customer_name} paid ${float(melon_cost):.2f},",
f"Customer underpaid for melons! ${customer_expected:.2f}")
else:
#return statement if they overpaid
print(f"{customer_name} paid ${float(melon_cost):.2f},",
f"Customer overpaid for melons! ${customer_expected:.2f}")
else: # return statement if they paid correctly
print(f"{customer_name} paid ${float(melon_cost):.2f},",
f"Customer paid for melons ${customer_expected:.2f}")
| true |
5f54918931521e0c43d9417908d2ddd2c37c4ae7 | coole123/NPTEL_Assignments | /The Joy of Computing using Python/Assignments29_StringSort.py | 451 | 4.21875 | 4 | '''
Write a program that accepts a comma-separated sequence of words as input and prints the words in a comma-separated sequence after sorting them alphabetically.
Input Format:
The first line of input contains words separated by the comma.
Output Format:
Print the sorted words separated by the comma.
Example:
Input:
without,hello,bag,world
Output:
bag,hello,without,world
'''
x=input()
x=list(x.split(","))
x.sort()
print(*x,sep=",",end="")
| true |
2fb57ecac8333fa224660054ff201ca61a0e9016 | b45ch1/taylorpoly | /examples/utps_for_algorithmic_differentiation.py | 929 | 4.5625 | 5 | """
This example shows how Taylor arithmetic can be used to compute derivatives of functions.
To be more specific, we compute here the gradient of a computer program that contains a
for loop in the so-called forward mode of Algorithmic Differentiation.
"""
import numpy
from taylorpoly.utps import UTPS, extract
def f(x, p, y ):
""" some arbitrary function """
N = numpy.size(x)
for n in range(1,N):
y[n] += numpy.sin(x[n-1])**2.3
y[n] *= p
return y
# finite differences
delta = numpy.sqrt(2**-53)
x = numpy.random.rand(100)
y = numpy.zeros(100)
p = 3.
y1 = f(x, p, y)
y = numpy.zeros(100)
y2 = f(x, p + delta, y)
g_fd = (y2 - y1)/delta
# compute on UTPS
x = numpy.array([ UTPS([xn,0.]) for xn in x])
y = numpy.array([ UTPS([0,0]) for xn in x])
p = UTPS([p,1.])
y = f(x, p, y)
g_ad = extract(y,0,1)
print 'comparing FD gradient g_fd and AD gradient g_ad'
print g_fd - g_ad
| true |
ab86c87f37854f58a9cccc745b30d9fecb863b75 | HayatoG/study.py | /strings.py | 1,013 | 4.21875 | 4 | #Aula 05/02/2020
'''
upper()
lower()
len()
replace("str", 'str')
count('str')
find('str')
title()
'''
#upper() - Transforma em maiúscula.
strUP = 'guilherme de souza'
strUP = strUP.upper()
print("Upper:")
print(strUP)
#lower() - Transforma em minúscula.
strLOW = 'GUILHERME DE SOUZA'
strLOW = strLOW.lower()
print("Lower:")
print(strLOW)
#len() - Conta a quantidade de caracteres armazenados, incluindo espaços.
print("Len:")
print('Letras na variavel strUP:',len(strUP))
#replace() - Sobrescreve a primeira palavra com a segunda palavra definida.
strUP = strUP.replace('DE SOUZA', 'OLIVEIRA')
print("Replace:")
print(strUP)
#count() - Conta a quantidade de caracteres definido no código.
print("Count(Letra):")
print(strUP.count('E'))
print("Count(Espaço):")
print(strUP.count(' '))
#find() - Diz a posição da string procurada, começando da posição zero.
print("Find:")
print(strUP.find('E'))
#title() - Função para deixar todas as primeiras letras maiúsculas.
print("Title:")
strLOW = strLOW.title()
print(strLOW) | false |
8808e67c8fba4916ca5a8bf871f04af058896cf2 | alisonlauren/Friyay_Algos_Practice | /answers.py | 2,652 | 4.15625 | 4 | import random
##1. Question One: With the given list below, loop through each name and make them say hello in the terminal.
name_list = ['Rachel', 'Ross', 'Chandler', 'Monica']
def sayHello(list):
for name in list:
print(f" Hi, I'm {name}")
sayHello(name_list)
#or
# for name in name_list:
# print(f" Hi, I'm {name}")
## Your output should look like "Hi, I'm __insert name____ " for each name.
##2. Question Two: With the given list below, create a function that adds one charachter.
name_list2 = ['Rachel', 'Ross', 'Chandler', 'Monica']
def add_character(list, name):
list.append(name)
print(list)
name_list2 = add_character(name_list2, 'ted')
##or
# name_list2.append('ted mosby')
# print(name_list2)
# name_list2.remove(name_list2[0])
# print(name_list2)
##3. Question Three: Create a function that has secret number and asks the user what it is.
## If the user gets the answer wrong, have it print "wrong number", until they guess correctly.
user_input = int(input("Hey user! Can you guess the secret number? "))
def findSecretNum(choice, number):
while number != choice:
if choice > number:
print("aw sorry, you guessed too high")
choice = int(input("Try again? "))
elif choice < number:
print("no way- your number is too small")
choice = int(input("Try again? "))
else:
print("You guessed it!")
findSecretNum(user_input, 33)
# user_input = int(input("Hey user! Can you guess the secret number? "))
# while 33 != user_input:
# if user_input > 33:
# print("aw sorry, you guessed too high")
# user_input = int(input("Try again? "))
# elif user_input < 33:
# print("no way- your number is too small")
# user_input = int(input("Try again? "))
# else:
# print("You guessed it!")
##4. Question 4: Create a Magic Eight Ball. Have the user ask a question, and then create a function that
## will randomly generate "yes", "no", "maybe one day", etc.
user_input1 = input("Ask magic eight ball a question: ")
magic8_answers = ["yes", "no", "not in a million years", "keep dreaming", "oh for sure, you got it", "Knowing you, I don't think so"]
# print(random.choice(magi))
def askMagic(input, list):
while True:
print(random.choice(list))
break
askMagic(user_input, magic8_answers)
user_input2 = input("Ask Lachlan a question: ")
lachlan_answers = ["it depends", "well, it depends", "in that case- it depends", "hmm, depends honestly!"]
def askLachlan(list):
while True:
print(random.choice(list))
break
askLachlan(lachlan_answers)
| true |
bd4d2a2dcc82e6089a07d4efd841338bf0e9aac2 | xzl995/Python | /CourseGrading/3.1.2计算两点之间的距离.py | 864 | 4.25 | 4 | """
【问题描述】编写程序实现计算两点之间的距离
【输入形式】标准输入的四行双精度数据分别表示第一个点的横坐标、第一个点的纵坐标、第二个点的横坐标、第二个点的纵坐标。
【输出形式】标准输出的一行双精度数据表示两点之间的距离。
【样例输入】0.0
0.0
3.0
4.0
【样例输出】5.0
【样例说明】
【提示】
Python中如何计算浮点数f的平方根,答案是调用math模块的sqrt函数,如下:
math.sqrt(f)
要使用math模块(math模块包含有大量数学计算函数),首先要在程序文件头部引入math模块,写法是:
import math
"""
import math
x1 = float(input())
y1 = float(input())
x2 = float(input())
y2 = float(input())
f = (x1-x2)**2+(y1-y2)**2
print(math.sqrt(f))
| false |
a1444c2222ffa545c2aa54df79c839381fa435c8 | xzl995/Python | /CourseGrading/5.1.1求绝对值.py | 385 | 4.15625 | 4 | """
【问题描述】
编写程序,功能是输入一个数,输出该数的绝对值。
【输入形式】
输入一个实数。
【输出形式】
对应输入数的绝对值。
【样例输入】
2.0
【样例输出】
2.0
【样例输出说明】
输出结果时小数点后保留1位。
"""
n = float(input())
if n >= 0:
print("%.1f" % n)
else:
print("%.1f" % -n) | false |
1aa2a8cf7859021013e8baa137d4b96536b4e550 | xzl995/Python | /CourseGrading/9.1.2.5类与对象-两点之间距离.py | 865 | 4.25 | 4 | """
【问题描述】
定义Point类实现三维坐标点。定义dist_from方法实现两点之间距离的计算。
【输入形式】输入两行,第一行是第一个点的坐标值,第二行是第二个点的坐标值。坐标值x, y, z之间用空格隔开。
【输出形式】距离
【样例输入】
0 0 0
1 1 1
【样例输出】
1.73205
"""
import math
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def dist_from(self, p):
dx = self.x - p.x
dy = self.y - p.y
dz = self.z - p.z
return math.sqrt(dx ** 2 + dy ** 2 + dz ** 2)
x1, y1, z1 = input().split()
x1 = float(x1)
y1 = float(y1)
z1 = float(z1)
p1 = Point(x1, y1, z1)
x2, y2, z2 = input().split()
x2 = float(x2)
y2 = float(y2)
z2 = float(z2)
p2 = Point(x2, y2, z2)
print("%.2f" % p1.dist_from(p2))
| false |
e90681df74bfbba89916de2a1983bd2b994e1758 | jfriend08/LeetCode | /BinaryTreeRightSideView.py | 1,019 | 4.25 | 4 | '''
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <---
/ \
2 3 <---
\ \
5 4 <---
You should return [1, 3, 4].
Credits:
Special thanks to @amrsaqr for adding this problem and creating all test cases.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def __init__(self):
self.rightSideArray = []
def travel(self, root, depth):
if root == None:
return
try:
self.rightSideArray[depth] = root.val
except:
self.rightSideArray.append(root.val)
self.travel(root.left, depth+1)
self.travel(root.right, depth+1)
def rightSideView(self, root):
self.travel(root, 0)
return self.rightSideArray;
| true |
14169434d52192c39443a753b2e04b16f53d80b5 | jfriend08/LeetCode | /SortColors.py | 1,240 | 4.1875 | 4 | '''
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent,
with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note:
You are not suppose to use the library's sort function for this problem.
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's, then overwrite array with total number of 0's,
then 1's and followed by 2's.
Could you come up with an one-pass algorithm using only constant space?
'''
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
rc, wc, bc = 0, 0, 0
for num in nums:
if num == 0:
rc += 1
elif num == 1:
wc += 1
elif num == 2:
bc += 1
for i in xrange(len(nums)):
if i < rc:
nums[i] = 0
elif i < rc + wc:
nums[i] = 1
else:
nums[i] = 2
sol = Solution()
arr = [0,1,0,2,0,2,0,2,1,0,2,0,1,2,0,0]
# arr = [1]
print arr
sol.sortColors(arr)
print arr
| true |
3d01c2220bbae4b90d4129a87a02dff3166f721a | jfriend08/LeetCode | /LargestNumber.py | 852 | 4.3125 | 4 | '''
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
'''
class Solution(object):
def largestNumber(self, nums):
struct = []
result = ''
for num in nums:
size = len(str(num))
digit = int(num/10**(size-1))
struct.append((digit,num))
struct = sorted(struct, key = lambda x: (x[0], x[1]), reverse = True)
for (digit, num) in struct:
result += str(num)
return result
if __name__ == "__main__":
test = Solution()
print test.largestNumber([3, 30, 34, 5, 9]) | true |
dfe88273bd47f835c3808b6d7d4cc7613bb55aac | charanbhavaraju2001/assignment | /Stacks_Q2.py | 1,234 | 4.4375 | 4 | #python program to check for balanced paranthesis
def check_balanced_paranthesis(expr):
stack=[]
top= -1
for char in expr:
if char in ["(","{","["]:
#pushing into the stack
#the append function in python is the push() function in stack
#it adds an element to the top of the stack and top is incremented
stack.append(char)
top+=1
else :
top_stack = stack[top]
if char == ")" and top_stack == "(" :
#the pop function in python is the pop() function in stack
#it removes an element from the top of the stack & top is decremented
stack.pop()
top-=1
if char == "}" and top_stack == "{" :
stack.pop()
top-=1
if char == "]" and top_stack == "[" :
stack.pop()
top-=1
if not stack and top == -1:
return True
else :
return False
expr = input("Enter the paranthesis expression")
if check_balanced_paranthesis(expr):
print("Yes, The Given Expression is Balanced")
else :
print("No, The Given Expression is Not Balanced")
| true |
5b6c5221e2af2f90de88f925845bb489199694c3 | Juan-789/Class_Activity_3.6 | /main.py | 616 | 4.25 | 4 | """
Write a program that asks a user for two integers. Print "YES" if exactly one of them is odd and print "NO" otherwise
"""
print("Give me two integers, and I will determine wether one of them is odd or not ")
firstInteger = int(input("Enter the first integer. "))
secondInteger = int(input("Enter the second Integer. "))
#asks the user for two integers to determine which is odd
if firstInteger % 2 == 1 and secondInteger % 2 ==0 or firstInteger % 2 == 0 and secondInteger % 2 ==1:
print ("One of the values is odd")
else:
print ("There is not only one odd value")
#determines wether one of the values is odd | true |
3a0dd4ef7a46194afa100916f1ff2869d79805b8 | Lipe16/Comecando_a_programar_com_Python | /exercicio01.py | 288 | 4.125 | 4 | # -*- coding: UTF-8 -*-
#Faça um programa que receba a idade do usuário e diga se ele é maior ou menor de idade.
idade = int(input("Digite sua idade: "))
if idade >= 18:
print("maior de idade")
elif idade > 0 and idade < 18:
print("menor de idade")
else:
print("idade inválida") | false |
e7fd4093dbdc768e11719dc7496d4bedd509e5ed | Teftelly/CPT | /lab0-1/1-1.py | 529 | 4.125 | 4 | a = float(input("введите а: "))
b = float(input("введите b: "))
c = float(input("введите c: "))
k = float(input("введите k: "))
if (a == 0) or (b == 0):
print("Знаменатель должен быть отличен от нуля")
elif a+b+c*(k-a/(b*b*b)) == 0:
print("Знаменатель должен быть отличен от нуля")
else:
ans = ((a*a)/(b*b)+c*c*a*a)/(a+b+c*(k-a/(b*b*b)))+c+(k/b-k/a)*c
if ans < 0:
ans = -ans
print("Ответ:", ans)
| false |
d83dcca7048f0548b7cfd36609ae36cf9f218b9c | davidchuck08/InterviewQuestions | /src/FractionToRecurringDecimal.py | 2,481 | 4.25 | 4 | #!/usr/bin/python
'''
Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
If the fractional part is repeating, enclose the repeating part in parentheses.
For example,
Given numerator = 1, denominator = 2, return "0.5".
Given numerator = 2, denominator = 1, return "2".
Given numerator = 2, denominator = 3, return "0.(6)".
'''
def fractionalDecimal(numerator, denominator):
if numerator is None or denominator is None:
return 'Input Error'
if denominator == 0:
return 'Input Error: denominator is 0'
if numerator == 0:
return 0
negative=False
if numerator*denominator<0:
negative=True
numList=[]
reminder=dict()
currLoc=0
loopStr=''
while True:
numList.append(str(numerator/denominator))
numerator=10*(numerator%denominator)
currLoc+=1
if numerator in reminder.keys():
preLoc=reminder[numerator]
loopStr=''.join(numList[preLoc:currLoc])
break
else:
reminder[numerator]=currLoc
ans=''
if negative==True:
ans='-'
ans+=numList[0]
if len(numList)>1:
ans+='.'
if len(loopStr)>0:
ans+=''.join(numList[1:len(numList)-len(loopStr)])+'('+loopStr+')'
else:
ans+=''.join(numList[1:])
return ans
'''
def fractionalDecimal(numerator, denominator):
if denominator == 0:
return ''
if numerator == 0:
return '0'
negative=False
if numerator*denominator < 0:
negative=True
numerator=abs(numerator)
denominator=abs(denominator)
numList=[]
reminder=dict()
currLoc=0
loopStr=''
while True:
numList.append(str(numerator/denominator))
numerator=10*(numerator%denominator)
currLoc+=1
if numerator == 0:
break
if numerator in reminder.keys():
preLoc=reminder[numerator]
loopStr=''.join(numList[preLoc:currLoc])
break
else:
reminder[numerator]=currLoc
ans=''
if negative:
ans='-'
ans+=numList[0]
if len(numList)>1:
ans+='.'
if len(loopStr)>0:
ans+=''.join(numList[1:len(numList)-len(loopStr)])+'('+loopStr+')'
else:
ans+=''.join(numList[1:])
return ans
'''
numerator=10
denominator=3
print fractionalDecimal(numerator, denominator) | true |
69889b2fdeec65c526d782e6a7e3e16c9d5f98b0 | davidchuck08/InterviewQuestions | /src/DungeonGame.py | 2,644 | 4.28125 | 4 | #!/usr/bin/python
'''
The demons had captured the princess (P) and imprisoned her in the bottom-right corner of a dungeon.
The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned
in the top-left room and must fight his way through the dungeon to rescue the princess.
The knight has an initial health point represented by a positive integer.
If at any point his health point drops to 0 or below, he dies immediately.
Some of the rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms;
other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).
In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.
For example, given the dungeon below, the initial health of the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.
-2 (K) -3 3
-5 -10 1
10 30 -5 (P)
'''
from matplotlib.sankey import DOWN
def dungeonGame(nums):
col=len(nums[0])
row=len(nums)
hp= [[0 for j in range(col)] for i in range(row)]
hp[row-1][col-1]=max(1-nums[-1][-1], 1)
for i in range(row-1, -1,-1):
for j in range(col-1,-1,-1):
down=None
if i+1 < row:
down=max(1, hp[i+1][j]-nums[i][j])
right=None
if j+1 < col:
right=max(1,hp[i][j+1]-nums[i][j])
if down and right:
hp[i][j]=min(down,right)
elif down:
hp[i][j]=down
elif right:
hp[i][j]=right
return hp[0][0]
'''
def dungeonGame(nums):
col = len(nums)
row = len(nums[0])
hp =[[0 for i in range(row)] for j in range(col)]
hp[row-1][col-1] = max(1-nums[row-1][col-1],1)
for i in range(row-1, -1, -1):
for j in range(col-1, -1, -1):
down = None
if i+1 < row:
down = max(1, hp[i+1][j]-nums[i][j])
right = None
if j+1 < col:
right = max(1, hp[i][j+1]-nums[i][j])
if down and right:
hp[i][j]=min(down, right)
elif down:
hp[i][j] = down
elif right:
hp[i][j] = right
print hp
return hp[0][0]
'''
c1=[-2,-5,10]
c2=[-3,-1,30]
c3=[3,1,-5]
nums = []
nums.append(c1)
nums.append(c2)
nums.append(c3)
print nums
print dungeonGame(nums) | true |
bbd25e87da9c9e304843c8e4d7a201c157aa23ec | hobbitcakes/learning | /Python/linuxacademy/Exercises/file_based_on_user_input.py | 1,049 | 4.28125 | 4 | #!/usr/bin/env python
import os
# https://linuxacademy.com/cp/exercises/view/id/651/module/158
# Prompt the user for the contet that should go in the file. The script should keep accepting lines of text until the user enters an empty line
def this():
# Prompt the user for a file_name where it should write the content
file_name = raw_input("What is the file name we should save this content to?\n")
# If the file exists, exit with an error
if os.path.isfile(file_name):
print("File %s exists, please specify a blank file\n" , file_name)
os._exit(1)
with open(file_name, 'w') as file:
end_of_file = False
file_contents = []
while not end_of_file:
user_input = raw_input("Enter text or a blank line to quit\n")
if user_input:
file_contents.append(user_input)
else:
end_of_file = True
# Write out the file
for line_given in file_contents:
file.write("%s\n" % line_given)
this()
| true |
f554573a7981dfce52da124426b35b62f8071d42 | Vann09/python | /AA_Ejercicios_Python/1H._Ejercicios.py | 680 | 4.21875 | 4 | import math
#### H1. Muestra las siguientes secuencias de número utilizando un WHILE:
# del 1 al 100 DONE
#num = 0
#while num < 100:
# num += 1
# print (num)
# los números impares del 51 al 91 DONE
#num = 50
#while num < 91:
#num += 1
#if (num % 2 != 0):
#print (num)
#num = 49
#while num < 91:
#num += 2
#print (num)
# tabla de multiplicar de PI DONE
#print (f"Tabla de multiplicar de PI")
#print ("===================================")
#count = 0
#while count < 10:
#count += 1
#result = count * math.pi
#print (f" {count:2} x {math.pi:1.5} = {result:2.5}")
# del 20 al 10 multimplicado del 5 a 8, utilizando un FOR
| false |
1acdab587a2446da75b14de2cd5a795a5d4e8e77 | curatorcorpus/FirstProgramming | /Python/Lab Functions.py | 607 | 4.1875 | 4 | #Film critic.py Lab Exercise 4.6 Question 8
def film_critic(movie):
print "Give this movie a rating"
rating = input("Rating: ")
print 'Movie: ', movie, 'Your rating; ', rating
#movie = raw_input("Movie: ")
#print film_critic(movie)
#remove comments to activate
def name_age(name, age):
print "Hello ", name, "you are ", age, "years old."
print "next year you will be, ", age + 1
#name = raw_input("name: ")
def score_summaries(x, y, z):
maximum = max(x, y, z)
minimum = min(x, y, z)
average = (x + y + z)/2
return maximum, minimum, average
| true |
2642bd1dddb5b1242a5c0b19944d7a4c9272b2e6 | curatorcorpus/FirstProgramming | /Python/return functions.py | 518 | 4.15625 | 4 | def print_square_root(x):
if x<0:
print "Error: cannot take square root of a negative number."
return
result = x**0.5
print "The square root of", x, "is ", result
def square_root(x):
if x<0:
print "error"
result = x**0.5
return result
def area_of_circle(radius):
if radius<0:
print "error"
return
area = 3.14159*radius**0.5
return area
def absolute_value(x):
if x=<0:
return -x
return x
| true |
33b7fb1d3e93e71e0b587b76b6d81750f0d11151 | JahnaviPC/Python-Workshop | /MergeTwoListsAndSortIt.py | 543 | 4.1875 | 4 | Python Program to merge two lists and sort it.
a=[]
c=[]
n1=int(input("Enter number of elements:"))
for i in range(1,n1+1):
b=int(input("Enter element:"))
a.append(b)
n2=int(input("Enter number of elements:"))
for i in range(1,n2+1):
d=int(input("Enter element:"))
c.append(d)
new=a+c
new.sort()
print("Sorted list is:",new)
x=0
l=[int(input(x)) for _ in range(int(input("Enter how many elements")))]
m=[int(input(x)) for _ in range(int(input("Enter how many elements ")))]
new=l+m
new.sort()
print("Sorted list is:",new)
| true |
1be2f7e50905a98b62e8c850feb3e73adf43b314 | JahnaviPC/Python-Workshop | /GenerateRandomNoFrom1To20.py | 232 | 4.15625 | 4 | Python Program to generate random numbers from 1 to 20 and append them to the list.
import random
a=[]
n=int(input("Enter number of elements:"))
for j in range(n):
a.append(random.randint(1,20))
print('Randomised list is: ',a)
| true |
f141a9be6b7ebb9cd6bb69ef31ac437c2f458e7d | arunapiravi/problemsets | /move_zeroes.py | 1,207 | 4.125 | 4 | Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
# in-place
def moveZeroes(self, nums):
zero = 0 # records the position of "0"
for i in xrange(len(nums)):
if nums[i] != 0:
nums[i], nums[zero] = nums[zero], nums[i]
zero += 1
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
i = 0
j = 1
while j < len(nums):
if nums[i] == 0 and nums[j] != 0:
# swap
print "swapping {0}, {1}".format(nums[i], nums[j])
nums[i], nums[j] = nums[j], nums[i]
i += 1
j += 1
elif nums[i] == 0 and nums[j] == 0:
# just increment j to swap on next non-zero
j += 1
else:
# no swap needed
i += 1
j += 1
| true |
107f5ed84a58ea81042782dba3cb400183810734 | Dahrio-Francois/ICS3U-Unit2-03-Python | /circumference_of_a_circle.py | 492 | 4.5 | 4 | #!/usr/bin/env python 3
# Created by: Dahrio Francois
# Created on: November 2020
# this program calculates the circumference of a circle using tau
# with user input
import constants
def main():
# this program calculates circumference
# input
radius = int(input("Enter radius of circle (mm): "))
# process
circumference = constants.TAU*radius
# output
print("")
print("Circumference is {}mm^2".format(circumference))
if __name__ == "__main__":
main()
| true |
7ca6b1cbeea6f75f17c4f3a18b6278cde99ef9a2 | donaahasrul/Algoritma_dan_Pemrograman | /Bab 2/27.Algoritma-Gravitasi.py | 649 | 4.125 | 4 | # Tipe Data, Variabel, Nilai, dan Ekspresi,Contoh 3 Halaman 26 - 27
print('Menghitung gaya gravitasi di antara massa')
# Definisi variabel
G = 6.67*10**-11 #newton-m**2/kg**2
# Rincian Langkah
m1 = float(input('Masukkan massa 1 : '))
m2 = float(input('Masukkan massa 2 : '))
m3 = float(input('Masukkan massa 3 : '))
r12 = float(input('Masukkan jarak antara massa-1 dan massas-2 : '))
r13 = float(input('Masukkan jarak antara massa-1 dan massas-3 : '))
r23 = float(input('Masukkan jarak antara massa-2 dan massas-3 : '))\
# Meghitung Gaya Gravitasi
gaya = G*(m1*m2/r12+m1*m3/r13+m2*m3/r23)
print('Besar gaya di antara ketiga massa ini =', gaya) | false |
1118447779cd72a2c2345c284c6c1e758056f967 | storrescano/Python | /P704.py | 503 | 4.375 | 4 | """Escribe un programa que pida una frase, y le pase como parámetro
a una función dicha frase. La función debe sustituir todos los espacios
en blanco de una frase por un asterisco, y devolver el resultado
para que el programa principal la imprima por pantalla.
Sergio Torres Cano
"""
def t(frase):
final=""
for i in range (len(frase)):
if frase[i]==" ":
final+="*"
else:
final+=frase[i]
return final
frase=input("Introduzca una frase: ")
print (t(frase)) | false |
53769e626aa1a6092bfb6560386e2f980602e69d | storrescano/Python | /P605.py | 1,156 | 4.28125 | 4 | """Escribe un programa que te pida números cada vez más grandes y que se guarden en una lista. Para acabar de escribir los números, escribe un número que no sea mayor que el anterior. El programa termina escribiendo la lista de números:
Escribe un número: 6
Escribe un número mayor que 6: 10
Escribe un número mayor que 10: 12
Escribe un número mayor que 12: 25
Escribe un número mayor que 25: 9
Los números que has escrito son: 6, 10, 12, 25 (Comentario si os fijáis ya no se imprime la lista tal cual, hay que imprimir uno por uno los valores de la lista, haced esto así a partir de ahora)
Sergio Torres Cano
"""
numero=int(input("Escribe un número: "))
lista=[numero]
i=0
numero=int(input("Escribe un número mayor que %d: " %(lista[i])))
if numero>lista[i]:
lista+=[numero]
while numero>lista[i]:
i+=1
numero=int(input("Escribe un número mayor que %d: " %(lista[i])))
if numero>lista[i-1]:
lista+=[numero]
print ("Los números escritos son: ", end='')
for i in range(len(lista)):
if i<(len(lista)-1):
print (lista[i], end=', ')
else:
print (lista[i], end='')
| false |
6f9b8b62a237389559b9b4feba32df8fb37d47a4 | prajasek/codewars | /Kata/Alphabetize.py | 341 | 4.21875 | 4 | def alphabet_position(text):
# Replace each letter with their position in the alphabet
# if not an alphabet, then ignore
#
# Input : "abcdz"
# Output : "1 2 3 4 26"
return_string = [str(ord(letter.lower())-96) for letter in text if 1<=ord(letter.lower())-96<=26]
return " ".join(return_string)
| true |
4f6da76cd71fccfd087b9cfa5b5729a936215b84 | larcefox/algo_and_structures_python | /Lesson_2/8.py | 1,297 | 4.15625 | 4 | """
8. Посчитать, сколько раз встречается определенная цифра в введенной
последовательности чисел. Количество вводимых чисел и цифра,
которую необходимо посчитать, задаются вводом с клавиатуры.
"""
NUM_STR = ''
NUM_QUANT = 0
try:
QUANT = int(input('Enter quantity of numbers:\n'))
except ValueError:
print("Data is incorrect!")
for i in range(QUANT):
try:
NUM_STR += str(int(input(f'Enter number {i + 1}:\n')))
except ValueError:
print("Data is incorrect!")
continue
try:
NUM = int(input('Enter seeking number:\n'))
except ValueError:
print("Data is incorrect!")
#-----------------------------------------------------------------
for i in NUM_STR:
if NUM == int(i):
NUM_QUANT += 1
print(f'{NUM}: {NUM_QUANT}')
#------------------------------------------------------------------
NUM_QUANT = 0
NUM_STR = int(NUM_STR)
def seek(num, num_str, num_quant):
if num_str == 0:
return print(f'{num}: {num_quant}')
if num_str % 10 == num:
num_quant += 1
num_str = num_str // 10
seek(num, num_str, num_quant)
seek(NUM, NUM_STR, NUM_QUANT)
| false |
fe37627ff566ea99b77d52602f9a42109b1a71b3 | kjs969/cs327e | /quizzes/Quiz24.py | 401 | 4.125 | 4 | #!/usr/bin/env python
"""
CS327e: Quiz #24 (5 pts)
"""
""" ----------------------------------------------------------------------
1. What is the output of the following program?
(4 pts)
['a', 'b', [4], (5,)]
[2, 3, [4], (5,)]
[2, 3, [4], 6]
[2, 3, 6, (5,)]
"""
def f ((x, y), z = [4], t = (5,)) :
return [x, y, z, t]
print f("ab")
print f([2, 3])
print f((2, 3), t = 6)
print f([2, 3], 6)
| false |
6b19c113b61724a29fcb6df9750fa68a2fe3e7d6 | dcastrocs/CursoPython | /Mundo 1/aula008.py | 576 | 4.25 | 4 | # from math import sqrt #// Aqui importei somente o modulo sqrt da biblioteca math
# nun = int (input('Digite um numero: ')) #// Recebe o numero a descobrir a raiz
# nun = sqrt(nun) #// Aqui calcula a raiz da variavel nun
#print ('A raiz de {} é igual a {}'.format (nun, raiz) #// exibe a raiz para o usuario.
import math
nun = int (input('Digite um numero: '))
raiz = math.sqrt (nun)
print ('A raiz de {} é igual a {}'.format (nun, raiz))
| false |
57bbfccf8efa416676075669756ed4543cc5f3ab | dcastrocs/CursoPython | /Mundo 2/ex053_2.py | 483 | 4.15625 | 4 | frase = str(input('Digite uma frase: ')).strip().upper() # strip retirou os espaços ante e depois e o upper deixa tudo maiusculo
palavras = frase.split() # Aqui a frase digititada foi separada pelo os espaços entra a frase
junto = ''.join(palavras)# Aqui a palavra é unida sem espaços
inverso = junto[::-1]
print(' O inverso de {} é {} '.format(junto, inverso))
if inverso == junto:
print('Temos um palíndromo!')
else:
print('A frase digitada não é um palíndromo!')
| false |
3622544d6b66b4ce3879b5165e375a2c4e332f87 | EKrzych/codecool_projects_python | /Python/2017_12_11_SI/romanre.py | 508 | 4.1875 | 4 | # Write a program which takes a natural number
# (written in Arabic numerals, greater than zero and less than 4000),
# and then prints it in Roman form.
Number = int (input("What's your number?"))
RomanNumber = ""
Arabic = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
Symbols = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"]
a = 0
while Number != 0:
while (Number) >= Arabic[a]:
RomanNumber = RomanNumber+Symbols[a]
Number = Number - Arabic[a]
a=a+1
print (RomanNumber)
| true |
ad6abc14a207c626766155b356065975375cfa9c | EKrzych/codecool_projects_python | /Python/2017_12_18_team_work/minmaxsort.py | 895 | 4.15625 | 4 | # let's practice some algorithms -
# calculate minimum, maximum and average from numbers in list.
# PLEASE DO NOT USE BUILD-IN PYTHON FUNCTIONS TO CALCULATE MIN, MAX, AVG and SORT!!!
Numbers = [-5, 23, 0, -9, 12, 99, 105, -43]
def min_max(Numbers):
i=1
while i < len(Numbers):
j=0
while j<=(len(Numbers)-2):
if Numbers[j] > Numbers[j+1]:
temp = Numbers[j+1]
Numbers[j+1] = Numbers[j]
Numbers[j] = temp
j=j+1
i=i+1
def avg (Numbers):
suma = 0
i=0
while i<len(Numbers):
suma=+Numbers[i]
i+=1
return suma/len(Numbers)
def main():
print(Numbers)
min_max(Numbers)
print ("Min value in Numbers is ", Numbers[0], "Max value in Numbers is ", Numbers[len(Numbers)-1])
average = avg(Numbers)
print ("Avarage in Numbers is ", average)
main() | true |
d4b6a982ea7fc9e91b236cbd260355db214fbf56 | Harshil78/Python | /A3P9.py | 911 | 4.40625 | 4 | english_to_dutch={"last" : "laatst", "week" : "week", "the" : "de", "royal" : "koninklijk",
"festival" : "feest", "hall" : "hal", "saw" : "zaag", "first" : "eerst", "performance" : "optreden",
"of" : "van", "a" : "een", "new" : "nieuw", "symphony" : "symphonie", "by" : "bij", "one" : "een",
"world" : "wereld", "leading" : "leidend", "modern" : "modern", "composer" : "componist",
"composers" : "componisten", "two" : "twee", "shed" : "schuur", "sheds" : "schuren"}
Sentence=input("Enter Sentence which you want to Convert into dutch:")
dutch_Sentence=""
words = list(Sentence.split(' '))
for word in words:
word = word.lower()
if word in english_to_dutch.keys():
dutch_Sentence = dutch_Sentence + english_to_dutch[word] + ' '
else:
dutch_Sentence = dutch_Sentence + word + ' '
print('English Sentence Is :',Sentence)
print('English To Dutch Convert Sentence Is :',dutch_Sentence) | false |
dc0a0e7f79f534e1f7961d0950134118a70f8be4 | adam-formela/Adam-s-repo | /11_OOP_intro/05.py | 987 | 4.21875 | 4 | # Utwórz klasę sklep. Sklep posiada różne produkty. W sklepie można produkt zobaczyc, przymierzyc, kupic, zwrocic.
class Product():
def __init__(self, name, size, cost):
self.name = name
self.size = size
self.cost = cost
def __repr__(self):
return f'{self.name} | {self.size} - {self.cost} PLN'
class Shop():
def __init__(self, products):
self.products = products
def show(self):
print(self.products)
def __repr__(self):
shop_to_text = ''
for prod in self.products:
prod_to_text = Product.__repr__(prod)
shop_to_text += '* ' + prod_to_text + '\n'
return shop_to_text
def try_product(self, index):
print(f'Przymierzam: {self.products[index]}')
p1 = Product('Spodnie 👖', 'L', 90)
p2 = Product('Koszulka 👕', 'M', 100)
p3 = Product('Buty 👟', '38', 120)
fashion_shop = Shop([p1, p2, p3])
fashion_shop.try_product(2)
print(fashion_shop) | false |
64625d68f86e4c3980a6c9540f7d2af9c106ef12 | Popzzy/answers_jymoh | /exercise_2.py | 1,166 | 4.15625 | 4 | num = input('Enter a number and i will tell you if it is \
odd or even \n==> ') # Man i form yauandika
# ivi nmejua saa ii 😜😜😜😜
if int(num) % 2 == 0:
print(str(int(num)) + ' is an even number.') # apa kuna redundacy str(int(num))
# ungeeka tu ivi iacha tu ikiwa num since ni string already
if int(num) % 4 == 0:
print(str(int(num)) + ' is divisible by 4')
else:
print(str(int(num)) + ' is an odd number.')
"""Alternatively"""
# first check if input is number/digit
if num.isdecimal():
if int(num) % 2 == 0:
print(num + ' is an even number.')
if int(num) % 4 == 0:
print(str(int(num)) + ' is divisible by 4')
num2 = input('Enter a number >> ')
num3 = input('Enter another number >> ')
#Not what was expected for this part of the question lazima uangalie kaa number inaweza divide iyo ingine
#
"""if num2 == num3:
print(str(num2) + ' is equal to ' + str(num3) + '.')
else:
print(str(num2) + ' is not divisible by ' + str(num3) )
"""
| false |
76357d4f82f765ef95e7aecdf8db252cff7e0614 | nilesh-hegde/Leetcode | /Print a binary tree.py | 2,609 | 4.21875 | 4 | '''
Print a binary tree in an m*n 2D string array following these rules:
The row number m should be equal to the height of the given binary tree.
The column number n should always be an odd number.
The root node's value (in string format) should be put in the exactly middle of the first row it can be put. The column and the row where the root node belongs will separate the rest space into two parts (left-bottom part and right-bottom part). You should print the left subtree in the left-bottom part and print the right subtree in the right-bottom part. The left-bottom part and the right-bottom part should have the same size. Even if one subtree is none while the other is not, you don't need to print anything for the none subtree but still need to leave the space as large as that for the other subtree. However, if two subtrees are none, then you don't need to leave space for both of them.
Each unused space should contain an empty string "".
Print the subtrees following the same rules.
Example 1:
Input:
1
/
2
Output:
[["", "1", ""],
["2", "", ""]]
Example 2:
Input:
1
/ \
2 3
\
4
Output:
[["", "", "", "1", "", "", ""],
["", "2", "", "", "", "3", ""],
["", "", "4", "", "", "", ""]]
Example 3:
Input:
1
/ \
2 5
/
3
/
4
Output:
[["", "", "", "", "", "", "", "1", "", "", "", "", "", "", ""]
["", "", "", "2", "", "", "", "", "", "", "", "5", "", "", ""]
["", "3", "", "", "", "", "", "", "", "", "", "", "", "", ""]
["4", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]]
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def printTree(self, root: TreeNode) -> List[List[str]]:
list1=[]
d=0
def traverse(node,depth):
nonlocal d
if not node:
return
if depth>d:
d=depth
traverse(node.left,depth+1)
traverse(node.right,depth+1)
traverse(root,0)
s=0
for i in range(d+1):
s+=2**i
list1=[[]]*(d+1)
for i in range(len(list1)):
list1[i]=[""]*s
def fill(node,d,l,r):
nonlocal list1
if not node:
return
list1[d][int((l+r)/2)]=str(node.val)
fill(node.left,d+1,l,int((l+r)/2)-1)
fill(node.right,d+1,int((l+r)/2)+1,r)
fill(root,0,0,s)
return(list1)
| true |
efac96b23daf08832414f54b3f2475b4938827db | nilesh-hegde/Leetcode | /Check completeness of Binary tree.py | 1,902 | 4.125 | 4 | '''
Given a binary tree, determine if it is a complete binary tree.
Definition of a complete binary tree from Wikipedia:
In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Example 1:
https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-1.png
Input: [1,2,3,4,5,6]
Output: true
Explanation: Every level before the last is full (ie. levels with node-values {1} and {2, 3}), and all nodes in the last level ({4, 5, 6}) are as far left as possible.
Example 2:
https://assets.leetcode.com/uploads/2018/12/15/complete-binary-tree-2.png
Input: [1,2,3,4,5,null,7]
Output: false
Explanation: The node with value 7 isn't as far left as possible.
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isCompleteTree(self, root: TreeNode) -> bool:
dict1=dict()
def traverse(node,depth):
if not node:
if depth not in dict1:
dict1[depth]=['null']
else:
dict1[depth]+=['null']
return
if depth not in dict1:
dict1[depth]=[node.val]
else:
dict1[depth]+=[node.val]
traverse(node.left,depth+1)
traverse(node.right,depth+1)
traverse(root,1)
print(dict1)
i=1
while i<=len(dict1)-2:
if 'null' in dict1[i]:
return False
i=i+1
while dict1[len(dict1)-1][-1]=='null':
dict1[len(dict1)-1].pop(-1)
if 'null' in dict1[len(dict1)-1]:
return False
return True
| true |
7b20b77c28976feba654778b7805090d79b8cc0b | Buzz-D/project-euler | /util/prime.py | 2,203 | 4.25 | 4 | import math
def is_prime(number):
if number % 2 == 0 and number != 2:
return False
for i in range(3, math.isqrt(number) + 1, 2):
if number % i == 0:
return False
return True
def find_prime_factors(number, primes):
# Initialize variables
number_temp = number
i = 0
prime_factors = [[], []]
# Loop through all possible/needed primes
while True:
# The maximum prime can be number/2. E.g. 10=2*5 -> 5 is 10/2
if primes[i] > (number / 2):
break
# Test how often the temporary number can be divided by the current prime
number_temp = test_divisibility(number_temp, primes[i], prime_factors)
if number_temp == 1:
break
i += 1
# If the temporary number is larger then 1 at this point the number itself is a prime
if number_temp > 1:
prime_factors[0].append(number)
prime_factors[1].append(1)
return tuple(map(tuple, prime_factors))
def test_divisibility(number, divisor, factors):
i = 0
# Test if the number is divisible by the divisor
if number % divisor == 0:
# As long as the number is divisible do so and count how often this is possible
while number % divisor == 0:
number /= divisor
i += 1
# Add the divisor and the amount how often it divides to the factors
factors[0].append(divisor)
factors[1].append(i)
# Return the new number that was divided
return int(number)
def generate_primes(number):
# Generate a simple list of primes up to the given number
f = open("./prime_numbers.txt", "a")
for i in range(3, number, 2):
if is_prime(i):
f.write("%d," % i)
f.close()
def get_prime_numbers(limit=False):
# Get the current list of primes
# If you only need it till a specific point pass the maximum value as a parameter
f = open("./prime_numbers.txt", "r")
primes = tuple(map(int, f.read().split(",")))
f.close()
if limit:
i = 0
while True:
if (limit + i) in primes:
return primes[: primes.index(limit + i)]
i += 1
return primes
| true |
b735b6cb5d40c3f042bdd70b4dd390896833aedd | Buzz-D/project-euler | /problem_1.py | 594 | 4.34375 | 4 | # 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.
import time
def main():
sum_of_multiples = 0
for i in range(3, 1000):
if i % 3 == 0:
sum_of_multiples += i
continue
elif i % 5 == 0:
sum_of_multiples += i
print("The sum of all multiples of 3 and 5 below 1000 is %d" % sum_of_multiples)
start_time = time.time()
main()
print("The runtime was %.2f seconds" % (time.time() - start_time))
| true |
891c7e10413996b1620fc49877b6d5d6c9402e90 | MrFurtado/python_for_informatics | /chap6/exercise3.py | 325 | 4.1875 | 4 | # accept a word and a letter and count how many times the letter is in the word. Do it in a function
def count(letter, word):
count = 0
for i in word:
if i == letter:
count = count + 1
print count
word = raw_input("Enter a word: ")
letter = raw_input("Enter a letter: ")
count(letter, word)
| true |
277083d35073d4a04bce6a708a5790c5d9fefa7f | Danisdnk/PythonExerciseGuide | /TP2/2.7.py | 760 | 4.28125 | 4 | #Intercalar los elementos de una lista entre los elementos de otra. La intercalación
#deberá realizarse exclusivamente mediante la técnica de rebanadas y no se creará
#una lista nueva sino que se modificará la primera. Por ejemplo, si lista1 = [8, 1, 3]
#y lista2 = [5, 9, 7], lista1 deberá quedar como [8, 5, 1, 9, 3, 7].
#import random
#def crearlista(n):
# lista = []
# for i in range(n):
# lista.append(random.randint(0, 40))
# print(lista)
# return lista
#n = int(input("ingrese la cantidad de valores para la lista"))
lista1= [8, 1, 3]
#lista1 = lista1[1::]
print(lista1)
lista2=[5, 9, 7]
lista1[1:-2] = lista2
print("[8, 5, 1, 9, 3, 7] ")
print(lista1)
#lista2 = crearlista(n)
#lista2[-1:3] = crearlista(n)
#print(lista2) | false |
9909250eec4e8e3001c3ff11d0bdfa013d381704 | Amfeat/euler_project | /14.py | 1,692 | 4.28125 | 4 | #Самая длинная последовательность Коллатца
'''Следующая повторяющаяся последовательность определена для множества натуральных чисел:
n → n/2 (n - четное)
n → 3n + 1 (n - нечетное)
Используя описанное выше правило и начиная с 13, сгенерируется следующая последовательность:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1'''
from time import time
start = time()
def whattime():
print("Time: ", time() - start)
s1 = 13 #стартовое число
l1 = [] # сюда записываем последовательность
def coll(s): #функция расчета последовательности
l=[s] #создаем список, первым элементом будет стартовое число
while s!=1:
if s%2==0:
s=s/2
else:
s=3*s+1
l.append(s)
# print(l)
return(len(l))
#тестируем разные последовательности
'''
coll(3)
coll(10)
coll(11)
coll(15)
coll(19)
coll(23)
'''
def max_coll(s_max): #функция поиска максимально длинной цепочки
#в диапозоне стартовых чисел от 1 до s_max
r_max = 1 #максимальная длина
i_max = 1 #стартовое число для максимальной длины
for i in range(1,s_max,2):
r = coll(i)
if r > r_max:
r_max = r
i_max = i
print(i_max, r_max)
max_coll(1000001)
whattime() | false |
d998a582850b9079383dca3738d216a58dfb91a0 | axd8911/CC189 | /3_4_Queue_via_Stacks.py | 1,033 | 4.25 | 4 | '''
Interesting logics.
Push a item in stack, move all items of this stack to another stack. As a result, the earliest item in stack is now on top, while the newly added one is at the bottom.
'''
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def pop(self):
return self.items.pop()
def push(self,item):
return self.items.append(item)
def peek(self):
return self.items[-1]
class MyQueue:
def __init__(self):
self.popstack = Stack()
self.pushstack = Stack()
def pop(self):
while not self.pushstack.isEmpty():
self.popstack.push(self.pushstack.pop())
return self.popstack.pop()
def push(self,item):
while not self.popstack.isEmpty():
self.pushstack.push(self.popstack.pop())
self.pushstack.push(item)
return self.pushstack
def isEmpty():
return self.popstack.isEmpty()
a = MyQueue()
a.push(1)
a.push(2)
a.push(3)
a.push(4)
a.push(5)
print (a.pop())
print (a.pop())
print (a.push(6))
print (a.pushstack.items)
| true |
c7d92c4e17826eada8852d293f73077559a4271c | axd8911/CC189 | /3_1_Three_in_One.py | 782 | 4.21875 | 4 | '''
Three lists in one list... This is easy in Python
'''
class ThreeInOneStack:
def __init__(self):
self.num = 3
self.items = [[] for i in range(self.num)]
def isEmpty(self):
return self.items == []
def pop(self,stack_index):
return self.items[stack_index].pop()
def push(self,stack_index,item):
return self.items[stack_index].append(item)
def peek(self,stack_index):
return self.items[stack_index][-1]
def display(self):
return self.items
def main():
multiple_stack = ThreeInOneStack()
multiple_stack.push(0,5)
multiple_stack.push(0,9)
multiple_stack.push(1,8)
multiple_stack.push(2,6)
multiple_stack.push(2,77)
multiple_stack.push(1,51)
multiple_stack.push(0,58)
multiple_stack.pop(0)
print (multiple_stack.display())
main()
| false |
a870f35d561696dc34bfc072e1487ab9044c29f6 | shweta2425/ML-Python | /Week2/List8.py | 318 | 4.25 | 4 | # Write a Python program to find the list of words that are longer than n from a given list of words
from Week2.Utilities import utility
class List8:
lst=["I am Learning Python ML and it's very interesting"]
size = int(input("Enter size"))
obj = utility.User.CalLength(size, lst)
print(obj)
| true |
b968d3f559c2be11ee9d20738ac887ae00089f38 | shweta2425/ML-Python | /Week1/Program6.py | 356 | 4.3125 | 4 | # Write a Python program to calculate number of days between two dates.
# Sample dates : (2014, 7, 2), (2014, 7, 11)
# Expected output : 9 days
from datetime import date
f_date = date(2020, 7, 2)
l_date = date(2020, 7, 11)
# return difference with datetime timedelta instance
delta = l_date - f_date
# print day portion of date as an int
print(delta.days) | true |
b22ec61427da726518d36509a910cd000a2cc942 | shweta2425/ML-Python | /Week2/String1.py | 1,211 | 4.3125 | 4 | # 1. Write a Python program to calculate the length of a string.
from Week2.Utilities import utility
class String1:
flag = True
while flag:
print("\n1.Calculate length of str")
print("0.Exit")
try:
choice = int(input("Enter ur choice"))
if choice == 0 or choice == 1:
if choice == 1:
try:
string = input("\nPlease enter your name")
CheckStr = utility.User.CheckString(string)
if CheckStr:
length = utility.User.CheckLen(string)
print("\nLength of the string", string, "is :", length)
else:
raise ValueError
except ValueError:
print("\nPlease enter only characters")
if choice == 0:
flag = False
else:
raise ValueError
except ValueError:
print("\nPlease give valid input")
print("Try again.....")
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.