blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
0d7273d3c8f1599fa823e3552d5dfe677f2eb37b | AdarshMarakwar/Programs-in-Python | /Birthday Database.py | 1,456 | 4.15625 | 4 | import sys
import re
birthday = {'John':'Apr 6','Robert':'Jan 2','Wayne':'Oct 10'}
print('Enter the name:')
name=input()
if name in birthday.keys():
print('Birthday of '+name+' is on '+birthday[name])
else:
print('The name is not in database.')
print('Do you want to see the entire databse?')
reply=input()
if reply=='yes':
for names,bdate in birthday.items():
print('Birthday of '+names+' is on '+bdate)
print('Would you like to include '+name+' in database?')
answer=input()
if answer=='yes':
print('Enter the birthdate of '+name)
birthdate=input()
# matching birthdate pattern
birthdayRegex=re.compile(r'\w+\s\d\d')
while birthdayRegex.search(birthdate) is None or birthdate[0].islower():
print('The pattern of birthdate is : \w+\s\d\d. \nFor example Oct 06 is a valid pattern.')
print('Please enter the correct pattern birthdate of '+name+' .')
birthdate=input()
birthday[name]=birthdate
else:
birthday[name]=birthdate
print('Enter the correct name:')
name=input()
while name in birthday.keys():
print('Birthday of '+name+' is on '+birthday[name])
sys.exit()
while name not in birthday.keys():
print('Name '+name+' not in database.')
sys.exit() | true |
f6f745b08e14bb8d912565e1efecf3bbf9a437a1 | mnk343/Automate-the-Boring-Stuff-with-Python | /partI/ch3/collatz.py | 321 | 4.1875 | 4 | import sys
def collatz(number):
if number%2 :
print(3*number+1)
return 3*number+1
else:
print(number//2)
return number//2
number = input()
try :
number = int(number)
except ValueError:
print("Please enter integer numbers!!")
sys.exit()
while True:
number = collatz(number)
if number == 1:
break
| true |
34ce2cbc18f6a937592da46d748ce032e709cfa4 | Rusvi/pippytest | /testReact/BasicsModule/dictionaries.py | 867 | 4.125 | 4 | #Dictionaries (keys and values)
# simple dictionary
student = {
"name": "Mark",
"student_id": 15163,
"feedback": None
}
#Get values
print(student["name"])# = Mark
#print(student["last_name"]) KeyError if there is no key
#avoid by get("key","default value")
print(student.get("last_name","Unknown_key"))# = Unknown_key
#get keys
print(student.keys())# returns list of keys
#get values
print(student.values())# returns list of values
#Change value
student["name"] = "James"
print(student)
#deleting keys
del student["name"]
print(student)
#List of dictionaries
all_students = [
{"name": "Mark", "student_id": 15163,"feedback": None},
{"name": "Katarina", "student_id": 63112,"feedback": None},
{"name": "Jessica", "student_id": 30021,"feedback": None}
]
for s in all_students:#itterate through dictionary list
print(s)# print(s["name"])
| true |
0eb8624cbe3c84cfbeeb7c3494e271fb00bfb726 | SchoBlockchain/ud_isdc_nd113 | /6. Navigating Data Structures/Temp/geeksforgeeks/geeksforgeeks_BFS_udacity.py | 1,679 | 4.3125 | 4 | # Program to print BFS traversal from a given source
# vertex. BFS(int s) traverses vertices reachable
# from s.
from collections import defaultdict
# This class represents a directed graph using adjacency
# list representation
class Graph:
# Constructor
def __init__(self):
# default dictionary to store graph
self.graph = defaultdict(list)
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
# Function to print a BFS of graph
def BFS(self, s):
# Mark all the vertices as not visited
# visited = [False]*(len(self.graph))
visited = defaultdict(bool) #because node could be of any label, not just integer
# Create a frontier for BFS
frontier = []
# Mark the source node as visited and enfrontier it
frontier.append(s)
visited[s] = True
# if frontier is empty, quit
while frontier:
# Defrontier a vertex from frontier and print it
s = frontier.pop(0)
print(s)
# Get all adjacent vertices of the defrontierd
# vertex s. If a adjacent has not been visited,
# then mark it visited and enfrontier it
for i in self.graph[s]:
if visited[i] == False:
frontier.append(i)
visited[i] = True
# Driver code
# Create a graph given in the above diagram
g = Graph()
g.addEdge('A', 'B')
g.addEdge('A', 'C')
g.addEdge('B', 'C')
g.addEdge('C', 'A')
g.addEdge('C', 'D')
g.addEdge('D', 'D')
print("Following is Breadth First Traversal (starting from vertex 2)")
g.BFS('C') | true |
4599cd49493f9376018cee225a14f139fd9c316f | m-tambo/code-wars-kata | /python-kata/counting_duplicate_characters.py | 1,112 | 4.21875 | 4 | # https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1/train/python
# Write a function that will return the count of distinct
# case-insensitive alphabetic characters and numeric digits
# that occur more than once in the input string.
# The input string can be assumed to contain only
# alphabets (both uppercase and lowercase) and numeric digits.
def duplicate_count(text):
characters = list(text.upper())
char_set = set()
duplicate_set = set()
count = 0
for char in characters:
x = char.upper()
if not x in char_set:
char_set.add(x)
elif not x in duplicate_set:
count += 1
duplicate_set.add(x)
return count
if __name__ == '__main__':
print(str(duplicate_count("abcde")) + " should equal 0")
print(str(duplicate_count("abcdea")) + " should equal 1")
print(str(duplicate_count("indivisibility")) + " should equal 1")
print(str(duplicate_count("Indivisibilities")) + " should equal 2")
print(str(duplicate_count("aA11")) + " should equal 2")
print(str(duplicate_count("ABBA")) + " should equal 2")
| true |
39dd901b68ac263934d07e52ace777357d37edbc | ProgrammingForDiscreteMath/20170828-karthikkgithub | /code.py | 2,881 | 4.28125 | 4 | from math import sqrt, atan, log
class ComplexNumber:
"""
The class of complex numbers.
"""
def __init__(self, real_part, imaginary_part):
"""
Initialize ``self`` with real and imaginary part.
"""
self.real = real_part
self.imaginary = imaginary_part
def __repr__(self):
"""
Return the string representation of self.
"""
return "%s + %s i"%(self.real, self.imaginary)
def __eq__(self, other):
"""
Test if ``self`` equals ``other``.
Two complex numbers are equal if their real parts are equal and
their imaginary parts are equal.
"""
return self.real == other.real and self.imaginary == other.imaginary
def modulus(self):
"""
Return the modulus of self.
The modulus (or absolute value) of a complex number is the square
root of the sum of squares of its real and imaginary parts.
"""
return sqrt(self.real**2 + self.imaginary**2)
def sum(self, other):
"""
Return the sum of ``self`` and ``other``.
"""
return ComplexNumber(self.real + other.real, self.imaginary + other.imaginary)
def product(self, other):
"""
Return the product of ''self'' and ''other''.
"""
return ComplexNumber(self.real*other.real - self.imaginary*other.real, self.real*other.imaginary - self.imaginary*imaginary.real)
def complex_conjugate(self):
"""
Return the complex conjugate of self.
The complex conjugate of a complex number is the same real part and opposite sign of its imaginary part.
"""
self.imaginary = -self.imaginary
class NonZeroComplexNumber(ComplexNumber):
def __init__(self, real_part, imaginary_part):
"""
Initialize ``self`` with real and imaginary parts after checking validity.
"""
if real_part == 0 and imaginary_part == 0:
raise ValueError("Real or imaginary part should be nonzero.")
return ComplexNumber.__init__(self, real_part, imaginary_part)
def inverse(self):
"""
Return the multiplicative inverse of ``self``.
"""
den = self.real**2 + self.imaginary**2
return NonZeroComplexNumber(self.real/den, -self.imaginary/den)
def polar_coordinates(self):
"""
Return the polar co-ordinates of ''self''.
The polar coordinates is (r, theta), in which r = sqrt(x**2 + y**2) and theta = atan(y/x)
"""
return sqrt(self.real**2 + self.imaginary**2), atan(self.imaginary/self.real)
def logarithm(self):
"""
Return the logarithm of ''self''
The logarithm is log(r) + theta i
"""
return log(self.polar_coordinates()[0]) + self.polar_coordinates()[1]
| true |
aef037a891c81af4f75ce89a534c7953f5da6f57 | christian-million/practice-python | /13_fibonacci.py | 653 | 4.1875 | 4 | # 13 Fibonacci
# Author: Christian Million
# Started: 2020-08-18
# Completed: 2020-08-18
# Last Modified: 2020-08-18
#
# Prompt: https://www.practicepython.org/exercise/2014/04/30/13-fibonacci.html
#
# Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
# Take this opportunity to think about how you can use functions.
# Make sure to ask the user to enter the number of numbers in the sequence to generate.
# (Hint: The Fibonnaci seqence is a sequence of numbers where the next number in the sequence
# is the sum of the previous two numbers in the sequence. The sequence looks like this: 1, 1, 2, 3, 5, 8, 13, …)
| true |
88157f9c38fd2952634c6a17f987d0d1a5149965 | git-uzzal/python-learning | /genPrimeNumbers.py | 579 | 4.21875 | 4 | def isPrime(n):
for num in range(2,n):
if n % num == 0:
return False
return True
def get_valid_input():
''' Get valid integer more than equal to 3'''
while(True):
try:
num = int(input('Enter a number: '))
except:
print("I dont undersand that")
continue
else:
if num < 3:
print("Number must be more than 2")
continue
else:
break
return num
print('This program generates all the less than a given number')
n = get_valid_input()
print('List of prime number less than', n, 'are:')
for num in range(2,n):
if isPrime(num):
print(num)
| true |
e5d7cde3aa799b147de8bb6a5ff62b308cac45d5 | ruchit1131/Python_Programs | /learn python/truncate_file.py | 896 | 4.1875 | 4 | from sys import argv
script,filename=argv
print(f"We are going to erase {filename}")
print("If you dont want that hit Ctrl-C")
print("If you want that hit ENTER")
input("?")
print("Opening file")
target=open(filename,'w')
print("Truncating the file.")
target.truncate()#empties the file
print("Write 3 lines")
line1=input("line 1:")
line2=input("line2 :")
line3=input("line3 :")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
#target.write(f"{line1}{line2}{line3}") can also be used
print("Andfinally we close it")
#print(target.read()) error: io.UnsupportedOperation: not readable
target.close()
#now to read the file
target=open(filename)
print(target.read())
# modes
#w for writing r for reading and a for append a+ for reading and writing
#open() opens in read mode default
| true |
d636b023af3f4e570bef64a37a4dbb5a162bd6db | chavarera/codewars | /katas/Stop gninnipS My sdroW.py | 1,031 | 4.34375 | 4 | '''
Stop gninnipS My sdroW!
Write a function that takes in a string of one or more words, and returns the same string,
but with all five or more letter words reversed (Just like the name of this Kata).
Strings passed in will consist of only letters and spaces.
Spaces will be included only when more than one word is present.
Examples:
spinWords( "Hey fellow warriors" ) => returns "Hey wollef sroirraw"
spinWords( "This is a test") => returns "This is a test"
spinWords( "This is another test" )=> returns "This is rehtona test"
other Answers:https://www.codewars.com/kata/5264d2b162488dc400000001/solutions/python
'''
#By Ravishankar chavare( Github: @chavarera)
def spin_words(sentence):
return " ".join([text[::-1] if len(text)>4 else text for text in sentence.split(" ")])
result=spin_words("Weme ddgggg trere")
print(result)
'''
spinWords( "Hey fellow warriors" )
=> returns "Hey wollef sroirraw"
spinWords( "This is a test")
=> returns "This is a test"
spinWords( "This is another test" )
=> returns "This is rehtona test"
'''
| true |
1b081dfc115a840dde956934dbab0ee5f3b41891 | harshaghub/PYTHON | /exercise.py | 457 | 4.15625 | 4 | """Create a list to hold the to-do tasks"""
to_do_list=[]
finished=False
while not finished:
task = input('enter a task for your to-do list. Press <enter> when done: ')
if len(task) == 0:
finished=True
else:
to_do_list.append(task)
print('Task added')
"""Display to-do list"""
print()
print('your to-do list: ')
print('-' * 16)
for task in to_do_list:
print(task)
| true |
f4bd846af010b1782d0e00da64f0fdf4314e93ba | mikikop/DI_Bootcamp | /Week_4/day_3/daily/codedaily.py | 700 | 4.1875 | 4 | choice = input('Do you want to encrypt (e) or decrypt (d)? ')
cypher_text = ''
decypher_text = ''
if choice == 'e' or choice == 'E':
e_message = input('Enter a message you want to encrypt: ')
#encrypt with a shift right of 3
for letter in e_message:
if ord(letter) == 32:
cypher_text += chr(ord(letter))
else:
cypher_text += chr(ord(letter)+3-26)
print(cypher_text)
elif choice == 'd' or choice == 'D':
d_message = input('Enter a message you want to decrypt: ')
#decrypt
for letter in d_message:
if ord(letter) == 32:
decypher_text += chr(ord(letter))
else:
decypher_text += chr(ord(letter)-3+26)
print(decypher_text)
else:
print("Sorry that's not an option. Retry!")
| true |
25e86fc49773801757274ede8969c27c68168747 | mikikop/DI_Bootcamp | /Week_4/day_5/exercises/Class/codeclass.py | 1,542 | 4.25 | 4 | # 1 Create a function that has 2 parameters:
# Your age, and your friends age.
# Return the older age
def oldest_age(my_age,friend_age):
if my_age > friend_age:
return my_age
return friend_age
print(oldest_age(34,23))
# 2. Create a function that takes 2 words
# It must return the lenght of the longer word
def longest_word(word1, word2):
if len(word1) > len(word2):
return word1
else:
return word2
print(longest_word('toto', 'longest word'))
# 3. Write the max() function yourself...
def max(my_list):
for i in range(0,len(my_list)-1):
for j in range(0,len(my_list)-1):
if my_list[i] >= my_list[j]:
big = my_list[i]
else:
big = my_list[j]
return big
print(max([1,5,43,2,7]))
print(max([1,5,43,2,7,-3]))
print(max([-1,-5,-43,-2,-7]))
# 4. Create a function that takes a list as an argument
# The list should contain any number of entries.
# each entry should have a name and grade
# return the name of the person with the highest grade
def highest_grade(my_list):
for key in my_list:
for key2 in my_list:
if my_list[key]>my_list[key2]:
name = key
else:
name = key2
return name
print(highest_grade ({'mike':40,'jon':60,'dina':90}))
# Example with default argument
def say_happy_birthday(name, age, from_name=None):
print(f"Happy Birthday {name}! You are {age} years old.")
if from_name is not None:
print(f"From {from_name}") | true |
aff2134f2e4a76a59dc2d99184a548e17f290de0 | LStokes96/Python | /Code/teams.py | 945 | 4.28125 | 4 | #Create a Python file which does the following:
#Opens a new text file called "teams.txt" and adds the names of 5 sports teams.
#Reads and displays the names of the 1st and 4th team in the file.
#Create a new Python file which does the following:
#Edits your "teams.txt" file so that the top line is replaced with "This is a new line".
#Print out the edited file line by line.
teams_file = open("teams.txt", "w")
teams_1 = str(input("Name a team: "))
teams_2 = str(input("Name a team: "))
teams_3 = str(input("Name a team: "))
teams_4 = str(input("Name a team: "))
teams_5 = str(input("Name a team: "))
teams_file.write(teams_1 + "\n")
teams_file.write(teams_2 + "\n")
teams_file.write(teams_3 + "\n")
teams_file.write(teams_4 + "\n")
teams_file.write(teams_5 + "\n")
teams_file.close()
teams_file = open("teams.txt", "r")
print(teams_file.readline())
teams_file.readline()
teams_file.readline()
print(teams_file.readline())
teams_file.close() | true |
58d75067e577cf4abaafc6e369db8da6cf8e7df1 | FL9661/Chap1-FL9661 | /Chap3-FL9661/FL9661-Chap3-3.py | 2,254 | 4.5 | 4 | # F Lyness
# Date 23 Sept 2021
# Lab 3.4.1.6: the basics of lists #
# Task: use a list to print a series of numbers
hat_numbers = [1,2,3,4,5]
#list containing each number value known as an element
print ('There once was a hat. The hat contained no rabbit, but a list of five numbers: ', hat_numbers [0], hat_numbers [1], hat_numbers [2], hat_numbers [3], 'and', hat_numbers [4])
# prints each element value using its index numeber
hat_numbers [3] = input('Please assign new number value: ')
# step 1 prompt the user to replace the middle element value
del hat_numbers [-1]
# removes the last element from the list (Step 2)
print ('number of list entries is: ', len(hat_numbers))
#outputs to the console number of elements within the list
# Lab 3.4.1.13: the Beatles #
# step 1 create an empty list named beatles;
beatles = [] # name of list = [] empty element container
print('Step 1:', beatles) # Outputs list elemetns to console
# step 2 - Add first memebr elements
beatles.append('John Lennon') #0
beatles.append('Paul McCartney') #1
beatles.append('George Harrison') #2
print('Step 2:', beatles) # Outputs list elemetns to console
# step 3 - input new memebr elements
a = input ('enter Pete Best: ')
b = input ('enter Stu Sutcliffe: ')
for i in beatles:
if a == ('Pete Best'):
beatles.append (a)
if b == ('Stu Sutcliffe'):
beatles.append (b)
print('Step 3:', beatles)
break
# step 4 - remove old memebr elements
del beatles [4] # Del George Harrison
del beatles [3] # Del Stu Sutcliffe
#Step 5
beatles.insert(0, 'Ringo Star')
print('step 4:', beatles)
# Lab 3.6.1.9 - copying uniques numbers to a new list
Forename = input('Please enter your Forename: ') # users firstname
Surname = input('Please enter your Forename: ') # users surname
mylist = [1, 2, 4, 4, 1, 4, 2, 6, 2, 9]#current list
newlist = [] #new blank list
print('Hello', Forename, Surname, 'I have taken your old list that contained')
print('these values ', mylist, '.', '\n', '\n', sep='' )
for i in mylist: #for numbers within mylist
if i not in newlist: #if i is unique not in newlist
newlist.append (i) # add i to new list
print('I have made a new list that has', (len(newlist)), 'unique instances. These instances are:')
print (newlist) | true |
6c68a4b129524de39ef050160decd697dfec5a86 | sigrunjm/Maximum-number | /maxnumb.py | 471 | 4.4375 | 4 |
num_int = int(input("Input a number: ")) # Do not change this line
# Fill in the missing code
#1. Get input from the user
#2. if number form user is not negative print out the largest positive number
#3. Stop if user inputs negative number
max_int = 0
while num_int > 0:
if num_int > max_int:
max_int = num_int
num_int = int(input("Input a number: ")) # Do not change this line
print("The maximum is", max_int) # Do not change this line
| true |
28962e9e8aaa5fb3ce7f67f8b4109c426fed0f65 | yaseenshaik/python-101 | /ints_floats.py | 539 | 4.15625 | 4 | int_ex = 2
float_ex = 3.14
print(type(float_ex))
# Float/normal division
print(3 / 2) # 1.5
# Floor division
print(3 // 2) # gives 1
# Exponent
print(3 ** 2) # 9
# Modulus
print(3 % 2) # 1
# priorities - order of operations
print(3 + 2 * 4) # 11
# increment
int_ex += 1
print(int_ex)
# round (takes a integer for decimal)
print(round(3.75, 1)) # 3.8
# comparison
print(int_ex == float_ex)
# same for !=, >, <, >=, <=
# typecasting
hund = '100'
# print(hund + int_ex) # Will throw error
print(int(hund) + int_ex)
| true |
dae861a719ced79a05da501c28302a2452395924 | abercrombiedj2/week_01_revision | /lists_task.py | 493 | 4.4375 | 4 | # 1. Create an empty list called `task_list`
task_list = []
# 2. Add a few `str` elements, representing some everyday tasks e.g. 'Make Dinner'
task_list.append("Make my bed")
task_list.append("Go for a run")
task_list.append("Cook some breakfast")
task_list.append("Study for class")
# 3. Print out `task_list`
print(task_list)
# 4. Remove the last task
task_list.pop()
# 5. Print out `task_list`
print(task_list)
# 6. Print out the number of elements in `task_list`
print(len(task_list)) | true |
a430e9bb28ae56dfe1309b2debbfff29b73a41b8 | milincjoshi/Python_100 | /95.py | 217 | 4.40625 | 4 | '''
Question:
Please write a program which prints all permutations of [1,2,3]
Hints:
Use itertools.permutations() to get permutations of list.
'''
import itertools
l = [1,2,3]
print tuple(itertools.permutations(l)) | true |
fac3f0586e4c82f66a35d23b3ec09640da8dab44 | milincjoshi/Python_100 | /53.py | 682 | 4.6875 | 5 | '''
Define a class named Shape and its subclass Square.
The Square class has an init function which takes a length as argument.
Both classes have a area function which can print the area of the shape
where Shape's area is 0 by default.
Hints:
To override a method in super class, we can define a method with the
same name in the super class.
'''
class Shape():
def __init__(self):# constructor
pass
def area(self):
return 0
class Square(Shape):
def __init__(self, length):
Shape.__init__(self)# calling super constructor
self.length = length
def area(self):
return self.length**2
square = Square(5)
print square.area() | true |
2822a1bdf75dc41600d2551378b7c533316e6a86 | milincjoshi/Python_100 | /45.py | 318 | 4.25 | 4 | '''
Question:
Write a program which can map() to make a list whose elements are square of elements in [1,2,3,4,5,6,7,8,9,10].
Hints:
Use map() to generate a list.
Use lambda to define anonymous functions.
'''
#print map([x for x in range(1,11)], lambda x : x**2)
print map( lambda x : x**2,[x for x in range(1,11)]) | true |
bc2efffa5e46d51c508b6afa2f5deda322a77765 | milincjoshi/Python_100 | /28.py | 247 | 4.15625 | 4 | '''
Question:
Define a function that can receive two integral numbers in string form and compute their sum and then print it in console.
Hints:
Use int() to convert a string to integer.
'''
def sum(a,b):
return int(a)+int(b)
print sum("2","4") | true |
9de6d50bce515e0003aaff576c3c92d04b162b9d | chandanakgd/pythonTutes | /lessons/lesson6_Task1.py | 1,513 | 4.125 | 4 | '''
* Copyright 2016 Hackers' Club, University Of Peradeniya
* Author : Irunika Weeraratne E/11/431
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
'''
'''
TASK 1:
add dict dictionary object to myList
sort array by index
select first 4 elements
sort it by name
print the list
'''
#Answer
dict = {'id':4, 'name': 'Amare'} #This is a dictionary in Python which is similar data structure like 'struct' in C
print 'id :', dict['id'] #Extract 'id' from the dictionary 'a'
print 'name :', dict['name'] #Extracted 'name' from the dictionary 'a'
myList = [
{'id':2, 'name':'Bhagya'},
{'id':1, 'name':'Irunika'},
{'id':7, 'name':'Tharinda'},
{'id':3, 'name':'Ruchira'},
{'id':6, 'name':'Namodya'},
{'id':5, 'name':'Menaka'}
]
myList.append(dict) #add dict dictionary object to myList
myList.sort(key=lambda x:x['id']) #Sort array by index
myList_new = myList[0:4] #select first 4 elements
myList_new.sort(key=lambda item:item['name']) #sort it by name
#print the list
for item in myList_new:
print item
| true |
6a0c9526c14dd7fb71a9ba8002d3673e7da8b29b | yangzhao1983/leetcode_python | /src/queue/solution225/MyStack.py | 1,512 | 4.125 | 4 | from collections import deque
class MyStack(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.q1 = deque()
self.q2 = deque()
def push(self, x):
"""
Push element x onto stack.
:type x: int
:rtype: None
"""
while len(self.q1) > 0:
self.q2.append(self.q1.popleft())
self.q1.append(x)
def pop(self):
"""
Removes the element on top of the stack and returns that element.
:rtype: int
"""
top = self.q1.popleft()
while len(self.q2)> 1:
self.q1.append(self.q2.popleft())
self.q1, self.q2 = self.q2, self.q1
return top
def top(self):
"""
Get the top element.
:rtype: int
"""
return self.q1[0]
def empty(self):
"""
Returns whether the stack is empty.
:rtype: bool
"""
return len(self.q1) == 0 and len(self.q2) == 0
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
def test1():
my_stack = MyStack()
my_stack.push(1)
my_stack.push(2)
my_stack.push(3)
print(my_stack.top())
print(my_stack.pop())
print(my_stack.top())
print(my_stack.pop())
print(my_stack.empty())
if __name__ == '__main__':
test1() | true |
a657612ac1dbce789b2f2815e631ffad2a8de060 | AlexMazonowicz/PythonFundamentals | /Lesson2.1/solution/urlvalidator_solution.py | 1,040 | 4.28125 | 4 | import requests
def validate_url(url):
"""Validates the given url passed as string.
Arguments:
url -- String, A valid url should be of form <Protocol>://<hostmain>/<fileinfo>
Protocol = [http, https, ftp]
Hostname = string
Fileinfo = [.html, .csv, .docx]
"""
protocol_valid = True
valid_protocols = ['http', 'https', 'ftp']
valid_fileinfo = ['.html', '.csv', '.docx']
#first split the url to get protocol
protocol = url.split("://")[0]
if protocol not in valid_protocols:
protocol_valid = False
fileinfo_valid = False
for finfo in valid_fileinfo:
if url.endswith(finfo):
fileinfo_valid = True
# both protocol and fileinfo should be valid to return true.
if protocol_valid and fileinfo_valid:
return True
else:
return False
#take home solution
def get_url_response(url):
r = requests.get(url)
if r.status_code == 200:
return r.text
else:
return r.status_code
if __name__ == '__main__':
url = input("Enter an Url: ")
print(validate_url(url))
| true |
79a2b5f3b7e3594ed0137ed3f0d12912f15e6d6f | mulus1466/raspberrypi-counter | /seconds-to-hms.py | 302 | 4.15625 | 4 | def convertTime(seconds):
'''
This function converts an amount of
seconds and converts it into a struct
containing [hours, minutes, seconds]
'''
second = seconds % 60
minutes = seconds / 60
hours = minutes / 60
Time = [hours, minutes, second]
return Time
| true |
45d1a3a08d68b4f7f24f36b9dc01f505ee715004 | JamesSG2/Handwriting-Conversion-Application | /src/GUI.py | 1,998 | 4.40625 | 4 | #tkinter is pre-installed with python to make very basic GUI's
from tkinter import *
from tkinter import filedialog
root = Tk()
#Function gets the file path and prints it in the command
#prompt as well as on the screen.
def UploadAction(event=None):
filename = filedialog.askopenfilename()
print('Selected:', filename)
myLabel1 = Label(root, text=filename)
myLabel1.grid(row=1,column=0)
#function specifies actions that take place on the click of myButton
def myClick():
#prints the user input from the entry box.
mylabel2 = Label(root, text="retrieving data for: " + e.get())
mylabel2.grid(row=4,column=0)
#creates button that calls function myClick
myButton = Button(root, text="type your name", command = myClick)
myButton.grid(row=2, column=0)
#entry box for user's name when adding images to program
e = Entry(root, width=50)
e.grid(row=3, column =0)
#very simple button that calls the upload action Function
button = Button(root, text='Upload a sample', command=UploadAction, width=40)
button.grid(row=0, column=0)
#-----------------------------------------------------------------------------------------
#hand used when the user wants to type a sentece and see the ai output
def hand():
#function prints the string that the user wants converted.
def sentence():
mylabel3 = Label(root, text="your sentece is: " + entry2.get())
mylabel3.grid(row=4,column=1)
#Button and corrisponding entry box that obtains characters to be converted.
myButton3 = Button(root, text="now type your desired characters", command=sentence)
myButton3.grid(row=2, column=1)
entry2 = Entry(root, width=50)
entry2.grid(row=3, column=1)
#the name of the person who wants to type and see their generated handwriting
button2 = Button(root, text="recive handwriting, type your name below", command=hand)
button2.grid(row=0, column=1)
entry = Entry(root, width=50)
entry.grid(row=1, column=1)
root.mainloop()
| true |
fcfe2cc13a4f75d0ea9d47f918a7d53e3f8495df | cs-fullstack-2019-fall/python-basics2f-cw-marcus110379 | /classwork.py | 1,610 | 4.5 | 4 | ### Problem 1:
#Write some Python code that has three variables called ```greeting```, ```my_name```, and ```my_age```. Intialize each of the 3 variables with an appropriate value, then rint out the example below using the 3 variables and two different approaches for formatting Strings.
#1) Using concatenation and the ```+``` and 2) Using an ```f-string```. Sample output:
#YOUR_GREETING_VARIABLE YOUR_NAME_VARIABLE!!! I hear that you are YOUR_MY_AGE_VARIABLE today!
#greeting = "hello"
#my_name = "marcus"
#my_age = 39
#print(f"{greeting} {my_name}!!! I hear that you are {my_age} today")
#print(greeting + " " + my_name + "!!! I hear that you are " + str(my_age) + " today")
### Problem 2:
#Write some Python code that asks the user for a secret password. Create a loop that quits with the user's quit word. If the user doesn't enter that word, ask them to guess again.
userInput = input("enter a password")
userInput2 = input("enter password again")
while userInput != userInput2 and userInput2 != "q":
userInput2 = input("enter password again or q to quit")
### Problem 3:
#Write some Python code using ```f-strings``` that prints 0 to 50 three times in a row (vertically).
#for i in range(0, 50 +1, 1):
# print(f"{i} {i} {i}")
### Problem 4:
#Write some Python code that create a random number and stores it in a variable. Ask the user to guess the random number. Keep letting the user guess until they get it right, then quit.
#import random
#randomNum = random.randint(1, 10 + 1)
#userInput = 0
#while userInput != randomNum:
# userInput = int(input("guess the random number"))
| true |
3763ee2e94ab64e04a0725240cdc3a7a6990a3ad | yz398/LearnFast_testing | /list_module/max_difference.py | 1,314 | 4.125 | 4 | def max_difference(x):
"""
Returns the maximum difference of a list
:param x: list to be input
:type x: list
:raises TypeError: if input is not a list
:raises ValueError: if the list contains a non-float or integer
:raises ValueError: if list contains +/-infinity
:return: the maximum difference of adjacent numbers
:rtype: float
"""
try:
import logging
from math import fabs
except ImportError:
print("Necessary imports failed")
return
logging.basicConfig(filename='max_difference.log', filemode='w',
level=logging.DEBUG)
if type(x) is not list:
logging.error("Input is not a list")
raise TypeError()
curr_max = 0.0
for index, entry in enumerate(x):
try:
num = float(entry)
except ValueError:
print("your input has a invalid value: {}".format(entry))
return None
if num == float('inf') or num == float('-inf'):
logging.warning("List contains infinities")
raise ValueError()
if index > 0:
diff = fabs(entry - x[index-1])
curr_max = max(curr_max, diff)
logging.info("Returning the maximum difference")
return curr_max
| true |
70276b8e585bd6299b8e9a711f5271089f25ab04 | BenjaminLBowen/Simple-word-frequency-counter | /word_counter.py | 938 | 4.25 | 4 | # Simple program to list each word in a text that is entered by the user
# and to count the number of time each word is used in the entered text.
# variable to hold users inputed text
sentence= input("Type your text here to count the words: ")
# function to perform described task
def counting_wordfunc(sentence):
# variable and dictionary used in the function
new_sentence= sentence.split()
counting_words= {}
# the part of the function that adds words to the dictionary and counts
# each time the word is used
for word in new_sentence:
if word not in counting_words:
counting_words[word] = 1
else:
counting_words[word] += 1
# returns the value of the completed dictionary
return counting_words
# prints a line to tell the user what is to folow
print("Here is a count of each word in the text you entered:")
# prints the result of the function
print(counting_wordfunc(sentence))
| true |
c7b32d7c040304d87a25b09008f6045d0d5d304b | rj-fromm/assignment3b-python | /assignment3b.py | 530 | 4.375 | 4 | # !user/bin/env python3
# Created by: RJ Fromm
# Created on: October 2019
# This program determines if a letter is uppercase or lowercase
def main():
ch = input("Please Enter a letter (uppercase or lowercase) : ")
if(ord(ch) >= 65 and ord(ch) <= 90):
print("The letter", ch, "is an uppercase letter")
elif(ord(ch) >= 97 and ord(ch) <= 122):
print("The letter", ch, "is a lowercase letter")
else:
print(ch, "is Not a lowercase or Uppercase letter")
if __name__ == "__main__":
main()
| true |
27b16e6ee0cbd9477fc99475382e5e8e95d1efb7 | gautamdayal/natural-selection | /existence/equilibrium.py | 2,379 | 4.28125 | 4 | from matplotlib import pyplot as plt
import random
# A class of species that cannot reproduce
# Population is entirely driven by birth and death rates
class Existor(object):
def __init__(self, population, birth_rate, death_rate):
self.population = population
self.birth_rate = birth_rate
self.death_rate = death_rate
# Updates population based on birth and death rates
def update(self):
if random.randint(0, 100) < self.birth_rate:
self.population += 1
for organism in range(self.population):
if random.randint(0, 100) < self.death_rate:
self.population -= 1
# Returns the predicted equilibrium value based on our equation
def getEquilibrium(self):
return(self.birth_rate/self.death_rate)
# Takes three arguments: number of cycles, whether to plot equilibrium, whether to plot mean
def plotPopulation(self, cycles, with_equilibrium = False, with_mean = False):
Y = []
for cycle in range(cycles):
self.update()
Y.append(self.population)
plt.ylim(0, 5 * self.getEquilibrium())
plt.plot(Y, label='Population')
if with_mean:
mean = sum(Y)/len(Y)
plt.plot([mean for i in range(cycles)], label = 'Mean population')
if with_equilibrium:
plt.plot([self.getEquilibrium() for i in range(cycles)], label = 'Predicted equilibrium')
plt.xlabel('Cycles')
plt.ylabel('Number of organisms')
plt.legend()
plt.show()
# A more realistic child class of Species as organisms can replicate
class Replicator(Existor):
def __init__(self, population, birth_rate, death_rate, replication_rate):
Existor.__init__(self, population, birth_rate, death_rate)
self.replication_rate = replication_rate
# Inherited from Existor but modified to include a replication rates
def update(self):
Existor.update(self)
for organism in range(self.population):
if random.randint(0, 100) < self.replication_rate:
self.population += 1
def getEquilibrium(self):
return(self.birth_rate/(self.death_rate - self.replication_rate))
raindrop = Existor(0, 100, 10)
pigeon = Replicator(3, 10, 5, 3)
# raindrop.plotPopulation(500, True, True)
pigeon.plotPopulation(500, True, True)
| true |
1a5f5335e97941b5797ba92bc13877e4a73acd00 | markagy/git-one | /Mcq_program.py | 1,487 | 4.25 | 4 | # Creating a class for multiple choice exam questions.Each class object has attribute "question" and "answer"
class Mcq:
def __init__(self, question, answer):
self.question = question
self.answer = answer
# Creating a list of every question
test = [
"1.How many sides has a triangle?\n (a) 1\n (b) 2\n (c) 3\n\n",
"2.How many sides has a rectangle?\n (a) 3\n (b) 4\n (c) 5\n\n",
"3.How many sides has a hexagon?\n (a) 1\n (b) 5\n (c) 6\n\n",
"4.What is the total internal angle of a Triangle?\n (a) 120\n (b) 180\n (c) 360\n\n",
"5.A square has the same sides as a rectangle?\n (a) True\n (b) False\n (c) None\n\n",
]
# Creating a list that contains object of the class with attributes to serve as a marking scheme
marking_scheme = [
Mcq(test[0], "c"),
Mcq(test[1], "b"),
Mcq(test[2], "c"),
Mcq(test[3], "b"),
Mcq(test[4], "a")
]
#Defining function that marks test with the marking scheme
def mark_script(marking_scheme):
print("\n\nEND OF SEMESTER EXAMS\nType the letter that corresponds to your answer!!\n\n")
score = 0
for obj in marking_scheme:
answer = input(obj.question)
if answer == obj.answer:
score += 1
print("\nYou got " + str(score) + "/" + str(len(test)) + " correct!")
if score < 3:
print("Sorry you need to take the exam again!!")
else:
print("Congratulations, you can proceed to the next class")
mark_script(marking_scheme)
| true |
a3e8cfb8a4f8f7765e9088883440d151e6d972d5 | nagios84/AutomatingBoringStuff | /Dictionaries/fantasy_game_inventory.py | 767 | 4.1875 | 4 | #! python3
# fantasy_game_inventory.py - contains functions to add a list of items to a dictionary and print it.
__author__ = 'm'
def display_inventory(inventory):
total_number_of_items = 0
for item, quantity in inventory.items():
print(quantity, item)
total_number_of_items += quantity
print("Total number of items: " + str(total_number_of_items))
def add_to_inventory(inventory, items_to_add):
for item in items_to_add:
inventory[item] = inventory.get(item, 0) + 1
def main():
inventory = {'gold coin': 42, 'rope': 1}
dragon_loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
add_to_inventory(inventory, dragon_loot)
display_inventory(inventory)
if __name__ == "__main__":
main()
| true |
017b0543fd031602af8129b05cd6567ce67fc5db | AnuraghSarkar/DataStructures-Algorithms_Practice | /queue.py | 1,671 | 4.53125 | 5 | class queue:
def __init__(self):
self.items = []
def enqueue(self, item):
"""
Function to add item in first index or simply enqueue.
Time complexity is O(n) or linear. If item is added in first index all next items should be shifted by one.
Time depends upon list length.
"""
self.items.insert(0, item)
def dequeue(self):
"""
It removes and return the first element which is added in a list or last item in list.
Time complexity is O(1) or constant since it works on last index only.
"""
if self.items:
return self.items.pop()
return None
def peek(self):
"""
Return last element in list or front-most in queue that is going to be deleted next.
Time complexity is O(1)
"""
if self.items:
return self.items[-1]
return None
def size(self):
"""
Return length of the queue. Time complexity O(1).
"""
return len(self.items)
def is_empty(self):
"""
Check if queue is empty or not. O(1).
"""
if self.items:
return 'not empty!'
return 'empty!'
my_queue = queue()
my_queue.enqueue('apple')
my_queue.enqueue('banana')
my_queue.enqueue('orange')
print(f'My queue order is {my_queue.items}.')
print(f'Removing the first item you inserted in list that is {my_queue.dequeue()}.')
print(f'The item going to be deleted next is {my_queue.peek()}.')
print(f'My queue order is {my_queue.items}.')
print(f'The size of queue is {my_queue.size()}.')
print(f'My queue status is {my_queue.is_empty()}.')
| true |
a29f06832bf4caa10f1c8d4141e96a7a50e55bb9 | YashMali597/Python-Programs | /binary_search.py | 1,180 | 4.125 | 4 | # Binary Search Implementation in Python (Iterative)
# If the given element is present in the array, it prints the index of the element.
# if the element is not found after traversing the whole array, it will give -1
# Prerequisite : the given array must be a sorted array
# Time Complexity : O(log n)
# Space complexity : O(1)
#defining the iterative function
def binary_search(array: list, n: int):
low = 0
high = len(array) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
# checking if n is present at mid
if array[mid] < n:
low = mid + 1
# If n is greater, compare to the right of mid
elif array[mid] > n:
high = mid - 1
# If n is smaller, compared to the left of mid
else:
return mid
# element was not present in the array, return -1 (standard procedure)
return -1
# example array
array = [2, 3, 4, 10, 12, 24, 32, 39, 40, 45, 50, 54]
n = 3
# calling the binary search function
result = binary_search(array, n)
if result != -1:
print("Element is present at index", result)
else:
print("Element is not present in given array")
| true |
d089562243b35b8be2df3c31888518a235858c43 | xiaoying1990/algorithm_stanford_part1 | /merge_sort.py | 2,293 | 4.53125 | 5 | #!/usr/bin/python3
import random
def merge_sort(ar):
"""
O(n*log(n)), dived & conquer algorithm for sorting array to increasing order.
:param ar: type(ar) = 'list', as a array of number.
:return: None, while sorting the parameter 'arr' itself. We can change it, because list is mutable.
"""
arr = ar[:]
def merge(begin, end, mid):
"""
The key function which merge two adjacent pieces of arr into a sorted one.
This function uses a copy list: arr[begin:end + 1].
first piece: arr[begin:mid + 1]
second piece: arr[mid + 1:end + 1]
:param begin: the beginning index of the first piece of list in arr
:param end: the last index of the second piece of list in arr
:param mid: the last index of the first piece of list in arr
:return: None, with the sorting change of arr[begin:end + 1]
"""
i, j, k = 0, mid + 1 - begin, begin # i and j means the index of the two pieces in arr_copy.
arr_copy = arr[begin:end + 1] # k is for resetting value from arr_copy to arr.
while i <= mid - begin and j <= end - begin:
if arr_copy[i] <= arr_copy[j]:
arr[k], k, i = arr_copy[i], k + 1, i + 1
else:
arr[k], k, j = arr_copy[j], k + 1, j + 1
while i <= mid - begin:
arr[k], k, i = arr_copy[i], k + 1, i + 1
while j <= end - begin:
arr[k], k, j = arr_copy[j], k + 1, j + 1
def merge_sort_for_arr(begin=0, end=len(arr) - 1):
if begin == end:
return
mid = (begin + end) // 2
merge_sort_for_arr(begin, mid)
merge_sort_for_arr(mid + 1, end)
merge(begin, end, mid)
merge_sort_for_arr()
return arr
def test():
l = list(random.randint(0 * i, 100) for i in range(50000))
random.shuffle(l)
print('the list l: {}'.format(l))
l_sorted = sorted(l)
l_sorted2 = merge_sort(l)
print('using built-in function sorted: {}'.format(l_sorted))
print('list l after applying merger_sort: {}'.format(l_sorted2))
print('Does these the same result? {}'.format(l_sorted2 == l_sorted))
print('Does these the same list object? {}'.format(l_sorted2 is l_sorted))
if __name__ == '__main__':
test()
| true |
0e48b82567ddcd2eabacdb0c1a4fb514f0e97eb7 | darwinini/practice | /python/avgArray.py | 655 | 4.21875 | 4 | # Program to find the average of all contiguous subarrays of size ‘5’ in the given array
def avg(k, array):
avg_array = []
for i in range(0, len(array) - k + 1):
sub = array[i:i+k]
sum, avg = 0, 0
# print(f"The subarray is {sub}")
for j in sub:
sum+= j
avg = sum / 5
avg_array.append(avg)
return avg_array
def main():
# test our avg function
k = 5
a = [1, 3, 2, 6, -1, 4, 1, 8, 2]
print(f"The input array is {a}, with k = {k}")
print(f"The averaged array is {avg(k,a)}")
print(f"the complexity for this algorithm is O(N*K) time | O(N) Space")
main()
| true |
0c0718a685533344d5fea9cfdf1ec9d925dbdcd9 | Surya0705/Number_Guessing_Game | /Main.py | 1,407 | 4.3125 | 4 | import random # Importing the Random Module for this Program
Random_Number = random.randint(1, 100) # Giving our program a Range.
User_Guess = None # Defining User Guess so that it doesn't throw up an error later.
Guesses = 0 # Defining Guesses so that it doesn't throw up an error later.
while(User_Guess != Random_Number): # Putting a while loop and telling Program to stop if Guess is Correct.
User_Guess = int(input("Enter the Guess: ")) # Taking the input from the User.
Guesses += 1 # Adding 1 per Guess.
if(User_Guess == Random_Number): # Telling the Program what to do if the Guess is Correct.
print("CORRECT! You Guessed it Right!") # Printing the Greetings if the guess is Correct.
else: # Putting an Else Condition so that the Program knows what to do in case the Guessed Number is not Correct.
if(User_Guess >= Random_Number): # In case if the User Guess is smaller than Random Number.
print("You guessed it Wrong! Enter a Smaller Number...") # Telling the user what to do.
else: # Putting an Else Condition so that the Program knows what to do in case the User guess is greater that Random Number.
print("You guessed it Wrong! Enter a Larger Number...") # Telling the User what to do.
print(f"You were able to guess the Number in {Guesses} Guesses!") # Printing the final output that you Guessed the Number in __ Number of Times. | true |
16d1c6a7eca1df4440a78ac2f657a56fa1b8300b | bnew59/sept_2018 | /find_largest_element.py | 275 | 4.21875 | 4 |
#Assignment: Write a program which finds the largest element in the array
# def largest_element(thing):
# for num in thing:
# if num + 1 in
# elements = [1, 2, 3, 4]
a=[1,2,3,4,6,7,99,88,999]
max = a[0]
for i in a:
if i > max:
max=i
print(max) | true |
c64b1e0c45ea4de9c2195c99bfd3b22ab2925347 | Samyak2607/CompetitiveProgramming | /Interview/postfix_evaluation.py | 1,133 | 4.15625 | 4 | print("For Example : abc+* should be entered as a b c + *")
for _ in range(int(input("Enter Number of Test you wanna Test: "))):
inp=input("Enter postfix expression with space: ")
lst=inp.split(" ")
operator=['+','-','/','*','^']
operands=[]
a=1
for i in lst:
if(i not in operator):
operands.insert(0,i)
else:
if(len(operands)>=2):
num1=operands.pop(0)
num2=operands.pop(0)
num1=int(num1)
num2=int(num2)
if(i=='*'):
operands.insert(0,num2*num1)
elif(i=='/'):
operands.insert(0,num2/num1)
elif(i=='+'):
operands.insert(0,num2+num1)
elif(i=='-'):
operands.insert(0,num2-num1)
elif(i=='^'):
operands.insert(0,num2**num1)
else:
print("Not Valid")
a=0
if(a==1):
if(len(operands)!=1):
print("Not valid")
else:
print(operands[0])
| true |
d5bcb62f24c54b161d518ac32c4a2434d01db76e | PaLaMuNDeR/algorithms | /Coding Interview Bootcamp/16_linked_list.py | 1,665 | 4.25 | 4 | """
Return the middle node of a Linked list.
If the list has an even number of elements, return the node
at the end of the first half of the list.
DO NOT use a counter variable, DO NOT retrieve the size of the list,
and only iterate through the list one time.
Example:
const l = LinkedL()
l.insertLast('a')
l.insertLast('b')
l.insertLast('c')
midpoint(l) -> { data: 'b' }
"""
class Node:
def __init__(self, data=None):
self.data = data
self.nextval = None
class LinkedList:
def __init__(self):
self.head = None
def insertLast(self, newdata):
NewNode = Node(newdata)
if self.head is None:
self.head = NewNode
return
last = self.head
while last.nextval:
last = last.nextval
last.nextval = NewNode
def listprint(self):
printval = self.head
while printval:
print(printval.data)
printval = printval.nextval
def midpoint(linkedL):
"""
We create two iterators.
One is jumping one step at a time
The other is jumping two steps at a time.
If in front of the second iterator the next 2 values are None,
then the first iterator has reached the midpoint
"""
head = linkedL.head
i = linkedL.head
j = linkedL.head
while j:
if j.nextval and j.nextval.nextval:
i = i.nextval
j = j.nextval.nextval
else:
return i.data
linkedL = LinkedList()
node1 = Node('a')
linkedL.head = node1
# print(linkedL.head.nextval.data)
linkedL.listprint()
print "Answer"
print midpoint(linkedL) | true |
edbbd4fe3fc4a8646c52d70636369ff1c1c23bd5 | PaLaMuNDeR/algorithms | /Coding Interview Bootcamp/10_capitalize.py | 2,096 | 4.28125 | 4 | import timeit
""" Write a function that accepts a string. The function should
capitalize the first letter of each word in the string then
return the capitalized string.
Examples:
capitalize('a short sentence') -> 'A Short Sentence'
capitalize('a lazy fox') -> 'A Lazy Fox'
capitalize('look, it is working!') -> 'Look, It Is Working!'
"""
def capitalize_move_index(str):
"""
Find a space, set index var to it and update the next char
Time: 16 sec.
"""
index = 0
str = str[index].upper() + str[index + 1:]
index = index + str[index + 1:].find(' ') + 1
while index < len(str):
str = str[0:index] + ' ' + str[index+1].upper() + str[index+2:]
next_space = str[index+1:].find(' ')
if not next_space == -1:
index = index + next_space + 1
else: break
return str
def capitalize_with_array(str):
"""
Split to array of words.
Convert the first letter of each to capital.
Join all the words
Time: 9 sec.
"""
index = 0
words = []
for word in str.split(' '):
words.append(word[0].upper() + word[1:])
return (' ').join(words)
def capitalize_after_space(str):
"""
Before you find a space, make the next character UpperCase
Time: 32 sec.
"""
result = str[0].upper()
for i in range(1, len(str)):
if str[i-1] == ' ':
result += str[i].upper()
else:
result += str[i]
return result
# print(capitalize_after_space('a short sentence') )
# print(capitalize_after_space('a lazy fox'))
# print(capitalize_after_space('look, it is working!'))
a_string = 'amanaplana canal panama' * 10
print "Method 1 - Find a space, set index var to it and capitalize after"
print min(timeit.repeat(lambda: capitalize_move_index(a_string)))
print "Method 2 - Split to array of words"
print min(timeit.repeat(lambda: capitalize_with_array(a_string)))
print "Method 3 - Capitalize everything after space"
print min(timeit.repeat(lambda: capitalize_after_space(a_string)))
| true |
52cf1f1b5914447294ae9eb29b40abaa5086f644 | PaLaMuNDeR/algorithms | /Algo Expert/113_group_anagrams.py | 894 | 4.34375 | 4 | """
Group Anagrams
Write a function that takes in an array of strings and returns a list of groups of anagrams.
Anagrams are strings made up of exactly the same letters, where order doesn't matter.
For example, "cinema" and "iceman" are anagrams; similarly, "foo" and "ofo" are anagrams.
Note that the groups of anagrams don't need to be ordered in any particular way.
Sample input: ["yo", "act", "flop", "tac", "cat", "oy", "olfp"] Sample output: [["yo", "oy"], ["flop", "olfp"], ["act", "tac", "cat"]]
"""
def groupAnagrams(words):
anagrams = {}
for word in words:
sortedWord = "".join(sorted(word))
if sortedWord not in anagrams.keys():
anagrams[sortedWord] = [word]
else:
anagrams[sortedWord] = anagrams[sortedWord]+[word]
return list(anagrams.values())
print groupAnagrams(["yo", "act", "flop", "tac", "cat", "oy", "olfp"] )
| true |
cdfa714d56aad96ba4cbcd6ff4dfd25865d8e085 | PaLaMuNDeR/algorithms | /Algo Expert/101_Two_number_sum.py | 819 | 4.125 | 4 | """
Two Number Sum
Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum.
If any two numbers in the input array sum up to the target sum, the function should return them in an array,
in sorted order. If no two numbers sum up to the target sum, the function should return an empty array.
Assume that there will be at most one pair of numbers summing up to the target sum.
Sample input: [3, 5, -4, 8, 11, 1, -1, 6], 10 Sample output: [-1,11]
"""
# Time O(n) | Space O(n)
def twoNumberSum(array, targetSum):
dict = {}
for i in array:
dict[i] = i
for i in dict.keys():
j = targetSum - i
if j != i and j in dict.keys():
return [min(i,j),max(i,j)]
return []
print(twoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10)) | true |
995aaacefeb011ff0ef04a62d4c9fd4688b4450e | PaLaMuNDeR/algorithms | /Algo Expert/124_min_number_of_jumps.py | 1,006 | 4.125 | 4 | """
Min Number Of Jumps
You are given a non-empty array of integers. Each element represents the maximum number of steps you can take forward.
For example, if the element at index 1 is 3, you can go from index Ito index 2, 3, or 4. Write a function that returns
the minimum number of jumps needed to reach the final index. Note that jumping from index i to index i + x always
constitutes 1 jump, no matter how large x is.
Sample input: [3, 4, 2, 1, 2, 3, 7, 1, 1, 1, 3] Sample output: 4 (3 --> 4 or 2 --> 2 or 3 --> 7 --> 3)
"""
def minNumberOfJumps(array):
if len(array)==1:
return 0
jump = 0
steps = array[0]
maxReach = array[0]
for i in range(1,len(array)-1):
maxReach = max(maxReach, array[i]+i)
steps -= 1
if steps == 0:
jump += 1
steps = maxReach-i
return jump +1
print(minNumberOfJumps([3, 4, 2, 1, 2, 3, 7, 1, 1, 1, 3]))
print(minNumberOfJumps([1]))
print(minNumberOfJumps([2,1,1]))
print(minNumberOfJumps([1,1,1])) | true |
edca001ae4dd97c5081f1c6421a457eec39f4ff4 | yasab27/HelpOthers | /ps7twoD/ps7pr2.py | 1,179 | 4.25 | 4 | #
# ps7pr2.py (Problem Set 7, Problem 2)
#
# 2-D Lists
#
# Computer Science 111
#
# If you worked with a partner, put his or her contact info below:
# partner's name:
# partner's email:
#
# IMPORTANT: This file is for your solutions to Problem 2.
# Your solutions to problem 3 should go in ps7pr3.py instead.
import random
def create_grid(height, width):
""" creates and returns a 2-D list of 0s with the specified dimensions.
inputs: height and width are non-negative integers
"""
grid = []
for r in range(height):
row = [0] * width # a row containing width 0s
grid += [row]
return grid
def print_grid(grid):
""" prints the 2-D list specified by grid in 2-D form,
with each row on its own line, and nothing between values.
input: grid is a 2-D list. We assume that all of the cell
values are integers between 0 and 9.
"""
height = len(grid)
width = len(grid[0])
for r in range(height):
for c in range(width):
print(grid[r][c], end='') # print nothing between values
print() # at end of row, go to next line
| true |
8ed7f544dd1ba222cf0b96ee7f1e3a2b18b9e993 | krathee015/Python_assignment | /Assignment4-task7/task7_exc2.py | 722 | 4.375 | 4 | # Define a class named Shape and its subclass Square. The Square class has an init function which
# takes length as argument. Both classes have an area function which can print the area of the shape
# where Shape’s area is 0 by default.
class Shape:
def area(self):
self.area_var = 0
print("area of shape is: ",self.area_var)
class Square(Shape):
def __init__(self,length):
self.length = length
def area(self):
area = (self.length * self.length)
print("The area of square with length {} is:{}".format(self.length,area))
value_length = int(input("Enter the value of length: "))
s_shape = Shape()
s_shape.area()
s_square = Square(value_length)
s_square.area()
| true |
83e8f766412009bd71dea93ed83a1d1f17414290 | krathee015/Python_assignment | /Assignment3/task5/task5_exc2.py | 376 | 4.34375 | 4 | print("Exercise 2")
# Write a program in Python to allow the user to open a file by using the argv module. If the
# entered name is incorrect throw an exception and ask them to enter the name again. Make sure
# to use read only mode.
import sys
try:
with open(sys.argv[1],"r") as f:
print(f.read())
except:
print("Wrong file name entered. Please enter again") | true |
d282703436352013daf16052b74fd03110c645c8 | krathee015/Python_assignment | /Assignment1/Task2/tasktwo_exercise2.py | 984 | 4.125 | 4 | print ("Exercise 2")
result = 0
num1 = eval(input("Enter first number: "))
num2 = eval(input("Enter second number: "))
user_enter = eval(input("Enter 1 for Addition, 2 for Subtraction, 3 for Division, 4 for Multiplication, 5 for Average: "))
if (user_enter == 1):
result = num1 + num2
print ("Addition of two numbers is: ")
elif (user_enter == 2):
result = num1 - num2
print("Subtraction of two numbers is: ")
elif (user_enter == 3):
result = num1 / num2
print ("Division of two numbers is: ")
elif (user_enter == 4):
result = num1 * num2
print ("Multiplication of two number is: ")
elif (user_enter == 5):
first = eval(input("Enter third number: "))
second = eval(input("Enter fourth number: "))
result = (num1 + num2 + first +second)/ 4
print ("Average of four numbers is: ")
else:
print("Kindly enter correct number 1-5")
if (user_enter <= 5 and user_enter > 0):
print(result)
if (result < 0):
print("Negative") | true |
904d7bf1450e3838387f787eb0411593c739d5f0 | kunal5042/Python-for-Everybody | /Course 2: Python Data Structures/Week 3 (Files)/Assignment_7.2.py | 1,119 | 4.125 | 4 | """
7.2 Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.
You can download the sample data at http://www.py4e.com/code3/mbox-short.txt when you are testing below enter mbox-short.txt as the file name.
Desired output:
Average spam confidence: 0.7507185185185187
"""
fileName = input("Please enter a file's name:\n")
try:
file = open(fileName)
except:
print("Coudn't open the file: " + fileName)
quit()
lineCount = 0
totalConfidence = 0.0
for line in file:
if not line.startswith("X-DSPAM-Confidence:"):
continue
lineCount += 1
index = line.find('0')
try:
totalConfidence += float((line[index:]).strip())
except:
print("Error while parsing the string.")
print("Average spam confidence: " + str(totalConfidence / lineCount))
| true |
b3be5eaf872a254f8cec7c7eb33740c9c4f30303 | kunal5042/Python-for-Everybody | /Course 1: Programming for Everbody (Getting Started with Python)/Week 6 (Functions)/Factorial.py | 603 | 4.28125 | 4 | # Here I am using recursion to solve this problem, don't worry about it if it's your first time at recursion.
def Factorial(variable):
if variable == 0:
return 1
return (variable * Factorial(variable-1))
variable = input("Enter a number to calculate it's factorial.\n")
try:
x = int(variable)
except:
print("Not a valid number.")
x = 0
if x == 0:
print("\nFactorial of", variable + " equals:")
print("Cannot compute factorial, because the number you entered is invalid.")
else:
print("\nFactorial of", variable + " equals:")
print(Factorial(x))
| true |
07f9f576b76b56b5f258d563de4b24cf8f5f2673 | kunal5042/Python-for-Everybody | /Course 2: Python Data Structures/Week 5 (Dictionaries)/Dictionaries.py | 1,291 | 4.3125 | 4 | """
Dictionaries:
Dic are python's most powerful data collection.
Dic allow us to do fast database-like operations in python.
Dic have different names in different languages.
For example:
Associative Arrays - Perl / PHP
Properties or Map or HashMap - Java
Property Bag - C# /.Net
"""
def dictionaryDemo():
#Initialization
myDictionary = dict()
#Dictionaries are like bags - no order
myDictionary["Kunal5042"] = 1
#So we index the things we put in the dictionary with a "lookup tag"
myDictionary["Tanya"] = 7
myDictionary["Macbook Pro"] = 2399.99
#To get something out we use the exact same label
print("Macbook Pro: $" + str(myDictionary["Macbook Pro"]))
#An object whose internal state can be changed is mutable. On the other hand, immutable doesn't allow any change in the object once it has been created
#Dictionary contents are mutable
myDictionary["Kunal5042"] = myDictionary["Kunal5042"] + 5041
print("kunal" + str(myDictionary["Kunal5042"]))
#Dictionaires are like lists except that they use keys instead of numbers to look up values.
#Changing values of the keys
myDictionary["Tanya"] = 9000
print("Power level over " + str(myDictionary["Tanya"]) + "!")
dictionaryDemo()
# Kunal Wadhwa
# Contact : kunalwadhwa.cs@gmail.com
# Alternate: kunalwadhwa900@gmail.com | true |
e52b318f5ef1e29c6f6ff08ef2fb68336c62ab4b | kunal5042/Python-for-Everybody | /Course 1: Programming for Everbody (Getting Started with Python)/Week 5 (Comparison Operators, Exception Handling basics)
/Assignment_3.1.py | 1,066 | 4.28125 | 4 | """
3.1 Write a program to prompt the user for hours and rate per hour using input to compute gross pay. Pay the hourly rate for the hours up to 40 and 1.5 times the hourly rate for all hours worked above 40 hours. Use 45 hours and a rate of 10.50 per hour to test the program (the pay should be 498.75). You should use input to read a string and float() to convert the string to a number. Do not worry about error checking the user input - assume the user types numbers properly.
"""
#print("This program computes gross pay.\n")
hours = input("Enter the number of hours:\n")
try:
H = float(hours)
except:
print("Not a valid number.")
print("Default hours value is 0 and will be used.")
H = 0
hourlyRate = input("Enter the hourly rate:\n")
try:
HR = float(hourlyRate)
except:
print("Not a valid number.")
print("Default hourly rate value is 0 and will be used.")
HR = 0
if H > 40:
extraHours = H - 40
print( 40*HR + (extraHours*1.5*HR))
else:
print(HR*H)
"""
Input:
Hours = 45
Rate = 10.05
Desired Output:
498.75
""" | true |
c2138c13915b9f7cde94d6989b462023e1b1becc | kunal5042/Python-for-Everybody | /Assignments-Only/Assignment_7.1.py | 1,002 | 4.46875 | 4 | """
7.1 Write a program that prompts for a file name, then opens that file and reads through the file, and print the contents of the file in upper case. Use the file words.txt to produce the output below.
You can download the sample data at http://www.py4e.com/code3/words.txt
"""
import urllib.request, urllib.parse, urllib.error
def getFileHandle():
try:
fileName = input("Please enter a file's name:\n")
file = open(fileName)
return file
except:
print("\nSample data file not found.")
print("I'll download it for you!\n\nProgram execution will continue once the sample data is available")
fileHandle = urllib.request.urlopen('http://data.pr4e.org/words.txt')
print("\nDESIRED OUTPUT:\n")
print((fileHandle.read()).decode().upper().strip())
quit()
file = getFileHandle()
print(((file.read()).upper()).rstrip())
# Answer by:
# kunal5042
# Email : kunalwadhwa.cs@gmail.com
# Alternate: kunalwadhwa900@gmail.com | true |
97e1c7c3c00067602ca94705bb73f097d464a735 | ShrutiBhawsar/problem-solving-py | /Problem4.py | 1,547 | 4.5 | 4 | #Write a program that asks the user how many days are in a particular month, and what day of the
# week the month begins on (0 for Monday, 1 for Tuesday, etc), and then prints a calendar for that
# month. For example, here is the output for a 30-day month that begins on day 4 (Thursday):
# S M T W T F S
# 1 2 3
# 4 5 6 7 8 9 10
# 11 12 13 14 15 16 17
# 18 19 20 21 22 23 24
# 25 26 27 28 29 30
week = [ "Su", "Mo", 'Tu', "We", "Th", "Fr", "Sa"]
days30 = list(range(1, 30+1))
days31 = list(range(1 , 31 + 1))
# daystring = " ".join(week)
# print(daystring)
def calender():
input_No_of_days = input(" Enter the number of days in a particular month (30/31/28) : " )
print("select - 0 for Sunday ,1 for Monday, 2 for Tuesday, 3 for Wednesday, 4 for Thursday, 5 for Friday, 6 for Saturday,")
input_day_of_week = input(" Enter the day of the week the month begins on ( 0 to 6 ) : ")
start_pos = int(input_day_of_week)
daystring = " ".join(week) # converting week list to string
print(daystring)
spacing = list(range(0,start_pos)) #providing spacing till the first day of the week
for space in spacing:
print("{:>2}".format(""), end = " ")
if input_No_of_days == "30":
days = days30
else:
days = days31
for day in days:
print('{:>2}'.format(day), end=' ')
start_pos += 1
if start_pos ==7:
# If start_pos == 7 (Sunday) start new line
print()
start_pos = 0 # Reset counter
print('\n')
calender() | true |
4f03b84942530c09ff2932e497683e5f75ccbf9c | ShrutiBhawsar/problem-solving-py | /Problem2_USerInput.py | 1,237 | 4.3125 | 4 | #2. Print the given number in words.(eg.1234 => one two three four).
def NumberToWords(digit):
# dig = int(digit)
"""
It contains logic to convert the digit to word
it will return the word corresponding to the given digit
:param digit: It should be integer
:return: returns the string back
"""
digitToWord = {0: 'Zero', 1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', 6: 'Six', 7: 'Seven',
8: 'Eight', 9: 'Nine'}
return digitToWord.get(digit, " Not Valid")
def NumberInWords():
"""
This is the main function.We are getting the input(Number) in string
String is converted to list and each digit is passded to NumberToWords function
:param numInString: Number string
:return: it returns nothing
"""
numInString = input("Please input the number : ") #it takes input from the user
if numInString.isnumeric():
print("The Number to word convertion for {} is : ".format(numInString))
number = list(numInString)
for digit in number:
word = NumberToWords(int(digit))
print(word, end= " ")
print()
else:
print("Wrong input!!..Please enter the number only")
NumberInWords()
| true |
dcee80352c93df7f9dccfef14c15ea31dd7bfe88 | databooks/databook | /deepml/pytorch-examples02/nn/two_layer_net_module.py | 1,980 | 4.21875 | 4 | import torch
"""
A fully-connected ReLU network with one hidden layer, trained to predict y from x
by minimizing squared Euclidean distance.
This implementation defines the model as a custom Module subclass. Whenever you
want a model more complex than a simple sequence of existing Modules you will
need to define your model this way.
"""
class TwoLayerNet(torch.nn.Module):
def __init__(self, D_in, H, D_out):
"""
In the constructor we instantiate two nn.Linear modules and assign them as
member variables.
"""
super(TwoLayerNet, self).__init__()
self.linear1 = torch.nn.Linear(D_in, H)
self.linear2 = torch.nn.Linear(H, D_out)
def forward(self, x):
"""
In the forward function we accept a Tensor of input data and we must return
a Tensor of output data. We can use Modules defined in the constructor as
well as arbitrary (differentiable) operations on Tensors.
"""
h_relu = self.linear1(x).clamp(min=0)
y_pred = self.linear2(h_relu)
return y_pred
# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10
# Create random Tensors to hold inputs and outputs
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)
# Construct our model by instantiating the class defined above.
model = TwoLayerNet(D_in, H, D_out)
# Construct our loss function and an Optimizer. The call to model.parameters()
# in the SGD constructor will contain the learnable parameters of the two
# nn.Linear modules which are members of the model.
loss_fn = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=1e-4)
for t in range(500):
# Forward pass: Compute predicted y by passing x to the model
y_pred = model(x)
# Compute and print loss
loss = loss_fn(y_pred, y)
print(t, loss.item())
# Zero gradients, perform a backward pass, and update the weights.
optimizer.zero_grad()
loss.backward()
optimizer.step()
| true |
75e8edfa8f01a8605e6f8fb37fecfe5f23d1ce2f | lpython2006e/student-practices | /12_Nguyen_Lam_Manh_Tuyen/2.7.py | 610 | 4.1875 | 4 | #Write three functions that compute the sum of the numbers in a list: using a for-loop, a while-loop and recursion.
# (Subject to availability of these constructs in your language of choice.)
def sum_with_while(lists):
list_sum = 0
i = 0
while i < len(lists):
list_sum += lists[i]
i += 1
return list_sum
def sum_with_for(lists):
list_sum = 0
for i in range(0, len(lists)):
list_sum += lists[i]
return list_sum
def sum_with_recursion(lists, i):
if i == 0:
return lists[0]
else:
return lists[i] + sum_with_recursion(lists, i-1) | true |
820baad5f24cfc52195fbf11f5c74214812a1b76 | lpython2006e/student-practices | /12_Nguyen_Lam_Manh_Tuyen/1.3.py | 308 | 4.25 | 4 | #Modify the previous program such that only the users Alice and Bob are greeted with their names.
names=["Alice","Bob"]
name=()
while name not in names:
print("Please input your name")
name = input()
if name=="Alice":
print("Hello",name)
elif name=="Bob":
print("Hello",name)
| true |
56dbe18f5cd493157d153647e82cc9b94fcb8f6c | Bhaveshsadhwani/Test | /ASSESSMENT/Que14 .py | 281 | 4.3125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 16:25:08 2017
@author: User
"""
num = input("Enter a positive number:")
if (num > 0) and (num &(num-1))==0:
print num,"is a power of 2"
else:
print num,"is not a power of 2 "
| true |
4ff98dc017eda7df9a80c19e72fab899eac3b044 | YuhaoLu/leetcode | /1_Array/easy/python/rotate_array.py | 1,677 | 4.125 | 4 | """
0.Name:
Rotate Array
1.Description:
Given an array, rotate the array to the right by k steps, where k is non-negative.
Could you do it in-place with O(1) extra space?
2.Example:
Input: [1, 2, 3, 4, 5, 6, 7] and k = 3
Output: [5, 6, 7, 1, 2, 3, 4]
3.Solution:
array.unshift - add from the head
array.shift - delete from the head
array.push - add from the tail
array.pop - delete from the tail
l = 7, k = 3
----------------------------
| 1 | 2 | 3 | 4 | 5 | 6 | 7 |
-----------------------------
----------------------------
| 5 | 6 | 7 | 1 | 2 | 3 | 4 |
-----------------------------
l-k ... l 0 1 l-k-1
i -> (i + k)/l
4.Corner Case:
5.Complexity:
O(1)
"""
"""
0 -> 3 -> 6 -> 2 -> 5 -> 1 -> 4 -> 7
0 -> 2 -> 4 -> 6 -> 0
1 -> 3 -> 5 -> 7
"""
from typing import List
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
k = k % len(nums)
return nums[-k:] + nums[:len(nums)-k]
def rotate2(self, nums: List[int], k: int) -> None:
def gcd(a,b):
if b==0:
return a
else:
return gcd(b, a%b)
n = len(nums)
for i in range(gcd(n,k)):
pre = nums[i]
j = i
while (j+k)%n != i: # j+k/len !=i
nums[(j+k)%n], pre = pre, nums[(j+k)%n]
j = (j+k)%n
nums[(j+k)%n] = pre
nums = [1,2,3,4,5,6,7]
k = 3
sol = Solution()
result = sol.rotate(nums, k)
print(result) | true |
8244b2c89489b52681b49174ee7889ec473cf6d7 | YuhaoLu/leetcode | /4_Trees/easy/python/Symmetric_Tree.py | 2,166 | 4.53125 | 5 | """
0.Name:
Symmetric Tree
1.Description:
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center)
2.Example:
Given linked list:
1
/ \
2 2
/ \ / \
3 4 4 3
Input: root = [1,2,2,3,4,4,3]
Output: true
1
/ \
2 2
\ \
3 3
Constraints:
The number of nodes in the tree is in the range [1, 1000].
-100 <= Node.val <= 100
3.Solution:
Check whether the left tree and right tree are mirror
If both trees are empty, then they are mirror images
1 - Their root node's key must be same
2 - left subtree of left tree and right subtree
of the right tree have to be mirror images
3 - right subtree of left tree and left subtree
of right tree have to be mirror images
4.Corner Case:
node is head or tail
5.Complexity:
O(n)
"""
# Python program to check if a
# given Binary Tree is symmetric or not
# Node structure
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Returns True if trees
#with roots as root1 and root 2 are mirror
class Solution:
def isSymmetric(self, root):
# Check if tree is mirror of itself
return self.isMirror(root, root)
def isMirror(self, root1, root2):
#
if root1 is None and root2 is None:
return True
if (root1 is not None and root2 is not None):
if root1.key == root2.key:
return (self.isMirror(root1.left, root2.right)and
self.isMirror(root1.right, root2.left))
# If none of the above conditions is true then root1
# and root2 are not mirror images
return False
# Test
root = Node(1)
root.left = Node(2)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(4)
root.right.left = Node(4)
root.right.right = Node(3)
sol = Solution()
print ("Symmetric" if sol.isSymmetric(root) == True else "Not symmetric")
| true |
1df94c11e36c23bd17752519659f96de91f7ea97 | johnerick89/iCube_tasks | /task2.py | 735 | 4.375 | 4 |
def get_maximum_value_recursion(weight,values,capacity, n):
'''
Function to get maximum value
Function uses recursion to get maximum value
'''
if n==0 or capacity == 0:
return 0
if weight[n-1]>capacity:
return get_maximum_value_recursion(weight,values,capacity, n-1)
else:
return max(
values[n-1] + get_maximum_value_recursion(
weight, values,capacity-weight[n-1], n-1),
get_maximum_value_recursion(weight,values,capacity, n-1))
'''
Function driver code
'''
weight = [5,4,6,4]
values = [10,40,30,50]
capacity = 10
n = len(values)
maximum_value = get_maximum_value_recursion(weight,values,capacity,n)
print(maximum_value)
| true |
951e6870e1c504e5e17122f8cb7a8600d13115bc | jtpio/algo-toolbox | /python/mathematics/cycle_finding.py | 1,154 | 4.21875 | 4 | def floyd(f, start):
""" Floyd Cycle Finding implementation
Parameters
----------
f: function
The function to transform one value to its successor
start:
The start point from where the cycle detection starts.
Returns
-------
out: tuple:
- mu: int
Position at which the cycle starts
- length: int
The length of the cycle
"""
slow, fast = f(start), f(f(start))
while slow != fast:
slow, fast = f(slow), f(f(fast))
mu = 0
fast = start
while slow != fast:
slow, fast = f(slow), f(fast)
mu += 1
length = 1
fast = f(slow)
while slow != fast:
fast = f(fast)
length += 1
return (mu, length)
def brent(f, start):
p = length = 1
slow, fast = start, f(start)
while slow != fast:
if p == length:
slow = fast
p *= 2
length = 0
fast = f(fast)
length += 1
mu = 0
slow = fast = start
for i in range(length):
fast = f(fast)
while slow != fast:
slow, fast = f(slow), f(fast)
mu += 1
return mu, length
| true |
ed32eff5d2a297f299deacf1e22d68193494fcce | Starluxe/MIT-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python | /Problem Set 1/Problem 3 - Longest Alphabetcal Substring.py | 1,187 | 4.28125 | 4 | # Assume s is a string of lower case characters.
# Write a program that prints the longest substring of s in which the letters
# occur in alphabetical order. For example, if s = 'azcbobobegghakl',
# then your program should print
# Longest substring in alphabetical order is: beggh
# In the case of ties, print the first substring. For example, if s = 'abcbcd',
# then your program should print
# Longest substring in alphabetical order is: abc
# Note: This problem may be challenging. We encourage you to work smart.
# If you'\ve spent more than a few hours on this problem, we suggest
# that you move on to a different part of the course. If you have time,
# come back to this problem after you've had a break and cleared your head.
# Paste your code into this box
maxLen=0
current=s[0]
longest=s[0]
# step through s indices
for i in range(len(s) - 1):
if s[i + 1] >= s[i]:
current += s[i + 1]
# if current length is bigger update
if len(current) > maxLen:
maxLen = len(current)
longest = current
else:
current=s[i + 1]
i += 1
print ('Longest substring in alphabetical order is: ' + longest)
| true |
b2da8890a183783c996070701b900c866f235d61 | Starluxe/MIT-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python | /Final Exam/Problem 3.py | 631 | 4.1875 | 4 | # Implement a function that meets the specifications below.
# def sum_digits(s):
# """ assumes s a string
# Returns an int that is the sum of all of the digits in s.
# If there are no digits in s it raises a ValueError exception. """
# # Your code here
# For example, sum_digits("a;35d4") returns 12.
# Paste your entire function, including the definition, in the box below.
# Do not leave any debugging print statements.
def sum_digits(string):
if any(i.isdigit() for i in string):
return sum(int(x) for x in string if x.isdigit())
else:
raise ValueError('No digits in input') | true |
94846af53f588d81cf57e822044d204cb5fef2d1 | lukelafountaine/euler | /23.py | 1,887 | 4.25 | 4 | #! /usr/bin/env python
# A perfect number is a number for which the sum of its proper divisors is exactly equal to the number.
# For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28,
# which means that 28 is a perfect number.
#
# A number n is called deficient if the sum of its proper divisors is less than n
# and it is called abundant if this sum exceeds n.
#
# As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16,
# the smallest number that can be written as the sum of two abundant numbers is 24.
# By mathematical analysis, it can be shown that all integers greater than 28123
# can be written as the sum of two abundant numbers.
#
# However, this upper limit cannot be reduced any further by analysis even though it is known
# that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.
#
# Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.
def get_divisors(n):
divisors = []
for x in range(n + 1):
divisors.append([])
for num in range(1, (n / 2) + 1):
multiple = num + num
while multiple < len(divisors):
divisors[multiple].append(num)
multiple += num
return divisors
def get_abundants(n, divisors):
abundants = []
for x in range(n):
if sum(divisors[x]) > x:
abundants.append(x)
return abundants
def non_abundant():
upper_limit = 28123
divisors = get_divisors(upper_limit)
abundants = get_abundants(upper_limit, divisors)
can_sum = set()
for i in range(len(abundants)):
for j in range(i, len(abundants)):
can_sum.add(abundants[i] + abundants[j])
total = 0
for x in range(upper_limit):
if x not in can_sum:
total += x
return total
print non_abundant()
| true |
f3d520e3294cb123db91beab99d28c34c939b1d0 | lukelafountaine/euler | /1.py | 426 | 4.34375 | 4 | #! /usr/bin/env python
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
# The sum of these multiples is 23.
#
# Find the sum of all the multiples of 3 or 5 below 1000.
def sum_of_multiples(n, bound):
multiples = (bound - 1) / n
return n * ((multiples * (multiples + 1)) / 2)
print sum_of_multiples(3, 1000) + sum_of_multiples(5, 1000) - sum_of_multiples(15, 1000)
| true |
87351efb827796bdde84fa15df577ad52b615ff5 | jfulghum/practice_thy_algos | /LinkedList/LLStack.py | 1,496 | 4.1875 | 4 | # Prompt
# Implement a basic stack class using an linked list as the underlying storage. Stacks have two critical methods, push() and pop() to add and remove an item from the stack, respectively. You'll also need a constructor for your class, and for convenience, add a size() method that returns the current size of the stack. All of these methods should run in O(1) time!
# Remember, a stack is a first in, first out data structure!
# A singly linked list is a simple way to create a stack. The head of the list is the top of the stack.
# Function Signature
class ListNode:
def __init__(self, value = 0, next = None):
self.value = value
self.next = next
class LLStack:
def __init__(self):
self.stack = []
def size(self):
return len(self.stack)
def pop(self):
return self.stack.pop()
def push(self, item):
return self.stack.append(item)
# Expected Runtime
# O(1) for all methods!
# Examples
stack = LLStack();
print(stack.size()) # 0
stack.push(2);
stack.push(3);
print(stack.size()) # 2
print(stack.pop()) # 3
print(stack.size()) # 1
print(stack.pop()) # 2
# Test various sequences of push/pop and be sure to test edge cases around an empty stack.
# Expected Questions
# If you were presented this question in an interview, these are some questions(s) you might want to ask:
# Q: Computing the size of a linked list is O(n). How can I make this constant?
# A: Keep track of the size as you push and pop in a separate field.
| true |
be1d46e5b24abc08a5ea94810dc69cc3297bbc29 | jfulghum/practice_thy_algos | /LinkedList/queue_with_linked _list.py | 1,352 | 4.5625 | 5 | # Your class will need a head and tail pointer, as well as a field to track the current size.
# Enqueue adds a new value at one side.
# Dequeue removes and returns the value at the opposite side.
# A doubly linked list is one of the simplest ways to implement a queue. You'll need both a head and tail pointer to keep track of where to add and where to remove data. Using a doubly linked list means you can do both operations without walking the whole list and all modifications of the list are at the ends.
class ListNode:
def __init__(self, value = 0, next = None):
self.value = value
self.next = next
class LLQueue:
def __init__(self):
self.front = self.rear = None
self.length = 0
def enqueue(self, item):
temp = ListNode(item)
self.length += 1
if self.rear == None:
self.front = self.rear = temp
return
self.rear.next = temp
self.rear = temp
def dequeue(self, item = None):
if self.front == None:
return
self.length -= 1
temp = self.front
self.front = temp.next
return temp.value
def size(self):
return self.length
# Expected Runtime
# O(1) for all methods!
# Examples
q = LLQueue()
print(q.size()) # 0
q.enqueue(2)
q.enqueue(3)
print(q.size()) # 2
print(q.dequeue()) # 2
print(q.size()) # 1
print(q.dequeue()) # 3
| true |
20059f23388b82201b8a8210f90fe3cc04a16e5a | 31337root/Python_crash_course | /Exercises/Chapter5/0.Conditionial_tests.py | 500 | 4.15625 | 4 | best_car = "Mercedes"
cars = ["Mercedes", "Nissan", "McLaren"]
print("Is " + cars[0] + " the best car?\nMy prediction is yes!")
print(cars[0] == best_car)
print("Is " + cars[1] + " the best car?\nMy prediction is nop :/")
print(cars[1] == best_car)
print("Is " + cars[2] + " the best car?\nMy prediction is nop :/")
print(cars[2] == best_car)
print(cars[0].lower() == best_car.lower())
if 1 > 0 and 0 < 1 and 3 == 3 or 3 != 3:
print("LOLA")
print(best_car in cars)
print(best_car not in cars)
| true |
c7663e6804cc478e517727f7996c6f5df936d364 | jerrywardlow/Euler | /6sumsquare.py | 592 | 4.1875 | 4 | def sum_square(x):
'''1 squared plus 2 squared plus 3 squared...'''
total = 0
for i in range(1, x+1):
total += i**2
return total
def square_sum(x):
'''(1+2+3+4+5...) squared'''
return sum(range(1, x+1))**2
def print_result(num):
print "The range is 1 through %s" % num
print "The sum of the squares is: %s" % sum_square(num)
print "The square of the sum is: %s" % square_sum(num)
print ("The difference between the sum of the squares and the square of "
"the sum is: %s" % (square_sum(num) - sum_square(num)))
print_result(100)
| true |
de7890db84895c8c8b9e5131bbf7528dc9e3a74f | Annarien/Lectures | /L6.2_25_04_2018.py | 356 | 4.3125 | 4 | import numpy
#make a dictionary containing cube from 1-10
numbers= numpy.arange(0,11,1)
cubes = {}
for x in numbers:
y = x**3
cubes[x]=y
print ("The cube of "+ str(x) +" is "+ str(y))
# making a z dictionary
# print (cubes)
print (cubes)
#for x in cubes.keys(): #want to list it nicely
#print (x, cubes())
| true |
e1336bc4c6810f7cd908f333502a3b6c83ca394c | bossenti/python-advanced-course | /sets.py | 1,137 | 4.21875 | 4 | # Set: collection data-type, unordered, mutable, no duplicates
# creation
my_set = {1, 2, 3}
my_set_2 = set([1, 2, 3])
my_set_3 = set("Hello") # good trick to count number of different characters in one word
# empty set
empty_set = set # {} creates a dictionary
# add elements
my_set.add(4)
# remove elements
my_set.remove(3)
my_set.discard(2) # does not throw an error if element does not exist
# remove all elements
my_set_3.clear()
# iterate over set
for i in my_set:
print(i)
# check element is in set
if 1 in my_set:
print("Yes")
# combine elements from both sets
union = my_set.union(my_set_2)
# only elements that are in both sets
intersec = my_set.intersection(my_set_2)
# determine the difference of two sets
diff = my_set.difference(my_set_2)
# all elements that are in one of set but not in both
sym_diff = my_set.symmetric_difference(my_set_2)
# check set is a subset of the other other
print(my_set.issubset(my_set_2))
# check set is a superset of the other
print(my_set.issuperset(my_set_2))
# check for same elements
print(my_set.isdisjoint(my_set_2))
# immutable set
a = frozenset([1, 2, 3, 4])
| true |
6ba34b1bcd307cbac829ad8fbaba27571cd2c807 | punkyjoy/LearningPython | /03.py | 514 | 4.125 | 4 | print("I will now count my chickens")
print("hens", 25.00+30.00/6.0)
print("roosters", 100.0-25.0*3.0%4.0)
print("Now I will count the eggs:")
print(3.0+2.0+1.0-5.0+4.0%2.0-1.0/4.0+6.0)
print("Is is true that 3.0+2.0<5.0-7.0?")
print(3.0+2.0<5.0-7.0)
print("What is 3+2?", 3.0+2.0)
print("What is 5-7?", 5-7)
#this is a comment
print("Oh, that's why it's false.")
print("how about some more.")
print("Is it greater?", 5 > -2)
print("is it greater or equal?", 5>= -2)
print("Is it less or equal?, 5 <= -2") | true |
d4bad854227ad91b7ad5a305906060837f0a11fa | Prince9ish/Rubik-Solver | /colors.py | 1,592 | 4.1875 | 4 | '''For representing color of the rubik's cube.'''
from pygame.locals import Color
from vpython import *
class ColorItem(object):
'''WHITE,RED,BLUE,etc are all instances of this class.'''
def __init__(self,name="red"):
self.name=name
self.color=color.red
self.opposite=None
def setColor(self,color):
self.color=color
def getColor(self):
return self.color
def getOpposite(self):
return self.opposite
def __str__(self):
return self.name
def __repr__(self):
return str(self)
def setOpposite(self,opposite):
self.opposite=opposite
opposite.opposite=self
RED=ColorItem("red");
BLUE=ColorItem("blue");
GREEN=ColorItem("green");
ORANGE=ColorItem("orange");
WHITE=ColorItem("white");
YELLOW=ColorItem("yellow");
RED.setColor(color.red)
GREEN.setColor(color.green)
YELLOW.setColor(color.yellow)
BLUE.setColor(color.blue)
WHITE.setColor(color.white)
ORANGE.setColor((color.orange))
RED.setOpposite(ORANGE)
BLUE.setOpposite(GREEN)
WHITE.setOpposite(YELLOW)
def decodeColorFromText(color):
'''Converts text and returns its instance.'''
color=color.lower()
if color.startswith(str(RED)): return RED
elif color.startswith(str(GREEN)): return GREEN
elif color.startswith(str(YELLOW)): return YELLOW
elif color.startswith(str(WHITE)): return WHITE
elif color.startswith(str(BLUE)): return BLUE
elif color.startswith(str(ORANGE)): return ORANGE
return None
print(RED.color)
if __name__=="__main__":
pass
| true |
ae471d6db283d8d28d6fe43934656f47a5192cec | claudiordgz/GoodrichTamassiaGoldwasser | /ch01/c113.py | 357 | 4.125 | 4 | __author__ = 'Claudio'
"""Write a pseudo-code description of a function that reverses a list of n
integers, so that the numbers are listed in the opposite order than they
were before, and compare this method to an equivalent Python function
for doing the same thing.
"""
def custom_reverse(data):
return [data[len(data)-x-1] for x in range(len(data))] | true |
47ade36bd4fc754b29fd7a3cd898ddef5b87ca7e | smholloway/miscellaneous | /python/indentation_checker/indentation_checker.py | 2,876 | 4.375 | 4 | def indentation_checker(input):
# ensure the first line is left-aligned at 0
if (spaces(input[0]) != 0):
return False
# emulate a stack with a list
indent_level = []
indent_level.append(0)
# flag to determine if previous line encountered was a control flow statement
previous_line_was_control = False
# iterate over all input lines
for line in input:
previous_indentation_level = indent_level[-1]
current_indentation_level = spaces(line)
if previous_line_was_control:
# ensure we have added spaces after a control flow statement
if current_indentation_level <= indent_level[-1]:
return False
previous_line_was_control = False
indent_level.append(current_indentation_level)
# are we at a valid indent level?
if not current_indentation_level in indent_level:
return False
# is this line a control flow statement
if line.endswith(":"):
previous_line_was_control = True
previous_indentation_level = current_indentation_level
# check to see that we did not exit without an indentation after a control flow statement
if previous_line_was_control:
return False
# if we made it this far, the indentation was clean
return True
# generic function to return the number of spaces at the beginning of a string
def spaces(input):
if input.startswith(' '):
return 1 + spaces(input[1:])
else:
return 0
# main will check the indentation in this file
def main():
# read this program into a variable so we can check indentation on a working file
filename = "indentation_checker.py"
source = open(filename, 'r').readlines()
# if this program compiles and runs via python indentation_checker.py
# we should see that the indentation check is True
print "Indentation check on %s is %s" %(filename, indentation_checker(source))
# some tests
def test():
print "### TESTS RUNNING ###"
print spaces(" test") , "should be 1"
print spaces(" test") , "should be 2"
print spaces(" test") , "should be 3"
print indentation_checker([" def main():"]) , "should be False"
print indentation_checker(["def main():"]) , "should be False"
print indentation_checker(["print foo"]) , "should be True"
print indentation_checker(["def main():", " print foo"]) , "should be True"
print indentation_checker(["def main():", " print foo", "print bar"]) , "should be True"
print indentation_checker(["def main():", "print foo", "print bar"]) , "should be False"
print indentation_checker(["print begin", "def main():", " print foo", " print bar"]) , "should be True"
print indentation_checker(["def main():", " if True:", " print 'True'", "print 'end'"]) , "should be True"
print indentation_checker(["print begin", " def main():"]) , "should be False"
print indentation_checker(["print begin", "def main():", " print 'begin'", " print 'end'"]) , "should be False"
print "### TESTS COMPLETED ###\n"
test()
main()
| true |
d1f00fa6f224748010687c63f08e01a3142d62cf | pawlmurray/CodeExamples | /ProjectEuler/1/MultiplesOf3sAnd5s.py | 688 | 4.3125 | 4 | #get all of the multiples of threes and add them up
def sumOfMultiplesOfThrees(max):
currentSum = 0
threeCounter = 3
while(threeCounter < max):
currentSum+= threeCounter
threeCounter += 3
return currentSum
#Get all of the multiples of fives and add them up, if they are
#evenly divisible by three just leave them out
def sumOfMultiplesOfFivesWithoutThrees(max):
currentSum = 0
fiveCounter = 5
while(fiveCounter < max):
if not fiveCounter % 3 == 0:
currentSum += fiveCounter
fiveCounter += 5
return currentSum
totalSum = sumOfMultiplesOfThrees(1000) + sumOfMultiplesOfFivesWithoutThrees(1000)
print totalSum | true |
d7468de2be523b14bb8cddf5e10bf67e64663fe9 | Kartikkh/OpenCv-Starter | /Chapter-2/8-Blurring.py | 2,789 | 4.15625 | 4 |
## Blurring is a operation where we average the pixel with that region
#In image processing, a kernel, convolution matrix, or mask is a small matrix. It is used for blurring, sharpening,
#embossing, edge detection, and more.
#This is accomplished by doing a convolution between a kernel and an image.
# https://www.youtube.com/watch?v=C_zFhWdM4ic&t=301s
# http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_filtering/py_filtering.html
import cv2
import numpy as np
image = cv2.imread('image.jpg')
cv2.imshow('Original Image' , image)
cv2.waitKey(0)
kernel_3 = np.ones((3,3),np.float32)/9
blurImage = cv2.filter2D(image,-1,kernel_3)
cv2.imshow("blurredImage",blurImage)
cv2.waitKey(0)
cv2.destroyAllWindows()
# checking with kernel of different size
kernel_9 = np.ones((20,20),np.float32)/400
blurImage = cv2.filter2D(image,-1,kernel_3)
cv2.imshow("blurredImage",blurImage)
cv2.waitKey(0)
cv2.destroyAllWindows()
## Other Blur Techniques
# Averaging
#This is done by convolving the image with a normalized box filter. It simply takes the average of all the pixels under kernel area
# and replaces the central element with this average. This is done by the function cv2.blur() or cv2.boxFilter().
img = cv2.imread('image.jpg')
blur = cv2.blur(img,(5,5))
cv2.imshow("blur",blur)
cv2.waitKey(0)
#Gaussian Filtering
#In this approach, instead of a box filter consisting of equal filter coefficients, a Gaussian kernel is used.
# It is done with the function, cv2.GaussianBlur().
# We should specify the width and height of the kernel which should be positive and odd.
img = cv2.imread('image.jpg')
blur = cv2.GaussianBlur(img,(5,5),0)
cv2.imshow("blur",blur)
cv2.waitKey(0)
# Median Filtering
# Here, the function cv2.medianBlur() computes the median of all the pixels under the kernel window and the central pixel
# is replaced with this median value. This is highly effective in removing salt-and-pepper noise.
# One interesting thing to note is that, in the Gaussian and box filters, the filtered value for the central element
# can be a value which may not exist in the original image. However this is not the case in median filtering,
# since the central element is always replaced by some pixel value in the image. This reduces the noise effectively.
# The kernel size must be a positive odd integer.
img = cv2.imread('image.jpg')
median = cv2.medianBlur(img,5)
cv2.imshow("median",median)
cv2.waitKey(0)
#Bilateral Filtering
#bilateral filter, cv2.bilateralFilter(), which was defined for, and is highly effective at noise removal while preserving edges.
img = cv2.imread('image.jpg')
bilateralFilter = cv2.bilateralFilter(img,9,75,75)
cv2.imshow("bilateralFilter",bilateralFilter)
cv2.waitKey(0)
cv2.destroyAllWindows()
| true |
514fbfa2e340addc29c2a928a6ace99c042fcb7b | jmtaysom/Python | /Euler/004ep.py | 643 | 4.25 | 4 | from math import sqrt
def palindrome():
"""
A palindromic number reads the same both ways.
The largest palindrome made from the product
of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the
product of two 3-digit numbers.
"""
for x in range(999,100,-1):
pal = int(str(x) + str(x)[::-1])
for i in range(999,int(sqrt(pal)), -1):
if pal % i == 0 and len(str(i)) > 2 and len(str(pal/i)) > 2:
return pal, i , pal / i
if __name__ == '__main__':
from time import time
start = time()
print(palindrome())
print(time()-start)
| true |
5904acd697e84a4063452b706ab129537e53ab5b | Aryamanz29/DSA-CP | /gfg/Recursion/binary_search.py | 627 | 4.15625 | 4 | #binary search using recursion
def binary_search(arr, target):
arr = sorted(arr) #if array is not sorted
return binary_search_func(arr, 0, len(arr)-1, target)
def binary_search_func(arr, start_index, end_index, target):
if start_index > end_index:
return -1 # element not found
mid = (start_index+end_index) //2
if arr[mid] == target:
return mid
elif arr[mid] > target:
return binary_search_func(arr, start_index, mid-1, target)
else:
return binary_search_func(arr, mid+1, end_index, target)
arr = [1,2,3,4,5,6,7,8,9]
target = 5
res = binary_search(arr,target)
print(res)
# time complexity : T(n) = log(n) | true |
d346746005b6b2a5c0b25a92e63f92c0bbadfa89 | Aryamanz29/DSA-CP | /random/word_count.py | 1,116 | 4.125 | 4 | # You are given some words. Some of them may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification.
# Note:
# All the words are composed of lowercase English letters only.
# Input Format
# It should contain all the words separated by space.
# Output Format
# Output the number of distinct words from the input
# Output the number of occurrences for each distinct word according to their appearance in the input.
# Both the outputs should be separated by space.
# Sample Input
# bcdef abcdefg bcde bcdef
# Sample Output
# 3 211
# Explanation
# There are distinct words. Here, "bcdef" appears twice in the input at the first and last positions. The other words appear once each. The order of the first appearances are "bcdef", "abcdefg" and "bcde" which corresponds to the output.
words = input().split()
d = {}
for i in words:
d[i] = d.get(i, 0) + 1
# print(d)
print(len(d), end=" ")
for i in words:
if d[i] is not None:
print(d[i], end="")
d[i] = None
| true |
eba979bd967c81ba4ad6d2435ffb09b3e4f5059f | n1e2h4a/AllBasicProgram | /BasicPython/leadingzero.py | 264 | 4.21875 | 4 | mystring="python"
#print original string
print("the original string :--- "+ str(mystring))
#no of zeros want
zero=5
#using rjust()for for adding leading zero
final=mystring.rjust(zero + len(mystring), '0')
print("string after adding leading zeros : " + str(final)) | true |
435fd488d1a513ebebcfc35354be57debca54442 | n1e2h4a/AllBasicProgram | /ListPrograms.py/MinimumInList.py | 213 | 4.125 | 4 | table = []
number = int(input("Enter number of digit you want to print:---"))
for x in range(number):
Element = int((input(' > ')))
table.append(Element)
table.sort()
print("Smallest in List:", *table[:1]) | true |
18b9d6e60429bcfc31d56ece3f3d1c1c79bb30d6 | abdul1380/UC6 | /learn/decorater_timer.py | 1,792 | 4.4375 | 4 | """
The following @debug decorator will print the arguments a function is
called with as well as its return value every time the function is called:
"""
import functools
import math
def debug(func):
"""Print the function signature and return value"""
@functools.wraps(func)
def wrapper_debug(*args, **kwargs):
args_repr = [repr(a) for a in args] # 1
kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()] # 2
signature = ", ".join(args_repr + kwargs_repr) # 3
print(f"Calling {func.__name__}({signature})")
value = func(*args, **kwargs)
print(f"{func.__name__!r} returned {value!r}") # 4
return value
return wrapper_debug
'''
The signature is created by joining the string representations of all the arguments.
The numbers in the following list correspond to the numbered comments in the code:
1 Create a list of the positional arguments. Use repr() to get a nice string representing each argument.
2: Create a list of the keyword arguments. The f-string formats each argument as key=value where the !r specifier means that repr() is used to represent the value.
3: The lists of positional and keyword arguments is joined together to one signature string with each argument separated by a comma.
4: The return value is printed after the function is executed.
Lets see how the decorator works in practice by applying it to a simple function with one position and one keyword argument:
'''
@debug
def make_greeting(name, age=None):
if age is None:
return f"Howdy {name}!"
else:
return f"Whoa {name}! {age} already, you are growing up!"
if __name__ == '__main__':
make_greeting("Benjamin")
print()
make_greeting("Benjamin", age = 21) | true |
d4cbd946ea754ed8bddb1f487f6a4250c4e3a96b | dengxinjuan/springboard | /python-syntax/words.py | 319 | 4.15625 | 4 | def print_upper_words(words,must_start_with):
for word in words:
for any in must_start_with:
if word.startswith(any):
result = word.upper()
print(result)
print_upper_words(["hello", "hey", "goodbye", "yo", "yes"],
must_start_with={"h", "y"}) | true |
5e26fa7180ec61b226b2824f4c3d4120df770254 | ptsiampas/Exercises_Learning_Python3 | /18_Recursion/Exercise_18.7.2a.py | 1,089 | 4.375 | 4 | import turtle
from math import cos, sin
def cesaro_fractal(turtle, order, size):
"""
(a) Draw a Casaro torn line fractal, of the order given by the user.
We show four different lines of order 0, 1, 2, 3. In this example, the angle of the
tear is 10 degrees.
:return:
"""
if order == 0: # The base case is just a straight line
turtle.forward(size)
else:
for angle in [-85, 170, -85, 0]:
cesaro_fractal(turtle, order - 1, size / 3)
turtle.left(angle)
wn = turtle.Screen()
wn.title("Exercise 18.7.2a Cesaro Fractal!")
wn.bgcolor("white")
fract_turtle = turtle.Turtle()
fract_turtle.pencolor("#0000FF")
fract_turtle.hideturtle()
fract_turtle.pensize(1)
# setup initial location
fract_turtle.penup()
fract_turtle.back(450)
fract_turtle.right(90)
fract_turtle.back(400)
fract_turtle.left(90)
fract_turtle.pendown()
size = 150
for order in [0, 1, 2, 3]:
cesaro_fractal(fract_turtle, order, size + (50 * (order + 1)))
fract_turtle.penup()
fract_turtle.forward(50)
fract_turtle.pendown()
wn.mainloop()
| true |
712a129202333470151c53d20af112057b41d9f6 | ptsiampas/Exercises_Learning_Python3 | /15._Classes and Objects_Basics/Exercise_15.12.4.py | 1,970 | 4.375 | 4 | # 4. The equation of a straight line is “y = ax + b”, (or perhaps “y = mx + c”). The coefficients
# a and b completely describe the line. Write a method in the Point class so that if a point
# instance is given another point, it will compute the equation of the straight line joining
# the two points. It must return the two coefficients as a tuple of two values.
#
# For example,
# >>> print(Point(4, 11).get_line_to(Point(6, 15)))
# >>> (2, 3)
#
# This tells us that the equation of the line joining the two points is “y = 2x + 3”. When
# will your method fail?
from unit_tester import test
class Point:
""" Point class represents and manipulates x,y coords. """
def __init__(self, x=0, y=0):
""" Create a new point at the origin """
self.x = x
self.y = y
def distance_from_origin(self):
""" Compute my distance from the origin """
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
def __str__(self): # All we have done is renamed the method
return "({0}, {1})".format(self.x, self.y)
def halfway(self, target):
""" Return the halfway point between myself and the target """
mx = (self.x + target.x) / 2
my = (self.y + target.y) / 2
return Point(mx, my)
def distance(self, target):
dx = target.x - self.x
dy = target.y - self.y
dsquared = dx * dx + dy * dy
result = dsquared ** 0.5
return result
def reflect_x(self):
ry = self.y * -1
return Point(self.x, ry)
def slope_from_origin(self):
if self.y == 0 or self.x == 0:
return 0
slope = float(self.y) / self.x
return slope
def get_line_to(self, target):
# y = mx + b
# m is the slope, and b is the y-intercept
m = (self.y - target.y) / (self.x - target.x)
b = self.y - (m * self.x)
return (m, b)
test(Point(4, 11).get_line_to(Point(6, 15)), (2, 3))
| true |
b10e4275bac85b19fbd094a6e205386b6f73f169 | ptsiampas/Exercises_Learning_Python3 | /07_Iteration/Exercise_7.26.16.py | 1,062 | 4.125 | 4 | # Write a function sum_of_squares(xs) that computes the sum of the squares of the numbers in the list xs.
# For example, sum_of_squares([2, 3, 4]) should return 4+9+16 which is 29:
#
# test(sum_of_squares([2, 3, 4]), 29)
# test(sum_of_squares([ ]), 0)
# test(sum_of_squares([2, -3, 4]), 29)
import sys
def test(actual, expected):
""" Compare the actual to the expected value,
and print a suitable message.
"""
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if (expected == actual):
msg = "Test on line {0} passed.".format(linenum)
else:
msg = ("Test on line {0} failed. Expected '{1}', but got '{2}'."
.format(linenum, expected, actual))
print(msg)
def test_suite():
""" Run the suite of tests for code in this module (this file).
"""
test(sum_of_squares([2, 3, 4]), 29)
test(sum_of_squares([ ]), 0)
test(sum_of_squares([2, -3, 4]), 29)
def sum_of_squares(xn):
result=0
for nu in xn:
result += (nu**2)
return result
test_suite() | true |
ad104e36e782364406c66006947e838a5ec2ab4d | ptsiampas/Exercises_Learning_Python3 | /05_Conditionals/Exercise_5.14.11.py | 710 | 4.25 | 4 | #
# Write a function is_rightangled which, given the length of three sides of a triangle, will determine whether the
# triangle is right-angled. Assume that the third argument to the function is always the longest side. It will return
# True if the triangle is right-angled, or False otherwise.
#
__author__ = 'petert'
def find_hypot(c1,c2):
hpot=((c1**2)+(c2**2))**0.5
return hpot
def is_rightangled(side1, side2, side3):
hypot_test=find_hypot(side1,side2)
if abs(hypot_test - side3) < 0.000001:
print("Triangle is at right angle",abs(hypot_test - side3))
else:
print("truangle is NOT a right angle",abs(hypot_test - side3))
is_rightangled(3,4,5)
is_rightangled(18,8,20) | true |
087cad1c17766f45940c7e98e789862465ba2934 | ptsiampas/Exercises_Learning_Python3 | /18_Recursion/Exercise_18.7.3.py | 1,236 | 4.4375 | 4 | from turtle import *
def Triangle(t, length):
for angle in [120, 120, 120]:
t.forward(length)
t.left(angle)
def sierpinski_triangle(turtle, order, length):
"""
3. A Sierpinski triangle of order 0 is an equilateral triangle. An order 1 triangle can be drawn by drawing 3
smaller triangles (shown slightly disconnected here, just to help our understanding).
Higher order 2 and 3 triangles are also shown.
Draw Sierpinski triangles of any order input by the user..
:return:
"""
if order == 0: # The base case is just a straight line
Triangle(turtle, length)
else:
for i in range(3):
turtle.forward(length)
turtle.left(120)
sierpinski_triangle(turtle, order - 1, length / 2)
wn = Screen()
wn.title("Exercise 18.7.3 Sierpinski triangle Fractal!")
wn.bgcolor("white")
fract_turtle = Turtle()
fract_turtle.pencolor("#0000FF")
fract_turtle.fillcolor("black")
fract_turtle.pensize(1)
# setup initial location
# delay(0)
fract_turtle.speed(0)
fract_turtle.up()
fract_turtle.goto(-450, -200)
fract_turtle.down()
fract_turtle.pendown()
fract_turtle.hideturtle()
size = 200
sierpinski_triangle(fract_turtle, 4, size)
exitonclick()
| true |
fa87af0a96105b9589fad9a32955db349089d5cd | ptsiampas/Exercises_Learning_Python3 | /18_Recursion/Exercise_18.7.10.py | 1,506 | 4.21875 | 4 | # Write a program that walks a directory structure (as in the last section of this chapter), but instead of printing
# filenames, it returns a list of all the full paths of files in the directory or the subdirectories.
# (Don’t include directories in this list — just files.) For example, the output list might have elements like this:
#
# ['C:\Python31\Lib\site-packages\pygame\docs\ref\mask.html',
# 'C:\Python31\Lib\site-packages\pygame\docs\ref\midi.html',
# ...
# 'C:\Python31\Lib\site-packages\pygame\examples\aliens.py',
# ...
# 'C:\Python31\Lib\site-packages\pygame\examples\data\boom.wav',
# ... ]
import os
def get_dirlist(path):
"""
Return a sorted list of all entries in path.
This returns just the names, not the full path to the names.
"""
dirlist = os.listdir(path)
dirlist.sort()
return dirlist
def list_files(path, prefix=""):
fileList = []
if prefix == "":
print('Folder listing for', path)
prefix = path + '/'
dirlist = get_dirlist(path)
for f in dirlist:
if not os.path.isdir(os.path.join(path, f)): # FIXME: this is ugly as, but just want to fix it now..
fileList.append(prefix + f)
fullname = os.path.join(path, f)
if os.path.isdir(fullname):
fileList.extend(list_files(fullname, prefix + f + '/'))
return fileList
def main():
print(list_files("/usr/local/lib/python3.4/dist-packages/pygame"))
return
if __name__ == '__main__':
main()
| true |
3de631c83b785cac3822aaaf26d06e85a32ce736 | ptsiampas/Exercises_Learning_Python3 | /21_Even_more_OOP/Examples_Point21.py | 2,367 | 4.5625 | 5 | class Point:
""" Point class represents and manipulates x,y coords. """
def __init__(self, x=0, y=0):
""" Create a new point at the origin """
self.x = x
self.y = y
def __str__(self): # All we have done is renamed the method
return "({0}, {1})".format(self.x, self.y)
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
def __mul__(self, other):
return self.x * other.x + self.y * other.y
def __rmul__(self, other):
""" If the left operand of * is a primitive type and the right operand is a Point, Python
invokes __rmul__, which performs scalar multiplication:
"""
return Point(other * self.x, other * self.y)
def reverse(self):
(self.x, self.y) = (self.y, self.x)
def distance_from_origin(self):
""" Compute my distance from the origin """
return ((self.x ** 2) + (self.y ** 2)) ** 0.5
def halfway(self, target):
""" Return the halfway point between myself and the target """
mx = (self.x + target.x) / 2
my = (self.y + target.y) / 2
return Point(mx, my)
def heading(s):
"""Draws a line under the heading - yes because I am bored"""
line = ""
for x in range(len(s)):
line += "="
return "{}\n{}".format(s, line)
def multadd(x, y, z):
return x * y + z
def front_and_back(front):
import copy
back = copy.copy(front)
back.reverse()
print(str(front) + str(back))
def main():
# examples of operator overloading - check the add, mul and rmul definitions
print(heading("21.8. Operator overloading Examples"))
p1 = Point(3, 4)
p2 = Point(5, 7)
print("Point{} * Point{} = {}".format(p1, p2, p1 * p2)) # Execute mul because the left of the * is a Point.
print("2 * Point{} = {}".format(p2, 2 * p2)) # Executes rmul because the left operand of * is a primitive.
print()
print(heading("21.9. Polymorphism Examples"))
print("multiadd function = {}".format(multadd(3, 2, 1)))
print("multiadd function also works with points = {}".format(multadd(2, p1, p2)))
print("multiadd function also works with points = {}".format(multadd(p1, p2, 1)))
my_list = [1, 2, 3, 4]
front_and_back(my_list)
p = Point(3, 4)
front_and_back(p)
if __name__ == '__main__':
main()
| true |
dbdf7c1059cffe23b0d8c47348e25e0c9347ed7e | ptsiampas/Exercises_Learning_Python3 | /01_03_Introduction/play_scr.py | 615 | 4.15625 | 4 | import turtle # Allows us to use turtles
wn = turtle.Screen() # Creates a playground for turtles
wn.bgcolor("lightgreen") # Sets window background colour
wn.title("Hey its me") # Sets title
alex = turtle.Turtle() # Create a turtle, assign to alex
alex.color("blue") # pen colour blue
alex.pensize(3) # Set pen size
alex.forward(50) # Tell alex to move forward by 50 units
alex.left(120) # Tell alex to turn by 90 degrees
alex.forward(50) # Complete the second side of a rectangle
turtle.mainloop() # Wait for user to close window | true |
6c151bbd8c7b00728fc6288bce8cec511d839050 | ptsiampas/Exercises_Learning_Python3 | /06_Fruitful_functions/Exercises_6.9.14-15.py | 1,449 | 4.53125 | 5 | # 14. Write a function called is_even(n) that takes an integer as an argument and returns True if the argument is
# an even number and False if it is odd.
import sys
def test(actual, expected):
""" Compare the actual to the expected value,
and print a suitable message.
"""
linenum = sys._getframe(1).f_lineno # Get the caller's line number.
if (expected == actual):
msg = "Test on line {0} passed.".format(linenum)
else:
msg = ("Test on line {0} failed. Expected '{1}', but got '{2}'."
.format(linenum, expected, actual))
print(msg)
def test_suite():
""" Run the suite of tests for code in this module (this file).
"""
test(is_even(0),True)
test(is_even(1),False)
test(is_even(2),True)
test(is_even(3),False)
test(is_odd(0),False)
test(is_odd(1),True)
test(is_odd(2),False)
test(is_odd(3),True)
def is_even(n):
if (n % 2) == 0:
return True
return False
# 15. Now write the function is_odd(n) that returns True when n is odd and False otherwise.
# Include unit tests for this function too.
def is_odd(n):
#if (n % 2) != 0:
# return True
# Finally, modify it so that it uses a call to is_even to determine if its argument is an
# odd integer, and ensure that its test still pass.
if is_even(n) == True:
return False
return True
test_suite() # Here is the call to run the tests | true |
2217a5fe8973d2d5a8d900f1c5ddc9b2b07f5689 | sobinrajan1999/258213_dailyCommit | /print.py | 518 | 4.28125 | 4 | print("hello world")
print(1+2+3)
print(1+3-4)
# Python also carries out multiplication and division,
# using an asterisk * to indicate multiplication and
# a forward slash / to indicate division.
print(2+(3*4))
# This will give you float value
print(10/4)
print(2*0.75)
print(3.4*5)
# if you do not want float value then
print(10//4)
# Exponential or power
# base 2 power 4
print(2**4)
# Chain exponential
print(2**3**2)
# Square root (result will be in float)
print(9**(1/2))
# Remainder
print(20%6)
print(1.25%0.5)
| true |
c0ced71bc1ef01689981bdc9f5c0f227ac76226a | rosexw/Practice_Python | /1-character_input.py | 842 | 4.125 | 4 | # https://www.practicepython.org/
# Create a program that asks the user to enter their name and their age. Print out a message addressed to them that tells them the year that they will turn 100 years old.
# name = raw_input("What is your name: ")
# age = int(input("How old are you: "))
# year = str((2018 - age)+100)
# print(name + " will be 100 years old in the year " + year)
# print("Were" + "wolf")
# print("Door" + "man")
# print("4" + "chan")
# print(str(4) + "chan")
# Extras:
# Add on to the previous program by asking the user for another number and printing out that many copies of the previous message. (Hint: order of operations exists in Python)
print(3 * "test")
# Print out that many copies of the previous message on separate lines. (Hint: the string "\n is the same as pressing the ENTER button)
print(3 * "test\n")
| true |
b96824853b54624a33730716da977019b9958c3d | BubbaHotepp/code_guild | /python/palindrome.py | 505 | 4.1875 | 4 | def reverse_string(x):
return x[::-1]
def compare(x,y):
if x == y:
return True
else:
return False
def main():
user_input = input('Please enter a word you think is an anagram: ')
print(user_input)
input_reversed = reverse_string(user_input)
print(input_reversed)
x = compare(user_input, input_reversed)
print(x)
if x is True:
print(f'{user_input} is a palindrome.')
else:
print(f'{user_input} is not a palindrome.')
main() | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.