blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
8f97da7c54be77e69733bb92efae07666c0ab421 | Didden91/PythonCourse1 | /Week 13/P4_XMLinPython.py | 1,689 | 4.25 | 4 | #To use XML in Python we have to import a library called ElementTree
import xml.etree.ElementTree as ET #The as ET is a shortcut, very useful, makes calling it a lot simpler
data = '''
<person>
<name>Chuck</name>
<phone type="intl">
+1 734 303 4456
</phone>
<email hide="yes" />
</person>'''
tree = ET.fromstring(data) #create a object called tree, put the xml string information from 'data' in there
print('Name:', tree.find('name').text) #in the tree find the tag name, and return the whole text content (.text)
print('Attr:', tree.find('email').get('hide')) #in the tree find the tag email and get (.get) only the data in the attribute 'hide'
#Second example:
import xml.etree.ElementTree as ET
input = '''
<stuff>
<users>
<user x="2">
<id>001</id>
<name>Chuck</name>
</user>
<user x="7">
<id>009</id>
<name>Brent</name>
</user>
<user x="29">
<id>1991</id>
<name>Ivo</name>
</user>
</users>
</stuff>'''
stuff = ET.fromstring(input)
lst = stuff.findall('users/user') # Creates a LIST called lst, and puts in there, every item it finds in the path users/user
#In other words, in the users 'directory' return every item 'user' and put in the list
print('User count:', len(lst))
for item in lst:
print(item)
print('Name', item.find('name').text) #in the tree find the tag name, and return the whole text content (.text)
print('Id', item.find('id').text) #in the tree find the tag id, and return the whole text content (.text)
print('Attribute', item.get('x')) #in the tree find the attribute x and get (.get) only the data in the attribute
| true |
69940b6c1626270cf73c0fe36c2819bbba1523bd | Didden91/PythonCourse1 | /Week 11/P5_GreedyMatching.py | 929 | 4.28125 | 4 | #WARNING: GREEDY MATCHING
#Repeat characters like * and + push OUTWARD in BOTH directions (referred to as greedy) to match THE LARGEST POSSIBLE STRING
#This can make your results different to what you want.
#Example:
import re
x = 'From: Using the : character'
y = re.findall('^F.+:', x)
print (y)
#So you want to find 'From:', so you say, starts with (^) F (F), followed by any character (.) one or more times (+) upto the colon (:)
#This finds 'From:' but it also finds 'From: Using the :'
#If this occurs, it always chooses the LARGEST ONE to return, so be careful with that.
#You can SUPRESS this behaviour (of course) by using adding another character, the questionmark '?'
import re
x = 'From: Using the : character'
y = re.findall('^F.+?:', x) #Adding the ? to the + means one or more characters, BUT NOT GREEDY
print (y)
#NOT GREEDY just means it prefers the SHORTEST string rather than the largest one
| true |
9c74e24deb16d11cc0194504b4be55ea81bd1115 | Didden91/PythonCourse1 | /Week 6/6_3.py | 645 | 4.125 | 4 | def count(letter, word):
counter = 0
for search in word:
if search == letter:
counter = counter + 1
return counter
letterinput = input("Enter a letter: ")
wordinput = input("Enter a word: ")
wordinput = wordinput.strip('b ')
counter = count(letterinput, wordinput)
print(counter)
lowercasewordinput = wordinput.lower()
if lowercasewordinput < 'banana':
print("Your word:",wordinput,"comes before banana")
elif lowercasewordinput > 'banana':
print("Your word:",wordinput,"comes after banana")
else:
print("Well everything is just bananas")
print("What I actually checked was",lowercasewordinput)
| true |
1b8b5732eeb4b7c9c767c815e5c0f2ec0676a99a | Didden91/PythonCourse1 | /Week 12/P7_HTMLParsing.py | 2,523 | 4.375 | 4 | #So now, what do we do with a webpage once we've retrieved it into our program
# We call this WEB SCRAPING, or WEB SPIDERING
# Not all website are happy to be scraped, quite a few don't want a 'robot' scraping their content
# They can ban you (account or IP) if they detect you scraping, so be careful when playing around with this.
#now onto PARSING HTML. It is difficult! You can search string manually but the internet is FULL of BAD HTML
#Errors everywhere
#FORTUNATELY, there is some software called Beautiful Soup which basically says, 'give me the HTML link and I'll return you the tags'
#I already have Beautful Soup 4 (BS4) installed.
# To call it we need to import it
import urllib.request, urllib.parse, urllib.error # First the same stuff we did earlier:
from bs4 import BeautifulSoup # and then BS4
# Now to write a simple program with BS4. NOTE: Beautiful Soup is a COMPLEX library. I'll do something simple here, but I might need to
# read up on the documentation if I want to use it more in depth.
url = input('Enter - ')
html = urllib.request.urlopen(url).read() #read() here means read the WHOLE thing, which is ok if you know the file is not so large
#This return a BYTES object and places it in HTML. BS4 knows how to deal with BYTES
soup = BeautifulSoup(html, 'html.parser') #Here we call BS4 and say, hey use the stuff in the variable html, and use your html.parser on it,
# place the results in soup
# Retrieve all of the anchor tags
tags = soup('a') #Here we call the soup object we just made (or BS4 made for us), and sort of call it like a function,
#The 'a' instruction says, hey give me the anchor tags in soup, and then place them in 'tags'
#Anchor tags are HYPERLINKS, by the way, this wasn't explained, you're basically extracting a LINK
# from the HTML.
for tag in tags:
print(tag.get('href', None)) #href is the tag used in HTML to indicate a hyperlink, so in the HTML code it is
# <a href="http://www.dr-chuck.com/page2.htm"> Second Page</a>
#That's why we're 'getting' the href part, so it prints the actual URL and nothing else
# Although I'm not sure exactly how that works
| true |
0196fbecdcaae1f917c8d17e505e2d6ca5cb8b4f | Didden91/PythonCourse1 | /Week 14/P4_Inheritance.py | 1,400 | 4.5 | 4 | # When we make a new class - we can reuse an existing class and inherit all the capabilities of an existing class
# and then add our own little bit to make our new class
#
# Another form of store and reuse
#
# Write once - reuse many times
#
# The new class (child) has all the capabilities of the old class (parent) - and then some more
#
# Again, for now this is just about learning TERMINOLOGY!
# I don't have to understand when to use this, why to use this etc. This is just to get a better grasp of the bigger picture
#
# With inheritance there is once again a hierarchical system!
# The original class is called the PARENT
# and the new class derived from it is called the CHILD
# SUBCLASSES are another word for this
#
# example:
class PartyAnimal:
x = 0
name = ""
def __init__(self, nam):
self.name = nam
print(self.name,"constructed")
def party(self) :
self.x = self.x + 1
print(self.name,"party count",self.x)
#Now FootballFan is a class which EXTENDS PartyAnimal. It has all the capabilities of PartyAnimal and MORE
#So FootballFan is an amalgamation of all this. It includes everything we see here.
class FootballFan(PartyAnimal):
points = 0
def touchdown(self):
self.points = self.points + 7
self.party()
print(self.name,"points",self.points)
s = PartyAnimal("Sally")
j = FootballFan("Jim")
s.party()
j.party()
j.touchdown()
| true |
47e3ee0aa65599b23394a1b494508e0e6e1e753b | d-robert-buckley3/FSND | /Programming_Fundamentals/Use_Classes/turtle_poly.py | 402 | 4.125 | 4 | import turtle
def draw_poly(sides, size):
window = turtle.Screen()
window.bgcolor("white")
myturtle = turtle.Turtle()
myturtle.shape("classic")
myturtle.color("black")
myturtle.speed(2)
for side in range(sides):
myturtle.forward(size)
myturtle.right(360/sides)
window.exitonclick()
if __name__ == "__main__":
draw_poly(3, 80)
| true |
ed26c58769cdce9bc099d1df83b6892e238c0804 | SummerLyn/devcamp_2016 | /python/Nov_29_Tue/warm_up.py | 527 | 4.1875 | 4 | def is_odd(num):
"""
>>> is_odd(1)
True
"""
if num % 2 == 0:
return False
else:
return True
def is_divisible(num1, num2):
"""
>>> is_divisible(4, 3)
True
>>>
"""
if num1 % num2 == 0:
return True
else:
return False
def is_palindrome(word):
"""
>>> is_palindrome("dad")
True
>>>
"""
return word == word[::-1]
def main():
print(is_odd(3))
print(is_divisible(4,3))
print(is_palindrome("dad"))
main()
| false |
7186b0324e96780924078e1d1e07058c1ddc1545 | SummerLyn/devcamp_2016 | /python/Nov_29_Tue/File_Reader/file_reader.py | 1,482 | 4.3125 | 4 | # This is an example on how to open a file as a read only text document
def open_file():
'''
Input: no input variables
Usage: open and read a text file
Output: return a list of words in the text file
'''
words = []
with open('constitution.html','r') as file:
#text = file.read()
#return text.split(" ")
for line in file:
line = line.rstrip().replace('\\n','\n')
line_words = line.split()
for w in line_words:
words.append(w)
return words
def create_frenquency_dict(word_list):
'''
Input:
Usage: puts the words into a dictionary so it has a
Output: returns how many times a word is used
'''
frenquency = {}
# 1) Loop through word_list
# a) check if word is in the dictionary and add if it isn't
# and increment count by one if it is
for word in word_list:
frenquency[word] = frenquency.get(word , 0) + 1
return frenquency
def get_max_word_in_file(frenquency_dict):
'''
Input: A dictionary of word frenquencies
Usage: Finds the max word user_word
Output: None just print the max used word
'''
frenquency = {}
for word in word_list:
frenquency[word] = frenquency.get(word , 0) + 1
return max(frenquency)
def main():
word_list = open_file()
#print(word_list)
print(create_frenquency_dict(word_list))
print(get_max_word_in_file(frenquency_dict))
main()
| true |
549d05dd07db0861e05d1a748cd34ce3cc5ed303 | SummerLyn/devcamp_2016 | /python/day3/string_problem_day3.py | 395 | 4.1875 | 4 | # Take the first and last letter of the string and replace the middle part of
# the word with the lenght of every other letter.
user_input_fun = input(" Give me a fun word. >>")
#user_input_shorter = input("Enter in a shorter word. >>")
if len(user_input_fun) < 3:
print("Error!")
else:
print(user_input_fun[0] + str(len(user_input_fun)- 2) + user_input_fun[len(user_input_fun)- 1])
| true |
1219597ac11a07ca8bbce48b6f18b61ca058052f | SummerLyn/devcamp_2016 | /python/day7/more_for_loops.py | 495 | 4.15625 | 4 | #use for range loop and then for each loop to print
word_list = ["a","b","c","d","e","f","g"]
# for each loop
for i in word_list:
print(i)
# for loop using range
for i in range(0,len(word_list)):
print(word_list[i])
#get user input
#loop through string and print value
#if value is a vowel break out of loop
user_input = input("Give me a word. >> ")
vowels = ("aeiou")
#can also cast as a list - list("aeiou")
for i in user_input:
if i in vowels:
break
print(i)
| true |
2d3d01facdd8cf1951f31bd1705391b1ccb53b68 | cafeduke/learn | /Python/Advanced/maga/call_on_object.py | 1,009 | 4.28125 | 4 | ##
# The __call__() method of a class is internally invoked when an object is called, just like a function.
#
# obj(param1, param2, param3, ..., paramN)
#
# The parameters are passed to the __call__ method!
#
# Connecting calls
# ----------------
# Like anyother method __call__ can take any number of arguments and return an object of any type.
# If the object returned by __call__, is of a class that has __call__ as well, then the next set of parameters will be passed to this __call__ method and so on.
##
class A:
def __call__(self, x):
return B(x)
class B:
def __init__(self, x):
self.x = x
def __call__(self):
return C()
class C:
pass
##
# Main
# -----------------------------------------------------------------------------
##
def main():
a = A()
b = a('Object arg to create instance of B')
c = b()
print("Type :", type(c))
# Short cut for the same thing above
print("Type :", A()('Arg')())
if __name__ == '__main__':
main()
| true |
b6bb152dc17af5ffc19dc1a6786c57bb7da80abe | ombanna/mama | /180pyramidpatt.py | 330 | 4.15625 | 4 | # 180 pyramidd Pattern Printing
n = int(input("How Many Number You Want To Print Pattern\n"))
def pyramidpatt(n):
k = 2 * n -2
for i in range(0,n):
for j in range(0,k):
print(end=" ")
k = k -2
for j in range(0,i + 1):
print("*",end=" ")
print("\r")
pyramidpatt(n)
| false |
fc1d3ba12a5e13e8e002d503e2a5e1f9e16e4736 | RLuckom/python-graph-visualizer | /abstract_graph/Edge.py | 1,026 | 4.15625 | 4 | #!/usr/bin/env python
class Edge(object):
"""Class representing a graph edge"""
def __init__(self, from_vertex, to_vertex, weight=None):
"""Constructor
@type from_vertex: object
@param from_vertex: conventionally a string; something unambiguously
representing the vertex at which the edge originates
@type to_vertex: object
@param to_vertex: conventionally a string; something unabiguously
representing the vertex at which the edge terminates
@type weight: number
@param weight: weight of the edge, defaults to None.
"""
self.from_vertex = from_vertex
self.to_vertex = to_vertex
self.weight = weight
def __str__(self):
"""printstring
@rtype: str
@return: printstring
"""
return "Edge {0}{1}, weight {2}.".format(self.from_vertex, self.to_vertex, self.weight)
if __name__ == '__main__':
x = Edge('A', 'B', 5)
print x
| true |
7ccb83743060b18258178b414afdd1ba418acd3c | lyndsiWilliams/Sprint-Challenge--Algorithms | /recursive_count_th/count_th.py | 901 | 4.28125 | 4 | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word):
# TBC
# Set a base case for recursion to stop (if the word is down to 1 or 0 letters)
if len(word) == 1 or len(word) == 0:
return 0
# Set the counting variable
count = 0
# Check if the word has 't' followed by 'h' in the first two positions
if word[0] == 't' and word[1] == 'h':
# If it does, increase the word count by 1
count += 1
# Recursively run through the input word and check the first two positions
# If the first two positions don't have 't' followed by 'h',
# Take the first letter off and check again
return count + count_th(word[1:])
| true |
1d05a84eed4a783996779cc9abe70a131995d3c5 | fahimfaisaal/Hello-Python | /fundamentals_of_python/3_loop-project.py | 299 | 4.21875 | 4 | # Odd Numbers
odd_number = int(input("Enter your number for Odd: "))
for i in range(0, odd_number + 1):
if i % 2 != 0:
print(i)
# Even number
even_number = int(input("Enter your number for even: "))
for i in range(0, even_number + 2):
if i % 2 == 0:
print(i)
| false |
3a2d5f04ac2d3fc8d498335ab744caa752df7fde | balasubramanianramesh/Python_Training | /forLoop.py | 302 | 4.4375 | 4 | for letter in 'Python': # First Example
print ('Current Letter :', letter)
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print ('Current fruit :', fruit)
for index in range(1,3):
print ('fruits[%d]: %s'% (index, fruits[index]))
print ("Good bye!") | false |
761184045db21f220fec3944baa74b7e18d6fd51 | rhenderson2/python1-class | /chapter06/hw_6-7.py | 418 | 4.125 | 4 | # homework assignment section 6-7
friend = {'first_name': 'john', 'last_name': 'wendler', 'city': 'colorado springs'}
wife = {'first_name': 'niki', 'last_name': 'henderson', 'city': 'fort wayne'}
child = {'first_name': 'carrissa', 'last_name': 'griffith', 'city': 'london'}
people = [friend, wife, child]
for person in people:
print('\n')
for key,value in person.items():
print(f"{value.title()}")
| false |
64742533ee6dd3747a8e1945a0ae3d74dd00bee7 | rhenderson2/python1-class | /Chapter03/hw_3-5.py | 627 | 4.25 | 4 | # homework assignment section 3-5
guest_list = ["Abraham Lincoln", "President Trump", "C.S.Lewis"]
print(f"Hello {guest_list[0]},\nYou are invited to dinner at my house.\n")
print(f"Hello {guest_list[1]},\nYou are invited to dinner at my house.\n")
print(f"Hello {guest_list[-1]},\nYou are invited to dinner at my house.")
print(f"\n{guest_list[1]} said he can't make it.\n")
guest_list[1] = "Andrew Wommack"
print(f"Hello {guest_list[0]},\nYou are still invited to dinner at my house.\n")
print(f"Hello {guest_list[1]},\nYou are invited to dinner at my house.\n")
print(f"Hello {guest_list[-1]},\nYou are still invited to dinner at my house.") | true |
2f84d347adabaa3c9788c2b550307e366998fc6f | RobertElias/AlgoProblemSet | /Easy/threelargestnum.py | 1,169 | 4.4375 | 4 | #Write a function that takes in an array of at least three integers
# and without sorting the input array, returns a sorted array
# of the three largest integers in the input array.
# The function should return duplicate integers if necessary; for example,
# it should return [10,10,12]for inquiry of [10,5,9,10,12].
#Solution 1
# O(n) time | O(1) space
def findThreeLargestNumbers(array):
# Write your code here.
threeLargest = [None, None, None]
for num in array:
updateLargest(threeLargest, num)
return threeLargest
# method helper function checks
# if the numbers are largets in stored array
def updateLargest(threeLargest, num):
if threeLargest[2] is None or num > threeLargest[2]:
shiftAndUpdate(threeLargest, num, 2)
elif threeLargest[1] is None or num > threeLargest[1]:
shiftAndUpdate(threeLargest, num, 1)
elif threeLargest[0] is None or num > threeLargest[0]:
shiftAndUpdate(threeLargest, num, 0)
# method helper function
def shiftAndUpdate(array, num, idx):
for i in range(idx + 1):
if i == idx:
array[i] = num
else:
arrya[i] = array[i + 1]
pass | true |
060b043e11b67ad11e5ecc8dc2076dacd6efa1cf | WebSofter/lessnor | /python/1. objects and data types/types.py | 695 | 4.21875 | 4 | """
int - integer type
"""
result = 1 + 2
print(result, type(result))
"""
float - float type
"""
result = 1 + 2.0
print(result, type(result))
"""
string - string type
"""
result = '1' * 3
print(result, type(result))
"""
list - list type
"""
result = ['1','hello', 'world', 5, True]
print(result, type(result))
"""
tuple - tuple type
"""
result = ('1','hello', 'world', 5, True)
print(result, type(result))
"""
seat - seat type (all values in seat must by or autoconverting as unical)
"""
result = {'1','hello', 'world', 5, True, 5}
print(result, type(result))
"""
dict- seat type (it simillar as array with custom keys)
"""
result = {'a': 'hello', 'b': 'world'}
print(result, type(result)) | true |
42f0dd12e80adbf732c8cef53f1deff43826049f | mwagrodzki/codecool_dojos | /poker_hand.py | 995 | 4.15625 | 4 | def poker_hand(table):
'''
Write a poker_hand function that will score a poker hand. The function
will take an array 5 numbers and return a string based on what is inside.
python3 -m doctest poker_hand.py
>>> poker_hand([1, 1, 1, 1, 1])
'five'
>>> poker_hand([2, 2, 2, 2, 3])
'four'
>>> poker_hand([1, 1, 1, 2, 3])
'three'
>>> poker_hand([2, 2, 3, 3, 4])
'twopairs'
>>> poker_hand([1, 2, 2, 3, 4])
'pair'
>>> poker_hand([1, 1, 2, 2, 2])
'fullhouse'
>>> poker_hand([1, 2, 3, 4, 6])
'nothing'
'''
temp = [table.count(x) for x in set(table)]
if 5 in temp:
return 'five'
elif 4 in temp:
return 'four'
elif 3 in temp and not 2 in temp:
return 'three'
elif 3 in temp and 2 in temp:
return 'fullhouse'
elif 2 in temp:
k = temp.count(2)
if k == 1:
return 'pair'
elif k == 2:
return 'twopairs'
return 'nothing'
| false |
e2f04c145a4836d14f933ae04557dd6598561af2 | blfortier/cs50 | /pset6/cash.py | 1,657 | 4.1875 | 4 | from cs50 import get_float
def main():
# Prompt the user for the amount
# of change owed until a positive
# number is entered
while True:
change = get_float("Change owed: ")
if (change >= 0):
break
# Call the function that will
# print the amount of coins that
# will be given to the user
changeReturned(change)
# A function that will convert the
# amount of change entered into cents
# and will calculate the number of
# coins needed to make change
def changeReturned(change):
# Convert change into cents
cents = round(change * 100)
# Set the counter to 0
count = 0;
# Calculate how many quarters can be used
if cents >= 25:
quarters = cents // 25;
# Keep track of amount of coins
count += quarters
# Keep track of amount of change
cents %= 25
# Calculate how many dimes can be used
if cents >= 10:
dimes = cents // 10
# Keep track of amount of coins and change
count += dimes
# Keep track of amount of change
cents %= 10
# Calculate how many nickels can be used
if cents >= 5:
nickels = cents // 5
# Keep track of amount of coins and change
count += nickels
# Keep track of amount of change
cents %= 5
# Calculate how many pennies can be used
if cents >= 1:
pennies = cents // 1
# Keep track of amount of coins and change
count += pennies
# Keep track of amount of change
cents %= 1
# Print total coins used
print(count)
if __name__ == "__main__":
main() | true |
4164c5ecc2da48210cb32028b01493a06b111873 | amymou/Python- | /masterticket.py | 2,298 | 4.34375 | 4 | SERVICE_CHARGE = 2
TICKET_PRICE = 10
tickets_remaining = 100
# Outpout how many tickets are remaining using the ticket_remaining variable
# Gather the user's name and assign it to a new variable
names = input("Please provide your name: ")
# Prompt the user by name and ask how many tickets they would like
print("Hi {}.".format(names))
tickets_asked = int()
# Create the calculate_price function. It takes number of tickets and returns
# num_tickets*TICKET_PRICE
def calculate_price(number_of_tickets):
return(number_of_tickets*TICKET_PRICE)+SERVICE_CHARGE
# Run this code continuously until we run of tickets
while tickets_remaining-tickets_asked>0:
# Expect a ValueError to happen and handle it appropriately...remember to test it out!
try:
tickets_asked = int(input("How many tickets would you like? "))
#Raise a ValueError if the request is for more tickets than are available
if tickets_asked > tickets_remaining:
raise ValueError("There are only {} tickets remaining".format(tickets_remaining))
except ValueError as err:
#Include the error text in the output
print("Oh no, we ran into an issue {}. Please try again!".format(err))
else:
# Calculate the price (number of tickets multiplied by the price) and assign it to variable
total_price = calculate_price(tickets_asked)
# Output the price to the screen
print("Okay, the total price is ${}".format(total_price))
# Prompt user if they want to proceed. Y/N?
proceed =input("Would you like to proceed? Yes/No ")
# If they want to proceed
if proceed == 'Yes':
# print out to the screen "SOLD!" to confirm purchase
print("SOLD!")
# and then decrement the tickets remaining by the number of tickets purchased
tickets_remaining -= tickets_asked
print("There are {} tickets remaining.".format(tickets_remaining))
# Otherwise...
print("Thank you, {}!".format(names))
user_keep_buying =input("Would you like more tickets? Yes/No ")
if user_keep_buying == 'No':
# Thank them by name
print("Thank you for visiting {}!".format(names))
break
# Nofify user that the tickets are sold out
else:
print("There are no more tickets for this event")
| true |
265462e6a06f4b50a87aecb72e05645d2a62d5e1 | danriti/project-euler | /problem019.py | 1,498 | 4.15625 | 4 | """ problem019.py
You are given the following information, but you may prefer to do some research
for yourself.
- 1 Jan 1900 was a Monday.
- Thirty days has September, April, June and November. All the rest have
thirty-one, Saving February alone, Which has twenty-eight, rain or shine.
And on leap years, twenty-nine.
- A leap year occurs on any year evenly divisible by 4, but not on a century
unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century
(1 Jan 1901 to 31 Dec 2000)?
"""
DAYS_IN_MONTH = {
1: 31, # jan
2: 28, # feb
3: 31, # mar
4: 30, # april
5: 31, # may
6: 30, # june
7: 31, # july
8: 31, # aug
9: 30, # sept
10: 31, # oct
11: 30, # nov
12: 31 # dec
}
DAYS_OF_WEEK = [
'monday',
'tuesday',
'wednesday',
'thursday',
'friday',
'saturday',
'sunday'
]
def main():
start = 1900
end = 2000
day_offset = 0 # 1 Jan 1900 was a Monday, so start there
any_given_sundays = []
for year in xrange(start, end + 1):
for month, days in DAYS_IN_MONTH.iteritems():
for day in xrange(1, days+1):
index = (day - 1 + day_offset) % 7
if DAYS_OF_WEEK[index] == 'sunday' and day == 1 and \
year >= 1901:
any_given_sundays.append((year, month, day,))
day_offset = index + 1
print len(any_given_sundays)
if __name__ == '__main__':
main()
| true |
ae99ba05dfed268a96cf36014ece74a6dc8ad58c | yash1th/hackerrank | /python/strings/Capitalize!.py | 418 | 4.125 | 4 | def capitalize(string):
return ' '.join([i.capitalize() for i in string.split(' ')])
if __name__ == '__main__':
string = input()
capitalized_string = capitalize(string)
print(capitalized_string)
# s = input().split(" ") #if i use default .split() it will strip the whitespace otherwise it will only consider single space
# for i in range(len(s)):
# s[i] = s[i].capitalize()
# print(" ".join(s))
| true |
23b10c277a1632f5a41c15ea55f8ca3598cf43c5 | FredericoIsaac/Case-Studies | /Data_Structure_Algorithms/code-exercicies/queue/queue_linked_list.py | 1,696 | 4.28125 | 4 | class Node:
def __init__(self, value):
self.value = value
self.next = None
class Queue:
def __init__(self):
# Attribute to keep track of the first node in the linked list
self.head = None
# Attribute to keep track of the last node in the linked list
self.tail = None
# Attribute to keep track of how many items are in the stack
self.num_elements = 0
def enqueue(self, value):
# Create a new node with the value to introduce
new_node = Node(value)
# Checks is queue is empty
if self.head is None:
# If queue empty point both head and tail to the new node
self.head = new_node
self.tail = self.head
else:
# Add data to the next attribute of the tail (i.e. the end of the queue)
self.tail.next = new_node
# Shift the tail (i.e., the back of the queue)
self.tail = self.tail.next
# Increment number of elements in the queue
self.num_elements += 1
def dequeue(self):
""" Eliminate first element of the queue and return that value """
# Checks if queue empty, if empty nothing to dequeue
if self.is_empty:
return None
# Save value of the element
value = self.head.value
# Shift head over to point to the next node
self.head = self.head.next
# Update number of elements
self.num_elements -= 1
# Return value that eliminate
return value
def size(self):
return self.num_elements
def is_empty(self):
return self.num_elements == 0 | true |
19d88c04da25f392e92c55469f8ebac6cdb5ba1b | frostickflakes/isat252s20_03 | /python/fizzbuzz/fizzbuzz.py | 1,291 | 4.15625 | 4 | """A FizzBuzz program"""
# import necessary supporting libraries or packages
from numbers import Number
def fizz(x):
"""
Takes an input `x` and checks to see if x is a
number, and if so, also a multiple of 3.
If it is both, return 'Fizz'.
Otherwise, return the input.
"""
return 'Fizz' if isinstance(x, Number) and x % 3 == 0 else x
def buzz(x):
"""
Takes an input `x` and checks to see if x is a
number, and if so, also a multiple of 5.
If it is both, return 'Buzz'.
Otherwise, return the input.
"""
return 'Buzz' if isinstance(x, Number) and x % 5 == 0 else x
def fibu(x):
"""
Takes an input `x` and checks to see if x is a
number, and if so, also a multiple of 15.
If it is both, return 'FizzBuzz'.
Otherwise, return the input.
"""
return 'FizzBuzz' if isinstance(x, Number) and x % 15 == 0 else x
def play(start, end):
"""
Given a start number and an end number, produce
all of the output expected for a game of FizzBuzz
as an array.
"""
# initialize an empty list (array) to hold our output
output = []
# loop from the start number to the end number
for x in range(start, end + 1):
# append the tranformed input to the output array
output.append(buzz(fizz(fibu(x))))
return output
| true |
c062d016b88b589ffdccaa0175269439778a8ae3 | sahil-athia/python-data-types | /strings.py | 979 | 4.5625 | 5 | # strings can be indexed and sliced, indexing starts at 0
# example: "hello", regular index: 0, 1, 2, 3, 4, reverse index: 0, -4, -3, -2, -1
greeting = "hello"
print "hello \nworld \n", "hello \t world" # n for newline t for tab
print greeting # will say hello
print greeting[1] # will say 'e'
print greeting[-1] # will say '0'
print len(greeting) # length function
# slicing lets us grab a subsection of characters, syntax: [start:stop:step]
# start is the index of where we start
# stop is where we go up to (but not include)
# step is the size of the jump
my_string = "abcdefghijk"
print my_string
print my_string[2:] # from 2 all the way to the end
print my_string[:3] # will give back abc [0:3]
print my_string[3:6] # will give back def
print "setting the step size"
print my_string[::] # from 0 to end with a step size of 1
print my_string[::2] # from 0 to end with a step size of 2
print my_string[::-1] # this can be used to reverse a string since the step size is -1 | true |
80338a9ae77a07f34f570ab5af53f0eabb3c277a | Divij808/basic_programming_exercises | /basic_command_line_calulator.py | 873 | 4.25 | 4 | import re
import math
calculator = input("enter math equation")
match = re.search(r'(\d+)(.+?)(\d+)', calculator.strip())
if match is None:
print("Do not know the maths equation")
else:
first = int(match.group(1))
second = match.group(2).strip()
third = int(match.group(3))
if second.strip() == "*":
answer = first * third
print(answer)
elif second.strip() == "/":
answer = first / third
print(answer)
elif second == "+":
answer = first + third
print(answer)
elif second == "-":
answer = first - third
print(answer)
elif second.strip() == "%":
answer = first % third
print(answer)
elif second.strip() == "^":
answer = math.pow(first, third)
print(answer)
else:
error = "Do not know the maths equation"
print(error)
| false |
62c86d943e116d8cafc2e3b5f180356b56896b1a | Kiranathas/Python-para-no-programadores | /promedio_notas.py | 673 | 4.125 | 4 | #COMPARAR notas
nota_uno=10
nota_dos=6
nota_tres=8
#promedio
promedio= (nota_uno+nota_dos+nota_tres)/3
print(promedio)
#mostrar si aprobó o no.
if promedio >=6:
print("aprobado")
else:
print("desaprobado")
# ~ El usuario debe ingresar una nota (Suponiendo que siempre es menor que 11)
# ~ Mostrar un msg "Excelente" si la nota es un 10
# ~ un "muy bien" si esta entre 7 y 9
# ~ un "bien" si esta entre un 4 y un 6
# ~ sino mostrar "mal"
nota= int(input("ingrese su nota: "))
if nota == 10:
print("excelente")
elif nota >=7 and nota <=9:
print("muy bien")
elif nota >=4 and nota <=6:
print("bien")
else:
print("mal") | false |
cc726350a1aeb82295bc788c582fc1b2164faed3 | mindful-ai/28092020LVC | /day_02/labs/lab_01.py | 660 | 4.1875 | 4 | # -------------------------------------------------
# LAB 1
# -------------------------------------------------
L = ['red', 'red', 'green', 'blue', 'orange']
# Removed one red: ['red', 'green', 'blue', 'orange']
L.remove('red')
# 'golden' was added: ['red', 'green', 'blue', 'orange', 'golden']
L.append('golden')
# ----------------- ['green', 'golden', 'blue', 'orange', 'red']
# reversed every item
'''
temp = []
for item in L:
temp.append(item[::-1])
L = temp
'''
L = [item[::-1] for item in L]
# reverse sorted
L.sort(reverse=True)
print(L)
# OUTPUT > ['neerg', 'nedlog', 'eulb', 'egnaro', 'der']
| false |
ecaf58ae492a1655d764d35ffebf3c8430905a61 | mindful-ai/28092020LVC | /day_02/labs/lab_02_alternate_pythonic.py | 365 | 4.25 | 4 | # -------------------------------------------------
# LAB 2 - Determine if a number is prime or not
# -------------------------------------------------
# input
n = int(input('Enter a number: '))
# process
for i in range(2, n):
if(n % i == 0):
print('The number is not prime')
break
else:
print('The number is a prime')
| false |
bb023dfb9addee809a0c50198632e3d10f5ffecb | AlfredodlRC/github-upload | /ejercicio3.py | 260 | 4.125 | 4 | print("Desea continuar:")
entrada=input()
if entrada == "no" or entrada =="n":
print("Saliendo")
elif entrada =="si" or entrada =="s":
print("continuando")
print("Completado!")
else:
print("Por favor la proxima vez conteste con si o no")
| false |
70dbef3e266ee7b61417b37099278c4d0cc0a3f7 | QAQUQvQ/Learn_Python | /learn/basic/start.py | 2,579 | 4.21875 | 4 | #!/usr/bin/python3
print("看到我了吗?")
# 第一种注释
'''
第二种注释
第二种注释
'''
"""
第三种注释
第三种注释
"""
print('上面的都没有执行。')
if True:
print("True")
else:
print("False")
word = '字符串'
sentence = "这是一个句子。"
paragraph = """这是一个段落,
可以由多行组成"""
str = 'Runoob'
print(str) # 输出字符串
print(str[0:-1]) # 输出第一个到倒数第二个的所有字符
print(str[0]) # 输出字符串第一个字符
print(str[2:5]) # 输出从第三个开始到第五个的字符
print(str[2:]) # 输出从第三个开始的后的所有字符
print(str * 2) # 输出字符串两次
print(str + '你好') # 连接字符串
print('------------------------------')
print('hello\nrunoob') # 使用反斜杠(\)+n转义特殊字符
print(r'hello\nrunoob') # 在字符串前面添加一个 r,表示原始字符串,不会发生转义
a = 5
b = 1.23
c = True
# 列表示例
list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7]
list3 = ["a", "b", "c", "d"]
print("list1[0]: ", list1[0])
print("list2[1:5]: ", list2[1:5])
list = ['Google', 'Runoob', 1997, 2000]
print("第三个元素为 : ", list[2])
list[2] = 2001
print("更新后的第三个元素为 : ", list[2])
list.append(2020)
print(list)
print(list[4])
list = ['Google', 'Runoob', 1997, 2000]
print("原始列表 : ", list)
del list[2]
print("删除第三个元素 : ", list)
元组示例
tup1 = ('Google', 'Runoob', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d"; # 不需要括号也可以
tup1 = (12, 34.56)
tup2 = ('abc', 'xyz')
# 以下修改元组元素操作是非法的。
# tup1[0] = 100
# 创建一个新的元组
tup3 = tup1 + tup2;
print(tup3)
集合示例
thisset = set(("Google", "Runoob", "Taobao"))
thisset.add("Facebook")
print(thisset)
thisset.update({1,3})
print(thisset)
thisset.remove("Taobao")
print(thisset)
thisset.remove("Facebook")
print(thisset)
print(len(thisset))
thisset.clear()
print(thisset)
# 字典示例
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
print("dict['Alice']: ", dict['Alice'])
print("dict['Age']: ", dict['Age'])
dict['Age'] = 8 # 更新 Age
dict['School'] = "菜鸟教程" # 添加信息
print("dict['Age']: ", dict['Age'])
print("dict['School']: ", dict['School'])
del dict['Name'] # 删除键 'Name'
dict.clear() # 清空字典
del dict # 删除字典
# print("dict['Age']: ", dict['Age'])
# print("dict['School']: ", dict['School'])
| false |
5eea12122a9ff7e636d3e6e6d7c81eff21adaa5a | RachelKolk/Intro-Python-I | /src/lists.py | 808 | 4.3125 | 4 | # For the exercise, look up the methods and functions that are available for use
# with Python lists.
x = [1, 2, 3]
y = [8, 9, 10]
# For the following, DO NOT USE AN ASSIGNMENT (=).
# Change x so that it is [1, 2, 3, 4]
# YOUR CODE HERE
x.append(4)
print(x)
# Using y, change x so that it is [1, 2, 3, 4, 8, 9, 10]
# YOUR CODE HERE
x.extend(y)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 10]
# YOUR CODE HERE
x.remove(8)
print(x)
# Change x so that it is [1, 2, 3, 4, 9, 99, 10]
# YOUR CODE HERE
x.insert(5, 99)
print(x)
# Print the length of list x
# YOUR CODE HERE
print(len(x))
# Print all the values in x multiplied by 1000
# YOUR CODE HERE
def mult_by_thousand(num):
return num * 1000
multiplied = map(mult_by_thousand, x)
multiplied_list = list(multiplied)
print(multiplied_list) | true |
f73825065f2bd67c2b36947b143ebe90a9ec2ce1 | Elisenochka/.vscode | /classes.py | 1,207 | 4.21875 | 4 | numbers = [1, 2]
# Class: blueprint for creating new objects
# Object: instance of a class
#Class: Human
# Objects: John, Mary, Jack
class Point:
default_color = "red"
def __init__(self, x, y):
self.x = x
self.y = y
def draw(self):
print(f"Point ({self.x},{self.y})")
def __str__(self):
return f"({self.x},{self.y})"
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __gt__(self, other):
return self.x > other.x and self.y > other.y
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)
@classmethod
def zero(cls):
return cls(0,0)
Point.default_color = "yellow"
mypoint = Point(1,2)
print(mypoint.default_color)
print(Point.default_color)
print(mypoint.x)
print(mypoint.y)
mypoint.z = 3
print(mypoint.z)
mypoint.draw()
yourpoint = Point(3,4)
yourpoint.draw()
print(yourpoint.default_color)
print(type(mypoint))
print(isinstance(mypoint, Point))
print(isinstance(mypoint, int))
zeropoint = Point(0,0)
zeropoint = Point.zero()
Point.zero()
onemorepoint = Point(1,2)
print(mypoint == onemorepoint)
print(mypoint + yourpoint + onemorepoint)
| false |
0f65a069cd882e3aac41649d09c1adbfe901a479 | vskemp/2019-11-function-demo | /list_intro.py | 2,910 | 4.65625 | 5 | # *******How do I define a list?
grocery_list = ["eggs", "milk", "bread"]
# *******How do I get the length of a list?
len(grocery_list)
# ******How do I access a single item in a list?
grocery_list[1]
# 'milk'
grocery_list[0]
# 'eggs'
#Python indexes start at 0
# ******How do I add stuff to a list?
grocery_list.append("beer")
# ['eggs', 'milk', 'bread', 'beer']
grocery_list.append("cat food")
# ['eggs', 'milk', 'bread', 'beer', 'cat food']
# ******How do I access the last item in a list?
grocery_list[-1]
# *******How do I access multiple items in a list?
grocery_list[0:3] # known as a slice (Starts at index[0] and goes up to but not including index[3])
# *******What is "iteration" and how do I do that with a list?
# To iterate a list, use a FOR LOOP
# You need to buy: eggs
# You need to buy: milk
# You need to buy: bread
# ...
for item in grocery_list:
print(f"You need to buy {item}")
# Item is an automatic variable
# *******How do I replace stuff in a list?
grocery_list[1] = "almond milk"
# replaces "milk" with "almond milk"
# *******How do I replace multiple items in a list?
# grocery_list[0:3] = "chocolate"
# grocery_list["c", "h", "o", "c", "o", "l", "a", "t", "e", "beer", "cat food"]
# Don't do that
an_item = "awesome" + an_item
for item in grocery_list:
grocery_list[???] = "awesome " + item
# replaces everything with cheese
index = 0
while index < len(grocery_list):
# print(grocery_list[index])
grocery_list[index] = "cheese"
index += 1
# adds awesome before every list entry
index = 0
while index < len(grocery_list):
# print(grocery_list[index])
grocery_list[index] = "awesome" + grocery_list[index]
index += 1
# ******How do I remove stuff from a list?
grocery_list.pop() #---->gives/removes last item of the list until list is empty \
#H******How to combine lists?
grocery_list = ["eggs", "milk", "bread"]
snacks = ["gummy bears", "pringles", "more beer"]
for snakcs in snacks:
grocery_list.append(snacks)
grocery_list.extend(snacks)
# list can be concatinated!
grocery_list + snacks
new_grocery_list = grocery_list + snacks
#******How do I create a list of lists
chris_dirs = ["Jonathan", "Tedge"]
seans_dirs = ["Evan", "Eric"]
all_dirs = [chris_dir, seans_dir]
all_dirs
[['Jonathan', 'Tedge'], ['Evan', 'Eric']]
#******How do I access items in a list... that's inside another list?
# NESTED LISTS
all_dirs = [chris_dir, seans_dir]
all_dirs
[['Jonathan', 'Tedge'], ['Evan', 'Eric']]
all_dirs[0]
['Jonathan', 'Tedge']
all_dirs[0][1]
'Tedge'
all_dirs[0][1] = ["Liz", "Tasha"]
all_dirs
[["Jonathan", ["Liz", "Tasha"]] ["Evan", "Eric"]]
all_dirs[0][1][1]
"Tasha"
all_dirs[0][1] = "Tedge"
[['Jonathan', 'Tedge'], ['Evan', 'Eric']]
count = 0
for dir_list in all_dirs:
print(dir_list)
["Jonathan", "Tedge"]
["Evan", "Eric"]
for name in dir_list:
print(name)
count += 1
count?
Jonathan
Tedge
Evan
Eric
4 | true |
81e42c23911fce65155e1da44ca35666e507bd6e | helaahma/python | /loops_task.py | 1,296 | 4.125 | 4 | #define an empty list which will hold our dictionary
list_items= []
#While loop, and the condition is True
while True:
#User 1st input
item= input ("Please enter \"done\" when finished or another item below: \n")
# Define a conditional statement to break at "Done" input
if item == "done" or item=="Done":
break
#return to the loop
#User input
price= input ("Please enter the price of the item below: \n")
quant= input ("Please enter quantity of the item below: \n")
#Required by the example
price_items= int(price)*int(quant)
#Add a dictionary to enter multiple variables
dict={}
#Add 1st key
dict["item"]=item
#Add 2nd key
dict["price"]=price
#Add 3rd key
dict["quantity"]=quant
#And the last key
dict["all"]=price_items
#Append our dictionary to the list_items
list_items.append(dict)
#Define new variable that shall be used later to calculate the sum of "all" key in the dictionary
total = 0
#Use for loop as required in the task but also to iterate over the values where i is now the dict
for i in list_items:
#print reciept
print (i["quantity"], i["item"], i["price"], i["all"])
#Now we use total which will iterate over "all" key and add the values up (Note to self: I used i)
total += i["all"]
#print the total price
print ("total: ", total, " K.D")
| true |
b55dfd6fe18a15149ff4befa6199165655c60011 | mspang/sprockets | /stl/levenshtein.py | 1,949 | 4.40625 | 4 | """Module for calculating the Levenshtein distance bewtween two strings."""
def closest_candidate(target, candidates):
"""Returns the candidate that most closely matches |target|."""
return min(candidates, key=lambda candidate: distance(target, candidate))
def distance(a, b):
"""Returns the case-insensitive Levenshtein edit distance between |a| and |b|.
The Levenshtein distance is a metric for measuring the difference between
two strings. If |a| == |b|, the distance is 0. It is roughly the number
of insertions, deletions, and substitutions needed to convert |a| -> |b|.
This distance is at most the length of the longer string.
This distance is 0 iff the strings are equal.
Examples:
levenshtein_distance("cow", "bow") == 1
levenshtein_distance("cow", "bowl") == 2
levenshtein_distance("cow", "blrp") == 4
See https://en.wikipedia.org/wiki/Levenshtein_distance for more background.
Args:
a: A string
b: A string
Returns:
The Levenshtein distance between the inputs.
"""
a = a.lower()
b = b.lower()
if len(a) == 0:
return len(b)
if len(b) == 0:
return len(a)
# Create 2D array[len(a)+1][len(b)+1]
# | 0 b1 b2 b3 .. bN
# ---+-------------------
# 0 | 0 1 2 3 .. N
# a1 | 1 0 0 0 .. 0
# a2 | 2 0 0 0 .. 0
# a3 | 3 0 0 0 .. 0
# .. | . . . . .. .
# aM | M 0 0 0 .. 0
dist = [[0 for _ in range(len(b)+1)] for _ in range(len(a)+1)]
for i in range(len(a)+1):
dist[i][0] = i
for j in range(len(b)+1):
dist[0][j] = j
# Build up the dist[][] table dynamically. At the end, the Levenshtein
# distance between |a| and |b| will be in the bottom right cell.
for i in range(1, len(a)+1):
for j in range(1, len(b)+1):
cost = 0 if a[i-1] == b[j-1] else 1
dist[i][j] = min(dist[i-1][j] + 1,
dist[i][j-1] + 1,
dist[i-1][j-1] + cost)
return dist[-1][-1]
| true |
e2064d9111bc5b9d73aeaf79eb3b248c25552b54 | ash0x0/AUC-ProgrammingLanguagePython | /Assignment.1/Qa.py | 506 | 4.3125 | 4 | """This module received three numbers from the user, computes their sum and prints the sum to the screen"""
try:
# Attempt to get input and cast to proper numeric type float
x = float(input("First number: "))
y = float(input("Second number: "))
z = float(input("Third number: "))
except ValueError:
# If cast fails print error message and exit with error code
print("Invalid input.")
exit(1)
# If nothing went wrong with input casting, sum and print
print("Sum is", x + y + z)
| true |
1ea7e928f266a8d63ec7735333632901954a1dea | ash0x0/AUC-ProgrammingLanguagePython | /Assignment.1/Qf.py | 763 | 4.15625 | 4 | """This module receives a single number input from the user for a GPA and prints a message depending on the value"""
try:
# Attempt to get input and cast to proper numeric type float
x = float(input("GPA: "))
except ValueError:
# If cast fails print error message and exit with error code
print("Invalid input")
exit(1)
"""Print the proper message depending on the range, if value isn't in the range print an error message
and exit with error code"""
if 0 <= x < 1:
print("No comment!")
elif 1 <= x < 2:
print("Hmm!")
elif 2 <= x < 3:
print("Good!")
elif 3 <= x <= 4:
print("Superb!")
else:
print("Invalid input, must be in range [0,4]")
# The exit is needles, it is merely here to indicate an error code
exit(1)
| true |
179d5d73c249b74a4056eaf0a6c1f9de6f4fc892 | AmandaMoen/StartingOutWPython-Chapter5 | /bug_collector.py | 1,141 | 4.1875 | 4 | # June 8th, 2010
# CS110
# Amanda L. Moen
# 1. Bug Collector
# A bug collector collects bugs every day for seven days. Write
# a program that keeps a running total of the number of bugs
# collected during the seven days. The loop should ask for the
# number of bugs collected for each day, and when the loop is
# finished, the program should display the total number of bugs
# collected.
def main():
# Call an intro function so the user doesn't have to
# press Enter to start the function.
intro()
# Initialize an accumulator variable.
bugs_collected = 0.0
# Ask the user to enter the number of bugs collected for each
# of the 7 days.
for counter in range(7):
daily = input('Enter the number of bugs collected daily: ')
bugs_collected = bugs_collected + daily
# Display the total bugs collected.
print 'The total number of bugs collected over 7 days was', bugs_collected
def intro():
# Explain what we are doing.
print 'This program calculates the sum of'
print 'the number of bugs collected over'
print 'a 7 day period.'
# Call the main function.
main()
| true |
2ebb6abe09a57a9ba5b4acdd4cf91b1a59b52545 | mkioga/17_python_Binary | /17_Binary.py | 637 | 4.375 | 4 |
# ==================
# 17_Binary.py
# ==================
# How to display binary in python
# Note that {0:>2} is for spacing. >2 means two spaces
# and on 0:>08b means 8 spaces with zeros filling the left side
# Note that adding b means to display in binary
for i in range(17):
print("{0:>2} in binary is {0:>08b}".format(i))
print()
# Here we have (0:>02} which has 0 filling the left side.
for i in range(17):
print("{0:>02} in binary is {0:>08b}".format(i))
# This is experimenting with high numbers to see how they display in binary
print()
for i in range(1000):
print("{0:>3} in binary is {0:>016b}".format(i))
| true |
ab96acd191ac9f8f97ec54b2de9e08b2b62261ca | zenithude/Python-Leetcode | /7-reverseDigit.py | 1,380 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
@author : zenithude
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note: Assume we are dealing with an environment which could only store
integers within the 32-bit signed integer range: [−2**31, 2**31 − 1]. For the
purpose of this problem, assume that your function returns 0 when the
reversed integer overflows.
Remarque: Supposons que nous ayons affaire à un environnement qui ne
pourrait stocker que des entiers dans la plage d'entiers signés 32 bits: [
−2**31, 2**31 - 1]. Aux fins de ce problème, supposez que votre fonction
renvoie 0 lorsque l'entier inversé déborde.
"""
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if -2 ** 31 < x < 2 ** 31 - 1:
listX = list(str(abs(x)))
listX.reverse()
if x < 0:
y = '-' + ''.join(listX)
else:
y = ''.join(listX)
if -2 ** 31 < int(y) < 2 ** 31 - 1:
return int(y)
else:
return 0
return 0
s = Solution()
print(s.reverse(-130))
x = 5321252021
print(s.reverse(x))
print(x < 2 ** 31)
| false |
32bdfbc9a0a8a1c6dac00220d7cd5a5f6932062b | zenithude/Python-Leetcode | /h-index.py | 1,936 | 4.34375 | 4 | # -*- coding: utf-8 -*-
"""
@author : zenithude
Given an array of citations (each citation is a non-negative integer) of a
researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index
h if h of his/her N papers have at least h citations each, and the other N −
h papers have no more than h citations each."
Example:
Input: citations = [3,0,6,1,5]
Output: 3
Explanation: [3,0,6,1,5] means the researcher has 5 papers in total and each
of them had received 3, 0, 6, 1, 5 citations respectively.
Since the researcher has 3 papers with at least 3 citations each and the
remaining two with no more than 3 citations each, her h-index is 3.
Note: If there are several possible values for h, the maximum one is taken
as the h-index.
"""
from bisect import bisect_right
class Solution_1:
def hIndex(self, citations):
"""
:param citations : List[int]
:return: int
"""
citations.sort(reverse=True)
ans = 0
for i, c in enumerate(citations, 1):
if c >= i: ans = i
return ans
class Solution_2:
def hIndex(self, citations):
"""
:param citations : List[int]
:return: int
"""
return next(
(len(citations) - i for i, x in enumerate(sorted(citations)) if
len(citations) - i <= x), 0)
class Solution:
def hIndex(self, citations):
"""
:param citations : List[int]
:return: int
"""
return bisect_right([i - c for i, c in
enumerate(sorted(citations, reverse=True), 1)], 0)
citations = [3, 0, 6, 1, 5]
obj_1 = Solution_1()
obj_2 = Solution_2()
obj = Solution()
print(obj_1.hIndex(citations))
print(obj_2.hIndex(citations))
print(obj.hIndex(citations))
| true |
0cbefae29e6cf212a779c7da538661df56063fa5 | zenithude/Python-Leetcode | /removeAllGivenElement.py | 2,245 | 4.125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: zenithude
Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
"""
class ListNode(object):
"""List of Nodes Linked."""
def __init__(self, val=0, nextval=None):
"""
Initialize the list.
Parameters
----------
val : TYPE int
nextval : Type int
Returns
-------
None.
"""
self.val = val
self.nextval = None
def constructListNode(arr):
"""
Construct ListNode with a List
:param arr: List()
:return: ListNode()
"""
NewListNode = ListNode(arr[0])
arr.pop(0)
if len(arr) > 0:
NewListNode.nextval = constructListNode(arr)
return NewListNode
def headLength(head):
"""
Function return number of Nodes in ListNode().
:param head: ListNode()
:return: int
"""
numberNode = 0
while head is not None:
head = head.next
numberNode += 1
return numberNode
def listPrint(node):
print("None", end='<-->')
while node is not None:
print(node.val, end='<-->')
last = node
node = node.nextval
print(node)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head, val):
"""
:param head : ListNode
:param val: int
:return : ListNode
"""
if not head:
return
factice = ListNode(float('-inf'))
factice.nextval = head
previous, current = factice, factice.nextval
while current:
if current.val == val:
previous.nextval = current.nextval
else:
previous = current
current = current.nextval
return factice.nextval
arr = [1, 2, 6, 3, 4, 5, 6]
head = constructListNode(arr)
obj = Solution()
listPrint(obj.removeElements(head, 6)) | true |
661959a1cace03d1be96a892ed6d8115c734a40f | zenithude/Python-Leetcode | /reorderList.py | 2,071 | 4.28125 | 4 | # -*- coding: utf-8 -*-
"""
@author : zenithude
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be
changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->3.
"""
class ListNode():
"""List of Nodes."""
def __init__(self, x):
"""
Initialize the list.
Parameters
----------
x : TYPE int
Returns
-------
None.
"""
self.val = x
self.next = None
def __str__(self):
"""Print the List."""
return '<ListNode {}>'.format(self.val)
def listPrint(head):
"""
Print the ListNode passed in params.
:param head : type ListNode
:return: nothing just print the Listnode
"""
while head:
print(head, end='->')
head = head.next
print(head)
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
# step 1: find middle
if not head:
return []
slow, fast = head, head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
# step 2: reverse second half
prev, curr = None, slow.next
while curr:
after = curr.next
curr.next = prev
prev = curr
curr = after
slow.next = None
# step 3: merge lists
head1, head2 = head, prev
while head2:
after = head1.next
head1.next = head2
head1 = head2
head2 = after
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
s = Solution()
listPrint(s.reorderList(a)) | true |
753f8053bf83931bf83cf1da422b89416eeb4184 | prasant73/python | /programs/m1_list_rotation.py | 605 | 4.1875 | 4 | from inputs import list_input
import cProfile
def forward_rotation(l, n):
for i in range(n):
for i in range(len(l)-1):
l[i],l[i+1] = l[i+1],l[i]
return l
def backward_rotation(l, n):
for i in range(n):
for i in range(-len(l)-1,-1):
l[i-1],l[i] = l[i],l[i-1]
return l
l = list_input(int(input("Enter the number of numbers you want as inputs : ")))
num_rot = int(
input(
"Enter the number of rotation you want : "
)
)
print(forward_rotation (l, num_rot))
cProfile.run("forward_rotation (l, num_rot)")
| false |
463fa32db7284ea1088d0193b26aa64f220da509 | prasant73/python | /programs/shapes/higher_order_functions.py | 2,063 | 4.4375 | 4 | '''4. Map, Filter and Reduce
These are three functions which facilitate a functional approach to programming. We will discuss them one by one and understand their use cases.
4.1. Map
Map applies a function to all the items in an input_list. Here is the blueprint:
Blueprint
map(function_to_apply, list_of_inputs)
Most of the times we want to pass all the list elements to a function one-by-one and then collect the output. For instance:
items = [1, 2, 3, 4, 5]
squared = []
for i in items:
squared.append(i**2)
Map allows us to implement this in a much simpler and nicer way. Here you go:
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
Most of the times we use lambdas with map so I did the same. Instead of a list of inputs we can even have a list of functions!
def multiply(x):
return (x*x)
def add(x):
return (x+x)
funcs = [multiply, add]
for i in range(5):
value = list(map(lambda x: x(i), funcs))
print(value)
# Output:
# [0, 0]
# [1, 2]
# [4, 4]
# [9, 6]
# [16, 8]
4.2. Filter
As the name suggests, filter creates a list of elements for which a function returns true. Here is a short and concise example:
number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)
# Output: [-5, -4, -3, -2, -1]
The filter resembles a for loop but it is a builtin function and faster.
Note: If map & filter do not appear beautiful to you then you can read about list/dict/tuple comprehensions.
4.3. Reduce
Reduce is a really useful function for performing some computation on a list and returning the result. It applies a rolling computation to sequential pairs of values in a list. For example, if you wanted to compute the product of a list of integers.
So the normal way you might go about doing this task in python is using a basic for loop:
product = 1
list = [1, 2, 3, 4]
for num in list:
product = product * num
# product = 24
Now let’s try it with reduce:
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
# Output: 24''' | true |
c1cd86da9cab336059a84e6401ac97232302036c | TurbidRobin/Python | /30Days/Day 10/open_file.py | 323 | 4.15625 | 4 | #fname = "hello-world.txt"
#file_object = open(fname, "w")
#file_object.write("Hello World")
#file_object.close()
# creates a .txt file that has hello world in it
#with open(fname, "w") as file_object:
# file_object.write("Hello World Again")
fname = 'hello-world.txt'
with open (fname, 'r') as f:
print(f.read()) | true |
bc00404073a57bad907452662f8df11bbfed47a9 | makkksimka/Holidaywork | /Домашнее задание2.py | 703 | 4.15625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from math import sqrt
if __name__ == "__main__":
a = float(input("a: "))
if a != 0:
b = float(input("b: "))
c = float(input("c: "))
D = b * b - 4 * a * c
if D > 0:
t1 = (-b - sqrt(D)) / (2 * a)
t2 = (-b + sqrt(D)) / (2 * a)
if t1 != t2:
print(-sqrt(t1), sqrt(t1), -sqrt(t2), sqrt(t2))
else:
print("Roots are equal and their value is ", -sqrt(t1), sqrt(t1))
elif D == 0:
t = -b / (2 * a)
print(-sqrt(t), sqrt(t))
else:
print("No roots.")
else:
print("a can't be zero.")
| false |
32851ca38461cdc284e106dc600c104ac3b025d7 | bioright/Digital-Coin-Flip | /coin_flip.py | 1,231 | 4.25 | 4 | # This is a digital coin flip of Heads or Tails
import random, sys #Importing the random and sys modules that we will use
random_number = random.randint(1, 2)
choice = "" # stores user's input
result = "" # stores random output
def play_game(): # the main function that calls other function
instructions()
decision()
flip_result()
quit()
def decision(): # getting player input
global choice # calling a global variable in a local scope
choice = input(" Heads or Tails? ")
if choice == "1":
choice = "Heads"
else:
choice = "Tails"
def flip_result(): # getting random output
global result
if random_number == 1:
result = "Heads"
else:
result = "Tails"
if result == choice: # comparing random output and player input
print(result, ", You win!")
else:
print(result, ", You lose!")
def instructions():
print("The system will generate a random number, either '1- for Heads' or '2- for Tails'.\n Choose '1' or '2' for this digital coin flip")
def quit():
sys.exit("The game has ended! Restart to flip the coin again")
play_game()
| true |
94d3b518f7ff885e83e92f4ca5310cfcbcf1341e | aes6218/hw2-python | /main.py | 1,047 | 4.3125 | 4 | # Author: August Sanderson aes6218@psu.edu
def getGradePoint(grade):
if grade=="A" or grade=="A+":
p = 4.0
elif grade=="A-":
p = 3.67
elif grade=="B+":
p = 3.33
elif grade=="B":
p = 3.0
elif grade=="B-":
p = 2.67
elif grade=="C+":
p = 2.33
elif grade=="C":
p = 2.0
elif grade=="D":
p = 1.0
else:
p = 0.0
return p
def run():
grade = input("Enter your course 1 letter grade: ")
g1 = getGradePoint(grade)
credit1 = float(input("Enter your course 1 credit: "))
print(f"Grade point for course 1 is: {g1}")
grade = input("Enter your course 2 letter grade: ")
g2 = getGradePoint(grade)
credit2 = float(input("Enter your course 2 credit: "))
print(f"Grade point for course 2 is: {g2}")
grade = input("Enter your course 3 letter grade: ")
g3 = getGradePoint(grade)
credit3 = float(input("Enter your course 3 credit: "))
print(f"Grade point for course 3 is: {g3}")
print(f"Your GPA is: {(g1*credit1 + g2*credit2 + g3*credit3)/(credit1+credit2+credit3)}")
if __name__ == "__main__":
run() | false |
83aeea4934c224bb313c05e567c398a5e00da6d6 | monicaihli/python_course | /misc/booleans_numbers_fractions.py | 1,091 | 4.21875 | 4 | # **********************************************************************************************************************
#
# File: booleans_numbers_fractions.py
#
# Author: Monica Ihli
#
# Date: Feb 03, 2020
#
# Description: Numbers and fractions in Python. Best results: use debugging to go through each line
# **********************************************************************************************************************
# Combine comparison operations that return boolean objects with boolean logic: and or
print("Boolean Logic: OR") # Either value has to pass the test to return True
print(True or True) # Returns True
print(True or False) # Returns True
print(False or True) # Returns True
print(False or False) # Returns False
print("Boolean Logic: AND") # Both values must pass the test to return True
print(True and True) # Returns True
print(True and False) # Returns False
print(False and True) # Returns False
print(False and False) # Returns False
print('/n/n')
print('Fractions')
from fractions import Fraction
print(Fraction(1/2)) | true |
7dda75c52ab735158c9daa38fb3661284c19c98c | dillon-DL/PolynomialReggression | /PolynomialRegression/poly.py | 1,592 | 4.1875 | 4 | # Firstly the program will be using polynomial regression to pefrom prediction based on the inputs
# The inputs or variables we will be anlysing to study is the relation between the price and the size of the pizza
# Lastly the data will displayed via a graph which indicates the "non-linear" relationship between the 2 features; in a user friednly manner
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
x_train = [[8], [18], [13], [17], [30]]
y_train = [[13], [22], [28], [30], [40]]
x_test = [[8], [18], [11], [16]]
y_test = [[13], [22], [15], [18]]
regresor = LinearRegression()
regresor.fit(x_train, y_train)
xx = np.linspace(0, 26, 100)
yy = regresor.predict(xx.reshape(xx.shape[0], 1))
plt.plot(xx, yy)
quadratic_featurizer = PolynomialFeatures(degree=2)
x_train_quadratic = quadratic_featurizer.fit_transform(x_train)
x_test_quadratic = quadratic_featurizer.transform(x_test)
regressor_quadratic = LinearRegression()
regressor_quadratic.fit(x_train_quadratic, y_train)
xx_quadratic = quadratic_featurizer.transform(xx.reshape(xx.shape[0], 1))
plt.plot(xx, regressor_quadratic.predict(xx_quadratic), c='y', linestyle='--')
plt.title('Pizza price regressed on the diameter')
plt.xlabel('Diameter in Cm')
plt.ylabel('Price in Rands')
plt.axis([0, 30, 0, 30])
plt.grid(True)
plt.scatter(x_train, y_train)
plt.show()
print (x_train)
print ()
print (x_train_quadratic)
print ()
print (x_test)
print ()
print (x_test_quadratic)
| true |
a63943db5fcb51f37ad30040070142285cd020da | Kuznetsova-28/101programmingtasks | /28.py | 481 | 4.15625 | 4 | Составить алгоритм и программу для реализации логических операций «И» и «ИЛИ» для двух переменных.
>>> x = input("значение x")
значение x
>>> a = input("значение a")
значение a
>>> c = input("значение c")
значение c
>>> if a > x and c < a or c > x :
print("получится четное значение")
else :
print("решения нет")
| false |
0e55757b1762833ff73673bc95f4bcbd12ba6177 | manojakondi/geeks4geeksPractice | /diffBetweenDates.py | 663 | 4.1875 | 4 | """
Given two dates (can be of different years), calculate the number of days between them (taking care of leap years).
"""
dt1 = [1,2,2000]
dt2 = [1,2,2004]
daysOfMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def countLeapYearsFromDate(dt):
d = dt[0]
m = dt[1]
y = dt[2]
if (m>2):
return (int(y/4) - int(y/100) + int(y/400))
else:
return (int((y-1)/4) - int((y-1)/100) + int((y-1)/400))
def countDays(dt):
d = dt[0]
m = dt[1]
y = dt[2]
n = y*365 + d
for i in range(0, m):
n += daysOfMonth[i]
n += countLeapYearsFromDate(dt)
return n
print(countDays(dt2)-countDays(dt1))
| false |
effe94d1b6bf723139b3afc02231b822d54f9d8c | Souro7/python_fundamentals | /conditionals.py | 450 | 4.28125 | 4 | x = 6
y = 5
# if x == y:
# print(f'{x} is equal to {y}')
if x > y:
print(f'{x} is greater than {y}')
elif x == y:
print(f'{x} is equal to {y}')
else:
print(f'{x} is less than {y}')
# membership operators - in, not in
numbers = [1, 2, 3, 4, 5]
if x in numbers:
print(x in numbers)
if x not in numbers:
print(x in numbers)
# identity operators - is, is not
if x is y:
print(x is y)
if x is not y:
print(x is y) | false |
0ea6d57a6bb60ffb37d296b30198750e2f837bf3 | rsg17/Python | /list_tuple.py | 425 | 4.125 | 4 | import sys
def merge_pair_list(list1,list2):
l1 = len(list1)
l2 = len(list2)
op = []
if l1 != l2:
print "Lists not of equal length"
sys.exit(1)
for i in range(0,l1):
y = (list1[i],list2[i])
op.append(y)
return op
if __name__ == "__main__":
input1 = ["apple", "banana", ""]
input2 = ["red", "yellow"]
# print merge_pair_list(input1,input2)
for x,y in zip(input2, input1):
print "%s : %s" % (x, y) | false |
dc44658426c6cd5f2a53e75811e2db59f15d2c88 | yama1102/python520 | /Aula2/condicionais.py | 1,607 | 4.21875 | 4 | #!/usr/bin/python3
#input('Digite qual o caminho a ser seguido: ')
#a = 'engarrafado'
#b = 'livre'
#if a == 'engarrafado':
# print('Melhor ir pela b')
#else:
# print('Indo pelo Caminho a')
#########
### Estrutura de condicional
#########
# nome = input('Digite seu nome: ').strip().title()
# sobrenome = input ('Digite seu sobrenome; ').strip().title()
# if nome == 'Daniel':
# print('Olá professor')
# print('Seja bem vindo')
#########
### Estrutura condicional composta
#########
# if nome == 'Daniel':
# print(f'Bem vindo Professor {nome}')
# else:
# print(f'Bem vindo Aluno {nome}')
# print('Você pode utilizar a plataforma')
#########
### Comparando duas condições
#########
# if nome == 'Daniel' and sobrenome == 'Silva': # pode-se utilizar o 'or'
# print(f'Bem vindo Professor {nome}')
# else:
# print(f'Bem vindo Aluno {nome}')
# print('Você pode utilizar a plataforma')
##########
## Condicionais Encadeadas
##########
# if nome == 'Daniel':
# if sobrenome == 'Silva':
# print('Olá professor')
# else:
# print('Você é Daniel, Mas não é professor')
# else:
# print(f'Olá Aluno {nome}')
###########
## Condicionais Aninhadadas
##########
nome = input('Digite seu nome: ').strip().title()
# Consegue fazer validação em mais de um fator
# com comportamento diferente
if nome == 'Daniel':
print(f'Seu nome é muito bonito, {nome}')
elif nome == 'Juliana':
print(f'Seu nome é bem legal, {nome}')
elif nome == 'Jorge':
print(f'Seu nome é muito feio, {nome}')
else:
print(f'Seu nome é bem normal, {nome}')
| false |
a28381495e08d45a75e21c512d06f688b9ab5dff | iwantroca/PythonNotes | /zeta.py | 2,427 | 4.46875 | 4 | ########LISTS########
# assigning the list
courses = ['History', 'Math', 'Physics', 'CompSci']
# finding length of list
print(len(courses))
# using index in list
print(courses[0])
# adding item to list
courses.append('Art')
print(courses)
# using insert to add in specific location
courses.insert(2, 'Art')
print(courses)
# using extend method to add lists
courses_2 = ['Humanities', 'Education']
courses.extend(courses_2)
print(courses)
# removing items from the list
courses.remove('Art')
print(courses)
# using pop to remove item from the list
popped = courses.pop()
print(popped)
print(courses)
# to find the index in the list
print(courses.index('Physics'))
# using del to remove specified item
del courses[2] # should delete physics
print(courses)
# to check if item is in list
print('Physics' in courses)
# to reverse the list
courses.reverse()
print(courses)
# to sort the list
sorted_courses = sorted(courses)
print(sorted_courses)
# list operations on the number
nums = [1, 5, 2, 4, 3]
sorted_nums = sorted(nums)
print(sorted_nums)
print(sum(nums))
print(min(nums))
print("")
# using loop in list
for index,item in enumerate(courses, start=1):
print(index, item)
# joining the courses with symbol
courses_str = ' - '.join(courses)
print(courses_str)
# spliting the list
courses_split = courses_str.split(' - ')
print(courses_split)
# tuples are immutable; can't be modified
tuple_1 = ('Art', 'Math', 'Physics')
print(tuple_1[2])
# tuple don't support list assignment
# tuple_1[0] = 'Chemistry'
####
######SETS######
####
# to make a empty set
# empty_set = set()
# in sets, order of the items do not matter
cs_courses = {'History', 'Math', 'Physics', 'CompSci', 'Math'}
art_courses = {'History', 'Math', 'Art', 'Design', 'Math'}
print('Math' in cs_courses)
print(cs_courses.intersection(art_courses))
#####
######Dictionaries######
#####
student = {1: 'John', 'age': 25, 'courses': ['Math', 'CompSci']}
print(student[1])
# adding new key to the dictionary
student['phone'] = '555-5555'
# using get helps us to change the error for defualt
print(student.get('phone', 'Not exist'))
print(student)
# updating student dict
student.update({1: 'Jane', 'age': 26})
print(student)
print(student.items())
# deleting key in dictionaries
# del student[1]
student.pop(1)
print(student)
# looping through dictionaries
for key, value in student.items():
print(key, value) | true |
f461e4886e514f6497cbe1f87d648efe3a7cf1cf | RaimbekNusi/Prime-number | /Project_prime.py | 1,146 | 4.25 | 4 | def is_prime(N):
"""
Determines whether a given positive integer is prime or not
input: N, any positive integer.
returns: True if N is prime, False otherwise.
"""
# special cases:
if N == 1:
return False
# the biggest divisor we're going to try
divisor = N // 2
while divisor > 1:
if N % divisor == 0:
# we found a number that is a factor of N
return False
divisor = divisor - 1
return True
out = {}
def numbers(x):
"""
Opens a numbers.txt file, reads all the numbers in the file,
calls a is_prime function, caches the numbers (keys) and values True or False to dictionary "out"
:param x: is a txt file, in this case numbers.txt
returns: The dictionary "out" containing numbers from the file and values True or False,
depending if the number is prime or non-prime respectively
"""
f = open(x,"r")
for line in f:
out[int(line)] = is_prime(int(line))
f.close()
return out
x = input("Write the name of the .txt file")
print(numbers(x))
| true |
0188c28e0485e2a0ff7efe15b89e7c5286723de9 | rajesh95cs/wordgame | /wordgameplayer.py | 2,158 | 4.15625 | 4 | class Player(object):
"""
General class describing a player.
Stores the player's ID number, hand, and score.
"""
def __init__(self, idNum, hand):
"""
Initialize a player instance.
idNum: integer: 1 for player 1, 2 for player 2. Used in informational
displays in the GUI.
hand: An object of type Hand.
postcondition: This player object is initialized
"""
self.points = 0.
self.idNum = idNum
self.hand = hand
def getHand(self):
"""
Return this player's hand.
returns: the Hand object associated with this player.
"""
return self.hand
# TODO
def addPoints(self, points):
"""
Add points to this player's total score.
points: the number of points to add to this player's score
postcondition: this player's total score is increased by points
"""
self.points += points
# TODO
def getPoints(self):
"""
Return this player's total score.
returns: A float specifying this player's score
"""
return self.points
# TODO
def getIdNum(self):
"""
Return this player's ID number (either 1 for player 1 or
2 for player 2).
returns: An integer specifying this player's ID number.
"""
return self.idNum
# TODO
def __cmp__(self, other):
"""
Compare players by their scores.
returns: 1 if this player's score is greater than other player's score,
-1 if this player's score is less than other player's score, and 0 if
they're equal.
"""
if self.points > other.getPoints() :
return 1
if self.points = other.getpoints() :
return 0
if self.points < other.getpoints() :
return -1
# TODO
def __str__(self):
"""
Represent this player as a string
returns: a string representation of this player
"""
return 'Player %d\n\nScore: %.2f\n' % \
(self.getIdNum(), self.getPoints())
| true |
1d76bf2cead6e296b7e7c37893a59a66cede9957 | Samk208/Udacity-Data-Analyst-Python | /Lesson_4_files_modules/flying_circus.py | 1,209 | 4.21875 | 4 | # You're going to create a list of the actors who appeared in the television programme Monty Python's Flying Circus.
# Write a function called create_cast_list that takes a filename as input and returns a list of actors' names. It
# will be run on the file flying_circus_cast.txt (this information was collected from imdb.com). Each line of that
# file consists of an actor's name, a comma, and then some (messy) information about roles they played in the
# programme. You'll need to extract only the name and add it to a list. You might use the .split() method to process
# each line.
import re
def create_cast_list(filename):
cast_list = []
# use with to open the file filename
# use the for loop syntax to process each line
# and add the actor name to cast_list
with open(filename) as f:
# p = re.compile('^[a-z ]+', re.IGNORECASE) tried regex for fun, but line split is much easier
for line in f:
# matched = p.match(line)
# if matched:
line_data = line.split(',')
cast_list.append(line_data[0])
# cast_list.append(matched.group())
return cast_list
print(create_cast_list('flying_circus_cast.txt'))
| true |
87a54bf9f8875f2f578c0ed361b8adb924ff866c | Samk208/Udacity-Data-Analyst-Python | /Lesson_3_data_structures_loops/flying_circus_records.py | 1,018 | 4.1875 | 4 | # A regular flying circus happens twice or three times a month. For each month, information about the amount of money
# taken at each event is saved in a list, so that the amounts appear in the order in which they happened. The
# months' data is all collected in a dictionary called monthly_takings.
# For this quiz, write a function total_takings that calculates the sum of takings from every circus in the year.
# Here's a sample input for this function:
monthly_takings = {'January': [54, 63], 'February': [64, 60], 'March': [63, 49],
'April': [57, 42], 'May': [55, 37], 'June': [34, 32],
'July': [69, 41, 32], 'August': [40, 61, 40], 'September': [51, 62],
'October': [34, 58, 45], 'November': [67, 44], 'December': [41, 58]}
def total_takings(monthly_takings):
pass # TODO: Implement this function
total = []
for i in monthly_takings:
total.append(sum(monthly_takings[i]))
return sum(total)
print(total_takings(monthly_takings)) | true |
319558317c1ad4f6667ebfc7b0b315e006abf084 | UstehKenny/Python | /Clases/clase2Cadenas.py | 1,339 | 4.375 | 4 | #Cadena:
#Arreglo de caracteres
cadena = "Este es el Curso de Python"
print(len(cadena))
print(cadena[11:16])
print(cadena[:20]) #Hasta el 20
print(cadena[20:]) #20 en adelante
print(cadena[::]) #Todo
#Formato de cadena
print(cadena.upper()) #Cambia a mayúsculas
print(cadena.lower()) #Cambia a minúsculas
print(cadena.swapcase()) #Invierte mayúsculas con minúsculas y viceversa
print(cadena.title()) #Formato de título
print(cadena.capitalize())
print(cadena.center(35, "-"))
print(cadena.count("Curso"))
cadena2 = "Python es un lenguaje interpretado"
arregloCadena = cadena2.split() #Separa nuestra cadena
print(arregloCadena)
cadena3 = "Python-es-un-lenguaje-interpretado"
arregloCadena2 = cadena3.split("-") #Separa nuestra cadena
print(arregloCadena2)
arregloPalabras = ["Python","es","lenguaje","de","tipado","dinamico"]
cadenaFinal = ""
for x in arregloPalabras:
cadenaFinal = cadenaFinal + " " + x
print(cadenaFinal)
cadenaFinalMetodo = "".join(arregloPalabras)
#Ciclos
#FOR
listaUsuarios = ["Kenny","Damian","Ricardo","Alberto","Gerardo"]
#Leer de teclado
#usuario = input("Ingresa el usuario\n")
#listaUsuarios.append(usuario)
#for usuario in listaUsuarios: print(usuario)
#Ciclo while
#contador = 0
#while contador < 10:
# print("El contador tiene valor de: ", contador)
# contador+=1 #contador = contador + 1
| false |
ae66153b1a667b2fdca4e9699aba6cbffc979fef | YuriYuriHentai/Yuri | /test.py | 376 | 4.15625 | 4 | #я долбаеб
x=float (input("Введите первое число:"))
z=input ("Введите действие (+, -, /, *, //)")
y=float (input("Введите второе число:"))
if z=="+":
res=x+y
elif z=="-":
res=x-y
elif z=="*":
res=x*y
if z=="/":
res=x/y
elif z=="//":
res=x//y
print ("Результат =", res)
| false |
cb2a90a4869b762145f3e48160d7448ad0fda3a4 | CODE-Lab-IASTATE/MDO_course | /03_programming_with_numpy/arrays.py | 889 | 4.40625 | 4 | #Numpy tutorials
#Arrays
#Import the numpy library
import numpy as np
a = np.array([1, 2, 3])
#print the values of 'a'
print(a)
#returns the type of 'a'
print(type(a))
#returns the shape of 'a'
print(a.shape)
#prints the value of 'a'
print(a[0], a[1], a[2])
# Change an element of the array
a[0] = 5
#print the values of 'a'
print(a)
#reshape a
a = a.reshape(-1,1)
#returns the shape of 'a'
print(a.shape)
#Note (3,) means it is a 1d matrix
#(3,1) means it is a 2d matrix
#In python this matters
a = a.reshape(1,-1)
#returns the shape of 'a'
print(a.shape)
#.reshape(1,-1) refers to the following
#the first index refers to number of columns, in this case 1
#second index is number of rows, -1 tells numpy to fiugre the length out
#Array of zeros
b = np.zeros(3)
print(b)
#Array of ones
c = np.ones(3)
print(c) | true |
cb3c16cae8164f495dd73644ec16ea267f8c0814 | NickosLeondaridisMena/nleondar | /shortest.py | 1,560 | 4.375 | 4 |
# Create a program, shortest.py, that has a function
# that takes in a string argument and prints a sentence
# indicating the shortest word in that string.
# If there is more than one word print only the first.
# Your print statement should read:
# “The shortest word is x”
# Where x = the shortest word.
# The word should be all uppercase.
def print_shortest_word(input_sentence):
# we need to split the sentence into separate words
temp = input_sentence.split()
# I'm going to initialize a very, very large number
initial_counter = 10000000000000000000000000000000
# returned word is just a placeholder. our answer will end up here
returned_word = ""
# for every word we come across in this sentence
for word in temp:
# if the length of the word is less than our current huge number
# note by making it strictly LESS, it will return the first occuring shortest
# letter. If I made it less than or equal to, then it wouldn't work as asked
if len(word) < initial_counter:
# you need to replace that large number with the shortest word
# length so far
initial_counter = len(word)
# and update our placeholder variable with our new shortest word
returned_word = word
# they asked to return this sentece with it capitalized
return print("The shortest word is " + returned_word.upper())
# see how I added another 1 letter word afterwards and our output still works?
print_shortest_word("The shortest word is x P")
| true |
7e13a6736cdae035792dec2400a1ec76e63289ce | SebasJ4679/CTI-110 | /P5T1_KilometerConverter_SebastianJohnson.py | 670 | 4.625 | 5 | # Todday i will create a program that converts kilometers to miles
# 10/27/19
# CTI-110 P5T1_KilometerConverter
# Sebastian Johnson
#
#Pseudocode
#1. Prompt the user to enter a distance in kilometers
#2. display the formula so the user knows what calculation is about to occur
#3 write a function that carries out the formula
#4. display the end result to the user
def main():
kilometers= float(input('Enter the kilometers you would like converted to miles: '))
print('The formula being used is miles = kilometers * 0.6214.')
miles = (kilometers) * 0.6214
print('The conversion of', kilometers,'kilometers','to miles is', miles)
main()
| true |
d0de9f4a94d395499f87c7c304a70cc4e6055de2 | AkshatTodi/Machine-Learning-Algorithms | /Supervised Learning/Regression/Simple Linear Regression/simple_linear_regression.py | 1,693 | 4.46875 | 4 | # Simple Linear Regression
# Formula
# y = b0 + b1*X1
# y -> dependent variable
# X1 -> independent variable
# b0 -> Constent
# b1 -> Coefficient
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Salary_Data.csv')
# When we build a machine learning model and specially regression model thgen we have to make our matix of feature to be considered all the
# time as a matrix means X should be in the form of (i,j) not as a vector (i,).
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
# Training the Simple Linear Regression model on the Training set
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
slr = regressor.fit(X_train, y_train) # fit(Training data, Target data)
# Predicting the Test set results
y_pred = regressor.predict(X_test)
# model accuracy
accuracy = slr.score(X_test, y_test)
print(accuracy)
print("\n\n")
# Visualising the Training set results
plt.scatter(X_train, y_train, color = 'red')
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.title('Salary vs Experience (Training set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show()
# Visualising the Test set results
plt.scatter(X_test, y_test, color = 'red')
plt.plot(X_train, regressor.predict(X_train), color = 'blue')
plt.title('Salary vs Experience (Test set)')
plt.xlabel('Years of Experience')
plt.ylabel('Salary')
plt.show() | true |
81d28f7e974c142d2792a4983342723fb8e7a712 | SarahMcQ/CodeWarsChallenges | /sortedDivisorsList.py | 618 | 4.1875 | 4 | def divisors(integer):
'''inputs an integer greater than 1
returns a list of all of the integer's divisor's from smallest to largest
if integer is a prime number returns '()is prime' '''
divs = []
if integer == 2:
print(integer,'is prime')
else:
for num in range(2,integer):
if integer%num == 0:
divs.append(num)
# print(sorted(divs))
if len(divs) == 0:
print(integer, 'is prime')
else:
return sorted(divs)
| true |
ef7cb3ec31fe915692c68d0d61da36bdb8004576 | jfonseca4/FonsecaCSC201-program03 | /program03-Part1.py | 1,129 | 4.375 | 4 | #Jordan Fonseca
#2.1
DNA = input(str("Enter the DNA sequence")) #asks user to input a string
DNA2 = []
for i in DNA:
if i == "A": #if DNA is A, replaces it with a T
DNA2.append("T")
if i == 'G': #if DNA is G, replaces it with a C
DNA2.append("C")
if i == "C": #if DNA is C, replaces it with a G
DNA2.append("G")
if i == "T": #if DNA is T, replaces it with a A
DNA2.append("A")
MirrorDNA = "".join(DNA2) #brings string together
print(MirrorDNA) #prints list mirrored DNA sequence
#2.2
DNA = input(str("Enter the DNA sequence")) #Asks user to enter DNA string
ReverseDNA = DNA[::-1] #reverses the entered DNA string
print(ReverseDNA) #prints reverse DNA string
#2.3
validDNA = "TGCA" #set valid DNA
DNA = input(str("Enter DNA sequence"))
if all(i in validDNA for i in DNA) == True : #If what the user enters for DNA is true
print("valid") #prints valid
else:
print("invalid") #If not true, prints invalid
#2.4
#I was not able to figure out how to put it all together, it would not work.
| true |
4585efdae5dffff316e6f37ff8ca74c176dadc0f | Nazzekas/python | /эния.py | 455 | 4.125 | 4 | #195
n = int(input("Введите количество панелей необходимых обработать: "))
a = int(input("Введите длину панели: "))
b = int(input("Введите ширину панели: "))
S = 2*a*b*n #общая площадь всех панелей, учитывая обработку с обеих сторон
print("На обработку необходимо " + str(S) + " сульфида!")
| false |
440bd8ba94e1320d5d44451e1abe2dca051cb25d | rjmarzec/Google-CSSI---Coursera | /Algorithmic Toolbox/week2_algorithmic_warmup/4_least_common_multiple/lcm.py | 523 | 4.125 | 4 | # Uses python3
def lcm(a, b):
current_a_mult = a
current_b_mult = b
a_times_b = a*b
while a_times_b > current_a_mult and a_times_b > current_b_mult:
if current_a_mult == current_b_mult:
return current_a_mult
elif current_a_mult < current_b_mult:
current_a_mult += a
elif current_b_mult < current_a_mult:
current_b_mult += b
return a*b
if __name__ == '__main__':
input = input()
a, b = map(int, input.split())
print(lcm(a, b))
| false |
23625cceeacc7e9b9d1287a87f95eb6a24ff0a4a | mlm-distrib/py-practice-app | /00 - basics/05-operators.py | 2,466 | 4.46875 | 4 | # Operators
# Arithmetic operators
x = 10
y = 5
print('#### Arithmetic ####')
print('addition :', x+y)
print('subtraction:', x-y)
print('multiply :', x*y)
print('division :', x/y)
print('modulus :', x % y)
print('exponential:', x**y)
print('floor division:', x//y)
print('')
# Assignment operators
x = 15
print('### Assignment operators')
x += 3
print('+= operator:', x)
x -= 3
print('-= operator:', x)
x *= 3
print('*= operator:', x)
x /= 3
print('/= operator:', x)
x %= 3
print('%= operator:', x)
x //= 3
print('//= operator:', x)
x **= 3
print('**= operator:', x)
x = 5
x &= 3
print('&= operator:', x)
x = 5
x |= 3
print('|= operator:', x)
x = 5
x ^= 3
print('^= operator:', x)
print('')
# Comparison operators
print('### Comparison operators')
x = 4
y = 4
if x == y:
print(x, y, '== operator: are equal')
y = 5
if x != y:
print(x, y, '!= operator: are not equal')
if y > x:
print(x, y, '> operator: y greater than x')
if x < y:
print(x, y, '< operator: x lesser than y')
y = 4
if x >= y:
print(x, y, '>= operator: x greater than or equal to y')
if x <= y:
print(x, y, '<= operator: x lesser than or equal to y')
print('')
# Logical operators
print('### Logical operators')
y = 5
if x < y and y > 4:
print(x, y, 'and operator: x less than y and y greater than 4')
if x == y or y > 4:
print(x, y, 'or operator: x equals y or y greater than 4')
if not(x >= y and y > 5):
print(x, y, 'not operator: x greater than y and y greater than 5')
print('')
# Identity operators
print('### Identity operators')
y = 4
if x is y:
print(x, y, 'is operator: return true when x, y variables are same ')
y = 5
if x is not y:
print(x, y, 'is not operator: return true when x, y variables are not same ')
print('')
# Membership operators
print('### Membership operators')
a = ['apple', 'banana', 'mango', 'grapes']
b = 'mango'
if b in a:
print('in operator : ', b, 'is available in the array', a)
b = 'orange'
if b not in a:
print('not in operator: ', b, 'is not available in the array', a)
print('')
# Bitwise operators
print('### Bitwise operators')
a = 60
b = 13
c = 0
c = a & b
print(a, b, '& operator: Value of c is: ', c)
c = a | b
print(a, b, '| operator: Value of c is: ', c)
c = a ^ b
print(a, b, '^ operator: Value of c is: ', c)
c = ~ a
print(a, b, '~ operator: Value of c is: ', c)
c = a << 2
print(a, b, '<< operator: Value of c is: ', c)
c = a >> 2
print(a, b, '>> operator: Value of c is: ', c)
| false |
b5eb87686608cd0fc8e4215db1479bfc2e9a379b | mlm-distrib/py-practice-app | /00 - basics/08-sets.py | 515 | 4.25 | 4 |
# Set is a collection which is unordered and unindexed. No duplicate members.
myset = {"apple", "banana", "mango"}
print(myset)
for x in myset:
print(x)
print('')
print('Is banana in myset?', "banana" in myset)
myset.add('orange')
print(myset)
myset.update(["pineapple", "orange", "grapes"])
print(myset)
print('length is', len(myset))
myset.remove("orange")
print(myset)
myset.discard("mango")
print(myset)
myset.pop()
print(myset)
myset.clear()
print(myset)
myset = set(("AAA", "BBB", "CCC"))
print(myset)
| true |
4cc99b2d1de0595bc2d0b6f335e7f8d1b80b906d | kannanmavila/coding-interview-questions | /quick_sort.py | 714 | 4.28125 | 4 | def r_quick_sort(array, start, end):
# Utility for swapping two elements of the array
def swap(pos1, pos2):
array[pos1], array[pos2] = array[pos2], array[pos1]
if start >= end:
return
pivot = array[start]
left = start+1
right = end
# Divide
while left - right < 1:
if array[left] > pivot:
swap(left, right)
right -= 1
if array[left] <= pivot:
left += 1
# Insert pivot in its position
swap(start, right)
# Recurse
r_quick_sort(array, start, right-1)
r_quick_sort(array, left, end)
def quick_sort(array):
r_quick_sort(array, 0, len(array)-1)
#################### DRIVERS ####################
l = [10, 1, 7, 3, 8, 9, 2, 6]
quick_sort(l)
print l
| true |
e177b1f2ba2fb3baaef810214a9325e1e9207342 | kannanmavila/coding-interview-questions | /reverse_string.py | 235 | 4.21875 | 4 | def reverse(string):
string = list(string)
length = len(string)
for i in xrange((length - 1) / 2 + 1):
string[i], string[length-i-1] = string[length-i-1],string[i]
return "".join(string)
print reverse("Madam, I'm Adam")
| true |
070d388659df628d00116c127f2b212c0e6033cf | kannanmavila/coding-interview-questions | /tree_from_inorder_postorder.py | 1,470 | 4.125 | 4 | class Node(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def binary_tree(inorder, postorder):
"""Return the root node to the BST represented by the
inorder and postorder traversals.
"""
# Utility for recursively creating BST for
# a subset of the traversals.
def _construct(left, right, head_pos):
if left > right:
return None
# Split the inorder array, using head
# as pivot. `head_pos` is the position
# of the head in `postorder`.
pivot = inorder.index(postorder[head_pos])
head = Node(inorder[pivot])
# Recursively create subtrees, and connect
# them to the head.
head.left = _construct(left, pivot-1,
head_pos - (right-pivot) - 1)
head.right = _construct(pivot+1, right,
head_pos-1)
return head
n = len(inorder)
return _construct(0, n-1, n-1)
def inorder(node):
if node is None:
return ""
return inorder(node.left) + " " + str(node.value) \
+ inorder(node.right)
def postorder(node):
if node is None:
return ""
return postorder(node.left) + postorder(node.right) \
+ " " + str(node.value)
if __name__ == "__main__":
ino = [4, 8, 2, 5, 1, 6, 3, 7]
post = [8, 4, 5, 2, 6, 7, 3, 1]
root = binary_tree(ino, post)
print inorder(root)
print postorder(root)
ino = [1, 2, 3]
post = [3, 2, 1]
root = binary_tree(ino, post)
print inorder(root)
print postorder(root)
| true |
668f846583dadfcd5270c9e674b3271ee7381235 | kannanmavila/coding-interview-questions | /interview_cake/16_cake_knapsack.py | 1,136 | 4.25 | 4 | def max_duffel_bag_value(cakes, capacity):
"""Return the maximum value of cakes that can be
fit into a bag. There are infinitely many number
of each type of cake.
Caveats:
1. Capacity can be zero (naturally handled)
2. Weights can be zero (checked at the start)
3. A zero-weight cake can give infinite value
iff its value is non-zero
Attributes:
cakes - list of cakes represented by a
(weight, value) tuple
capacity - the maximum weight the bag can carry
"""
# If there is a cake with zero weight and non-zero
# value, the result is infinity.
if [c for c in cakes if c[0] == 0 and c[1] > 0]:
return float('inf')
max_value = [0] * (capacity+1)
for i in xrange(1, capacity+1):
# For every cake that weighs not more
# than i, see if including it will
# give better results for capacity 'i'
choices = [max_value[i-cake[0]] + cake[1]
for cake in cakes
if cake[0] <= i] + [0]
max_value[i] = max(choices)
return max_value[capacity]
if __name__ == "__main__":
cakes = [(7, 160), (3, 90), (2, 15)]
print max_duffel_bag_value(cakes, 20) # 555 (6*90 + 1*15)
| true |
4a46b2a0a5c8455746758351e85cbf52eaee7e72 | engineeredcurlz/Sprint-Challenge--Intro-Python | /src/oop/oop2.py | 1,535 | 4.15625 | 4 | # To the GroundVehicle class, add method drive() that returns "vroooom".
#
# Also change it so the num_wheels defaults to 4 if not specified when the
# object is constructed.
class GroundVehicle():
def __init__(self, num_wheels = 4): # only works for immutable (cant change) variables otherwise use []
self.num_wheels = num_wheels
# TODO
def drive(self):
return "vroooom"
# Subclass Motorcycle from GroundVehicle. (motorcycle in groundvehicle)
#
# Make it so when you instantiate a Motorcycle, it automatically sets the number
# of wheels to 2 by passing that to the constructor of its superclass.
#
# Override the drive() method in Motorcycle so that it returns "BRAAAP!!"
class Motorcycle(GroundVehicle):
def __init__(self, num_wheels = 2): # set number, doesn't change for now (why do we need __ instead of _?)
self.num_wheels = num_wheels # because it is a special defined method in python. it is used when an object is created from a class
# TODO # and used to initialize the attributes of said class
def drive(self):
return "BRAAAP!!"
vehicles = [
GroundVehicle(),
GroundVehicle(),
Motorcycle(),
GroundVehicle(),
Motorcycle(),
]
# Go through the vehicles list and print the result of calling drive() on each.
# through the vehicles list = for loop
# vehicle = groundvehicle = car
# vehicles = list
# call drive on each , attach drive to vehicle on the end
# TODO
for vehicle in vehicles:
print (vehicle.drive())
| true |
f29173d2bf9875c2748b4cb686b2d63522dda286 | AdiKaran/Project-Euler | /Problem9.py | 720 | 4.15625 | 4 |
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a**2 + b**2 = c**2
# For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
sqr_roots = {}
ans = [] * 3
for x in range(500) :
sqr_roots[x**2] = x
a = 1
b =1
while a < 1000:
for b in range(1,a):
hypotenuse = a ** 2 + b **2
try:
c = sqr_roots[hypotenuse]
if a + b + c == 1000:
print('[a,b,c,hypotenuse,abc] =',a,b,c,hypotenuse,a*b*c)
except KeyError:
pass
a += 1
| false |
57170eafa6f1197f2032a809dbb0981f49b507ff | a100kpm/daily_training | /problem 0029.py | 983 | 4.1875 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Run-length encoding is a fast and simple method of encoding strings.
The basic idea is to represent repeated successive characters as a single count and character.
For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
Implement run-length encoding and decoding.
You can assume the string to be encoded have no digits and consists solely of
alphabetic characters. You can assume the string to be decoded is valid.
'''
string = "AAAABBBCCDAA"
def encodeur(string):
retour = []
lenn=len(string)
retour.append([string[0],1])
j=0
for i in range(1,lenn):
if string[i]==retour[j][0]:
retour[j][1]+=1
else:
j+=1
retour.append([string[i],1])
lenn2=len(retour)
encodage=''
for i in range(lenn2):
encodage=encodage+str(retour[i][1])+retour[i][0]
return encodage | true |
003bc82579dfd89b4d1d001ee16d40d6a726da67 | a100kpm/daily_training | /problem 0207.py | 1,301 | 4.15625 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Dropbox.
Given an undirected graph G, check whether it is bipartite.
Recall that a graph is bipartite if its vertices can be divided into two independent sets,
U and V, such that no edge connects vertices of the same set.
'''
import numpy as np
graph = np.array([[0,1,1,1,0,0,0],
[1,0,0,0,0,0,0],
[1,0,1,1,0,0,0],
[1,0,1,1,0,0,0],
[0,0,0,0,0,1,1],
[0,0,0,0,1,0,1],
[0,0,0,0,1,1,0]
])
def bipartite(graph):
lenn=np.shape(graph)[0]
list_=set()
compteur=0
while len(list_)<lenn:
compteur+=1
for i in range(lenn):
if i not in list_:
break
current_list=[i]
while len(current_list):
for j in range(lenn):
val = graph[current_list[0]][j]
if val==1 and j not in list_ and j not in current_list:
list_.add(j)
current_list.append(j)
current_list=current_list[1:]
if compteur==2:
return True
return False
| true |
0dc1cf2fcc01b34b4cf943a17ba24475df7e768a | a100kpm/daily_training | /problem 0034.py | 958 | 4.21875 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Quora.
Given a string, find the palindrome that can be made by inserting the fewest
number of characters as possible anywhere in the word. If there is more than
one palindrome of minimum length that can be made, return the lexicographically
earliest one (the first one alphabetically).
For example, given the string "race", you should return "ecarace",
since we can add three letters to it (which is the smallest amount to make a palindrome).
There are seven other palindromes that can be made from "race" by adding three letters,
but "ecarace" comes first alphabetically.
As another example, given the string "google", you should return "elgoogle".
'''
string1 = "race"
string2="google"
def palindr(string):
lenn=len(string)
bout=""
A=True
j=1
for i in range(1,lenn+1):
bout+=string[-i]
new_str=bout+string | true |
211d0303800ef36e5c658498aa5c8ed99b3a91e8 | a100kpm/daily_training | /problem 0202.py | 671 | 4.28125 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Palantir.
Write a program that checks whether an integer is a palindrome.
For example, 121 is a palindrome, as well as 888. 678 is not a palindrome.
Do not convert the integer into a string.
'''
nbr1=121
nbr2=123454321
nbr3=678
nbr4=1234
def nbr_palindrome(nbr):
if nbr<10:
return True
taille=0
while nbr//10**taille>0:
taille+=1
taille-=1
while nbr>9:
if nbr%10!=nbr//10**taille:
return False
nbr=int((nbr-(nbr//10**taille*10**taille)-nbr%10)/10)
taille-=2
return True
| true |
2d3369c67839346d1e81cc29eda6163e1bf27080 | a100kpm/daily_training | /problem 0063.py | 1,824 | 4.15625 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Microsoft.
Given a 2D matrix of characters and a target word, write a function that returns
whether the word can be found in the matrix by going left-to-right, or up-to-down.
For example, given the following matrix:
[['F', 'A', 'C', 'I'],
['O', 'B', 'Q', 'P'],
['A', 'N', 'O', 'B'],
['M', 'A', 'S', 'S']]
and the target word 'FOAM', you should return true, since it's the leftmost column.
Similarly, given the target word 'MASS', you should return true, since it's the last row.
'''
import numpy as np
word= 'FOAM'
word2= 'MASS'
word3 = 'AAAAA'
word4= 'MASSS'
matrix = np.array([['F', 'A', 'C', 'I'],
['O', 'B', 'Q', 'P'],
['A', 'N', 'O', 'B'],
['M', 'A', 'S', 'S']])
def word_finder(matrix,word):
first_letter = word[0]
size=len(word)
lenn=np.shape(matrix)[0]
lenn2=np.shape(matrix)[1]
for i in range(lenn):
for j in range(lenn2):
if matrix[j][i]==first_letter:
# print('i={} and j={}'.format(i,j))
horizontal=i
vertical=j
ok=True
n=1
while horizontal < lenn2-1 and ok ==True:
horizontal+=1
n+=1
if word[n-1]!=matrix[j][horizontal]:
ok=False
if n==size and ok==True:
return True
ok=True
n=1
while vertical < lenn-1 and ok ==True:
vertical+=1
n+=1
if word[n-1]!=matrix[vertical][i]:
ok=False
if n==size and ok==True:
return True
return False
| true |
f34bef76194d77d6a5e5f5891c334c33c8d7ca10 | a100kpm/daily_training | /problem 0065.py | 1,407 | 4.15625 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Amazon.
Given a N by M matrix of numbers, print out the matrix in a clockwise spiral.
For example, given the following matrix:
[[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]]
You should print out the following:
1
2
3
4
5
10
15
20
19
18
17
16
11
6
7
8
9
14
13
12
'''
import numpy as np
matrice = np.array([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]])
def asticot_printer(matrix):
base1=0
base2=1
coorX=0
coorY=0
base1_max=np.shape(matrix)[1]-1
base2_max=np.shape(matrix)[0]-1
taille_=np.shape(matrix)[0]*np.shape(matrix)[1]-1
direction=0
for _ in range(taille_):
print(matrix[coorY][coorX])
if direction==0:
coorX+=1
if coorX==base1_max:
direction=1
base1_max-=1
elif direction==1:
coorY+=1
if coorY==base2_max:
direction=2
base2_max-=1
elif direction==2:
coorX-=1
if coorX==base1:
direction=3
base1+=1
else:
coorY-=1
if coorY==base2:
direction=0
base2+=1
print(matrix[coorY][coorX])
| true |
4be59ab979de011b3761d0744013c0ff1ff5d9d2 | a100kpm/daily_training | /problem 0241.py | 949 | 4.3125 | 4 | '''
Good morning! Here's your coding interview problem for today.
This problem was asked by Palantir.
In academia, the h-index is a metric used to calculate the impact of a researcher's papers. It is calculated as follows:
A researcher has index h if at least h of her N papers have h citations each.
If there are multiple h satisfying this formula, the maximum is chosen.
For example, suppose N = 5, and the respective citations of each paper are
[4, 3, 0, 1, 5]. Then the h-index would be 3, since the researcher has 3 papers with at least 3 citations.
Given a list of paper citations of a researcher, calculate their h-index.
'''
citation= [4, 3, 0, 1, 5]
def h_value(citation):
lenn=len(citation)
for i in range(lenn,-1,-1):
compteur=0
for j in range(lenn):
if citation[j]>=i:
compteur+=1
if compteur==i:
return i
return 0 | true |
625c3d016087f104ed463b41872b3510d000a04c | Abhishek4uh/Hacktoberfest2021_beginner | /Python3-Learn/Decorators_dsrathore1.py | 1,775 | 4.625 | 5 | #AUTHOR: DS Rathore
#Python3 Concept: Decorators in Python
#GITHUB: https://github.com/dsrathore1
# Any callable python object that is used to modify a function or a class is known as Decorators
# There are two types of decorators
# 1.) Fuction Decorators
# 2.) Class Decorators
# 1.) Nested function
# 2.) Function return function
# 3.) reference
# 4.) Function as parameter
''' Note: Need to take a function as parameter
Add functionality to the function
Function need to return another function'''
def outer ():
a = 3
def inner ():
b = 4
result = a +b
return result
return inner # Refrences to the inner funtion
# retun inner() # Returning the value of the function
a = outer ()
print (a)
def function1():
print ("Hi, I am function 1")
def function2():
print ("Hi, I am function 2")
function1()
function2()
def function1():
print("Hi, I am function 1")
def function2(func):
print ("Hi, I am function 2, and now I am calling function 1")
func()
function2(function1)
def str_lower(func):
def inner():
str1 = func()
return str1.lower
return inner()
@str_lower
def print_str():
return ("GOOD MORNING")
print(print_str())
d = str_lower(print_str)
print(d())
def add(func):
def sum():
result = func() + 5
return result
return sum
@add
def function1():
x = 3
y = 5
return x + y
print(function1())
print (add(function1()))
# Parameteric Decorator
def d(func):
def inner(x, y):
result = f'Answer of divide and the value of the a : {x} b : {y} \nResult is {func(x, y)}'
return result
return inner
@d
def div(a, b):
divide = a // b
return divide
print (div(4, 2)) | true |
d29b902b56c3dcd3f132d6a3d699b061ccdb3bb6 | michaeldton/Fall20-Text-Based-Adventure-Game- | /main.py | 1,859 | 4.21875 | 4 | import sys
from Game.game import Game
# Main function calls the menu
def main():
menu()
# Quit function
def quit_game():
print("Are you sure you want to quit?")
choice = input("""
1: YES
2: NO
Please enter your choice: """)
if choice == "1":
sys.exit
elif choice == "2":
menu()
else:
print("You can only select 1 for yes or 2 for no")
quit_game()
# The playNewGame() initializes a new game from the beginning
def play_new_game():
print()
print("---- Starting New Game ----")
game = Game()
game.start_game()
# The loadCurrentGame() opens a file to the players current level
def load_current_game():
print()
print("---- Loading Save File ----")
game = Game()
game.load_game()
'''
The playGame() allows the user to play a new game, load an existing game,
or return to the main menu.
'''
def play_game():
choice = input("""
1: NEW GAME
2: LOAD GAME
3: GO BACK
Please enter your choice: """)
if choice == "1":
play_new_game()
elif choice == "2":
load_current_game()
elif choice == "3":
menu()
else:
print("Invalid choice, please select 1, 2, or 3.")
play_game()
# The main menu()
def menu():
print("************MAIN MENU**************")
print()
choice = input("""
1: PLAY GAME
2: QUIT
Please enter your choice: """)
if choice == "1":
play_game()
elif choice == "2":
quit_game()
else:
print("You must only select 1 to play or 2 to quit. Please try again.")
menu()
# Main function
if __name__ == '__main__':
main()
| true |
570fb365c121fcf6d5dbb573410de4b947539441 | zqh-hub/python_base | /列表/列表_01_通用操作.py | 758 | 4.3125 | 4 | # 序列:列表、元组、字符串
# 容器:序列、映射(如:字典)
# 通用序列操作:索引、切片、相加、相乘、成员资格
# 索引
print("hello"[0])
print("hello"[-1])
# res = input("year:")[3]
# print(res)
# 切片
tag = '<a href="http://www.python.org">Python web site</a>'
print(tag[9:30])
print(tag[9:-21])
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(nums[7: 10])
print(nums[-3:])
print(nums[:])
print(nums[::-1])
# 序列相加
print([1, 2] + [3, 4])
print("hello" + " world")
# 乘法
print("python " * 5)
print([None] * 4)
# 成员资格
print("h" in "hello")
ls = [
["coco", "1234"],
["jojo", "3456"]
]
print(["coco", "1234"] in ls)
print(len(ls))
print(max(nums))
print(max(2, 5, 8))
print(min(nums))
| false |
d770011ac09cf8880cf245995f150112d1d3b1fc | LopesAbigail/UFABC-BCC-2021 | /CSV/statistic-conditional-median.py | 651 | 4.1875 | 4 | # Ler a planilha
# Receber do usuario a turma
# Calcular a media e a mediana da turma recebida no passo anterior
# Se a media for maior ou igual a mediana, imprima a palavra Media
# Caso contrario, imprima a palavra Mediana
import pandas as pd
import numpy as np
df = pd.read_csv(
"https://www.dropbox.com/s/jqficiaig0a8aze/NotasTurmas.csv?dl=1")
turma = input()
turmas_validas = ["Turma 1", "Turma 2", "Turma 3", "Turma 4",
"Turma 5", "Turma 6", "Turma 7", "Turma 8", "Turma 9", "Turma 10"]
if turma in turmas_validas:
if df[turma].mean() >= df[turma].median():
print("Media")
else:
print("Mediana")
| false |
f6c5b9ae9be92219d025cf496286b9413eb8f434 | stoneskin/mlcccCoding | /2018-03-11/10-Inheritance/shape.py | 709 | 4.21875 | 4 | # https://www.programiz.com/python-programming/inheritance
class Shape:
def __init__(self, name: str=""):
self.name = name
def printInfo(self):
print("in shapes, Name=", self.name)
class Polygon(Shape):
def __init__(self, no_of_sides,name:str="Ploygon"):
self.name=name;
Shape.__init__(self, self.name)
def printInfo(self):
print("in Ploygon, Name=", self.name)
class Triangle(Polygon):
def __init__(self):
Polygon.__init__(self, 3,"Triangle")
class Rectangle(Polygon):
def __init__(self):
Polygon.__init__(self, 4,"Rectangle")
print("test")
shape1 = Triangle()
shape1.printInfo()
shape2 = Rectangle()
shape2.printInfo()
| false |
5ef61d947c51a4f5793a005629f22e6ca44e4cbf | iamdeepakram/CsRoadmap | /python/regularexpressions.py | 1,106 | 4.1875 | 4 | # find the patterns without RegEx
# some global variable holding function information
test = "362-789-7584"
# write isphonenumber function with arguments text
def isPhoneNumber(text):
global test
test = text
# check length of string
if len(text) != 12 :
return False
# check area code from index 0 to index 2
for i in range(0,3): # upto 3 but not including 3
if not text[i].isdecimal():
return False
# check hyphen in string
if text[3] != '-':
return False
# check area code from index 4 to index 6
for i in range(4, 7):
if not text[i].isdecimal():
return False
# check hyphen in string
if text[7] != '-':
return False
# check for phone number form index 8 to index 11
for i in range(8, 12):
if not text[i].isdecimal():
return False
#if return true print following
return True
print(test + ' is a phone number:' )
print(isPhoneNumber('362-789-7584'))
print('Is \"agents of shield\" is a phone number:')
print(isPhoneNumber('agents of shield'))
| true |
b91733a9e8050ec851b412a322c4ca86224f462e | better331132/hello | /review2.py | 548 | 4.125 | 4 | #변수 Variables (문자열)
'hello'"world"
print('hello'"world")
print('hello',"world") #문자열 변수 사이의 ,는 결과에서 공백으로 나타남
message = "hello world"
print(message)
print(message[0:5])
print(message[:6]) #공백 또한 하나의 문자로 취급
print(message[:-4])
print(len(message))
print(len(message[0:6]))
print(len(message[:-8]))
print(len(message[3:len(message)]))
print(message.split(' '))
first, second = message.split(' ')
print(first, second) | false |
b3a1e3ab177fac333bc9ee0a5a0b379751807f58 | aklgupta/pythonPractice | /Q4 - color maze/color_maze.py | 2,950 | 4.375 | 4 | """Team Python Practice Question 4.
Write a function that traverse a color maze by following a sequence of colors. For example this maze can be solved by the sequence 'orange -> green'. Then you would have something like this
For the mazes you always pick a spot on the bottom, in the starting color and try to get to the first row. Once you reach the first row, you are out of the maze. You can move horizontally and vertically, but not diagonally. It is also allowed to move on the same node more then once.
Sample Input
Sequence
O G
Maze
B O R O Y
O R B G R
B O G O Y
Y G B Y G
R O R B R
Sample output
/ / / O /
/ / / G /
/ O G O /
/ G / / /
/ O / / /
"""
import copy
MAZE = []
SEQ = []
SOL = []
N = 0 # No of rows in maze
M = 0 # No of cols in maze
S = 0 # Sequence Length
def main():
"""Main Function.
Calls other function to work for it... :D
"""
# input the MAZE, SEQunece, and gereates a blank SOLution
get_inputs()
failed = True
for i in xrange(M):
if get_sol(copy.deepcopy(SOL), [['' for _ in x] for x in SOL], -1, [N-1, i]):
failed = False
print '\n'*3, 'SOLUTION:'
for row in SOL:
for e in row:
print e,
print ''
break
if failed:
print '\n'*3, 'FAILED, No Solution Found'
def get_inputs():
"""Input."""
global SOL, MAZE, SEQ, M, N, S
# Input Maze
MAZE = input('Enter a list of list as input matrix: ')
N = M = len(MAZE)
# Create Blank Solution
SOL = [['/' for _ in x] for x in MAZE]
# Get Sequence to use
S = int(raw_input('Enter length of Sequence: '))
for i in xrange(S):
col = raw_input('Enter Color Letter: ').upper()
SEQ.append(col)
print '\n', 'Maze:'
for i in xrange(N):
for j in xrange(M):
print MAZE[i][j],
print ''
print '\n', 'Sequence:'
print SEQ
def get_sol(cur_sol, when_reached, seq_pos, last_pos):
"""Sols."""
global SOL
seq_pos = 0 if seq_pos == S-1 else seq_pos + 1
i, j = last_pos
# print MAZE[i][j], SEQ[seq_pos], MAZE[i][j] == SEQ[seq_pos]
if MAZE[i][j] == SEQ[seq_pos]:
# Check if we are entering an infinite loop
if str(seq_pos) in when_reached[i][j]:
return False
# Updated current temp solution, and mark the path used
cur_sol[i][j] = SEQ[seq_pos]
when_reached[i][j] += str(seq_pos)
# If we reached the top
if i == 0:
SOL = cur_sol
return True
# Go Up
if i > 0 and get_sol(copy.deepcopy(cur_sol), when_reached, seq_pos, [i-1, j]):
return True
# Go Down
if i < N-1 and get_sol(copy.deepcopy(cur_sol), when_reached, seq_pos, [i+1, j]):
return True
# Go Left
if j > 0 and get_sol(copy.deepcopy(cur_sol), when_reached, seq_pos, [i, j-1]):
return True
# Go Right
if j < M-1 and get_sol(copy.deepcopy(cur_sol), when_reached, seq_pos, [i, j+1]):
return True
# Return False if no sol found
return False
if __name__ == '__main__':
main()
| true |
2e2040449bac85c3dcabef42f995a2bef7c00966 | pavit939/A-December-of-Algorithms | /December-09/url.py | 444 | 4.1875 | 4 | def https(s):
if(s[0:8]=="https://"):
return '1'
else:
return '0'
def url(s):
if (".com" in s or ".net" in s or ".org" in s or ".in" in s):
return "1"
else :
return '0'
s = input("Enter the string to check if it is an URL")
c = https(s)
if c =='1':
u = url(s)
if u =='1':
print(f"{s} is an URL")
else:
print(f"{s} is not an URL")
else:
print(f"{s} is not an URL")
| true |
63488064897109f0ba3806912b1fcf38e759a97f | Krishna-Mohan-V/SkillSanta | /Assignment101-2.py | 964 | 4.40625 | 4 | # Python program to find the second largest number in a list
# Method 1
lst = []
num = int(input("Enter the Number of elements for the List: "))
for i in range(num):
elem = int(input("Enter the list element: "))
lst.append(elem)
print("List Elements are: ",lst)
lst.sort()
print("Second largest Number in the List is ",lst[-2])
# Method 2
lst = []
num = int(input("Enter the Number of elements for the List: "))
for i in range(num):
elem = int(input("Enter the list element: "))
lst.append(elem)
print("List Elements are: ",lst)
lst.sort()
lst.reverse()
print("Second largest Number in the List is ",lst[1])
# Method 3
lst = []
num = int(input("Enter the Number of elements for the List: "))
for i in range(num):
elem = int(input("Enter the list element: "))
lst.append(elem)
print("List Elements are: ",lst)
lst.remove(max(lst))
print("Second largest Number in the List is ",max(lst))
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.