blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string | is_english bool |
|---|---|---|---|---|---|---|---|
74f507795fb12a75b0a499f5f302c4252e2ab9f7 | leonguevara/WriteSomething_Python | /main.py | 887 | 4.6875 | 5 | # main.py
# WriteSomething_Python
#
# This program will help you get the size of a phrase given by the user, and let you
# know if that size is an even or odd number.
#
# Python interpreter: 3.6
#
# Author: León Felipe Guevara Chávez
# email: leon.guevara@itesm.mx
# date: May 29, 2017
#
# We ask the user for a phrase and read it
phrase = input("Write something:")
# We get the size of our phrase (the number of characters in our phrase)
phraseSize = len(phrase)
# We identify if the phrase size is an odd or an even number. We do this dividing the size by
# two. If the remainder of such division is 0, then it is an even number; otherwise, it is an
# odd number
if (phraseSize % 2) == 0:
phraseSizeIs = "even"
else:
phraseSizeIs = "odd"
# We display our findings
print("Your phrase's size is " + str(phraseSize) + " characters and that is an " + phraseSizeIs + " number.")
| true |
73dbb32953bc17d70ee927370b1a0a75e0e27e2c | JRRRRRRR/Python | /Comparing(ifelse).py | 324 | 4.4375 | 4 | #Test if a number is even or odd
number = int (input("Enter input: "))
if number % 2 == 0: # == means "is equal to"
print(number, "is even")
else:
print(number, "is odd")
if number > 5:
print("Greater than 5")
elif number < 0:
print("Number is negative")
else:
print("Number is relatively small")
| true |
8aa467a97e853048c5836b2e1bcd8cd0ba93bc95 | somesh202/Assignments-2021 | /Week1/run.py | 804 | 4.15625 | 4 | ## This is the most simplest assignment where in you are asked to solve
## the folowing problems, you may use the internet
'''
Problem - 0
Print the odd values in the given array
'''
arr = [5,99,36,54,88]
import array as arr
a = arr.array('i', [5, 99, 36,54,88])
for i in a:
if i%2 != 0:
print(i, end=" ")
'''
Problem - 1
Print all the prime numbers from 0-100
'''
lower = 0
upper = 100
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
'''
Problem - 2
Print the reverse of a string
'''
string = 'Reverse Me!'
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = 'Reverse Me!'
print("Reversed string is : ", end="")
print(reverse(s))
| true |
ca0ea374d2777b6f48dabc48935d1e3729a203ff | SherriMaya/CIS189 | /validate_input_in_functions.py | 989 | 4.28125 | 4 | """Takes a test_name, test_score, and invalid_message that validates
the test_score, asking the user for a valid test score until it is in the range,
then prints valid input as 'Test name: #"""
def score_input(test_name, test_score=0, invalid_message='Invalid test score, try again!'):
"""Returns
:param test_name: name of the test
:param test_score: optional test score
:param invalid_message: optional invalid message
# return { test_name: test_score}
:returns test_name and test_score in a string
"""
try:
if test_score < 0 or test_score > 100:
return invalid_message
else:
test_name_and_score = (test_name + ": " + str(test_score))
except TypeError as err:
raise TypeError
else:
return test_name_and_score
if __name__ == '__main__':
try:
print(score_input("math", 100))
except TypeError as err:
print("TypeError encountered")
| true |
eb1da2a4d6d9afdef681607b88a2ff5fea07d88e | KeetonMartin/HomemadeProgrammingIntro | /Lesson7.py | 1,890 | 4.3125 | 4 | #Lesson 7 topics
#Problem 1
"""
Write a function taking in a string like "WOW this is REALLY amazing" and returning "Wow this is really amazing". String should be capitalized and properly spaced.
Hint: Try using functions like
"APPLE".lower()
or
ourList = "Multiple words in a string".split()
["Multiple", "words", "in", "a", "string"]
"""
def filter_words(st):
#We know st is a sentence
temp = st.split()
print(temp)
returnable = []
for word in temp:
returnable.append(word.lower())
return returnable
print(filter_words("Big Burritos WAKE UP"))
print("ExAMple".lower())
print("ExAM PLE").split()
#Lesson 8 topics
"""
You need to write a function that reverses the words in a given string. A word can also fit an empty string. If this is not clear enough, here are some examples:
backwards('Hello World') == 'World Hello'
backwards('Hi There.') == 'There. Hi'
As the input may have trailing spaces, you will also need to ignore unneccesary whitespace.
Hint (helpful functions):
https://www.w3schools.com/python/ref_func_reversed.asp
https://www.w3schools.com/python/ref_string_split.asp
"""
def backwards(st):
# Your Code Here
pass
#Problem 3: recursion
"""
Example 1 of Recursion:
Every recursive function has at least one base case.
It also has at least one recursive case.
Lets see an example. Fibonacci numbers.
https://en.wikipedia.org/wiki/Fibonacci_number
"""
def fib(n):
#first base case
if n == 0:
return 0
#second base case
elif n == 1:
return 1
#recursive case
else:
return fib(n-1) + fib(n-2)
for n in range(0, 8):
print(fib(n))
"""
Now time to try recursion yourself:
factorials!
https://en.wikipedia.org/wiki/Factorial
"""
def fac(n):
#First (and only?) base case:
#Recursive case:
pass
#Problem 4 (for next time?):
"""
Recursion with lists
"""
def head(myList):
pass
def tail(myList):
pass | true |
b251b03e61f2ffd2c4af1727b8d399b439ad87c4 | KeetonMartin/HomemadeProgrammingIntro | /Lesson17.py | 2,084 | 4.40625 | 4 | #Lesson 17
#Student Name:
"""
Today's lesson will be mostly work on anticipating the actions of a program.
"""
teams = ["Warriors", "76ers", "Celtics", "Lakers", "Clippers"]
print("Problem 1")
for i in range(0, len(teams)):
print(i)
print(teams[i])
#Group:
"""
0
Warriors
1
76ers
2
Celtics
3 Lakers
4 Clippers
0
1
2
3
4
Warriors
76ers
"""
# -3 Celtics
# -2 Lakers
# -1 Clippers
# 0 Warriors
# 1 76ers
print("\nProblem 2")
for i in range(1, len(teams)+1):
print(i)
print(teams[-i])
"""
Group Guess:
1
Clippers
2
Lakers
3
Celtics
4
76ers
5
Warriors
"""
print("\nProblem 3")
for team in teams:
print(team)
if team == "Warriors" or team == "76ers":
print("That's a home team")
else:
print("We don't root for that team")
"""
Seth Guess:
Warriors
That's a home team
76ers
That's a home team
Celtics
We don't root for that team
Lakers
We don't root for that team
Clippers
We don't root for that team
"""
fourByFour = [
[1,2,3,4],
[5,6,7,8],
[9,10,11,12]
]
fourByFour.append([13,14,15,16])
print("\nProblem 4")
for innerList in fourByFour:
print("A")
for num in innerList:
if num % 3 == 0:
print("B")
print("C")
"""
Group Guess:
A
B
A
B
A
B
B
A
B
C
"""
#Keeton creates problem 4.5:
for i in range(5, 9):
for j in range(-3, 8):
print(i + j)
"""
Solution:
2
3
4
"""
#Seth creates problem 5:
#Andrew creates problem 6:
#Ryan creates problem 7:
print("\nProblem 8")
# def recur(num):
# if num <= 0:
# print("A")
# else:
# print("B")
# return recur(num-1)
# recur(5)
# recur(-2)
# recur(0)
# recur(1)
#A helper function:
def printGrid(grid):
for innerList in grid:
print(innerList)
#Homework Problem
print("\nHomework Problem")
def modifyArray(grid):
pass
#Test 1:
threeByThree = [[1,2,3],[4,5,6],[7,8,9]]
printGrid(threeByThree)
print(modifyArray(threeByThree))
#Should give us: [[1,2,3],[2,1,6],[2,2,1]]
print("above should match this:")
printGrid([[1,2,3],[2,1,6],[2,2,1]])
#Test 2:
#Test 3:
print("\nHint Homework")
#Hint for problem 1:
threeByThree[1][1] = 100
printGrid(threeByThree) | true |
ea064efef05364414aa5b1665e42bb362d7a2182 | stroudgr/UofT | /CSC148/exercises/ex3/linked_list_test.py | 2,302 | 4.15625 | 4 | # Exercise 3 - More Linked List Practice
#
# CSC148 Fall 2015, University of Toronto
# Instructor: David Liu
# ---------------------------------------------
"""Exercise 3, Task 1 TESTS.
Warning: This is an extremely incomplete set of tests!
Add your own to practice writing tests,
and to be confident your code is correct!
"""
import unittest
from linked_list_ex import LinkedList
class TestLinkedListEq(unittest.TestCase):
def test_simple(self):
list1 = LinkedList([1])
list2 = LinkedList([1])
# The following two tests do the same thing
self.assertTrue(list1 == list2)
self.assertTrue(list1.__eq__(list2))
def test_same_length(self):
list1 = LinkedList([2, 5, 10, -5, 4])
list2 = LinkedList([2, 5, 10, -5, 10])
self.assertFalse(list1 == list2)
def test_one_empty(self):
list1 = LinkedList([3])
list2 = LinkedList([])
self.assertFalse(list1 == list2)
self.assertFalse(list2 == list1)
def test_same(self):
list1 = LinkedList([1,2,3,4,5])
list2 = LinkedList([1,2,3,4,5])
self.assertEqual(list1, list2)
def test_diff(self):
list1 = LinkedList([1,2,3,4,5])
list2 = LinkedList([-1,2,3,4,5])
self.assertNotEqual(list1, list2)
class TestLinkedListDeleteAll(unittest.TestCase):
# NOTE: the tests will use the '__str__' method, so don't change the
# implementation we've given you!
def test_simple(self):
lst = LinkedList([1, 2, 3])
lst.delete_all(2)
self.assertEqual(str(lst), '[1 -> 3]')
def test_no_deletions(self):
lst = LinkedList([1, 2, 3])
lst.delete_all(4)
self.assertEqual(str(lst), '[1 -> 2 -> 3]')
def test_doctest(self):
lst = LinkedList([1, 1, 2, 1, 3, 1, 1, 1])
lst.delete_all(1)
self.assertEqual(str(lst), '[2 -> 3]')
def test_all_deleted(self):
lst = LinkedList([1,1,1,1,1,1,1,1])
lst.delete_all(1)
self.assertEqual(str(lst), '[]')
def test_complex(self):
lst = LinkedList([1, 1, 2, 1, 1, 1, 1, 3, 1, 2, 4, 1, 3, 1, 2, 1, 1, 1])
lst.delete_all(1)
self.assertEqual(str(lst), '[2 -> 3 -> 2 -> 4 -> 3 -> 2]')
if __name__ == '__main__':
unittest.main(exit=False)
| true |
310abd3e7b24f02ec4bd5132e482038a1d30184a | yoliskdeveloper/zero_to_hero_bootcamp_udemy | /projects/project3_compilation/hutang_pinjaman.py | 817 | 4.125 | 4 | """
kalkulasi pembayaran bulanan dari nilai tetap dari cicilan rumah
berdasarkan bunga yang diberikan, dan butuh berapa lama cicilan rumah itu selesai
"""
print('CALCULATOR CICILAN RUMAH')
print('Masukkan jangka waktu cicilan rumah (dalam bulan, jika 3 tahun = 36 bulan)')
bulan = int(input(">>> "))
print('Masukkan bunga cicilan perbulan (nilai desimal bukan persentase)')
rate = float(input(">>> "))
print('Masukkan nilai cicilan per bulan')
pinjaman = float(input(">>> "))
# calculasi
rate_per_bulan = pinjaman / 100 / 12
pembayaran = round((rate_per_bulan / (1 - (1 + rate_per_bulan) ** (-bulan))) * pinjaman)
print(f'pembayaran bulanan: {pinjaman:1.0f} /bulan')
print(f'selama: {bulan / 12:1.0f} tahun')
print(f'dengan bunga pinjaman {rate:1.0f} %')
print(f'maka nilai rumahnya adalah: {pembayaran:1.0f}')
| false |
e5409030792e51ee91c431312410622389ba1544 | matthewmjm/100-days-of-code-days-1-through-10 | /day3/leap.py | 355 | 4.125 | 4 | year = int(input("Input a year: "))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f"So the year {year} is a leap year")
else:
print(f"So the year {year} is a not leap year")
else:
print(f"So the year {year} is a leap year")
else:
print(f"So the year {year} is a not leap year") | false |
5fcd0cdd756b4b4e8ee9349a04ec7dfd52efeefd | PratikAmatya/8-bit-adder-Python-Program | /Program Files/NumberValidation.py | 1,028 | 4.40625 | 4 | # function which returns the correct number entered by the user
def validate(numberPosition):
correctNumberEntered=False
while correctNumberEntered == False:
# Exception Handling using try except block
try:
if numberPosition==1:
# Converting the entered number to Int datatype
number=int(input("\nEnter the first number in decimal number system: "))
else:
number=int(input("\nEnter the second number in decimal number system: "))
# Returning the number if it is in range
if number >=0 and number <256:
return number
break
# Notifying the user that the number they entered was negative
elif number<0:
print("Please enter positive numbers only. Please try again:")
continue
# Notifying the user that the number they entered exceeds the range
elif number>255:
print("Please enter numbers between 0 and 255 only. Please try again:")
continue
except:
# Printing error message if exception occurs
print("Please enter whole numbers only. Please try again:")
| true |
e9649e34baab504cc78572e00e821d4595ae7478 | davidrey87/Learn-x-in-y-minutes-Python | /Variables_Colecciones.py | 2,500 | 4.25 | 4 | # Print
print "Yo soy Python, gusto en conocerte."
# Obtener Datos
dato = int(raw_input("Pon algun dato: "))
dato2 = int(input("Pon algun dato: "))
print(dato+dato2)
#Variable
var = 5
print(var)
#Expresiones
print("yahoo!" if 3 > 2 else 2)
# Lista
li = []
# Lista inicializada con datos
other_li = [4, 5, 6]
print(other_li)
# Agregando lista a posicion
li.append(1)
li.append(2)
li.append(4)
li.append(3)
print(li)
# Quitando el ultimo elemento de la pila
li.pop()
print(li)
# Poniendolo de regreso
li.append(3)
print(li)
#Accesando a la posicion de una lista
print(li[0])
#Asignando valor a la posicion de una lista
li[0] = 42
print(li[0])
#Accediendo al ultimo elemento
print(li[-1])
#Accediendo por rangos
print(li[1:3])
print(li[2:])
print(li[:3])
print(li[::2])
print(li[::-1])
del li[2]
print(li)
print(li + other_li)
print(li.extend(other_li))
print(li.remove(2))
print(li.insert(1, 2))
print(li.index(2))
print(1 in li)
print(len(li))
# Las tuplas son como las listas pero inmutables
tup = (1, 2, 3)
print(tup[0])
print(len(tup))
print(tup + (4, 5, 6))
print(tup[:2])
print(2 in tup)
# Desempacar tuplas en variables
a, b, c = (1, 2, 3)
d, e, f = 4, 5, 6
#Las tuplas son creadas por defecto
g = 4, 5, 6
#Intercambiando valores
e, d = d, e
#Un diccionario prellenado
filled_dict = {"uno": 1, "dos": 2, "tres": 3}
print(filled_dict["uno"])
#Obteniendo las llaves
print(filled_dict.keys())
#Obteneindo los valores
print(filled_dict.values())
#Obteniendo los el elemento
print(filled_dict.items())
#Revisando si existe una llave
print("one" in filled_dict)
print(1 in filled_dict)
#Usando get para evitar errores
print(filled_dict.get("uno"))
print(filled_dict.get("cuatro"))
#Valor por defecto cuando es necesario
print(filled_dict.get("one", 4))
print(filled_dict.get("four", 4))
# Inicializar set con un manojo de valores
some_set = set([1, 2, 2, 3, 4])
print(some_set)
# No se garantoza el prden
another_set = set([4, 3, 2, 2, 1])
print(another_set)
# En python 2.7
filled_set = {1, 2, 2, 3, 4}
print(filled_set)
# Agregando mas items
filled_set.add(5)
print(filled_set)
#Haciendo intersecciones
other_set = {3, 4, 5, 6}
print(filled_set & other_set)
#Union
print(filled_set | other_set)
#Diferencia
print({1, 2, 3, 4} - {2, 3, 5})
# Diferencia simetrica
print({1, 2, 3, 4} ^ {2, 3, 5})
# Revisa si el conjunto de la izquierda es un super conjunto de la derecha
print({1, 2} >= {1, 2, 3})
# Revisa si existen en el conjunto
print(2 in filled_set)
print(10 in filled_set) | false |
568ece6291cd4be09f1fb0fbeb8eee9805ee8761 | louloz/Python-Crash-Course | /Ch3-4List/for_loop_list_2.py | 622 | 4.8125 | 5 | # Python Crash Course, Eric Matthes, no starch press
# Textbook Exercises
# Louis Lozano
# 3-1-2019
# for_loop_list_2.py
# List comprehension used to create a list of odd numbers between 1 and 20
odd_numbers = [odd for odd in range(1, 20, 2)]
for num in odd_numbers:
print(num)
# List comprehension used to create a list of multiples of 3 from 3 to 30.
multiples_of_three = [num*3 for num in range(3, 30)]
for three in multiples_of_three:
print(three)
# List comprehension used to create a list of cubes from 1 to 10.
cubes = [num**3 for num in range(1, 11)]
for cube in cubes:
print(cube)
| true |
6debbb8e40919aca9555ffb135ad494cb7ffcd92 | louloz/Python-Crash-Course | /Ch7_User_Input_and_while_Loops/7-2_restaurant_seating.py | 477 | 4.34375 | 4 | # Python Crash Course, Eric Matthes, no starch press
# Ch7 User Input and while Loops
# Textbook Exercises
# Louis Lozano
# 3-8-2019
# 7-2_restaurant_seating.py
group_num = input("How many people are in your dinner group?")
# Converts user input(string value) into an int data type.
# Lets you use user input for numerical comparisons.
group_num = int(group_num)
if group_num > 8:
print("You'll have to wait for a table.")
else:
print("Your table is ready.")
| true |
bdb446c4ab9e7a52ecd08478eadcc26894bf90c8 | louloz/Python-Crash-Course | /Ch5IfStatements/5-11_ordinal_numbers.py | 524 | 4.34375 | 4 | # Python Crash Course, Eric Matthes, no starch press
# Ch5 if statements
# Textbook Exercises
# Louis Lozano
# 3-5-2019
# 5-11_ordinal_numbers.py
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# A for loop that uses conditional statements to handle certain
# items in a list differently.
for number in numbers:
if number == 1:
print(str(number) + 'st')
elif number == 2:
print(str(number) + 'nd')
elif number == 3:
print(str(number) + 'rd')
else:
print(str(number) + 'th')
| false |
b290a9c28c4a25564238191f84e3737ceccfff5a | louloz/Python-Crash-Course | /Ch11_Testing_Your_Code/Employee.py | 876 | 4.28125 | 4 | # Python Crash Course, Eric Matthes, no starch press
# Ch11 Files and Exceptions
# Textbook Exercises
# Louis Lozano
# 07-08-2019
# Try It Yourself: 11-3 'Employee.py'
# Python Version: 3.5.3
# Description: Creates an Employee class that takes a first name, last name,
# and salary. Has a function to give raises.
class Employee():
'''Models an employee.'''
def __init__(self, first_name, last_name, salary):
'''Initializes attribute.'''
self.first_name = first_name
self.last_name = last_name
self.salary = salary
def give_raise(self, amount=5000):
'''Adds money to an employees salary.'''
self.salary = self.salary + amount
hire = Employee('Louie', 'Lozano', 50000)
'''
print(hire.salary)
hire.give_raise()
print(hire.salary)
hire.give_raise(100700)
print(hire.salary)
'''
| true |
84fb398b4a5f7318ae4e5684e0ab2ddf30d5ccfb | barawalojas/Hacktoberfest2020-1 | /Floyd_Warshall.py | 1,527 | 4.28125 | 4 | """
Floyd Warshall Algorithm finds All-pair shortest path for an weighted directed graph.
It uses idea that distance to any points(v) must be greater sum of connecting edge
weight(u,v) and preceding distance to the point(u).
"""
V = 4
INT_MAX = 9999
def floydWarshall(graph):
dist = [row[:] for row in graph]
for src in range(V):
# Take each vertex as source of path
for dest in range(V):
# Take each vertex as destination of path
for iterator in range(V):
"""
Optimising each vertex between src and dest
If vertex k is on the shortest path from
i to j, then update the value of dist[i][j]
"""
dist[dest][iterator] = min(
dist[dest][iterator], dist[dest][src] + dist[src][iterator]
)
printSolution(dist)
# A utility function to print the solution
def printSolution(dist):
print(
"Following matrix shows the shortest distances between every pair of vertices:"
)
for row in range(V):
for col in range(V):
if dist[row][col] >= INT_MAX:
print("%5s" % ("INF"), end=" ")
else:
print("%5d" % (dist[row][col]), end=" ")
print("\n")
# Driver graph to check function
graph = [
[0, 5, INT_MAX, 10],
[INT_MAX, 0, 3, INT_MAX],
[INT_MAX, INT_MAX, 0, 1],
[INT_MAX, INT_MAX, INT_MAX, 0],
]
# Find and print the solution
floydWarshall(graph)
| true |
40336426062da448ddb8260af6ea39f82a1218ab | Tarini-Tyagi/TryPython | /Task3.py | 490 | 4.125 | 4 | from datetime import datetime
name=input("Enter your name: ")
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
hrs=int(now.strftime("%H"))
min=int(now.strftime("%M"))
if hrs>4 and hrs<12:
print("Good Morning "+name)
elif hrs==12:
print("Good Afternoon " + name)
elif hrs>12 and hrs<15:
print("Good Afternoon " + name)
elif hrs>15 and hrs<22:
print("Good Evening " + name)
else:
print("You should sleep. It's "+current_time)
print("Have a good night")
| true |
3c93333318257673bfcad316d2ca573a8e5750e5 | runaphasia335/Traveling-Salesman-WGUPS | /Algorithm.py | 2,320 | 4.34375 | 4 | # Carlos Perez
# Student ID: 000819792
import heapq
# Algorithm to determine the shortest path.
# function takes the graph and the starting node. Sets the starting node to 0 distance, and predecessor to none. Since each node
# has a minimum distance of MAX. 0 distance for the starting will determine each edge weight to its adjacent nodes.
# 0(N^2)
class Algorithm(object):
def __init__(self,graph, start_node):
start_node.min_distance = 0
start_node.predecessor = None
unvisited = [i for i in graph.adjacency_list]
# uses heapify to set the lowest as priority
heapq.heapify(unvisited)
# Function will continue to run until empty
while len(unvisited):
# Pops the smallest node and makes it the current node
current = heapq.heappop(unvisited)
current.visited = True
# Searches through the current nodes adjacency list, making 'target' the adjacent node
for target in graph.adjacency_list[current]:
# while the adjacent node is has not been visited
if target.visited == True:
continue
weight = graph.get_weight(current, target)
# create edge weight with an adjacent node
new_distance = current.min_distance + float(weight)
# if new_distance is less than the adjacent node minimum distance, it assigns new_distance weight
# to the adjance node's minimum_distance. Then sets the current node as predecessor.
if new_distance < target.min_distance:
target.min_distance = new_distance
target.predecessor = current
# Pops each node fro, unvisited_list
while len(unvisited):
heapq.heappop(unvisited)
# recreates unvisited_list while leaving out nodes marked as visited.
unvisited = [i for i in graph.adjacency_list if i.visited == False]
heapq.heapify(unvisited)
# function to find the shortest path to a node. Returns the target node with an assigned distance.
def shortest_path(self, target_node):
node = target_node
while node is not None:
node = node.predecessor
return target_node
| true |
fe2b52ff655e939074dd5c02831ebc62fa4ad309 | CrzRabbit/Python | /leetcode/0461_E_汉明距离.py | 715 | 4.15625 | 4 | '''
两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。
给出两个整数 x 和 y,计算它们之间的汉明距离。
注意:
0 ≤ x, y < 231.
示例:
输入: x = 1, y = 4
输出: 2
解释:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
上面的箭头指出了对应二进制位不同的位置。
'''
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
i = 1
count = 0
IMAX = 2 ** 31
while i <= IMAX and (i <= x or i <= y):
if x & i != y & i:
count += 1
i = i << 1
return count
so = Solution()
print(so.hammingDistance(0, 4)) | false |
76d5e82c7bac3d270856142c7a48490ec0e4fe41 | niosus/EasyClangComplete | /plugin/utils/unique_list.py | 1,351 | 4.28125 | 4 | """Encapsulates set augmented list with unique stored values."""
class UniqueList:
"""A list that guarantees unique insertion."""
def __init__(self, other=None):
"""Init with another iterable if it is present."""
self.__values = list()
self.__values_set = set()
if not other:
return
for value in other:
self.append(value)
def append(self, value):
"""Append a single value.
Args:
value: input value
"""
if value not in self.__values_set:
self.__values.append(value)
self.__values_set.add(value)
def as_list(self):
"""Return an ordinary python list."""
return self.__values
def clear(self):
"""Clear the list."""
self.__values = list()
self.__values_set = set()
def __add__(self, other):
"""Append another iterable.
Args:
other (iterable): some other iterable container
Returns:
UniqueList: new list with appended elements
"""
for value in other:
self.append(value)
return self
def __iter__(self):
"""Make iterable."""
return iter(self.__values)
def __str__(self):
"""Make convertable to str."""
return str(self.__values)
| true |
b45fc04bccee35570f32935d6f8425a3974ae0d5 | caoxudong/code_practice | /projecteuler/Problem4.py | 758 | 4.15625 | 4 | """
A palindromic number reads the same both ways.
The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99.
Find the largest palindrome made from the product of two 3-digit numbers.
"""
import sys
def isPalindrome(number) :
palindromeString = str(number)
palindromeStringlength = len(palindromeString)
flag = True
for i in range(palindromeStringlength / 2):
if palindromeString[i] != palindromeString[palindromeStringlength - i - 1]:
flag = False
break
return flag
maxNum=0
for i in range(500, 999):
for j in range(500, 999):
result = i * j
if isPalindrome(result):
if maxNum < result:
maxNum = result
print(maxNum)
| true |
4fa58eab70f8308c2808ba39f8cd351416c0be7d | elisainz/UADE-Best-of-Python | /Sainz_EjContraseña While True.py | 2,283 | 4.28125 | 4 | '''Ejercicio:
Contraseñas! En general las contraseñas a crear deben cumplir reglas por seguridad para que sean válidas.
Desarrolle un programa que ingrese contraseñas hasta ingresar una contraseña vacía.
A medida que se ingresan verifique e informe si cumple con las reglas:
No puede comenzar con número.
Debe contener al menos dos números, una letra mayuscula y una longitud de 8 caracteres mínimo.
Resolver utilizando exclusivamente manejo de excepciones y estructura While-True,
creando una nueva excepción o utilizando una existente (ValueError) cuando no cumpla alguno de las dos reglas,
mostrar mensaje aclaratorio correspondiente en cada caso.'''
class ComienzaConNumeroError(Exception):
pass
class NoCumpleRequisitosError(Exception):
pass
def ingresarContraseña():
contraseña = input("Ingrese una contraseña: ")
return contraseña
def verificarContraseña():
contraseña = ingresarContraseña()
while True:
if contraseña == "":
break
elif contraseña != "":
try:
cont_numeros = 0
cont_mayusculas = 0
if contraseña[0].isdigit(): #verificar si el primer caracter es un numero
raise ComienzaConNumeroError
if len(contraseña) < 8: #verificar si la longitud es menor a 8
raise NoCumpleRequisitosError
for caracter in contraseña:
if caracter.isdigit():
cont_numeros = cont_numeros + 1 #contar la cantidad de numeros en la contraseña
if caracter.isupper():
cont_mayusculas = cont_mayusculas + 1 #contar la cantidad de mayusculas en la contraseña
if cont_numeros < 2 or cont_mayusculas <= 0:
raise NoCumpleRequisitosError
else:
print("La contraseña es válida!")
except ComienzaConNumeroError:
print("No puede comenzar con número")
except NoCumpleRequisitosError:
print("No cumple con los requisitos de seguridad")
contraseña = input("Ingrese otra contraseña: ")
verificarContraseña()
| false |
d05173c139756b13c785c17485651f2cc2904e32 | udaykumarbhanu/iq-prep | /ibts364/integer-to-roman.py | 855 | 4.125 | 4 | '''Given an integer, convert it to a roman numeral, and return a string corresponding to its roman numeral version
Input is guaranteed to be within the range from 1 to 3999.
Example :
Input : 5
Return : "V"
Input : 14
Return : "XIV"
'''
class Solution:
# @param A : integer
# @return a strings
def intToRoman(self, A):
numeral_dict = {1: "I", 4: "IV", 5: "V", 9: "IX", 10: "X", 40: "XL",
50: "L", 90: "XC", 100: "C", 400: "CD", 500: "D", 900: "CM",
1000: "M"}
result = []
key_set = sorted(numeral_dict.keys())
while A>0:
for key in reversed(key_set):
while A/key > 0:
A -= key
result += numeral_dict[key]
return "".join(result)
if __name__ == '__main__':
A = 14
print Solution().intToRoman(A)
| true |
b4e348abaf559bbf9cccbfb47397ced7c0c9296f | evansmusomi/python3-101 | /design-patterns/abstract_factory.py | 1,097 | 4.65625 | 5 | """ Abstract factory example"""
class Dog:
""" One of the objects """
def speak(self):
""" Implements dog's speech """
return "Woof!"
def __str__(self):
return "Dog"
class DogFactory:
""" Concrete factory """
def get_pet(self):
"""returns a dog object"""
return Dog()
def get_food(self):
"""returns a dog food object"""
return "Dog food!"
class PetStore:
""" Houses abstract factory """
def __init__(self, pet_factory=None):
""" pet_factory is our abstract factory """
self._pet_factory = pet_factory
def show_pet(self):
"""shows a pet's info"""
pet = self._pet_factory.get_pet()
pet_food = self._pet_factory.get_food()
print("Our pet is {}".format(pet))
print("Our pet says hello by {}".format(pet.speak()))
print("It eats {}".format(pet_food))
# Create concrete factory
FACTORY = DogFactory()
# Create pet store to house our abstract factory
SHOP = PetStore(FACTORY)
# Invoke utility method to show pet details
SHOP.show_pet()
| true |
bdef61984eace5ddecb594e7ee1feacffd329f1d | hrokr/pyknowledge | /short_progs/04.py | 533 | 4.15625 | 4 | #write a program that will print the song "99 bottles of beer on the wall".
#for extra credit, do not allow the program to print each loop on a new line.
# remove the # in the line above the decriment for extra credit.
def bottles_of_beer(bottles):
while bottles > 0:
print (bottles, "bottles of beer on the wall.", bottles, "Bottles of beer!\n"
"Take one down, pass it around ...", bottles -1, "bottles of beer on \n"
"the wall." #, sep = ' ' )
bottles -= 1
print(bottles_of_beer(2))
| true |
e931ded5802c2206b832bb03f45348b7bd8631a3 | akashmg/Python | /google-python-exercises/MyCode/hello.py~ | 312 | 4.1875 | 4 | #!/user/bin/python
# Using sys
"""
A program that takes an argument from the terminal and prints it
"""
import sys
def main():
if len(sys.argv) >= 2:
name = sys.argv[1]
print "Hello" + name + "\nBuenos Dias!\n"
else:
print "Program is empty!"
if __name__ == '__main__':
main()
| true |
a2088d6c6f790c94d09366c961495a9174d76ac5 | D0rianGrey/PythonAutomation | /practice/letpy.py | 560 | 4.125 | 4 | # default = input()
# default_with_out_space = default.replace(" ", "").lower()
# reverse = default_with_out_space[::-1].lower()
# if default_with_out_space == reverse:
# print("Да")
# else:
# print("Нет")
# print(default_with_out_space)
# print(reverse)
# a = input()
#
# if len(a) >= 8 and a.isdigit():
# final = a.replace(a[0:-4], "*")
# size = len(a) - 5
# print("*" * size + final)
# else:
# print("Ошибка")
a = input()
if "#" in a:
print(a[:a.find("#")])
else:
print("There isn't '#'")
print(a)
| false |
865d8459ec0eaf6292e8aa0193bfc53e8950b447 | Jeffmanjones/python-for-everybody | /13_Extract_Data_from_JSON.py | 1,567 | 4.40625 | 4 | """
Extracting Data from JSON
In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/json2.py. The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file and enter the sum below:
We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual data you need to process for the assignment.
Sample data: http://py4e-data.dr-chuck.net/comments_42.json (Sum=2553)
Actual data: http://py4e-data.dr-chuck.net/comments_57128.json (Sum ends with 10)
You do not need to save these files to your folder since your program will read the data directly from the URL. Note: Each student will have a distinct data url for the assignment - so only use your own data url for analysis.
The closest sample code that shows how to parse JSON and extract a list is json2.py. You might also want to look at geoxml.py to see how to prompt for a URL and retrieve data from a URL.
"""
import urllib.request, json
address = input('Enter location: ')
print('Retrieving', address)
with urllib.request.urlopen(address) as url:
raw = json.loads(url.read().decode())
print('Retrieved', len(str(raw)), 'characters')
data = raw.get("comments")
#print(data)
num = total = 0
for i in range(len(data)):
tmp = data[i]
value = tmp.get("count")
num = num + 1
total = total + int(value)
print("Count:",num)
print("Sum:",total) | true |
ff5da270e46f7f9a86b121d94837f2da97c133ad | xpxu/learnPython | /decorator/multiple_closing.py | 879 | 4.28125 | 4 | '''
Q: what is a decorator?
A: input for a decrator is a function and it will return a new function
'''
def log1(func):
def wrapper(*args, **kwargs):
print 'start'
func(*args, **kwargs)
print 'end'
return wrapper
def log2(message):
# print message
def decorator(func):
def wrapper(*args, **kwargs):
print 'start'
func(*args, ** kwargs)
print 'end'
return wrapper
return decorator
def log(input):
if isinstance(input, str):
# return a decorator
return log2(input)
elif hasattr(input, '__call__'):
# return a function
return log1(input)
else:
raise Exception
# f1 = log(f1)
@log
def f1():
print '1' * 20
# f2 = log('hello')(f2)
# log('hello') will return a decorator.
@log('hello')
def f2():
print '2' * 20
f1()
f2() | true |
30590dc07df4e04943e8239cb01854279ab0b97c | prajaktanarkhede97/Python-Assignments | /Program-3.py | 344 | 4.125 | 4 | #Write a program which contains one function named as Add() which accepts two numbers from user and return addition of that two numbers.
def add(num1,num2):
ans=(num1 + num2)
return ans
value1=(int(input("Enter value of num1")))
value2=(int(input("Enter value of num2")))
ret= add(value1,value2)
print("Sum of numbers is" )
print(ret)
| true |
82bdbb489d3b5d882be807bebdc7a2496667f38f | Pandeyjidev/All_hail_python | /DSA_MadeEasy/queues/queue_list.py | 856 | 4.125 | 4 | class Queue(object):
def __init__(self):
self.queue = []
def enqueue(self,data):
self.queue.insert(0,data)
def dequeue(self):
return self.queue.pop()
def isEmpty(self):
return not bool(self.queue)
def size(self):
return len(self.queue)
def peek(self):
return self.queue[-1]
def __repr__(self):
return '{}'.format(self.queue)
if __name__ == '__main__':
queue = Queue()
print("Is the queue empty? ", queue.isEmpty())
print("Adding 0 to 10 in the queue...")
for i in range(10):
queue.enqueue(i)
print("Queue size: ", queue.size())
print("Queue peek : ", queue.peek())
print("Dequeue...", queue.dequeue())
print("Queue peek: ", queue.peek())
print("Is the queue empty? ", queue.isEmpty())
print(queue)
| false |
9e6649455475a2943d2b12a22fea1d73e68b4306 | Sylk/mit-programming-in-python | /ch-02/finger-exercise-one.py | 651 | 4.4375 | 4 | # Finger exercise: Write a program that examines three variables—x, y, and z—and prints the largest
# odd number among them. If none of them are odd, it should print a message to that effect.
from random import randint
x, y, z = randint(0, 1000), randint(0, 1000), randint(0, 1000)
print("X => " + str(x), "\nY => " + str(y), "\nZ => " + str(z))
# Determine odd values and add them to oddValues
oddValues = []
if x % 2 != 0:
oddValues.append(x)
if y % 2 != 0:
oddValues.append(y)
if z % 2 != 0:
oddValues.append(z)
if len(oddValues):
print("\nLargest Odd Number => " + str(max(oddValues)))
else:
print("\nNo odd values") | true |
c5eced1f1879b6c91ebb1c8829c6ca87927b91f6 | Tanish74/Code-and-Compile | /meeting late comers.py | 945 | 4.15625 | 4 | """
A certain number of people attended a meeting which was to begin at 10:00 am on a given day. The arrival time in HH:MM
format of those who attended the meeting is passed as the input in a single line, with each arrival time by a space. The
program must print the count of people who came late (after 10:00 am) to the meeting.
Input Format:
The first line contains the arrival time separated by a space.
Output Format:
The first line contains the count of late comers.
Boundary Conditions:
The length of the input string is between 4 to 10000.
The time HH:MM will be in 24 hour format (HH is hours and MM is minutes).
Example Input/Output 1:
Input:
10:00 9:55 10:02 9:45 11:00
Output:
2
Explanation:
The 2 people were those who came at 10:02 and 11:00
"""
string=input()
c=0
l=list(string.strip().split())
for i in range(len(l)):
x,y=l[i].split(":")
h,m=int(x),int(y)
if((h==10 and m>0)or h>10):
c+=1
print(c)
| true |
308efdd9e0a784de279ef0694f3121f5bae975f6 | Tanish74/Code-and-Compile | /odd length string-middle three letters.py | 460 | 4.375 | 4 | """An odd length string S is passed as the input. The middle three letters of S must be printed as the output.
Input Format:
First line will contain the string value S
Output Format:
First line will contain the middle three letters of S.
Boundary Conditions:
Length of S is from 5 to 100
Example Input/Output 1:
Input:
level
Output:
eve
Example Input/Output 2:
Input:
manager
Output:
nag"""
string=input()
le=len(string)
m=le//2
print(string[m-1:m+2])
| true |
90214a01620e9429c69d946047cb083b3656cc61 | Tanish74/Code-and-Compile | /lowest mileage car.py | 800 | 4.25 | 4 | """
The name and mileage of certain cars is passed as the input. The format is CARNAME@MILEAGE and the input is as a single line, with each car information separated by a space. The program must print the car with the lowest mileage. (Assume no two cars will have the lowest mileage)
Input Format:
The first line contains the CARNAME@MILEAGE separated by a space.
Output Format:
The first line contains the name of the car with the lowest mileage.
Boundary Conditions:
The length of the input string is between 4 to 10000.
The length of the car name is from 1 to 50.
Example Input/Output 1:
Input:
Zantro@16.15 Zity@12.5 Gamry@9.8
Output:
Gamry
"""
string=input()
l=string.split()
c=100
for i in range(len(l)):
x,y=l[i].split('@')
y=float(y)
if(y<c):
c=y
car=x
print(car)
| true |
6bc2aca3ca41f654396106ac5c44b44784ed6a22 | eruiztech/Python | /Lab 2/bmi.py | 858 | 4.3125 | 4 | #Edgar Ruiz
#CS 299
#Lab 2
#September 29th, 2016
#!/usr/bin/python
print("Lab 2")
print("Calculate your BMI")
unitChoice = input("Would you like to use (1) kilograms/meters or (2) pounds/inches as units?\nPlease enter 1 or 2\n")
if unitChoice == 1:
weight = float(input("Weight in kilograms: "))
height = float(input("Height in meters: "))
bmi = float(weight/(height*height))
elif unitChoice == 2:
weight = float(input("Weight in pounds: "))
height = float(input("Height in inches: "))
bmi = float((weight/(height*height)) * 703)
else:
print("invalid choice")
exit()
print("Your BMI is: %d" % int(bmi))
if int(bmi) <= 24:
print("you have a normal BMI")
elif int(bmi) >= 25 and int(bmi) <= 29:
print("you are considered overweight")
elif int(bmi) >= 30 and int(bmi) <= 39:
print("you are considered obese")
else:
print("you are extremely obese")
| false |
3ad41e815a9a8f97c338c1f16ccfaf1438ce3c21 | akshya-j31/python_bootcamp | /assignment4.py | 945 | 4.21875 | 4 | import os
import os.path
from os import path
def main():
FileName = input("Please enter the file name: ")
if path.exists(FileName):
print("file exists")
UserInput = input("***Please enter your choice***\na. Read the file\nb. Delete the file and start over\nc. Append the file\n\n")
if UserInput == 'a':
f = open(FileName,"r")
print(f.read())
elif UserInput == 'b':
os.remove(FileName)
f = open(FileName,"w+")
f.write("")
elif UserInput == 'c':
FileTxtAppend = input("Please enter the text to append:\n")
f = open(FileName,"a")
f.write(FileTxtAppend)
else:
print("Wrong choice")
else:
FileTxt = input("File does not exist. Please enter the text which you want to write:\n")
f = open(FileName,"w+")
f.write(FileTxt)
if __name__== "__main__" :
main() | true |
0cf145c5a1915b268513880e66c448c1cd2f7a41 | OkoroKelvin/parsel_tongue_mastered | /kelvin_okoro/chapter_seven/question_43.py | 388 | 4.28125 | 4 | # Write a function that takes a string as an argument, converts the string to a list of
# characters, sorts the list, converts the list back to a string, and returns the resulting string.
def conversion(strings, ):
my_list = []
my_list += strings
my_list.sort()
my_new_string = ""
return my_new_string.join(my_list)
my_love = "Lordship"
print(conversion(my_love))
| true |
12682c6d5d48916663860ba24972ae1ad91d0035 | erikagreen7777/HackerRankPython | /capitalize.py | 1,127 | 4.375 | 4 | Capitalize!
You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck.
Given a full name, your task is to capitalize the name appropriately.
Input Format
A single line of input containing the full name, .
Constraints
The string consists of alphanumeric characters and spaces.
Note: in a word only the first character is capitalized. Example 12abc when capitalized remains 12abc.
Output Format
Print the capitalized string, .
Sample Input
chris alan
Sample Output
Chris Alan
##########################################################################
def capitalize(string):
newstr = string.split()
for i in range(0, len(newstr)):
for j in range(0, len(newstr[i])):
if (newstr[i][0].isdigit()):
# print ("it's a number! %s" % newstr[i])
continue
else:
newstr[i] = newstr[i].capitalize()
# print ("newstr[i]: %s\n" % newstr[i])
continue
print (newstr)
return ' '.join(newstr)
| true |
9bf22058173040b971477e36a5eff206b01d0450 | calebajayi/Python_Codes | /OOSD_revision.py | 2,537 | 4.21875 | 4 | # # Exercise 1: Write a Python program that reads a text file and
# # prints a list of unique words in the text.
#
# filename = "input1.txt"
# unique_words = []
# try:
# fp = open(filename, "r")
# lines = fp.readlines()
# for line in lines:
# line = line.strip()
# words = line.split()
# for word in words:
# if word not in unique_words:
# unique_words.append(word)
# print(unique_words)
# fp.close()
# except IOError:
# print("File doesn’t exist")
#
# Exercise 2: Write a Python program that reads a text file
# and prints the longest word in the text.
# def longest_word(filename):
# longest_word = ""
# try:
# fp = open(filename, "r")
# lines = fp.readlines()
# fp.close()
#
# for line in lines:
# line = line.strip()
# words = line.split()
# for word in words:
# word = word.strip(".,!?")
# if len(word) > len(longest_word):
# longest_word = word
# #print("current longest word", longest_word)
# return longest_word
#
# except ValueError:
# print("File doesn’t exist")
# return None
#
# #main
#
# filename = "input1.txt"
# l_w = longest_word(filename)
# print(l_w)
#
# Exercise 3: Given a text file containing student data – each line represents one student -
# course student is enrolled in, student number and student name, separated by a comma,
# write a Python function that will list all students enrolled in a specific module.
# ---
# DT265A,John Smith,c12345
# DT265C,Mary Keane,c12356
# DT265A,Peter Boyd,c14523
# ---
# #Exercise 4: Write a Python function that takes two lists and
# # returns true if they have at least one element in common.
#
# def contains(l1, l2):
# for el in l1:
# if el in l2:
# return True
#
# return False
#
# def elements_in_common(l1, l2):
# for el in l1:
# if el in l2:
# print(el)
#
# #main
# l1 = [1,2,3,4]
# l2 = [3,5,6,7,4]
# elements_in_common(l1, l2)
# Exercise 5: Write a python program to check whether two lists are circularly identical.
# For example, [1,2,3,4,5] and [3,4,5,1,2] are circularly identical.
def circ_identical(l1, l2):
for i in range(len(l1)):
if (l1[i:] + l1 [:i]) == l2:
return True
return False
print(circ_identical([1,2,3,4],[2,3,4,12]))
| true |
ceab9c9cfc0e4327b9b22b71f5f969a9d6b17477 | botantantan/pangkui | /hw5/hw5_9.py | 480 | 4.15625 | 4 | """
Input example 1:
FONTNAME and FILENAME
Output sample 1:
FONTAMEIL
Input example 2:
fontname and filrname
Output sample 2:
Not Found
"""
str1 = input()
str2 = ''
str3 = ''
for ch in str1:
if ord('A') <= ord(ch) <= ord('Z'):
str2 += ch
mylist = list(set(str2))
mylist.sort(key = str2.index)
for ch in mylist:
str3 += ch
if str3 != '':
print(str3)
else:
print("Not Found")
| true |
e317b5e673f8914253e1dab99412ee407ff10115 | markyashar/Python_Scientific_Programming_Book | /looplist/odd.py | 454 | 4.28125 | 4 | """
Generate odd numbers
This program generates odd numbers from 1 to n.
It sets n in the beginning of the program and uses
a while loop to compute the numbers (making sure that
if n is an even number, the largest generated odd number
is n-1).
"""
n = 9 # The upper limit
odd = 1 # Start at 1
while odd < n:
print odd
odd = odd + 2 # To get odd number
"""
Running program
Unix>python odd.py
1
3
5
7
"""
| true |
a4f140176275a52b0febb2f1bd5b56981938674f | thatnerdjoe/violent_python | /week03/lecture/Exp-8.py | 936 | 4.25 | 4 | '''
Hash File Functions and usage example
'''
from __future__ import print_function
import hashlib
import sys
''' Determine which version of Python '''
if sys.version_info[0] < 3:
PYTHON_2 = True
else:
PYTHON_2 = False
def HashFile(filePath):
'''
function takes one input a valid filePath
returns the hexdigest of the file
or error
'''
try:
with open(filePath, 'rb') as fileToHash:
fileContents = fileToHash.read()
hashObj = hashlib.md5()
hashObj.update(fileContents)
digest = hashObj.hexdigest()
return digest
except Exception as err:
return str(err)
print("Hash File Function Demonstration")
if PYTHON_2:
fileName = raw_input("Enter file to hash: ")
else:
fileName = input("Enter file to hash: ")
hexDigest = HashFile(fileName)
print(hexDigest)
| true |
c63db43c96052601ed5ba6d6bafd4265daeb54db | Stav30/Python | /range.py | 209 | 4.125 | 4 | """
In 3.X range is an iterable, that generates items on demand, so we need to wrap it in a list call to display its results all at once.
"""
x = list(range(5)), list(range(2,5)), list(range(0,10,2))
print(x)
| true |
f21eab6cb4090ffdf3aa201a9e685976b7830343 | araschermer/python-code | /LeetCode/is-palindrom.py | 1,024 | 4.4375 | 4 | def is_palindrome(x):
"""
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
For example, 121 is palindrome while 123 is not.
:type x: int
:rtype: bool
"""
val = str(x) # convert number to string
return val == val[::-1] # check if the reverse equals the original value, True if palindrome, otherwise False
if __name__ == '__main__':
print(is_palindrome(121))
print(is_palindrome(-121))
print(is_palindrome(10))
print(is_palindrome(-101))
# Example 1:
# Input: x = 121
# Output: true
# Example 2:
# Input: x = -121
# Output: false
# Explanation: From left to right, it reads -121. From right to left, it becomes
# 121-. Therefore it is not a palindrome.
# Example 3:
# Input: x = 10
# Output: false
# Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
# Example 4:
# Input: x = -101
# Output: false | true |
c963229ed1fcbb5dc25dc974c3c98a883960ae7e | araschermer/python-code | /LeetCode/move-zeros.py | 963 | 4.3125 | 4 | def move_zeroes(nums):
"""Given an array nums, write a function to move all 0's to the end of it
while maintaining the relative order of the non-zero elements.
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
# approach 01
zero_counter = 0
while 0 in nums:
nums.remove(0)
zero_counter += 1
while zero_counter > 0:
nums.append(0)
zero_counter -= 1
print(nums)
# approach 02: faster than approach 01
zero_tracker = 0
for index, num in enumerate(nums):
if num != 0 and zero_tracker != index:
nums[zero_tracker], nums[index] = nums[index], nums[zero_tracker]
zero_tracker += 1
elif num != 0:
zero_tracker += 1
print(nums)
if __name__ == '__main__':
move_zeroes([0, 2, 0, 2, 0, 8, 0, 4, 9])
move_zeroes([0, 4, 9])
move_zeroes([9, 0])
move_zeroes([0, 1, 0, 3, 12])
| true |
2ebda9a3f3b3c87168eb4263a11f01afbfc9fa67 | araschermer/python-code | /algorithms_and_data_structures/arrays/arrays.py | 2,137 | 4.40625 | 4 | #Basic Array operaitons
# appending elements to the first unoccupied element in the array
array1 = []
for num in range(10):
array1.append(num)
print(f"array1: {array1}")
# Inserting elements at the beginning of the array
array3 = []
for num in range(10):
array3.insert(0, num)
print(f"array3:{array3}")
# insert number at index of the number's value
array4 = []
for num in range(10):
array4.insert(num, num)
print(f"array4: {array4}")
# to remove item from array
array = [i for i in range(10)]
array.remove(9)
print(f"Array: {array}")
# delete element by index
print(f"Array: {array}")
del array[0]
print(f"Array after deleting element at index 0: {array}")
# Reverse Array
array.reverse()
print(f"Array: {array}")
# getting index of element
print(f"Index of element 5 in {array} is {array.index(5)}")
# search element between indices
array = [1, 2, 4, 1, 2, 3, 2, 1, 3, 2, 2, 1, ]
print(f"index of element 2 between indices 0,2 in {array} is {array.index(2, 0, 2)}")
# counting number of appearance of number 2 in the array
print(f"element number 2 appears {array.count(2)} times in {array}")
# getting maximum
print(f"maximum number in {array} is: {max(array)}")
# Deep copy of an array
copy_array=array.copy()
print(f"deep copy of {array} is {copy_array} ")
# testing the copy
del copy_array[0]
print(f"Array {array}, Copy array: {copy_array} ")
# list comprehension for a 1D array
flat_list = [element for element in range(4 * 4)]
# Row major 2d array
row_major_2d_array = []
start = 0
end = 4 # num of columns
for _ in range(4): # num of rows
row_major_2d_array.append(flat_list[start:end])
start += 4 # num of columns
end += 4 # num of columns
state_var = len(flat_list) # updates the state variable to the number of elements in the matrix
print(f"row major 2d array: {row_major_2d_array}")
# Column major 2d array
column_major_2d_array = []
start = 0
for _ in range(4):
# number of rows equals 4
column_major_2d_array.append(flat_list[start:: 4]) # start from first element and jump by 4 to get the next element
start += 1
print(f"Column major 2D array{column_major_2d_array}")
| true |
273846508ef2f7cb6b4fdb979ce61dcff99a7c2c | araschermer/python-code | /LeetCode/count-primes.py | 1,104 | 4.21875 | 4 | def count_primes(n):
"""Count the number of prime numbers less than a non-negative number, n.
# extra: return the prime numbers
:type n: int
:rtype: int
"""
prime_numbers = []
if n < 2:
return 0
prime = [1] * n # fill a list of length n with 1
for i in range(2, n):
if prime[i]:
prime[i * i:n:i] = [0] * len(prime[i * i:n:i]) # set all multiples of i to 0
for i, value in enumerate(prime): # to print the prime numbers themselves
if value == 1 and i >= 2: # only consider values= 1, since those are the prime numbers, disregard 1 and 0
prime_numbers.append(i) # append the (prime)number to the prime numbers list
print(prime_numbers)
return sum(prime[2:])
if __name__ == '__main__':
# Example 1:
# Input: n = 10
# Output: 4
# Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
print(count_primes(10))
# Example 2:
# Input: n = 0
# Output: 0
print(count_primes(0))
# Example 3:
# Input: n = 1
# Output: 0
print(count_primes(1)) | true |
cbd1a5e0ed518d7ed64684fe0c7dfaad577fcf3a | araschermer/python-code | /LeetCode/reverse-integer.py | 1,231 | 4.34375 | 4 | def reverse_integer(x):
"""Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside
the signed 32-bit integer range [-2^31, (2^31) - 1], then return 0.
:type x: int
:rtype: int
"""
x_string = str(x)
if x_string[0] == "-": # in case the number is negative
x_string = x_string[1:] # remove the negative sign
x_string = x_string[::-1] # reverse the number
x_string = "-" + x_string # append the negative sign to the new number
else:
x_string = x_string[::-1] # if number is positive, reverse the number
if (-2) ** 31 <= int(x_string) < ((2 ** 31) - 1): # test boundaries of 32-bit integers
return int(x_string) # if number is valid, return it
else:
return 0 # otherwise return 0
if __name__ == '__main__':
print(reverse_integer(123))
print(reverse_integer(-123))
print(reverse_integer(120))
print(reverse_integer(0))
# Example
# 1:
# Input: x = 123
# Output: 321
# Example
# 2:
# Input: x = -123
# Output: -321
# Example
# 3:
# Input: x = 120
# Output: 21
# Example
# 4:
# Input: x = 0
# Output: 0 | true |
52e4f4dd1af4e34768962cc25132d8ba3a8f07ec | araschermer/python-code | /100 days of code/tip-calculator.py | 714 | 4.3125 | 4 | def calculate_tip(bill, people, tip):
""" calculates a tip based on a given percentage of the total bill amount.
the functionality can be viewed on repl.it website using the following links
https://repl.it/@abdelkha/Tip-calculator?embed=1&output=1#main.py"""
tip_percentage = tip / 100
total_tip_amount = bill * tip_percentage
bill_after_tips = bill + total_tip_amount
bill_per_person = round(bill_after_tips / people, 2)
print(f"Each person should pay: ${bill_per_person}")
if __name__ == '__main__':
# If the bill was $150.00, split between 5 people, with 12% tip.
# Each person should pay (150.00 / 5) * 1.12 = 33.6
calculate_tip(bill = 150, people = 5, tip = 12)
| true |
e7edf71414e6531335ebed17b5cbbcfe2478d07e | araschermer/python-code | /algorithms_and_data_structures/arrays/largest_range.py | 2,138 | 4.375 | 4 | def find_largest_range(array: [float]):
"""Returns the largest range of numbers that exist in the array
Time complexity: O(NlogN)
Space complexity: O(1)"""
current_range = 1
max_range = 1
upper_bound = array[0]
array.sort()
for index, number in enumerate(array):
if number == array[index - 1]:
# if duplicate exists, do not increase range and continue
continue
if number == array[index - 1] + 1:
# if number is in ascending with the previous numbers , increase range
current_range += 1
if current_range > max_range:
# update max range
max_range = current_range
upper_bound = array[index]
else:
# otherwise, start over
current_range = 1
lower_bound = upper_bound - max_range + 1
return [lower_bound, upper_bound]
def largest_range(array: [int]):
# Time complexity: O(N)
# Space complexity: O(N)
largest_existing_range = []
longest_range = 0
numbers_table = {number: True for number in array}
for number in array:
if not numbers_table[number]: # number already explored, and its value is set to False
continue
numbers_table[number] = False
current_length = 1
lower_bound = number - 1
upper_bound = number + 1
while lower_bound in numbers_table:
numbers_table[lower_bound] = False
current_length += 1
lower_bound -= 1
while upper_bound in numbers_table:
numbers_table[upper_bound] = False
current_length += 1
upper_bound += 1
if current_length > longest_range:
longest_range = current_length
largest_existing_range = [lower_bound + 1, upper_bound - 1]
return largest_existing_range
if __name__ == '__main__':
print(largest_range(array=[1, 0, 2, 3, -1, 4, 6]))
print(largest_range(array=[1, 7, 5, 2, 3, 4, 6]))
print(find_largest_range(array=[1, 0, 2, 3, -1, 4, 6]))
print(find_largest_range(array=[1, 7, 5, 2, 3, 4, 6]))
| true |
10b8325ef58e419e858c6a85f89feaa354d5197c | araschermer/python-code | /algorithms_and_data_structures/linked_lists/merge_linked_lists.py | 2,394 | 4.3125 | 4 | from linked_lists_util import print_linked_list, insert_list, Node
class LinkedList:
def __init__(self):
self.head = None
def merge_linked_lists(self, list_to_merge):
"""returns a single linked list out of merging two single linked lists with sorted elements."""
pointer1 = self.head
pointer2 = list_to_merge.head
pointer3 = None
while pointer1 and pointer2:
if pointer1.data < pointer2.data:
pointer3 = pointer1
pointer1 = pointer1.next_node
else: # pointer1.data < pointer2.data
if pointer3:
pointer3.next_node = pointer2
pointer3 = pointer2
pointer2 = pointer2.next_node
pointer3.next_node = pointer1
if pointer2:
pointer3.next_node = pointer2
elif pointer1:
pointer3.next_node = pointer1
return self if self.head.data < list_to_merge.head.data else list_to_merge
def recursive_merge(self, list_to_merge):
pointer1 = self.head
pointer2 = list_to_merge.head
print_linked_list(self)
list_to_merge.print_linked_list()
self.recursive_call(pointer1, pointer2)
return self if self.head.data < list_to_merge.head.data else list_to_merge
def recursive_call(self, pointer1, pointer2, pointer3=None):
print_linked_list(self)
if not pointer1:
pointer3.next_node = pointer2
return
if not pointer2:
return
if pointer1.data < pointer2.data:
self.recursive_call(pointer1.next_node, pointer2, pointer1)
else:
if pointer3 is not None:
pointer3.next_node = pointer2
temp_pointer2 = pointer2.next_node
pointer2.next_node = pointer1
self.recursive_call(pointer1=pointer1, pointer2=temp_pointer2, pointer3=pointer2)
if __name__ == '__main__':
linked_list2 = LinkedList()
insert_list(linked_list2, [-10, 1, 3, 4, 8])
print_linked_list(linked_list2)
linked_list3 = LinkedList()
insert_list(linked_list3, [-1, 0, 2, 5])
print_linked_list(linked_list3)
# linked_list2 = linked_list2.recursive_merge(linked_list3)
linked_list2 = linked_list2.merge_linked_lists(list_to_merge=linked_list3)
print_linked_list(linked_list2)
| true |
36ad6e0255aef608a48b16381dd477bed2286a37 | kateallison/Python_Learnins | /ex11.py | 961 | 4.40625 | 4 | #ex11.py = Asking Questions
#https://learnpythonthehardway.org/book/ex11.html
print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()
print "So, you're %r old, %r tall and %r heavy." % (
age, height, weight)
#[Take note of the commas at the end of the line]
#Mistake I made: % instead of %r is the wrong type of argument and this errors out.
#Defining "raw_input"
#Note: in Python 3, it's just "input". Apparently there are security issues?
#Other uses might be surveys where you want people to check their answers (assuming you
#can store the data somehow?
#On my own.
print "How many cats do you own?",
cat = raw_input()
print "How many dogs do you own?",
dog = raw_input()
print "Day drinking: a great idea, or the greatest idea?",
booze = raw_input()
print "So, you have %r cats, %r dogs and think day drinking is %r. Let's be friends" % (
cat, dog, booze)
| true |
27982ee0b2058e23ff0889c8f2009b94a0ba6358 | kateallison/Python_Learnins | /ex14.py | 1,833 | 4.28125 | 4 | #ex14.py = Prompting and Passing
#https://learnpythonthehardway.org/book/ex14.html
#from sys import argv
#script, user_name = argv
#prompt = '>'
#print "Hi %s, I'm the %s script." % (user_name, script)
#print "I'd like to ask you a few questions."
#print "Do you like me %s?" % user_name
#likes = raw_input(prompt)
#print "Where do you live %s?" % user_name
#lives = raw_input(prompt)
#print "What kind of computer do you have?"
#computer = raw_input (prompt)
#print """
#Alright, so you said %r about liking me.
#You live in %r. Not sure where that is.
#And you have a %r computer. Nice.
#""" % (likes, lives, computer)
#HQSML-150831:Desktop kallis201$ python ex14.py Kate
#Hi Kate, I'm the ex14.py script.
#I'd like to ask you a few questions.
#Do you like me Kate?
#>Yes
#Where do you live Kate?
#>Philadelphia
#What kind of computer do you have?
#>Mac
#Alright, so you said 'Yes' about liking me.
#You live in 'Philadelphia'. Not sure where that is.
#And you have a 'Mac' computer. Nice.
#Zork! Adventure! I remember this.
#Try it out
from sys import argv
script, user_name = argv
prompt = '>'
print "Hi %s, I'm the %s awesome-o 5000 question asker." % (user_name, script)
print "I'd like to ask you a few questions."
print "Do you have any coffee %s?" % user_name
coffee = raw_input(prompt)
print "Are you wearing pants at work today, %s?" % user_name
pants = raw_input(prompt)
print "How many dragons do you have?"
dragons = raw_input (prompt)
print "Can I play with your pet dragons?"
play = raw_input (prompt)
print """
Alright, so you said %r about having coffee. I have no coffee. You should bring me some.
You said %r about pants wearing. Interesting.
And you have %r dragons. Nice. You said %r about playing with them. Rude.
You should have said 'Hell, yes'.
""" % (coffee, pants, dragons, play)
| true |
d6c604dfc817b67b8b61240f13c022ff37e8c9f6 | VladKli/Lasoft | /2.py | 750 | 4.34375 | 4 | # Користувач вводить рядок і символ. У рядку знайти всі входження цього символу і перевести його в верхній регістр,
# а також видалити частину рядка, починаючи з останнього входження цього символу і до кінця.
string = input('Print a string, please: ')
symbol = input('Print a symbol, please: ')
def find_result(text, symb):
new_str = ''
result = ''
for el in text:
if el == symb:
new_str = text.replace(el, symb.upper())
index = new_str.rfind(symb.upper())
result = new_str[0:index]
return result
print(find_result(string, symbol))
| false |
e43da145e964ddf558b202c966eba9e9da8360ad | VladKli/Lasoft | /7.py | 886 | 4.25 | 4 | # Написати функцію, що перетворює дробове або ціле число в рядок.
# якщо вводити 1.3 результат текстом -> одна ціла три десятих
number = float(input('Print a number from 0 to 10, please: '))
def transform_to_words(num):
integer_part = ['zero ', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ']
units_part = str(num).split('.')[0]
decimal_part = str(num).split('.')[1]
if str(num - int(num))[-1] == '0':
return integer_part[int(num)]
elif (num >= 1) and (num < 20):
transferred_num = integer_part[int(units_part)] + 'point ' + integer_part[int(decimal_part)]
return transferred_num
try:
print(transform_to_words(number))
except IndexError:
print('A number should be in range from 0 to 10')
| false |
05c76e56a74a9a9f4040bed73167e91093022279 | LucasSalu/Curso_Python_Basico_Avan-ado | /Orientado_objetos/exercicio_04.py | 930 | 4.125 | 4 | '''Crie uma classe elevador que vc determine a quantidade de andares '''
class Elevador:
andar = 0
pessoas = 0
def __init__(self,andares,capacidade):
self.__andares = andares
self.__capacidade = capacidade
def Entra(self):
if Elevador.pessoas + 1 > self.__capacidade:
print("capacidade excedida")
else:
Elevador.pessoas += 1
print(Elevador.pessoas)
def Sai(cls):
if cls.pessoas -1 < 0:
print("Nao existe passageiro")
else:
Elevador.pessoas -= 1
def Sobe(self):
if Elevador.andar + 1 > self.__andares:
print('você ja esta no ultimo andar')
else:
Elevador.andar += 1
@classmethod
def desce(cls):
if cls.andar - 1 < 0:
print('voce ja esta no terreo')
else:
Elevador.andar -= 1
lucas = Elevador(20,20)
| false |
5dd3d86a7e38261130e3add94570ce807a28aa37 | dcheung15/Python | /ecs102/Hw/Distances.py | 770 | 4.1875 | 4 | #Doung Lan Cheung
#dcheun01@syr.edu
#Assignment 2, problem 2.
#February 1, 2019
#Ask the user for how many pairs of points and compute the distances.
import math
def main():
#Ask for how many pairs of points and for the x and y cooridinates
pts = eval(input("Enter how many pairs of points: "))
for a in range(pts):
x, y = eval(input("Enter x and y cooridinates separated by a comma"))
x2,y2 = eval(input("Enter x and y cooridinates separated by a comma"))
d= math.sqrt((x2-x)**2+(y2-y)**2)
#print the how many pairs of points, starting and ending points and the distance.
print("How many pair of points?",pts)
print("start point - ",x,",",y)
print("end point - ",x2,",",y2)
print("Distance: ",d)
main() | true |
f01dc8ccdc1f52d98a7615fd02d4d919cd7db156 | dcheung15/Python | /ecs102/Hw/DayofYear.py | 1,177 | 4.25 | 4 | #Official Name: Doung Lan Cheung
#email: dcheun01@syr.edu
#Assignment: Assignment 4, problem 1.
#Date:February 18, 2019
#Figuring out what day of the year and week, given the date is through input
def main ():
monthLengths=[31,28,31,30,31,30,31,31,30,31,30,31]
d = input("What is the day of the week in mm/dd/yyyy? ")
month = int(d[0:2])
day = int(d[3:5])
#use a loop and monthLengths to figure out the day of the year
start = 0
for n in monthLengths[:int(month)-1]:
start = start + n
start = start + day
print(d,"is day",start,"of the year.")
print("1 for Sunday")
print("2 for Monday")
print("3 for Tuesday")
print("4 for Wednesday")
print("5 for Thursday")
print("6 for Friday")
print("7 for Saturday")
#Ask user for number for what the day will be for Jan. 1
dayofw = int(input("What day of the week is Jan 1? (Enter a number) "))
weekdays=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
DaY = start//7
DAY = weekdays[((start+dayofw)%13)-2]
print(d, "falls on a",DAY)
main() | true |
17dab45af402d124d97837816b17ebcf6e7e542e | abdur-razzak2672/Calculate-sgpa-use-tkinter-in-python | /cgpa calculate.py | 1,984 | 4.21875 | 4 | print("Enter Student Information")
name = (input("Student Name : "))
id = (input("Student Id : "))
section = (input("Section : "))
semester = (input("Semester : "))
print("\nEnter Course Information")
number = int(input("Enter Number Of Course : "))
total_gpa=0
total_credit = 0
course1 = []
grade1 = []
credit1 = []
grade_point1 = []
for i in range(number):
course=(input("Enter name Of Course Code: "))
credit= (int(input("Enter a course credit :")))
marks = (float(input("Enter Marks : ")))
if 80<= marks <= 100 :
grade = "A+"
grade_point = 4.00
elif 75<= marks < 80 :
grade = "A"
grade_point = 3.75
elif 70<= marks < 75 :
grade = "A-"
grade_point = 3.50
elif 65<= marks < 70 :
grade = "B+"
grade_point = 3.25
elif 60<= marks< 65 :
grade = "B"
grade_point = 3.00
elif 55<= marks< 60 :
grade = "B-"
grade_point = 2.75
elif 50<= marks < 55 :
grade = "C+"
grade_point = 2.50
elif 45<= marks < 50 :
grade = "C"
grade_point = 2.25
elif 40<= marks < 45 :
grade = "D"
grade_point = 2.00
else :
grade = "F"
grade_point = 0.00
total_gpa = total_gpa+grade_point*credit
total_credit = total_credit+credit
course1.append(course)
credit1.append(credit)
grade1.append(grade)
grade_point1.append(grade_point)
sgpa = total_gpa/total_credit
print("\n\n")
print("Student Name : ",name)
print("Student Id : ",id)
print("Section : ",section)
print("Semester : ",semester)
print("\n")
print("Course Code Course Credit Grades Grades Point")
for i in range(number) :
print(course1[i]," ",credit1[i]," ",grade1[i]," ",grade_point1[i])
print("\n")
print("Total Credit :",total_credit )
print("SGPA :"+"{:.2f}".format(sgpa))
| false |
7bf149606d80aa353116f2ec9c81b64a7d0182cc | MangeshSodnar123/python-practice-programs | /factorial_forLoop.py | 235 | 4.3125 | 4 | num = int(input("Enter the number : "))
factorial = 1
if num == 1 or num == 0:
print("The factorial is 1. ")
else:
for i in range( 1, num+1):
factorial = factorial * i
print("The factorial of the ",num,"is ",factorial) | true |
7708db5110dfcb07aa1189c3c230f663c90c25fe | vandanasen/Python-Projects | /May-week4/prob5.py | 545 | 4.125 | 4 | """
Define a class which has at least two methods:
getString: to get a string from console input
printString: to print the string in upper case.
Also please include simple test function to test the class methods.
"""
class myclass:
def __init__(self,str1):
self.str1 = str1
def __str__(self):
return "" \
"string".format(self.str1)
def getstring(self):
self.str1=input('Enter a String:')
def printstring(self):
print(self.str1)
ob=myclass('')
f=ob.getstring()
g=ob.printstring()
| true |
596eb6e59ae078bb2aa4213592002a94aacda38b | harrisont/ProjectEuler | /Common/Prime.py | 1,438 | 4.25 | 4 | from math import sqrt, ceil, floor
def is_prime(n):
"""
>>> is_prime(0)
True
>>> is_prime(1)
False
>>> is_prime(2)
True
>>> is_prime(3)
True
>>> is_prime(4)
False
>>> is_prime(7)
True
>>> is_prime(9)
False
>>> is_prime(13)
True
"""
if n == 1:
return False
elif n < 4:
return True
elif n % 2 == 0:
return False
elif n < 9:
return True
elif n % 3 == 0:
return False
else:
# Use the fact that all primes greater than 3 can be
# written as 6k +/- 1.
factor = 5
for factor in range(5, 1 + floor(sqrt(n)), 6):
if n % factor == 0:
return False
if n % (factor + 2) == 0:
return False
return True
def prime_factors(n):
"""
>>> prime_factors(6)
[2, 3]
>>> prime_factors(8)
[2, 2, 2]
>>> prime_factors(143)
[11, 13]
>>> prime_factors(2431)
[11, 13, 17]
>>> prime_factors(13195)
[5, 7, 13, 29]
"""
product = n
prime_factors = []
factor = 2
newProduct = True
while True:
if newProduct:
newProduct = False
maxFactor = ceil(sqrt(product))
if factor > maxFactor:
break
if (product % factor == 0) and is_prime(factor):
prime_factors.append(factor)
# Update the product.
product //= factor
newProduct = True
# Allow multiples of the same factor.
factor -= 1
factor += 1
# Handle the last prime factor.
if product != 1:
prime_factors.append(product)
return prime_factors
if __name__ == "__main__":
import doctest
doctest.testmod() | true |
8456f0dc64309a6f3778657827d11758d9286475 | dsmall3303/portfolio | /Python/largerthan.py | 491 | 4.3125 | 4 | first_number = 0
second_number = 0
user_unput = ''
largest = 0
#get the first number from the user
user_input = input("Please enter the first number: ")
first_number = int(user_input)
#get the second number from the user
user_input = input("Please enter the second number: ")
second_number = int(user_input)
#determine the largest of the two
if first_number > second_number:
largest = first_number
else:
largest = second_number
#display largest
print("The largest is", largest)
| true |
6f98814417f70b385476913d50f571137c35a898 | cRYP70n-13/Algorithms | /Data_Structures/python/Linked_lists/swapNodeWithoutSwappingData.py | 1,630 | 4.15625 | 4 | class Node :
# constructor
def __init__(self, val = None, next1 = None):
self.data = val
self.next = next1
# print list from this
# to last till None
def printList(self):
node = self
while (node != None) :
print(node.data, end = " ")
node = node.next
print(" ")
def push(head_ref, new_data) :
(head_ref) = Node(new_data, head_ref)
return head_ref
def swapNodes(head_ref, x, y) :
head = head_ref
# Nothing to do if x and y are same
if (x == y) :
return None
a = None
b = None
# search for x and y in the linked list
# and store therir pointer in a and b
while (head_ref.next != None) :
if ((head_ref.next).data == x) :
a = head_ref
elif ((head_ref.next).data == y) :
b = head_ref
head_ref = ((head_ref).next)
# if we have found both a and b
# in the linked list swap current
# pointer and next pointer of these
if (a != None and b != None) :
temp = a.next
a.next = b.next
b.next = temp
temp = a.next.next
a.next.next = b.next.next
b.next.next = temp
return head
# Driver code
start = None
# The constructed linked list is:
# 1.2.3.4.5.6.7
start = push(start, 7)
start = push(start, 6)
start = push(start, 5)
start = push(start, 4)
start = push(start, 3)
start = push(start, 2)
start = push(start, 1)
print("Linked list before calling swapNodes() ")
start.printList()
start=swapNodes(start, 6, 3)
print("Linked list after calling swapNodes() ")
start.printList()
| true |
85bfc4e59c8fea3265864c2a26c8d2b8de9ad96f | Bogdan808/mypython | /inherit_abc.py | 1,401 | 4.15625 | 4 | from abc import *
class SchoolMembers(metaclass=ABCMeta):
'''Представляет любого человека в школе.'''
def __init__(self, name, age):
self.name = name
self.age = age
print('(Создан SchoolMember: {0})'.format(self.name))
@abstractmethod
def tell(self):
'''Вывести информацию.'''
print('Имя:"{0}" Возраст:"{1}"'.format(self.name, self.age), end=" ")
class Teacher(SchoolMembers):
'''Представляет преподавателя.'''
def __init__(self, name, age, salary):
SchoolMembers.__init__(self, name, age)
self.salary = salary
print('(Создан Teacher: {0})'.format(self.name))
def tell(self):
SchoolMembers.tell(self)
print('Зарплата: "{0:d}"'.format(self.salary))
class Student(SchoolMembers):
'''Представляет student.'''
def __init__(self, name, age, marks):
SchoolMembers.__init__(self, name, age)
self.marks = marks
print('(Создан Student: {0})'.format(self.name))
def tell(self):
SchoolMembers.tell(self)
print('Оценки: "{0:d}"'.format(self.marks))
teacher = Teacher('Lidia Pavlovna', 2000, 1400)
student = Student('Andrey', 18, 4)
print()
print()
members = [teacher, student]
for memb in members:
memb.tell()
| false |
f827a70e2dc5ab4490a8f2c3844cc530e5bb07ee | nehamundye/random-python-projects | /03_hangman/main.py | 1,430 | 4.21875 | 4 | import random
from words import words
# Pick a random word
def pick_word():
word = random.choice(words)
while '-' in word or ' ' in word:
word = random.choice(words)
return word
word = pick_word()
guessed_letter = []
def hide_word(guessed_letter):
hide = ""
for letter in word:
if letter in guessed_letter:
hide = hide + letter
else:
hide = hide + "_"
return hide
def remaining_guesses(letter_input, guess_no):
if letter_input not in word:
guess_no -= 1
return guess_no
guess_no = 6
hide = hide_word(guessed_letter)
while guess_no != 0:
print(f"Word: {hide} & guessed letters: {guessed_letter} & remaining guesses: {guess_no}")
# Display a message if letter was already guessed.
while True:
letter_input = input('Input your guessed letter: ')
if letter_input in guessed_letter:
print("Letter already guessed. Please input another letter")
if letter_input not in guessed_letter:
break
guessed_letter.append(letter_input)
# If guessed_letter in word, then display hide_word including this letter.
hide = hide_word(guessed_letter)
guess_no = remaining_guesses(letter_input, guess_no)
if hide == word:
print(f"You won! The word was {word}.")
break
if hide != word:
print(f"You lost. The word was {word}. Please try again later")
| true |
49f802161da33233a083944e4c6e9e0bf6c007b8 | OreBank/udacity-pds | /python/lesson 6/10-practice-question.py | 1,041 | 4.1875 | 4 | # Create a function that opens the flowers.txt, reads every line in it, and saves it as a dictionary. The main (separate) function should take user input (user's first name and last name) and parse the user input to identify the first letter of the first name. It should then use it to print the flower name with the same first letter (from dictionary created in the first function).
# output: >>> Enter your First [space] Last name only: Bill Newman
# output: >>> Unique flower name with the first letter: Bellflower
def readFlowers(filename):
flowersDict = {}
with open(filename) as f:
for line in f:
letter = line.split(':')[0].strip()
flower = line.split(':')[1].strip().title()
flowersDict[letter] = flower
return flowersDict
def main():
flowers = readFlowers('10-flowers.txt')
name = input("Enter your first and last name: ").title().strip()
firstLetter = name[0].title()
print(flowers.get(firstLetter))
main()
# print the desired output | true |
ac0b857ee83eb6e5c2539181d789dc0d2eaa645a | EthanSargent/python-ml-implementations | /LinReg.py | 2,711 | 4.15625 | 4 | # Author: Ethan Sargent
#
# The following is an implementation of regularized, multiple linear regression
# (for an arbitrary number of parameters) using gradient descent. I learned the
# algorithm from Andrew Ng's free online lecture.
#
# In the example, we predict weight from blood pressure and age, and plot the
# decrease of the cost function over time to verify gradient descent is
# working.
#
# Retrieved dataset from:
# http://college.cengage.com/mathematics/brase/understandable_statistics/7e/students/datasets/mlr/frames/frame.html
import csv
import numpy as np
import matplotlib.pyplot as plt
def gradient_descent(X, Y, iterations, alpha, l = 0):
""" We use gradient descent the coefficients (betas) of a linear function
of multiple variables. By default, l = 0; setting l > 0 will penalize
large betas which corrects for overfitting, and this becomes
regularized gradient descent.
"""
# initialize B0, B1, ..., Bp
betas = np.array([0.0]*(len(X[0])+1))
# initialize list of cost vs iterations; should see a gradual descent
costs = np.array([0.0]*iterations)
# number of observations
m = len(X)
for i in range(iterations):
sumterms = 1.0/m * ([estimation(xvec,betas) for xvec in X] - Y)
errors = np.array([0.0]*len(betas))
errors[0] = sum(sumterms) # error term for B0 has no multiplier
for k in range(1,len(betas)):
errors[k] = np.dot(sumterms, [row[k-1] for row in X]) + l/m*betas[k]
betas = betas - alpha * errors
costs[i] = cost(X, Y, betas, l)
return betas, costs
def estimation(xvec, betas):
# B0 + B1*X1 + B2*X2 + ... + Bp * Xp
return (betas[0] + np.dot(xvec, betas[1:]))
def cost(X, Y, betas, l):
# the total cost for our data for some betas; higher cost indicates worse
# performing betas and/or too large betas i.e. overfitting
total_cost = 0
for i in range(len(data)):
total_cost += (estimation(X[i], betas) - Y[i])**2
# regularization
total_cost += l*sum([beta**2 for beta in betas])
return total_cost/(2*len(X))
# column to predict
c = 2 # weight
# read data, take off row of labels (which evaluate to NaNs)
data = np.genfromtxt('BloodPressure.csv', delimiter = ',')[1:]
# delete the cth column from the data, which we will attempt to predict
X = np.delete(data, c, 1)
Y = np.array([row[c] for row in data])
# we use quite a low alpha; for alpha around .01-.001 errors diverge
# for this data set.
betas, costs = gradient_descent(X,Y, 1000, .00001, 0)
# on this data set, cost descends incredibly quickly
plt.plot(range(len(costs)), costs)
plt.show()
| true |
27c7695fc678229dca277fba603aa6404c64aed6 | EL001/GemMine | /gem_enoch2.py | 1,492 | 4.5625 | 5 | #!/usr/bin/env python
# coding: utf-8
# """
# Write a python program that does this;
# It collects a user’s
# - name
# - age
# - sex
#
# Prints out a welcome message like below.
# “Hi {user’s name}, you are welcome. In 10 years time, you will be {age in 10 years time} years old and very old by then.”
#
# The python program then asks for 2 or more favorites fruits separated by comma and prints the result to a list.
#
# The python program then asks for 2 or more favorite numbers separated by comma and prints the result to a sorted list in
# descending order.
# """
# In[1]:
name = input("Enter username ")
age = input("Enter age ")
age = int(age) + 10
sex = input("Enter sex ")
print("Hi {}, you are welcome, in 10 years time, you will be {} years "
"old and very old by then.".format(name, age))
# In[3]:
#The python program then asks for 2 or more favorites fruits separated by comma and prints the result to a list.
fav_fruits = input("Enter at least 2 favourite fruits, separated by a comma: ")
fruits_list = fav_fruits.split(",")
print(fruits_list)
# In[4]:
'''The python program then asks for 2 or more favorite numbers separated by comma and prints the result
to a sorted list in Descending order.'''
fav_no = input('Enter at least 2 favourite numbers separated by a comma ')
split_list = fav_no.split(',')
sorted_list = []
for i in split_list:
sorted_list.append(int(i))
sorted_list.sort(reverse=True)
print(sorted_list)
# In[ ]:
| true |
5a0ae81921e8d28d618834a583d04ea250a53e2e | Aman-Achotani/Python-Projects | /Library_project.py | 2,374 | 4.21875 | 4 | # My library project
class Library:
def __init__(self,Book,Library) :
self.book_name = Book
self.library_name = Library
print("\t\t***Welcome to ",self.library_name,"***")
def display(self):
print()
print()
print("Books avaiable are : ")
for items in self.book_name:
print(items)
def lend(self):
print()
name = input("Enter your name : ")
ch1 = input("Enter the name of the book you want to lend : ")
if ch1 in self.book_name:
self.book_name.remove(ch1)
print(ch1,"book lended to you succesfully")
f = open("Library_Record.txt","a")
f.writelines(f"{name} lended {ch1} book\n")
else:
print()
print("This type of book is not available ")
def donate(self):
print()
name2 = input("Donator please enter your name : ")
ch2 = input("Please enter the name of book you want to donate : ")
self.book_name.append(ch2)
f = open("Library_Record.txt","a")
f.writelines(f"{name2} donated {ch2} book\n")
print("Thank you ",name2,"for donating",ch2,"book!!!")
def return_book(self):
print()
name3 = input("Please enter your name : ")
ch3 = input("Please enter the name of book you want to return : ")
self.book_name.append(ch3)
f = open("Library_Record.txt","a")
f.writelines(f"{name3} returned {ch3} book\n")
print("Thank you ",name3,"for returning",ch3,"book!!!")
def arrange(self):
a = True
while a== True:
self.display()
print()
print("Enter 1 to lend a book")
print("Enter 2 to donate a book")
print("Enter 3 to return a book")
print("Enter 4 to exit\n")
ch4 = input()
if ch4 == '1':
self.lend()
elif ch4 == '2':
self.donate()
elif ch4 == '3':
self.return_book()
elif ch4 == '4':
break
else:
print("Invalid input")
Aman = Library(["Harry Potter","Tales of shivaji","Annabella returns","The fall of troy","Panchatantra"],"Aman's Library")
Aman.display()
print()
Aman.arrange() | true |
9c40bb8ffccc0817e22e59eaa8c19f2fb8e0fb2f | AdrianMartinezCodes/PythonScripts | /E14.py | 585 | 4.1875 | 4 | def sort(a_list):
return set(a_list)
def sort_list(a_list):
b = []
for i in a_list:
if i in a_list and i not in b:
#just needed if i not in b:
b.append(i)
return b
#updated soln below, old soln above, not working
#return [b.append(i) for i in a_list if i not in b]
def ex_5_sort(first_list,second_list):
return set(first_list) & set(second_list)
a = ['hi','hi','ok','lol']
b = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
c = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
print(sort(a))
print(sort_list(a))
print(ex_5_sort(b,c))
| true |
f30d01eee9940196171497e329da6298774b54bc | IODevelopers/hacktoberfest | /contribution/usmcamgrimm/randomWorld.py | 304 | 4.21875 | 4 | print ("Hello World?")
import random
helloWorld = random.randint(1,2)
randomChoice = 0
while randomChoice < 1 or randomChoice > 2:
randomChoice = int(input("Choose 1 or 2: "))
print ("You chose number ", randomChoice)
if randomChoice == helloWorld:
print ("Hello World!")
else:
print ("Hi World.")
| false |
930884982712570afbd534bce6c4734bd8a94fdf | edwardst14/python_homework | /homework5/homework5.1.py | 282 | 4.21875 | 4 | #Homework 5.1
#Sept. 30 2020
#Use generator functions to create your own version of range function, call it my_range.
#Do not use the python's range function in the code.
def my_range(start, end):
x = start
while x < end:
yield x
x=x + 1
for i in my_range(0,10):
print(i) | true |
50b16653fa7f527117e5f77a5f336268d155c4c1 | Saplyng/Hello-World-redux | /Python/chapter 7/rainfall statistics.py | 2,108 | 4.46875 | 4 | initial_dialog = ("""Hello User, you must be an aspiring meteorologist!
that's the only reason I can think you would want something like
an rainfall statistics calculator.
But what would I know, I'm just a robot
Anyway, I wont burden you the hassle of converting your units, just be
consistent, if you start with Inches you better not change to Centimeters
by the end.
But since your too lazy to do some simple math yourself, I'm sure I won't
have to worry about that...
But what would I know, I'm just a robot\n""")
print(initial_dialog)
months = ('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December')
rainfall_num = []
print("just type in the rainfall for each month,")
print("I'll do the rest of the work\n")
for i in months:
while True:
try:
rainfall_num.append(float(input(i + ": ")))
if not rainfall_num[-1] >= 0:
del rainfall_num[-1]
print("I don't think your number was quite right, try again")
continue
except ValueError:
print("You have to type something different that")
continue
else:
break
total_rainfall = sum(rainfall_num)
average_rainfall = total_rainfall / 12
def finding_max():
for k, j in enumerate(rainfall_num):
if j == max(rainfall_num):
return k
def finding_min():
for k, j in enumerate(rainfall_num):
if j == min(rainfall_num):
return k
print("\nTotal Rainfall: " + str(format(total_rainfall, ",.2f")) + " units")
print("Average Rainfall per month over a year: " +
str(format(average_rainfall, ',.2f') + " units"))
print("\nThe month with the most rain was " +
str(months[finding_max()]) + " with: " +
str(format(rainfall_num[finding_max()], ",.2f")) + " units")
print("The month with the least rain was " +
str(months[finding_min()]) + " with: " +
str(format(rainfall_num[finding_min()], ",.2f")) + " units")
print("\nGood luck User, it seems pretty wet in your world.")
| true |
a765639b6211d5a6deed266b376e30364defd3ee | Saplyng/Hello-World-redux | /Python/chapter 3/if else statements.py | 1,348 | 4.21875 | 4 | # library
roman_numerals = {'1': 'I',
'2': 'II',
'3': 'III',
'4': 'IV',
'5': 'V',
'6': 'VI',
'7': 'VII',
'8': 'VIII',
'9': 'IX',
'10': 'X'}
startup_dialog = """Ave, User! Welcome to Roman Numerology \"CI\" (or 101)!
Today we're going to be starting with the basics, as such
you're going to need to know how to count from the beginning.
1-10 will get you 80% of the way through our numbering system
so you should familiarize yourself with those first.
"""
print(startup_dialog)
# this was the complicated bit, very hard to understand, well, for me...
def conversion(number):
converted_number = roman_numerals[number]
print(' ')
print('The Roman equivalent is {}'.format(converted_number))
# had to look up a way to make sure that i was getting no errors
while True:
try:
user_number = int(input("Pick a number 1 through 10 :"))
except ValueError:
print("There's a time and place for everything but not now.")
continue
else:
break
if 0 < user_number < 11:
conversion(str(user_number))
else:
print(" ")
print("We have no time for your tomfoolery, this is a learned")
print("society, get out of my class!")
| true |
755196c7dd1c6a50bf33fe8b78d41927c88423d5 | davidforero2016/Fundamentals-for-Python | /Lists.py | 717 | 4.375 | 4 | #This file contains fundamental notions about lists.
Demolist1=[1, "John", True, 1,8, [1,2,3,4]]
print(Demolist1)
Demolist2=list((1, "John", True, 1,8, [1,2,3,4]))
print(Demolist2)
Demolist3=list(range(0,10))
print(Demolist3)
print(len(Demolist1))
print(Demolist1[5])
print("John" in Demolist1)
Demolist1[4]=False
print(Demolist1)
Demolist1.append("Juan") #append just works with one argument.
print(Demolist1)
Demolist1.extend([7,8,9])
print(Demolist1)
Demolist1.insert(1,2)
print(Demolist1)
Demolist1.insert(len(Demolist1),"Carlos")
print(Demolist1)
Demolist1.pop()
print(Demolist1)
Demolist1.remove("Juan")
print(Demolist1)
Demolist1.pop(0)
print(Demolist1)
Demolist3.reverse() #To order, use sort
print(Demolist3) | true |
91a3d28deb8541b6403e5f20bc3945fcec0b6817 | RobertElias/UdacityDataStructuresAlgorithms | /Python/functions.py | 2,657 | 4.40625 | 4 | # Example function 1: return the sum of two numbers.
def sum(a, b):
return a+b
# Example function 2: return the size of list, and modify the list to now be sorted.
my_list = ["Robert", "Cynthia", "Robbie"]
def list_sort(my_list):
my_list.sort()
return len(my_list), my_list
print(list_sort(my_list))
################################################
# Definition of the generator to produce even numbers.
def all_even():
n = 0
while True:
yield n
n += 2
my_gen = all_even()
# Generate the first 5 even numbers.
for i in range(5):
print(next(my_gen))
# Now go and do some other processing.
do_something = 4
do_something += 3
print(do_something)
# Now go back to generating more even numbers.
for i in range(100):
print(next(my_gen))
###############
#fibonacci
def prod(a, b):
# TODO change output to the product of a and b
return a*b
def fact_gen():
i = 1
n = i
while True:
output = prod(n, i)
yield output
# TODO: update i and n
# Hint: i is a successive integer and n is the previous product
i += 1
n = output
# Test block
my_gen = fact_gen()
num = 5
for i in range(num):
print(next(my_gen))
# Correct result when num = 5:
# 1
# 2
# 6
# 24
# 120
### sudoku test
correct = [[1, 2, 3],
[2, 3, 1],
[3, 1, 2]]
incorrect = [[1, 2, 3, 4],
[2, 3, 1, 3],
[3, 1, 2, 3],
[4, 4, 4, 4]]
incorrect2 = [[1, 2, 3, 4],
[2, 3, 1, 4],
[4, 1, 2, 3],
[3, 4, 1, 2]]
incorrect3 = [[1, 2, 3, 4, 5],
[2, 3, 1, 5, 6],
[4, 5, 2, 1, 3],
[3, 4, 5, 2, 1],
[5, 6, 4, 3, 2]]
incorrect4 = [['a', 'b', 'c'],
['b', 'c', 'a'],
['c', 'a', 'b']]
incorrect5 = [[1, 1.5],
[1.5, 1]]
# Define a function check_sudoku() here:
def test_sudoku(square):
for row in square:
check_list = list(range(1, len(square[0])+ 1))
for i in row:
if i not in check_list:
return False
check_list.remove(i)
for n in range(len(square[0])):
check_list = list(range(1, len(square[0])+1))
for row in square:
if row[n] not in check_list:
return False
check_list.remove(row[n])
return True
print(test_sudoku(incorrect))
#>>> False
print(test_sudoku(correct))
#>>> True
print(test_sudoku(incorrect2))
#>>> False
print(test_sudoku(incorrect3))
#>>> False
print(test_sudoku(incorrect4))
#>>> False
print(test_sudoku(incorrect5))
#>>> False
| true |
ca692034924e7c27287a7ff5524fabdf34e87201 | CDinuwan/Py-Advanced | /Dictionary.py | 950 | 4.15625 | 4 | # Dictionary: key-Value pairs,Unordered,Mutable
myDic = {"name": "Chanuka", "age": 21, "City": "New York"}
print(myDic)
myDict2 = dict(name="Dinuwan", age=27, city="Boston")
print(myDict2)
value = myDic["age"]
print(value)
myDic["email"] = "hecdinuwan@gmail.com"
print(myDic)
myDic["email"] = "chanukadinuwan35@gmail.com"
print(myDic)
del myDict2["name"]
print(myDict2)
myDict2.popitem()
print(myDict2)
try:
print(myDic["name"])
except:
print("Error")
for key in myDic:
print(key)
for key in myDic.keys():
print(key)
# for key, value in myDic.values():
# print(key+value)
for value in myDic:
print(value)
# mydict_cpy = myDic
# print(mydict_cpy)
# When we update copy dictionary also update original dictionary.
# In here these two variable pointed to same container.
# myDic.update(myDict2)
# print(myDic)
my_dict = {3: 9, 6: 36, 9: 81}
print(my_dict)
value = my_dict[3]
print(value)
mytuple = (8, 7)
mydict = {mytuple: 15}
print(mydict)
| true |
faf30f112f35955e0fa80bedd94fca75f01860ba | GT-rc/udemy-apps | /Section-5/S5L51Ex1.py | 921 | 4.71875 | 5 | """
In one of the previous exercises we created the following function that gets Celsius degrees as input and returns Fahrenheit, or a message if the Celsius input value is less than -273.15.
def c_to_f(c):
if c< -273.15:
return "That temperature doesn't make sense!"
else:
f=c*9/5+32
return f
Please implement a for loop that iterates through the following temperatures list temperatures=[10,-20,-289,100] and calls the above c_to_f function in each iteration. In other words, this time you are using the function to calculate a series of values instead of just one value.
"""
temperatures = [10,-20,-289,100]
def c_to_f(c):
if c< -273.15:
return "That temperature doesn't make sense!"
else:
f=c*9/5+32
return f
converted_temps = []
for item in temperatures:
converted_temps.append(c_to_f(item))
print(converted_temps)
| true |
83e0e6da343274fdc62fdfe1f2c6d56e46c09e9d | GT-rc/udemy-apps | /Section-6/S6L66Ex4.py | 1,279 | 4.40625 | 4 | """
Please take a look at the following code:
temperatures=[10,-20,-289,100]
def c_to_f(c):
if c< -273.15:
return "That temperature doesn't make sense!"
else:
f=c*9/5+32
return f
for t in temperatures:
print(c_to_f(t))
The code prints out the output of the c_to_f function multiple times in the terminal.
For this exercise, please write the output in a text file instead of printing it out in the terminal.
"""
# Copied code
temperatures=[10,-20,-289,100]
def c_to_f(c):
if c< -273.15:
return "That temperature doesn't make sense!"
else:
f=c*9/5+32
return f
new_temps = []
for t in temperatures:
new_temps.append(c_to_f(t))
# TODO: Write to file
with open("example.txt", 'a+') as file:
file.write("\n")
file.write("Attempt #4:")
file.write("\n")
for i in new_temps:
if isinstance(i, float):
file.write(str(i) + "\n")
"""
Book Answer:
def writer(temperatures):
with open("temps.txt", 'w') as file:
for c in temperatures:
if c>-273.15:
f=c*9/5+32
file.write(str(f)+"\n")
writer(temperatures) #Here we're calling the function, otherwise no output will be generated
"""
| true |
95845bd4d9d06aedbb036444a790321db23bde55 | shubhrock777/Python-basic-code- | /Assignment module 5/py_module05.py | 1,912 | 4.25 | 4 |
#############Q1
## A)list1=[1,5.5,(10+20j),’data science’].. Print default functions and parameters exists in list1.
list1=[1, 5.5, (10+20j), 'data science']
print(list1)
len(list1) #length of list
#Access values in the variable using index numbers
print(list1[0])
#### B)How do we create a sequence of numbers in Python.
num = list(range(0,11,1))
num
#### C)Read the input from keyboard and print a sequence of numbers up to that number
n= int(input('Please enter a number :'))
if n>0:
print (list(range(0,n+1)))
#############22. Create 2 lists.. one list contains 10 numbers (list1=[0,1,2,3....9]) and other
#list contains words of those 10 numbers (list2=['zero','one','two',.... ,'nine']).
# Create a dictionary such that list2 are keys and list 1 are values..
list1=list(range(0,10))
list1
list2=['zero','one','two','three','four','five','six','seven','eight','nine']
list2
dict_1={'List_1' : list1,
'List_2' : list2}
dict_1
#############3Consider a list1 [3,4,5,6,7,8]. Create a new list2 such that Add 10 to the even number and multiply with 5 if it is odd number in the list1..
list1=[3,4,5,6,7,8]
list2 = [x+10 for x in list1 if x%2==0] + [x*5 for x in list1 if x%2==1]
list2
################4
#######i)) It should accept both name of person and message you want to deliver.
name=input('Please enter your name : ')
message=input('Message you want to deliver : ')
sentance = "Hello "+ name + " your message : "+ message
print(sentance)
#######ii) If no message is provided, it should greet a default message ‘How are you’
name=input('Please enter your name : ')
message=input('Message you want to deliver : ')
if message =="" :
print( "Hello "+ name + " How are you ")
else:
print("Hello "+ name + " your message : "+ message)
| true |
91fd7464a4d0d97a4ad4d2fea73e95dc7a2b3b41 | cgarcianeal/Owens-Attendance | /src/recording.py | 1,773 | 4.25 | 4 | import csv
import sys
import datetime
from datetime import date
more = 'y' # Settingfactor for while loop
today = str(date.today())
year = datetime.date.today().year
default_option = "current"
prev_month = 0
prev_day = 0
file_name = "record_" + today + ".csv"
#opening records csv file for writing
record = open (file_name, "w")
# Recording Loop
while more == 'y':
first_name = input("What's the students first name? ")
last_name = input("What's the students last name? ")
if first_name == "" or last_name =="":
sys.exit("Please enter a first and last name")
#Just press Enter to have it be a PB
reason = input("Reason (Default=PB): ")
if reason == "":
reason = "PB"
#Now getting the date of the absence: year, month, day
month = input("Month? (Default=" + default_option + "): ")
if month == "":
if default_option == "current":
month = datetime.date.today().month
else:
month = prev_month
day = input("Day? (Default=" + default_option + "): ")
if day == "":
if default_option == "current":
day = datetime.date.today().day
else:
day = prev_day
date = datetime.datetime(int(year), int(month), int(day))
# Writing data to make a line in csv file
# Format: "LastName, FirstName",Reason
record.write("\"" + last_name + ", " + first_name + "\"" + "," +
reason + "," +
date.strftime("%m/%d/%y"))
more = input("More? (default=yes, no = n): ")
if more == "":
more = 'y'
# add new line if there are more entries
if more == 'y':
default_option = "previous"
prev_month = month
prev_day = day
print("")
record.write("\n")
| true |
1327f24d03c82c4624ce3d59d096afd9fe63e7fe | suchana172/My_python_beginner_level_all_code | /basic1/age_checker.py | 250 | 4.125 | 4 | your_age = input("How old are you?")
your_friends_age = input("How old is your friend?")
if int(your_age) >=18 or int(your_friends_age) >=18 :
print("Congrats, one of you is old enough to vote!")
else:
print("One of you is too young to vote") | true |
092f455f31e6a3ad58ad3fcf735fe93f000a67d1 | krhckd93/Data-Structures | /stacks.py | 1,854 | 4.1875 | 4 | def display(s, top):
if top == -1:
print("Stack is empty!")
else:
while top != -1:
print(s[top])
def push_item(s, top, max_size, value):
if top != max_size:
top += 1
s.append(value)
print("Item added :", s[top])
return top
else:
print("Stack is full. Try popping some elements first.")
return top
def pop_item(s, top):
if top != -1:
temp = s.pop()
top -= 1
print("Item popped is ", temp)
return top
else:
print("Stack is empty! Try adding some items first.")
return top
def main():
s = []
top = -1
while 1:
print("1.Create a new stack\t2.Add\t3.Delete\t4.Display\t5.Exit")
choice = int(input("Enter your choice"))
if choice == 1:
if max_size is not None:
ans = input("Stack exists. Do you want to create a new one?")
if ans == 'y' or ans == 'Y':
max_size = int(input("Enter the maximum size of the stack:"))
value = int(input("Enter a value:"))
top = push_item(s, top, max_size, value)
continue
else:
continue
max_size = int(input("Enter the maximum size of the stack:"))
value = int(input("Enter a value:"))
top = push_item(s, top, max_size, value)
elif choice == 2:
if top == -1:
print("Create a stack first.")
continue
value = int(input("Enter a value:"))
top = push_item(s, top, max_size, value)
elif choice == 3:
top = pop_item(s, top)
print()
elif choice == 4:
display(s, top)
elif choice == 5:
exit()
main()
| true |
672dff443335e840fcd1f8e312f980aa09606545 | amidoge/Python-2 | /ex012.py | 502 | 4.21875 | 4 | from math import *
t1 = float(input('What is your first longitude?'))
t2 = float(input('What is your first latitude?'))
g1 = float(input('What is your second longitude?'))
g2 = float(input('What is your second latitude?'))
# converting the degrees to radians so that it is able to do the formula
radians(t1)
radians(t2)
radians(g1)
radians(g2)
distance = 6371.01 * acos(sin(t1) * sin(t2) + cos(t1) + cos(t2) * cos(g1 - g2))
print(f'The distance from {t1},{g1} to {t2},{g2} is {distance} kilometers!')
| false |
99d3a263f4286a26e06135d11d930b3f1071b26a | amidoge/Python-2 | /ex080.py | 1,923 | 4.21875 | 4 | from random import randint #going to use 1 and 2 to represent heads or tails
#for one round of coin flip
#variables:
flip_count = 0
total_flips = 0
consecutive_count = 0 #this is zero because we don't even have a flip yet.
for i in range(10): #doing this 10 times
#in the beginning of the line, we should have some sort of number to compare to the first toss in the line, so that way it would count as the first consecutive number
h_or_t = randint(1, 2) #heads is 1 tails is 2
last_num = h_or_t
consecutive_count = 1 #because this is the first number in the consecutive series
#need to print it out:
if h_or_t == 1:
print('H', end=' ')
if h_or_t == 2:
print("T", end=' ')
#ONE LINE LOOP UNTIL THERE ARE 3 CONSECUTIVE NUMBERS:
while consecutive_count != 3:
h_or_t = randint(1, 2) #heads is 1 tails is 2
#COMPARISON
if h_or_t == last_num:
consecutive_count += 1
last_num = h_or_t #setting last_num to the new heads or tails
else:
#set it back to one because it is going to be the first consecutive number in the series
consecutive_count = 1 #because it is going to be the first in the series of consecutive numbers, we set it to one
last_num = h_or_t #going to set this also to compare
#PRINTING
if h_or_t == 1:
print('H', end=' ')
if h_or_t == 2:
print("T", end=' ')
flip_count += 1 #counting the flips
#printing the number of flips
print(f"({flip_count} Flips)")
total_flips += flip_count #this is for the average in the end. I am going to add them all up, and then divide it by 10 (since there are 10 groups.)
#also setting flip_counts to zero so that we can count the number of flips per line
flip_count = 0
#printing the average
print(f'On average, {total_flips / 10} flips were needed.') | true |
a46c37d955945468272275e925aac5e8a7fb7fdf | amidoge/Python-2 | /ex041.py | 668 | 4.21875 | 4 | #find out frequency from a note that the user inputs
note = str(input('What note do you want to know the frequency of? '))
C4 = 261.63
D4 = 293.66
E4 = 329.63
F4 = 349.23
G4 = 392.00
A4 = 440.00
B4 = 493.88
if note == 'C4':
print(C4)
elif note == 'D4':
print(D4)
elif note == 'E4':
print(E4)
elif note == 'F4':
print(F4)
elif note == 'G4':
print(G4)
elif note == 'A4':
print(A4)
elif note == 'B4':
print(B4)
else:
if note[0] == 'C' and int(note[1]) <= 8 and len(note) == 2:
frequency = C4 / 2 ** (4 - int(note[1]))
print(f'{frequency:.2f}')
else:
print('Sorry, but I cannot find the frequency of this note.') | true |
69579627325bee141245c3b323b5cc7ff71a2ecc | amidoge/Python-2 | /ex079.py | 1,229 | 4.25 | 4 | from random import randint
random_int = randint(1, 100) #need to get a number to store to maximum_int, so that we can compare it with the next 99 numbers
maximum_int = random_int
print(maximum_int) #must also print the maximum integer first otherwise I will only have 99 numbers and not 100
update_count = 0
for i in range(99): #99 because we already did a random_int once before for comparison to the others.
random_int = randint(1, 100)
if random_int > maximum_int:
update_count += 1 #we want to count how many times the maximum_number updated, to show the user how many times it did, whenm every number was being generated.
maximum_int = random_int
print(f"{maximum_int} <== Update") #need to include the Update to show that the maximum number has changed
else:
print(random_int) #otherwise. I don't print the maximum integer (new) but print the random_int generated
#after the loop, I should have the maximum int ever generated on that list stored on maximum_int variable
#I should also have the count of the number of times it updated stored in update_count variable
print(f"The maximum value found was {maximum_int}")
print(f"The maximum value was updated {update_count} times") | true |
24bdd04f164c63779262bf95209bdfc825343c49 | amidoge/Python-2 | /ex096b.py | 2,642 | 4.28125 | 4 | #Check a password
'''
Write a function that determines whether or not a
password is good. We will define a good password to be a
one that is at least 8 characters long and contains at
least one uppercase letter, at least one lowercase letter,
and at least one number. Your function should return true
if the password passed to it as its only parameter is good.
Otherwise it should return false. Include a main program
that reads a password from the user and reports whether
or not if it is good. Ensure that your main program only
runs when your solution has not been imported to another
file.
'''
def password_checker(password):
#checking if it is at least eight characters long
if len(password) < 8:
return False
#making sure that there is at least 1 uppercase letter in the password
#I am going to use the ord() function to convert the char into an ASCII, to make sure that there is at least 1 uppercase letter.
uppercase_found = False #this is going to be False right now. If an uppercase is found, then it is going to change to True
for i in range(len(password)):
if password[i].isupper() == True: #using the isupper method in python
uppercase_found = True
if uppercase_found == False:
return False
#making sure that there is at least 1 lowercase letter in the password
#I am going to use the ord() function to convert the char into an ASCII, to make sure that there is at least 1 lowercase letter.
lowercase_found = False #this is going to be False right now. If a lowercase letter is found, then it is going to change to True
for x in range(len(password)):
if password[x].islower() == True: #using the islower method in python
lowercase_found = True
if lowercase_found == False:
return False
#the final thing to check is if there is a number in the password.
#I am going to use the ord() function again because it will help convert the char into an ASCII number, and I can use that to check if it is in between the numbers ASCII range
number_found = False #this is going to be False right now. If there is a number found, then I am going to change this to True
for j in range(len(password)):
if ord(password[j]) >= 48 and ord(password[j]) <= 57: #if the char turns out to be in the number ASCII range, then that means that it is a number. WHich means that I can change it to True.
number_found = True
if number_found == False:
return False
return True
if __name__ == '__main__':
user_password = input('Password: ')
print(password_checker(user_password))
| true |
ce5b720b688c6c5dd06bf93195309fdaaa8e7e03 | amidoge/Python-2 | /ex032.py | 509 | 4.3125 | 4 | #read 3 different integers and list them from smallest to largest using the min() and max() functions
num_1 = int(input('What is the first integer?'))
num_2 = int(input('What is the second integer?'))
num_3 = int(input('What is the third integer?'))
highest = max(num_1, num_2, num_3)
lowest = min(num_1, num_2, num_3)
middle = num_1 + num_2 + num_3 - lowest - highest
print(f'''
The order from the numbers you gave me from the lowest value to the greatest value is...
{lowest}, {middle}, and {highest}
''') | true |
01df20571644a961209dbe9966955401a876db09 | SimonCWatts/MIT-6.00.1x | /MID TERM Problem 6x.py | 762 | 4.15625 | 4 |
def laceStringsRecur(s1, s2):
"""
s1 and s2 are strings.
Returns a new str with elements of s1 and s2 interlaced,
beginning with s1. If strings are not of same length,
then the extra elements should appear at the end.
"""
def helpLaceStrings(s1, s2, out):
if s1 == '':
#PLACE A LINE OF CODE HERE
return s2[len(s1):]
if s2 == '':
#PLACE A LINE OF CODE HERE
return s1[len(s2):]
else:
#PLACE A LINE OF CODE HERE
return s1[0] + helpLaceStrings(s2, s1[1:], out)
return helpLaceStrings(s1, s2, '')
s1 = 'abc'
s2 = '123'
print('string1:', s1, '\nstring2:', s2, '\nlaced:', laceStringsRecur(s1, s2)) | true |
eda62614b41d7f54c66440c601e7d2021ffbaa0c | dansmyers/IntroToCS-2020 | /Examples/2-Variables/magic_computer.py | 754 | 4.34375 | 4 | """
The Magic Computer: a Mad Lib
CMS 195, Spring 2020
"""
# Prompt the user to enter all of the required words
noun1 = input('Enter a noun: ')
plural_noun1 = input('Enter a plural noun: ')
verb1 = input('Enter a present tense verb: ')
verb2 = input('Enter a present tense verb: ')
part_of_body = input('Ener a plural part of the body: ')
adj1 = input('Enter an adjective: ')
plural_noun2 = input('Enter a plural noun: ')
adj2 = input('Enter an adjective: ')
# Print out the story with the user's words mixed in
print('Today, every student has a computer small enough to fit into his ' + noun1 + '.')
print('He can solve any math problem by simply pushing the computer\'s little '+ plural_noun1 + '.')
# We finished the rest of the story in class...
| true |
7115080820e3091995c63dac919e5acd358ca45c | dansmyers/IntroToCS-2020 | /Examples/3-Conditonals/pos_neg_or_zero.py | 715 | 4.5 | 4 | """
Test if a number is positive, negative, or zero
CMS 195, Spring 2020
"""
# Read the number
number = int(input('Enter a number: '))
# This test block has three outcomes
#
# Use if-elif-else to test three or more outcomes
# If the first test is True, the if block executes and all of the other cases are skipped
#
# If the first test is False, the elif test is checked. If that test is True, the elif block executes
#
# If both tests are False, the else block executes as the default outcome
# You can add any number of elif clauses to test more than three outcomes
# There can be only one final else block
if number > 0:
print('Positive')
elif number < 0:
print('Negative')
else:
print('Zero')
| true |
93b4669fb03a0da0cfe047ec12e09c49621df58b | FrauBoes/aviation_routing | /flightplan.py | 1,755 | 4.125 | 4 | from itertools import permutations
class Flightplan:
"""
Class to store flightplan objects. A Flightplan class defines a container object for a flightplan.
Implements flightplan object as a queue using a list
Provides methods to access the first and last item in the flightplan
Store aircraft as data field of a flightplan object to get range
"""
def __init__(self, flightplan):
self.flightplan = str(flightplan)
self.items = []
self.aircraft = None
self.best_route = None
self.best_cost = None
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
def getFlightplan(self):
return self.flightplan
def setAircraft(self, aircraft):
self.aircraft = aircraft
def getAircraft(self):
return self.aircraft
def setBestRoute(self, best_route):
self.best_route = best_route
def getBestRoute(self):
return self.getBestRoute
def setBestCost(self, best_cost):
self.best_cost = best_cost
def getBestCost(self):
return self.getBestCost
def getAllRoutes(self):
"""
:return: Successive permutations of all airports of all airports other than start/end
Start/end airport is added at the start and end of each permutation
"""
start_airport = self.dequeue()
all_routes = []
for route in permutations(self.items):
all_routes.append((start_airport, ) + route + (start_airport, ))
return all_routes
def __str__(self):
return self.getFlightplan() | true |
a5d68b227850fec5c3c7901791b24208b75d2bec | leiurus17/tp_python | /strings/python_max.py | 241 | 4.4375 | 4 | #The method max() returns the max alphabetical character from the string str.
str = "This is really a string example....wow!!! z"
print "Max character: " + max(str)
str = "This is a string example."
print "Max character: " + max(str) | true |
7b13905fcc57e2863fcf5b7af5745db5b77b71cb | leiurus17/tp_python | /variables/python_tuple.py | 414 | 4.3125 | 4 | tuplez = ('abcd', 786, 2.23, 'john', 70.2)
tinytuple = (123, 'daniel')
print tuplez # Prints complete tuple
print tuplez[0] # Prints first element of the tuple
print tuplez[1:3] # Prints elements starting from 2nd till 3rd
print tuplez[2:] # Prints elements starting from 3rd element
print tinytuple * 2 # Prints tuple two times
print tuplez + tinytuple # Prints concatenated tuples | true |
586d6eb66995593b922178cb50369521a7025251 | leiurus17/tp_python | /operators/python_comparison.py | 723 | 4.125 | 4 | a = 21
b = 10
c = 0
print "a = ", a
print "b = ", b
print "c = ", c
if (a == b):
print "a == b is True"
else:
print "a == b is False"
if (a != b):
print "a != b is True"
else:
print "a != b is False"
if (a <> b):
print "a <> b is True"
else:
print "a <> b is False"
if (a < b):
print "a < b is True"
else:
print "a < b is False"
if (a > b):
print "a > b is True"
else:
print "a > b is False"
a = 5
b = 20
print a
print b
print "a = ", a
print "b = ", b
if (a <= b):
print "a <= b is True"
else:
print "a <= b is False"
if (b >= a):
print "b >= a is True"
else:
print "b >= a is False"
| false |
8b70021aa4d42681dcf3f766b96111030e367959 | myke2424/my-python-learning | /super.py | 2,048 | 4.53125 | 5 | # At a high level, super() gives you access to methods in a parent class from the subclass that inherits from it
# super() alone returns a temporary object of the parent class that then allows you call that superclass's methods
# A common use case is building classes that extend the functionality of previously built classes.
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * self.length + 2 * self.width
# Calling super here, lets us take our instance variable length
# and pass it to the width and length values to set on the object
# We need to pass all required init params from the super class to super.__init__() or else it will fail
class Square(Rectangle):
def __init__(self, length):
# This is really calling "Rectangle.__init__()"
# In python3, calling "super()" is equivalent to calling "super(Square, self)"
super().__init__(width=length, length=length)
# The primary use case of super is to extend the functionality of the inherited method.
# The cube class doesn't need a __init__ method because it inherits it from Square
# The __init__ method of the parent class will be called automatically
class Cube(Square):
def surface_area(self):
# I'm extending the functionality of the inherited area method here.
# This is equivalent to calling "super(Square, self).area()" -> This searches the square class for the area method:wq!
face_area = super().area() # We could also call "self.area()" because we inherit the method
return face_area * 6
# You could reinitialise an object like this, *Not recommended*
class Person:
def __init__(self, name):
self.name = name
p = Person('mike')
Person.__init__(p, name='Charlie') # now p.name = charlie
r = Rectangle(5, 5)
s = Square(5)
c = Cube(5)
cube_area = c.surface_area()
print() | true |
3aabc19b3d1d49476d0f9b519f1e04c0b4e37f7e | myke2424/my-python-learning | /lambdas.py | 1,463 | 4.46875 | 4 | # Lambdas are just anonymous functions (e.g. js arrow function cb)
# Taken literally, an anonymous function is a function without a name.
# In Python, an anonymous function is created with the lambda keyword.
# We can apply the an argument to the lambda by surrounding the func and its arg with parentheses
(lambda x, y: x + y)(2, 3) # this is immediately invoked and will return 5 (not recommended to do this)
add = lambda x, y: x + y
# Now we can call the lambda func
add(5, 5)
# This is the same as creating the function:
def add(x, y):
return x + y
full_name = lambda first, last: print(f'Fullname: {first, last}')
full_name('Kobe', 'Bryant')
# Lambda functions are frequently used with higher-order-functions (a func that takes a func as a parameter or returns a function)
high_order_func = lambda x, func: func(x)
high_order_func(5, lambda x: x * 10) # this will return 50
# You’ll use lambda functions together with Python higher-order (map, reduce, filter etc)
# Here's a quote from the python design history faq:
# Unlike lambda forms in other languages, where they add functionality, Python lambdas are only a shorthand notation if you’re too lazy to define a function
# A lambda function can’t contain any statements.
# In a lambda function, statements like return, pass, assert, or raise will raise a SyntaxError exception.
# Also, you can't use type annotations in a lambda (e.g. x: str) | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.