blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
f746de4262b1c9f975a55ee02581b7a873ce1146 | tglaza/Automate-the-Boring-Stuff-with-Python | /while_break_yourName_input.py | 514 | 4.28125 | 4 | #this is similar the first yourName program, except it uses a break to end the program
#break statements are useful if you have several different places in a while loop that would allow you to leave from that point
name = ''
while True: #this would never be False so it's an infinite loop because it's always True
print('Please type your name.')
name = input()
if name == 'your name': #uses an if statement to cause a break in the program so it doesn' run forever
break
print('Thank you!')
| true |
3caa06220975d573f9400da144c54c853555addc | robbailiff/database-operations | /sqlite_functions.py | 1,920 | 4.84375 | 5 | """
Here is some practice code for using the sqlite3 module with Python.
Here I was experimenting with applying functions in SQLite statements.
I have included comments throughout explaining the code for my own benefit, but hopefully they'll help someone else too.
Hope you like the code. Any tips, comments or general feedback are welcome.
Thanks,
Rob
+++++++++++++++++++++++++++++++++++++++++
For anyone looking for a tutorial on the sqlite3 module, the tutorial I used is located here: https://www.pythoncentral.io/advanced-sqlite-usage-in-python/
Also the official documentation: https://docs.python.org/3/library/sqlite3.html
"""
# Import libraries
import sqlite3
# Define function
def temp_converter(temp):
result = round((temp - 32) / 1.8, 1)
return result
# Connect to the database
db = sqlite3.connect(':memory:')
# Register the function using the create_function method of connection object, which takes 3 arguments
# First is the name which will be used to call the function in an SQL statement
# Second is the number of arguments in the function to be called
# Third is the function object (i.e. the defined function itself)
db.create_function('F_to_C', 1, temp_converter)
# Create cursor object
cursor = db.cursor()
# Create a table in the database
cursor.execute('''CREATE TABLE weather(
id INTEGER PRIMARY KEY,
city TEXT,
temp REAL)''')
# Insert data into the table but call the function to convert the temperature from Farenheit to Celcius
cursor.execute('''INSERT INTO weather(city, temp) VALUES (?,F_to_C(?))''', ("London", 68.3))
# Commit the changes
db.commit()
# Retrieve all the data in the table
cursor.execute('''SELECT * FROM weather''')
# Fetch first entry of cursor selection and notice that the temperature has been converted
result = cursor.fetchone()
print(f"Result returned from query: \n{result}")
# And finally close down the database
db.close()
| true |
43d180dea65f2b5d65ec2da20c6524b0e42047c5 | mareaokim/hello-world | /03_8번Gregorian.py | 456 | 4.1875 | 4 | def main():
print("Gregorian epact value of year.")
print()
year = int(input("Enter the year (e.g. 2020) : "))
c = year // 100
epact = (8+(c//4) - c + ((8*c+13)//25) + 11 * (year % 19)) % 30
print()
print("The epact value is" , epact, "days.")
main()
>>>>>>>>>>>>>>>
Gregorian epact value of year.
Enter the year (e.g. 2020) : 2030
The epact value is 25 days.
Press any key to continue . . .
| true |
d0a504f3603a3c9471c2826dd00cada6044f1a21 | mareaokim/hello-world | /03_3번weight.py | 700 | 4.28125 | 4 |
def main():
print("This program calculates the molecular weight of a hydrocarbon.")
print()
h = int(input("Enter the number of hydrogen atoms : "))
c = int(input("Enter the number of carbon atoms : "))
ox = int(input("Enter the number of oxygen atoms : "))
weight = 1.00794 * h + 12.0107 * c + 15.9994 * ox
print()
print("The molecular weight is :" , weight)
main()
>>>
This program calculates the molecular weight of a hydrocarbon.
Enter the number of hydrogen atoms : 45
Enter the number of carbon atoms : 56
Enter the number of oxygen atoms : 55
The molecular weight is : 1597.9234999999999
Press any key to continue . . .
| true |
e18412d42429782751836ec1759665325a172b4f | mareaokim/hello-world | /03_12번number2.py | 975 | 4.375 | 4 | def main():
print("This program finds the sum of the cubes of the first n natural numbers.")
print()
n = int(input("Please enter a value for n : "))
sum = 0
for i in range(1,n+1):
sum = sum + i**3
print()
print("The sum of cubes of 1 through through", n, "is : ",sum)
main()
>>>>>>>>>>>>>>>>
This program finds the sum of the cubes of the first n natural numbers.
Please enter a value for n : 9
The sum of cubes of 1 through through 9 is : 1
The sum of cubes of 1 through through 9 is : 9
The sum of cubes of 1 through through 9 is : 36
The sum of cubes of 1 through through 9 is : 100
The sum of cubes of 1 through through 9 is : 225
The sum of cubes of 1 through through 9 is : 441
The sum of cubes of 1 through through 9 is : 784
The sum of cubes of 1 through through 9 is : 1296
The sum of cubes of 1 through through 9 is : 2025
Press any key to continue . . .
| true |
2decab40de10c88aa8102ab675e9fa1f3a46c8b0 | riteshsahu16/python-programming | /2 loop/ex1.10_check_ifprime.py | 270 | 4.125 | 4 | #Q10. Write a program to check whether a number is prime or not.
n = int(input())
i = 2
is_prime = True
while(i <= n//2):
if n%i==0:
is_prime = False
break
i += 1
if is_prime:
print("The no. is prime")
else:
print("The no. is NOT prime")
| true |
a0a1fbc6a48d45ccb858529ca0f5718390adeb00 | MOIPA/MyPython | /practice/basic/text_encode.py | 473 | 4.21875 | 4 | # in RAM all text would be translated to Unicode
# while in Disk there are UTF-8
str = u'编码' # Unicode now
str = str.encode('utf-8') # UTF-8
print(str)
str = str.decode('utf-8')
print(str)
# riverse
a = u'\u5916'
print(a)
a = a.encode('utf-8')
print(a)
# -*- coding: utf-8 -*-
# the above line means read the code file in utf-8
# format string
str = 'hello,%s, the num is %d' % ('world',10)
print(str)
str = '%.2f' % 3.14111
print(str)
str = '%d%%' % 10
print(str) | true |
6e0e2c9518732023f4416e5971029e73947d5ea3 | MOIPA/MyPython | /practice/basic/list_tuple.py | 372 | 4.15625 | 4 | list_num = [1, 2, 3, 4, 5]
print(list_num[-1]) # 3
# delete
list_num.pop() # delete the end one
list_num.pop(2) # delete the third one
print(list_num)
# add
list_num.append(6)
list_num.insert(0, -1)
# update
list_num[0] = 0
# tow dimensional array
one = [2.1, 2.2, 2.3]
array = [1, one, 2, 3]
print(array[1][0])
# tuple ,can't be changed once inited
t = (1, 2, 3)
| true |
d47af399c0c701882f4c78b20395df6808d2c503 | Douglass-Jeffrey/Unit-5-06-Python | /rounder.py | 1,330 | 4.375 | 4 | #!/usr/bin/env python3
# Created by: Douglass Jeffrey
# Created on: Nov 2019
# This program turns inputs into a proper address format
def rounding(number, rounder):
# This function rounds the user's number
# Process
rounded_number = (number[0]*(10**rounder))
rounded_number = rounded_number + 0.5
rounded_number = int(rounded_number)
rounded_number = rounded_number/(10**rounder)
return rounded_number
def main():
# This function takes the user's number then outputs the number rounded
# rounder list
rounding_number = []
# Process
while True:
decimal = input("Enter the number you wish to be rounded: ")
rounder = input("Enter how many decimal places you want left: ")
try:
decimal = float(decimal)
rounder = int(rounder)
rounding_number.append(decimal)
if decimal == float(decimal) and \
rounder == int(rounder):
rounded_val = rounding(rounding_number, rounder)
print("")
print("Your number rounded is", rounded_val)
break
else:
print("Please input proper values")
except Exception:
print("Please input proper values")
print("")
if __name__ == "__main__":
main()
| true |
74ae9c1c92272b3cd54e2a76269ddf32994c5822 | brentholmes317/Project_Euler_Problems_1-10 | /Project_Euler/13_adjacent.py | 1,086 | 4.34375 | 4 | from sys import argv, exit
from check_integer import check_input_integer
"""
This reads a file and finds the largest product that can be had by multiplying
13 adjancent numbers. The program needs the final line in the text to be blank.
"""
script, filename = argv
txt = open(filename)
reading = 1 #keeps track of if the file has concluded
array_of_digits = []
#converts our file to an array of digits
while(reading == 1):
sequence = txt.readline()
if sequence == '':
reading = 0
else:
line = check_input_integer(sequence)
for i in range(sequence.__len__()-1):
array_of_digits.append(line % (10**(sequence.__len__()-1-i)) // 10**(sequence.__len__()-2-i))
biggest = 0
biggest_array = [0,0,0,0,0,0,0,0,0,0,0,0,0]
for i in range(array_of_digits.__len__()-12):
product = 1
for j in range(13):
product = product * array_of_digits[i+j]
if biggest < product:
biggest = product
for k in range(13):
biggest_array[k] = array_of_digits[i+k]
print(f"{biggest} is the product of {biggest_array}")
| true |
b942302e280c289fceac406b562b7fb05b7cab36 | 36rahu/codewar_works | /22-4-2015/product_of_diagonal.py | 341 | 4.3125 | 4 | '''
Description:
Given a list of rows of a square matrix, find the product of the main diagonal.
Examples:
main_diagonal_product([[1,0],[0,1]]) => 1
main_diagonal_product([[1,2,3],[4,5,6],[7,8,9]]) => 45
'''
def main_diagonal_product(mat):
result = 1
for i in range(len(mat[0])):
result *= mat[i][i]
return result
| true |
153705a0ea3ff05d7e59fcd5bee4f28ac60ce413 | muhammeta7/CodeAcademyPython | /strings_cons_output.py | 1,542 | 4.375 | 4 | # Create a string by surrounding it with quotes
string = "Hello there "
# For words with apostrophe's us a backslash \
print "There isn\'t flying, this is falling with style!"
# Accesing by index
print fifth_letter = "MONTY"[4] # Will return Y
# String methods
parrot = "Parrot"
print len(parrot) # will return number of letters in a string which in this case is 6
print parrot.lower() # will return parrot with all lowercase letters
print parrot.upper() # will return PARROT with all captialized letters
pi = 3.14
print str(pi) # will turn non-strings into strings
# String Concatenation
print "Green Eggs " + "and " + "ham!" # Must take into account spaces
# String formatting with %
name = "Moe"
state = "New Jersey"
print "Hello my name is %s! I am from %s" %(name, state)
# String concatination with raw_inputs
name = raw_input("What is your name?")
quest = raw_input("What is your quest?")
color = raw_input("What is your favorite color?")
# \ is simply a continuation marker
print "Ah, so your name is %s, your quest is %s, " \
"and your favorite color is %s." % (name, quest, color)
# Getting current data and time
from datetime import datetime
now = datetime.now
print now # will print date in following format year-month-day 23:43:37.127290
print now.year # will return current year
print now.month # will return current month
print now.day # will return current day
# To properly format everything simply use %s
print "%s/%s/%s" % (now.month, now.day, now.year)
# Same can be done for time using hour, minute, second
| true |
598768ac97d73068511606617b003142fcbcc7c1 | anbarasanv/PythonWB | /Merge Sort Recursive.py | 890 | 4.21875 | 4 | #Time complexity O(n log n)
def merge(left,right):
'''This Function will merge 2 array or list'''
result = []
i,j = 0,0
#Comparing two list for smallest element
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i +=1
else:
result.append(right[j])
j +=1
#left elements appends to the result list
result += left[i:]
result += right[j:]
return result
def mergeSort(lst):
'''This is the recursive sorting array'''
if(len(lst) <= 1):
return lst
#Finding the mid
mid = int(len(lst)/2)
#Recursive call for left and right array or list
left = mergeSort(lst[:mid])
right = mergeSort(lst[mid:])
#Merginging splited lists or array
return merge(left,right)
A = [1,-2,0,-3,10,999999,20]
print(mergeSort(A))
| true |
3000f9b65ad6926b0274a5d94ea41a7e2608781f | bimri/programming_python | /chapter_1/person_start.py | 1,107 | 4.125 | 4 | "Step 3: Stepping Up to OOP"
'Using Classes'
class Person:
def __init__(self, name, age, pay=0, job=None):
self.name = name
self.age = age
self.pay = pay
self.job = job
if __name__ == '__main__':
bob = Person('Bob Smith', 42, 30000, 'software')
sue = Person('Sue Jones', 45, 40000, 'hardware')
print(bob.name, sue.pay)
print(bob.name.split()[-1])
sue.pay *= 1.10
print(sue.pay)
'''
This isn’t a database yet, but we could stuff these objects into a list or dictionary as
before in order to collect them as a unit:
>>> from person_start import Person
>>> bob = Person('Bob Smith', 42)
>>> sue = Person('Sue Jones', 45, 40000)
>>> people = [bob, sue] # a "database" list
>>> for person in people:
print(person.name, person.pay)
>>> x = [(person.name, person.pay) for person in people]
>>> x
[('Bob Smith', 0), ('Sue Jones', 40000)]
>>> [rec.name for rec in people if rec.age >= 45] # SQL-ish query
['Sue Jones']
>>> [(rec.age ** 2 if rec.age >= 45 else rec.age) for rec in people]
[42, 2025]
'''
| true |
9ae6c269b41521b7ededa35ccae246557185174f | bimri/programming_python | /chapter_7/gui2.py | 492 | 4.28125 | 4 | "Adding Buttons and Callbacks"
import sys
from tkinter import *
widget = Button(None, text='Hello GUI world!', command=sys.exit)
widget.pack()
widget.mainloop()
'''
Here, instead of making a label, we create an instance of the tkinter Button class.
For buttons, the command option is the place where we specify a callback handler function
to be run when the button is later pressed. In effect, we use command to register an
action for tkinter to call when a widget’s event occurs.
'''
| true |
f46676e4e06c7657a92b10f6ac48f8a13f199d02 | bimri/programming_python | /chapter_1/tkinter102.py | 964 | 4.15625 | 4 | "Step 5: Adding a GUI"
'Using OOP for GUIs'
'''
In larger programs, it is often more useful to code a GUI as a subclass
of the tkinter Frame widget—a container for other widgets.
'''
from tkinter import *
from tkinter.messagebox import showinfo
class MyGui(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
button = Button(self, text='press', command=self.reply)
button.pack()
def reply(self):
showinfo(title='popup', message='Button pressed!')
if __name__ == '__main__':
window = MyGui()
window.pack()
window.mainloop()
'''
The button’s event handler is a bound method—self.reply, an object that remembers
both self and reply when later called.
but because it is now a subclass of
Frame, it automatically becomes an attachable component—i.e., we can add all of the
widgets this class creates, as a package, to any other GUI, just by attaching this Frame
to the GUI.
'''
| true |
73e6e2712fc736f21f7818bef2c63815de570750 | hymhanraj/lockdown_coding | /range.py | 266 | 4.40625 | 4 | ''' Given start and end of a range, write a Python program to print all negative numbers in given range.
Example: Input: start = -4, end = 5 Output: -4, -3, -2, -1 Input: start = -3, end = 4 Output: -3, -2, -1
'''
for num in range(-3,4):
if num<0:
print(num)
| true |
040cdf085336c553e8b0951a59a25028577999f7 | helper-uttam/Hacktober2020-5 | /Python/calc.py | 1,011 | 4.1875 | 4 | def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
while True:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("Select operation.")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice(1/2/3/4):")
result = 0
if choice == '1':
result = add(num1, num2)
elif choice == '2':
result = subtract(num1, num2)
elif choice == '3':
result = multiply(num1, num2)
elif choice == '4':
if(num2 !=0):
result = divide(num1, num2)
else:
result="Divide by 0"
else:
print("Invalid Input")
print("Result = ", result)
quit = input("Do you want to continue (y/n) ?")
if quit == 'n':
break
| true |
20e5713218979589bc452c464c4e9d52216d2b2b | mishra28soumya/Hackerrank | /Python/Basic_Data_Types/second_largest.py | 673 | 4.125 | 4 | #Find the Runner-Up Score!
# Given the participants' score sheet for your University Sports Day, you are required to find the runner-up score.
# You are given n scores. Store them in a list and find the score of the runner-up.
# Input Format
# The first line contains N. The second line contains an array A[] of N integers each separated by a space.
# Constraints
# 2 <= N <= 10
# -100 <= A[i] <= 100
# Output Format
# Output the value of the second largest number.
if __name__ == '__main__':
n = int(raw_input())
l = list(map(int, raw_input().split()))
s = set(l) #to get all the unique numbers
result = sorted(list(s))
print(result[-2])
| true |
8763f32cd9ae69553a4554c0223283a51c5522be | crypto4808/PythonTutorial_CoreySchafer-master1 | /intro.py | 1,731 | 4.3125 | 4 | #import as a smaller name so you don't have to type 'my_modules' each time
# import my_modules
# #from my_module import find_index
# courses = ['history', 'math' , 'physics' , 'compsci' ]
# index = my_modules.find_index(courses,'math')#
# print(index)
#Use shorthand for my_modules so you don't have to type it out all the time
# import my_modules as mm
# courses = ['history', 'math' , 'physics' , 'compsci' ]
# index = mm.find_index(courses,'math')
# print(index)
# #import the function itself
# from my_modules import find_index
# courses = ['history', 'math' , 'physics' , 'compsci' ]
# index = find_index(courses,'math')
# print(index)
# #import the function itself
# #access the test variable from my_modules
# from my_modules import find_index,test
# courses = ['history', 'math' , 'physics' , 'compsci' ]
# index = find_index(courses,'math')
# print(index)
# print(test)
# #import the function itself
# #access the test variable from my_modules
# from my_modules import find_index as fi, test
# courses = ['history', 'math' , 'physics' , 'compsci' ]
# index = fi(courses,'math')
# print(index)
# print(test)
#import everything though it's frowned upon
#Reason is if something goes wrong with find_index
#it's virtually impossible to find which module it was imported from
#access the test variable from my_modules
# from my_modules import *
# courses = ['history', 'math' , 'physics' , 'compsci' ]
# index = find_index(courses,'math')
# print(index)
#how does python know where is the module?
#py checks multiple locations for this modules
from my_modules import find_index, test
import sys
courses = ['history', 'math' , 'physics' , 'compsci' ]
index = find_index(courses,'math')
print(index)
print(sys.path)
| true |
b9b1a64e80fe8d1a4e9038e36d98f84b56f75ba8 | Cassie-bot/Module-3 | /Area.py | 340 | 4.40625 | 4 | #Casandra Villagran
#1/30/2020
#This is a program that computes the area of a circle using the radius and it prints a message to the user with the answer.
radius = int(input ("What is the radius of the circle? "))
Area= 3.14 * radius ** 2
print ("I loved helping you find the area of this circle, here is your answer " + str(Area))
| true |
13091fa05d4d93a37a34f95520e6de8746a93763 | avijitkumar2011/My-Python-programs | /middle_letter.py | 213 | 4.1875 | 4 | #To find middle letter in a string
def middle(strg):
if len(strg) % 2 == 1:
n = len(strg)//2
print('Middle letter in string is:', strg[n])
else:
print('enter string of length odd number')
middle('kuma')
| true |
dcd1d7304fd1d7dbf55602f6f95150d98d92ea66 | Ma11ock/cs362-asgn4 | /avg_list.py | 226 | 4.125 | 4 | #!/usr/bin/env python
# Calculate the average of elements in a list.
def findAvg(lst):
if(len(lst) == 0):
raise ValueError("List is empty")
avg = 0
for i in lst:
avg += i
return avg / len(lst)
| true |
af211c4fb797589561c443a8593c3cc3bf122d47 | purnimagupta17/python-excel-func | /string_indexing_slicing_usingpython.py | 967 | 4.65625 | 5 | print('Hello World')
#to shift the 'World' to next line, we can use \n in the symtax as follows:
print('Hello \nWorld')
#to count the number of characters in a string, we use len function as follows:
str1="Hello"
print(len(str1))
#to assign the index number to a string, for example:
ss="Hello World"
print(ss[0])
print(ss[3:8])
#to jump on the string:
str2="abcdefghijk"
print(str2[::])
#to exclude the 2nd character from string
print(str2[::2])
#to reverse the string
print(str2[::-1])
#to edit the name in a string
name='sam'
#name[0]='P'
last_letters=name[1:]
last_letters
'P'+last_letters
#to combine two sentences/stings
x='Hello World'
x=x+ " It is beautiful outside"
x
#to concatenate the string
letter='z'
letter*10
#to concatenate the string
2+3
'2'+'3'
#to change the string to uppercase and lowercase
x='Hello World'
x
x.upper()
x.lower()
#to split the string
x.split()
#to split the string based on some specific characters
x.split('o')
| true |
7a71cc280ae6302fc83eebd003a4693c17f8bc2a | krallnyx/NATO_Alphabet_Translation | /main.py | 527 | 4.1875 | 4 | import pandas
data = pandas.read_csv("nato_phonetic_alphabet.csv")
alphabet = {row.letter: row.code for (index, row) in data.iterrows()}
def generate_phonetic():
to_translate = input("Please enter the word you want to translate into NATO Alphabet.\n").upper()
try:
output = [alphabet[letter] for letter in to_translate]
except KeyError:
print("Please enter a valid word, only letters in the alphabet are allowed")
generate_phonetic()
else:
print(output)
generate_phonetic()
| true |
efb19779c940b3f7d1f8999d089c2b2849764f1c | rckc/CoderDojo | /Python-TurtleGraphics/PythonIntro2-1Sequences.py | 1,435 | 4.5625 | 5 | # Author: Robert Cheung
# Date: 29 March 2014
# License: CC BY-SA
# For CoderDojo WA
# Python Intro Turtle Graphics
# Python has a rich "library" of functions.
# We are going to use "turtle" to do some simple graphics.
import turtle
# see https://docs.python.org/2/library/turtle.html#filling
if __name__ == "__main__":
# Setup our drawning surface
turtle.setup(800,600) # Sets up the size of the window
turtle.Screen() # Turns on the graphics window
# Set how fast we want the turtle to draw
turtle.speed(6); # 0 (fastest) .. 10 (slowest)
width = 20 # Create a variable called "width"
# and make it equal to 10
# In programming, computer follows instructions
# A "sequence" of instructions is the most basic construct
# It is simply a list of instructions
turtle.forward(width) # Step 1: Move forward 20 steps
turtle.right(90) # Step 2: Turn right 90 degrees
turtle.forward(width) # Step 3: Move forward 20 steps
turtle.right(90) # ... and so on
turtle.forward(width)
turtle.right(90)
turtle.forward(width)
turtle.right(90)
ret = input("Press enter to exit.")
turtle.Screen().bye() # Turn off the graphics window
# Library reference: http://docs.python.org/2/library/turtle.html
| true |
786073c2e842f81fd71fc391628f6161546b5a9e | yyuuliang/codingchallenges | /hackerrank/Reverse-a-doubly-linked-list.py | 2,556 | 4.15625 | 4 | '''
File: Reverse-a-doubly-linked-list.py
Source: hackerrank
Author: yyuuliang@github
-----
File Created: Thursday, 12th March 2020 4:21:54 pm
Last Modified: Thursday, 12th March 2020 4:21:58 pm
-----
Copyright: MIT
'''
# Reverse a doubly linked list
# https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=linked-lists
# Sample Input
# 4
# 1
# 2
# 3
# 4
# Sample Output
# 4 3 2 1
#!/bin/python3
import math
import os
import random
import re
import sys
class DoublyLinkedListNode:
def __init__(self, node_data):
self.data = node_data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def insert_node(self, node_data):
node = DoublyLinkedListNode(node_data)
if not self.head:
self.head = node
else:
self.tail.next = node
node.prev = self.tail
self.tail = node
def print_doubly_linked_list(node, sep, fptr):
while node:
fptr.write(str(node.data))
node = node.next
if node:
fptr.write(sep)
# Complete the reverse function below.
#
# For your reference:
#
# DoublyLinkedListNode:
# int data
# DoublyLinkedListNode next
# DoublyLinkedListNode prev
#
#
# use recursion to solve the problem
class node:
data=0
nextnode=None
prevnode=None
def __init__(self, dvalue):
self.data=dvalue
def printvalue(self):
print(self.data)
def printlinkedlist(head):
while head is not None:
head.printvalue()
head=head.nextnode
# double linked list
def reversedoublelinkedlist(head):
if head is None:
return None
tmp=reversedoublelinkedlist(head.nextnode)
if tmp is not None:
tmp.nextnode=head
tmp.nextnode.prevnode=tmp
tmp.nextnode.nextnode=None
return tmp.nextnode
else:
tmp=head
tmp.prevnode=None
tmp.nextnode=None
return tmp
def reverse(head):
tail =reversedoublelinkedlist(head)
# con=None
while tail.prevnode is not None:
# con=tail.prevnode
tail=tail.prevnode
return tail
n=node(1)
n2=node(2)
n3=node(3)
n4=node(4)
n.nextnode=n2
n2.nextnode=n3
n3.nextnode=n4
n2.prevnode=n
n3.prevnode=n2
n4.prevnode=n3
printlinkedlist(n)
t=reverse(n)
printlinkedlist(t)
# now I want to practice to reverse linkedlist in recursion
# which means dont use prev
| true |
7b04023a27193cf35c7c4db27c72cbb265193ddf | manusoler/code-challenges | /projecteuler/pe_1_multiples_3_and_5.py | 364 | 4.3125 | 4 | """
If we list all the natural numbers below 10 that are multiples of 3 or 5,
we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def multiples_of(*nums, max=1000):
return [i for i in range(max) if any([i % n == 0 for n in nums])]
if __name__ == "__main__":
print(sum(multiples_of(3,5)))
| true |
74b4f4975aff361161aaa469e959a1652b22a77d | manusoler/code-challenges | /projecteuler/pe_9_special_pythagorean_triplet.py | 723 | 4.3125 | 4 | import functools
from math import sqrt
from utils.decorators import timer
"""
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a**2+b**2=c**2
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
def pythagorean_triplet(summ):
for a in range(1,summ):
for b in range(a+1, summ):
c = sqrt(a**2+b**2)
if a + b + c == summ:
return (a,b,int(c))
@timer
def main():
triplet = pythagorean_triplet(1000)
print("Triplet: {}, Product: {}".format(triplet, functools.reduce(lambda x,y: x*y, triplet)))
if __name__ == "__main__":
main()
| true |
d3c3a3cf50793588756306288b30433842460b60 | littlejoe1216/Chapter-6-Exercies | /Python Chapter 6 Exercises/Chp 6 Excercise 4.py | 596 | 4.21875 | 4 | #Exercise 4:
#There is a string method called count that is similar to the function in the previous exercise.
#Read the documentation of this method at https://docs.python.org/3.5/library/stdtypes.html#string-methods
#and write an invocation that counts the number of times the letter a occurs in "banana".
word = "banana"
let = input("Enter a letter in the word banana.")
def counter():
count = 0
for letter in word:
if letter == let:
count = count + 1
return count
print (counter())
print ("is the number of times this letter is in the word banana.")
| true |
e3ddbeb215a0d6419b2ae83f2a0933ffc6fcb459 | mmengote/CentralParkZoo | /sketch_181013b/sketch_181013b.pyde | 971 | 4.34375 | 4 | #this library converts the random into integers
from random import randint
#lists of animals included in the simulation
#divided into two types, the zoo animals will have a starting state position of zoolocation.
#local animals will have a starting position of something else.
zoo_animals = ["Penguins", "Zebras", "Monkeys", "Sloths"]
local_animals = ["Humans", "Squirrels", "Racoons", "Coyotes"]
#this chooses the type of zoo animal that will escape randomly. they're stored in variables.
escapedAnimalRandom = zoo_animals[randint(0,3)]
numberOfescaped = randint(0,100) #maybe change the max to the capacity of population for the zoo
#this is the variable of which animal escaped and how many of them escaped
wantedAnimals = {
"animal escaped": escapedAnimalRandom,
"number escaped": numberOfescaped
}
#random escaped
#will need to visualize this instead of words eventually.
print wantedAnimals
## where would the penguin go##
| true |
4f03b52ca0f1f596bfe78b065f44ee8eb0f3b10c | markcharyk/data-structures | /tests/insert_sort_tests.py | 1,085 | 4.125 | 4 | import unittest
from data_structures.insert_sort import insertion_sort
class TestInsertSort(unittest.TestCase):
def setUp(self):
"""Set up some lists to be sorted"""
self.empty = []
self.single = [5]
self.sorted = [1, 2, 3, 10]
self.unsorted = [8, 1, 94, 43, 33]
def testEmpty(self):
"""Test an empty list"""
expected = []
actual = insertion_sort(self.empty)
self.assertEqual(expected, actual)
def testSingle(self):
"""Test a list of one item"""
expected = [5]
actual = insertion_sort(self.single)
self.assertEqual(expected, actual)
def testSorted(self):
"""Test an already sorted list"""
expected = [1, 2, 3, 10]
actual = insertion_sort(self.sorted)
self.assertEqual(expected, actual)
def testUnsorted(self):
"""Test an unsorted list"""
expected = [1, 8, 33, 43, 94]
actual = insertion_sort(self.unsorted)
self.assertEqual(expected, actual)
if __name__ == '__main__':
unittest.main()
| true |
9689a252589118db6d6623abb196aff8c3efa9ab | vielma24/playground | /bank.py | 1,337 | 4.40625 | 4 | #!/usr/bin/python
'''Program will intake customer information and account information. Account
management will also be added.'''
from datetime import date
#*******************************************************************************
class person:
"""
Returns a ```Person``` object with the given name, DOB, and phone number.
"""
import datetime
def __init__(self, name, DOB, phone_num):
self.name = name
self.DOB = date(DOB[0], DOB[1], DOB[2])
self.phone_num = phone_num
print("A student object is now created.")
def print_details(self):
"""
Prints the details of the student.
"""
print("Name:", self.name)
print("DOB:", self.DOB.year, self.DOB.month, self.DOB.day)
print("phone number:", self.phone_num)
#*******************************************************************************
def main():
# Test
'''This is how you create a new Person object and print the details.
The constructor must include 3 arguments as listed below.'''
aPerson = person('John Doe', (1982, 12, 15), 1)
aPerson.print_details()
''' TODO: Obtain the information of 5 new people and store them in a list
when complete print their details one at a time.'''
if __name__ == "__main__":
main()
| true |
9d625b9f273e27a48db58a2694b0b8e1eb537063 | dolapobj/interviews | /Data Structures/Array/MaximumProductSubarray.py | 1,155 | 4.3125 | 4 | #Maximum Product Subarray
#LC 152
"""
Given an integer array nums, find the contiguous subarray within an array
(containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
"""
#idea--> at every step we have three options
# 1. we get a max product by multiplying by current max so far with current element
# 2. we get a max product by multiplying current min so far with current element (multiply negs)
# 3. the current element can be the start for the maximum product subarray
def maxProductSubarray(nums):
maxProduct,minProduct,ans = nums[0],nums[0],nums[0]
for i in range(1,len(nums)):
tempMax = max(nums[i], nums[i]*maxProduct,nums[i]*minProduct)
tempMin = min(nums[i], nums[i]*maxProduct,nums[i]*minProduct)
maxProduct,minProduct = tempMax,tempMin
ans = max(ans,maxProduct)
return ans
#RT: O(n) --> loop through once
#SC: O(1) --> store 4 variables that are updated in each iteration
| true |
4076f61a183fac23c05fbf162dde7289caff5a74 | sndp2510/PythonSelenium | /basic/_04Geometry.py | 432 | 4.28125 | 4 | sideCount=int(input("Enter Number of side: "))
if(sideCount==1):
print("Its square")
side=int(input("Enter length of side : "))
print("Area of the square is : " , (side*side))
elif(sideCount==2):
print("Its Rectangle")
length = int(input("Enter length of side : "))
breadth =int(input("Enter length of side : "))
print("Area of the square is : " , (length*breadth))
else:
print("Invalid Entry")
| true |
d60ccaf31fe2c293d566effaf936c5c17e6064e3 | ksu-is/Commute-Traffic-Twitter-Bot | /Practice/user_funct.py | 1,027 | 4.28125 | 4 |
## will create text file for new users with info on each line. (not able to do OOP yet reliably so this is the best I've got)
# do you have an account?
user_ask = input("Before we start, lets specify what user this is for\nHave you used this program before?\nType 'y' or 'n' only: ")
if user_ask.lower() == "n":
filename = input("Okay, new user! What is your name?\nType your first name here to create your username: ").lower() + ".txt"
user_file = open(filename, 'w+')
print("\nNow lets load up all the highways that you use for your commute into your user account.")
#at this point, i am able to make a custom text file for any new user
while True:
append = input("\nEnter one highway at a time\nType '75', '85, '285', '20', or '400'\nOr type 'end' to finish.\nEnter here: ")
if append.lower() == "end":
break
else:
user_file.write(append)
user_file.write("\n")
user_file.seek(0)
print(user_file.readlines())
#def make_user(): | true |
1e3cc57af263476e1346cccf480a6ed62e7c891d | jenshurley/python-practice | /python_early_examples.py | 1,836 | 4.125 | 4 | # Initial variable to track game play
user_play = "y"
# While we are still playing...
while user_play == "y":
# Ask the user how many numbers to loop through
user_number = input("How many numbers? ")
# Loop through the numbers. (Be sure to cast the string into an integer.)
for x in range(int(user_number) + 1):
# Print each number in the range
print(x)
# Once complete...
user_play = input("Continue: (y)es or (n)o? ")
# Ask for how many numbers
# Print them out
# Ask again or quit
# if you get more numbers, add that many to the highest original number
playing = True
current_num = 1
while playing:
number = input("How many numbers would you like or q to quit: ")
if number != 'q':
number = int(number)
for x in range(current_num, current_num + number):
print(x)
current_num += number
else:
playing = False
# In 2 lists, we have dogs and their meals
# eg, Chance eats steak, lucky eats chow, etc...
dogs = ['chance', 'scout', 'rover', 'lucky', 'boss']
meals = ['steak', 'chicken', 'bones', 'chow', 'vegan']
# If someone gives us a dog, how can we return their meal?
def find_meal(some_dog):
pass
#Return the meal the dog eats
# Hit, you'll have to use an index lookup and
# Use that to find the meals
#Rover --> Bones as an example
# Ask for how many numbers
# Print them out
# Ask again or quit
# if you get more numbers, add that many to the highest original number
playing = True
current_num = 1
while playing:
number = input("How many numbers would you like or q to quit: ")
if number != 'q':
number = int(number)
for x in range(current_num, current_num + number):
print(x)
current_num += number
else:
playing = False
3 CommentsCollapse
| true |
0be835d18fae63f8b63fbae296f65250f8b38ac4 | koaning/scikit-fairness | /skfair/common.py | 1,752 | 4.4375 | 4 | import collections
def as_list(val):
"""
Helper function, always returns a list of the input value.
:param val: the input value.
:returns: the input value as a list.
:Example:
>>> as_list('test')
['test']
>>> as_list(['test1', 'test2'])
['test1', 'test2']
"""
treat_single_value = str
if isinstance(val, treat_single_value):
return [val]
if hasattr(val, "__iter__"):
return list(val)
return [val]
def flatten(nested_iterable):
"""
Helper function, returns an iterator of flattened values from an arbitrarily nested iterable
>>> list(flatten([['test1', 'test2'], ['a', 'b', ['c', 'd']]]))
['test1', 'test2', 'a', 'b', 'c', 'd']
>>> list(flatten(['test1', ['test2']]))
['test1', 'test2']
"""
for el in nested_iterable:
if isinstance(el, collections.abc.Iterable) and not isinstance(
el, (str, bytes)
):
yield from flatten(el)
else:
yield el
def expanding_list(list_to_extent, return_type=list):
"""
Make a expanding list of lists by making tuples of the first element, the first 2 elements etc.
:param list_to_extent:
:param return_type: type of the elements of the list (tuple or list)
:Example:
>>> expanding_list('test')
[['test']]
>>> expanding_list(['test1', 'test2', 'test3'])
[['test1'], ['test1', 'test2'], ['test1', 'test2', 'test3']]
>>> expanding_list(['test1', 'test2', 'test3'], tuple)
[('test1',), ('test1', 'test2'), ('test1', 'test2', 'test3')]
"""
listed = as_list(list_to_extent)
if len(listed) <= 1:
return [listed]
return [return_type(listed[: n + 1]) for n in range(len(listed))]
| true |
7a5d6f9bdd12a2aa3d4d1ce7c50723742a23cd46 | Azoad/Coursera_py4e | /chapter7/ex_07_01.py | 220 | 4.375 | 4 | """Take a file as input and display it at uppercase"""
fname = input('Enter the file name: ')
try:
file = open(fname)
except:
print('Error in file!')
quit()
for line in file:
print(line.strip().upper())
| true |
6dafc193f5e2f1731df5462295131e2cee3236b8 | victorrayoflight/Foudil | /Examen 2019-02-18/6.py | 582 | 4.15625 | 4 | x = True
y = False
z = False
# False OR True == True
# True OR False == True
# True OR True == True
# False OR False == False
# True AND True = True
# True AND False = False
# False AND True = False
# False AND False = False
# False XOR True == True
# True XOR False == True
# True XOR True == False
# False XOR False == False
if not x or y:
# False or False == False
print(1)
elif not x or not y and z:
# False or True and False == False
print(2)
elif not x or y or not y and x:
# False or False or True and True == True
print(3)
else:
print(4)
| true |
9d848849b6d688b2872bd9923a86319e3ad73807 | Anchals24/InterviewBit-Practice | /Topic - String/Longest Common Prefix.py | 1,216 | 4.25 | 4 | #Longest Common Prefix.
#Arr = ["aa" , "aab" , "aabvde"]
"""
Problem Description >>
Given the array of strings A, you need to find the longest string S which is the prefix of ALL the strings in the array.
Longest common prefix for a pair of strings S1 and S2 is the longest string S which is the prefix of both S1 and S2.
For Example: longest common prefix of "abcdefgh" and "abcefgh" is "abc".
"""
#Solution : 1
def longestcommonprefix(Arr):
smallest = min(Arr) #Find the smallest element of the array
#print(smallest)
lmini = len(smallest) #length of the smallest element of the array
i = 0
common = ""
while i < lmini:
for A in Arr:
if A[i] != smallest[i]:
return common
common += smallest[i]
i += 1
return common
print(longestcommonprefix(["aaaaaa" , "aab" , "aabvde" , "aabb"]))
#Solution : 2
def longestcommonprefix2(Arr):
minele = min(Arr)
maxele = max(Arr)
count = 0
for i in range(min(len(maxele) , len(minele))):
if minele[i] == maxele[i]:
count += 1
return minele[:count]
print(longestcommonprefix2(["aa" , "aabse" , "a" ]))
| true |
ac81f1e984700b6b3993e1b60e29812dc82e69c4 | emlemmon/emlemmon.github.io | /python/Week6/check06b.py | 1,121 | 4.4375 | 4 | class Phone:
"""Parent class that has 3 member variables and 2 methods"""
def __init__(self):
self.area_code = 0
self.prefix = 0
self.suffix = 0
def prompt_number(self):
self.area_code = input("Area Code: ")
self.prefix = input("Prefix: ")
self.suffix = input("Suffix: ")
def display(self):
print("Phone info:")
print("({}){}-{}".format(self.area_code, self.prefix, self.suffix))
class SmartPhone(Phone):
"""Child class of Phone that includes the member variables from Phone as well as an email address"""
def __init__(self):
super().__init__()
self.email = ""
def prompt(self):
Phone.prompt_number(self)
self.email = input("Email: ")
def display(self):
Phone.display(self)
print(self.email)
def main():
newPhone = Phone()
newCell = SmartPhone()
print("Phone:")
newPhone.prompt_number()
print()
newPhone.display()
print()
print("Smart phone:")
newCell.prompt()
print()
newCell.display()
if __name__ == "__main__":
main() | true |
41f61ba806ae6942a62b114ae624ab00ce0d6b7d | kobecow/algo | /NoAdjacentRepeatingCharacters/problem.py | 543 | 4.15625 | 4 | """
Given a string, rearrange the string so that no character next to each other are the same.
If no such arrangement is possible, then return None.
Example:
Input: abbccc
Output: cbcbca
"""
def rearrangeString(s: str) -> str or None:
pass
print(rearrangeString("gahoeaddddggrea"))
# no order required
# ahgogrgededadad
print(rearrangeString("cccciiiiiddddssskkdddcc"))
# no order required
# ckckcscscsdidididididcd
# improvement
# this is too complicated comarared to answer.py.
# use only slice operation, not priority queue. | true |
c47370697303df60b4e50e91092a5564b047a718 | stephenforsythe/crypt | /shift.py | 1,172 | 4.125 | 4 | """
This is essentially a substitution cypher designed to avoid fequency analysis.
The idea is to shift the char to the right by an increasing number, until n = 25,
at which time the loop will start again.
Spaces are treated as a character at the end of the alphabet.
"""
import string
FULL_ALPHABET = string.lowercase + ' '
MOD_NUM = len(FULL_ALPHABET)
def encrypt_decrypt(instr, direction):
shift = 0
encrypted_message = ''
for char in instr.lower():
pos = string.index(FULL_ALPHABET, char)
mod_pos = pos % MOD_NUM
if direction == 'en':
shift_pos = (mod_pos + shift) % MOD_NUM
else:
shift_pos = (mod_pos - shift) % MOD_NUM
encrypted_message += FULL_ALPHABET[shift_pos]
shift += 1
return encrypted_message
eord = raw_input('Encrypt or decrypt? (e/d):\n')
if eord == 'e':
user_input = raw_input('Message to be encrypted:\n')
print 'encrypted message:\n'
print encrypt_decrypt(user_input, 'en')
elif eord == 'd':
user_input = raw_input('Message to be decrypted:\n')
print 'plain text:\n'
print encrypt_decrypt(user_input, 'de')
else:
print 'error'
| true |
dfed06b4bbf51b8d57511753a08f09e26e3605d0 | MuhammetEser/Class4-PythonModule-Week4 | /4- Mis Calculator.py | 2,631 | 4.28125 | 4 | # As a user, I want to use a program which can calculate basic mathematical operations. So that I can add, subtract, multiply or divide my inputs.
# Acceptance Criteria:
# The calculator must support the Addition, Subtraction, Multiplication and Division operations.
# Define four functions in four files for each of them, with two float numbers as parameters.
# To calculate the answer, use math.ceil() and get the next integer value greater than the result
# Create a menu using the print command with the respective options and take an input choice from the user.
# Using if/elif statements for cases and call the appropriate functions.
# Use try/except blocks to verify input entries and warn the user for incorrect inputs.
# Ask user if calculate numbers again. To implement this, take the input from user Y or N.
import math
from addition import Addition
from subtraction import Subtraction
from multiplication import Multiplication
from division import Division
afronden = math.ceil
def num_input():
while True:
try:
number = float(input("Please enter a float number: "))
break
except ValueError:
print("""Please enter a valid float number using "." """)
return number
def operant():
while True:
try:
symbol = input("Please enter a mathematical operator symbol (+,-,*,/): ")
if symbol != '+' and symbol != '-' and symbol != '*' and symbol != '/':
raise ValueError
break
except ValueError:
print("Please enter a valid mathematical operator!")
return symbol
def yes_no():
while True:
try:
letter = input("Would you like to make another calculation (Y,N): ")
if letter != 'Y' and letter != 'y' and letter != 'N' and letter != 'n':
raise ValueError
break
except ValueError:
print("Oops! That was no valid symbol. Try again...")
return letter
while True:
symbol = operant()
if symbol == '+':
print("Result: " + str(afronden(Addition(num_input(), num_input()))))
elif symbol == '-':
print("Result: " + str(afronden(Subtraction(num_input(), num_input()))))
elif symbol == '*':
print("Result: " + str(afronden(Multiplication(num_input(), num_input()))))
elif symbol == '/':
print("Result: " + str(afronden(Division(num_input(), num_input()))))
antwoord = yes_no()
if antwoord == 'N' or antwoord == 'n':
break | true |
5cae2691b29e74917c55007405b67e7fcf1a60de | KennethNielsen/presentations | /python_and_beer_lesser_known_gems/ex6_namedtuple.py | 2,143 | 4.21875 | 4 | """namedtuple example"""
from __future__ import print_function
from collections import namedtuple
def arange(start, end, step):
"""Arange dummy function"""
print('arange', start, end, step)
def get_data_from_db(data_id):
"""Get data from db dummy function"""
print('get_data_from_db', data_id)
def plot(x, y, title):
"""plot dummy function"""
print('plot with title: "{}"'.format(title))
################################### Without named tuple
def without_named_tuple():
"""Without named tuple"""
print('Without named tuple')
# A dataset is: data_id, comment, step, start, end
datasets = (
(1234, 'this is the one', 0.1, 45, 55),
(1345, 'no wait this is', 0.2, 40, 60),
(1456, 'I know I got it now', 0.2, 40, 60),
(1567, 'OK maybe not .. let\'s try something else', 0.05, 40, 60),
(1678, 'here we go again', 0.05, 40, 62),
)
for dataset in datasets:
print('\n### Process dataset', dataset)
# Remember a dataset is: data_id, comment, step, start, end
x = arange(dataset[3], dataset[4], dataset[2])
y = get_data_from_db(data_id=dataset[0])
plot(x, y, title=dataset[1])
####################################### With named tuple
def with_named_tuple():
"""With named tuple"""
print('\n\nWith named tuple')
dataset = namedtuple('dataset', 'data_id comment step start end')
#dataset = namedtuple('dataset', ['data_id', 'comment', 'step', 'start', 'end'])
datasets = (
dataset(1234, 'this is the one', 0.1, 45, 55),
dataset(1345, 'no wait this is', 0.2, 40, 60),
dataset(1456, 'I know I got it now', 0.2, 40, 60),
dataset(1567, 'OK maybe not .. let\'s try something else', 0.05, 40, 60),
dataset(1678, 'here we go again', 0.05, 40, 62),
)
for dataset in datasets:
print('\n### Process', dataset)
x = arange(dataset.start, dataset.end, dataset.step)
y = get_data_from_db(data_id=dataset.data_id)
plot(x, y, title=dataset.comment)
if __name__ == '__main__':
#without_named_tuple()
with_named_tuple()
| true |
de31bc761ac04f9c15ac4a74328d74b907fbd822 | oliviamillard/CS141 | /coinAdder.py | 1,690 | 4.28125 | 4 | #Olivia Millard - Lab 3a
#This program will add up a user's coins based off of their input.
#Short welcome message.
print("Hello. This program will add up all of your change!\nCool! Let's get started.\n")
"""
This function, first, take input from the user asking how many coins they have. Next, it takes input for what type of coin they have.
And last, it adds up the total coins depending on their value
### Variables ###
value = how much the individual coin is worth.
coinNumber = which coin of theirs they are inputting the type for (penny, nickel, dime, quarter).
total = the total amount of their coins added together.
dollarAmount = the quotient from doing integer division on the total.
centsAmount = the remainder from using modulus on the total.
"""
def addUpCoins():
value = 0
coinNumber = 1
total = 0
numOfCoins = int(input("How many coins do you have? "))
while coinNumber <= numOfCoins:
coin = str(input("What is coin #" +str(coinNumber)+ "? (q for quarter, d for dime, n for nickel, p for penny): "))
coinNumber = coinNumber + 1
if coin == "p":
value = 0.01
total = total + value
elif coin == "n":
value = 0.05
total = total + value
elif coin == "d":
value = 0.10
total = total + value
elif coin == "q":
value = 0.25
total = total + value
dollarAmount = total // 100
centsAmount = total % 100
print("\n")
print("Whoa... you have a lot of monies!\n" +str(dollarAmount)+ " dollars and " +str(centsAmount)+ " cents if we're being exact.")
print("Now go buy yourself something nice.")
addUpCoins()
| true |
173ecefb3bd3070bff1b3cd83e91dab2dd2eb4bd | renan-suetsugu/WorkshopPythonOnAWS | /Labs/Loops/lab_6_step_1_Simple_Loops.py | 545 | 4.125 | 4 | #fruit = ['apples','oranges','bananas']
#for item in fruit:
# print(f'The best fruit now is {item}')
#numbers = [0,1,2,3,4,5,6,7,8,9,10]
#for number in numbers:
# print(f'The next number is {number}')
#for number in range(10):
# print(f'The next number is{number}')
#for number in range(10):
# print(f'The actual number is {number} and next number is {number+1}')
#for number in range(1,10):
# print(f'The next number is {number}')
for number in range(1,10,2):
print(f'The next number is {number}')
| true |
2a4dd3b8574142a991f73761bd43d6e2688c83a0 | blackicetee/Python | /python_games/simple_games/MyValidator.py | 451 | 4.125 | 4 | """This self written python module will handle different kinds of user input and validate it"""
# This is a module for regular expressions see python documentation "Regular expression operations"
import re
class MyValidator:
@staticmethod
def is_valid_from_zero_to_three(user_input):
regex_pattern = r'[0-3]'
if re.match(regex_pattern, user_input) is not None:
return True
else:
return False
| true |
8190dd1f19c1c918cd16997aae5a2c0b77c60607 | CoitThomas/Milestone_7 | /7.1/test_string.py | 480 | 4.3125 | 4 | """Verify the correct returned string value of a list of chars given
to the funtion string().
"""
from reverse_string import string
def test_string():
"""Assert the correct returned string values for various lists of
chars given to the string() function.
"""
# Anticipated input.
assert string(['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']) == 'Hello world'
# 1 input.
assert string(['A']) == 'A'
# No input.
assert string([]) == ''
| true |
bc58fb8b971f9a907786caac451b8d603a7ec1c0 | llduyll10/backup | /Backup/BigOGreen/classPython.py | 1,960 | 4.34375 | 4 | #Create Class
class MyClass:
x=5
print(MyClass)
#Create object
p1 = MyClass()
print(p1.x)
#__innit__() function
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
p1 = Person("DuyNND",22)
print(p1.name)
print(p1.age)
#Object METHOD
#Object can also cotain method
class People:
def __init__(self,name,age):
self.name = name
self.age = age
def myFunction(self):
print("Hello my name is: " + self.name)
p1 = People("DuyNguyenVJPPRO",20)
p1.myFunction()
#Self parameter
#parameter is a reference to the current instance of the class,
# and is used to access variables that belong to the class.
#Use the words mysillyobject and abc instead of self
class UpdatePerson:
def __init__(duyobject,name,age):
duyobject.name = name
duyobject.age = age
def myFunction(abc):
print("Hello my name is: " + abc.name)
p1 = UpdatePerson("John", 30)
p1.myFunction()
#Delete Objects
# p2 = UpdatePerson("Test", 20)
# del p2.age
# print(p2.age)
#Python Inheritance
class ParentClass:
def __init__(self,fname,lname):
self.firstName = fname
self.lastName = lname
def printName(self):
print(self.firstName, self.lastName)
P1 = ParentClass("Nguyen","Duy")
P1.printName()
#Create child class
class ChildClass(ParentClass):
pass
P2 = ChildClass("Duy","Pro")
P2.printName()
#Add properties in Child class
#And add method in Child class
class People:
def __init__(self,fname,lname):
self.firstName = fname
self.lastName = lname
def printName(self):
print(self.firstName, self.lastName)
class Student(People):
def __init__(self,fname,lname,year):
super().__init__(fname,lname)
self.graduationyear = year
def welcomeNewbie(self):
print(self.firstName, self.lastName, self.graduationyear)
x = Student("DuyNND","Vippro",2020)
x.welcomeNewbie()
print(x.graduationyear) | true |
950af6a1c4cd4ffe12ff99061bb44cfd0104fec6 | regismagnus/challenge_python | /is_list_palindrome.py | 1,390 | 4.15625 | 4 | '''
Note: Try to solve this task in O(n) time using O(1) additional space,
where n is the number of elements in l, since this is what you'll be asked to do during an interview.
Given a singly linked list of integers, determine whether or not it's a palindrome.
Note: in examples below and tests preview linked lists are presented as arrays just for simplicity of visualization:
in real data you will be given a head node l of the linked list
Example
For l = [0, 1, 0], the output should be
isListPalindrome(l) = true;
For l = [1, 2, 2, 3], the output should be
isListPalindrome(l) = false.
'''
# Singly-linked lists are already defined with this interface:
class ListNode(object):
def __init__(self, x):
self.value = x
self.next = None
def isListPalindrome(l):
a=convertToArray(l)
for i in range(int(len(a)/2)):
if a[i]!=a[len(a)-i-1]:
return False
return True
def convertToArray(l):
a=[]
if(l!=None):
a.append(l.value)
c=l.next
while(c!=None):
a.append(c.value)
c=c.next
return a
''''l=ListNode(1)
l.next=ListNode(1000000000)
l.next.next=ListNode(-1000000000)
l.next.next.next=ListNode(-1000000000)
l.next.next.next.next=ListNode(1000000000)
l.next.next.next.next.next=ListNode(1)'''
l=ListNode(0)
l.next=ListNode(1)
l.next.next=ListNode(0)
print(isListPalindrome(l)) | true |
0f9ba273804db8997bd5ec73e7c233c11d58eac5 | regismagnus/challenge_python | /longest_word.py | 611 | 4.34375 | 4 | '''
Define a word as a sequence of consecutive English letters. Find the longest word from the given string.
Example
For text = "Ready, steady, go!", the output should be
longestWord(text) = "steady".
best solution by dnl-blkv:
return max(re.split('[^a-zA-Z]', text), key=len)
'''
def longestWord(text):
rex='[\[\],!@#$%&{}+-=~^`_*/:()<>|?*]|(\\\)'
m=None
w=None
text=re.sub(rex, ' ',text)
for word in text.split():
word=re.sub(rex, '',word)
if m==None or m<len(word):
m=len(word)
w=word
return w
print(longestWord('Ready, steady, go!')) | true |
bee95c39ec36fa669a574732be32e6a85d024117 | bvishny/basic-algos | /mergesort_inversions.py | 2,008 | 4.25 | 4 | # Basic Merge Sort Implementation
# Components
# 1. split_array(array) array array - takes an array and splits it at the midpoint into two other arrays
# 2. merge(array, array) array - takes two split arrays and merges them together sorted
# 3. mergesort(array) array - takes an array and sorts it using mergesort
def split_array(array):
split_pt = (len(array) / 2)
return (array[:split_pt], array[split_pt:])
# Tests:
# Empty Array:
arr1, arr2 = split_array([])
if not (len(arr1) == 0 and len(arr2) == 0):
print("Empty array failed")
# 1 Elem Array
arr1, arr2 = split_array([1])
if not (len(arr1) == 0 and len(arr2) == 1 and arr2[0] == 1):
print("1 Elem array failed")
# Odd Elem Array
arr1, arr2 = split_array([1,2,4])
if not (len(arr1) == 1 and len(arr2) == 2 and arr2[-1] == 4):
print("Odd Elem Array Failed")
# Even Elem Array
arr1, arr2 = split_array([1,2,3, 4])
if not (len(arr1) == 2 and len(arr2) == 2 and arr1[-1] == 2):
print("Even Elem Array Failed")
# MERGE:
class Counter(object):
def __init__(self):
self.total = 0
def incr(self, amt):
self.total += amt
def count(self):
return self.total
def merge(array1, array2, counter):
idx1, idx2, result = 0, 0, []
while idx1 < len(array1) or idx2 < len(array2):
if idx2 >= len(array2) or (idx1 < len(array1) and array1[idx1] <= array2[idx2]):
result.append(array1[idx1])
idx1 += 1
else:
result.append(array2[idx2])
idx2 += 1
counter.incr(len(array1) - idx1)
return result
# MERGESORT:
def mergesort(array, counter = Counter()):
if len(array) > 1:
arr1, arr2 = split_array(array)
else:
return array
return merge(mergesort(arr1, counter), mergesort(arr2, counter), counter)
c = Counter()
f = [int(x) for x in open("/Users/10gen/Downloads/IntegerArray.txt", 'r').read().split("\r\n")[:-1]]
result3 = mergesort(f, c)
print(c.count())
| true |
b98c45e58694e05b7fadee7721ce57a4e625c603 | shubhamPrakashJha/selfLearnPython | /6.FunctionalProgramming/6.Recursion.py | 328 | 4.1875 | 4 | def factorial(x):
if x == 1:
return 1
else:
return x*factorial(x-1)
print(factorial(int(input("enter the number: "))))
def is_even(x):
if x == 0:
return True
else:
return is_odd(x-1)
def is_odd(x):
return not is_even(x)
print(is_even(23))
print(is_odd(1))
print(is_odd(2)) | true |
f9a34ec2cd69deb1bc020afd803e3abd5f3ac877 | juechen-zzz/LeetCode | /python/0207.Course Schedule.py | 2,706 | 4.125 | 4 | """
There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
Example 1:
Input: numCourses = 2, prerequisites = [[1,0]]
Output: true
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0. So it is possible.
Example 2:
Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should
also have finished course 1. So it is impossible.
"""
# BFS
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# 存储有向图
edges = collections.defaultdict(list)
# 存储每个节点的入度
indeg = [0] * numCourses
# 存储答案
visited = 0
for info in prerequisites:
edges[info[1]].append(info[0])
indeg[info[0]] += 1
# 将所有入度为 0 的节点放入队列中
q = collections.deque([u for u in range(numCourses) if indeg[u] == 0])
while q:
visited += 1
u = q.popleft()
for v in edges[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return visited == numCourses
# DFS
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# 存储有向图
edges = collections.defaultdict(list)
# 标记每个节点的状态:0=未搜索,1=搜索中,2=已完成
visited = [0] * numCourses
# 用数组来模拟栈,下标 0 为栈底,n-1 为栈顶
result = list()
# 判断有向图中是否有环
valid = True
for info in prerequisites:
edges[info[1]].append(info[0])
def dfs(u: int):
nonlocal valid
visited[u] = 1
for v in edges[u]:
if visited[v] == 0:
dfs(v)
if not valid:
return
elif visited[v] == 1:
valid = False
return
visited[u] = 2
result.append(u)
for i in range(numCourses):
if valid and not visited[i]:
dfs(i)
return valid
| true |
837c95fb0a7b12b26dd16d0c3c693ac16ed1bfd1 | juechen-zzz/LeetCode | /python/0075.Sort Colors.py | 1,075 | 4.21875 | 4 | '''
Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library's sort function for this problem.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
'''
class Solution:
def sortColors(self, nums: List[int]) -> None:
'''
荷兰三色旗问题解
'''
# 对于所有 idx < p0 : nums[idx < p0] = 0
# curr是当前考虑元素的下标
p0 = curr = 0
# 对于所有 idx > p2 : nums[idx > p2] = 2
p2 = len(nums) - 1
while curr <= p2:
if nums[curr] == 0:
nums[p0], nums[curr] = nums[curr], nums[p0]
p0 += 1
curr += 1
elif nums[curr] == 2:
nums[curr], nums[p2] = nums[p2], nums[curr]
p2 -= 1
else:
curr += 1
| true |
c22a3a2358c43fa2010303fa125199b77168d3b5 | colemai/coding-challenges | /leetcode_challenges/L267-PalindromeP2.py | 2,627 | 4.28125 | 4 | #!/usr/bin/env python3
"""
Author: Ian Coleman
Input:
Output:
Challenge:
Given a string s, return all the palindromic permutations (without duplicates) of it.
Return an empty list if no palindromic permutation could be form.
For example:
Given s = "aabb", return ["abba", "baab"].
Given s = "abc", return [].
"""
from sys import argv
import pdb
from itertools import permutations
from sympy.utilities.iterables import multiset_permutations
# 1. Test case x
# 2. Brute
# 3. Optimise
# 4. Run Edge cases
# 5. Write Tests
# TODO make sure even numbers of each letter x
# make sure palindromic perm possible (only one uneven count) x
# use is palandrome as test
# def make_permutations (s):
# """
# Input: STRING s
# Output: List of permutations of s
# """
# perms = permutations(s)
# perms = [''.join(x) for x in perms]
# return(list(perms))
def is_palindrome (s):
"""
Input: STRING s
Output: BOOLEAN, True if s is a palindrome
"""
if s[::-1] == s:
return True
else:
return False
def get_symmetrical_half (s):
"""
Input: STRING s, must have even numbers of each char (except optionally for one letter)
Output: STRING, Symmetrical half of s
"""
assert isinstance(s, str), 'Argument must be string'
even = len(s) % 2 == 0
letters = list(set(list(s))) # crudely get unique letters
counts = []
symm_half = ''
for letter in letters:
counts.append(s.count(letter))
# Actually let's get the odd letter here (in the case of uneven length)
odd_letter = ''
if not even:
# Check string valid (odd length):
if not len([x for x in counts if x % 2 != 0]) == 1: exit('[]')
odd_letter = [x for x in letters if s.count(x) % 2 != 0][0]
letters.remove(odd_letter)
counts = [x for x in counts if x % 2 == 0]
# Check valid string (even length):
if not len([x for x in counts if x % 2 != 0]) == 0: exit('[]')
for i in range(0, len(letters)):
symm_half += ((counts[i]//2) * letters[i])
return(symm_half, odd_letter)
def get_pal_perms (sym_half, odd_letter):
"""
Input: STRING sym_half - half the string as split by letter,
STRING odd_letter - the odd letter if there is one
Output: LIST of all palindromic permutations of s
"""
perms = list(multiset_permutations(list(sym_half)))
perms = [''.join(x) for x in perms]
pal_perms = [x + odd_letter + x[::-1] for x in perms]
return pal_perms
if __name__ == "__main__":
s = 'aabbc'
# Edge Cases
if len(s) == 1:
print(s)
exit()
elif len(s) == 0:
print('Error: must give non-empty string')
exit()
sym_half, odd_letter = get_symmetrical_half(s)
pal_perms = get_pal_perms(sym_half, odd_letter)
print(pal_perms)
| true |
0c0e23c15708325ec523a31bd9b7bea1044ad2e4 | prameya21/python_leetcode | /Valid_Palindrome.py | 800 | 4.25 | 4 | '''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
'''
class Solution:
def isPalindrome(self,s:str) -> bool:
s=s.lower()
l,r=0,len(s)-1
while l<=r:
if not s[l].isdigit() and not s[l].isalpha():
l+=1
elif not s[r].isdigit() and not s[r].isalpha():
r-=1
else:
if s[l]!=s[r]:
return False
l+=1;r-=1
return True
obj=Solution()
print(obj.isPalindrome("A man, a plan, a canal: Panama")) | true |
92cc8732044e9fc0a64a3d7de55ec4393b6b4beb | kangwonlee/16pfa_kangwonlee | /ex29_if/ex29.py | 714 | 4.1875 | 4 | # -*-coding:utf8
# http://learnpythonthehardway.org/book/
people = 10
cats = 30
dogs = 15
if people < cats:
print("Too many cats! The world is doomed!")
if people > cats:
print("No many cats! The world is saved!")
if people < dogs:
print("The world is drooled on!")
if people > dogs:
print("The world is dry!")
dogs += 5
if people >= dogs:
print("People are greater than or equal to dogs.")
if people <= dogs:
print("People are less than or equal to dogs.")
if people == dogs:
print("People are dogs.")
# 여기까지 입력 후 add, commit
# 각 행 주석 입력 후 commit
# 각자 Study drills 시도 후 필요시 commit
# 오류노트 에 각자 오류노트 작성
| true |
24dad66dd22395fc2a92f2a403de09dcb82fbfe4 | Maschenka77/100_Day_Python | /day_2_tip_project_calculator.py | 625 | 4.21875 | 4 | #If the bill was $150.00, split between 5 people, with 12% tip.
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60
#Tip: You might need to do some research in Google to figure out how to do this.
print("Welcome to the tip calculator!")
total_bill = float(input("What is the total bill? "))
percent = int(input("What percentage tip would you like to give? "))
percent_div = percent/100
split = int(input("How many people to split the bill? "))
bill_splitted = total_bill/split
with_tip = round(bill_splitted*(1+percent_div),2)
print(f"Each person should pay: ${with_tip}")
| true |
9d0dec604ab6ca5aefcec6aca0a3766082e1419d | Aravind-39679/tri.py | /triangle.py | 658 | 4.125 | 4 | t=True
while(t):
A=int(input('Enter first side of the triangle:'))
B=int(input('Enter second side of the triangle:'))
C=int(input('Enter third side of the triangle:'))
if(A+B>C and B+C>A and A+C>B):
print("It is a triangle")
if(A==B==C):
print('It is an equailateral triangle')
break
elif(A==B!=C or A==C!=B or B==C!=A):
print('It is isosceles triangle')
break
elif(A!=B!=C):
print('It is scalene triangle')
break
else:
print("It is not a triangle")
print('input correct inputs')
#t=True
| true |
cae0951dcb0aaed9aa287c1e924211365b6bcf80 | Lynch08/pands-problem-sheet | /squareroot.py | 1,061 | 4.3125 | 4 | #Programme that uses a function so when you input a number it will return the square root
#Author Enda Lynch
#REF https://medium.com/@sddkal/newton-square-root-method-in-python-270853e9185d
#REF https://www.youtube.com/watch?v=WsQQvHm4lSw - Understand Calculas
#REF https://www.homeschoolmath.net/teaching/square-root-algorithm.php
#REF https://www.geeksforgeeks.org/find-root-of-a-number-using-newtons-method/
#REF https://www.school-for-champions.com/algebra/square_root_approx.htm#.YD102-j7TDe
#REF Automate the Boring Stuff - Chapter 3 Functions
newt = input("Number to get square root of:" )
def sqrt(number, iterations = 100):
newt = float(number) # number to get square root of
for i in range(1, iterations): # iteration number
number = 0.5 * (newt / number + number) # √ number ≈ .5*(newt/number + number)
return round((number), 1) # return number in for loop and set to 1 decimal place
print ("Square number of", newt, "is approx:", (sqrt(float(newt))))
| true |
53b9d3683feff9adfa34c88be6c856db960072ad | sheelabhadra/LeetCode-Python | /1033_Moving_Stones_Until_Consecutive.py | 2,232 | 4.21875 | 4 | """PROBLEM:
Three stones are on a number line at positions a, b, and c.
Each turn, you pick up a stone at an endpoint (ie., either the lowest or highest position stone), and move it
to an unoccupied position between those endpoints. Formally, let's say the stones are currently at positions
x, y, z with x < y < z. You pick up the stone at either position x or position z, and move that stone to an
integer position k, with x < k < z and k != y.
The game ends when you cannot make any more moves, ie. the stones are in consecutive positions.
When the game ends, what is the minimum and maximum number of moves that you could have made?
Return the answer as an length 2 array: answer = [minimum_moves, maximum_moves]
"""
"""SOLUTION:
The maximum number of moves would be the total number of empty spots between the stones.
The minimum number of moves can be obtained by analyzing the following 4 cases:
1. If the number of empty spots between any one of the pairs of successive stones is 1,
e.g. [1, 3, 5], and [3, 5, 10], then only 1 move is required which fills the empty spot between the pair of stones.
2. If there are no empty spots between both the successive pair of stones, e.g. [1, 2, 3], then no move is required.
3. If there is no empty spot between any one of the pairs of successive stones,
e.g. [2, 10, 11] or [2, 3, 10], then only 1 move is required.
4. For all the other possible configurations, at least 2 moves are required.
"""
class Solution:
def numMovesStones(self, a: int, b: int, c: int) -> List[int]:
stones = sorted([a, b, c])
max_moves = (stones[1] - stones[0] - 1) + (stones[2] - stones[1] - 1) # points between the stones
# add cases for min_moves
if stones[1] - stones[0] == 2 or stones[2] - stones[1] == 2:
# [1, 3, 5]
min_moves = 1
elif stones[1] - stones[0] == 1 and stones[2] - stones[1] == 1:
# [1, 2, 3]
min_moves = 0
elif stones[1] - stones[0] == 1 or stones[2] - stones[1] == 1:
# [2, 10, 11] or [2, 3, 10]
min_moves = 1
else:
# all other cases
min_moves = 2
return [min_moves, max_moves]
| true |
22e6457a4791af6292a17bbb294566aefdb9834e | sheelabhadra/LeetCode-Python | /728_Self_Dividing_Numbers.py | 1,425 | 4.125 | 4 | #A self-dividing number is a number that is divisible by every digit it contains.
# For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.
# Also, a self-dividing number is not allowed to contain the digit zero.
# Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.
# Example 1:
# Input:
# left = 1, right = 22
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
res = []
for num in range(left,right+1):
digits = []
temp = num
print(num)
while temp != 0:
lsd = temp%10
flag1 = 0
if lsd == 0:
print("Contains 0")
flag1 = 1
break
digits.append(lsd)
temp = temp//10
if flag1:
continue
for d in digits:
flag2 = 0
if num%d != 0:
flag2 = 1
break
if flag2:
continue
else:
res.append(num)
print(res)
return res
| true |
8f977472fd05fb250e180589c6545a545805a2ac | zahraaassaad/holbertonschool-machine_learning | /math/0x06-multivariate_prob/0-mean_cov.py | 854 | 4.28125 | 4 | #!/usr/bin/env python3
""" calculates the mean and covariance of a data set """
import numpy as np
def mean_cov(X):
"""
X is a numpy.ndarray of shape (n, d) containing the data set:
n is the number of data points
d is the number of dimensions in each data point
Returns: mean, cov:
mean numpy.ndarray of shape (1, d) containing the mean of the data set
cov numpy.ndarray of shape (d, d) containing the covariance matrix
of the data set
"""
if not isinstance(X, np.ndarray) or len(X.shape) != 2:
raise TypeError("X must be a 2D numpy.ndarray")
if X.shape[0] < 2:
raise ValueError("X must contain multiple data points")
d = X.shape[1]
mean = np.mean(X, axis=0)
a = X - mean
c = np.matmul(a.T, a)
cov = c/(X.shape[0] - 1)
return mean.reshape((1, d)), cov
| true |
e4a322de533519abc12a1819ef9bcea84113c488 | kwierman/Cards | /Source/Shuffle.py | 1,032 | 4.125 | 4 | """ @package Shuffle
Performs shuffling operations on decks
"""
import Deck
## splits the deck into two decks
# @param deck The deck to be split
# @param split_point how many cards from the top of the deck to split it
def split_deck(deck, split_point=26):
deck_1 = Deck.Deck()
deck_2 = Deck.Deck()
for x, card in enumerate(deck.private.cards):
if(x<split_point):
deck_1.add_card(card)
else:
deck_2.add_card(card)
return (deck_1, deck_2)
## performs a tent shuffle
def tent_shuffle(deck, split_point=26, groups=[], shuffle_left=True):
#first split it into two decks
deck1, deck2 = split_deck( deck, split_point )
if(shuffle_left):
deck3=deck1
deck1=deck2
deck2=deck3
#for each of the groups of cards
result_deck=Deck.Deck()
for x,i in enumerate(groups):
tent_group=Deck.Deck()
if(x%2==0 ):
tent_group,deck1 = split_deck(deck1, i)
else:
tent_group,deck2 = split_deck(deck2, i)
result_deck.add_deck(tent_group)
result_deck.add_deck(deck1)
result_deck.add_deck(deck2)
return result_deck
| true |
5fd87282bd2429a43a83feb00c542b07da1a4259 | simiyub/python | /interview/practice/code/arrays/SortedSquareFromSortedArray.py | 642 | 4.28125 | 4 | """
Given an array of sorted integers, this function returns a sorted array of the square of the numbers
"""
def sorted_square_array(array):
result = [0 for _ in array]
smaller_value_index = 0
larger_value_index = len(array) - 1
for index in reversed(range(len(array))):
smaller_value = array[smaller_value_index]
larger_value = array[larger_value_index]
if (abs(smaller_value) > abs(larger_value)):
result[index] = smaller_value ** 2
smaller_value_index += 1
else:
result[index] = larger_value ** 2
larger_value_index += 1
return result
| true |
6e713b61bedbe73121c1326b8d17ae7cd5d1ef06 | simiyub/python | /interview/practice/code/recursion/Permutations.py | 1,724 | 4.15625 | 4 | """
Requirement:This function will receive an array of integers and
create an array of unique permutations or ordering of integers
that can be created from the integers in the array.
Implementation: We build all permutations for the array within the array in place using pointers.
We select the first element in the array and use it as a starting element of all the combinations
of permutations that can be formed from the rest of the elements in the array.
We swap the first element in the remaining array of elements with the current anchor index.
Then we iteratively call the helper method a second time with the next element in the array of
remaining elements, the array and the array of permutations.
When we are done with this call, we swap back the elements to how they were before
and move on to the next index after the anchor index. When the index is the last one in the array,
we copy the array into the array of permutations.
Complexity: O(n*n!) T and O(n.n!) S For each element in the array,
we make calls to the helper equivalent to the position of the element in the array
which means the last one will have n.n! calls.
"""
def __swap(array, i, j):
array[i], array[j] = array[j], array[i]
def __permutations_helper(anchor_index, array, all_permutations):
if anchor_index == len(array) - 1:
all_permutations.append(array[:])
else:
for j in range(anchor_index, len(array)):
__swap(array, anchor_index, j)
__permutations_helper(anchor_index + 1, array, all_permutations)
__swap(array, anchor_index, j)
def permutations(array):
permutations_found = []
__permutations_helper(0, array, permutations_found)
return permutations_found
| true |
61066f828ffa00dd2652b07ea8e546e255682cf8 | simiyub/python | /interview/practice/code/linked_lists/ReverseLinkedList.py | 1,248 | 4.15625 | 4 | """
Requirement: Given a linked list where each node points to the next node,
this function will return the linked list in reverse order
Implementation: Conceptually, a node is reversed when the next pointer points to the previous node.
However, as this is a singly linked list, we do not have a pointer to the previous node.
So we need to create one. We do this using a temporary node that we initialise to None
as we start traversing the linked list from head.
We also need to keep a reference to the next node after the current node because
if we move the next pointer of the current node to the previous node,
we would lose connection to the rest of the linked list.
Once we have these two temporary references in place,
we start moving our pointers along recursively until the current node is null
and at that point the linked list will be reversed.
Complexity: O(n) T O(1) S as we have to recursively traverse the whole linked list.
However, we do not use any additional space than that of the linked list.
"""
def reverse(head):
previous = head
current = head
while current is not None:
next_node = current.next
current.next = previous
previous = current
current = next_node
return previous
| true |
fe1c5e5cea9e34e329b658982acd5bd7fd8f23af | shorya97/AddSkill | /DS & Algo/Week 2/Stack/Implement Stack using Queues.py | 1,420 | 4.15625 | 4 |
from queue import Queue
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.q1 = Queue() #inbuilt queues
self.q2 = Queue()
self.cur_size = 0 #contains number of elements
def push(self, x: int) -> None:
"""
Push element x onto stack.
"""
self.cur_size+=1
self.q2.put(x)
while (not self.q1.empty()):
self.q2.put(self.q1.queue[0])
self.q1.get()
self.q = self.q1
self.q1 = self.q2
self.q2 = self.q
def pop(self) -> int:
"""
Removes the element on top of the stack and returns that element.
"""
if (self.q1.empty()):
return
return self.q1.get()
self.cur_size -= 1
def top(self) -> int:
"""
Get the top element.
"""
if self.q1.empty():
return -1
return self.q1.queue[0]
def empty(self) -> bool:
"""
Returns whether the stack is empty.
"""
if self.q1.empty():
return True
else:
return False
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
| true |
be1b56dc341fc45d7c0d017bc979c4d1426f7afa | prabhu30/Python | /Strings/Set - 1/maketrans_translate.py | 743 | 4.5625 | 5 | """
maketrans() :-
It is used to map the contents of string 1 with string 2 with respective indices to be translated later using translate().
translate() :-
This is used to swap the string elements mapped with the help of maketrans().
"""
# Python code to demonstrate working of
# maketrans() and translate()
from string import maketrans # for maketrans()
str = "geeksforgeeks"
str1 = "gfo"
str2 = "abc"
# using maktrans() to map elements of str2 with str1
mapped = maketrans( str1, str2 )
# using translate() to translate using the mapping
print "The string after translation using mapped elements is : "
print str.translate(mapped)
"""
Output :
The string after translation using mapped elements is :
aeeksbcraeeks
"""
| true |
bdbfdd41268b98866a0eb26d1d335267b1a4f0b9 | prabhu30/Python | /Lists/Set - 1/indexing_negative.py | 666 | 4.375 | 4 | """
Negative indexing :-
In Python, negative sequence indexes represent positions from the end of the array.
Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3].
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.
"""
List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']
# accessing a element using
# negative indexing
print("Accessing element using negative indexing")
# print the last element of list
print(List[-1])
# print the third last element of list
print(List[-3])
"""
Output:
Accessing element using negative indexing
Geeks
For
"""
| true |
df60640085e6f84ebd72aee33d3dd29dfc4d950e | TrevorSpitzley/PersonalRepo | /PythonProjects/listCheck.py | 920 | 4.25 | 4 | #!/usr/bin/env python
# This file is used for comparing two lists.
# If there is an element in the input_list,
# and it is not in the black_list, then it
# will be added to the out_list and printed
def list_check(input_list, black_list):
out_list = []
for element in input_list:
if element not in black_list:
out_list.append(element)
return out_list
chars = ['a', 'b', 'c', 'd']
chars2 = ['e', 'f', 'g', 'h']
chars3 = ['a', 'c']
chars4 = ['e', 'h']
ints = [1, 2, 3, 4]
ints2 = [5, 6, 7, 8]
ints3 = [1, 2, 3]
ints4 = [5, 6, 7, 8]
# Should return ['b', 'd']
print(list_check(chars, chars3))
# Should return ['f', 'g']
print(list_check(chars2, chars4))
# Should return [4]
print(list_check(ints, ints3))
# Should return []
print(list_check(ints2, ints4))
# Should return ['e', 'f', 'g', 'h']
print(list_check(chars2, ints))
# Should return [1, 2, 3]
print(list_check(ints3, chars3))
| true |
62615472dad8b7cbd47655acab1ee1dcafcfc4f3 | cbolson13/Pyautogui_CO | /Personality_Survey_C.py | 1,876 | 4.21875 | 4 | print("What's your name?")
name = input().title()
if name == "Connor":
print("Same here!")
else:
print(name + " is a pretty cool name.")
print("What's your favorite sport")
sport = input().title()
if sport == "Soccer":
print("Cool, what's your favorite team!")
soccerteam = input().title()
if soccerteam == "Liverpool":
print("That is my favorite team also!")
elif soccerteam == "Manchester United" or soccerteam == "Everton":
print("Oh no, I like Liverpool and not " + soccerteam)
else:
print(soccerteam + " is not my favorite team, but I don't mind them")
elif sport == "Tenis":
print("Cool, sometimes I like to play tenis too!")
else:
print("Wow, " + sport + " sound fun!")
print("What's your favorite TV Show?")
tvshow = input().title()
if tvshow == "Flash" or tvshow == "Rick And Morty" or tvshow == "The Flash":
print("I love " + tvshow + " too! Who is your favorite character?")
character = input().title()
if character == "Cisco" or character == "Barry" or character == "The Flash" or character == "Joe" or character == "Wally" or character == "Kid Flash" or character == "HR" or character == "Rick" or character == "Morty" or character == "Beth" or character == "Jerry" or character == "Summer" or character == "Mr.Meeseeks":
print("Awesome, " + character + " is one of my favorite character too!")
elif character == "Iris":
print("I don't really like " + character + " that much.")
else:
print(character + " isn't my favorite, but I don't mind them.")
elif tvshow == "Leverage" or tvshow == "Psych" or tvshow == "Wizards Of Waverly Place":
print("I used to watch " + tvshow + " too!")
else:
print("I don't know about " + tvshow + " but it sounds good!")
| true |
e120d6a0b5708af15a2a50b654ef68837a12c03e | Abhiaish/GUVI | /ZEN class/day 1/fare.py | 236 | 4.15625 | 4 | distance=int(input("enter the distance"))
peaktime=int(input("enter the peaktime"))
if(distance>5):
distance=distance-5
else:
print("fare is 100")
fare=int(distance*8+100)
if(peaktime==1):
fare=fare+0.25*fare
print(fare)
| true |
bbdb68232f6a2d04d342d4cc274faa2d3d083aeb | renzhiliang/python_work | /chapter4/4-10.py | 293 | 4.34375 | 4 | #numbers=range(3,31,3)
numbers=[number**3 for number in range(1,11)]
print(numbers)
print("The first three items in the list are:")
print(numbers[0:3])
print("Three items from the middle of the list are:")
print(numbers[5:8])
print("The last three items in the list are:")
print(numbers[-3:])
| true |
cabc815a05896d9d72e0f904eac1aede308438e7 | thu4nvd/project_euler | /prob014.py | 1,184 | 4.15625 | 4 | #!/usr/bin/env python3
'''
Longest Collatz sequence
Problem 14
The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.
23.73s user
0.00s system
99% cpu
23.734 total
https://projecteuler.net/problem=14
'''
def collatz_seq(n):
length = 1
while n != 1:
if n % 2 == 0 : n = n // 2
else: n = 3 * n + 1
length += 1
return length
def solve(N):
max_length = 1
for i in range(2, N):
if max_length < collatz_seq(i):
max_length = collatz_seq(i)
max_i = i
return max_i
def main():
print(solve(1000000))
if __name__ == "__main__":
main()
| true |
12abd510bd551ccafd2101bb6392c35357bdbe47 | mtmccarthy/langlearn | /bottomupcs/Types.py | 1,530 | 4.71875 | 5 | from typing import NewType, Dict
"""
In Chapter 1, we learned that 'Everything is a File!'. Here we've created a new type, 'FileType' which models a file
as its path in the filesystem.
"""
FileType = NewType('FileType', str)
"""
In Chapter 1, we learned about FileDescriptors, which are essentially integer indexes into a table
stored by the kernel called the file descriptor table (shocking!)
Since a file descriptor is essentially just an integer, we can model it as such.
"""
FileDescriptorType = NewType('FileDescriptorType', int)
"""
We can model the table as a dictionary with key file descriptor and value file.
The fd table is generated for every process and holds a pointer to the system fd table, but the model still holds up.
"""
FileDescriptorTableType = Dict[FileDescriptorType, FileType]
"""
In Chapter 1, we learned about Device Drivers are software which provide an abstraction between the kernel and
external devices such as a keyboard, mouse, monitor etc.
"""
DeviceDriverType = NewType('DeviceDriverType', None)
"""
Programs are files that can also be executed. We can model that like this:
"""
ProgramType = NewType('ProgramType', FileType)
"""
In Chapter 1, the kernel was mentioned. The kernel is essentially a program executed when the system boots.
The kernel is responsible for processing low level system calls, examples include input/output and memory management.
Since the kernel is just a special type of program, we can model it like this:
"""
KernelType = NewType('KernelType', ProgramType)
| true |
6bb5fbe258c60e039c2380dcbbf50dc6b8e5d803 | mtmccarthy/langlearn | /dailyredditor/easy/imgurlinks_352.py | 1,574 | 4.25 | 4 | from common import *
from typing import Union
"""
Finds the greatest exponent of n that is less than or equal to another number m
Example: if n = 2 and m = 17 return 4
"""
def get_base62_character(index: int) -> Union[str, None]:
capital_letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
lower_case = 'abcdefghijklmnopqrstuvwxyz'
if index < 10:
return str(index)
elif 10 <= index < 36:
return lower_case[index - 10]
elif 36 <= index < 62:
return capital_letters[index - 36]
else:
return None
def find_greatest_exponent_of_n_loe_than_m(n: int, m: int) -> int:
current_exponent = 0
while n ** current_exponent <= m:
current_exponent += 1
return current_exponent - 1
def convert_from_base10ton(baseN: int, num: int) -> str:
conversion = []
power = find_greatest_exponent_of_n_loe_than_m(baseN, num)
while power > 0:
place_value = baseN ** power
digit = 0
while num - place_value > 0:
digit += 1
num -= place_value
conversion.append(digit)
power -= 1
conversion.append(num) # One's place
return ''.join(list(map(lambda digit: get_base62_character(digit), conversion)))
def generate_output(path: str) -> str:
lines = get_file_lines(path)
output = ""
for line in lines:
output += convert_from_base10ton(62, int(line.rstrip())) + '\n'
return output
def main():
path = 'easytests/imgurlinks_352_challenge_input.txt'
print(generate_output(path))
if __name__ == '__main__':
main()
| true |
17ce6e5c354abe914abb538356201ed5cfc55a25 | lamyai-norn/algorithsm-week11 | /week11/thursday1.py | 279 | 4.15625 | 4 | def sumFromTo(start,end):
result=0
if start>end:
return 0
else:
for index in range(start,end+1):
result=result+index
return result
startValue=int(input("Start value : "))
endValue=int(input("End value : "))
print(sumFromTo(startValue,endValue)) | true |
3ce463b0b5860ae48129db242597bb45d7620ecc | NikolasSchildberg/guesser | /guesser_simple.py | 1,218 | 4.21875 | 4 | """
Welcome to the number guesser in python!
The logic is to use the bissection method to find a number chosen by the user, only
providing guesses and asking to try a bigger or smaller one next time.
"""
# Initial message
print("Welcome to the number guesser!\nThink of a number between 1 and 1000 (including them).I'll take only 10 guesses (or less) to find out which number you picked.\nYou'll just have to tell me if your number is smaler or bigger than my guess. Wanna try it?")
print("Please enter '0' if I'm already right, '1' if your number is smaller, and '2' if your number is bigger.\n")
right = False
smaller = 0
bigger = 1000
guess = int((smaller + bigger)/2)
count_guesses = 0
while(right != True):
whattodo = input("Is it "+str(guess)+"?\n>>> " )
if whattodo == '0':
right = True
elif whattodo == '1':
bigger = guess
guess = int((smaller + bigger)/2)
elif whattodo == '2':
smaller = guess
guess = int((smaller + bigger)/2)
else: print("Try again...")
count_guesses += 1
else:
if(count_guesses == 1):
print("Gotcha! Needed",count_guesses,"guesse!\nBye!")
else:
print("Gotcha! Needed",count_guesses,"guesses!\nBye!") | true |
826f03f9f1dc41fe4aca2c70b505d7381ba091bf | EagleRock1313/Python | /circle.py | 523 | 4.40625 | 4 | # Load the Math Library (giving us access to math.pi and other values)
import math
# Ask for the radius of a circle that will be entered as a decimal number
radius = eval(input(("Enter the radius of the circle: ")))
# Computer circumference and area of this circle
circumference = 2 * math.pi * radius
area = math.pi * (radius ** 2)
# Results
print()
print("Circumference is", circumference)
print("Area is", area)
print("\nRounded: ")
print("Circumference is", round(circumference,2))
print("Area is", round(area,2)) | true |
fdeecfeec4bbea1b1c5bd1738bbadf905dcb3772 | Kapilmundra/Complete-Python-for-Lerner | /4 set.py | 691 | 4.21875 | 4 | #Create set
print("Create set")
s={"teena","meena","reena"}
print(s) # it can print in unorder way
#pop the element from the set
print("\npop the element from the set")
s.pop() # it can pop the element in unorder way
print(s)
#Add element in the set
print("\nAdd element in the set")
s.add("priya") # it can add the new value in unorder way
print(s)
s.add("priya") # distinct(not return same value in set)
print(s)
#Operation
print("\nOperation")
p={"rajesh","manish","reena"}
print(p)
print("Difference")
x=s.difference(p)
print(x)
print("Intersection")
z=s.intersection(p)
print(z)
print("Difference_update")
y=s.difference_update(p)
print(y)
| true |
d86d7fdc1e4fb8c3e6c328b2d4141f5b2e078f66 | das-jishu/data-structures-basics-leetcode | /Leetcode/hard/regular-expression-matching.py | 2,506 | 4.28125 | 4 | """
# REGULAR EXPRESSION MATCHING
Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*' where:
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa", p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Example 3:
Input: s = "ab", p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
Example 4:
Input: s = "aab", p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".
Example 5:
Input: s = "mississippi", p = "mis*is*p*."
Output: false
Constraints:
0 <= s.length <= 20
0 <= p.length <= 30
s contains only lowercase English letters.
p contains only lowercase English letters, '.', and '*'.
It is guaranteed for each appearance of the character '*', there will be a previous valid character to match.
"""
class Solution:
def isMatch(self, s: str, p: str) -> bool:
table = [[None for _ in range(len(p) + 1)] for _ in range(len(s) + 1)]
table[0][0] = True
for row in range(1, len(s) + 1):
table[row][0] = False
for col in range(1, len(p) + 1):
if p[col - 1] == "*":
table[0][col] = table[0][col - 2]
else:
table[0][col] = False
for row in range(1, len(s) + 1):
for col in range(1, len(p) + 1):
if p[col - 1] == ".":
table[row][col] = table[row - 1][col - 1]
elif p[col - 1] != "*":
table[row][col] = table[row - 1][col - 1] and s[row - 1] == p[col - 1]
else:
if p[col - 2] == ".":
table[row][col] = table[row][col - 1] or table[row][col - 2] or table[row - 1][col - 1] or table[row - 1][col]
else:
table[row][col] = table[row][col - 1] or table[row][col - 2] or (table[row - 1][col - 1] and p[col - 2] == s[row - 1])
for row in range(len(s) + 1):
print(table[row])
return table[-1][-1] | true |
59d4865c48cf12bac99b751cec480b1aa52b59c5 | das-jishu/data-structures-basics-leetcode | /Leetcode/medium/simplify-path.py | 2,163 | 4.5 | 4 | """
# SIMPLIFY PATH
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period '.' refers to the current directory. Furthermore, a double period '..' moves the directory up a level.
Note that the returned canonical path must always begin with a slash '/', and there must be only a single slash '/' between two directory names. The last directory name (if it exists) must not end with a trailing '/'. Also, the canonical path must be the shortest string representing the absolute path.
Example 1:
Input: path = "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: path = "/../"
Output: "/"
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: path = "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Example 4:
Input: path = "/a/./b/../../c/"
Output: "/c"
Constraints:
1 <= path.length <= 3000
path consists of English letters, digits, period '.', slash '/' or '_'.
path is a valid Unix path.
"""
def simplifyPath(path: str) -> str:
if len(path) == 1:
return "/"
res = "/"
path = path[1:]
if path[-1] != "/":
path += "/"
temp = ""
for x in path:
if x != "/":
temp += x
continue
else:
if temp == "" or temp == ".":
pass
elif temp == "..":
if res == "/":
pass
else:
t = len(res) - 2
while True:
if res[t] != "/":
res = res[:t]
t -= 1
else:
t -= 1
break
else:
res += temp + "/"
temp = ""
if len(res) > 2 and res[-1] == "/":
res = res[:len(res) - 1]
return res | true |
7028074d72039afc722149007fbae5fda2bba392 | SPARSHAGGARWAL17/DSA | /Linked List/linked_ques_4.py | 1,325 | 4.28125 | 4 | # reverse of a linked list
class Node():
def __init__(self,data):
self.data = data
self.nextNode = None
class LinkedList():
def __init__(self):
self.head = None
self.size = 0
def insertAtStart(self,data):
self.size += 1
node = Node(data)
currentNode = self.head
if self.head is None:
self.head = node
return
node.nextNode = currentNode
self.head = node
return
def display(self):
currentNode = self.head
if self.head is None:
print('List is Empty')
return
while currentNode is not None:
print('Data : ',currentNode.data)
currentNode = currentNode.nextNode
def reverse(self):
if self.head is None:
print('List is empty')
return
current = self.head
prev = None
while current is not None:
nextNode = current.nextNode
current.nextNode = prev
prev = current
current = nextNode
self.head = prev
link = LinkedList()
link.insertAtStart(4)
link.insertAtStart(3)
link.insertAtStart(2)
link.insertAtStart(1)
link.display()
link.reverse()
link.display() | true |
50dfd4b377425832e0a75179c16433e00d68ffda | Unknown-Flyin-Wayfarer/pycodes | /7/test_if4.py | 658 | 4.25 | 4 | a = int(input("enter first number"))
b = int(input("Enter second number"))
if a > b:
print("a is larger")
if a > 100:
print("a is also greater than 100")
if a > 1000:
print ("a is greater than 1000 also")
print("a is only greater than and not 1000")
print ("Thats enough")
if a > b and a > 100 and a > 1000:
print ("a is larger than b and 100 and 1000")
if b > a or b > 100 or b > 50:
print ("b has something to print")
print("Code exiting")
#input 3 numbers from user and find the largest
# input 6 numbers from the user and find the largest and smallest
| true |
e0622163402f580a65518211eb3378994a15bec2 | rajeshpillai/learnpythonhardway | /ex9.py | 717 | 4.1875 | 4 | # Exercise 9: Printing, Printing, Printing
# By now you should realize the pattern for this book is to use more than one
# exercise to teach you something new. I start with code that you might not
# understand, then more exercises explain the concept. If you don't understand something now,
# you will later as you complete more exercises. Write down what you don't understand, and keep going.
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the days: ", days
print "here are the months: ", months
print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as we like.
Even 4 lines if we want, or 5, or 6.
"""
| true |
e4288c0c6d4b3d2decad9a22a96a79fe8b9502b7 | rajeshpillai/learnpythonhardway | /ex31.py | 2,038 | 4.59375 | 5 | # Exercise 32: Loops and Lists
# You should now be able to do some programs that are much more interesting. If you have been keeping up, you should realize that now you can combine all the other things you have learned with if-statements and boolean expressions to make your programs do smart things.
# However, programs also need to do repetitive things very quickly. We are going to use a for-loop in this exercise to build and print various lists. When you do the exercise, you will start to figure out what they are. I won't tell you right now. You have to figure it out.
# Before you can use a for-loop, you need a way to store the results of loops somewhere. The best way to do this is with lists. Lists are exactly what their name says: a container of things that are organized in order from first to last. It's not complicated; you just have to learn a new syntax. First, there's how you make lists:
# hairs = ['brown', 'blond', 'red']
# eyes = ['brown', 'blue', 'green']
# weights = [1, 2, 3, 4]
# You start the list with the [ (left bracket) which "opens" the list. Then you put each item you want in the list separated by commas, similar to function arguments. Lastly, end the list with a ] (right bracket) to indicate that it's over. Python then takes this list and all its contents and assigns them to the variable.
the_count = [1,2,3,4,5]
fruits = ['apples', 'oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'quarters']
# this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number
# also we can go through mixed lists too
# notice we have use %r since we don't know what's in it
for i in change:
print "I got %r" % i
# we can also build lists, first start with an empty oranges
elements = []
# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print "Adding %d to the list." % i
# append is a function that lists understand
elements.append(i)
# now we can print them out too
for i in elements:
print "Element was : %d" % i
| true |
b6350d9fb8134ecb5fa0d840315140af1c905978 | mauriceLC92/LeetCode-solutions | /Arrays/Selection-sort.py | 607 | 4.125 | 4 | def find_smallest(arr):
smallestIndex = 0
smallestValue = arr[smallestIndex]
index = 1
while index < len(arr):
if arr[index] < smallestValue:
smallestValue = arr[index]
smallestIndex = index
index += 1
return smallestIndex
def selection_sort(arr):
sorted_array = []
arr_len = len(arr)
for i in range(arr_len):
smallest_value_position = find_smallest(arr)
sorted_array.append(arr.pop(smallest_value_position))
print(sorted_array)
return sorted_array
testArr = [5, 3, 6, 2, 10]
selection_sort(testArr)
| true |
c6fb497553306801c5ee4c71ef33e19a832dd6f0 | has-g/HR | /fb_1_TestQuestions.py | 1,551 | 4.1875 | 4 | '''
In order to win the prize for most cookies sold, my friend Alice and
I are going to merge our Girl Scout Cookies orders and enter as one unit.
Each order is represented by an "order id" (an integer).
We have our lists of orders sorted numerically already, in lists.
Write a function to merge our lists of orders into one sorted list.
For example:
my_list = [3, 4, 6, 10, 11, 15]
alices_list = [1, 5, 8, 12, 14, 19]
# Prints [1, 3, 4, 5, 6, 8, 10, 11, 12, 14, 15, 19]
print merge_lists(my_list, alices_list)
Solution:
def merge_sorted_lists(arr1, arr2):
return sorted(arr1 + arr2)
'''
def merge_sorted_lists(arr1, arr2):
sorted_arr = []
idx1 = 0
idx2 = 0
if len(arr1) == 0: return arr2
if len(arr2) == 0: return arr1
count = 0
while count < len(arr2) + len(arr1):
print('count = ' + str(count) + ', idx1 = ' + str(idx1) + ', idx2 = ' + str(idx2) + ', sorted_arr = ' + str(sorted_arr))
if idx2 >= len(arr2):
# idx2 is exhausted
sorted_arr.append(arr1[idx1])
idx1 += 1
elif idx1 >= len(arr1):
# idx1 is exhausted
sorted_arr.append(arr2[idx2])
idx2 += 1
elif arr2[idx2] < arr1[idx1]:
sorted_arr.append(arr2[idx2])
idx2 += 1
else:
sorted_arr.append(arr1[idx1])
idx1 += 1
count += 1
return sorted_arr
print(merge_sorted_lists([2, 4, 6, 8], [1, 7]))
#print(merge_sorted_lists([], [1, 7]))
#print(merge_sorted_lists([2, 4, 6], [1, 3, 7]))
| true |
77d6e6cd9187f8c0b5dc63059a37a717873f3717 | OSUrobotics/me499 | /plotting/basic.py | 1,617 | 4.5 | 4 | #!/usr/bin/env python3
# Import the basic plotting package
# plt has all of the plotting commands - all of your plotting will begin with ply.[blah]
# To have this behave more like MatLab, do
# import matplotlib.pyplot
# in which case the plt scoping isn't needed
import matplotlib.pyplot as plt
# Get some things from numpy. The numpy sin function allows us to apply sin to an array of numbers all at once,
# rather than one at a time. Don't worry much about this for now, since we'll talk about it more when we cover
# numpy in more detail.
from numpy import arange, sin, pi
if __name__ == '__main__':
# This shows the basic plotting functionality. plot() can take an iterable, and will plot the values in it.
# It will assume that the x-values are 0, 1, 2, and so on. In this example, we're plotting a sine function
# from 0 to 2 * pi, in increments of 0.01. The x-axis, however, (since you didn't specify it) will go from
# 0 to the number of points (around 500). See better.py to specify both x and y
plt.plot(sin(arange(0, 2 * pi, 0.01)))
# Note that functionality differs depending on if you're running in the debugger and what operating system you're
# using. In debug/interactive mode, the window may show up when you do the plot command. In non-interactive
# mode it won't show up until you do show
# We'll only see the graph when you run show(). The program will stop here, until you kill the plot window.
# If you want the window to stay up when you step over this line in the debugger, use this instead:
# plt.show(block=True)
plt.show()
| true |
744b7479288431296863e7d8d2254c0cd58c1ea4 | OSUrobotics/me499 | /files/basics.py | 760 | 4.40625 | 4 | #!/usr/bin/env python3
if __name__ == '__main__':
# Open a file. The second argument means we're opening the file to write to it.
f = open('example_file', 'w')
# Write something to the file. You have to explicitly add the end of lines.
f.write('This is a string\n')
f.write('So is this\n')
# You can't guarantee that things are written to the file until you close it.
f.close()
# You open for reading like this
f = open('example_file', 'r')
# You can read with f.read(), f.readline(), or use the more convenient for loop approach. The end of line
# character is included in the string that gets assigned to the line variable.
for line in f:
print(line)
# Close the file again
f.close()
| true |
84eb498c2dc5b63eb5942e3bd057b1d2602c0348 | OSUrobotics/me499 | /control/while_loops.py | 613 | 4.3125 | 4 | #!/usr/bin/env python3
if __name__ == '__main__':
# This is the basic form a while statement. This particular example is better suited to a for loop, though, since
# you know how many times round the loop you're going to go.
n = 0
while n < 5:
print(n)
n += 1
# This is a better example of using a while loop, since we don't know how many times round the loop we need to go.
numbers = [1, 4, 3, 6, 7]
i = 0
while numbers[i] != 3:
i += 1
if i == len(numbers):
print('Did not find number')
else:
print('Number is in position', i)
| true |
23b5df5c6836f5759b1b820eb7d57fc51d9d70ff | OSUrobotics/me499 | /containers/list_comprehensions.py | 870 | 4.3125 | 4 | #!/usr/bin/env python3
from random import random
if __name__ == '__main__':
# Instead of enumerating all of the items in a list, you can use a for loop to build one. Start with an empty
# list.
a = []
# This will build a list of the first 10 even numbers.
for i in range(10):
a.append(i * 2)
print(a)
# There's a more compact syntax for this, called a list comprehension.
a = [2 * i for i in range(10)]
print(a)
# Here's a list of 5 random numbers, using the random() function
a = [random() for _ in range(5)]
print(a)
# Same code as below but with if and for written out
a = []
for i in range(10):
if i % 2 == 0:
a.append(i)
# You can put conditions on the list elements. This builds a list of even numbers.
a = [i for i in range(10) if i % 2 == 0]
print(a)
| true |
7730f652b4b1bb37f4e2b33533317aca526af6c0 | Mksourav/Python-Data-Structures | /stringlibraryfunction.py | 819 | 4.15625 | 4 | greet=input("Enter the string on which you want to perform the operation::")
# zap=greet.lower()
# print("lower case of the inputted value:",zap)
#
# search=input("Enter the substring you want the find:")
# pos=greet.find(search)
# if pos=='-1':
# print("substring not found!")
# else:
# print("substring spotted!")
# print("So, the position of the substring is ", pos)
#
# old=input("Enter the old substring you want to remove:")
# new=input("Enter the new substring you want to replace on old one:")
# nstr=greet.replace(old,new)
# print("Your new string is ", nstr)
lws=greet.lstrip()
print("String after removing the left whitespace:", lws)
rws=greet.rstrip()
print("String after removing the right whitespace:", rws)
ras=greet.strip()
print("String after removing both left & right whitespace:",ras)
| true |
78345b42e8ff3dc48545a9d4d3bd1aeac5b74eef | HighPriestJonko/Anger-Bird | /Task1.py | 1,366 | 4.15625 | 4 | import math
v = int(input('Enter a velocity in m/s:')) # With which bird was flung
a = int(input('Enter an angle in degrees:')) # With respect to the horizontal
d = int(input('Enter distance to structure in m:'))
h = int(input('Enter a height in m:')) # Height of structure
g = -9.8 # m/s^2
degC = math.pi / 180
ar = a * degC # Degrees into radians for computational purposes
# Tips to you, you should use meaningful name for variables,
# instead of using x,y,z and it is a bad thing.
horizontal_speed = v * math.cos(ar)
vertical_speed = v * math.sin(ar)
t = d / horizontal_speed # Time to reach structure
vf_vertical = vertical_speed + g*t # Final vertical velocity
dy = (vertical_speed * t) + ((1/2) * g * (t ** 2)) # Vertical position
dx = horizontal_speed * t # Horizontal position
v_co_speed = math.sqrt(vf_vertical * vf_vertical + horizontal_speed * horizontal_speed)
degrees = math.acos(horizontal_speed / v_co_speed) * 180 / math.pi
print('Did the Red Bird hit the structure? Let\'s review the results:\n')
print('Your Red Bird reached the structure in ', t, 's')
print('and was traveling at a velocity of ', v_co_speed, 'm/s')
print(' at an angle of ', degrees, "below the horizontal")
print('The Red Bird was at a height of', dy + h, 'm from the ground')
print('when it reached your intended structure, so your Red Bird', '', 'the structure.')
| true |
8b11e8566191510812c33c50c77a9c4610904130 | ajakaiye33/pythonic_daily_capsules | /apythonicworkout_book/pig_latin.py | 1,814 | 4.21875 | 4 |
def pig_latin():
"""
The program should asks the user to enter an english word. your program should
then print the word, translated into Pig Latin.
If the word begins with a vowel(a,e,i,o,u), then add way to the end of the word e.g
so "air" becomes "airway" eat becomes "eatway"
if the word begin with any other letter, put it on the end of the word and then add "ay"
so python becomes "ythonpay"
"""
your_word = input("type a word > ")
vowel = "aeiou"
if your_word[0] in vowel:
wayword = your_word[1:] + "way"
else:
frst_word = your_word[0]
wayword = your_word[1:] + frst_word + "ay"
return wayword
print(pig_latin())
Bonus
def pig_latin2():
"""
if the word contains two different vowels "way" should added at its end but if
it contain one vowel the first word should placed at it end and subsequently add "ay"
"""
the_vow = "aeiou"
counter = []
ask_word = input("Give us a word > ")
for i in the_vow:
if i in ask_word:
counter.append(i)
if len(counter) == 2:
res = f"{ask_word}way"
else:
res = f"{ask_word[1:]}{ask_word[0]}ay"
return res
print(pig_latin2())
def pig_latin3():
fly = []
vow_the = "aeiou"
the_sentence = input("Lets have your sentence > ")
for word in the_sentence.split():
if word[0] in vow_the:
fly.append(f"{word}way")
else:
fly.append(f"{word[1:]}{word[0]}ay")
return " ".join(fly)
print(pig_latin3())
# Morsels python problem
def unique_only(lst):
return [i for i in set(lst)]
print(unique_only([1, 2, 2, 1, 1, 3, 2, 1]))
# print(unique_only())
nums = [1, -3, 2, 3, -1]
sqr = [i**2for i in nums]
print(unique_only(sqr))
| true |
25223ab1874f7cf1e492040faba073faba3881a4 | ajakaiye33/pythonic_daily_capsules | /make_car_drive.py | 469 | 4.125 | 4 |
class Car(object):
"""
make a car that drive
"""
def __init__(self, electric):
"""
receives a madatory argument: electric
"""
self. electric = electric
def drive(self):
if not self.electric:
return "VROOOOM"
else:
return "WHIRRRRRRRR"
car1 = Car(electric=False)
print(car1.electric)
print(car1.drive())
car2 = Car(electric=True)
print(car2.electric)
print(car2.drive())
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.